<commit_before>/* eslint-disable */

const mock = require("./_parser_mock").named("sns");
const parser = require(`../../src/parsers/sns`);

test(`Parser[${mock.name}] exists`, () => {
	expect(parser).toEqual(expect.any(Function));
	expect(parser.prototype)
		.toEqual(expect.objectContaining({ parse: expect.any(Function) }));
});

const instance = mock.makeNew();

test(`Parser[${mock.name}] exists`, async () => {
	function rand(digits) {
		return String(Math.random() * 100000000).substr(0, digits);
	}

	const message = {
		"foo": "bar",
	};

	const event = {
		Records: [{
			"EventSource": "aws:sns",
			"EventVersion": "1.0",
			"EventSubscriptionArn": "arn:aws:sns:region:9999999991:ExampleTopic:ExampleSubscriptionId",
			"Sns": {
				"Type": "Notification",
				"TopicArn": "arn:aws:sns:region:9999999991:ExampleTopic",
				"SignatureVersion": "1",
				"Timestamp": `1970-0${rand(1)}-2${rand(1)}T0${rand(1)}:0${rand(1)}:0${rand(1)}.${rand(3)}Z`,
				"Signature": "http://example.com/signature",
				"SigningCertUrl": "http://example.com/signingcerturl",
				"UnsubscribeUrl": "http://example.com/unsubscribeurl",
				"Subject": "TestInvoke",
				"MessageId": `95df01b4-ee${rand(2)}-5cb9-9903-4c221d41${rand(4)}`,
				"Message": JSON.stringify(message),
				"MessageAttributes": {
					"Test": {
						"Type": "String",
						"Value": "TestString"
					},
					"TestBinary": {
						"Type": "Binary",
						"Value": "TestBinary"
					}
				},
			},
		}]
	};

	instance.handleMessage = (record) => {
		expect(record).toEqual(expect.objectContaining({ "foo": "bar" }));
		expect(instance.getSubject()).toEqual(event.Records[0].Sns.Subject);
		expect(instance.getTimestamp()).toEqual(event.Records[0].Sns.Timestamp);
		expect(instance.getRegion()).toEqual("region");
		expect(instance.getAccountId()).toEqual("9999999991");
	};

	expect.assertions(5);
	await instance.parse(event);
});
<commit_msg>smarter tests for sns.js<commit_after>/* eslint-disable */

const mock = require("./_parser_mock").named("sns");

test(`Parser[${mock.name}] can be loaded and has .parse() method`, () => {
	const parser = require(`../../src/parsers/sns`);
	expect(parser).toEqual(expect.any(Function));
	expect(parser.prototype)
		.toEqual(expect.objectContaining({ parse: expect.any(Function) }));
});

test(`Parser[${mock.name}] convenience functions return values`, async () => {
	function rand(digits) {
		return String(Math.random() * 100000000).substr(0, digits);
	}

	const message = {
		"foo": "bar",
	};

	const event = {
		Records: [{
			"EventSource": "aws:sns",
			"EventVersion": "1.0",
			"EventSubscriptionArn": "arn:aws:sns:region:9999999991:ExampleTopic:ExampleSubscriptionId",
			"Sns": {
				"Type": "Notification",
				"TopicArn": "arn:aws:sns:region:9999999991:ExampleTopic",
				"SignatureVersion": "1",
				"Timestamp": `1970-0${rand(1)}-2${rand(1)}T0${rand(1)}:0${rand(1)}:0${rand(1)}.${rand(3)}Z`,
				"Signature": "http://example.com/signature",
				"SigningCertUrl": "http://example.com/signingcerturl",
				"UnsubscribeUrl": "http://example.com/unsubscribeurl",
				"Subject": "TestInvoke",
				"MessageId": `95df01b4-ee${rand(2)}-5cb9-9903-4c221d41${rand(4)}`,
				"Message": JSON.stringify(message),
				"MessageAttributes": {
					"Test": {
						"Type": "String",
						"Value": "TestString"
					},
					"TestBinary": {
						"Type": "Binary",
						"Value": "TestBinary"
					}
				},
			},
		}]
	};

	const instance = mock.makeNew();
	instance.handleMessage = (record) => {
		expect(record).toEqual(expect.objectContaining({ "foo": "bar" }));
		expect(instance.getSubject()).toEqual(event.Records[0].Sns.Subject);
		expect(instance.getTimestamp()).toEqual(event.Records[0].Sns.Timestamp);
		expect(instance.getRegion()).toEqual("region");
		expect(instance.getAccountId()).toEqual("9999999991");
	};

	expect.assertions(5);
	await instance.parse(event);
});

test(`Parser[${mock.name}] will not accept any events`, async () => {
	const event = { foo: "bar" };
	const result = await mock.makeNew().parse(event);
	expect(result).toBeFalsy();
});

test(`Parser[${mock.name}] handleMessage will throw`, () => {
	const event = { foo: "bar" };
	expect(() => mock.makeNew().handleMessage(event)).toThrow();
});
<|endoftext|>


<commit_before>import * as _ from 'lodash'

import * as common from 'sto-areas/lib/commonGraduationRequirements'
import * as utilities from 'sto-areas/lib/commonGraduationUtilities'
import * as educ from 'sto-areas/lib/commonEducationRequirements'
import * as eduUtilities from 'sto-areas/lib/commonEducationUtilities'
let countGeneds = eduUtilities.countGeneds

function onlyMusicMajors(major) {
	return _.any([
		major.title === 'Performance',
		major.title === 'Church Music',
		major.title === 'Theory-Composition',
		major.title === 'Music Education',
		major.title === 'Elective Studies',
	])
}

function foreignLanguage(courses) {
	// Foreign Language [FOL] -- 0-2 courses
	// Vocal Performance: 0-2 courses in each of 2 languages; one must be French or German)
	return {
		title: 'Foreign Language',
		abbr: 'FOL',
		result: true,
	}
}

function abstractAndQuantitativeReasoning(courses) {
	// AQR or SED or IST
	let which = _.find([
		{
			title: 'Abstract and Quantitative Reasoning',
			abbr: 'AQR',
			result: countGeneds(courses, 'AQR') >= 1,
		},
		{
			title: 'Studies in Natural Science: Scientific Exploration and Discovery',
			abbr: 'SED',
			result: countGeneds(courses, 'SED') >= 1,
		},
		{
			title: 'Integrated Scientific Topics',
			abbr: 'IST',
			result: countGeneds(courses, 'IST') >= 1,
		},
	], 'result')

	let generic = {
		title: 'Abstract and Quantitative Reasoning OR Studies in Natural Science: Scientific Exploration and Discovery OR Integrated Scientific Topics',
		abbr: 'AQR/SED/IST',
		result: false,
	}

	if (which) {
		return which
	} else {
		return generic
	}
}

function historicalOrLiteraryStudies(courses) {
	// ALS-L or HWC - 1 course
	let which = _.find([
		{
			title: 'Historical Studies in Western Culture',
			abbr: 'HWC',
			result: countGeneds(courses, 'HWC') >= 1,
		},
		{
			title: 'Literary Studies',
			abbr: 'ALS-L',
			result: countGeneds(courses, 'ALS-L') >= 1,
		},
	], 'result')

	let generic = {
		title: 'Historical Studies in Western Culture OR Literary Studies',
		abbr: 'HWC/ALS-L',
		result: false,
	}

	if (which) {
		return which
	} else {
		return generic
	}
}

function multiculturalStudies(courses) {
	// MCD or MCG - 1 course
	let which = _.find([
		{
			title: 'Multicultural Studies - Domestic',
			abbr: 'MCD',
			result: countGeneds(courses, 'MCD') >= 1,
		},
		{
			title: 'Multicultural Studies - Global',
			abbr: 'MCG',
			result: countGeneds(courses, 'MCG') >= 1,
		},
	], 'result')

	let generic = {
		title: 'Multicultural Studies',
		abbr: 'MCD/MCG',
		result: false,
	}

	if (which) {
		return which
	} else {
		return generic
	}
}

function dedicatedMusicMajor(studies, courses) {
	// B.M. candidates must choose from the five majors offered. Please
	// consult the Music Department listing in this catalog for specific major
	// requirements. These constitute the final authority on degree
	// requirements.  Entrance to all B.M. majors is by audition and/or
	// application only. Once approved, students should declare their major
	// formally as soon as possible by submitting a completed declaration of
	// major form to the Music Department office. Subsequent changes are
	// allowed, but students are encouraged to keep their records current,
	// documenting any changes with re-submissions of the same form.

	// Other regulations are:

	// Of the credits counting toward the minimum requirements for a major, a
	// total of six (6.00) must be completed with a grade of C or higher.
	// NOTE: Ignored, because we don't store grades.

	// No courses explicitly required for a B.M Music major may be taken S/U.
	// NOTE: Ignored, because we don't store s/u status.

	// At least 50 percent of the minimum major must be taken through St.
	// Olaf. Students should consult the registrar and the department chair or
	// program director about counting toward a major courses taken at other
	// colleges. In addition to the registrar, the chair must sign the
	// student’s transfer of credit form (available from the Office of the
	// Registrar and Academic Advising) if work from other institutions is
	// accepted in advance. Likewise, courses taken through St. Olaf off-
	// campus programs must be approved by the chair or director and the off-
	// campus program advisor in advance if credit toward a major is sought.
	// (See TRANSFER OF CREDIT TO ST. OLAF )
	// NOTE: Ignored, because this doesn't know about major requirements.

	let majors = _.filter(studies, {type: 'major'})

	let musicMajors = _.filter(majors, onlyMusicMajors)

	return {
		title: 'Music Major',
		type: 'boolean',
		result: _.size(musicMajors) >= 1 && _.every(musicMajors, utilities.creditsBeyondTheArea(courses, 8))
	}
}

function checkBachelorOfMusicDegree(student) {
	return student.data().then((studentPieces) => {
		let {
			courses,
			fabrications,
			studies,
			creditsNeeded,
			graduation,
			matriculation,
		} = studentPieces

		courses = _.filter(courses, utilities.onlyQuarterCreditCoursesCanBePassFail)

		// Requirements taken from
		// http://www.stolaf.edu/catalog/1314/academiclife/bm-gen-grad-requirements.html

		let graduationRequirements = [
			common.courses(courses, creditsNeeded),
			common.residency(courses, fabrications),
			common.interim(courses, fabrications, graduation),
			common.courseLevel(courses),
			common.gpa(courses),
			common.gradedCourses(courses, fabrications),
			dedicatedMusicMajor(studies, courses),
		]

		if (utilities.isBachelorOfBoth(studies)) {
			graduationRequirements.push(common.artsAndMusicDoubleMajor(courses, studies, fabrications))
		}

		let educationRequirements = {
			foundation: [
				educ.firstYearWriting(courses, matriculation),
				educ.writingInContext(courses),
				foreignLanguage(courses),
				educ.oralCommunication(courses),
				abstractAndQuantitativeReasoning(courses),
				educ.studiesInPhysicalMovement(courses),
			],
			core: [
				historicalOrLiteraryStudies(courses),
				multiculturalStudies(courses),
				educ.biblicalStudies(courses, matriculation),
				educ.theologicalStudies(courses),
				educ.studiesInHumanBehaviorAndSociety(courses),
			],
			integrative: [
				educ.ethicalIssuesAndNormativePerspectives(courses),
			],
		}

		let educationRequirementsResults = [
			{
				title: 'Foundation',
				type: 'array/boolean',
				result: _.all(educationRequirements.foundation, 'result'),
				details: educationRequirements.foundation,
			},
			{
				title: 'Core',
				type: 'array/boolean',
				result: _.all(educationRequirements.core, 'result'),
				details: educationRequirements.core,
			},
			{
				title: 'Integrative',
				type: 'array/boolean',
				result: _.all(educationRequirements.integrative, 'result'),
				details: educationRequirements.integrative,
			},
		]

		let bachelorOfMusicRequirements = [
			{
				title: 'Graduation',
				type: 'array/boolean',
				result: _.all(graduationRequirements, 'result'),
				details: graduationRequirements,
			},
			{
				title: 'Education',
				type: 'array/requirementSet',
				result: _.all(educationRequirementsResults, 'result'),
				details: educationRequirementsResults,
			},
		]

		// console.log('checkBachelorOfMusicDegree', 'results', results)

		return {
			result: _.all(bachelorOfMusicRequirements, 'result'),
			details: bachelorOfMusicRequirements,
		}
	})
}

export default checkBachelorOfMusicDegree
<commit_msg>Put `else`s on their own line in degrees/bm<commit_after>import * as _ from 'lodash'

import * as common from 'sto-areas/lib/commonGraduationRequirements'
import * as utilities from 'sto-areas/lib/commonGraduationUtilities'
import * as educ from 'sto-areas/lib/commonEducationRequirements'
import * as eduUtilities from 'sto-areas/lib/commonEducationUtilities'
let countGeneds = eduUtilities.countGeneds

function onlyMusicMajors(major) {
	return _.any([
		major.title === 'Performance',
		major.title === 'Church Music',
		major.title === 'Theory-Composition',
		major.title === 'Music Education',
		major.title === 'Elective Studies',
	])
}

function foreignLanguage(courses) {
	// Foreign Language [FOL] -- 0-2 courses
	// Vocal Performance: 0-2 courses in each of 2 languages; one must be French or German)
	return {
		title: 'Foreign Language',
		abbr: 'FOL',
		result: true,
	}
}

function abstractAndQuantitativeReasoning(courses) {
	// AQR or SED or IST
	let which = _.find([
		{
			title: 'Abstract and Quantitative Reasoning',
			abbr: 'AQR',
			result: countGeneds(courses, 'AQR') >= 1,
		},
		{
			title: 'Studies in Natural Science: Scientific Exploration and Discovery',
			abbr: 'SED',
			result: countGeneds(courses, 'SED') >= 1,
		},
		{
			title: 'Integrated Scientific Topics',
			abbr: 'IST',
			result: countGeneds(courses, 'IST') >= 1,
		},
	], 'result')

	let generic = {
		title: 'Abstract and Quantitative Reasoning OR Studies in Natural Science: Scientific Exploration and Discovery OR Integrated Scientific Topics',
		abbr: 'AQR/SED/IST',
		result: false,
	}

	if (which) {
		return which
	}
	else {
		return generic
	}
}

function historicalOrLiteraryStudies(courses) {
	// ALS-L or HWC - 1 course
	let which = _.find([
		{
			title: 'Historical Studies in Western Culture',
			abbr: 'HWC',
			result: countGeneds(courses, 'HWC') >= 1,
		},
		{
			title: 'Literary Studies',
			abbr: 'ALS-L',
			result: countGeneds(courses, 'ALS-L') >= 1,
		},
	], 'result')

	let generic = {
		title: 'Historical Studies in Western Culture OR Literary Studies',
		abbr: 'HWC/ALS-L',
		result: false,
	}

	if (which) {
		return which
	}
	else {
		return generic
	}
}

function multiculturalStudies(courses) {
	// MCD or MCG - 1 course
	let which = _.find([
		{
			title: 'Multicultural Studies - Domestic',
			abbr: 'MCD',
			result: countGeneds(courses, 'MCD') >= 1,
		},
		{
			title: 'Multicultural Studies - Global',
			abbr: 'MCG',
			result: countGeneds(courses, 'MCG') >= 1,
		},
	], 'result')

	let generic = {
		title: 'Multicultural Studies',
		abbr: 'MCD/MCG',
		result: false,
	}

	if (which) {
		return which
	}
	else {
		return generic
	}
}

function dedicatedMusicMajor(studies, courses) {
	// B.M. candidates must choose from the five majors offered. Please
	// consult the Music Department listing in this catalog for specific major
	// requirements. These constitute the final authority on degree
	// requirements.  Entrance to all B.M. majors is by audition and/or
	// application only. Once approved, students should declare their major
	// formally as soon as possible by submitting a completed declaration of
	// major form to the Music Department office. Subsequent changes are
	// allowed, but students are encouraged to keep their records current,
	// documenting any changes with re-submissions of the same form.

	// Other regulations are:

	// Of the credits counting toward the minimum requirements for a major, a
	// total of six (6.00) must be completed with a grade of C or higher.
	// NOTE: Ignored, because we don't store grades.

	// No courses explicitly required for a B.M Music major may be taken S/U.
	// NOTE: Ignored, because we don't store s/u status.

	// At least 50 percent of the minimum major must be taken through St.
	// Olaf. Students should consult the registrar and the department chair or
	// program director about counting toward a major courses taken at other
	// colleges. In addition to the registrar, the chair must sign the
	// student’s transfer of credit form (available from the Office of the
	// Registrar and Academic Advising) if work from other institutions is
	// accepted in advance. Likewise, courses taken through St. Olaf off-
	// campus programs must be approved by the chair or director and the off-
	// campus program advisor in advance if credit toward a major is sought.
	// (See TRANSFER OF CREDIT TO ST. OLAF )
	// NOTE: Ignored, because this doesn't know about major requirements.

	let majors = _.filter(studies, {type: 'major'})

	let musicMajors = _.filter(majors, onlyMusicMajors)

	return {
		title: 'Music Major',
		type: 'boolean',
		result: _.size(musicMajors) >= 1 && _.every(musicMajors, utilities.creditsBeyondTheArea(courses, 8))
	}
}

function checkBachelorOfMusicDegree(student) {
	return student.data().then((studentPieces) => {
		let {
			courses,
			fabrications,
			studies,
			creditsNeeded,
			graduation,
			matriculation,
		} = studentPieces

		courses = _.filter(courses, utilities.onlyQuarterCreditCoursesCanBePassFail)

		// Requirements taken from
		// http://www.stolaf.edu/catalog/1314/academiclife/bm-gen-grad-requirements.html

		let graduationRequirements = [
			common.courses(courses, creditsNeeded),
			common.residency(courses, fabrications),
			common.interim(courses, fabrications, graduation),
			common.courseLevel(courses),
			common.gpa(courses),
			common.gradedCourses(courses, fabrications),
			dedicatedMusicMajor(studies, courses),
		]

		if (utilities.isBachelorOfBoth(studies)) {
			graduationRequirements.push(common.artsAndMusicDoubleMajor(courses, studies, fabrications))
		}

		let educationRequirements = {
			foundation: [
				educ.firstYearWriting(courses, matriculation),
				educ.writingInContext(courses),
				foreignLanguage(courses),
				educ.oralCommunication(courses),
				abstractAndQuantitativeReasoning(courses),
				educ.studiesInPhysicalMovement(courses),
			],
			core: [
				historicalOrLiteraryStudies(courses),
				multiculturalStudies(courses),
				educ.biblicalStudies(courses, matriculation),
				educ.theologicalStudies(courses),
				educ.studiesInHumanBehaviorAndSociety(courses),
			],
			integrative: [
				educ.ethicalIssuesAndNormativePerspectives(courses),
			],
		}

		let educationRequirementsResults = [
			{
				title: 'Foundation',
				type: 'array/boolean',
				result: _.all(educationRequirements.foundation, 'result'),
				details: educationRequirements.foundation,
			},
			{
				title: 'Core',
				type: 'array/boolean',
				result: _.all(educationRequirements.core, 'result'),
				details: educationRequirements.core,
			},
			{
				title: 'Integrative',
				type: 'array/boolean',
				result: _.all(educationRequirements.integrative, 'result'),
				details: educationRequirements.integrative,
			},
		]

		let bachelorOfMusicRequirements = [
			{
				title: 'Graduation',
				type: 'array/boolean',
				result: _.all(graduationRequirements, 'result'),
				details: graduationRequirements,
			},
			{
				title: 'Education',
				type: 'array/requirementSet',
				result: _.all(educationRequirementsResults, 'result'),
				details: educationRequirementsResults,
			},
		]

		// console.log('checkBachelorOfMusicDegree', 'results', results)

		return {
			result: _.all(bachelorOfMusicRequirements, 'result'),
			details: bachelorOfMusicRequirements,
		}
	})
}

export default checkBachelorOfMusicDegree
<|endoftext|>


<commit_before>require('colors');

var _ = require('lodash'),
    program = require('commander'),
    async = require('async'),
    colors = require('colors'),
    version = require('../../package.json').version,

    /**
     * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result.
     *
     * @param {String} arg - The stringified number argument pulled from the CLI arguments list.
     * @returns {Number} - The supplied argument, casted to an integer.
     */
    Integer = (arg) => {
        var num = Number(arg);

        if (!_.isSafeInteger(num)) {
            throw new Error('The value must be an integer.');
        }

        return num.valueOf();
    },

    /**
     * Separates reporter specific arguments from the rest.
     *
     * @todo Figure out a better way! (Or submit a PR to argparse).
     * @param {Array} allArgs - An array of strings, each coresponding to a CLI argument.
     * @returns {Object} - An object with reporter and regular argument key-values.
     */
    separateReporterArgs = (allArgs) => {
        var reporterArgs = [],
            args = [],

            i;

        // Separate the reporter arguments from the rest
        for (i = 0; i < allArgs.length; i++) {
            if (_.startsWith(allArgs[i], '--reporter-')) {
                reporterArgs.push(allArgs[i]);

                // Also push the next parameter if it's not an option.
                allArgs[i + 1] && !_.startsWith(allArgs[i + 1], '-') && reporterArgs.push(allArgs[++i]);
            }
            else {
                args.push(allArgs[i]);
            }
        }
        return {
            reporter: reporterArgs,
            argv: args
        };
    },

    /**
     * Creates a parser capable of handling options typically given to "newman run" command.
     *
     *  Adds run command options to the common commander program instance.
     * @private
     */

    _run = () => {
        /**
             *  used for collecting global key=value variables supplied through command line
             *
             * --global-var "foo=bar" --global-var "alpha=beta"
             *
             * @param {String} val - The argument provided to `--global-var`.
             * @param {String} memo - The array that is populated by key value pairs.
             * @returns {{key, value}} - The object representation of the current CLI variable.
        */
        function collect (val, memo) {
            var arg = val,
                eqIndex = arg.indexOf('='),
                hasEq = eqIndex !== -1;
            // This is done instead of splitting by `=` to avoid chopping off `=` that could be present in the value
            arg = hasEq ? { key: arg.slice(0, eqIndex), value: arg.slice(eqIndex + 1) } :
                { key: arg, value: undefined };
            memo.push(arg);
            return memo;
        }

        program
            .command('run <collection>')
            .version(version)
            .description('URL or path to a Postman Collection.')
            .option('-e, --environment <path>', 'Specify a URL or Path to a Postman Environment.')
            .option('-g, --globals <path>', 'Specify a URL or Path to a file containing Postman Globals.')
            .option('--folder <path>', 'Run a single folder from a collection.')
            .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli')
            .option('-n, --iteration-count <n>', 'Define the number of iterations to run.', Integer)
            .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either json or csv).')
            .option('--export-environment <path>', 'Exports the environment to a file after completing the run.')
            .option('--export-globals <path>', 'Specify an output file to dump Globals before exiting.')
            .option('--export-collection <path>', 'Specify an output file to save the executed collection')
            .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', Integer)
            .option('--bail',
                'Specify whether or not to gracefully stop a collection run on encountering the first error.')
            .option('-x , --suppress-exit-code',
                'Specify whether or not to override the default exit code for the current run.')
            .option('--silent', 'Prevents newman from showing output to CLI.')
            .option('--disable-unicode',
                'Forces unicode compliant symbols to be replaced by their plain text equivalents')
            .option('--global-var <value>',
                'Allows the specification of global variables via the command line, in a key=value format', collect, [])
            // commander had some issue with flags starting with --no, thus camelCased
            // resolved https://github.com/tj/commander.js/pull/709
            .option('--no-color', 'Disable colored output.')
            .option('--color', 'Force colored output (for use in CI environments).')
            .option('--timeout-request <n>', 'Specify a timeout for requests (in milliseconds).', Integer)
            .option('--timeout-script <n>', 'Specify a timeout for script (in milliseconds).', Integer)
            .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.')
            .option('-k, --insecure', 'Disables SSL validations.')
            .option('--ssl-client-cert <path>',
                'Specify the path to the Client SSL certificate. Supports .cert and .pfx files.')
            .option('--ssl-client-key <path>',
                'Specify the path to the Client SSL key (not needed for .pfx files)')
            .option('--ssl-client-passphrase <path>',
                'Specify the Client SSL passphrase (optional, needed for passphrase protected keys).')
            .parse(process.argv);
    },

    /**
     * A CLI helper to display various commands avaialbe, in cases where no valid command matches are found.
     *
     * @returns {ArgumentParser} - An ArgumentParser instance with the commands wrapped in.
     */
    commands = () => {
        _run();
    },

    /**
     * Parses the variadic arguments for reporters.
     *
     * @param {Array} args - The array of passed CLI arguments.
     * @param {Array} reporters - A list of reporters used within the current run.
     * @returns {Object} - An object of parsed reporter options.
     */
    reporter = function (args, reporters) {
        var parsed = {
                generic: {}
            },

            name,
            path,
            arg,
            i;

        // ensure that whatever reporter is provided a blank options object object is forwarded
        _.forEach(reporters, (reporter) => { parsed[reporter] = {}; });

        for (i = 0; i < args.length; i++) {
            // Remove trailing whitespace
            arg = _.trim(args[i]);

            // Remove "--reporter-"
            arg = arg.replace('--reporter-', '');

            name = _.split(arg, '-', 1)[0]; // Reporter Name.

            // if we have a valid reporter, the path should be the <name>.camelCaseOfTheRest
            // otherwise, we add it to the generic options.
            path = _.includes(reporters, name) ?
                [name, _.camelCase(arg.replace(name + '-', ''))].join('.') :
                ['generic', _.camelCase(arg)].join('.');

            // If the next arg is an option, set the current arg to true,
            // otherwise set it to the next arg.
            _.set(parsed, path, (!args[i + 1] || _.startsWith(args[i + 1], '-')) ? true : args[++i]);
        }
        return parsed;
    },

    /**
     * Formats the options to the required format for the dispatch function.
     *
     * @param {Object} options - The options populated through CLI.
     * @returns {Object} - An object of formatted options.
     */
    formatOptions = function (options) {
        var command = options._name,
            optionsObj = { [command]: {} };

        optionsObj[command].version = options._version || false;
        optionsObj[command].noColor = !options.color || false;
        optionsObj[command].color = options.color || false;
        optionsObj[command].timeoutRequest = options.timeoutRequest || null;
        optionsObj[command].timeoutScript = options.timeoutScript || null;
        optionsObj[command].ignoreRedirects = options.ignoreRedirects || false;
        optionsObj[command].insecure = options.insecure || false;
        optionsObj[command].sslClientCert = options.sslClientCert || null;
        optionsObj[command].sslClientKey = options.sslClientKey || null;
        optionsObj[command].sslClientPassphrase = options.sslClientPassphrase || null;
        optionsObj[command].collection = options.args[1];
        optionsObj[command].environment = options.environment || null;
        optionsObj[command].globals = options.globals || null;
        optionsObj[command].folder = options.folder || null;
        optionsObj[command].reporters = options.reporters || [];
        optionsObj[command].iterationCount = options.iterationCount || null;
        optionsObj[command].iterationData = options.iterationData || null;
        optionsObj[command].exportEnvironment = options.exportEnvironment || null;
        optionsObj[command].exportGlobals = options.exportGlobals || null;
        optionsObj[command].exportCollection = options.exportCollection || null;
        optionsObj[command].delayRequest = options.delayRequest || 0;
        optionsObj[command].bail = options.bail || false;
        optionsObj[command].suppressExitCode = options.suppressExitCode || false;
        optionsObj[command].silent = options.silent || false;
        optionsObj[command].disableUnicode = options.disableUnicode || false;
        optionsObj[command].globalVar = options.globalVar || null;
        optionsObj[command].reporterOptions = options.reporterOptions || {};
        optionsObj[command].reporter = options.reporter || {};
        optionsObj.command = command;
        return optionsObj;
    },

    /**
     * Loads the raw options for Newman, without loading special options such as collection, environment etc. This
     * function does not access the network or the file-system.
     *
     * @param {Array} procArgv - An array of strings, each corresponding to a command line argument.
     * @param {String} programName - The program name displayed at the start of every newman run.
     * @param {Function} callback - The callback function whose invocation marks the end of the raw options parsing.
     * @returns {*}
     */
    rawOptions = function (procArgv, programName, callback) {
        var legacyMode = (procArgv.length && _.startsWith(procArgv[0], '-') &&
                !_.includes(['--help', '-h'], procArgv[0])),
            reporterArgs,
            rawArgs,
            result;
        commands();
        rawArgs = separateReporterArgs(procArgv);

        try {
            result = program.commands[0];
            if (!result.args.length) {
                result.outputHelp(callback);
            }
        }
        catch (error) {
            result.outputHelp(callback);
        }

        if (legacyMode && !result.silent) {
            // @todo: add a link to the migration guide just before releasing V3
            // eslint-disable-next-line max-len
            console.warn(`${colors.yellow('newman:')} the v2.x CLI options are deprecated. You should use newman run <path> [options] instead.`);
            console.warn('        refer https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md for details.');
        }

        // Handle the reporter Names
        _.isString(result.reporters) && (result.reporters = result.reporters.split(','));

        // Populate the reporter args as well.
        reporterArgs = reporter(rawArgs.reporter, result.reporters);
        result.reporterOptions = reporterArgs.generic;
        result.reporter = _.transform(_.omit(reporterArgs, 'generic'), function (acc, value, key) {
            acc[key] = _.assignIn(value, reporterArgs.generic);
        }, {});
        result = formatOptions(result);
        return callback(null, result);
    };

/**
 * Loads resources from the network, and then calls the callback.
 *
 * @param {Array} procArgv - The array of tokenised CLI argument strings.
 * @param {String} programName - The displayed program name during runs.
 * @param {Function} callback - The callback function whose invocation marks the end of the CLI parsing routine.
 * @returns {*}
 */
module.exports = function (procArgv, programName, callback) {
    async.waterfall([
        function (cb) {
            rawOptions(procArgv, programName, cb);
        },
        function (options, cb) {
            // Handle logging configurations here
            cb(null, options);
        }
    ], callback);
};

module.exports.rawOptions = rawOptions;
<commit_msg>Run moved to try block, error handling modified<commit_after>require('colors');

var _ = require('lodash'),
    program = require('commander'),
    async = require('async'),
    colors = require('colors'),
    version = require('../../package.json').version,

    /**
     * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result.
     *
     * @param {String} arg - The stringified number argument pulled from the CLI arguments list.
     * @returns {Number} - The supplied argument, casted to an integer.
     */
    Integer = (arg) => {
        var num = Number(arg);

        if (!_.isSafeInteger(num) || num <= 0) {
            throw new Error('The value must be a positive integer.');
        }

        return num.valueOf();
    },

    /**
     * Separates reporter specific arguments from the rest.
     *
     * @todo Figure out a better way! (Or submit a PR to argparse).
     * @param {Array} allArgs - An array of strings, each coresponding to a CLI argument.
     * @returns {Object} - An object with reporter and regular argument key-values.
     */
    separateReporterArgs = (allArgs) => {
        var reporterArgs = [],
            args = [],

            i;

        // Separate the reporter arguments from the rest
        for (i = 0; i < allArgs.length; i++) {
            if (_.startsWith(allArgs[i], '--reporter-')) {
                reporterArgs.push(allArgs[i]);

                // Also push the next parameter if it's not an option.
                allArgs[i + 1] && !_.startsWith(allArgs[i + 1], '-') && reporterArgs.push(allArgs[++i]);
            }
            else {
                args.push(allArgs[i]);
            }
        }
        return {
            reporter: reporterArgs,
            argv: args
        };
    },

    /**
     * Creates a parser capable of handling options typically given to "newman run" command.
     *
     *  Adds run command options to the common commander program instance.
     * @private
     */

    _run = () => {
        /**
             *  used for collecting global key=value variables supplied through command line
             *
             * --global-var "foo=bar" --global-var "alpha=beta"
             *
             * @param {String} val - The argument provided to `--global-var`.
             * @param {String} memo - The array that is populated by key value pairs.
             * @returns {{key, value}} - The object representation of the current CLI variable.
        */
        function collect (val, memo) {
            var arg = val,
                eqIndex = arg.indexOf('='),
                hasEq = eqIndex !== -1;
            // This is done instead of splitting by `=` to avoid chopping off `=` that could be present in the value
            arg = hasEq ? { key: arg.slice(0, eqIndex), value: arg.slice(eqIndex + 1) } :
                { key: arg, value: undefined };
            memo.push(arg);
            return memo;
        }

        program
            .command('run <collection>')
            .version(version)
            .description('URL or path to a Postman Collection.')
            .option('-e, --environment <path>', 'Specify a URL or Path to a Postman Environment.')
            .option('-g, --globals <path>', 'Specify a URL or Path to a file containing Postman Globals.')
            .option('--folder <path>', 'Run a single folder from a collection.')
            .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli')
            .option('-n, --iteration-count <n>', 'Define the number of iterations to run.', Integer)
            .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either json or csv).')
            .option('--export-environment <path>', 'Exports the environment to a file after completing the run.')
            .option('--export-globals <path>', 'Specify an output file to dump Globals before exiting.')
            .option('--export-collection <path>', 'Specify an output file to save the executed collection')
            .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', Integer)
            .option('--bail',
                'Specify whether or not to gracefully stop a collection run on encountering the first error.')
            .option('-x , --suppress-exit-code',
                'Specify whether or not to override the default exit code for the current run.')
            .option('--silent', 'Prevents newman from showing output to CLI.')
            .option('--disable-unicode',
                'Forces unicode compliant symbols to be replaced by their plain text equivalents')
            .option('--global-var <value>',
                'Allows the specification of global variables via the command line, in a key=value format', collect, [])
            // commander had some issue with flags starting with --no, thus camelCased
            // resolved https://github.com/tj/commander.js/pull/709
            .option('--no-color', 'Disable colored output.')
            .option('--color', 'Force colored output (for use in CI environments).')
            .option('--timeout-request <n>', 'Specify a timeout for requests (in milliseconds).', Integer)
            .option('--timeout-script <n>', 'Specify a timeout for script (in milliseconds).', Integer)
            .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.')
            .option('-k, --insecure', 'Disables SSL validations.')
            .option('--ssl-client-cert <path>',
                'Specify the path to the Client SSL certificate. Supports .cert and .pfx files.')
            .option('--ssl-client-key <path>',
                'Specify the path to the Client SSL key (not needed for .pfx files)')
            .option('--ssl-client-passphrase <path>',
                'Specify the Client SSL passphrase (optional, needed for passphrase protected keys).')
            .parse(process.argv);
    },

    /**
     * A CLI helper to display various commands avaialbe, in cases where no valid command matches are found.
     *
     * @param {Function} callback - The callback function passed to rawOptions.
     */
    commands = function (callback) {
        try {
            _run();
        }
        catch (err) {
            return callback(_.set(err, 'help', program.outputHelp()));
        }
    },

    /**
     * Parses the variadic arguments for reporters.
     *
     * @param {Array} args - The array of passed CLI arguments.
     * @param {Array} reporters - A list of reporters used within the current run.
     * @returns {Object} - An object of parsed reporter options.
     */
    reporter = function (args, reporters) {
        var parsed = {
                generic: {}
            },

            name,
            path,
            arg,
            i;

        // ensure that whatever reporter is provided a blank options object object is forwarded
        _.forEach(reporters, (reporter) => { parsed[reporter] = {}; });

        for (i = 0; i < args.length; i++) {
            // Remove trailing whitespace
            arg = _.trim(args[i]);

            // Remove "--reporter-"
            arg = arg.replace('--reporter-', '');

            name = _.split(arg, '-', 1)[0]; // Reporter Name.

            // if we have a valid reporter, the path should be the <name>.camelCaseOfTheRest
            // otherwise, we add it to the generic options.
            path = _.includes(reporters, name) ?
                [name, _.camelCase(arg.replace(name + '-', ''))].join('.') :
                ['generic', _.camelCase(arg)].join('.');

            // If the next arg is an option, set the current arg to true,
            // otherwise set it to the next arg.
            _.set(parsed, path, (!args[i + 1] || _.startsWith(args[i + 1], '-')) ? true : args[++i]);
        }
        return parsed;
    },

    /**
     * Formats the options to the required format for the dispatch function.
     *
     * @param {Object} options - The options populated through CLI.
     * @returns {Object} - An object of formatted options.
     */
    formatOptions = function (options) {
        var command = options._name,
            optionsObj = { [command]: {} };

        optionsObj.version = options._version || false;
        optionsObj[command].noColor = !options.color || false;
        optionsObj[command].color = options.color || false;
        optionsObj[command].timeoutRequest = options.timeoutRequest || null;
        optionsObj[command].timeoutScript = options.timeoutScript || null;
        optionsObj[command].ignoreRedirects = options.ignoreRedirects || false;
        optionsObj[command].insecure = options.insecure || false;
        optionsObj[command].sslClientCert = options.sslClientCert || null;
        optionsObj[command].sslClientKey = options.sslClientKey || null;
        optionsObj[command].sslClientPassphrase = options.sslClientPassphrase || null;
        optionsObj[command].collection = options.args ? options.args[1] : null;
        optionsObj[command].environment = options.environment || null;
        optionsObj[command].globals = options.globals || null;
        optionsObj[command].folder = options.folder || null;
        optionsObj[command].reporters = options.reporters || [];
        optionsObj[command].iterationCount = options.iterationCount || null;
        optionsObj[command].iterationData = options.iterationData || null;
        optionsObj[command].exportEnvironment = options.exportEnvironment || null;
        optionsObj[command].exportGlobals = options.exportGlobals || null;
        optionsObj[command].exportCollection = options.exportCollection || null;
        optionsObj[command].delayRequest = options.delayRequest || 0;
        optionsObj[command].bail = options.bail || false;
        optionsObj[command].suppressExitCode = options.suppressExitCode || false;
        optionsObj[command].silent = options.silent || false;
        optionsObj[command].disableUnicode = options.disableUnicode || false;
        optionsObj[command].globalVar = options.globalVar || null;
        optionsObj[command].reporterOptions = options.reporterOptions || {};
        optionsObj[command].reporter = options.reporter || {};
        optionsObj.command = command;
        return optionsObj;
    },

    /**
     * Loads the raw options for Newman, without loading special options such as collection, environment etc. This
     * function does not access the network or the file-system.
     *
     * @param {Array} procArgv - An array of strings, each corresponding to a command line argument.
     * @param {String} programName - The program name displayed at the start of every newman run.
     * @param {Function} callback - The callback function whose invocation marks the end of the raw options parsing.
     * @returns {*}
     */
    rawOptions = function (procArgv, programName, callback) {
        var legacyMode = (procArgv.length && _.startsWith(procArgv[0], '-') &&
                !_.includes(['--help', '-h'], procArgv[0])),
            reporterArgs,
            rawArgs,
            result;
        rawArgs = separateReporterArgs(procArgv);

        try {
            commands(callback);
            result = program.commands[0];

            if (_.isEmpty(result.args)) {
                result.outputHelp();
            }
        }
        catch (error) {
            return callback(_.set(error, 'help', result.outputHelp()));
        }

        if (legacyMode && !result.silent) {
            // @todo: add a link to the migration guide just before releasing V3
            // eslint-disable-next-line max-len
            console.warn(`${colors.yellow('newman:')} the v2.x CLI options are deprecated. You should use newman run <path> [options] instead.`);
            console.warn('        refer https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md for details.');
        }

        // Handle the reporter Names
        _.isString(result.reporters) && (result.reporters = result.reporters.split(','));

        // Populate the reporter args as well.
        reporterArgs = reporter(rawArgs.reporter, result.reporters);
        result.reporterOptions = reporterArgs.generic;
        result.reporter = _.transform(_.omit(reporterArgs, 'generic'), function (acc, value, key) {
            acc[key] = _.assignIn(value, reporterArgs.generic);
        }, {});
        result = formatOptions(result);
        return callback(null, result);
    };

/**
 * Loads resources from the network, and then calls the callback.
 *
 * @param {Array} procArgv - The array of tokenised CLI argument strings.
 * @param {String} programName - The displayed program name during runs.
 * @param {Function} callback - The callback function whose invocation marks the end of the CLI parsing routine.
 * @returns {*}
 */
module.exports = function (procArgv, programName, callback) {
    async.waterfall([
        function (cb) {
            rawOptions(procArgv, programName, cb);
        },
        function (options, cb) {
            // Handle logging configurations here
            cb(null, options);
        }
    ], callback);
};

module.exports.rawOptions = rawOptions;
<|endoftext|>


<commit_before>// https://fgnass.github.com/spin.js
(function(a,b){function M(a){F(arguments,function(c,d){a[c]===b&&(a[c]=d)});return a}function L(a){F(arguments,function(b,c){a[l][K(a,b)||b]=c});return a}function K(a,c){var e=a[l],f,g;if(e[c]!==b)return c;c=c.charAt(0).toUpperCase()+c.slice(1);for(g=0;g<C[d];g++){f=C[g]+c;if(e[f]!==b)return f}}function J(a,b){var c=[i,b,~~(a*100)].join("-"),e="{"+i+":"+a+"}",f;if(!D[c]){for(f=0;f<C[d];f++)try{I.insertRule("@"+(C[f]&&"-"+C[f].toLowerCase()+"-"||"")+"keyframes "+c+"{0%{"+i+":1}"+b+"%"+e+"to"+e+"}",I.cssRules[d])}catch(g){}D[c]=1}return c}function H(a,b,c){c&&!c[s]&&H(a,c),a.insertBefore(b,c||null);return a}function G(b){var c=a.createElement(b||"div");F(arguments,function(a,b){c[a]=b});return c}function F(a,b){var c=~~((a[d]-1)/2);for(var e=1;e<=c;e++)b(a[e*2-1],a[e*2])}var c="width",d="length",e="radius",f="lines",g="trail",h="color",i="opacity",j="speed",k="shadow",l="style",m="height",n="left",o="top",p="px",q="childNodes",r="firstChild",s="parentNode",t="position",u="relative",v="absolute",w="animation",x="transform",y="Origin",z="coord",A="#000",B=l+"Sheets",C="webkit0Moz0ms0O".split(0),D={},E;H(a.documentElement[r],G(l));var I=a[B][a[B][d]-1],N=function(a){this.el=this[f](this.opts=M(a||{},f,12,g,100,d,7,c,5,e,10,h,A,i,.25,j,1))},O=N.prototype={spin:function(a){var b=this,c=b.el;a&&H(a,L(c,n,~~(a.offsetWidth/2)+p,o,~~(a.offsetHeight/2)+p),a[r]),b.on=1;if(!E){var d=b.opts,e=0,h=20/d[j],k=(1-d[i])/(h*d[g]/100),l=h/d[f];(function m(){e++;for(var a=d[f];a;a--){var g=Math.max(1-(e+a*l)%h*k,d[i]);b[i](c,d[f]-a,g,d)}b.on&&setTimeout(m,50)})()}return b},stop:function(){var a=this,b=a.el;a.on=0,b[s]&&b[s].removeChild(b);return a}};O[f]=function(a){function s(b,g){return L(G(),t,v,c,a[d]+a[c]+p,m,a[c]+p,"background",b,"boxShadow",g,x+y,n,x,"rotate("+~~(360/a[f]*q)+"deg) translate("+a[e]+p+",0)","borderRadius","100em")}var b=L(G(),t,u),l=J(a[i],a[g]),q=0,r;for(;q<a[f];q++)r=L(G(),t,v,o,1+~(a[c]/2)+p,x,"translate3d(0,0,0)",w,l+" "+1/a[j]+"s linear infinite "+(1/a[f]/a[j]*q-1/a[j])+"s"),a[k]&&H(r,L(s(A,"0 0 4px "+A),o,2+p)),H(b,H(r,s(a[h],"0 0 1px rgba(0,0,0,.1)")));return b},O[i]=function(a,b,c){a[q][b][l][i]=c};var P="behavior",Q="url(#default#VML)",R="group0roundrect0fill0stroke".split(0);(function(){var a=L(G(R[0]),P,Q),b;if(!K(a,x)&&a.adj){for(b=0;b<R[d];b++)I.addRule(R[b],P+":"+Q);O[f]=function(){function s(d,g,k){H(l,H(L(j(),"rotation",360/a[f]*d+"deg",n,~~g),H(L(G(R[1],"arcsize",1),c,b,m,a[c],n,a[e],o,-a[c]/2,"filter",k),G(R[2],h,a[h],i,a[i]),G(R[3],i,0))))}function j(){return L(G(R[0],z+"size",g+" "+g,z+y,-b+" "+ -b),c,g,m,g)}var a=this.opts,b=a[d]+a[c],g=2*b,l=j(),q=~(a[d]+a[e]+a[c])+p,r;if(a[k])for(r=1;r<=a[f];r++)s(r,-2,"progid:DXImage"+x+".Microsoft.Blur(pixel"+e+"=2,make"+k+"=1,"+k+i+"=.3)");for(r=1;r<=a[f];r++)s(r);return H(L(G(),"margin",q+" 0 0 "+q,t,u),l)},O[i]=function(a,b,c,d){d=d[k]&&d[f]||0,a[r][q][b+d][r][r][i]=c}}else E=K(a,w)})(),window.Spinner=N})(document)<commit_msg>Updated the minified version<commit_after>// https://fgnass.github.com/spin.js
(function(a,b){function M(a){F(arguments,function(c,d){a[c]===b&&(a[c]=d)});return a}function L(a){F(arguments,function(b,c){a[l][K(a,b)||b]=c});return a}function K(a,c){var e=a[l],f,g;if(e[c]!==b)return c;c=c.charAt(0).toUpperCase()+c.slice(1);for(g=0;g<C[d];g++){f=C[g]+c;if(e[f]!==b)return f}}function J(a,b){var c=[i,b,~~(a*100)].join("-"),e="{"+i+":"+a+"}",f;if(!D[c]){for(f=0;f<C[d];f++)try{I.insertRule("@"+(C[f]&&"-"+C[f].toLowerCase()+"-"||"")+"keyframes "+c+"{0%{"+i+":1}"+b+"%"+e+"to"+e+"}",I.cssRules[d])}catch(g){}D[c]=1}return c}function H(a,b,c){c&&!c[s]&&H(a,c),a.insertBefore(b,c||null);return a}function G(b){var c=a.createElement(b||"div");F(arguments,function(a,b){c[a]=b});return c}function F(a,b){var c=~~((a[d]-1)/2);for(var e=1;e<=c;e++)b(a[e*2-1],a[e*2])}var c="width",d="length",e="radius",f="lines",g="trail",h="color",i="opacity",j="speed",k="shadow",l="style",m="height",n="left",o="top",p="px",q="childNodes",r="firstChild",s="parentNode",t="position",u="relative",v="absolute",w="animation",x="transform",y="Origin",z="coord",A="#000",B=l+"Sheets",C="webkit0Moz0ms0O".split(0),D={},E;H(a.getElementsByTagName("head")[0],G(l));var I=a[B][a[B][d]-1],N=function(a){this.el=this[f](this.opts=M(a||{},f,12,g,100,d,7,c,5,e,10,h,A,i,.25,j,1))},O=N.prototype={spin:function(a){var b=this,c=b.el;a&&H(a,L(c,n,~~(a.offsetWidth/2)+p,o,~~(a.offsetHeight/2)+p),a[r]),b.on=1;if(!E){var d=b.opts,e=0,h=20/d[j],k=(1-d[i])/(h*d[g]/100),l=h/d[f];(function m(){e++;for(var a=d[f];a;a--){var g=Math.max(1-(e+a*l)%h*k,d[i]);b[i](c,d[f]-a,g,d)}b.on&&setTimeout(m,50)})()}return b},stop:function(){var a=this,b=a.el;a.on=0,b[s]&&b[s].removeChild(b);return a}};O[f]=function(a){function s(b,g){return L(G(),t,v,c,a[d]+a[c]+p,m,a[c]+p,"background",b,"boxShadow",g,x+y,n,x,"rotate("+~~(360/a[f]*q)+"deg) translate("+a[e]+p+",0)","borderRadius","100em")}var b=L(G(),t,u),l=J(a[i],a[g]),q=0,r;for(;q<a[f];q++)r=L(G(),t,v,o,1+~(a[c]/2)+p,x,"translate3d(0,0,0)",w,l+" "+1/a[j]+"s linear infinite "+(1/a[f]/a[j]*q-1/a[j])+"s"),a[k]&&H(r,L(s(A,"0 0 4px "+A),o,2+p)),H(b,H(r,s(a[h],"0 0 1px rgba(0,0,0,.1)")));return b},O[i]=function(a,b,c){a[q][b][l][i]=c};var P="behavior",Q="url(#default#VML)",R="group0roundrect0fill0stroke".split(0);(function(){var a=L(G(R[0]),P,Q),b;if(!K(a,x)&&a.adj){for(b=0;b<R[d];b++)I.addRule(R[b],P+":"+Q);O[f]=function(){function s(d,g,k){H(l,H(L(j(),"rotation",360/a[f]*d+"deg",n,~~g),H(L(G(R[1],"arcsize",1),c,b,m,a[c],n,a[e],o,-a[c]/2,"filter",k),G(R[2],h,a[h],i,a[i]),G(R[3],i,0))))}function j(){return L(G(R[0],z+"size",g+" "+g,z+y,-b+" "+ -b),c,g,m,g)}var a=this.opts,b=a[d]+a[c],g=2*b,l=j(),q=~(a[d]+a[e]+a[c])+p,r;if(a[k])for(r=1;r<=a[f];r++)s(r,-2,"progid:DXImage"+x+".Microsoft.Blur(pixel"+e+"=2,make"+k+"=1,"+k+i+"=.3)");for(r=1;r<=a[f];r++)s(r);return H(L(G(),"margin",q+" 0 0 "+q,t,u),l)},O[i]=function(a,b,c,d){d=d[k]&&d[f]||0,a[r][q][b+d][r][r][i]=c}}else E=K(a,w)})(),window.Spinner=N})(document)<|endoftext|>


<commit_before>var assert = require('assert');
var exec = require('child_process').exec;
var configUtils = require('./utils/config');
var testUtils = require('./utils/test');

describe('An retina array of image positions, dimensions, and names', function () {
  testUtils.setInfo(configUtils.retinaMultipleSprites);

  describe('processed by `spritesheet-templates` into retina SCSS', function () {
    testUtils.runTemplater({format: 'scss_retina'});
    testUtils.assertOutputMatches(__dirname + '/expected_files/scss_retina.scss');

    testUtils.generateCssFile('\n' + [
      '@include retina-sprites($retina-groups);'
    ].join('\n'));

    describe('processed by `sass --scss` (ruby) into CSS', function () {
      // Process the SCSS
      testUtils.processCss(function processScss (cb) {
        exec('sass --scss ' + this.tmp.path, function (err, css, stderr) {
          // Assert no errors during conversion
          assert.strictEqual(stderr, '');
          assert.notEqual(css, '');
          // DEV: Repair vendor specific validation issues
          css = css.replace(/\(-webkit-min-device-pixel-ratio: 2\), /g, '');
          cb(err, css);
        });
      });

      // Assert agains the generated CSS
      testUtils.assertValidCss();
    });

    describe('processed by `sassc` (libsass) into CSS', function () {
      // Process the SCSS
      testUtils.processCss(function processScss (cb) {
        exec('sassc ' + this.tmp.path, function (err, css, stderr) {
          assert.strictEqual(stderr, '');
          assert.notEqual(css, '');
          css = css.replace(/\(-webkit-min-device-pixel-ratio: 2\), /g, '');
          cb(err, css);
        });
      });
      testUtils.assertValidCss();
    });
  });
});
<commit_msg>Moving to isolate diff<commit_after>var assert = require('assert');
var exec = require('child_process').exec;
var configUtils = require('./utils/config');
var testUtils = require('./utils/test');

describe('An retina array of image positions, dimensions, and names', function () {
  testUtils.setInfo(configUtils.retinaMultipleSprites);

  describe.only('processed by `spritesheet-templates` into retina SCSS', function () {
    testUtils.runTemplater({format: 'scss_retina'});
    testUtils.assertOutputMatches(__dirname + '/expected_files/scss_retina.scss');

    testUtils.generateCssFile('\n' + [
      '@include retina-sprites($retina-groups);'
    ].join('\n'));

    describe.skip('processed by `sass --scss` (ruby) into CSS', function () {
      // Process the SCSS
      testUtils.processCss(function processScss (cb) {
        exec('sass --scss ' + this.tmp.path, function (err, css, stderr) {
          // Assert no errors during conversion
          assert.strictEqual(stderr, '');
          assert.notEqual(css, '');
          // DEV: Repair vendor specific validation issues
          css = css.replace(/\(-webkit-min-device-pixel-ratio: 2\), /g, '');
          cb(err, css);
        });
      });

      // Assert agains the generated CSS
      testUtils.assertValidCss();
    });

    describe.skip('processed by `sassc` (libsass) into CSS', function () {
      // Process the SCSS
      testUtils.processCss(function processScss (cb) {
        exec('sassc ' + this.tmp.path, function (err, css, stderr) {
          assert.strictEqual(stderr, '');
          assert.notEqual(css, '');
          css = css.replace(/\(-webkit-min-device-pixel-ratio: 2\), /g, '');
          cb(err, css);
        });
      });
      testUtils.assertValidCss();
    });
  });
});
<|endoftext|>


<commit_before>require('colors');

var _ = require('lodash'),
    program = require('commander'),
    async = require('async'),
    colors = require('colors'),
    version = require('../../package.json').version,

    /**
     * Separates reporter specific arguments from the rest.
     *
     * @todo Figure out a better way! (Or submit a PR to argparse).
     * @param {Array} allArgs - An array of strings, each coresponding to a CLI argument.
     * @returns {Object} - An object with reporter and regular argument key-values.
     */
    separateReporterArgs = (allArgs) => {
        var reporterArgs = [],
            args = [],

            i;

        // Separate the reporter arguments from the rest
        for (i = 0; i < allArgs.length; i++) {
            if (_.startsWith(allArgs[i], '--reporter-')) {
                reporterArgs.push(allArgs[i]);

                // Also push the next parameter if it's not an option.
                allArgs[i + 1] && !_.startsWith(allArgs[i + 1], '-') && reporterArgs.push(allArgs[++i]);
            }
            else {
                args.push(allArgs[i]);
            }
        }
        return {
            reporter: reporterArgs,
            argv: args
        };
    },

    /**
     * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result.
     *
     * @param {String} arg - The stringified number argument pulled from the CLI arguments list.
     * @returns {Number} - The supplied argument, casted to an integer.
     */
    Integer = (arg) => {
        var num = Number(arg);

        if (!_.isSafeInteger(num)) {
            throw new Error('The value must be an integer.');
        }

        return num.valueOf();
    },

    /**
     * Creates a parser capable of handling options typically given to "newman run" command.
     *
     *  Adds run command options to the common commander program instance.
     * @private
     */

    _run = () => {
        /**
             *  used for collecting global key=value variables supplied through command line
             *
             * --global-var "foo=bar" --global-var "alpha=beta"
             *
             * @param {String} val - The argument provided to `--global-var`.
             * @param {String} memo - The argument provided to `--global-var`.
             * @returns {{key = value}} - The object representation of the current CLI variable.
        */
        function collect (val, memo) {
            memo.push(val);
            return memo;
        }

        program
            .command('run <collection>')
            .version(version)
            .description('URL or path to a Postman Collection.')
            .option('-e, --environment <path>', 'Specify a URL or Path to a Postman Environment.')
            .option('-g, --globals <path>', 'Specify a URL or Path to a file containing Postman Globals.')
            .option('--folder <path>', 'Run a single folder from a collection.')
            .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli')
            .option('-n, --iteration-count <n>', 'Define the number of iterations to run.', parseInt)
            .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either json or csv).')
            .option('--export-environment <path>', 'Exports the environment to a file after completing the run.')
            .option('--export-globals <path>', 'Specify an output file to dump Globals before exiting.')
            .option('--export-collection', 'Specify an output file to save the executed collection')
            .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', parseInt, 0)
            .option('--bail', 'Specify whether or not to gracefully stop a collection run on encountering the first error', false)
            .option('-x , --suppress-exit-code', 'Specify whether or not to override the default exit code for the current run', false)
            .option('--silent', 'Prevents newman from showing output to CLI', false)
            .option('--disable-unicode', 'Forces unicode compliant symbols to be replaced by their plain text equivalents')
            .option('--global-var [value]', 'Allows the specification of global variables via the command line, in a key=value format', collect, [])
            // commander had some issue with flags starting with --no, thus camelCased
            // resolved https://github.com/tj/commander.js/pull/709
            .option('--no-color', 'Disable colored output.')
            .option('--color', 'Force colored output (for use in CI environments).')
            .option('--timeout-request <n>', 'Specify a timeout for requests (in milliseconds).', parseInt)
            .option('--timeout-script <n>', 'Specify a timeout for script (in milliseconds).', parseInt)
            .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.')
            .option('-k, --insecure', 'Disables SSL validations.')
            .option('--ssl-client-cert <path>', 'Specify the path to the Client SSL certificate. Supports .cert and .pfx files.')
            .option('--ssl-client-key <path>', 'Specify the path to the Client SSL key (not needed for .pfx files)')
            .option('--ssl-client-passphrase <path>', 'Specify the Client SSL passphrase (optional, needed for passphrase protected keys).')
            .parse(process.argv);
    },

    /**
     * A CLI helper to display various commands avaialbe, in cases where no valid command matches are found.
     *
     * @returns {ArgumentParser} - An ArgumentParser instance with the commands wrapped in.
     */
    commands = () => {
        _run();
    },

    /**
     * Parses the variadic arguments for reporters.
     *
     * @param {Array} args - The array of passed CLI arguments.
     * @param {Array} reporters - A list of reporters used within the current run.
     * @returns {Object} - An object of parsed reporter options.
     */
    reporter = function (args, reporters) {
        var parsed = {
                generic: {}
            },

            name,
            path,
            arg,
            i;

        // ensure that whatever reporter is provided a blank options object object is forwarded
        _.forEach(reporters, (reporter) => { parsed[reporter] = {}; });

        for (i = 0; i < args.length; i++) {
            // Remove trailing whitespace
            arg = _.trim(args[i]);

            // Remove "--reporter-"
            arg = arg.replace('--reporter-', '');

            name = _.split(arg, '-', 1)[0]; // Reporter Name.

            // if we have a valid reporter, the path should be the <name>.camelCaseOfTheRest
            // otherwise, we add it to the generic options.
            path = _.includes(reporters, name) ?
                [name, _.camelCase(arg.replace(name + '-', ''))].join('.') :
                ['generic', _.camelCase(arg)].join('.');

            // If the next arg is an option, set the current arg to true,
            // otherwise set it to the next arg.
            _.set(parsed, path, (!args[i + 1] || _.startsWith(args[i + 1], '-')) ? true : args[++i]);
        }
        return parsed;
    },

    /**
     * Loads the raw options for Newman, without loading special options such as collection, environment etc. This
     * function does not access the network or the file-system.
     *
     * @param {Array} procArgv - An array of strings, each corresponding to a command line argument.
     * @param {String} programName - The program name displayed at the start of every newman run.
     * @param {Function} callback - The callback function whose invocation marks the end of the raw options parsing.
     * @returns {*}
     */
    rawOptions = function (procArgv, programName, callback) {
        var legacyMode = (procArgv.length && _.startsWith(procArgv[0], '-') &&
                !_.includes(['--help', '-h'], procArgv[0])),
            reporterArgs,
            rawArgs,
            result;
        commands();
        rawArgs = separateReporterArgs(procArgv);

        try {
            result = program.commands[0];
            if (!result.args.length) {
                result.outputHelp(callback);
            }
        }
        catch (error) {
            result.outputHelp(callback);
        }

        if (legacyMode && !result.silent) {
            // @todo: add a link to the migration guide just before releasing V3
            // eslint-disable-next-line max-len
            console.warn(`${colors.yellow('newman:')} the v2.x CLI options are deprecated. You should use newman run <path> [options] instead.`);
            console.warn('        refer https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md for details.');
        }

        // Handle the reporter Names
        _.isString(result.reporters) && (result.reporters = result.reporters.split(','));

        // Populate the reporter args as well.
        reporterArgs = reporter(rawArgs.reporter, result.reporters);
        result.reporterOptions = reporterArgs.generic;
        result.reporter = _.transform(_.omit(reporterArgs, 'generic'), function (acc, value, key) {
            acc[key] = _.assignIn(value, reporterArgs.generic);
        }, {});

        return callback(null, result);
    };

/**
 * Loads resources from the network, and then calls the callback.
 *
 * @param {Array} procArgv - The array of tokenised CLI argument strings.
 * @param {String} programName - The displayed program name during runs.
 * @param {Function} callback - The callback function whose invocation marks the end of the CLI parsing routine.
 * @returns {*}
 */
module.exports = function (procArgv, programName, callback) {
    async.waterfall([
        function (cb) {
            rawOptions(procArgv, programName, cb);
        },
        function (options, cb) {
            // Handle logging configurations here
            cb(null, options);
        }
    ], callback);
};

module.exports.rawOptions = rawOptions;
<commit_msg>Global var collect functionality fixed<commit_after>require('colors');

var _ = require('lodash'),
    program = require('commander'),
    async = require('async'),
    colors = require('colors'),
    version = require('../../package.json').version,

    /**
     * Separates reporter specific arguments from the rest.
     *
     * @todo Figure out a better way! (Or submit a PR to argparse).
     * @param {Array} allArgs - An array of strings, each coresponding to a CLI argument.
     * @returns {Object} - An object with reporter and regular argument key-values.
     */
    separateReporterArgs = (allArgs) => {
        var reporterArgs = [],
            args = [],

            i;

        // Separate the reporter arguments from the rest
        for (i = 0; i < allArgs.length; i++) {
            if (_.startsWith(allArgs[i], '--reporter-')) {
                reporterArgs.push(allArgs[i]);

                // Also push the next parameter if it's not an option.
                allArgs[i + 1] && !_.startsWith(allArgs[i + 1], '-') && reporterArgs.push(allArgs[++i]);
            }
            else {
                args.push(allArgs[i]);
            }
        }
        return {
            reporter: reporterArgs,
            argv: args
        };
    },

    /**
     * A CLI parser helper to process stringified numbers into integers, perform safety checks, and return the result.
     *
     * @param {String} arg - The stringified number argument pulled from the CLI arguments list.
     * @returns {Number} - The supplied argument, casted to an integer.
     */
    Integer = (arg) => {
        var num = Number(arg);

        if (!_.isSafeInteger(num)) {
            throw new Error('The value must be an integer.');
        }

        return num.valueOf();
    },

    /**
     * Creates a parser capable of handling options typically given to "newman run" command.
     *
     *  Adds run command options to the common commander program instance.
     * @private
     */

    _run = () => {
        /**
             *  used for collecting global key=value variables supplied through command line
             *
             * --global-var "foo=bar" --global-var "alpha=beta"
             *
             * @param {String} val - The argument provided to `--global-var`.
             * @param {String} memo - The array that is populated by key value pairs.
             * @returns {{key, value}} - The object representation of the current CLI variable.
        */
        function collect (val, memo) {
            var arg = val,
                eqIndex = arg.indexOf('='),
                hasEq = eqIndex !== -1;
            // This is done instead of splitting by `=` to avoid chopping off `=` that could be present in the value
            arg = hasEq ? { key: arg.slice(0, eqIndex), value: arg.slice(eqIndex + 1) } :
                { key: arg, value: undefined };
            memo.push(arg);
            return memo;
        }

        program
            .command('run <collection>')
            .version(version)
            .description('URL or path to a Postman Collection.')
            .option('-e, --environment <path>', 'Specify a URL or Path to a Postman Environment.')
            .option('-g, --globals <path>', 'Specify a URL or Path to a file containing Postman Globals.')
            .option('--folder <path>', 'Run a single folder from a collection.')
            .option('-r, --reporters [reporters]', 'Specify the reporters to use for this run.', 'cli')
            .option('-n, --iteration-count <n>', 'Define the number of iterations to run.', parseInt)
            .option('-d, --iteration-data <path>', 'Specify a data file to use for iterations (either json or csv).')
            .option('--export-environment <path>', 'Exports the environment to a file after completing the run.')
            .option('--export-globals <path>', 'Specify an output file to dump Globals before exiting.')
            .option('--export-collection', 'Specify an output file to save the executed collection')
            .option('--delay-request [n]', 'Specify the extent of delay between requests (milliseconds)', parseInt, 0)
            .option('--bail', 'Specify whether or not to gracefully stop a collection run on encountering the first error', false)
            .option('-x , --suppress-exit-code', 'Specify whether or not to override the default exit code for the current run', false)
            .option('--silent', 'Prevents newman from showing output to CLI', false)
            .option('--disable-unicode', 'Forces unicode compliant symbols to be replaced by their plain text equivalents')
            .option('--global-var [value]', 'Allows the specification of global variables via the command line, in a key=value format', collect, [])
            // commander had some issue with flags starting with --no, thus camelCased
            // resolved https://github.com/tj/commander.js/pull/709
            .option('--no-color', 'Disable colored output.')
            .option('--color', 'Force colored output (for use in CI environments).')
            .option('--timeout-request <n>', 'Specify a timeout for requests (in milliseconds).', parseInt)
            .option('--timeout-script <n>', 'Specify a timeout for script (in milliseconds).', parseInt)
            .option('--ignore-redirects', 'If present, Newman will not follow HTTP Redirects.')
            .option('-k, --insecure', 'Disables SSL validations.')
            .option('--ssl-client-cert <path>', 'Specify the path to the Client SSL certificate. Supports .cert and .pfx files.')
            .option('--ssl-client-key <path>', 'Specify the path to the Client SSL key (not needed for .pfx files)')
            .option('--ssl-client-passphrase <path>', 'Specify the Client SSL passphrase (optional, needed for passphrase protected keys).')
            .parse(process.argv);
    },

    /**
     * A CLI helper to display various commands avaialbe, in cases where no valid command matches are found.
     *
     * @returns {ArgumentParser} - An ArgumentParser instance with the commands wrapped in.
     */
    commands = () => {
        _run();
    },

    /**
     * Parses the variadic arguments for reporters.
     *
     * @param {Array} args - The array of passed CLI arguments.
     * @param {Array} reporters - A list of reporters used within the current run.
     * @returns {Object} - An object of parsed reporter options.
     */
    reporter = function (args, reporters) {
        var parsed = {
                generic: {}
            },

            name,
            path,
            arg,
            i;

        // ensure that whatever reporter is provided a blank options object object is forwarded
        _.forEach(reporters, (reporter) => { parsed[reporter] = {}; });

        for (i = 0; i < args.length; i++) {
            // Remove trailing whitespace
            arg = _.trim(args[i]);

            // Remove "--reporter-"
            arg = arg.replace('--reporter-', '');

            name = _.split(arg, '-', 1)[0]; // Reporter Name.

            // if we have a valid reporter, the path should be the <name>.camelCaseOfTheRest
            // otherwise, we add it to the generic options.
            path = _.includes(reporters, name) ?
                [name, _.camelCase(arg.replace(name + '-', ''))].join('.') :
                ['generic', _.camelCase(arg)].join('.');

            // If the next arg is an option, set the current arg to true,
            // otherwise set it to the next arg.
            _.set(parsed, path, (!args[i + 1] || _.startsWith(args[i + 1], '-')) ? true : args[++i]);
        }
        return parsed;
    },

    /**
     * Loads the raw options for Newman, without loading special options such as collection, environment etc. This
     * function does not access the network or the file-system.
     *
     * @param {Array} procArgv - An array of strings, each corresponding to a command line argument.
     * @param {String} programName - The program name displayed at the start of every newman run.
     * @param {Function} callback - The callback function whose invocation marks the end of the raw options parsing.
     * @returns {*}
     */
    rawOptions = function (procArgv, programName, callback) {
        var legacyMode = (procArgv.length && _.startsWith(procArgv[0], '-') &&
                !_.includes(['--help', '-h'], procArgv[0])),
            reporterArgs,
            rawArgs,
            result;
        commands();
        rawArgs = separateReporterArgs(procArgv);

        try {
            result = program.commands[0];
            if (!result.args.length) {
                result.outputHelp(callback);
            }
        }
        catch (error) {
            result.outputHelp(callback);
        }

        if (legacyMode && !result.silent) {
            // @todo: add a link to the migration guide just before releasing V3
            // eslint-disable-next-line max-len
            console.warn(`${colors.yellow('newman:')} the v2.x CLI options are deprecated. You should use newman run <path> [options] instead.`);
            console.warn('        refer https://github.com/postmanlabs/newman/blob/develop/MIGRATION.md for details.');
        }

        // Handle the reporter Names
        _.isString(result.reporters) && (result.reporters = result.reporters.split(','));

        // Populate the reporter args as well.
        reporterArgs = reporter(rawArgs.reporter, result.reporters);
        result.reporterOptions = reporterArgs.generic;
        result.reporter = _.transform(_.omit(reporterArgs, 'generic'), function (acc, value, key) {
            acc[key] = _.assignIn(value, reporterArgs.generic);
        }, {});

        return callback(null, result);
    };

/**
 * Loads resources from the network, and then calls the callback.
 *
 * @param {Array} procArgv - The array of tokenised CLI argument strings.
 * @param {String} programName - The displayed program name during runs.
 * @param {Function} callback - The callback function whose invocation marks the end of the CLI parsing routine.
 * @returns {*}
 */
module.exports = function (procArgv, programName, callback) {
    async.waterfall([
        function (cb) {
            rawOptions(procArgv, programName, cb);
        },
        function (options, cb) {
            // Handle logging configurations here
            cb(null, options);
        }
    ], callback);
};

module.exports.rawOptions = rawOptions;
<|endoftext|>


<commit_before>var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../src/server/app');
var knex = require('../db/knex');

var should = chai.should();

chai.use(chaiHttp);

//GET ALL PROFILES
describe('Get all top level User Profiles', function() {

    it('should get top level User Profiles', function(done) {
        chai.request(server)
        .get('/api/shows')
        .end(function(err, res) {
            res.should.have.status(200);
            res.should.be.json;
            res.body.should.be.a('array');
            res.body.length.should.equal(4);
            res.body[0].should.have.property('first_name');
            res.body[0].first_name.should.be.a('string');
            res.body[0].first_name.should.equal('Dan');

            res.body[0].should.have.property('last_name');
            res.body[0].last_name.should.be.a('string');
            res.body[0].last_name.should.equal('Klein');

            res.body[0].should.have.property('phone');
            res.body[0].phone.should.be.a('string');
            res.body[0].phone.should.equal('888-888-8888');

            res.body[0].should.have.property('email');
            res.body[0].email.should.be.a('string');
            res.body[0].email.should.equal('dan@dan.com');

            res.body[0].should.have.property('password');
            res.body[0].password.should.be.a('string');
            res.body[0].password.should.equal('Bacon');

            res.body[0].channel.should.equal('USA Network');
            res.body[0].should.have.property('genre');
            res.body[0].genre.should.equal('Drama');
            res.body[0].should.have.property('rating');
            res.body[0].rating.should.equal(3);
            res.body[0].should.have.property('explicit');
            res.body[0].explicit.should.equal(false);
            done();
        });
    });

});<commit_msg>Finished first TDD Created Base Profile Get All Test<commit_after>var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../src/server/app');
var knex = require('../db/knex');

var should = chai.should();

chai.use(chaiHttp);

//GET ALL PROFILES
describe('Get all top level User Profiles', function() {

    it('should get top level User Profiles', function(done) {
        chai.request(server)
        .get('/api/shows')
        .end(function(err, res) {
            res.should.have.status(200);
            res.should.be.json;
            res.body.should.be.a('array');
            res.body.length.should.equal(4);
            res.body[0].should.have.property('f_name');
            res.body[0].f_name.should.be.a('string');
            res.body[0].f_name.should.equal('Dan');

            res.body[0].should.have.property('l_name');
            res.body[0].l_name.should.be.a('string');
            res.body[0].l_name.should.equal('Klein');

            res.body[0].should.have.property('phone');
            res.body[0].phone.should.be.a('string');
            res.body[0].phone.should.equal('888-888-8888');

            res.body[0].should.have.property('email');
            res.body[0].email.should.be.a('string');
            res.body[0].email.should.equal('dan@dan.com');

            res.body[0].should.have.property('password');
            res.body[0].password.should.be.a('string');
            res.body[0].password.should.equal('Bacon');

            res.body[0].should.have.property('google_id');
            res.body[0].google_id.should.be.a('string');

            res.body[0].should.have.property('english');
            res.body[0].english.should.be.a('integer');
            res.body[0].english.should.equal('1');

            res.body[0].should.have.property('admin');
            //might be special case for this, check docs
            res.body[0].admin.should.be.a('boolean');
            res.body[0].admin.should.equal(true);

            res.body[0].should.have.property('create_date');
            //might be special case for this, check docs
            res.body[0].create_date.should.be.a('date');
            res.body[0].create_date.should.equal('NO CLUE');

            res.body[0].should.have.property('update_date');
            //might be special case for this, check docs
            res.body[0].update_date.should.be.a('date');
            res.body[0].update_date.should.equal('NO CLUE');
            res.body[0].should.have.property('case_worker_id');
            res.body[0].case_worker_id.should.be.a('integer');
            rse.body[0].case_worker_id.should.equal('null')

            done();
        });
    });

});<|endoftext|>


<commit_before>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(FILL_ME_IN);
    expect(this.swedishChef.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual(FILL_ME_IN);
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
  this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual(FILL_ME_IN);
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(FILL_ME_IN);
    expect(this.gonzo.hobby).toEqual(FILL_ME_IN);
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual(FILL_ME_IN);
  });
});
<commit_msg>up to 47<commit_after>function Muppet(age, hobby) {
  this.age = age;
  this.hobby = hobby;

  this.answerNanny = function(){
	return "Everything's cool!";
  }
}

function SwedishChef(age, hobby, mood) {
  Muppet.call(this, age, hobby);
  this.mood = mood;

  this.cook = function() {
    return "Mmmm soup!";
  }
}

SwedishChef.prototype = new Muppet();

describe("About inheritance", function() {
  beforeEach(function(){
    this.muppet = new Muppet(2, "coding");
	this.swedishChef = new SwedishChef(2, "cooking", "chillin");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.swedishChef.cook()).toEqual('Mmmm soup!');
  });

  it("should be able to call a method on the base object", function() {
    expect(this.swedishChef.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.swedishChef.age).toEqual(2);
    expect(this.swedishChef.hobby).toEqual("cooking");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.swedishChef.mood).toEqual('chillin');
  });
});

// http://javascript.crockford.com/prototypal.html
Object.prototype.beget = function () {
  function F() {}
  F.prototype = this;
  return new F();
}

function Gonzo(age, hobby, trick) {
  Muppet.call(this, age, hobby);
  this.trick = trick;

  this.doTrick = function() {
    return this.trick;
  }
}

//no longer need to call the Muppet (base type) constructor
Gonzo.prototype = Muppet.prototype.beget();

describe("About Crockford's inheritance improvement", function() {
  beforeEach(function(){
  this.gonzo = new Gonzo(3, "daredevil performer", "eat a tire");
  });

  it("should be able to call a method on the derived object", function() {
    expect(this.gonzo.doTrick()).toEqual("eat a tire");
  });

  it("should be able to call a method on the base object", function() {
    expect(this.gonzo.answerNanny()).toEqual("Everything's cool!");
  });

  it("should set constructor parameters on the base object", function() {
    expect(this.gonzo.age).toEqual(3);
    expect(this.gonzo.hobby).toEqual("daredevil performer");
  });

  it("should set constructor parameters on the derived object", function() {
    expect(this.gonzo.trick).toEqual("eat a tire");
  });
});
<|endoftext|>


<commit_before>/**
 * This class provides access to device accelerometer data.
 * @constructor
 */
var utils = require("cordova/utils"),
    exec = require("cordova/exec"),
    Acceleration = require('cordova/plugin/Acceleration');

// Is the accel sensor running?
var running = false;

// Keeps reference to watchAcceleration calls.
var timers = {};

// Array of listeners; used to keep track of when we should call start and stop.
var listeners = [];

// Last returned acceleration object from native
var accel = null;

// Tells native to start.
function start() {
    exec(function(a) {
        var tempListeners = listeners.slice(0);
        accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
        for (var i = 0, l = tempListeners.length; i < l; i++) {
            tempListeners[i].win(accel);
        }
    }, function(e) {
        var tempListeners = listeners.slice(0);
        for (var i = 0, l = tempListeners.length; i < l; i++) {
            tempListeners[i].fail(e);
        }
    }, "Accelerometer", "start", []);
    running = true;
}

// Tells native to stop.
function stop() {
    exec(null, null, "Accelerometer", "stop", []);
    running = false;
}

// Adds a callback pair to the listeners array
function createCallbackPair(win, fail) {
    return {win:win, fail:fail};
}

// Removes a win/fail listener pair from the listeners array
function removeListeners(l) {
    var idx = listeners.indexOf(l);
    if (idx > -1) {
        listeners.splice(idx, 1);
        if (listeners.length === 0) {
            stop();
        }
    }
}

var accelerometer = {
    /**
     * Asynchronously aquires the current acceleration.
     *
     * @param {Function} successCallback    The function to call when the acceleration data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
     * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
     */
    getCurrentAcceleration: function(successCallback, errorCallback, options) {
        // successCallback required
        if (typeof successCallback !== "function") {
            throw "getCurrentAcceleration must be called with at least a success callback function as first parameter.";
        }

        var p;
        var win = function(a) {
            removeListeners(p);
            successCallback(a);
        };
        var fail = function(e) {
            removeListeners(p);
            errorCallback(e);
        };

        p = createCallbackPair(win, fail);
        listeners.push(p);

        if (!running) {
            start();
        }
    },

    /**
     * Asynchronously aquires the acceleration repeatedly at a given interval.
     *
     * @param {Function} successCallback    The function to call each time the acceleration data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
     * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
     * @return String                       The watch id that must be passed to #clearWatch to stop watching.
     */
    watchAcceleration: function(successCallback, errorCallback, options) {
        // Default interval (10 sec)
        var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000;

        // successCallback required
        if (typeof successCallback !== "function") {
            throw "watchAcceleration must be called with at least a success callback function as first parameter.";
        }

        // Keep reference to watch id, and report accel readings as often as defined in frequency
        var id = utils.createUUID();

        var p = createCallbackPair(function(){}, function(e) {
            removeListeners(p);
            errorCallback(e);
        });
        listeners.push(p);

        timers[id] = {
            timer:window.setInterval(function() {
                if (accel) {
                    successCallback(accel);
                }
            }, frequency),
            listeners:p
        };

        if (running) {
            // If we're already running then immediately invoke the success callback
            // but only if we have retreived a value, sample code does not check for null ...
            if(accel) {
                successCallback(accel);
            }
        } else {
            start();
        }

        return id;
    },

    /**
     * Clears the specified accelerometer watch.
     *
     * @param {String} id       The id of the watch returned from #watchAcceleration.
     */
    clearWatch: function(id) {
        // Stop javascript timer & remove from timer list
        if (id && timers[id]) {
            window.clearInterval(timers[id].timer);
            removeListeners(timers[id].listeners);
            delete timers[id];
        }
    }
};

module.exports = accelerometer;
<commit_msg>Spelling: retrieve<commit_after>/**
 * This class provides access to device accelerometer data.
 * @constructor
 */
var utils = require("cordova/utils"),
    exec = require("cordova/exec"),
    Acceleration = require('cordova/plugin/Acceleration');

// Is the accel sensor running?
var running = false;

// Keeps reference to watchAcceleration calls.
var timers = {};

// Array of listeners; used to keep track of when we should call start and stop.
var listeners = [];

// Last returned acceleration object from native
var accel = null;

// Tells native to start.
function start() {
    exec(function(a) {
        var tempListeners = listeners.slice(0);
        accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
        for (var i = 0, l = tempListeners.length; i < l; i++) {
            tempListeners[i].win(accel);
        }
    }, function(e) {
        var tempListeners = listeners.slice(0);
        for (var i = 0, l = tempListeners.length; i < l; i++) {
            tempListeners[i].fail(e);
        }
    }, "Accelerometer", "start", []);
    running = true;
}

// Tells native to stop.
function stop() {
    exec(null, null, "Accelerometer", "stop", []);
    running = false;
}

// Adds a callback pair to the listeners array
function createCallbackPair(win, fail) {
    return {win:win, fail:fail};
}

// Removes a win/fail listener pair from the listeners array
function removeListeners(l) {
    var idx = listeners.indexOf(l);
    if (idx > -1) {
        listeners.splice(idx, 1);
        if (listeners.length === 0) {
            stop();
        }
    }
}

var accelerometer = {
    /**
     * Asynchronously aquires the current acceleration.
     *
     * @param {Function} successCallback    The function to call when the acceleration data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
     * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
     */
    getCurrentAcceleration: function(successCallback, errorCallback, options) {
        // successCallback required
        if (typeof successCallback !== "function") {
            throw "getCurrentAcceleration must be called with at least a success callback function as first parameter.";
        }

        var p;
        var win = function(a) {
            removeListeners(p);
            successCallback(a);
        };
        var fail = function(e) {
            removeListeners(p);
            errorCallback(e);
        };

        p = createCallbackPair(win, fail);
        listeners.push(p);

        if (!running) {
            start();
        }
    },

    /**
     * Asynchronously aquires the acceleration repeatedly at a given interval.
     *
     * @param {Function} successCallback    The function to call each time the acceleration data is available
     * @param {Function} errorCallback      The function to call when there is an error getting the acceleration data. (OPTIONAL)
     * @param {AccelerationOptions} options The options for getting the accelerometer data such as timeout. (OPTIONAL)
     * @return String                       The watch id that must be passed to #clearWatch to stop watching.
     */
    watchAcceleration: function(successCallback, errorCallback, options) {
        // Default interval (10 sec)
        var frequency = (options && options.frequency && typeof options.frequency == 'number') ? options.frequency : 10000;

        // successCallback required
        if (typeof successCallback !== "function") {
            throw "watchAcceleration must be called with at least a success callback function as first parameter.";
        }

        // Keep reference to watch id, and report accel readings as often as defined in frequency
        var id = utils.createUUID();

        var p = createCallbackPair(function(){}, function(e) {
            removeListeners(p);
            errorCallback(e);
        });
        listeners.push(p);

        timers[id] = {
            timer:window.setInterval(function() {
                if (accel) {
                    successCallback(accel);
                }
            }, frequency),
            listeners:p
        };

        if (running) {
            // If we're already running then immediately invoke the success callback
            // but only if we have retrieved a value, sample code does not check for null ...
            if(accel) {
                successCallback(accel);
            }
        } else {
            start();
        }

        return id;
    },

    /**
     * Clears the specified accelerometer watch.
     *
     * @param {String} id       The id of the watch returned from #watchAcceleration.
     */
    clearWatch: function(id) {
        // Stop javascript timer & remove from timer list
        if (id && timers[id]) {
            window.clearInterval(timers[id].timer);
            removeListeners(timers[id].listeners);
            delete timers[id];
        }
    }
};

module.exports = accelerometer;
<|endoftext|>