<commit_before>'use strict';

var nextTick = require('next-tick')
  , Base     = require('../../lib/types/base');

module.exports = function (t, a, d) {
	var ns = Base.create('SignalTest1');
	setTimeout(function () {
		var emitted = [];
		t.on('data', function (data) { emitted.push(data); });

		ns.$set('fooSigTest', 'trzy');
		t(ns._fooSigTest, 'trzy');
		ns.$set('fooSigTest2', 34);
		t(ns._fooSigTest2, 34);

		nextTick(function () {
			var signal = emitted[0];
			a(emitted.length, 1, "Signal emitted");
			emitted.length = 0;
			a.deep(signal, { 'SignalTest1:fooSigTest': 'trzy',
				'SignalTest1:fooSigTest2': 34 }, "Signal data");
			a.deep(t.history, { 'SignalTest1:fooSigTest': [signal],
				'SignalTest1:fooSigTest2': [signal] }, "History");

			ns.fooSigTest = 'pięć';
			t(ns._fooSigTest, 'pięć');
			ns.fooSigTest2 = 54;
			t(ns._fooSigTest2, 54);

			t.rollback();
			nextTick(function () {
				a(emitted.length, 0, "Rollback: Signal");
				a.deep([ns.fooSigTest, ns.fooSigTest2], ['trzy', 34],
					"Rollback: Values");
				a.deep(t.history, { 'SignalTest1:fooSigTest': [signal],
					'SignalTest1:fooSigTest2': [signal] }, "History");
				d();
			});
		});
	}, 50);
};
<commit_msg>Make tests independent<commit_after>'use strict';

var nextTick = require('next-tick')
  , Base     = require('../../lib/types/base');

module.exports = function (t, a, d) {
	var ns = Base.create('SignalTest1');
	setTimeout(function () {
		var emitted = [];
		t.on('data', function (data) { emitted.push(data); });

		ns.$set('fooSigTest', 'trzy');
		t(ns._fooSigTest, 'trzy');
		ns.$set('fooSigTest2', 34);
		t(ns._fooSigTest2, 34);

		nextTick(function () {
			var signal = emitted[0];
			a(emitted.length, 1, "Signal emitted");
			emitted.length = 0;
			a.deep(signal, { 'SignalTest1:fooSigTest': 'trzy',
				'SignalTest1:fooSigTest2': 34 }, "Signal data");
			a.deep(t.history['SignalTest1:fooSigTest'], [signal], "History #1");
			a.deep(t.history['SignalTest1:fooSigTest2'], [signal], "History #2");

			ns.fooSigTest = 'pięć';
			t(ns._fooSigTest, 'pięć');
			ns.fooSigTest2 = 54;
			t(ns._fooSigTest2, 54);

			t.rollback();
			nextTick(function () {
				a(emitted.length, 0, "Rollback: Signal");
				a.deep([ns.fooSigTest, ns.fooSigTest2], ['trzy', 34],
					"Rollback: Values");
				a.deep(t.history['SignalTest1:fooSigTest'], [signal], "History #1");
				a.deep(t.history['SignalTest1:fooSigTest2'], [signal], "History #2");
				d();
			});
		});
	}, 50);
};
<|endoftext|>


<commit_before>/**
 * @fileoverview Creates new issues after specified old issues are closed
 * @author Teddy Katz
 */

"use strict";

const moment = require("moment-timezone");

/**
 * Gets the desired issue body for a release issue, given the date of the release.
 * @param {Moment} releaseDate The date of the release, as Moment UTC date
 * @returns {Promise<string>} The text of the issue
 */
async function getReleaseIssueBody(releaseDate) {
    return `

The scheduled release on ${releaseDate.format("dddd, MMMM Do, YYYY")} is assigned to:

* (needs volunteers)
* (needs volunteers)

Please use this issue to document how the release went, any problems during the release, and anything the team might want to know about the release process. This issue should be closed after all patch releases have been completed (or there was no patch release needed).

Resources:

* [Release guidelines](https://eslint.org/docs/maintainer-guide/releases)

`.trim();
}

/**
 * Gets the members of a particular team on GitHub
 * @param {GitHub} github A GitHub API client
 * @returns {{login: string, name: (string|null)}} A list of team member login names and full names
 */
async function getTeamMembers({ github, organizationName, teamName }) {

    /*
     * NOTE: This will fail if the organization contains more than 100 teams. This isn't
     * close to being a problem right now, so it hasn't been worth figuring out a good
     * way to paginate yet, but that would be a good enhancement in the future.
     */
    const teams = await github.orgs.getTeams({ org: organizationName, per_page: 100 }).then(res => res.data);
    const desiredTeam = teams.find(team => team.slug === teamName);

    if (!desiredTeam) {
        throw new Error(`No team with name ${teamName} found`);
    }

    const teamMembers = await github.orgs.getTeamMembers({ id: desiredTeam.id, per_page: 100 }).then(res => res.data);

    return Promise.all(teamMembers.map(async member => ({
        login: member.login,
        name: await github.users.getById({ id: member.id }).then(res => res.data.name)
    })));
}

/**
 * Formats a list of team members' names and GitHub usernames into a bulleted Markdown list
 * @param {{name: string, login: string}[]} teamMembers Information about team members
 * @returns {string} Markdown text containing a bulleted list of names
 */
function formatTeamMembers(teamMembers) {
    return teamMembers.map(({ login, name }) => `- ${name || login} (@${login}) - TSC`).join("\n");
}

/**
 * Gets the desired issue body for a release issue, given the date and of the meeting
 * @param {Moment} meetingDate The date and time when the meeting will take place, as a Moment date
 * @param {GitHub} github A GitHub API client
 * @returns {Promise<string>} The text of the issue
 */
async function getTscMeetingIssueBody({ meetingDate, github, organizationName, tscTeamName }) {
    const timeFormatString = "ddd DD-MMM-YYYY HH:mm";

    return `

# Time

UTC ${moment.utc(meetingDate).format(timeFormatString)}:
- Los Angeles: ${moment.tz(meetingDate, "America/Los_Angeles").format(timeFormatString)}
- Chicago: ${moment.tz(meetingDate, "America/Chicago").format(timeFormatString)}
- New York: ${moment.tz(meetingDate, "America/New_York").format(timeFormatString)}
- Madrid: ${moment.tz(meetingDate, "Europe/Madrid").format(timeFormatString)}
- Moscow: ${moment.tz(meetingDate, "Europe/Moscow").format(timeFormatString)}
- Tokyo: ${moment.tz(meetingDate, "Asia/Tokyo").format(timeFormatString)}
- Sydney: ${moment.tz(meetingDate, "Australia/Sydney").format(timeFormatString)}

# Location

https://gitter.im/eslint/tsc-meetings

# Agenda

Extracted from:

* Issues and pull requests from the ESLint organization with the ["tsc agenda" label](https://github.com/issues?utf8=%E2%9C%93&q=org%3Aeslint+label%3A%22tsc+agenda%22)
* Comments on this issue

# Invited

${await getTeamMembers({ github, organizationName, teamName: tscTeamName }).then(formatTeamMembers)}

# Public participation

Anyone is welcome to attend the meeting as observers. We ask that you refrain from interrupting the meeting once it begins and only participate if invited to do so.

    `.trim();
}

/**
 * A function that determines whether an issue on GitHub was closed multiple times in the past.
 * @param {GitHub} github A GitHub API client
 * @param {Object} issueInfo information about the issue
 * @param {string} issueInfo.owner The owner of the repository
 * @param {string} issueInfo.repo The repo name
 * @param {number} issueInfo.number The issue number on GitHub
 * @returns {Promise<boolean>} A Promise that fulfills with `true` if the issue was closed multiple times
 */
async function issueWasClosedMultipleTimes(github, { owner, repo, number }) {
    const issueEvents = await github.issues.getEvents({
        owner,
        repo,
        number,
        per_page: 100
    }).then(res => res.data);

    return issueEvents.filter(eventObj => eventObj.event === "closed").length > 1;
}

/**
 * Creates a webhook handler that responds when an issue is closed for the first time
 * by creating a new issue.
 * @param {string} labelTrigger A label that the closed issue must have for this webhook
 * to run
 * @param {string[]} newLabels The labels that the newly-created issue should be given
 * @param {Function} shouldCreateNewIssue A function that accepts an object with `title` and
 * `body` properties as an argument, and returns a Promise for a boolean indicating whether
 * a new issue should be created. If the Promise fulfills with `false`, creating a new issue
 * will be cancelled.
 * @param {Function} getNewIssueInfo A function to get the title and body of the new issue.
 * Accepts a single parameter with `title` and `body` properties for the old issue, as well as
 * a `github` property containing a GitHub API client and an `organizationName` property containing
 * the name of the organization that owns the repo where the issue was filed. Returns a promise
 * for an object with `title` and `body` properties for the new issue.
 * @returns {function(probot.Context): Promise<void>} A Probot event listener
 */
function createIssueHandler({ labelTrigger, newLabels, shouldCreateNewIssue, getNewIssueInfo }) {
    return async context => {
        const { title: oldTitle, body: oldBody, labels: oldLabels } = context.payload.issue;

        // If the issue does not have the correct label, skip it.
        if (!oldLabels.some(label => label.name === labelTrigger)) {
            return;
        }

        // If the issue was previously closed and then reopened, skip it.
        if (await issueWasClosedMultipleTimes(context.github, context.issue())) {
            return;
        }

        if (!await shouldCreateNewIssue({ title: oldTitle, body: oldBody })) {
            return;
        }

        const { title: newTitle, body: newBody } = await getNewIssueInfo({
            title: oldTitle,
            body: oldBody,
            github: context.github,
            organizationName: context.repo().owner
        });

        // Create a new issue.
        await context.github.issues.create(
            context.repo({
                title: newTitle,
                body: newBody,
                labels: newLabels
            })
        );
    };
}

const RELEASE_ISSUE_TITLE_FORMAT = "[Scheduled release for ]MMMM Do, YYYY";
const releaseIssueHandler = createIssueHandler({
    labelTrigger: "release",
    newLabels: ["release", "tsc agenda"],
    async shouldCreateNewIssue({ title }) {
        return moment.utc(title, RELEASE_ISSUE_TITLE_FORMAT, true).isValid();
    },
    async getNewIssueInfo({ title }) {
        const oldReleaseDate = moment.utc(title, RELEASE_ISSUE_TITLE_FORMAT, true);
        const newReleaseDate = oldReleaseDate.clone().add({ weeks: 2 });

        return {
            title: newReleaseDate.format(RELEASE_ISSUE_TITLE_FORMAT),
            body: await getReleaseIssueBody(newReleaseDate)
        };
    }
});

const TSC_MEETING_TITLE_FORMAT = "[TSC meeting ]DD-MMMM-YYYY";
const tscMeetingIssueHandler = createIssueHandler({
    labelTrigger: "tsc meeting",
    newLabels: ["tsc meeting"],
    async shouldCreateNewIssue({ title }) {
        return moment.utc(title, TSC_MEETING_TITLE_FORMAT, true).isValid();
    },
    async getNewIssueInfo({ title, github, organizationName }) {
        const meetingDate = moment.tz(title, TSC_MEETING_TITLE_FORMAT, "America/New_York")
            .hour(16)
            .add({ weeks: 2 });

        const newTitle = meetingDate.format(TSC_MEETING_TITLE_FORMAT);
        const newBody = await getTscMeetingIssueBody({
            meetingDate,
            github,
            organizationName,
            tscTeamName: "eslint-tsc"
        });

        return { title: newTitle, body: newBody };
    }
});

module.exports = robot => {
    robot.on("issues.closed", releaseIssueHandler);
    robot.on("issues.closed", tscMeetingIssueHandler);
};
<commit_msg>Update: only require one volunteer when creating release issue (#120)<commit_after>/**
 * @fileoverview Creates new issues after specified old issues are closed
 * @author Teddy Katz
 */

"use strict";

const moment = require("moment-timezone");

/**
 * Gets the desired issue body for a release issue, given the date of the release.
 * @param {Moment} releaseDate The date of the release, as Moment UTC date
 * @returns {Promise<string>} The text of the issue
 */
async function getReleaseIssueBody(releaseDate) {
    return `

The scheduled release on ${releaseDate.format("dddd, MMMM Do, YYYY")} is assigned to:

* (needs volunteer)

Please use this issue to document how the release went, any problems during the release, and anything the team might want to know about the release process. This issue should be closed after all patch releases have been completed (or there was no patch release needed).

Resources:

* [Release guidelines](https://eslint.org/docs/maintainer-guide/releases)

`.trim();
}

/**
 * Gets the members of a particular team on GitHub
 * @param {GitHub} github A GitHub API client
 * @returns {{login: string, name: (string|null)}} A list of team member login names and full names
 */
async function getTeamMembers({ github, organizationName, teamName }) {

    /*
     * NOTE: This will fail if the organization contains more than 100 teams. This isn't
     * close to being a problem right now, so it hasn't been worth figuring out a good
     * way to paginate yet, but that would be a good enhancement in the future.
     */
    const teams = await github.orgs.getTeams({ org: organizationName, per_page: 100 }).then(res => res.data);
    const desiredTeam = teams.find(team => team.slug === teamName);

    if (!desiredTeam) {
        throw new Error(`No team with name ${teamName} found`);
    }

    const teamMembers = await github.orgs.getTeamMembers({ id: desiredTeam.id, per_page: 100 }).then(res => res.data);

    return Promise.all(teamMembers.map(async member => ({
        login: member.login,
        name: await github.users.getById({ id: member.id }).then(res => res.data.name)
    })));
}

/**
 * Formats a list of team members' names and GitHub usernames into a bulleted Markdown list
 * @param {{name: string, login: string}[]} teamMembers Information about team members
 * @returns {string} Markdown text containing a bulleted list of names
 */
function formatTeamMembers(teamMembers) {
    return teamMembers.map(({ login, name }) => `- ${name || login} (@${login}) - TSC`).join("\n");
}

/**
 * Gets the desired issue body for a release issue, given the date and of the meeting
 * @param {Moment} meetingDate The date and time when the meeting will take place, as a Moment date
 * @param {GitHub} github A GitHub API client
 * @returns {Promise<string>} The text of the issue
 */
async function getTscMeetingIssueBody({ meetingDate, github, organizationName, tscTeamName }) {
    const timeFormatString = "ddd DD-MMM-YYYY HH:mm";

    return `

# Time

UTC ${moment.utc(meetingDate).format(timeFormatString)}:
- Los Angeles: ${moment.tz(meetingDate, "America/Los_Angeles").format(timeFormatString)}
- Chicago: ${moment.tz(meetingDate, "America/Chicago").format(timeFormatString)}
- New York: ${moment.tz(meetingDate, "America/New_York").format(timeFormatString)}
- Madrid: ${moment.tz(meetingDate, "Europe/Madrid").format(timeFormatString)}
- Moscow: ${moment.tz(meetingDate, "Europe/Moscow").format(timeFormatString)}
- Tokyo: ${moment.tz(meetingDate, "Asia/Tokyo").format(timeFormatString)}
- Sydney: ${moment.tz(meetingDate, "Australia/Sydney").format(timeFormatString)}

# Location

https://gitter.im/eslint/tsc-meetings

# Agenda

Extracted from:

* Issues and pull requests from the ESLint organization with the ["tsc agenda" label](https://github.com/issues?utf8=%E2%9C%93&q=org%3Aeslint+label%3A%22tsc+agenda%22)
* Comments on this issue

# Invited

${await getTeamMembers({ github, organizationName, teamName: tscTeamName }).then(formatTeamMembers)}

# Public participation

Anyone is welcome to attend the meeting as observers. We ask that you refrain from interrupting the meeting once it begins and only participate if invited to do so.

    `.trim();
}

/**
 * A function that determines whether an issue on GitHub was closed multiple times in the past.
 * @param {GitHub} github A GitHub API client
 * @param {Object} issueInfo information about the issue
 * @param {string} issueInfo.owner The owner of the repository
 * @param {string} issueInfo.repo The repo name
 * @param {number} issueInfo.number The issue number on GitHub
 * @returns {Promise<boolean>} A Promise that fulfills with `true` if the issue was closed multiple times
 */
async function issueWasClosedMultipleTimes(github, { owner, repo, number }) {
    const issueEvents = await github.issues.getEvents({
        owner,
        repo,
        number,
        per_page: 100
    }).then(res => res.data);

    return issueEvents.filter(eventObj => eventObj.event === "closed").length > 1;
}

/**
 * Creates a webhook handler that responds when an issue is closed for the first time
 * by creating a new issue.
 * @param {string} labelTrigger A label that the closed issue must have for this webhook
 * to run
 * @param {string[]} newLabels The labels that the newly-created issue should be given
 * @param {Function} shouldCreateNewIssue A function that accepts an object with `title` and
 * `body` properties as an argument, and returns a Promise for a boolean indicating whether
 * a new issue should be created. If the Promise fulfills with `false`, creating a new issue
 * will be cancelled.
 * @param {Function} getNewIssueInfo A function to get the title and body of the new issue.
 * Accepts a single parameter with `title` and `body` properties for the old issue, as well as
 * a `github` property containing a GitHub API client and an `organizationName` property containing
 * the name of the organization that owns the repo where the issue was filed. Returns a promise
 * for an object with `title` and `body` properties for the new issue.
 * @returns {function(probot.Context): Promise<void>} A Probot event listener
 */
function createIssueHandler({ labelTrigger, newLabels, shouldCreateNewIssue, getNewIssueInfo }) {
    return async context => {
        const { title: oldTitle, body: oldBody, labels: oldLabels } = context.payload.issue;

        // If the issue does not have the correct label, skip it.
        if (!oldLabels.some(label => label.name === labelTrigger)) {
            return;
        }

        // If the issue was previously closed and then reopened, skip it.
        if (await issueWasClosedMultipleTimes(context.github, context.issue())) {
            return;
        }

        if (!await shouldCreateNewIssue({ title: oldTitle, body: oldBody })) {
            return;
        }

        const { title: newTitle, body: newBody } = await getNewIssueInfo({
            title: oldTitle,
            body: oldBody,
            github: context.github,
            organizationName: context.repo().owner
        });

        // Create a new issue.
        await context.github.issues.create(
            context.repo({
                title: newTitle,
                body: newBody,
                labels: newLabels
            })
        );
    };
}

const RELEASE_ISSUE_TITLE_FORMAT = "[Scheduled release for ]MMMM Do, YYYY";
const releaseIssueHandler = createIssueHandler({
    labelTrigger: "release",
    newLabels: ["release", "tsc agenda"],
    async shouldCreateNewIssue({ title }) {
        return moment.utc(title, RELEASE_ISSUE_TITLE_FORMAT, true).isValid();
    },
    async getNewIssueInfo({ title }) {
        const oldReleaseDate = moment.utc(title, RELEASE_ISSUE_TITLE_FORMAT, true);
        const newReleaseDate = oldReleaseDate.clone().add({ weeks: 2 });

        return {
            title: newReleaseDate.format(RELEASE_ISSUE_TITLE_FORMAT),
            body: await getReleaseIssueBody(newReleaseDate)
        };
    }
});

const TSC_MEETING_TITLE_FORMAT = "[TSC meeting ]DD-MMMM-YYYY";
const tscMeetingIssueHandler = createIssueHandler({
    labelTrigger: "tsc meeting",
    newLabels: ["tsc meeting"],
    async shouldCreateNewIssue({ title }) {
        return moment.utc(title, TSC_MEETING_TITLE_FORMAT, true).isValid();
    },
    async getNewIssueInfo({ title, github, organizationName }) {
        const meetingDate = moment.tz(title, TSC_MEETING_TITLE_FORMAT, "America/New_York")
            .hour(16)
            .add({ weeks: 2 });

        const newTitle = meetingDate.format(TSC_MEETING_TITLE_FORMAT);
        const newBody = await getTscMeetingIssueBody({
            meetingDate,
            github,
            organizationName,
            tscTeamName: "eslint-tsc"
        });

        return { title: newTitle, body: newBody };
    }
});

module.exports = robot => {
    robot.on("issues.closed", releaseIssueHandler);
    robot.on("issues.closed", tscMeetingIssueHandler);
};
<|endoftext|>


<commit_before>/*
 * Simple popup menu 1.0 (2010-05-15)
 *
 * Copyright (c) 2010 Combodo SARL (www.combodo.com)
 * Licenced under the GPL licence.
 *
 * http://www.combodo.com/
 *
 * Built upon jQuery jQuery 1.2.3a (http://jquery.com)
 * Requires the (modified) jQuery positionBy plugin by Jonathan Sharp (http://jdsharp.us)
 */
jQuery.fn.popupmenu = function ()
{
	var popupmenu = null;
	return this.each(function()
	{
		$(this).bind('click.popup_menu', function (evt)
		{
			var previous_popup = popupmenu;
			var bMenuClosed = false;
			popupmenu = $(this).find('ul');
			if ( previous_popup != null)
			{
				// The user clicked while a menu is open, close the currently opened menu
				previous_popup.css('display', 'none');

			}
			if ( (previous_popup == null) || (previous_popup.get(0) != popupmenu.get(0))) // Comparing the DOM objects
			{
				// The user clicked in a different menu, let's open it
				popupmenu.positionBy({ target: $(this),
										targetPos: 	4,
										elementPos: 0,
										hideAfterPosition: true
										});
				// In links containing a hash, replace what's after the hash by the current hash
				// In order to navigate to the same tab as the current one when editing an object
				currentHash = '';
				aMatches = /#(.*)$/.exec(window.location.href);
				if (aMatches != null)
				{
					currentHash = aMatches[1];
					popupmenu.find('a').each( function() {
						if ( /#(.*)$/.test(this.href))
						{
							this.href = this.href.replace(/#(.*)$/, '#'+currentHash);
						}
					});
				}
				popupmenu.css('display', 'block');
			}
			else
			{
				// The user clicked in the opened menu, it is closed now
				popupmenu = null;
			}
			evt.stopPropagation();
		});

		$(document).bind('click.popup_menu', function(evt)
		{
			if (popupmenu)
			{
				// The user clicked in the document's body, let's close the menu
				popupmenu.css('display', 'none');
				popupmenu = null;
			}
		});
	});
};<commit_msg>#862: Popup menu misplaced when the window scrolls (e.g. when displaying large lists of results)<commit_after>/*
 * Simple popup menu 1.0 (2010-05-15)
 *
 * Copyright (c) 2010 Combodo SARL (www.combodo.com)
 * Licenced under the GPL licence.
 *
 * http://www.combodo.com/
 *
 * Built upon jQuery jQuery 1.2.3a (http://jquery.com)
 * Requires the (modified) jQuery positionBy plugin by Jonathan Sharp (http://jdsharp.us)
 */
jQuery.fn.popupmenu = function ()
{
	var popupmenu = null;
	return this.each(function()
	{
		$(this).bind('click.popup_menu', function (evt)
		{
			var previous_popup = popupmenu;
			var bMenuClosed = false;
			popupmenu = $(this).find('ul');
			if ( previous_popup != null)
			{
				// The user clicked while a menu is open, close the currently opened menu
				previous_popup.css('display', 'none');

			}
			if ( (previous_popup == null) || (previous_popup.get(0) != popupmenu.get(0))) // Comparing the DOM objects
			{
				// The user clicked in a different menu, let's open it
				popupmenu.positionBy({ target: $(this),
										targetPos: 	4,
										elementPos: 0,
										hideAfterPosition: true
										});
				// In links containing a hash, replace what's after the hash by the current hash
				// In order to navigate to the same tab as the current one when editing an object
				currentHash = '';
				aMatches = /#(.*)$/.exec(window.location.href);
				if (aMatches != null)
				{
					currentHash = aMatches[1];
					popupmenu.find('a').each( function() {
						if ( /#(.*)$/.test(this.href))
						{
							this.href = this.href.replace(/#(.*)$/, '#'+currentHash);
						}
					});
				}
				popupmenu.css('top', ''); // let the "position: absolute;" do its job, for better support of scrolling...
				popupmenu.css('display', 'block');
			}
			else
			{
				// The user clicked in the opened menu, it is closed now
				popupmenu = null;
			}
			evt.stopPropagation();
		});

		$(document).bind('click.popup_menu', function(evt)
		{
			if (popupmenu)
			{
				// The user clicked in the document's body, let's close the menu
				popupmenu.css('display', 'none');
				popupmenu = null;
			}
		});
	});
};<|endoftext|>


<commit_before>(function ($) {

    // Navigation scrolls
    $('.navbar-nav li a').bind('click', function (event) {
        $('.navbar-nav li').removeClass('active');
        $(this).closest('li').addClass('active');
        var $anchor = $(this);
        var nav = $($anchor.attr('href'));
        if (nav.length) {
            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top
            }, 1500, 'easeInOutExpo');

            event.preventDefault();
        }
    });

    // About section scroll
    $(".overlay-detail a").on('click', function (event) {
        event.preventDefault();
        var hash = this.hash;
        $('html, body').animate({
            scrollTop: $(hash).offset().top
        }, 900, function () {
            window.location.hash = hash;
        });
    });

    //jQuery to collapse the navbar on scroll
    $(window).scroll(function () {
        if ($(".navbar-default").offset().top > 40) {
            alert('pop')
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    });

    $('.navbar-collapse').on('show.bs.collapse', function () {
        $(".navbar-fixed-top").addClass("top-nav-collapse-shadow");
    })
    $('.navbar-collapse').on('hide.bs.collapse', function () {
        $(".navbar-fixed-top").removeClass("top-nav-collapse-shadow");
    })

})(jQuery);<commit_msg>hapus pop<commit_after>(function ($) {

    // Navigation scrolls
    $('.navbar-nav li a').bind('click', function (event) {
        $('.navbar-nav li').removeClass('active');
        $(this).closest('li').addClass('active');
        var $anchor = $(this);
        var nav = $($anchor.attr('href'));
        if (nav.length) {
            $('html, body').stop().animate({
                scrollTop: $($anchor.attr('href')).offset().top
            }, 1500, 'easeInOutExpo');

            event.preventDefault();
        }
    });

    // About section scroll
    $(".overlay-detail a").on('click', function (event) {
        event.preventDefault();
        var hash = this.hash;
        $('html, body').animate({
            scrollTop: $(hash).offset().top
        }, 900, function () {
            window.location.hash = hash;
        });
    });

    //jQuery to collapse the navbar on scroll
    $(window).scroll(function () {
        if ($(".navbar-default").offset().top > 40) {
            $(".navbar-fixed-top").addClass("top-nav-collapse");
        } else {
            $(".navbar-fixed-top").removeClass("top-nav-collapse");
        }
    });

    $('.navbar-collapse').on('show.bs.collapse', function () {
        $(".navbar-fixed-top").addClass("top-nav-collapse-shadow");
    })
    $('.navbar-collapse').on('hide.bs.collapse', function () {
        $(".navbar-fixed-top").removeClass("top-nav-collapse-shadow");
    })

})(jQuery);<|endoftext|>


<commit_before>var M = process.mono;
var mongo = require('mongodb');
var Server = mongo.Server;
var MongoClient = mongo.MongoClient;

var CONNECTION_STRING_RE = new RegExp('^([a-zA-Z0-9]+)://([a-zA-Z0-9\\._-]+):(\\d{4,5})/([a-zA-Z0-9\\._-]+)$');
var serverOptions = {
    native_parser: true,
    server: {
        poolSize: 3
    }
};

var clients = {};
var cbBuffer = {};

// available stores
M.stores = {};

module.exports = connect;

// TODO check caching
function connect (connection, callback, log) {

    var config = parseConnection(connection);

    if (log) {
        console.log('connection:', config);
    }

    // check config
    if (!config) {
        return callback(new Error('Invalid connection string.'));
    }

    // check store cache
    if (M.stores[config.db]) {
        if (log) {
            console.log('- store from cache');
        }
        return callback(null, M.stores[config.db]);
    }

    // buffer callbacks when db is connecting
    if (cbBuffer[config.db] instanceof Array) {
        if (log) {
            console.log('- store callback in buffer');
        }
        return cbBuffer[config.db].push(callback);
    }

    // save callback in buffer
    (cbBuffer[config.db] = cbBuffer[config.db] || []).push(callback);

    // get client
    clients[config.client] = clients[config.client] || new MongoClient(new Server(config.host, config.port, serverOptions));

    if (log) {
        console.log('- store new client');
    }

    // TODO mongo client should only open once
    // to get a db then is sync
    // maybe make another function for retrieving a db

    // open db
    clients[config.client].db(config.name).open(function (err, db) {

        if (err) {
            return callbacks(config.db, err, db);
        }

        // authenticate
        db.authenticate(config.user, config.pass, function(err) {

            // handle error
            if (err) {
                return callbacks(config.db, err);
            }

            M.stores[config.db] = db;
            callbacks(config.db, null, db);
        });
    });
}

// parse connection string
function parseConnection (connection) {

    // TODO this is is a hack!
    if (!connection.match(CONNECTION_STRING_RE)) {
        connection = 'mongodb://localhost:27017/' + connection;
    }

    // check connection
    if (!(connection = connection.match(CONNECTION_STRING_RE))) {
        return;
    }

    // create connection object
    connection = {
        type: connection[1],
        host: connection[2],
        port: connection[3],
        name: connection[4],
        user: M.config.owner,
        pass: M.config.apiKey
    };

    // check connection values
    if (!connection.type || !connection.host || !connection.port || !connection.name) {
        return;
    }

    // add cache keys
    connection.client = connection.type + '://' + connection.host + ':' + connection.port;
    connection.db = connection.client + '/' + connection.name;

    return connection;
}

// call callbacks in callback buffer
function callbacks (key, err, db) {
    for (var i = 0; i < cbBuffer[key].length; ++i) {
        if (typeof cbBuffer[key][i] === 'function') {
            cbBuffer[key][i](err, db);
        }
    }

    delete cbBuffer[key];
}
<commit_msg>fixed client double connection bug<commit_after>var M = process.mono;
var mongo = require('mongodb');
var Server = mongo.Server;
var MongoClient = mongo.MongoClient;

var CONNECTION_STRING_RE = new RegExp('^([a-zA-Z0-9]+)://([a-zA-Z0-9\\._-]+):(\\d{4,5})/([a-zA-Z0-9\\._-]+)$');
var serverOptions = {
    native_parser: true,
    server: {
        poolSize: 3
    }
};

var clients = {};
var cbBuffer = {};

// available stores
M.stores = {};

module.exports = connect;

// TODO test callback buffering
function connect (connection, callback) {

    var config = parseConnection(connection);

    // check config
    if (!config) {
        return callback(new Error('Invalid connection string.'));
    }

    // check store cache
    if (M.stores[config.db]) {
        return callback(null, M.stores[config.db]);
    }

    // buffer callbacks when db is connecting
    if (cbBuffer[config.db] instanceof Array) {
        return cbBuffer[config.db].push(callback);
    }

    // save callback in buffer
    (cbBuffer[config.db] = cbBuffer[config.db] || []).push(callback);

    // get and authenticate db with cached client
    if (clients[config.client]) {
        return getAndAuthenticateDb(clients[config.client], config);
    }

    // get client
    clients[config.client] = new MongoClient(new Server(config.host, config.port, serverOptions));

    // open client connection
    clients[config.client].open(function (err, client) {

        if (err) {
            return callbacks(config.db, err, db);
        }

        // get and authenticate db
        getAndAuthenticateDb(client, config);
    });
}

function getAndAuthenticateDb (client, config) {

    // get db
    var db = client.db(config.name);

    // authenticate
    db.authenticate(config.user, config.pass, function(err) {

        // handle error
        if (err) {
            return callbacks(config.db, err);
        }

        M.stores[config.db] = db;
        callbacks(config.db, null, db);
    });
}

// parse connection string
function parseConnection (connection) {

    // TODO this is is a hack!
    if (!connection.match(CONNECTION_STRING_RE)) {
        connection = 'mongodb://localhost:27017/' + connection;
    }

    // check connection
    if (!(connection = connection.match(CONNECTION_STRING_RE))) {
        return;
    }

    // create connection object
    connection = {
        type: connection[1],
        host: connection[2],
        port: connection[3],
        name: connection[4],
        user: M.config.owner,
        pass: M.config.apiKey
    };

    // check connection values
    if (!connection.type || !connection.host || !connection.port || !connection.name) {
        return;
    }

    // add cache keys
    connection.client = connection.type + '://' + connection.host + ':' + connection.port;
    connection.db = connection.client + '/' + connection.name;

    return connection;
}

// call callbacks in callback buffer
function callbacks (key, err, db) {
    for (var i = 0; i < cbBuffer[key].length; ++i) {
        if (typeof cbBuffer[key][i] === 'function') {
            cbBuffer[key][i](err, db);
        }
    }

    delete cbBuffer[key];
}
<|endoftext|>


<commit_before>var lang = {

    default_language: 'en',
    language: 'en',

    strings: {
        en: {
            'score': 'Score',
            'grader_msg': 'Your score is ',
            'validate': 'Validate',
            'placeholder_text': 'Enter text',
            'placeholder_number': 'Enter number',
            'error_number': 'Must be a number',
            'placeholder_string': 'Enter string',
            'error_string': 'Must be a string',
            'placeholder_regexp': 'Enter text',
            'error_regexp': 'Invalid format'
        },
        fr: {}
    },

    set: function(lng) {
        this.language = lng;
    },

    translate: function(key) {
        if(this.strings[this.language] && this.strings[this.language][key]) {
            return this.strings[this.language][key];
        }
        return this.strings[this.default_language][key] || key;
    }

}

var task_token = {

    token: null,

    init: function() {
        var query = document.location.search.replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
        this.token = query.sToken || '';
    },

    get: function() {
        return this.token
    },

    update: function(token) {
        this.token = token
    },

    getAnswerToken: function(answer) {
        return null;
    }
}

var task = {}

task.getViews = function(success, error) {
    var views = {
        task: {}
    };
    success(views);
};

task.updateToken = function(token, success, error) {
    task_token.update(token)
    success();
};

task.getHeight = function(success, error) {
    var d = document;
    var h = Math.max(d.body.offsetHeight, d.documentElement.offsetHeight);
    success(h);
};

task.getMetaData = function(success, error) {
    if (typeof json !== 'undefined') {
        success(json);
    } else {
        success({nbHints: 0});
    }
};

task.reloadState = function(state, success, error) { success() }
task.getState = function(success, error) { success({})  }
task.reloadStateObject = function(obj) { }
task.getStateObject = function() { return {} }
task.getDefaultStateObject = function() { return {} }

$('solution').hide();
$('#solution').hide();
$('.grader').hide();

// grade

function useGraderData(answer, callback) {
    if(window.QuizzeGrader.grade && window.QuizzeGrader.data) {
        return callback(window.QuizzeGrader.grade(window.QuizzeGrader.data, answer));
    }
    console.error('Local QuizzeGrader not found');
}

function useGraderUrl(url, task_token, answer, callback) {
    var data = {
        action: 'grade',
        task: task_token,
        answer: answer
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(data),
        crossDomain: true,
        contentType: 'application/json'
    }).done(function(res) {
        if(res.success) {
            return callback(res.data);
        }
        console.error('Grader response error: ', res);
    }).fail(function(jqxhr, settings, exception ) {
        console.error('Grader url not responding: ' + url);
    });
}

task.load = function(views, success) {
    task_token.init()

    platform.getTaskParams(null, null, function(taskParams) {
        var random = parseInt(taskParams.randomSeed, 10) || 0
        var q = QuizzeUI({
            parent: $('#task'),
            shuffle_questions: random > 0, // in dev mode always 0 here and shuffle disabled
            shuffle_answers: random > 0,
            random: random
        });

        task.showViews = function(views, callback) {
            q.toggleSolutions(!!views.solution);
            $('#solution').toggle(!!views.solution);
            callback()
        }

        task.getAnswer = function(callback) {
            callback(JSON.stringify(q.getAnswer()));
        };

        task.reloadAnswer = function(answer, callback) {
            try {
                answer = JSON.parse(answer);
                q.setAnswer(answer);
            } catch(e) {

            }
            callback();
        };

        function displayScore(score, max_score) {
            var msg = '' + lang.translate('score') + '' + ' ' + score + '/' + max_score + '';
            if($('#score').length == 0) {
                var div = '

';
                $('.taskContent').first().append(div);
            }
            $('#score').html(msg);
        }

        task.gradeAnswer = function(answer, answer_token, callback) {
            answer = JSON.parse(answer);
            function onGrade(result) {
                var d = taskParams.maxScore - taskParams.minScore;
                var final_score = Math.max(
                    taskParams.minScore + Math.round(d * result.score),
                    taskParams.noScore || 0
                );
                q.showResult(result.mistakes);
                displayScore(final_score, taskParams.maxScore);
                callback(final_score, lang.translate('grader_msg') + final_score, null);
            }
            var token = task_token.get()
            if(token) {
                useGraderUrl(json.graderUrl, token, answer, onGrade);
            } else {
                useGraderData(answer, onGrade);
            }
        };

        task.reloadAnswerObject = function(answerObj) {
            return q.setAnswer(answerObj);
        }

        task.getAnswerObject = function() {
            return q.getAnswer();
        }

        task.getDefaultAnswerObject = function() {
            return [];
        }

        var btn = $('<button class="btn btn-success btn-validate">' + lang.translate('validate') + '</button>');
        btn.on('click', function() {
            platform.validate('done');
        });
        btn.insertAfter($('.taskContent'));

        success();
    });
};

window.QuizzeGrader = {}

var grader = {
    gradeTask: task.gradeAnswer
};

if(window.platform) {
    platform.initWithTask(task);
}

lang.set(window.stringsLanguage)<commit_msg>quizze: Fix getState<commit_after>var lang = {

    default_language: 'en',
    language: 'en',

    strings: {
        en: {
            'score': 'Score',
            'grader_msg': 'Your score is ',
            'validate': 'Validate',
            'placeholder_text': 'Enter text',
            'placeholder_number': 'Enter number',
            'error_number': 'Must be a number',
            'placeholder_string': 'Enter string',
            'error_string': 'Must be a string',
            'placeholder_regexp': 'Enter text',
            'error_regexp': 'Invalid format'
        },
        fr: {}
    },

    set: function(lng) {
        this.language = lng;
    },

    translate: function(key) {
        if(this.strings[this.language] && this.strings[this.language][key]) {
            return this.strings[this.language][key];
        }
        return this.strings[this.default_language][key] || key;
    }

}

var task_token = {

    token: null,

    init: function() {
        var query = document.location.search.replace(/(^\?)/,'').split("&").map(function(n){return n = n.split("="),this[n[0]] = n[1],this}.bind({}))[0];
        this.token = query.sToken || '';
    },

    get: function() {
        return this.token
    },

    update: function(token) {
        this.token = token
    },

    getAnswerToken: function(answer) {
        return null;
    }
}

var task = {}

task.getViews = function(success, error) {
    var views = {
        task: {}
    };
    success(views);
};

task.updateToken = function(token, success, error) {
    task_token.update(token)
    success();
};

task.getHeight = function(success, error) {
    var d = document;
    var h = Math.max(d.body.offsetHeight, d.documentElement.offsetHeight);
    success(h);
};

task.getMetaData = function(success, error) {
    if (typeof json !== 'undefined') {
        success(json);
    } else {
        success({nbHints: 0});
    }
};

task.reloadState = function(state, success, error) { success() }
task.getState = function(success, error) { success("{}")  }
task.reloadStateObject = function(obj) { }
task.getStateObject = function() { return {} }
task.getDefaultStateObject = function() { return {} }

$('solution').hide();
$('#solution').hide();
$('.grader').hide();

// grade

function useGraderData(answer, callback) {
    if(window.QuizzeGrader.grade && window.QuizzeGrader.data) {
        return callback(window.QuizzeGrader.grade(window.QuizzeGrader.data, answer));
    }
    console.error('Local QuizzeGrader not found');
}

function useGraderUrl(url, task_token, answer, callback) {
    var data = {
        action: 'grade',
        task: task_token,
        answer: answer
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(data),
        crossDomain: true,
        contentType: 'application/json'
    }).done(function(res) {
        if(res.success) {
            return callback(res.data);
        }
        console.error('Grader response error: ', res);
    }).fail(function(jqxhr, settings, exception ) {
        console.error('Grader url not responding: ' + url);
    });
}

task.load = function(views, success) {
    task_token.init()

    platform.getTaskParams(null, null, function(taskParams) {
        var random = parseInt(taskParams.randomSeed, 10) || 0
        var q = QuizzeUI({
            parent: $('#task'),
            shuffle_questions: random > 0, // in dev mode always 0 here and shuffle disabled
            shuffle_answers: random > 0,
            random: random
        });

        task.showViews = function(views, callback) {
            q.toggleSolutions(!!views.solution);
            $('#solution').toggle(!!views.solution);
            callback()
        }

        task.getAnswer = function(callback) {
            callback(JSON.stringify(q.getAnswer()));
        };

        task.reloadAnswer = function(answer, callback) {
            try {
                answer = JSON.parse(answer);
                q.setAnswer(answer);
            } catch(e) {

            }
            callback();
        };

        function displayScore(score, max_score) {
            var msg = '' + lang.translate('score') + '' + ' ' + score + '/' + max_score + '';
            if($('#score').length == 0) {
                var div = '

';
                $('.taskContent').first().append(div);
            }
            $('#score').html(msg);
        }

        task.gradeAnswer = function(answer, answer_token, callback) {
            answer = JSON.parse(answer);
            function onGrade(result) {
                var d = taskParams.maxScore - taskParams.minScore;
                var final_score = Math.max(
                    taskParams.minScore + Math.round(d * result.score),
                    taskParams.noScore || 0
                );
                q.showResult(result.mistakes);
                displayScore(final_score, taskParams.maxScore);
                callback(final_score, lang.translate('grader_msg') + final_score, null);
            }
            var token = task_token.get()
            if(token) {
                useGraderUrl(json.graderUrl, token, answer, onGrade);
            } else {
                useGraderData(answer, onGrade);
            }
        };

        task.reloadAnswerObject = function(answerObj) {
            return q.setAnswer(answerObj);
        }

        task.getAnswerObject = function() {
            return q.getAnswer();
        }

        task.getDefaultAnswerObject = function() {
            return [];
        }

        var btn = $('<button class="btn btn-success btn-validate">' + lang.translate('validate') + '</button>');
        btn.on('click', function() {
            platform.validate('done');
        });
        btn.insertAfter($('.taskContent'));

        success();
    });
};

window.QuizzeGrader = {}

var grader = {
    gradeTask: task.gradeAnswer
};

if(window.platform) {
    platform.initWithTask(task);
}

lang.set(window.stringsLanguage)
<|endoftext|>


<commit_before>import test from 'ava';
import { initFakeEnvVariables, TEST_VARIABLES, PARSED_VALUES } from './utils';
import readEnv from '../dist';

initFakeEnvVariables();

test('Doesn\'t parse at all', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: false,
  });

  t.true(options.object === TEST_VARIABLES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, TEST_VARIABLES.EXAMPLE_ARRAY);
  t.true(options.int === TEST_VARIABLES.EXAMPLE_INT);
  t.true(options.float === TEST_VARIABLES.EXAMPLE_FLOAT);
  t.true(options.true === TEST_VARIABLES.EXAMPLE_TRUE);
  t.true(options.false === TEST_VARIABLES.EXAMPLE_FALSE);
  t.true(options.string === TEST_VARIABLES.EXAMPLE_STRING);
});

test('Doesn\'t parse object but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      object: false,
    },
  });

  t.true(options.object === TEST_VARIABLES.EXAMPLE_OBJECT);

  // rest
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.float === PARSED_VALUES.EXAMPLE_FLOAT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse array but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      array: false,
    },
  });

  t.true(options.array === TEST_VARIABLES.EXAMPLE_ARRAY);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.float === PARSED_VALUES.EXAMPLE_FLOAT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse int but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      int: false,
    },
  });

  t.true(options.int === TEST_VARIABLES.EXAMPLE_INT);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.float === PARSED_VALUES.EXAMPLE_FLOAT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse float but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      float: false,
    },
  });

  t.true(options.float === TEST_VARIABLES.EXAMPLE_FLOAT);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse boolean but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      bool: false,
    },
  });

  t.true(options.true === TEST_VARIABLES.EXAMPLE_TRUE);
  t.true(options.false === TEST_VARIABLES.EXAMPLE_FALSE);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse invalid Object', (t) => {
  initFakeEnvVariables({
    EXAMPLE_OBJECT_BROKEN: '{"prop"',
  });

  const error = t.throws(() => readEnv('EXAMPLE'));
  t.is(error.message, 'Environment Variable "EXAMPLE_OBJECT_BROKEN" has invalid JSON input.');
});

test('Doesn\'t parse invalid Array', (t) => {
  initFakeEnvVariables({
    EXAMPLE_ARRAY_BROKEN: '[1,2,3, "string"',
  });

  const error = t.throws(() => readEnv('EXAMPLE'));
  t.is(error.message, 'Environment Variable "EXAMPLE_ARRAY_BROKEN" has invalid JSON input.');
});
<commit_msg>cleanFakeEnvVariables function introduced<commit_after>import test from 'ava';
import { initFakeEnvVariables, TEST_VARIABLES, PARSED_VALUES } from './utils';
import readEnv from '../dist';

initFakeEnvVariables();

test('Doesn\'t parse at all', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: false,
  });

  t.true(options.object === TEST_VARIABLES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, TEST_VARIABLES.EXAMPLE_ARRAY);
  t.true(options.int === TEST_VARIABLES.EXAMPLE_INT);
  t.true(options.float === TEST_VARIABLES.EXAMPLE_FLOAT);
  t.true(options.true === TEST_VARIABLES.EXAMPLE_TRUE);
  t.true(options.false === TEST_VARIABLES.EXAMPLE_FALSE);
  t.true(options.string === TEST_VARIABLES.EXAMPLE_STRING);
});

test('Doesn\'t parse object but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      object: false,
    },
  });

  t.true(options.object === TEST_VARIABLES.EXAMPLE_OBJECT);

  // rest
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.float === PARSED_VALUES.EXAMPLE_FLOAT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse array but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      array: false,
    },
  });

  t.true(options.array === TEST_VARIABLES.EXAMPLE_ARRAY);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.float === PARSED_VALUES.EXAMPLE_FLOAT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse int but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      int: false,
    },
  });

  t.true(options.int === TEST_VARIABLES.EXAMPLE_INT);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.float === PARSED_VALUES.EXAMPLE_FLOAT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse float but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      float: false,
    },
  });

  t.true(options.float === TEST_VARIABLES.EXAMPLE_FLOAT);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.true === PARSED_VALUES.EXAMPLE_TRUE);
  t.true(options.false === PARSED_VALUES.EXAMPLE_FALSE);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse boolean but parses rest', (t) => {
  const options = readEnv({
    prefix: 'EXAMPLE',
    parse: {
      bool: false,
    },
  });

  t.true(options.true === TEST_VARIABLES.EXAMPLE_TRUE);
  t.true(options.false === TEST_VARIABLES.EXAMPLE_FALSE);

  // rest
  t.deepEqual(options.object, PARSED_VALUES.EXAMPLE_OBJECT);
  t.deepEqual(options.array, PARSED_VALUES.EXAMPLE_ARRAY);
  t.true(options.int === PARSED_VALUES.EXAMPLE_INT);
  t.true(options.string === PARSED_VALUES.EXAMPLE_STRING);
});

test('Doesn\'t parse invalid Object', (t) => {
  initFakeEnvVariables({
    EXAMPLE_OBJECT_BROKEN: '{"prop"',
  });

  const error = t.throws(() => readEnv('EXAMPLE'));
  t.is(error.message, 'Environment Variable "EXAMPLE_OBJECT_BROKEN" has invalid JSON input.');
  delete process.env.EXAMPLE_OBJECT_BROKEN;
});

test('Doesn\'t parse invalid Array', (t) => {
  initFakeEnvVariables({
    EXAMPLE_ARRAY_BROKEN: '[1,2,3, "string"',
  });

  const error = t.throws(() => readEnv('EXAMPLE'));
  t.is(error.message, 'Environment Variable "EXAMPLE_ARRAY_BROKEN" has invalid JSON input.');
  delete process.env.EXAMPLE_OBJECT_BROKEN;
});
<|endoftext|>


<commit_before>/*jshint unused:false */

/**
 * @fileOverview The primitive CRUD operations.
 *
 */

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var midd = require('middlewarify');

var Entity = require('./entity');

/**
 * The CRUD Entity Class.
 *
 * @constructor
 * @extends {Entity}
 */
var entityCrud = module.exports = Entity.extend(function() {
  /** @type {?Object} The current user or null for anonymous */
  this.udo = null;

  /** @type {string} The default 'id' field name */
  this._idName = 'id';
  // Create primitive middlewares
  midd.make(this, 'create', this._create.bind(this), {beforeAfter: true});
  midd.make(this, 'read', this._read.bind(this), {beforeAfter: true});
  midd.make(this, 'readOne', this._readOne.bind(this), {beforeAfter: true});
  midd.make(this, 'readLimit', this._readLimit.bind(this), {beforeAfter: true});
  midd.make(this, 'update', this._update.bind(this), {beforeAfter: true});
  midd.make(this, 'delete', this._delete.bind(this), {beforeAfter: true});
  midd.make(this, 'count', this._count.bind(this), {beforeAfter: true});
});

/**
 * Set the current user data object
 * @param {Object} udo A User Data Object.
 */
entityCrud.prototype.setUdo = function(udo) {
  this.udo = udo;
};

/**
 * Create an entity item.
 *
 * @param {Object} itemData The data to use for creating.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
entityCrud.prototype._create = function(itemData, done) {
  throw new Error('Not Implemented');
};

/**
 * Read one entity item.
 *
 * @param {string|Object} id the item id or an Object to query against.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
entityCrud.prototype._readOne = function(id, done) {
  throw new Error('Not Implemented');
};

/**
 * Read items based on query or if not defined, read all items.
 * Do practice common sense!
 *
 * @param {Object|string=} optQuery Optionally define a query to limit results.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
entityCrud.prototype._read = function(optQuery, done) {
  throw new Error('Not Implemented');
};

/**
 * Read a limited set of items.
 *
 * @param {?Object} query Narrow down the set, set to null for all.
 * @param {number} skip starting position.
 * @param {number} limit how many records to fetch.
 * @param {Function(Error=, Array.<Object>=)} done callback.
 * @protected
 */
entityCrud.prototype._readLimit = function(query, skip, limit, done) {
  throw new Error('Not Implemented');
};

/**
 * Get the count of items.
 *
 * @param {?Object} query Narrow down the set, set to null for all.
 * @param {Function(Error=, number=)} done callback.
 * @protected
 */
entityCrud.prototype._count = function(query, done) {
  throw new Error('Not Implemented');
};

/**
 * Update an entity item.
 *
 * @param {string} id the item id.
 * @param {Object} itemData The data to use for creating.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
entityCrud.prototype._update = function(id, itemData, done) {
  throw new Error('Not Implemented');
};

/**
 * Remove an entity item.
 *
 * @param {string} id the item id.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
entityCrud.prototype._delete = function(id, done) {
  throw new Error('Not Implemented');
};

<commit_msg>refactor entity-crud to new design<commit_after>/*jshint unused:false */

/**
 * @fileOverview The primitive CRUD operations.
 *
 */

var EventEmitter = require('events').EventEmitter;
var util = require('util');

var midd = require('middlewarify');

var Entity = require('./entity');

/**
 * The CRUD Entity Class.
 *
 * @param {Object=} optUdo Optionally define the UDO of the user performing
 *   the action.
 * @constructor
 * @extends {Entity}
 */
var EntityCrud = module.exports = Entity.extend(function(optUdo) {
  /** @type {?Object} The current user or null for anonymous */
  this.udo = optUdo || null;

  /** @type {string} The default 'id' field name */
  this._idName = 'id';
  // Create primitive middlewares
  this.method('create', this._create.bind(this));
  this.method('read', this._read.bind(this));
  this.method('readOne', this._readOne.bind(this));
  this.method('readLimit', this._readLimit.bind(this));
  this.method('update', this._update.bind(this));
  this.method('delete', this._delete.bind(this));
  this.method('count', this._count.bind(this));
});

/**
 * Set the current user data object
 * @param {Object} udo A User Data Object.
 */
EntityCrud.prototype.setUdo = function(udo) {
  this.udo = udo;
};

/**
 * Create an entity item.
 *
 * @param {Object} itemData The data to use for creating.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
EntityCrud.prototype._create = function(itemData, done) {
  throw new Error('Not Implemented');
};

/**
 * Read one entity item.
 *
 * @param {string|Object} id the item id or an Object to query against.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
EntityCrud.prototype._readOne = function(id, done) {
  throw new Error('Not Implemented');
};

/**
 * Read items based on query or if not defined, read all items.
 * Do practice common sense!
 *
 * @param {Object|string=} optQuery Optionally define a query to limit results.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
EntityCrud.prototype._read = function(optQuery, done) {
  throw new Error('Not Implemented');
};

/**
 * Read a limited set of items.
 *
 * @param {?Object} query Narrow down the set, set to null for all.
 * @param {number} skip starting position.
 * @param {number} limit how many records to fetch.
 * @param {Function(Error=, Array.<Object>=)} done callback.
 * @protected
 */
EntityCrud.prototype._readLimit = function(query, skip, limit, done) {
  throw new Error('Not Implemented');
};

/**
 * Get the count of items.
 *
 * @param {?Object} query Narrow down the set, set to null for all.
 * @param {Function(Error=, number=)} done callback.
 * @protected
 */
EntityCrud.prototype._count = function(query, done) {
  throw new Error('Not Implemented');
};

/**
 * Update an entity item.
 *
 * @param {string} id the item id.
 * @param {Object} itemData The data to use for creating.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
EntityCrud.prototype._update = function(id, itemData, done) {
  throw new Error('Not Implemented');
};

/**
 * Remove an entity item.
 *
 * @param {string} id the item id.
 * @param {Function(Error=, Object=)} done callback.
 * @protected
 */
EntityCrud.prototype._delete = function(id, done) {
  throw new Error('Not Implemented');
};

<|endoftext|>


<commit_before>'use strict'

const FAILED = 'failed'
const SUCCEEDED = 'succeeded'

let domain = require('domain')
let logger = require('tracer').colorConsole()
let Pipeline = require('../../core/pipelines/pipeline')
let Stage = require('../../core/pipelines/stage')
let registry = require('../../extensions/registry')

module.exports = class Job {
  constructor(msg, next) {
    this.next = next
    this.pipeline = new Pipeline(msg.id)
    this.start()
  }

  start() {
    // Pipeline execution is a complicated mix of async
    // and sync processes. In order to handle both all steps
    // must be wrapped in a Promise. This keeps a promise chain
    // working through out the whole execution. Then sync
    // operations are handled internally by the promise wrapped
    // functions.

    // Start once our pipeline execution record has been loaded
    this.pipeline.exec
      .then(() => this.pipeline.running())
      .then(() => {
        // Create stage instance for each configuration
        this.stages = this.pipeline.config.stageConfigs.map((config, index) => {
          return new Stage(index + 1, config, this.pipeline)
        })
        // Resolve once all instances have an execution record
        return Promise.all(this.stages.map(stage => stage.exec))
      })
      .then(() => {
        return Promise.all(this.stages.map(stage => this.execute(stage)))
      })
      .then(() => this.pipeline.complete())
      .then(() => this.next())
      .catch((err) => {
        logger.error('Pipeline execution failed in an unexpected way!')
        logger.error(err)
      })
  }

  execute(stage) {
    let extension = registry.get(stage.config.type)

    // TODO: should we use the reject callback
    // to have to promise fail fast? but then
    // we can't mark stages as skipped
    return new Promise(resolve => {
      if (this.pipeline.hasFailed) {
        logger.debug('previous stage failed')
        // TODO: skip execution
      } else {
        // Turn stage async execution into a sync operation
        let wait = setInterval(() => {
          logger.debug('Running stage | ' + stage.stageId)
        }, 2000)

        stage.on(FAILED, () => {
          this.pipeline.hasFailed = true
          clearInterval(wait)
          resolve()
        })

        stage.on(SUCCEEDED, () => {
          clearInterval(wait)
          resolve()
        })

        // This try-catch doesn't work
        // Looks like we'll need to use process.on('uncaughtException'...
        // https://nodejs.org/docs/latest/api/process.html#process_event_uncaughtexception
        // OR, domains

        let d = domain.create()

        d.on('error', function(err) {
          logger.error(err)
          stage.trigger(FAILED)
        })

        d.run(() => {
          extension.execute(stage)
        })

      }
    })
  }

  // skip() {
  //   return connection
  // }

}
<commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before>/* eslint-env browser, jquery */
(function () {
	'use strict';

	// Super ugly, but who cares
	// Intentionally using older JS syntax here as I want to ensure this works
	if (window.location.search === '?success') {
		$('#main').html('
Thanks for the feedback!

You will now be redirected to my website.');

		setTimeout(function () {
			window.location.href = 'https://sindresorhus.com';
		}, 3000);
	}
})();

(() => {
	'use strict';

	$('button[type="submit"]').on('click', event => {
		$(event.target)
			.closest('form')
			.find('[required]')
			.addClass('required');
	});

	const params = new URL(location.href).searchParams;

	if (params.has('product')) {
		$('#main h1 > span').text(` · ${params.get('product')}`);
	}

	const form = $('#feedback-form');

	// Include all the existing search params
	for (const [key, val] of params) {
		form.append(`<input type="hidden" name="${key}" value="${val}">`);
	}

	form.on('submit', () => {
		const product = params.has('product') ? ` · ${params.get('product')}` : '';
		const message = form.find('[name="message"]').val().slice(0, 100);
		const subject = `Feedback${product} - ${message}`;
		form.append(`<input type="hidden" name="_subject" value="${subject}">`);
	});
})();
<commit_msg>Update main.js<commit_after>/* eslint-env browser, jquery */
(function () {
	'use strict';

	// Super ugly, but who cares
	// Intentionally using older JS syntax here as I want to ensure this works
	if (window.location.search === '?success') {
		$('#main').html('
Thanks for the feedback!

You will now be redirected to my website.');

		setTimeout(function () {
			window.location.href = 'https://homereck.me';
		}, 3000);
	}
})();

(() => {
	'use strict';

	$('button[type="submit"]').on('click', event => {
		$(event.target)
			.closest('form')
			.find('[required]')
			.addClass('required');
	});

	const params = new URL(location.href).searchParams;

	if (params.has('product')) {
		$('#main h1 > span').text(` · ${params.get('product')}`);
	}

	const form = $('#feedback-form');

	// Include all the existing search params
	for (const [key, val] of params) {
		form.append(`<input type="hidden" name="${key}" value="${val}">`);
	}

	form.on('submit', () => {
		const product = params.has('product') ? ` · ${params.get('product')}` : '';
		const message = form.find('[name="message"]').val().slice(0, 100);
		const subject = `Feedback${product} - ${message}`;
		form.append(`<input type="hidden" name="_subject" value="${subject}">`);
	});
})();
<|endoftext|>


<commit_before>"use strict";

var assert = require("assert");
var referee = require("./referee");

describe("add", function() {
    context("when passed an invalid name argument", function() {
        it("should throw a TypeError", function() {
            var expected =
                "'name' argument must be a non-empty string matching /^[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*$/";
            var error;
            try {
                referee.add("invalid name");
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when passed an invalid options argument", function() {
        it("should throw a TypeError", function() {
            var expected = "'options' argument must be a non-empty object";
            var options = {};
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid assert option", function() {
        it("should throw a TypeError", function() {
            var expected =
                "'assert' option must be a Function, taking at least one argument";
            var options = {
                assert: function() {}
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid refute option", function() {
        it("should throw a TypeError", function() {
            var expected =
                "'refute' option must be a Function, taking at least one argument";
            var options = {
                assert: function(actual) {
                    return actual;
                },
                refute: function() {}
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid assertMessage option", function() {
        it("should throw a TypeError", function() {
            var expected = "'assertMessage' option must be a non-empty String";
            var options = {
                assert: function(actual) {
                    return actual;
                },
                refute: function(actual) {
                    return actual;
                },
                assertMessage: ""
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid refuteMessage option", function() {
        it("should throw a TypeError", function() {
            var expected = "'refuteMessage' option must be a non-empty String";
            var options = {
                assert: function(actual) {
                    return actual;
                },
                refute: function(actual) {
                    return actual;
                },
                assertMessage: "apple pie",
                refuteMessage: ""
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });
});
<commit_msg>Fix coverage for define-assertion promise handling<commit_after>"use strict";

var assert = require("assert");
var sinon = require("sinon");
var referee = require("./referee");

describe("add", function() {
    context("when passed an invalid name argument", function() {
        it("should throw a TypeError", function() {
            var expected =
                "'name' argument must be a non-empty string matching /^[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*$/";
            var error;
            try {
                referee.add("invalid name");
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when passed an invalid options argument", function() {
        it("should throw a TypeError", function() {
            var expected = "'options' argument must be a non-empty object";
            var options = {};
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid assert option", function() {
        it("should throw a TypeError", function() {
            var expected =
                "'assert' option must be a Function, taking at least one argument";
            var options = {
                assert: function() {}
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid refute option", function() {
        it("should throw a TypeError", function() {
            var expected =
                "'refute' option must be a Function, taking at least one argument";
            var options = {
                assert: function(actual) {
                    return actual;
                },
                refute: function() {}
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid assertMessage option", function() {
        it("should throw a TypeError", function() {
            var expected = "'assertMessage' option must be a non-empty String";
            var options = {
                assert: function(actual) {
                    return actual;
                },
                refute: function(actual) {
                    return actual;
                },
                assertMessage: ""
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("when called with invalid refuteMessage option", function() {
        it("should throw a TypeError", function() {
            var expected = "'refuteMessage' option must be a non-empty String";
            var options = {
                assert: function(actual) {
                    return actual;
                },
                refute: function(actual) {
                    return actual;
                },
                assertMessage: "apple pie",
                refuteMessage: ""
            };
            var error;

            try {
                referee.add("isApplePie", options);
            } catch (err) {
                error = err;
            }

            assert.equal(error.message, expected);
            assert(error instanceof TypeError);
        });
    });

    context("with assert returning a promise", function() {
        before(function() {
            if (typeof Promise === "undefined") {
                this.skip();
            }
        });

        it("returns a promise and calls referee.pass when resolved", function() {
            var then = sinon.fake();
            var options = {
                assert: function(thing) {
                    return thing && new Promise(then);
                },
                assertMessage: "returning a promise",
                refuteMessage: "not returning a promise"
            };
            referee.add("returningPromise", options);

            var result = referee.assert.returningPromise(1);

            assert(result instanceof Promise);

            then.firstCall.args[0](); // Get coverage on then handler
        });
    });
});
<|endoftext|>


<commit_before>// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var common = require('./common.js');
var pexprs = require('./pexprs.js');

var awlib = require('awlib');
var printString = awlib.stringUtils.printString;
var makeStringBuffer = awlib.objectUtils.stringBuffer;

// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------

pexprs.PExpr.prototype.toExpected = function(ruleDict) {
  return undefined;
};

pexprs.anything.toExpected = function(ruleDict) {
  return "any object";
};

pexprs.end.toExpected = function(ruleDict) {
  return "end of input";
};

pexprs.Prim.prototype.toExpected = function(ruleDict) {
  return printString(this.obj);
};

pexprs.Not.prototype.toExpected = function(ruleDict) {
  return "no " + this.expr.toExpected();
};

// TODO: think about Listy and Obj

pexprs.Apply.prototype.toExpected = function(ruleDict) {
  var description = ruleDict[this.ruleName].description;
  if (description) {
    return description;
  } else {
    var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a";
    return article + " " + this.ruleName;
  }
};

<commit_msg>Print end as "nothing" instead of "no any object"<commit_after>// --------------------------------------------------------------------
// Imports
// --------------------------------------------------------------------

var common = require('./common.js');
var pexprs = require('./pexprs.js');

var awlib = require('awlib');
var printString = awlib.stringUtils.printString;
var makeStringBuffer = awlib.objectUtils.stringBuffer;

// --------------------------------------------------------------------
// Operations
// --------------------------------------------------------------------

pexprs.PExpr.prototype.toExpected = function(ruleDict) {
  return undefined;
};

pexprs.anything.toExpected = function(ruleDict) {
  return "any object";
};

pexprs.end.toExpected = function(ruleDict) {
  return "end of input";
};

pexprs.Prim.prototype.toExpected = function(ruleDict) {
  return printString(this.obj);
};

pexprs.Not.prototype.toExpected = function(ruleDict) {
  if (this.expr === pexprs.anything) {
    return "nothing";
  } else {
    return "no " + this.expr.toExpected();
  }
};

// TODO: think about Listy and Obj

pexprs.Apply.prototype.toExpected = function(ruleDict) {
  var description = ruleDict[this.ruleName].description;
  if (description) {
    return description;
  } else {
    var article = /^[aeiouAEIOU]/.test(this.ruleName) ? "an" : "a";
    return article + " " + this.ruleName;
  }
};

<|endoftext|>


<commit_before>function jcc(a, b, c) {
    "use strict";
    var uc_a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        lc_a = "abcdefghijklmnopqrstuvwxyz",
        z;
    b = Number(b);
    c = Number(c);
    if (typeof a === "string" && b > 0 && b < 26 && /^(0|1)$/.test(c)) {
        z = a.split("");
        uc_a = uc_a.split("");
        lc_a = lc_a.split("");
        // shifting each letter
        z.forEach(function (v, i) {
            var rui, rli;
            // matching and shifting uppercase [rui]
            uc_a.forEach(function (iv, ii) {
                if (v === iv) {
                    if (c === 0) {
                        rui = ii + b;
                        if (rui > 25) {
                            rui = rui % 26;
                        }
                        z[i] = uc_a[rui];
                    } else {
                        rui = ii - b;
                        if (rui < 0) {
                            rui = 26 + rui;
                        }
                        z[i] = uc_a[rui];
                    }
                }
            });
            // matching and shifting lowercase [rli]
            lc_a.forEach(function (iv, ii) {
                if (v === iv) {
                    if (c === 0) {
                        rli = ii + b;
                        if (rli > 25) {
                            rli = rli % 26;
                        }
                        z[i] = lc_a[rli];
                    } else {
                        rli = ii - b;
                        if (rli < 0) {
                            rli = 26 + rli;
                        }
                        z[i] = lc_a[rli];
                    }
                }
            });
        });
        z = z.join("");
    } else {
        z = "ERROR INPUT";
    }
    return z;
}
<commit_msg>trimmed a bit<commit_after>function jcc(a, b, c) {
    "use strict";
    var uc_a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
        lc_a = "abcdefghijklmnopqrstuvwxyz",
        z;
    b = Number(b);
    c = Number(c);
    if (typeof a === "string" && b > 0 && b < 26 && /^(0|1)$/.test(c)) {
        z = a.split("");
        uc_a = uc_a.split("");
        lc_a = lc_a.split("");
        // shifting each letter
        z.forEach(function (v, i) {
            var rui, rli;
            uc_a.forEach(function (iv, ii) {
                // matching and shifting uppercase [rui]
                if (v === iv) {
                    if (c === 0) {
                        rui = ii + b;
                        if (rui > 25) {
                            rui = rui % 26;
                        }
                        z[i] = uc_a[rui];
                    } else {
                        rui = ii - b;
                        if (rui < 0) {
                            rui = 26 + rui;
                        }
                        z[i] = uc_a[rui];
                    }
                }
                // matching and shifting lowercase [rli]
                if (v === lc_a[iv]) {
                    if (c === 0) {
                        rli = ii + b;
                        if (rli > 25) {
                            rli = rli % 26;
                        }
                        z[i] = lc_a[rli];
                    } else {
                        rli = ii - b;
                        if (rli < 0) {
                            rli = 26 + rli;
                        }
                        z[i] = lc_a[rli];
                    }
                }
            });
        });
        z = z.join("");
    } else {
        z = "ERROR INPUT";
    }
    return z;
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var Q = require('q');
var MongoClient = require('mongodb').MongoClient;

var host = 'brie.cshl.edu'
  , port = 27017
  , dbName = 'search'
  , dbVersion = '57'
  , rootMongoUrl = 'mongodb://' + host + ':' + port + '/' + dbName + dbVersion
  , databasePromise = Q.ninvoke(MongoClient, "connect", rootMongoUrl);

function Collections(collections) {
  // copy all the properties to this object
  _.assign(this, collections);

  // add mongoCollection function to each.
  _.forOwn(collections, function (collection) {
    collection.mongoCollection = function() {
      return databasePromise.then(function (db) {
        return db.collection(collection.collectionName);
      }).catch(function(err) {
        console.log(err);
      });
    }.bind(this)
  }.bind(this));
}

Collections.prototype.closeMongoDatabase = function () {
  databasePromise.then(function (db) {
    db.close();
  });
};

Collections.prototype.getVersion = function () {
  return dbVersion;
};

Collections.prototype.getMongoConfig = function () {
  return {
    host: host,
    port: port,
    version: dbVersion,
    db: dbName + dbVersion
  };
};

var collections = new Collections({
  genes: {
    collectionName: 'genes',
    description: 'gramene genes'
  },
  genetrees: {
    collectionName: 'genetree',
    description: 'compara gene trees'
  },
  GO: {
    collectionName: 'GO',
    description: 'gene ontology terms'
  },
  PO: {
    collectionName: 'PO',
    description: 'plant ontology terms'
  },
  taxonomy: {
    collectionName: 'taxonomy',
    description: 'NCBI taxonomy (pruned to cover gramene species)'
  },
  domains: {
    collectionName: 'domains',
    description: 'intepro domains'
  },
  pathways: {
    collectionName: 'pathways',
    description: 'plant reactome pathways and reactions'
  },
  maps: {
    collectionName: 'maps',
    description: 'maps genomes, genetic maps, and physical maps'
  },
  experiments: {
    collectionName: 'experiments',
    description: 'EBI Atlas experiments'
  },
  assays: {
    collectionName: 'assays',
    description: 'EBI Atlas assays'
  },
  expression: {
    collectionName: 'expression',
    description: 'EBI Atlas expression data'
  }
});

module.exports = collections;
<commit_msg>release58<commit_after>'use strict';

var _ = require('lodash');
var Q = require('q');
var MongoClient = require('mongodb').MongoClient;

var host = 'brie.cshl.edu'
  , port = 27017
  , dbName = 'search'
  , dbVersion = '58'
  , rootMongoUrl = 'mongodb://' + host + ':' + port + '/' + dbName + dbVersion
  , databasePromise = Q.ninvoke(MongoClient, "connect", rootMongoUrl);

function Collections(collections) {
  // copy all the properties to this object
  _.assign(this, collections);

  // add mongoCollection function to each.
  _.forOwn(collections, function (collection) {
    collection.mongoCollection = function() {
      return databasePromise.then(function (db) {
        return db.collection(collection.collectionName);
      }).catch(function(err) {
        console.log(err);
      });
    }.bind(this)
  }.bind(this));
}

Collections.prototype.closeMongoDatabase = function () {
  databasePromise.then(function (db) {
    db.close();
  });
};

Collections.prototype.getVersion = function () {
  return dbVersion;
};

Collections.prototype.getMongoConfig = function () {
  return {
    host: host,
    port: port,
    version: dbVersion,
    db: dbName + dbVersion
  };
};

var collections = new Collections({
  genes: {
    collectionName: 'genes',
    description: 'gramene genes'
  },
  genetrees: {
    collectionName: 'genetree',
    description: 'compara gene trees'
  },
  GO: {
    collectionName: 'GO',
    description: 'gene ontology terms'
  },
  PO: {
    collectionName: 'PO',
    description: 'plant ontology terms'
  },
  taxonomy: {
    collectionName: 'taxonomy',
    description: 'NCBI taxonomy (pruned to cover gramene species)'
  },
  domains: {
    collectionName: 'domains',
    description: 'intepro domains'
  },
  pathways: {
    collectionName: 'pathways',
    description: 'plant reactome pathways and reactions'
  },
  maps: {
    collectionName: 'maps',
    description: 'maps genomes, genetic maps, and physical maps'
  },
  experiments: {
    collectionName: 'experiments',
    description: 'EBI Atlas experiments'
  },
  assays: {
    collectionName: 'assays',
    description: 'EBI Atlas assays'
  },
  expression: {
    collectionName: 'expression',
    description: 'EBI Atlas expression data'
  }
});

module.exports = collections;
<|endoftext|>


<commit_before>const bunyan = require('bunyan')
const bunyanFormat = require('bunyan-format')

const chalk = require('chalk')
chalk.enabled = true

const name = process.env.API_LOG_NAME || 'colmena'
const level = process.env.API_LOG_LEVEL || 'debug'

const streams = []

streams.push({
  level,
  stream: bunyanFormat({ outputMode: 'short' }),
})

const log = bunyan.createLogger({
  name,
  streams,
})

const colors = [
  'black',
  'red',
  'green',
  'yellow',
  'blue',
  'magenta',
  'cyan',
  'white',
  'gray',
]

colors.forEach(
  color => (log[color] = (...str) => log.info(chalk[color](...str)))
)
colors.forEach(
  color => (log[color].b = (...str) => log.info(chalk[color].bold(...str)))
)
colors.forEach(
  color => (log[color].d = (...str) => log.info(chalk[color].dim(...str)))
)

module.exports = log
<commit_msg>chore(logger): format files using prettier<commit_after>const bunyan = require('bunyan')
const bunyanFormat = require('bunyan-format')

const chalk = require('chalk')
chalk.enabled = true

const name = process.env.API_LOG_NAME || 'colmena'
const level = process.env.API_LOG_LEVEL || 'debug'

const streams = []

streams.push({
  level,
  stream: bunyanFormat({ outputMode: 'short' }),
})

const log = bunyan.createLogger({
  name,
  streams,
})

const colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray']

colors.forEach(color => (log[color] = (...str) => log.info(chalk[color](...str))))
colors.forEach(color => (log[color].b = (...str) => log.info(chalk[color].bold(...str))))
colors.forEach(color => (log[color].d = (...str) => log.info(chalk[color].dim(...str))))

module.exports = log
<|endoftext|>