<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint devel: true*/
/* global module, test, asyncTest, ok, _playground, expect, start, equal */

define(function () {
    "use strict";

    module("low-level");

    /**
     * Validates that the returned result-value is a success code
     *
     * @private
     * @param {Error=} err
     */
    var _validateNotifierResult = function (err) {
        // Acceptable success codes are: undefined, or an object with a
        // number property that has the value 0
        var testPasses = (err === undefined);
        if (!testPasses) {
            testPasses = (err.number !== undefined && err.number === 0);
        }

        ok(testPasses, "result is success");

        if (!testPasses) {
            console.log("validateNotifierResult failed for err:");
            console.log(err);
        }
    };

    /**
     * Validates that the returned result-value is an error object containing
     * number and message properties. Other properties are possible too.
     *
     * @private
     * @param {Error=} err
     * @param {number=} expectedError
     */
    var _validateNotifierResultError = function (err, expectedError) {

        var testPasses = false;
        do {
            if (err === undefined) {
                break;
            }
            // FIXME: restore this check once we always return Error objects
            // if (!(err instanceof Error)) {
            //     break;
            // }
            if (err.number === undefined) {
                break;
            }
            if (err.message === undefined) {
                break;
            }

            testPasses = true;
        } while (false);

        if (!testPasses) {
            console.log("Invalid form of an error resultValue:");
            console.log(err);
        } else {
            // test the returned error code
            // REVISIT: Replace the hard coded number with an enumeration
            // when that becomes available
            testPasses = (err.number === expectedError);

            if (!testPasses) {
                console.log("resultValue did not have the expected error code:" +
                    expectedError + " Actual error is: " + err.number);
            }
        }
        ok(testPasses, "error resultValue validation");
    };

    test("_playground object exists", function () {
        expect(1);
        ok(!!_playground, "_playground object exists");
    });

    test("_playground.ps property exists", function () {
        expect(1);
        ok(!!_playground.ps, "_playground.ps property exists");
    });

    test("_playground.ps.descriptor property exists", function () {
        expect(1);
        ok(!!_playground.ps.descriptor, "_playground.ps.descriptor property exists");
    });

    test("_playground.ps.ui property exists", function () {
        expect(1);
        ok(!!_playground.ps.ui, "_playground.ps.ui property exists");
    });

    test("_playground._debug property exists", function () {
        expect(1);
        ok(!!_playground._debug, "_playground.debug property exists");
    });

    // Basic test for obtaining a value with no arguments
    asyncTest("_playground.ps.ui.getScaleFactor property", function () {
        expect(2);

        _playground.ps.ui.getScaleFactor(function (err, scaleFactor) {
            _validateNotifierResult(err);

            var scaleFactorValidation = (scaleFactor === 1 || scaleFactor === 2);
            ok(scaleFactorValidation, "scale factor validation");

            if (!scaleFactorValidation) {
                console.log("scale factor not the expected value. returned value is: " + scaleFactor);
            }

            start();
        });
    });

    // Negative test: Invoke a host method without providing a notifier
    test("_playground.ps.ui.getScaleFactor property (negative)", function () {
        expect(1);

        var result;
        try {
            _playground.ps.ui.getScaleFactor("some value");
        } catch (err) {
            result = err;
        }

        ok(result !== undefined, "missing notifier exception");
    });

    // Negative test. Invoke a host method with an incorrect number/typs of arguments
    asyncTest("_playground._debug.forcePlayArgumentFailure", function () {
        expect(1);

        _playground._debug.forcePlayArgumentFailure(function (err) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);

            start();
        });
    });

    // _playground.ps.ui.setPointerPropagationMode
    test("_playground.ps.ui.setPointerPropagationMode property exists", function () {
        expect(1);
        ok(!!_playground.ps.ui.setPointerPropagationMode,
            "_playground.ps.ui.setPointerPropagationMode property exists");
    });

    // _playground.ps.ui.getPointerPropagationMode
    test("_playground.ps.ui.getPointerPropagationMode property exists", function () {
        expect(1);
        ok(!!_playground.ps.ui.getPointerPropagationMode,
            "_playground.ps.ui.getPointerPropagationMode property exists");
    });

    asyncTest("_playground.ps.ui.getPointerPropagationMode property", function () {
        expect(2);

        _playground.ps.ui.getPointerPropagationMode(function (err, mode) {
            _validateNotifierResult(err);

            var modeValidation = (mode === _playground.ps.ui.pointerPropagationMode.ALPHA_PROPAGATE ||
                mode === _playground.ps.ui.pointerPropagationMode.NEVER_PROPAGATE ||
                mode === _playground.ps.ui.pointerPropagationMode.ALWAYS_PROPAGATE);

            ok(modeValidation, "mode factor validation");
            if (!modeValidation) {
                console.log("mode not the expected value. returned value is: " + mode);
            }

            start();
        });
    });

    asyncTest("_playground.ps.ui.setPointerPropagationMode property", function () {
        expect(1);

        var options = {
            defaultMode: _playground.ps.ui.pointerPropagationMode.ALPHA_PROPAGATE
        };

        _playground.ps.ui.setPointerPropagationMode(options, function (err) {
            _validateNotifierResult(err);

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.get: success", function () {
        expect(5);

        var reference = {
            ref: [
                {
                    ref: "property",
                    property: "hostName"
                },
                {
                    ref: "application",
                    enum: "ordinal",
                    value: "targetEnum"
                }
            ]
        };

        _playground.ps.descriptor.get(reference, function (err, descriptor) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(typeof descriptor, "object", "Result is a descriptor");
            ok(descriptor.hasOwnProperty("hostName"), "Descriptor has the hostName property");
            equal(descriptor.hostName.indexOf("Adobe Photoshop"), 0, "hostName property starts with 'Adobe Photoshop'");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.get: semantic failure", function () {
        expect(2);

        var reference = {
            "ref": "xxx-ref-does-not-exist-xxx",
            "enum": "$Ordn",
            "value": "$Trgt"
        };

        _playground.ps.descriptor.get(reference, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.UNKNOWN_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.get: argument failure", function () {
        expect(2);

        _playground.ps.descriptor.get("xxx-ref-does-not-exist-xxx", function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: success", function () {
        expect(4);

        _playground.ps.descriptor.play("jsonAction", {}, {}, function (err, descriptor) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(typeof descriptor, "object", "Result is a descriptor");
            equal(Object.keys(descriptor), 0, "Result object is empty");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: undefined argument failure", function () {
        expect(2);

        _playground.ps.descriptor.play("jsonAction", undefined, undefined, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: non-JSON-stringifyable argument failure", function () {
        expect(2);

        _playground.ps.descriptor.play("jsonAction", { ref: NaN }, {}, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: semantic failure", function () {
        expect(2);

        _playground.ps.descriptor.play("xxx-ref-does-not-exist-xxx", {}, {}, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.UNKNOWN_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay: success", function () {
        expect(13);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        _playground.ps.descriptor.batchPlay(commands, {}, {}, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 3, "Received three possible results");
            equal(errors.length, 3, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            equal(typeof descriptors[1], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[1]), 0, "Result object is empty");
            ok(!errors[1], "Error is falsy");

            equal(typeof descriptors[2], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[2]), 0, "Result object is empty");
            ok(!errors[1], "Error is falsy");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay: partial semantic failure", function () {
        expect(9);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "xxx-no-such-descriptor-xxx",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        _playground.ps.descriptor.batchPlay(commands, {}, {}, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 2, "Received three possible results");
            equal(errors.length, 2, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            ok(!descriptors[1], "Result is falsy");
            _validateNotifierResultError(errors[1], _playground.errorCodes.UNKNOWN_ERROR);

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay: partial argument failure", function () {
        expect(9);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                "xxx-bad-property-name-xxx": "jsonAction",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        _playground.ps.descriptor.batchPlay(commands, {}, {}, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 2, "Received three possible results");
            equal(errors.length, 2, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            ok(!descriptors[1], "Result is falsy");
            _validateNotifierResultError(errors[1], _playground.errorCodes.ARGUMENT_ERROR);

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay with continueOnError: partial semantic failure", function () {
        expect(12);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "xxx-no-such-descriptor-xxx",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        var batchOptions = {
            continueOnError: true
        };

        _playground.ps.descriptor.batchPlay(commands, {}, batchOptions, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 3, "Received three possible results");
            equal(errors.length, 3, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            ok(!descriptors[1], "Result is falsy");
            _validateNotifierResultError(errors[1], _playground.errorCodes.UNKNOWN_ERROR);

            equal(typeof descriptors[2], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[2]), 0, "Result object is empty");
            ok(!errors[2], "Error is falsy");

            start();
        });
    });

});
<commit_msg>Correctly verify argument errors and conversion errors<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint devel: true*/
/* global module, test, asyncTest, ok, _playground, expect, start, equal */

define(function () {
    "use strict";

    module("low-level");

    /**
     * Validates that the returned result-value is a success code
     *
     * @private
     * @param {Error=} err
     */
    var _validateNotifierResult = function (err) {
        // Acceptable success codes are: undefined, or an object with a
        // number property that has the value 0
        var testPasses = (err === undefined);
        if (!testPasses) {
            testPasses = (err.number !== undefined && err.number === 0);
        }

        ok(testPasses, "result is success");

        if (!testPasses) {
            console.log("validateNotifierResult failed for err:");
            console.log(err);
        }
    };

    /**
     * Validates that the returned result-value is an error object containing
     * number and message properties. Other properties are possible too.
     *
     * @private
     * @param {Error=} err
     * @param {number=} expectedError
     */
    var _validateNotifierResultError = function (err, expectedError) {

        var testPasses = false;
        do {
            if (err === undefined) {
                break;
            }
            // FIXME: restore this check once we always return Error objects
            // if (!(err instanceof Error)) {
            //     break;
            // }
            if (err.number === undefined) {
                break;
            }
            if (err.message === undefined) {
                break;
            }

            testPasses = true;
        } while (false);

        if (!testPasses) {
            console.log("Invalid form of an error resultValue:");
            console.log(err);
        } else {
            // test the returned error code
            // REVISIT: Replace the hard coded number with an enumeration
            // when that becomes available
            testPasses = (err.number === expectedError);

            if (!testPasses) {
                console.log("resultValue did not have the expected error code:" +
                    expectedError + " Actual error is: " + err.number);
            }
        }
        ok(testPasses, "error resultValue validation");
    };

    test("_playground object exists", function () {
        expect(1);
        ok(!!_playground, "_playground object exists");
    });

    test("_playground.ps property exists", function () {
        expect(1);
        ok(!!_playground.ps, "_playground.ps property exists");
    });

    test("_playground.ps.descriptor property exists", function () {
        expect(1);
        ok(!!_playground.ps.descriptor, "_playground.ps.descriptor property exists");
    });

    test("_playground.ps.ui property exists", function () {
        expect(1);
        ok(!!_playground.ps.ui, "_playground.ps.ui property exists");
    });

    test("_playground._debug property exists", function () {
        expect(1);
        ok(!!_playground._debug, "_playground.debug property exists");
    });

    // Basic test for obtaining a value with no arguments
    asyncTest("_playground.ps.ui.getScaleFactor property", function () {
        expect(2);

        _playground.ps.ui.getScaleFactor(function (err, scaleFactor) {
            _validateNotifierResult(err);

            var scaleFactorValidation = (scaleFactor === 1 || scaleFactor === 2);
            ok(scaleFactorValidation, "scale factor validation");

            if (!scaleFactorValidation) {
                console.log("scale factor not the expected value. returned value is: " + scaleFactor);
            }

            start();
        });
    });

    // Negative test: Invoke a host method without providing a notifier
    test("_playground.ps.ui.getScaleFactor property (negative)", function () {
        expect(1);

        var result;
        try {
            _playground.ps.ui.getScaleFactor("some value");
        } catch (err) {
            result = err;
        }

        ok(result !== undefined, "missing notifier exception");
    });

    // Negative test. Invoke a host method with an incorrect number/typs of arguments
    asyncTest("_playground._debug.forcePlayArgumentFailure", function () {
        expect(1);

        _playground._debug.forcePlayArgumentFailure(function (err) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);

            start();
        });
    });

    // _playground.ps.ui.setPointerPropagationMode
    test("_playground.ps.ui.setPointerPropagationMode property exists", function () {
        expect(1);
        ok(!!_playground.ps.ui.setPointerPropagationMode,
            "_playground.ps.ui.setPointerPropagationMode property exists");
    });

    // _playground.ps.ui.getPointerPropagationMode
    test("_playground.ps.ui.getPointerPropagationMode property exists", function () {
        expect(1);
        ok(!!_playground.ps.ui.getPointerPropagationMode,
            "_playground.ps.ui.getPointerPropagationMode property exists");
    });

    asyncTest("_playground.ps.ui.getPointerPropagationMode property", function () {
        expect(2);

        _playground.ps.ui.getPointerPropagationMode(function (err, mode) {
            _validateNotifierResult(err);

            var modeValidation = (mode === _playground.ps.ui.pointerPropagationMode.ALPHA_PROPAGATE ||
                mode === _playground.ps.ui.pointerPropagationMode.NEVER_PROPAGATE ||
                mode === _playground.ps.ui.pointerPropagationMode.ALWAYS_PROPAGATE);

            ok(modeValidation, "mode factor validation");
            if (!modeValidation) {
                console.log("mode not the expected value. returned value is: " + mode);
            }

            start();
        });
    });

    asyncTest("_playground.ps.ui.setPointerPropagationMode property", function () {
        expect(1);

        var options = {
            defaultMode: _playground.ps.ui.pointerPropagationMode.ALPHA_PROPAGATE
        };

        _playground.ps.ui.setPointerPropagationMode(options, function (err) {
            _validateNotifierResult(err);

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.get: success", function () {
        expect(5);

        var reference = {
            ref: [
                {
                    ref: "property",
                    property: "hostName"
                },
                {
                    ref: "application",
                    enum: "ordinal",
                    value: "targetEnum"
                }
            ]
        };

        _playground.ps.descriptor.get(reference, function (err, descriptor) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(typeof descriptor, "object", "Result is a descriptor");
            ok(descriptor.hasOwnProperty("hostName"), "Descriptor has the hostName property");
            equal(descriptor.hostName.indexOf("Adobe Photoshop"), 0, "hostName property starts with 'Adobe Photoshop'");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.get: semantic failure", function () {
        expect(2);

        var reference = {
            "ref": "xxx-ref-does-not-exist-xxx",
            "enum": "$Ordn",
            "value": "$Trgt"
        };

        _playground.ps.descriptor.get(reference, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.UNKNOWN_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.get: argument failure", function () {
        expect(2);

        _playground.ps.descriptor.get("xxx-ref-does-not-exist-xxx", function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: success", function () {
        expect(4);

        _playground.ps.descriptor.play("jsonAction", {}, {}, function (err, descriptor) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(typeof descriptor, "object", "Result is a descriptor");
            equal(Object.keys(descriptor), 0, "Result object is empty");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: argument failure", function () {
        expect(2);

        _playground.ps.descriptor.play("jsonAction", 123, {}, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.ARGUMENT_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: argument conversion failure", function () {
        expect(2);

        _playground.ps.descriptor.play("jsonAction", { ref: NaN }, {}, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.CONVERSION_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.play: semantic failure", function () {
        expect(2);

        _playground.ps.descriptor.play("xxx-ref-does-not-exist-xxx", {}, {}, function (err, descriptor) {
            _validateNotifierResultError(err, _playground.errorCodes.UNKNOWN_ERROR);
            ok(!descriptor, "Call failed");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay: success", function () {
        expect(13);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        _playground.ps.descriptor.batchPlay(commands, {}, {}, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 3, "Received three possible results");
            equal(errors.length, 3, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            equal(typeof descriptors[1], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[1]), 0, "Result object is empty");
            ok(!errors[1], "Error is falsy");

            equal(typeof descriptors[2], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[2]), 0, "Result object is empty");
            ok(!errors[1], "Error is falsy");

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay: partial semantic failure", function () {
        expect(9);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "xxx-no-such-descriptor-xxx",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        _playground.ps.descriptor.batchPlay(commands, {}, {}, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 2, "Received three possible results");
            equal(errors.length, 2, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            ok(!descriptors[1], "Result is falsy");
            _validateNotifierResultError(errors[1], _playground.errorCodes.UNKNOWN_ERROR);

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay: partial argument failure", function () {
        expect(9);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                "xxx-bad-property-name-xxx": "jsonAction",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        _playground.ps.descriptor.batchPlay(commands, {}, {}, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 2, "Received three possible results");
            equal(errors.length, 2, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            ok(!descriptors[1], "Result is falsy");
            _validateNotifierResultError(errors[1], _playground.errorCodes.ARGUMENT_ERROR);

            start();
        });
    });

    asyncTest("_playground.ps.descriptor.batchPlay with continueOnError: partial semantic failure", function () {
        expect(12);

        var commands = [
            {
                name: "jsonAction",
                descriptor: {}
            },
            {
                name: "xxx-no-such-descriptor-xxx",
                descriptor: {}
            },
            {
                name: "jsonAction",
                descriptor: {}
            }
        ];

        var batchOptions = {
            continueOnError: true
        };

        _playground.ps.descriptor.batchPlay(commands, {}, batchOptions, function (err, descriptors, errors) {
            _validateNotifierResult(err);
            ok(!err, "Call succeeded");

            equal(descriptors.length, 3, "Received three possible results");
            equal(errors.length, 3, "Received three possible errors");

            equal(typeof descriptors[0], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[0]), 0, "Result object is empty");
            ok(!errors[0], "Error is falsy");

            ok(!descriptors[1], "Result is falsy");
            _validateNotifierResultError(errors[1], _playground.errorCodes.UNKNOWN_ERROR);

            equal(typeof descriptors[2], "object", "Result is a descriptor");
            equal(Object.keys(descriptors[2]), 0, "Result object is empty");
            ok(!errors[2], "Error is falsy");

            start();
        });
    });

});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var request = require('request');
var _ = require('underscore');
var parseArgs = require('minimist');

var args = parseArgs(process.argv.slice(2));
console.dir(args);

var minPrice = args.minPrice || 0;
var maxPrice = args.maxPrice || 9999;
var numBedrooms = args.bedrooms || 2;
var numBathrooms = args.bathrooms || 2;

request('http://api.avalonbay.com/json/reply/ApartmentSearch?communityCode=CA067&min=' + minPrice + '&max=' + maxPrice + '&_=1443137667833', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var aptData = JSON.parse(body);
    var availableApts = aptData.results.availableFloorPlanTypes;
    var twoBrApts = _.where(availableApts, { floorPlanTypeCode: (numBedrooms + "BD") })[0].availableFloorPlans;
    var twoBrTwoBaApts = _.where(twoBrApts, { floorPlanBathType: (numBathrooms + " baths") });
    var cheapTwoBrTwoBaApts = _.filter(twoBrTwoBaApts, function (e) {
        var pricing = e.finishPackages[0].apartments[0].pricing;
        return Math.min(pricing.amenitizedRent, pricing.effectiveRent) < 4900;
    });
    console.log(JSON.stringify(cheapTwoBrTwoBaApts));
  }
});<commit_msg>Fixed bugs, added undef and empty checks<commit_after>#!/usr/bin/env node

// Init node modules
var request = require('request');
var _ = require('underscore');
var parseArgs = require('minimist');

// Collect and parse the CLI arguments
var args = parseArgs(process.argv.slice(2));
var minRent = args.minRent || 0;
var maxRent = args.maxRent || 9999;
var numBedrooms = args.bedrooms || 2;
var numBathrooms = args.bathrooms || 2;

// Make the request to the Avalon API
request('http://api.avalonbay.com/json/reply/ApartmentSearch?communityCode=CA067&min=' + minRent + '&max=' + maxRent + '&_=1443137667833', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    // Parse the JSON output
    var aptData = JSON.parse(body);

    // Filter down based on parameters
    var availableApts = aptData.results.availableFloorPlanTypes;

    if (!_.isUndefined(availableApts)) {
        var bedroomFilter = _.where(availableApts, { floorPlanTypeCode: (numBedrooms + "BD") });

        if (!_.isUndefined(bedroomFilter) && !_.isEmpty(bedroomFilter)) {
            bedroomFilter = bedroomFilter[0].availableFloorPlans;

            if (!_.isUndefined(bedroomFilter)) {
                var bedBathFilter = _.where(bedroomFilter, { floorPlanBathType: (numBathrooms + " baths") });

                if (!_.isEmpty(bedBathFilter)) {
                    console.log(JSON.stringify(bedBathFilter));
                } else {
                    console.log("None available");
                }
            }
        }
    }
  }
});<|endoftext|>


<commit_before>/**
 * Created by fsuda on 18.09.2018.
 */
import { details, emptyDraft } from "../detail-definitions.js";
import { findLatestIntervallEndInJsonLdOrNowAndAddMillis } from "../../app/won-utils.js";
import won from "../../app/won-es6.js";
import { getIn } from "../../app/utils.js";
import {
  filterInVicinity,
  concatenateFilters,
  sparqlQuery,
} from "../../app/sparql-builder-utils.js";

export const personalTransportSearch = {
  identifier: "liftDemand",
  label: "Need a Lift",
  icon: "#ico36_uc_route_demand",
  doNotMatchAfter: findLatestIntervallEndInJsonLdOrNowAndAddMillis,
  draft: {
    ...emptyDraft,
    content: {
      title: "Need a lift",
      tags: "search-lift",
      searchString: "offer-lift",
    },
  },
  // TODO: amount of people? other details?
  details: {
    title: { ...details.title },
    description: { ...details.description },
  },
  seeksDetails: {
    fromDatetime: { ...details.fromDatetime },
    travelAction: { ...details.travelAction },
  },
  generateQuery: (draft, resultName) => {
    const fromLocation = getIn(draft, [
      "seeks",
      "travelAction",
      "fromLocation",
    ]);
    const toLocation = getIn(draft, ["seeks", "travelAction", "toLocation"]);

    const baseFilter = {
      prefixes: {
        won: won.defaultContext["won"],
        s: won.defaultContext["s"],
      },
      operations: [
        `${resultName} a won:Need.`,
        `${resultName} won:isInState won:Active. { { ${resultName} a <http://dbpedia.org/resource/Ridesharing>.  } union { ${resultName} a s:TaxiService} }`,
      ],
    };

    const locationFilter = filterInVicinity(
      "?location",
      fromLocation,
      /*radius=*/ 100
    );
    const fromLocationFilter = filterInVicinity(
      "?fromLocation",
      fromLocation,
      /*radius=*/ 5
    );
    const toLocationFilter = filterInVicinity(
      "?toLocation",
      toLocation,
      /*radius=*/ 5
    );

    const union = operations => {
      if (!operations || operations.length === 0) {
        return "";
      } else {
        return "{" + operations.join("} UNION {") + "}";
      }
    };
    const filterAndJoin = (arrayOfStrings, seperator) =>
      arrayOfStrings.filter(str => str).join(seperator);

    const locationFilters = {
      prefixes: locationFilter.prefixes,
      operations: union([
        filterAndJoin(
          [
            fromLocation &&
              `${resultName} a <http://dbpedia.org/resource/Ridesharing>. ${resultName} won:travelAction/s:fromLocation ?fromLocation. `,
            fromLocation && fromLocationFilter.operations.join(" "),
            toLocation &&
              `${resultName} won:travelAction/s:toLocation ?toLocation.`,
            toLocation && toLocationFilter.operations.join(" "),
          ],
          " "
        ),
        filterAndJoin(
          [
            location &&
              `${resultName} a s:TaxiService . ${resultName} won:hasLocation ?location .`,
            location && locationFilter.operations.join(" "),
          ],
          " "
        ),
      ]),
    };

    const concatenatedFilter = concatenateFilters([
      baseFilter,
      locationFilters,
    ]);

    return sparqlQuery({
      prefixes: concatenatedFilter.prefixes,
      distinct: true,
      variables: [resultName],
      where: concatenatedFilter.operations,
      orderBy: [
        {
          order: "ASC",
          variable: "?location_geoDistance",
        },
      ],
    });
  },
};
<commit_msg>Fix ridesharing demand usecase<commit_after>/**
 * Created by fsuda on 18.09.2018.
 */
import { details, emptyDraft } from "../detail-definitions.js";
import { findLatestIntervallEndInJsonLdOrNowAndAddMillis } from "../../app/won-utils.js";
import won from "../../app/won-es6.js";
import { getIn } from "../../app/utils.js";
import {
  filterInVicinity,
  concatenateFilters,
  sparqlQuery,
} from "../../app/sparql-builder-utils.js";

export const personalTransportSearch = {
  identifier: "personalTransportSearch",
  label: "Need a Lift",
  icon: "#ico36_uc_route_demand",
  doNotMatchAfter: findLatestIntervallEndInJsonLdOrNowAndAddMillis,
  draft: {
    ...emptyDraft,
    content: {
      title: "Need a lift",
      type: "won:PersonalTransportSearch",
    },
  },
  // TODO: amount of people? other details?
  details: {
    title: { ...details.title },
    description: { ...details.description },
  },
  seeksDetails: {
    fromDatetime: { ...details.fromDatetime },
    travelAction: { ...details.travelAction },
  },
  generateQuery: (draft, resultName) => {
    const fromLocation = getIn(draft, [
      "seeks",
      "travelAction",
      "fromLocation",
    ]);
    const toLocation = getIn(draft, ["seeks", "travelAction", "toLocation"]);

    const baseFilter = {
      prefixes: {
        won: won.defaultContext["won"],
        s: won.defaultContext["s"],
      },
      operations: [
        `${resultName} a won:Need.`,
        `${resultName} won:isInState won:Active. { { ${resultName} a <http://dbpedia.org/resource/Ridesharing>.  } union { ${resultName} a s:TaxiService} }`,
      ],
    };

    const locationFilter = filterInVicinity(
      "?location",
      fromLocation,
      /*radius=*/ 100
    );
    const fromLocationFilter = filterInVicinity(
      "?fromLocation",
      fromLocation,
      /*radius=*/ 5
    );
    const toLocationFilter = filterInVicinity(
      "?toLocation",
      toLocation,
      /*radius=*/ 5
    );

    const union = operations => {
      if (!operations || operations.length === 0) {
        return "";
      } else {
        return "{" + operations.join("} UNION {") + "}";
      }
    };
    const filterAndJoin = (arrayOfStrings, seperator) =>
      arrayOfStrings.filter(str => str).join(seperator);

    const locationFilters = {
      prefixes: locationFilter.prefixes,
      operations: union([
        filterAndJoin(
          [
            fromLocation &&
              `${resultName} a <http://dbpedia.org/resource/Ridesharing>. ${resultName} won:travelAction/s:fromLocation ?fromLocation. `,
            fromLocation && fromLocationFilter.operations.join(" "),
            toLocation &&
              `${resultName} won:travelAction/s:toLocation ?toLocation.`,
            toLocation && toLocationFilter.operations.join(" "),
          ],
          " "
        ),
        filterAndJoin(
          [
            location &&
              `${resultName} a s:TaxiService . ${resultName} won:hasLocation ?location .`,
            location && locationFilter.operations.join(" "),
          ],
          " "
        ),
      ]),
    };

    const concatenatedFilter = concatenateFilters([
      baseFilter,
      locationFilters,
    ]);

    return sparqlQuery({
      prefixes: concatenatedFilter.prefixes,
      distinct: true,
      variables: [resultName],
      where: concatenatedFilter.operations,
    });
  },
};
<|endoftext|>


<commit_before>export var REVISION = '85';
export var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
export var CullFaceNone = 0;
export var CullFaceBack = 1;
export var CullFaceFront = 2;
export var CullFaceFrontBack = 3;
export var FrontFaceDirectionCW = 0;
export var FrontFaceDirectionCCW = 1;
export var BasicShadowMap = 0;
export var PCFShadowMap = 1;
export var PCFSoftShadowMap = 2;
export var FrontSide = 0;
export var BackSide = 1;
export var DoubleSide = 2;
export var FlatShading = 1;
export var SmoothShading = 2;
export var NoColors = 0;
export var FaceColors = 1;
export var VertexColors = 2;
export var NoBlending = 0;
export var NormalBlending = 1;
export var AdditiveBlending = 2;
export var SubtractiveBlending = 3;
export var MultiplyBlending = 4;
export var CustomBlending = 5;
export var AddEquation = 100;
export var SubtractEquation = 101;
export var ReverseSubtractEquation = 102;
export var MinEquation = 103;
export var MaxEquation = 104;
export var ZeroFactor = 200;
export var OneFactor = 201;
export var SrcColorFactor = 202;
export var OneMinusSrcColorFactor = 203;
export var SrcAlphaFactor = 204;
export var OneMinusSrcAlphaFactor = 205;
export var DstAlphaFactor = 206;
export var OneMinusDstAlphaFactor = 207;
export var DstColorFactor = 208;
export var OneMinusDstColorFactor = 209;
export var SrcAlphaSaturateFactor = 210;
export var NeverDepth = 0;
export var AlwaysDepth = 1;
export var LessDepth = 2;
export var LessEqualDepth = 3;
export var EqualDepth = 4;
export var GreaterEqualDepth = 5;
export var GreaterDepth = 6;
export var NotEqualDepth = 7;
export var MultiplyOperation = 0;
export var MixOperation = 1;
export var AddOperation = 2;
export var NoToneMapping = 0;
export var LinearToneMapping = 1;
export var ReinhardToneMapping = 2;
export var Uncharted2ToneMapping = 3;
export var CineonToneMapping = 4;
export var UVMapping = 300;
export var CubeReflectionMapping = 301;
export var CubeRefractionMapping = 302;
export var EquirectangularReflectionMapping = 303;
export var EquirectangularRefractionMapping = 304;
export var SphericalReflectionMapping = 305;
export var CubeUVReflectionMapping = 306;
export var CubeUVRefractionMapping = 307;
export var RepeatWrapping = 1000;
export var ClampToEdgeWrapping = 1001;
export var MirroredRepeatWrapping = 1002;
export var NearestFilter = 1003;
export var NearestMipMapNearestFilter = 1004;
export var NearestMipMapLinearFilter = 1005;
export var LinearFilter = 1006;
export var LinearMipMapNearestFilter = 1007;
export var LinearMipMapLinearFilter = 1008;
export var UnsignedByteType = 1009;
export var ByteType = 1010;
export var ShortType = 1011;
export var UnsignedShortType = 1012;
export var IntType = 1013;
export var UnsignedIntType = 1014;
export var FloatType = 1015;
export var HalfFloatType = 1016;
export var UnsignedShort4444Type = 1017;
export var UnsignedShort5551Type = 1018;
export var UnsignedShort565Type = 1019;
export var UnsignedInt248Type = 1020;
export var AlphaFormat = 1021;
export var RGBFormat = 1022;
export var RGBAFormat = 1023;
export var LuminanceFormat = 1024;
export var LuminanceAlphaFormat = 1025;
export var RGBEFormat = RGBAFormat;
export var DepthFormat = 1026;
export var DepthStencilFormat = 1027;
export var RGB_S3TC_DXT1_Format = 2001;
export var RGBA_S3TC_DXT1_Format = 2002;
export var RGBA_S3TC_DXT3_Format = 2003;
export var RGBA_S3TC_DXT5_Format = 2004;
export var RGB_PVRTC_4BPPV1_Format = 2100;
export var RGB_PVRTC_2BPPV1_Format = 2101;
export var RGBA_PVRTC_4BPPV1_Format = 2102;
export var RGBA_PVRTC_2BPPV1_Format = 2103;
export var RGB_ETC1_Format = 2151;
export var LoopOnce = 2200;
export var LoopRepeat = 2201;
export var LoopPingPong = 2202;
export var InterpolateDiscrete = 2300;
export var InterpolateLinear = 2301;
export var InterpolateSmooth = 2302;
export var ZeroCurvatureEnding = 2400;
export var ZeroSlopeEnding = 2401;
export var WrapAroundEnding = 2402;
export var TrianglesDrawMode = 0;
export var TriangleStripDrawMode = 1;
export var TriangleFanDrawMode = 2;
export var LinearEncoding = 3000;
export var sRGBEncoding = 3001;
export var GammaEncoding = 3007;
export var RGBEEncoding = 3002;
export var LogLuvEncoding = 3003;
export var RGBM7Encoding = 3004;
export var RGBM16Encoding = 3005;
export var RGBDEncoding = 3006;
export var BasicDepthPacking = 3200;
export var RGBADepthPacking = 3201;
<commit_msg>r86dev<commit_after>export var REVISION = '86dev';
export var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
export var CullFaceNone = 0;
export var CullFaceBack = 1;
export var CullFaceFront = 2;
export var CullFaceFrontBack = 3;
export var FrontFaceDirectionCW = 0;
export var FrontFaceDirectionCCW = 1;
export var BasicShadowMap = 0;
export var PCFShadowMap = 1;
export var PCFSoftShadowMap = 2;
export var FrontSide = 0;
export var BackSide = 1;
export var DoubleSide = 2;
export var FlatShading = 1;
export var SmoothShading = 2;
export var NoColors = 0;
export var FaceColors = 1;
export var VertexColors = 2;
export var NoBlending = 0;
export var NormalBlending = 1;
export var AdditiveBlending = 2;
export var SubtractiveBlending = 3;
export var MultiplyBlending = 4;
export var CustomBlending = 5;
export var AddEquation = 100;
export var SubtractEquation = 101;
export var ReverseSubtractEquation = 102;
export var MinEquation = 103;
export var MaxEquation = 104;
export var ZeroFactor = 200;
export var OneFactor = 201;
export var SrcColorFactor = 202;
export var OneMinusSrcColorFactor = 203;
export var SrcAlphaFactor = 204;
export var OneMinusSrcAlphaFactor = 205;
export var DstAlphaFactor = 206;
export var OneMinusDstAlphaFactor = 207;
export var DstColorFactor = 208;
export var OneMinusDstColorFactor = 209;
export var SrcAlphaSaturateFactor = 210;
export var NeverDepth = 0;
export var AlwaysDepth = 1;
export var LessDepth = 2;
export var LessEqualDepth = 3;
export var EqualDepth = 4;
export var GreaterEqualDepth = 5;
export var GreaterDepth = 6;
export var NotEqualDepth = 7;
export var MultiplyOperation = 0;
export var MixOperation = 1;
export var AddOperation = 2;
export var NoToneMapping = 0;
export var LinearToneMapping = 1;
export var ReinhardToneMapping = 2;
export var Uncharted2ToneMapping = 3;
export var CineonToneMapping = 4;
export var UVMapping = 300;
export var CubeReflectionMapping = 301;
export var CubeRefractionMapping = 302;
export var EquirectangularReflectionMapping = 303;
export var EquirectangularRefractionMapping = 304;
export var SphericalReflectionMapping = 305;
export var CubeUVReflectionMapping = 306;
export var CubeUVRefractionMapping = 307;
export var RepeatWrapping = 1000;
export var ClampToEdgeWrapping = 1001;
export var MirroredRepeatWrapping = 1002;
export var NearestFilter = 1003;
export var NearestMipMapNearestFilter = 1004;
export var NearestMipMapLinearFilter = 1005;
export var LinearFilter = 1006;
export var LinearMipMapNearestFilter = 1007;
export var LinearMipMapLinearFilter = 1008;
export var UnsignedByteType = 1009;
export var ByteType = 1010;
export var ShortType = 1011;
export var UnsignedShortType = 1012;
export var IntType = 1013;
export var UnsignedIntType = 1014;
export var FloatType = 1015;
export var HalfFloatType = 1016;
export var UnsignedShort4444Type = 1017;
export var UnsignedShort5551Type = 1018;
export var UnsignedShort565Type = 1019;
export var UnsignedInt248Type = 1020;
export var AlphaFormat = 1021;
export var RGBFormat = 1022;
export var RGBAFormat = 1023;
export var LuminanceFormat = 1024;
export var LuminanceAlphaFormat = 1025;
export var RGBEFormat = RGBAFormat;
export var DepthFormat = 1026;
export var DepthStencilFormat = 1027;
export var RGB_S3TC_DXT1_Format = 2001;
export var RGBA_S3TC_DXT1_Format = 2002;
export var RGBA_S3TC_DXT3_Format = 2003;
export var RGBA_S3TC_DXT5_Format = 2004;
export var RGB_PVRTC_4BPPV1_Format = 2100;
export var RGB_PVRTC_2BPPV1_Format = 2101;
export var RGBA_PVRTC_4BPPV1_Format = 2102;
export var RGBA_PVRTC_2BPPV1_Format = 2103;
export var RGB_ETC1_Format = 2151;
export var LoopOnce = 2200;
export var LoopRepeat = 2201;
export var LoopPingPong = 2202;
export var InterpolateDiscrete = 2300;
export var InterpolateLinear = 2301;
export var InterpolateSmooth = 2302;
export var ZeroCurvatureEnding = 2400;
export var ZeroSlopeEnding = 2401;
export var WrapAroundEnding = 2402;
export var TrianglesDrawMode = 0;
export var TriangleStripDrawMode = 1;
export var TriangleFanDrawMode = 2;
export var LinearEncoding = 3000;
export var sRGBEncoding = 3001;
export var GammaEncoding = 3007;
export var RGBEEncoding = 3002;
export var LogLuvEncoding = 3003;
export var RGBM7Encoding = 3004;
export var RGBM16Encoding = 3005;
export var RGBDEncoding = 3006;
export var BasicDepthPacking = 3200;
export var RGBADepthPacking = 3201;
<|endoftext|>


<commit_before>var models = require('../models/models.js');

// GET /statics
exports.load = function(req, res){
	var datos = {};

	//nmero de preguntas
	models.Quiz.findAndCountAll().then(function(result){
		datos.numPreguntas = result.count;

		models.Comment.findAndCountAll().then(function(result){
			//nmero de comentarios totales
				datos.numComentarios = result.count;
			//nmero medio de comentarios por pregunta
			datos.numComentariosMedio = datos.numComentarios / datos.numPreguntas;

			models.Comment.findAll({group: ['QuizId']}).then(function(result){
					//nmero de preguntas con comentarios
					datos.numPregComent = result.length;

					//nmero preguntas sin comentarios
					datos.numPregSinComent = datos.numPreguntas - datos.numPregComent;

				res.render('statistics/statistics', {statistics: datos, errors:[]});
			});
		});
	}).catch(function(error){next(error)});

};<commit_msg>modificación estadísticas<commit_after>var models = require('../models/models.js');

// GET /statics
exports.load = function(req, res){
	var datos = {};

	//nmero de preguntas
	models.Quiz.findAndCountAll().then(function(result){
		datos.numPreguntas = result.count;

		models.Comment.findAndCountAll().then(function(result){
			//nmero de comentarios totales
				datos.numComentarios = result.count;
			//nmero medio de comentarios por pregunta
			datos.numComentariosMedio = datos.numComentarios / datos.numPreguntas;

			models.Quiz.findAll({include: [{ model: models.Comment }]}).then(function (result) {
				if (result) {
					var numPregNoComments = 0;
					result.forEach(function (quiz) {
						if (quiz.Comments.length === 0) {
							numPregNoComments++;
						}
					});
					//nmero preguntas sin comentarios
					datos.numPregSinComent = numPregNoComments;
					//nmero de preguntas con comentarios
					datos.numPregComent = datos.numPreguntas - datos.numPregSinComent;
				}else{
					datos.numPregSinComent = 0;
					datos.numPregComent = 0;
				}

				res.render('statistics/statistics', {statistics: datos, errors:[]});
			});
		});
	}).catch(function(error){next(error)});

};<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import setUpGames from '../actions/setup-games'
import setGameId from '../actions/set-current-game'
import Paper from 'material-ui/Paper'
import RaisedButton from 'material-ui/RaisedButton'
import FlatButton from 'material-ui/FlatButton'
import saveGame from '../actions/update-game'
import Board from '../components/Board'

import './Game.sass'

const PLAYER_COLORS = ['#0f0', '#00f']

class Game extends Component {
  componentWillMount() {
    this.props.setGameId(this.props.routeParams.gameId)
    this.props.setUpGames()
  }

  isPlayer() {
    const { game, currentUser } = this.props
    return game.players.filter((player) =>
      player.userId === currentUser._id).length > 0
  }

  canJoin() {
    if (this.isPlayer()) { return false }
    const { game } = this.props
    return game.players.length < 3
  }

  joinGame() {
    const { game, saveGame, currentUser } = this.props
    saveGame(game, { players: game.players.concat({
      userId: currentUser._id,
      name: currentUser.name,
      playerTurn: game.players.length,
      color: PLAYER_COLORS[game.players.length],
    })})
  }

  currentPlayer(){
    const { game, currentUser } = this.props
    const { players } = this.props.game
    // check if there actually are there are players...
    if( !!!players ) { return }
    // filter out the current player and return it
    return players.filter((player) => player.userId === currentUser._id)[0]
  }

  otherPlayer(){
    const { game, currentUser } = this.props
    const { players } = this.props.game
    // check if there actually are there are players...
    if( !!!players ) { return }
    // check if there are two players
    if( players.length < 2 ) { return }
    // filter out the other player and return it
    return players.filter((player) => player.userId != currentUser._id)[0]
  }

  notYouTurn(){
    const currentPlayer = this.currentPlayer()
    const otherPlayer = this.otherPlayer()
    const { turn } = this.props.game
    // check if there is another player
    if ( !otherPlayer ) { return false }
    // if turn is not playerTurn return true
    if (turn != currentPlayer.playerTurn) { return true }
  }

  gameNotOver(){
    const { players } = this.props.game
    const playerOneScore = players[0].boxes.length
    const playerTwoScore = players[1].boxes.length
    if (playerOneScore + playerTwoScore < 9){return true}
    return false
  }

  waitForOtherPlayer(){
    const otherPlayer = this.otherPlayer()
    // check if there is another player
    if ( !otherPlayer ) { return true }
  }

  render() {
    const { game } = this.props
    const { winner } = this.props.game
    const otherPlayer = this.otherPlayer()
    if (!!!game._id) { return null }

    if (this.canJoin()) {
      return (
        <Paper zDepth={3} className="join-game">

Join this Game?

Join { game.players.map((player) => player.name).join(' and ') } in this game.

          <RaisedButton label="Join" primary={true} onClick={ this.joinGame.bind(this) } />
          <Link to="/"><FlatButton label="Back to the Lobby" /></Link>
        </Paper>
      )
    } // end if() return

    return(

        {/*
Is player: { this.isPlayer() ? 'Yes' : 'No' }

Can join: { this.canJoin() ? 'Yes' : 'No' }
 */}

{ game.players.map((player) =>
{player.name}: SCORE = {player.boxes.length}
) }

 Winner: { winner }

        <Board />

        { (( this.notYouTurn.bind(this)() ) && this.gameNotOver.bind(this)() ) ?

Be patient, it's not your turn! { otherPlayer.name } is still thinking...

Or getting coffee...

          : null }

        { ( this.waitForOtherPlayer.bind(this)() )  ?

Nobody else here to play with... You can wait, or invite a friend!

          : null }

 // end div className="game"
    ) // end return
  } // end render
} // end component

Game.propTypes = {
  game: PropTypes.object.isRequired,
  currentUser: PropTypes.object.isRequired,
}

const mapStateToProps = (state) => {
  return {
    game: state.games.reduce((currentGame, nextGame) => {
      return nextGame._id === state.currentGame ? nextGame : currentGame
    }, {}),
    currentUser: state.currentUser,
  }
}

export default connect(mapStateToProps, { setUpGames, setGameId, saveGame })(Game)
<commit_msg>adjust text<commit_after>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import setUpGames from '../actions/setup-games'
import setGameId from '../actions/set-current-game'
import Paper from 'material-ui/Paper'
import RaisedButton from 'material-ui/RaisedButton'
import FlatButton from 'material-ui/FlatButton'
import saveGame from '../actions/update-game'
import Board from '../components/Board'

import './Game.sass'

const PLAYER_COLORS = ['#0f0', '#00f']

class Game extends Component {
  componentWillMount() {
    this.props.setGameId(this.props.routeParams.gameId)
    this.props.setUpGames()
  }

  isPlayer() {
    const { game, currentUser } = this.props
    return game.players.filter((player) =>
      player.userId === currentUser._id).length > 0
  }

  canJoin() {
    if (this.isPlayer()) { return false }
    const { game } = this.props
    return game.players.length < 3
  }

  joinGame() {
    const { game, saveGame, currentUser } = this.props
    saveGame(game, { players: game.players.concat({
      userId: currentUser._id,
      name: currentUser.name,
      playerTurn: game.players.length,
      color: PLAYER_COLORS[game.players.length],
    })})
  }

  currentPlayer(){
    const { game, currentUser } = this.props
    const { players } = this.props.game
    // check if there actually are there are players...
    if( !!!players ) { return }
    // filter out the current player and return it
    return players.filter((player) => player.userId === currentUser._id)[0]
  }

  otherPlayer(){
    const { game, currentUser } = this.props
    const { players } = this.props.game
    // check if there actually are there are players...
    if( !!!players ) { return }
    // check if there are two players
    if( players.length < 2 ) { return }
    // filter out the other player and return it
    return players.filter((player) => player.userId != currentUser._id)[0]
  }

  notYouTurn(){
    const currentPlayer = this.currentPlayer()
    const otherPlayer = this.otherPlayer()
    const { turn } = this.props.game
    // check if there is another player
    if ( !otherPlayer ) { return false }
    // if turn is not playerTurn return true
    if (turn != currentPlayer.playerTurn) { return true }
  }

  gameNotOver(){
    const { players } = this.props.game
    const playerOneScore = players[0].boxes.length
    const playerTwoScore = players[1].boxes.length
    if (playerOneScore + playerTwoScore < 9){return true}
    return false
  }

  waitForOtherPlayer(){
    const otherPlayer = this.otherPlayer()
    // check if there is another player
    if ( !otherPlayer ) { return true }
  }

  render() {
    const { game } = this.props
    const { winner } = this.props.game
    const otherPlayer = this.otherPlayer()
    if (!!!game._id) { return null }

    if (this.canJoin()) {
      return (
        <Paper zDepth={3} className="join-game">

Join this Game?

Join { game.players.map((player) => player.name).join(' and ') } in this game.

          <RaisedButton label="Join" primary={true} onClick={ this.joinGame.bind(this) } />
          <Link to="/"><FlatButton label="Back to the Lobby" /></Link>
        </Paper>
      )
    } // end if() return

    return(

        {/*
Is player: { this.isPlayer() ? 'Yes' : 'No' }

Can join: { this.canJoin() ? 'Yes' : 'No' }
 */}

{ game.players.map((player) =>
{player.name}: SCORE = {player.boxes.length}
) }

 Winner: { winner }

        <Board />

        { (( this.notYouTurn.bind(this)() ) && this.gameNotOver.bind(this)() ) ?

Be patient, it's not your turn! { otherPlayer.name } is still thinking...

Or getting coffee...

          : null }

        { ( this.waitForOtherPlayer.bind(this)() )  ?

Nobody else here to play with... Please wait, or invite a friend!

          : null }

 // end div className="game"
    ) // end return
  } // end render
} // end component

Game.propTypes = {
  game: PropTypes.object.isRequired,
  currentUser: PropTypes.object.isRequired,
}

const mapStateToProps = (state) => {
  return {
    game: state.games.reduce((currentGame, nextGame) => {
      return nextGame._id === state.currentGame ? nextGame : currentGame
    }, {}),
    currentUser: state.currentUser,
  }
}

export default connect(mapStateToProps, { setUpGames, setGameId, saveGame })(Game)
<|endoftext|>


<commit_before>/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the 2-clause BSD license.
 * See license.txt in the OpenLayers distribution or repository for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/WFSCapabilities.js
 */

/**
 * Class: OpenLayers.Format.WFSCapabilities.v2_0_0
 * Abstract class not to be instantiated directly.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.WFSCapabilities.v2_0_0 = OpenLayers.Class(
    OpenLayers.Format.XML, {

    /**
     * Property: namespaces
     * {Object} Mapping of namespace aliases to namespace URIs.
     */
    namespaces: {
        wfs: "http://www.opengis.net/wfs/2.0",
        xlink: "http://www.w3.org/1999/xlink",
        xsi: "http://www.w3.org/2001/XMLSchema-instance",
        ows: "http://www.opengis.net/ows/1.1"
    },

    /**
     * Property: regExes
     * Compiled regular expressions for manipulating strings.
     */
    regExes: {
        trimSpace: (/^\s*|\s*$/g),
        removeSpace: (/\s*/g),
        splitSpace: (/\s+/),
        trimComma: (/\s*,\s*/g)
    },

    /**
     * APIProperty: errorProperty
     * {String} Which property of the returned object to check for in order to
     * determine whether or not parsing has failed. In the case that the
     * errorProperty is undefined on the returned object, the document will be
     * run through an OGCExceptionReport parser.
     */
    errorProperty: "featureTypeList",

    /**
     * Property: defaultPrefix
     */
    defaultPrefix: "wfs",

    /**
     * Constructor: OpenLayers.Format.WFSCapabilities.v1_1
     * Create an instance of one of the subclasses.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    /**
     * APIMethod: read
     * Read capabilities data from a string, and return a list of layers.
     *
     * Parameters:
     * data - {String} or {DOMElement} data to read/parse.
     *
     * Returns:
     * {Array} List of named layers.
     */
    read: function(data) {
        if(typeof data == "string") {
            data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
        }
        var raw = data;
        if(data && data.nodeType == 9) {
            data = data.documentElement;
        }
        var capabilities = {};
        this.readNode(data, capabilities);
        return capabilities;
    },

    /**
     * Property: readers
     * Contains public functions, grouped by namespace prefix, that will
     *     be applied when a namespaced node is found matching the function
     *     name.  The function will be applied in the scope of this parser
     *     with two arguments: the node being read and a context object passed
     *     from the parent.
     */
    readers: {
        "wfs": {
            "WFS_Capabilities": function(node, obj) {
                this.readChildNodes(node, obj);
            },
            "FeatureTypeList": function(node, request) {
                request.featureTypeList = {
                    featureTypes: []
                };
                this.readChildNodes(node, request.featureTypeList);
            },
            "FeatureType": function(node, featureTypeList) {
                var featureType = {};
                this.readChildNodes(node, featureType);
                featureTypeList.featureTypes.push(featureType);
            },
            "Name": function(node, obj) {
                var name = this.getChildValue(node);
                if(name) {
                    var parts = name.split(":");
                    obj.name = parts.pop();
                    if(parts.length > 0) {
                        obj.featureNS = this.lookupNamespaceURI(node, parts[0]);
                    }
                }
            },
            "Title": function(node, obj) {
                var title = this.getChildValue(node);
                if(title) {
                    obj.title = title;
                }
            },
            "Abstract": function(node, obj) {
                var abst = this.getChildValue(node);
                if(abst) {
                    obj["abstract"] = abst;
                }
            },
            "DefaultCRS": function(node, obj) {
                var defaultCRS = this.getChildValue(node);
                if (defaultCRS) {
                    obj.srs = defaultCRS;
                }
            }
        },
        "ows": OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows
    },

    CLASS_NAME: "OpenLayers.Format.WFSCapabilities.v2_0_0"

});
<commit_msg>resolve js dependencies for build<commit_after>/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
 * full list of contributors). Published under the 2-clause BSD license.
 * See license.txt in the OpenLayers distribution or repository for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/WFSCapabilities.js
 * @requires OpenLayers/Format/OWSCommon/v1_1_0.js
 */

/**
 * Class: OpenLayers.Format.WFSCapabilities.v2_0_0
 * Abstract class not to be instantiated directly.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.WFSCapabilities.v2_0_0 = OpenLayers.Class(
    OpenLayers.Format.XML, {

    /**
     * Property: namespaces
     * {Object} Mapping of namespace aliases to namespace URIs.
     */
    namespaces: {
        wfs: "http://www.opengis.net/wfs/2.0",
        xlink: "http://www.w3.org/1999/xlink",
        xsi: "http://www.w3.org/2001/XMLSchema-instance",
        ows: "http://www.opengis.net/ows/1.1"
    },

    /**
     * Property: regExes
     * Compiled regular expressions for manipulating strings.
     */
    regExes: {
        trimSpace: (/^\s*|\s*$/g),
        removeSpace: (/\s*/g),
        splitSpace: (/\s+/),
        trimComma: (/\s*,\s*/g)
    },

    /**
     * APIProperty: errorProperty
     * {String} Which property of the returned object to check for in order to
     * determine whether or not parsing has failed. In the case that the
     * errorProperty is undefined on the returned object, the document will be
     * run through an OGCExceptionReport parser.
     */
    errorProperty: "featureTypeList",

    /**
     * Property: defaultPrefix
     */
    defaultPrefix: "wfs",

    /**
     * Constructor: OpenLayers.Format.WFSCapabilities.v1_1
     * Create an instance of one of the subclasses.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */

    /**
     * APIMethod: read
     * Read capabilities data from a string, and return a list of layers.
     *
     * Parameters:
     * data - {String} or {DOMElement} data to read/parse.
     *
     * Returns:
     * {Array} List of named layers.
     */
    read: function(data) {
        if(typeof data == "string") {
            data = OpenLayers.Format.XML.prototype.read.apply(this, [data]);
        }
        var raw = data;
        if(data && data.nodeType == 9) {
            data = data.documentElement;
        }
        var capabilities = {};
        this.readNode(data, capabilities);
        return capabilities;
    },

    /**
     * Property: readers
     * Contains public functions, grouped by namespace prefix, that will
     *     be applied when a namespaced node is found matching the function
     *     name.  The function will be applied in the scope of this parser
     *     with two arguments: the node being read and a context object passed
     *     from the parent.
     */
    readers: {
        "wfs": {
            "WFS_Capabilities": function(node, obj) {
                this.readChildNodes(node, obj);
            },
            "FeatureTypeList": function(node, request) {
                request.featureTypeList = {
                    featureTypes: []
                };
                this.readChildNodes(node, request.featureTypeList);
            },
            "FeatureType": function(node, featureTypeList) {
                var featureType = {};
                this.readChildNodes(node, featureType);
                featureTypeList.featureTypes.push(featureType);
            },
            "Name": function(node, obj) {
                var name = this.getChildValue(node);
                if(name) {
                    var parts = name.split(":");
                    obj.name = parts.pop();
                    if(parts.length > 0) {
                        obj.featureNS = this.lookupNamespaceURI(node, parts[0]);
                    }
                }
            },
            "Title": function(node, obj) {
                var title = this.getChildValue(node);
                if(title) {
                    obj.title = title;
                }
            },
            "Abstract": function(node, obj) {
                var abst = this.getChildValue(node);
                if(abst) {
                    obj["abstract"] = abst;
                }
            },
            "DefaultCRS": function(node, obj) {
                var defaultCRS = this.getChildValue(node);
                if (defaultCRS) {
                    obj.srs = defaultCRS;
                }
            }
        },
        "ows": OpenLayers.Format.OWSCommon.v1_1_0.prototype.readers.ows
    },

    CLASS_NAME: "OpenLayers.Format.WFSCapabilities.v2_0_0"

});
<|endoftext|>


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

var App = require('app');
var stringUtils = require('utils/string_utils');

App.WizardStep4Controller = Em.ArrayController.extend({

  name: 'wizardStep4Controller',

  /**
   * List of Services
   * @type {Object[]}
   */
  content: [],

  /**
   * Is Submit button disabled
   * @type {bool}
   */
  isSubmitDisabled: function () {
    return this.filterProperty('isSelected', true).filterProperty('isInstalled', false).length === 0;
  }.property("@each.isSelected"),

  /**
   * Check whether all properties are selected
   * @type {bool}
   */
  isAll: function () {
    return this.everyProperty('isSelected', true);
  }.property('@each.isSelected'),

  /**
   * Check whether none properties(minimum) are selected
   * @type {bool}
   */
  isMinimum: function () {
    return this.everyProperty('isSelected', false);
  }.property('@each.isSelected'),

  /**
   * Onclick handler for select all link
   * @method selectAll
   */
  selectAll: function () {
    this.setEach('isSelected', true);
  },

  /**
   * Onclick handler for select minimum link
   * @method selectMinimum
   */
  selectMinimum: function () {
    this.setEach('isSelected', false);
  },

  /**
   * Check whether we should turn on HDFS or GLUSTERFS service
   * @return {bool}
   * @method noDFSs
   */
  noDFSs: function () {
    return  !this.filterProperty('isDFS',true).someProperty('isSelected',true);
  },

  /**
   * Check if multiple distributed file systems were selected
   * @return {bool}
   * @method multipleDFSs
   */
  multipleDFSs: function () {
    var dfsServices = this.filterProperty('isDFS',true).filterProperty('isSelected',true);
	  return  dfsServices.length > 1;
  },

  /**
   * Check do we have any monitoring service turned on
   * @return {bool}
   * @method gangliaOrNagiosNotSelected
   */
  isMonitoringServiceNotSelected: function () {
    var stackMonitoringServices = this.filterProperty('isMonitoringService',true);
    return stackMonitoringServices.someProperty('isSelected',false);
  },

  /**
   * Check whether user turned on monitoring service and go to next step
   * @method validateMonitoring
   */
  validateMonitoring: function () {
    var monitoringServices =  this.filterProperty('isMonitoringService',true);
    var notSelectedService = monitoringServices.filterProperty('isSelected',false);
    if (!!notSelectedService.length) {
      notSelectedService = stringUtils.getFormattedStringFromArray(notSelectedService.mapProperty('displayNameOnSelectServicePage'));
      monitoringServices = stringUtils.getFormattedStringFromArray(monitoringServices.mapProperty('displayNameOnSelectServicePage'));
      this.monitoringCheckPopup(notSelectedService,monitoringServices);
    } else {
      App.router.send('next');
    }
  },

  /**
   * Onclick handler for Next button
   * @method submit
   */
  submit: function () {
    this.setGroupedServices();
    if (!this.get("isSubmitDisabled") && !this.isSubmitChecksFailed()) {
      this.validateMonitoring();
    }
  },

  /**
   * @method  {isSubmitChecksFailed} Do the required checks on Next button click event
   * @returns {boolean}
   */
  isSubmitChecksFailed: function() {
    return this.isFileSystemCheckFailed() || this.isServiceDependencyCheckFailed();
  },

  /**
   * @method: isFileSystemCheckFailed - Checks if a filesystem is selected and only one filesystem is selected
   * @return: {boolean}
   */
  isFileSystemCheckFailed: function() {
    var isCheckFailed = false;
    var primaryDFS = this.findProperty('isPrimaryDFS',true);
    var primaryDfsDisplayName = primaryDFS.get('displayNameOnSelectServicePage');
    var primaryDfsServiceName = primaryDFS.get('serviceName');
     if (this.noDFSs()) {
       isCheckFailed = true;
       this.needToAddServicePopup.apply(this, [{serviceName: primaryDfsServiceName, selected: true},'fsCheck',primaryDfsDisplayName]);
     } else if (this.multipleDFSs()) {
       var dfsServices = this.filterProperty('isDFS',true).filterProperty('isSelected',true).mapProperty('serviceName');
       var services = dfsServices.map(function (item){
         var mappedObj = {
           serviceName: item,
           selected: false
         };
         if (item ===  primaryDfsServiceName) {
           mappedObj.selected = true;
         }
         return mappedObj;
       });
       isCheckFailed = true;
       this.needToAddServicePopup.apply(this, [services,'multipleDFS',primaryDfsDisplayName]);
     }
    return isCheckFailed;
  },

  /**
   * @method: isServiceDependencyCheckFailed - Checks if a dependent service is selected without selecting the main service
   * @return {boolean}
   */
  isServiceDependencyCheckFailed: function() {
    var isCheckFailed = false;
    var notSelectedServices = this.filterProperty('isSelected',false);
    notSelectedServices.forEach(function(service){
      var showWarningPopup;
      var dependentServices =  service.get('dependentServices');
      if (!!dependentServices) {
        showWarningPopup = false;
        dependentServices.forEach(function(_dependentService){
          var dependentService = this.findProperty('serviceName', _dependentService);
          if (dependentService && dependentService.get('isSelected') === true) {
            showWarningPopup = true;
            isCheckFailed = true;
          }
        },this);
        if (showWarningPopup) {
          this.needToAddServicePopup.apply(this, [{serviceName: service.get('serviceName'), selected: true},'serviceCheck',service.get('displayNameOnSelectServicePage')]);
        }
      }
    },this);
    return isCheckFailed;
  },

  setGroupedServices: function() {
    this.forEach(function(service){
      var coSelectedServices = service.get('coSelectedServices');
      coSelectedServices.forEach(function(groupedServiceName) {
        var groupedService = this.findProperty('serviceName', groupedServiceName);
        groupedService.set('isSelected',service.get('isSelected'));
      },this);
    },this);
  },

  /**
   * Select/deselect services
   * @param services array of objects
   *
   *    [
   *      {
   *        service: 'HDFS',
   *        selected: true
   *      },
   *      ....
   *    ]
   *
   * @param {string} i18nSuffix
   * @param {string} serviceName
   * @return {App.ModalPopup}
   * @method needToAddServicePopup
   */

  needToAddServicePopup: function(services, i18nSuffix, serviceName) {
    if (!(services instanceof Array)) {
      services = [services];
    }
    var self = this;
    return App.ModalPopup.show({
      header: Em.I18n.t('installer.step4.' + i18nSuffix + '.popup.header').format(serviceName),
      body: Em.I18n.t('installer.step4.' + i18nSuffix + '.popup.body').format(serviceName),
      onPrimary: function () {
        services.forEach(function (service) {
          self.findProperty('serviceName', service.serviceName).set('isSelected', service.selected);
        });
        this.hide();
        self.submit();
      }
    });
  },

  /**
   * Show popup with info about not selected (but should be selected) services
   * @return {App.ModalPopup}
   * @method monitoringCheckPopup
   */
  monitoringCheckPopup: function (notSelectedServiceNames,monitoringServicesNames) {
    return App.ModalPopup.show({
      header: Em.I18n.t('installer.step4.monitoringCheck.popup.header'),
      body: Em.I18n.t('installer.step4.monitoringCheck.popup.body').format(notSelectedServiceNames,monitoringServicesNames),
      onPrimary: function () {
        this.hide();
        App.router.send('next');
      }
    });
  }
});
<commit_msg>AMBARI-6571. "all/none" links affects already installed services on "Select Services" step. (onechiporenko)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var App = require('app');
var stringUtils = require('utils/string_utils');

App.WizardStep4Controller = Em.ArrayController.extend({

  name: 'wizardStep4Controller',

  /**
   * List of Services
   * @type {Object[]}
   */
  content: [],

  /**
   * Is Submit button disabled
   * @type {bool}
   */
  isSubmitDisabled: function () {
    return this.filterProperty('isSelected', true).filterProperty('isInstalled', false).length === 0;
  }.property("@each.isSelected"),

  /**
   * Check whether all properties are selected
   * @type {bool}
   */
  isAll: function () {
    return this.filterProperty('isInstalled', false).
      filterProperty('isHiddenOnSelectServicePage', false).
      everyProperty('isSelected', true);
  }.property('@each.isSelected'),

  /**
   * Check whether none properties(minimum) are selected
   * @type {bool}
   */
  isMinimum: function () {
    return this.filterProperty('isInstalled', false).
      filterProperty('isHiddenOnSelectServicePage', false).
      everyProperty('isSelected', false);
  }.property('@each.isSelected'),

  /**
   * Onclick handler for select all link
   * @method selectAll
   */
  selectAll: function () {
    this.filterProperty('isInstalled', false).setEach('isSelected', true);
  },

  /**
   * Onclick handler for select minimum link
   * @method selectMinimum
   */
  selectMinimum: function () {
    this.filterProperty('isInstalled', false).setEach('isSelected', false);
  },

  /**
   * Check whether we should turn on HDFS or GLUSTERFS service
   * @return {bool}
   * @method noDFSs
   */
  noDFSs: function () {
    return  !this.filterProperty('isDFS',true).someProperty('isSelected',true);
  },

  /**
   * Check if multiple distributed file systems were selected
   * @return {bool}
   * @method multipleDFSs
   */
  multipleDFSs: function () {
    var dfsServices = this.filterProperty('isDFS',true).filterProperty('isSelected',true);
	  return  dfsServices.length > 1;
  },

  /**
   * Check do we have any monitoring service turned on
   * @return {bool}
   * @method gangliaOrNagiosNotSelected
   */
  isMonitoringServiceNotSelected: function () {
    var stackMonitoringServices = this.filterProperty('isMonitoringService',true);
    return stackMonitoringServices.someProperty('isSelected',false);
  },

  /**
   * Check whether user turned on monitoring service and go to next step
   * @method validateMonitoring
   */
  validateMonitoring: function () {
    var monitoringServices =  this.filterProperty('isMonitoringService',true);
    var notSelectedService = monitoringServices.filterProperty('isSelected',false);
    if (!!notSelectedService.length) {
      notSelectedService = stringUtils.getFormattedStringFromArray(notSelectedService.mapProperty('displayNameOnSelectServicePage'));
      monitoringServices = stringUtils.getFormattedStringFromArray(monitoringServices.mapProperty('displayNameOnSelectServicePage'));
      this.monitoringCheckPopup(notSelectedService,monitoringServices);
    } else {
      App.router.send('next');
    }
  },

  /**
   * Onclick handler for Next button
   * @method submit
   */
  submit: function () {
    this.setGroupedServices();
    if (!this.get("isSubmitDisabled") && !this.isSubmitChecksFailed()) {
      this.validateMonitoring();
    }
  },

  /**
   * @method  {isSubmitChecksFailed} Do the required checks on Next button click event
   * @returns {boolean}
   */
  isSubmitChecksFailed: function() {
    return this.isFileSystemCheckFailed() || this.isServiceDependencyCheckFailed();
  },

  /**
   * @method: isFileSystemCheckFailed - Checks if a filesystem is selected and only one filesystem is selected
   * @return: {boolean}
   */
  isFileSystemCheckFailed: function() {
    var isCheckFailed = false;
    var primaryDFS = this.findProperty('isPrimaryDFS',true);
    var primaryDfsDisplayName = primaryDFS.get('displayNameOnSelectServicePage');
    var primaryDfsServiceName = primaryDFS.get('serviceName');
     if (this.noDFSs()) {
       isCheckFailed = true;
       this.needToAddServicePopup.apply(this, [{serviceName: primaryDfsServiceName, selected: true},'fsCheck',primaryDfsDisplayName]);
     } else if (this.multipleDFSs()) {
       var dfsServices = this.filterProperty('isDFS',true).filterProperty('isSelected',true).mapProperty('serviceName');
       var services = dfsServices.map(function (item){
         var mappedObj = {
           serviceName: item,
           selected: false
         };
         if (item ===  primaryDfsServiceName) {
           mappedObj.selected = true;
         }
         return mappedObj;
       });
       isCheckFailed = true;
       this.needToAddServicePopup.apply(this, [services,'multipleDFS',primaryDfsDisplayName]);
     }
    return isCheckFailed;
  },

  /**
   * @method: isServiceDependencyCheckFailed - Checks if a dependent service is selected without selecting the main service
   * @return {boolean}
   */
  isServiceDependencyCheckFailed: function() {
    var isCheckFailed = false;
    var notSelectedServices = this.filterProperty('isSelected',false);
    notSelectedServices.forEach(function(service){
      var showWarningPopup;
      var dependentServices =  service.get('dependentServices');
      if (!!dependentServices) {
        showWarningPopup = false;
        dependentServices.forEach(function(_dependentService){
          var dependentService = this.findProperty('serviceName', _dependentService);
          if (dependentService && dependentService.get('isSelected') === true) {
            showWarningPopup = true;
            isCheckFailed = true;
          }
        },this);
        if (showWarningPopup) {
          this.needToAddServicePopup.apply(this, [{serviceName: service.get('serviceName'), selected: true},'serviceCheck',service.get('displayNameOnSelectServicePage')]);
        }
      }
    },this);
    return isCheckFailed;
  },

  setGroupedServices: function() {
    this.forEach(function(service){
      var coSelectedServices = service.get('coSelectedServices');
      coSelectedServices.forEach(function(groupedServiceName) {
        var groupedService = this.findProperty('serviceName', groupedServiceName);
        groupedService.set('isSelected',service.get('isSelected'));
      },this);
    },this);
  },

  /**
   * Select/deselect services
   * @param services array of objects
   *
   *    [
   *      {
   *        service: 'HDFS',
   *        selected: true
   *      },
   *      ....
   *    ]
   *
   * @param {string} i18nSuffix
   * @param {string} serviceName
   * @return {App.ModalPopup}
   * @method needToAddServicePopup
   */

  needToAddServicePopup: function(services, i18nSuffix, serviceName) {
    if (!(services instanceof Array)) {
      services = [services];
    }
    var self = this;
    return App.ModalPopup.show({
      header: Em.I18n.t('installer.step4.' + i18nSuffix + '.popup.header').format(serviceName),
      body: Em.I18n.t('installer.step4.' + i18nSuffix + '.popup.body').format(serviceName),
      onPrimary: function () {
        services.forEach(function (service) {
          self.findProperty('serviceName', service.serviceName).set('isSelected', service.selected);
        });
        this.hide();
        self.submit();
      }
    });
  },

  /**
   * Show popup with info about not selected (but should be selected) services
   * @return {App.ModalPopup}
   * @method monitoringCheckPopup
   */
  monitoringCheckPopup: function (notSelectedServiceNames,monitoringServicesNames) {
    return App.ModalPopup.show({
      header: Em.I18n.t('installer.step4.monitoringCheck.popup.header'),
      body: Em.I18n.t('installer.step4.monitoringCheck.popup.body').format(notSelectedServiceNames,monitoringServicesNames),
      onPrimary: function () {
        this.hide();
        App.router.send('next');
      }
    });
  }
});
<|endoftext|>


<commit_before>import React from 'react';

import PageLink from './common/PageLink';

const GiDataFilter = ({categoryFilter}) => {

  //console.log('*** GiDataFilter ***');
  //console.log({categoryFilter});

  return (

      <PageLink to={'/glycemic-index/'}>
        [All]
      </PageLink>
      <PageLink to={'/glycemic-index/beans'}>
        [Beans]
      </PageLink>
      <PageLink to={'/glycemic-index/breads'}>
        [Breads]
      </PageLink>
      <PageLink to={'/glycemic-index/breakfast-cereals'}>
        [Breakfast Cereals]
      </PageLink>

  );
};

export default GiDataFilter;
<commit_msg>show active category filter<commit_after>import React from 'react';

import PageLink from './common/PageLink';
import { categoryPathMap, pathCategoryMap } from '../utils';

const GiDataFilter = ({categoryFilter}) => {

  const FilterLink = ({categoryPath}) => {

    let isActive = false;
    const category = (categoryPath) ? pathCategoryMap()[categoryPath] : 'All';

    if (!categoryFilter && !categoryPath) {
      isActive = true;
    } else {
      if ( category === categoryFilter ) {
        isActive = true;
      }
    }

    const pathTo = (categoryPath) ? '/glycemic-index/' + categoryPath : '/glycemic-index/';

    return (

        <PageLink to={pathTo}>
          {category} {isActive && '*'}
        </PageLink>

    );
  };

  return (

      <FilterLink/>
      <FilterLink categoryPath="beans"/>
      <FilterLink categoryPath="breads"/>
      <FilterLink categoryPath="breakfast-cereals"/>

  );
};

export default GiDataFilter;
<|endoftext|>


<commit_before>// namespace
var GNOVEL = GNOVEL || {};

(function() {
	"use strict";

	/**
	 * @class  Flow
	 * @constructor
	 */
	var Flow = function(page) {
		this._flowCounter = 0;
		this._page = page;
		this._elements = null;
		this._labels = [];
		this._objs = [];
	};

	Flow.DIALOG = "dialog";
	Flow.CHOICES = "choices";
	Flow.SHOW = "show";
	Flow.HIDE = "hide";
	Flow.GOTO = "goto";

	Flow.prototype._set = function(flowElements) {
		this._elements = flowElements;
		this._processLabels();
	};

	Flow.prototype._jump = function(index) {
		this._flowCounter = index - 1;
		this._next();
	};

	Flow.prototype._exec = function() {
		var obj = this._elements[this._flowCounter];

		// hack
		if(obj == null)
			return;

		this._processParameters(obj);

		var type = obj.type;

		switch(type) {
			case Flow.DIALOG:
				this._handleDialog(obj);
				break;
			case Flow.CHOICES:
				this._handleChoices(obj);
				break;
			case Flow.SHOW:
				this._handleShow(obj);
				break;
			case Flow.HIDE:
				this._handleHide(obj);
				break;
			case Flow.GOTO:
				this._handleGoto(obj);
				break;
		}
	};

	Flow.prototype._next = function() {
		this._flowCounter++;
	};

	Flow.prototype._processLabels = function() {
		for(var i = 0; i < this._elements.length;i++) {
			var e = this._elements[i];
			if(e.label != null) {
				var label = e.label;
				this._labels[label] = i;
			}
		};
	};

	Flow.prototype._processParameters = function(obj) {
		// iterate over all properties in the obj
		for (var prop in obj) {
			if(obj.hasOwnProperty(prop)) {
				// check if this property's value start with '#'
				// which would mark this value as a label of other
				// flow element

				if(typeof (obj[prop]) === "string") {
					// check if it starts with '#'
					var c = obj[prop].charAt(0);
					if(c == '#') {
						var label = obj[prop].substring(1);
						// search for that label in labels dictionary
						var value = this._labels[label];

						if(value === null)
							console.log("cannot find " + label);

						obj[prop] = value;
					} else if(c == '%') {
						var label = obj[prop].substring(1);
						// search for that label in objs dictionary
						var value = this._objs[label];

						if(value === null)
							console.log("cannot find " + label);

						obj[prop] = value;
					}
				} else if(typeof(obj[prop]) === "object") {
					// recurse to this object
					this._processParameters(obj[prop]);
				}
			}
		}
	};

	Flow.prototype._handleDialog = function(obj) {
		var x = obj.x || 0; // optional
		var y = obj.y || 0; // optional

		this._page._showDialog(obj.text, x, y);
	};

	Flow.prototype._handleChoices = function(obj) {
		// collect choices' text to its own array
		var choicesTextArr = [];
		for(var i = 0; i < obj.choices.length; i++) {
			choicesTextArr.push(obj.choices[i].text);
		}

		// collect choices' jump to its own array
		var jumpArr = [];
		for(var i=0; i < obj.choices.length;i++) {
			jumpArr.push(obj.choices[i].go);
		}

		this._page._showChoices(choicesTextArr, null, jumpArr);
	};

	Flow.prototype._handleShow = function(obj) {
		var img = obj.img;

		this._page._show(img);
	};

	Flow.prototype._handleHide = function(obj) {
		var img = obj.img;
		var params = {};

		if(obj.waitUntilHidden != null) {
			params.waitUntilHidden = obj.waitUntilHidden;
		}

		this._page._hide(img, params);
	};

	Flow.prototype._handleGoto = function(obj) {
		var pageIndex = obj.page;
		var transitionType = obj.transition;

		switch(transitionType) {
			case "fade" :
				transitionType = GNOVEL.TransitionType.FADE;
				break;
		};

		this._page.goToPage(pageIndex, transitionType, null);
	};

	Flow.prototype._setObjectTag = function(tag, obj) {
		this._objs[tag] = obj;
	};

	GNOVEL.Flow = Flow;
}());
<commit_msg>Add Flow._reset and reset Flow every call to Flow._set<commit_after>// namespace
var GNOVEL = GNOVEL || {};

(function() {
	"use strict";

	/**
	 * @class  Flow
	 * @constructor
	 */
	var Flow = function(page) {
		this._page = page;
		this._objs = [];
		this._reset();
	};

	Flow.prototype._reset = function() {
		this._flowCounter = 0;
		this._elements = null;
		this._labels = [];
	};

	Flow.DIALOG = "dialog";
	Flow.CHOICES = "choices";
	Flow.SHOW = "show";
	Flow.HIDE = "hide";
	Flow.GOTO = "goto";

	Flow.prototype._set = function(flowElements) {
		this._reset();

		if(flowElements == null)
			flowElements = [];

		this._elements = flowElements;
		this._processLabels();
	};

	Flow.prototype._jump = function(index) {
		this._flowCounter = index - 1;
		this._next();
	};

	Flow.prototype._exec = function() {
		var obj = this._elements[this._flowCounter];

		// hack
		if(obj == null)
			return;

		this._processParameters(obj);

		var type = obj.type;

		switch(type) {
			case Flow.DIALOG:
				this._handleDialog(obj);
				break;
			case Flow.CHOICES:
				this._handleChoices(obj);
				break;
			case Flow.SHOW:
				this._handleShow(obj);
				break;
			case Flow.HIDE:
				this._handleHide(obj);
				break;
			case Flow.GOTO:
				this._handleGoto(obj);
				break;
		}
	};

	Flow.prototype._next = function() {
		this._flowCounter++;
	};

	Flow.prototype._processLabels = function() {
		for(var i = 0; i < this._elements.length;i++) {
			var e = this._elements[i];
			if(e.label != null) {
				var label = e.label;
				this._labels[label] = i;
			}
		};
	};

	Flow.prototype._processParameters = function(obj) {
		// iterate over all properties in the obj
		for (var prop in obj) {
			if(obj.hasOwnProperty(prop)) {
				// check if this property's value start with '#'
				// which would mark this value as a label of other
				// flow element

				if(typeof (obj[prop]) === "string") {
					// check if it starts with '#'
					var c = obj[prop].charAt(0);
					if(c == '#') {
						var label = obj[prop].substring(1);
						// search for that label in labels dictionary
						var value = this._labels[label];

						if(value === null)
							console.log("cannot find " + label);

						obj[prop] = value;
					} else if(c == '%') {
						var label = obj[prop].substring(1);
						// search for that label in objs dictionary
						var value = this._objs[label];

						if(value === null)
							console.log("cannot find " + label);

						obj[prop] = value;
					}
				} else if(typeof(obj[prop]) === "object") {
					// recurse to this object
					this._processParameters(obj[prop]);
				}
			}
		}
	};

	Flow.prototype._handleDialog = function(obj) {
		var x = obj.x || 0; // optional
		var y = obj.y || 0; // optional

		this._page._showDialog(obj.text, x, y);
	};

	Flow.prototype._handleChoices = function(obj) {
		// collect choices' text to its own array
		var choicesTextArr = [];
		for(var i = 0; i < obj.choices.length; i++) {
			choicesTextArr.push(obj.choices[i].text);
		}

		// collect choices' jump to its own array
		var jumpArr = [];
		for(var i=0; i < obj.choices.length;i++) {
			jumpArr.push(obj.choices[i].go);
		}

		this._page._showChoices(choicesTextArr, null, jumpArr);
	};

	Flow.prototype._handleShow = function(obj) {
		var img = obj.img;

		this._page._show(img);
	};

	Flow.prototype._handleHide = function(obj) {
		var img = obj.img;
		var params = {};

		if(obj.waitUntilHidden != null) {
			params.waitUntilHidden = obj.waitUntilHidden;
		}

		this._page._hide(img, params);
	};

	Flow.prototype._handleGoto = function(obj) {
		var pageIndex = obj.page;
		var transitionType = obj.transition;

		switch(transitionType) {
			case "fade" :
				transitionType = GNOVEL.TransitionType.FADE;
				break;
		};

		this._page.goToPage(pageIndex, transitionType, null);
	};

	Flow.prototype._setObjectTag = function(tag, obj) {
		this._objs[tag] = obj;
	};

	GNOVEL.Flow = Flow;
}());
<|endoftext|>