<commit_before>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require('fs');
var colors = require("colors");
var UserAgent = require('useragent');
var FileUtil = require("../util/fileutil");
var path = require('path');
var XMLWriter = require('xml-writer');
var util = require('util');
var xw;
var log4js = require("log4js");
var existsSync = fs.existsSync || path.existsSync;

/**
 *
 * @param reportObj includes all information about testSessions, wsSessions and the test report itself
 * @constructor
 */
function ReportManager(reportObj) {
    this.passCount = 0;
    this.failCount = 0;
    this.skipCount = 0;
    this.timeCount = 0;
    this.totalCount = 0;
    this.totalTimeTaken = 0;
    this.logger = log4js.getLogger("ReportManager");

    if (reportObj) {
        this.timeReport = reportObj.timeReport;
    }

    xw = new XMLWriter();
    this.xw = xw;

    //checking if we need to do colorless reporting.
    if (global.color === false) {
        colors.mode = "none";
    } else {
        if (!process.stdout.isTTY) {
            colors.mode = "none";
        }
    }
    try {
        if (reportObj.arrTestSessions) {
            this.testSessions = reportObj.arrTestSessions;
        } else {
            this.testSessions = [];
        }
        if (reportObj.arrWDSessions) {
            this.wdSessions = reportObj.arrWDSessions;
        } else {
            this.wdSessions = [];
        }
        this.reportObj = reportObj;

    } catch (ex) {
        //console.log(ex);
    }

}

ReportManager.prototype.addProperty = function (name, val) {
    if (val) {
        val += '';  // convert to string, since XMLWriter is picky
        this.xw.startElement('property');
        this.xw.writeAttribute('name', name);
        this.xw.writeAttribute('value', val);
        this.xw.endElement();
    }
};

ReportManager.prototype.addTest = function (time, className, name, failureMessage) {
    this.xw.startElement('testcase');
    this.xw.writeAttribute('time', (time / 1000).toFixed(2));
    this.xw.writeAttribute('classname', className);
    this.xw.writeAttribute('name', name);

    if (failureMessage) {
        if (failureMessage === "skip") {
            this.xw.writeAttribute('executed', 'false');
        } else {
            this.xw.startElement('failure');
            this.xw.text(util.format(failureMessage));
            this.xw.endElement();
        }
    }

    this.xw.endElement();
};

ReportManager.prototype.parseYUIResults = function (testJson, dtName, self) {

    var l, m, errorRep,
        yuiUserAgent = testJson.ua,
        yuiSuiteName = testJson.name,
        browser = UserAgent.parse(yuiUserAgent).toAgent(),
        descTestName = dtName,
        currentUrl = testJson.currentUrl,
        yuiTestCaseName,
        timePerTest,
        className,
        testName;

    if (browser === "Other 0.0.0") {
        browser = "NodeJS";
    }

    for (l in testJson) {
        if (testJson[l]) {
            if (testJson[l].type === "testcase") {
                yuiTestCaseName = testJson[l].name;
                timePerTest = testJson[l].duration / testJson[l].total;
                self.passCount += testJson[l].passed;
                self.failCount += testJson[l].failed;
                self.skipCount += testJson[l].ignored;
                self.timeCount += testJson[l].duration;
                self.totalCount += testJson[l].total;

                for (m in testJson[l]) {
                    if (testJson[l][m].type === "test") {
                        className = browser + "." + descTestName;
                        testName = yuiSuiteName + "::" + yuiTestCaseName + "::" + testJson[l][m].name;
                        if (testJson[l][m].result === "fail") {
                            self.addTest(timePerTest, className, testName, testJson[l][m].message + "." + "\n" + " URL :" + currentUrl);
                        } else if (testJson[l][m].result === "pass") {
                            self.addTest(timePerTest, className, testName);
                        } else if (testJson[l][m].result === "ignore") {
                            self.addTest(timePerTest, className, testName, "skip");
                        }
                    }
                }
            }
        }
    }
};

ReportManager.prototype.showReportOnConsole = function (result, verbose) {

    var lastSuite, suite, k, k1, test, msg, m, browser,
        log = console.log;

    log("");
    browser = result.ua;
    if (result.failed) {
        log("Failed ".red + result.name.blue + " on " + browser);
    } else {
        log("Passed ".green + result.name.blue + " on " + browser);
    }
    log((result.passed + " Passed").green + ", " + (result.failed + " Failed ").red + ", " + (result.ignored + " skipped ").grey);
    if (result.failed) {
        for (k in result) {
            suite = result[k];
            if ("object" === typeof suite) {

                if (suite.failed) {
                    for (k1 in suite) {
                        test = suite[k1];
                        if ("object" === typeof test) {
                            if ("fail" === test.result) {

                                if (!lastSuite || lastSuite !== suite.name) {
                                    log(" in " + suite.name.bold);
                                    lastSuite = suite.name;
                                }
                                msg = test.message.split('\n');
                                log(" " + test.name.bold.red + ":" + msg[0]);
                                for (m = 1; m < msg.length; m = m + 1) {
                                    log(" " + msg[m]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    log("");
};

ReportManager.prototype.writeReports = function () {

    var i, j, k, strJunitReport, strReport, rep, results, testJson, browser,
        testName, testSuiteName, arrReport, xmlReportName, jsonReportName, errorRep,
        self = this,
        wdSessions = self.wdSessions,
        testSessions = self.testSessions,
        jsonReport = {},
        log = console.log,
        resultPresent = false,
        missingErrorCount = 0,
        xwRoot = new XMLWriter(),
        fileUtil = new FileUtil(),
        dirPath,
        relPath;
    function writeFile(fileName, data) {
        fs.writeFileSync(fileName, data, 'utf8');
        log(("Report Created: " + fileName).inverse.toString());
    }

    /**
     * log test results on console
     */
    function logTestResults(reportObj) {
        log();
        log(("Total Number of Executed Tests: " + reportObj.totalCount).blue.toString());
        log(("Total Number of Passed Tests: " + reportObj.passCount).green.toString());
        log(("Total Number of Failed Tests: " + reportObj.failCount).red.toString());
        log(("Total Number of Skipped Tests: " + reportObj.skipCount).cyan.toString());
        log();
        log(("Total Test Execution Time Inside Browser: " + (reportObj.timeCount / 1000).toFixed(2) + " seconds").green.bold.toString());
        log(("Total Test Execution Time:" + reportObj.totalTimeTaken + " seconds").green.bold.toString());
        log();
    }

    for (i = 0; i < testSessions.length; i = i + 1) {

        rep = testSessions[i].driver.getReports();

        if (rep.scenario) {
            arrReport = rep.scenario;
        } else {
            arrReport = rep.results;
        }
        resultPresent = false;
        for (j = 0; j < arrReport.length; j = j + 1) {
            if (rep.scenario) {
                results = arrReport[j].results;

                for (k = 0; k < results.length; k = k + 1) {

                    testJson = results[k];
                    if (testJson.type === "report") {
                        if (!(testJson.passed === 0 && testJson.failed === 0 && testJson.total === 0)) {
                            resultPresent = true;
                            this.parseYUIResults(testJson, testSessions[i].driver.testName, this);
                        }
                    }
                }
            } else {
                testJson = arrReport[j];
                if (testJson.type === "report") {
                    if (!(testJson.passed === 0 && testJson.failed === 0 && testJson.total === 0)) {
                        resultPresent = true;
                        this.parseYUIResults(testJson, testSessions[i].driver.testName, this);
                    }
                }
            }
        }

        if (!resultPresent) {

            try {
                console.log(testSessions[i].driver.hasTest);
                if (errorRep) {
                    missingErrorCount = missingErrorCount + 1;
                    errorRep = arrReport[arrReport.length - 1];
                    if (errorRep.results && errorRep.results.length > 0) {
                        this.addTest(0, "Error." + testSessions[i].driver.testName, "Error", errorRep.results[0].error);
                    } else if (errorRep.error) {
                        this.addTest(0, "Error." + testSessions[i].driver.testName, "Error", errorRep.error);
                    } else {
                        self.logger.debug("Test Report Error : UNKOWN");
                        this.addTest(0, "Error." + testSessions[i].driver.testName, "Error", "Arrow didn't receive result from the test !!!!");
                    }
                } else {
                    if (!testSessions[i].driver.hasTest) {
                        self.logger.info("No TestReport found, but passing the test because 'hasTest' was passed as 'false'");
                        self.passCount += 1;
                        self.totalCount += 1;
                        this.addTest(0, testSessions[i].driver.browserName + "." + testSessions[i].driver.testName, "NoTestClass");
                    } else {
                        self.logger.error("Test failed without any error message");
                    }
                }
            } catch (e) {
                self.logger.debug(e);
            }
        }
    }
    this.totalCount = this.totalCount + missingErrorCount;
    this.failCount = this.failCount + missingErrorCount;

    if (this.reportObj.descriptor) {

        dirPath = path.dirname(this.reportObj.descriptor);
        if (global.reportFolder) {

            // if condition to keep unit tests happy on node10
            if (global.workingDirectory ) {
                //Get relative path to the descriptor
                relPath = path.relative(global.workingDirectory, dirPath);
            } else {
                relPath = dirPath;
            }

            dirPath = path.resolve(global.reportFolder, 'arrow-report', relPath);
            // Create directory if it doesnt exist
            // This check helps when keepTestReport is set to true ( If its not set to true, arrow-report would have been cleaned up as part of setup anyways
            if (!existsSync(dirPath)) {
                fileUtil.createDirectory(dirPath);
            }

        }

        xmlReportName = path.resolve(dirPath, path.basename(this.reportObj.descriptor, '.json') + "-report.xml");
        jsonReportName = path.resolve(dirPath, path.basename(this.reportObj.descriptor, '.json') + "-report.json");

        if (this.failCount > 0) {
            global.failedDescriptors.push({"desc" : this.reportObj.descriptor, "failures" : this.failCount});
        }

        log(("Test Report Summary for the descriptor::" + this.reportObj.descriptor).bold.magenta.toString());

        logTestResults(this);

    } else {

        xmlReportName = "arrow-test-summary.xml";
        jsonReportName = "arrow-test-summary.json";

        if (this.reportObj.showConsolidatedReport) {

            log("\n*************************************************************************************");
            log("                            Consolidated Report                                          ");

            log("Test Report Summary".bold.magenta.toString());
            logTestResults(this);

            log("\n*************************************************************************************");

        }

        if (global.failedDescriptors.length > 0) {

            log("\n*************************************************************************************");
            log("                           List of failed descriptors                                  ");

            for (i = 0; i < global.failedDescriptors.length; i += 1) {
                log('\nFailed Descriptor Path : ' + global.failedDescriptors[i].desc);
                log('Total Number of Failed Tests : ' + global.failedDescriptors[i].failures);
                log("-----------------------------------------------------------------------");
            }
            log('\n');

        }

    }

    testSuiteName = "";
    if (this.reportObj.testSuiteName) {
        testSuiteName = this.reportObj.testSuiteName;
    } else {
        testSuiteName = "TestSuite";
    }
    this.errorCount = this.totalCount - this.passCount - this.failCount - this.skipCount;

    // Store report files in user specified location, if explicitly specified, otherwise store in arrow-target/arrow-report
    if (global.reportFolder) {

        this.xw.startElement("properties");
        this.addProperty("descriptor", this.reportObj.descriptor);
        this.addProperty("parallel", this.reportObj.parallel);
        this.addProperty("driver", this.reportObj.driver);
        this.addProperty("browser", this.reportObj.browser);
        this.addProperty("reuseSession", this.reportObj.reuseSession);
        this.addProperty("activeSeleniumSessionCount", wdSessions.length);
        this.addProperty("seleniumSessionIds", wdSessions.join());
        this.addProperty("group", this.reportObj.group);
        this.addProperty("testName", this.reportObj.testName);
        this.xw.endElement();
        //collecting all report
        strReport = xw.toString();

        //starting report root
        xwRoot.startDocument();
        xwRoot.startElement("testsuite");
        xwRoot.writeAttribute('failures', this.failCount.toString());
        xwRoot.writeAttribute('time', this.totalTimeTaken.toString());
        xwRoot.writeAttribute('errors', this.errorCount.toString());
        xwRoot.writeAttribute('skipped', this.skipCount.toString());
        xwRoot.writeAttribute('tests', this.totalCount.toString());
        xwRoot.writeAttribute('name', testSuiteName.toString());
        xwRoot.text("$$report$$");
        xwRoot.endElement();
        xwRoot.endDocument();
        strJunitReport = xwRoot.toString().replace("$$report$$", strReport);

        xmlReportName = path.resolve(global.reportFolder, 'arrow-report', xmlReportName);
        jsonReportName = path.resolve(global.reportFolder, 'arrow-report', jsonReportName);

        log('\n');
        writeFile(xmlReportName, strJunitReport);

        //writing json file
        for (i = 0; i < testSessions.length; i = i + 1) {
            jsonReport[testSessions[i].driver.testName] = JSON.parse(JSON.stringify(testSessions[i].driver.getReports()));
        }
        jsonReport.testSuiteName = testSuiteName;
        writeFile(jsonReportName, JSON.stringify(jsonReport));
        log('\n');

    }

};

ReportManager.prototype.writeTimeReport = function () {

    var timeReportJsonStr,
        descriptor,
        testSessionTimeArr,
        testName;

    timeReportJsonStr = '{ "descriptors" : [';

    for (descriptor in this.timeReport) {

        timeReportJsonStr += "{";
        timeReportJsonStr += ('"descriptor": ' + ' "' + descriptor + '"' + ' ,');
        timeReportJsonStr += ('"time": ' + ' "' + this.timeReport[descriptor].timeTaken + ' seconds' + '",');

        testSessionTimeArr = this.timeReport[descriptor].testSessionTimeArr;

        timeReportJsonStr += '"tests": [';

        for (testName in testSessionTimeArr) {
            timeReportJsonStr += '{';
            timeReportJsonStr += ('"Testname" :' + ' "' + testName + '"' + ',');
            timeReportJsonStr += ('"Time" :' + ' "' + testSessionTimeArr[testName].timeTaken + ' seconds' + '"');
            timeReportJsonStr += '} ,';
        }

        if (timeReportJsonStr.charAt(timeReportJsonStr.length - 1) === ",") {
            timeReportJsonStr = timeReportJsonStr.slice(0, -1);
        }

        timeReportJsonStr += " ] } ,";
    }

    if (timeReportJsonStr.charAt(timeReportJsonStr.length - 1) === ",") {
        timeReportJsonStr = timeReportJsonStr.slice(0, -1);
    }

    timeReportJsonStr += ('] ,"Total time":' + ' "' + this.totalTimeTaken + ' seconds' + '" ');
    timeReportJsonStr += ' }';

    fs.writeFileSync(path.resolve(global.reportFolder, 'arrow-report', 'timeReport.json'), timeReportJsonStr, 'utf8');

};

module.exports = ReportManager;
<commit_msg>removing unwanted console log statement<commit_after>/*jslint forin:true sub:true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/

/*
 * Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */

var fs = require('fs');
var colors = require("colors");
var UserAgent = require('useragent');
var FileUtil = require("../util/fileutil");
var path = require('path');
var XMLWriter = require('xml-writer');
var util = require('util');
var xw;
var log4js = require("log4js");
var existsSync = fs.existsSync || path.existsSync;

/**
 *
 * @param reportObj includes all information about testSessions, wsSessions and the test report itself
 * @constructor
 */
function ReportManager(reportObj) {
    this.passCount = 0;
    this.failCount = 0;
    this.skipCount = 0;
    this.timeCount = 0;
    this.totalCount = 0;
    this.totalTimeTaken = 0;
    this.logger = log4js.getLogger("ReportManager");

    if (reportObj) {
        this.timeReport = reportObj.timeReport;
    }

    xw = new XMLWriter();
    this.xw = xw;

    //checking if we need to do colorless reporting.
    if (global.color === false) {
        colors.mode = "none";
    } else {
        if (!process.stdout.isTTY) {
            colors.mode = "none";
        }
    }
    try {
        if (reportObj.arrTestSessions) {
            this.testSessions = reportObj.arrTestSessions;
        } else {
            this.testSessions = [];
        }
        if (reportObj.arrWDSessions) {
            this.wdSessions = reportObj.arrWDSessions;
        } else {
            this.wdSessions = [];
        }
        this.reportObj = reportObj;

    } catch (ex) {
        //console.log(ex);
    }

}

ReportManager.prototype.addProperty = function (name, val) {
    if (val) {
        val += '';  // convert to string, since XMLWriter is picky
        this.xw.startElement('property');
        this.xw.writeAttribute('name', name);
        this.xw.writeAttribute('value', val);
        this.xw.endElement();
    }
};

ReportManager.prototype.addTest = function (time, className, name, failureMessage) {
    this.xw.startElement('testcase');
    this.xw.writeAttribute('time', (time / 1000).toFixed(2));
    this.xw.writeAttribute('classname', className);
    this.xw.writeAttribute('name', name);

    if (failureMessage) {
        if (failureMessage === "skip") {
            this.xw.writeAttribute('executed', 'false');
        } else {
            this.xw.startElement('failure');
            this.xw.text(util.format(failureMessage));
            this.xw.endElement();
        }
    }

    this.xw.endElement();
};

ReportManager.prototype.parseYUIResults = function (testJson, dtName, self) {

    var l, m, errorRep,
        yuiUserAgent = testJson.ua,
        yuiSuiteName = testJson.name,
        browser = UserAgent.parse(yuiUserAgent).toAgent(),
        descTestName = dtName,
        currentUrl = testJson.currentUrl,
        yuiTestCaseName,
        timePerTest,
        className,
        testName;

    if (browser === "Other 0.0.0") {
        browser = "NodeJS";
    }

    for (l in testJson) {
        if (testJson[l]) {
            if (testJson[l].type === "testcase") {
                yuiTestCaseName = testJson[l].name;
                timePerTest = testJson[l].duration / testJson[l].total;
                self.passCount += testJson[l].passed;
                self.failCount += testJson[l].failed;
                self.skipCount += testJson[l].ignored;
                self.timeCount += testJson[l].duration;
                self.totalCount += testJson[l].total;

                for (m in testJson[l]) {
                    if (testJson[l][m].type === "test") {
                        className = browser + "." + descTestName;
                        testName = yuiSuiteName + "::" + yuiTestCaseName + "::" + testJson[l][m].name;
                        if (testJson[l][m].result === "fail") {
                            self.addTest(timePerTest, className, testName, testJson[l][m].message + "." + "\n" + " URL :" + currentUrl);
                        } else if (testJson[l][m].result === "pass") {
                            self.addTest(timePerTest, className, testName);
                        } else if (testJson[l][m].result === "ignore") {
                            self.addTest(timePerTest, className, testName, "skip");
                        }
                    }
                }
            }
        }
    }
};

ReportManager.prototype.showReportOnConsole = function (result, verbose) {

    var lastSuite, suite, k, k1, test, msg, m, browser,
        log = console.log;

    log("");
    browser = result.ua;
    if (result.failed) {
        log("Failed ".red + result.name.blue + " on " + browser);
    } else {
        log("Passed ".green + result.name.blue + " on " + browser);
    }
    log((result.passed + " Passed").green + ", " + (result.failed + " Failed ").red + ", " + (result.ignored + " skipped ").grey);
    if (result.failed) {
        for (k in result) {
            suite = result[k];
            if ("object" === typeof suite) {

                if (suite.failed) {
                    for (k1 in suite) {
                        test = suite[k1];
                        if ("object" === typeof test) {
                            if ("fail" === test.result) {

                                if (!lastSuite || lastSuite !== suite.name) {
                                    log(" in " + suite.name.bold);
                                    lastSuite = suite.name;
                                }
                                msg = test.message.split('\n');
                                log(" " + test.name.bold.red + ":" + msg[0]);
                                for (m = 1; m < msg.length; m = m + 1) {
                                    log(" " + msg[m]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    log("");
};

ReportManager.prototype.writeReports = function () {

    var i, j, k, strJunitReport, strReport, rep, results, testJson, browser,
        testName, testSuiteName, arrReport, xmlReportName, jsonReportName, errorRep,
        self = this,
        wdSessions = self.wdSessions,
        testSessions = self.testSessions,
        jsonReport = {},
        log = console.log,
        resultPresent = false,
        missingErrorCount = 0,
        xwRoot = new XMLWriter(),
        fileUtil = new FileUtil(),
        dirPath,
        relPath;
    function writeFile(fileName, data) {
        fs.writeFileSync(fileName, data, 'utf8');
        log(("Report Created: " + fileName).inverse.toString());
    }

    /**
     * log test results on console
     */
    function logTestResults(reportObj) {
        log();
        log(("Total Number of Executed Tests: " + reportObj.totalCount).blue.toString());
        log(("Total Number of Passed Tests: " + reportObj.passCount).green.toString());
        log(("Total Number of Failed Tests: " + reportObj.failCount).red.toString());
        log(("Total Number of Skipped Tests: " + reportObj.skipCount).cyan.toString());
        log();
        log(("Total Test Execution Time Inside Browser: " + (reportObj.timeCount / 1000).toFixed(2) + " seconds").green.bold.toString());
        log(("Total Test Execution Time:" + reportObj.totalTimeTaken + " seconds").green.bold.toString());
        log();
    }

    for (i = 0; i < testSessions.length; i = i + 1) {

        rep = testSessions[i].driver.getReports();

        if (rep.scenario) {
            arrReport = rep.scenario;
        } else {
            arrReport = rep.results;
        }
        resultPresent = false;
        for (j = 0; j < arrReport.length; j = j + 1) {
            if (rep.scenario) {
                results = arrReport[j].results;

                for (k = 0; k < results.length; k = k + 1) {

                    testJson = results[k];
                    if (testJson.type === "report") {
                        if (!(testJson.passed === 0 && testJson.failed === 0 && testJson.total === 0)) {
                            resultPresent = true;
                            this.parseYUIResults(testJson, testSessions[i].driver.testName, this);
                        }
                    }
                }
            } else {
                testJson = arrReport[j];
                if (testJson.type === "report") {
                    if (!(testJson.passed === 0 && testJson.failed === 0 && testJson.total === 0)) {
                        resultPresent = true;
                        this.parseYUIResults(testJson, testSessions[i].driver.testName, this);
                    }
                }
            }
        }

        if (!resultPresent) {
            try {
                if (errorRep) {
                    missingErrorCount = missingErrorCount + 1;
                    errorRep = arrReport[arrReport.length - 1];
                    if (errorRep.results && errorRep.results.length > 0) {
                        this.addTest(0, "Error." + testSessions[i].driver.testName, "Error", errorRep.results[0].error);
                    } else if (errorRep.error) {
                        this.addTest(0, "Error." + testSessions[i].driver.testName, "Error", errorRep.error);
                    } else {
                        self.logger.debug("Test Report Error : UNKOWN");
                        this.addTest(0, "Error." + testSessions[i].driver.testName, "Error", "Arrow didn't receive result from the test !!!!");
                    }
                } else {
                    if (!testSessions[i].driver.hasTest) {
                        self.logger.info("No TestReport found, but passing the test because 'hasTest' was passed as 'false'");
                        self.passCount += 1;
                        self.totalCount += 1;
                        this.addTest(0, testSessions[i].driver.browserName + "." + testSessions[i].driver.testName, "NoTestClass");
                    } else {
                        self.logger.error("Test failed without any error message");
                    }
                }
            } catch (e) {
                self.logger.debug(e);
            }
        }
    }
    this.totalCount = this.totalCount + missingErrorCount;
    this.failCount = this.failCount + missingErrorCount;

    if (this.reportObj.descriptor) {

        dirPath = path.dirname(this.reportObj.descriptor);
        if (global.reportFolder) {

            // if condition to keep unit tests happy on node10
            if (global.workingDirectory ) {
                //Get relative path to the descriptor
                relPath = path.relative(global.workingDirectory, dirPath);
            } else {
                relPath = dirPath;
            }

            dirPath = path.resolve(global.reportFolder, 'arrow-report', relPath);
            // Create directory if it doesnt exist
            // This check helps when keepTestReport is set to true ( If its not set to true, arrow-report would have been cleaned up as part of setup anyways
            if (!existsSync(dirPath)) {
                fileUtil.createDirectory(dirPath);
            }

        }

        xmlReportName = path.resolve(dirPath, path.basename(this.reportObj.descriptor, '.json') + "-report.xml");
        jsonReportName = path.resolve(dirPath, path.basename(this.reportObj.descriptor, '.json') + "-report.json");

        if (this.failCount > 0) {
            global.failedDescriptors.push({"desc" : this.reportObj.descriptor, "failures" : this.failCount});
        }

        log(("Test Report Summary for the descriptor::" + this.reportObj.descriptor).bold.magenta.toString());

        logTestResults(this);

    } else {

        xmlReportName = "arrow-test-summary.xml";
        jsonReportName = "arrow-test-summary.json";

        if (this.reportObj.showConsolidatedReport) {

            log("\n*************************************************************************************");
            log("                            Consolidated Report                                          ");

            log("Test Report Summary".bold.magenta.toString());
            logTestResults(this);

            log("\n*************************************************************************************");

        }

        if (global.failedDescriptors.length > 0) {

            log("\n*************************************************************************************");
            log("                           List of failed descriptors                                  ");

            for (i = 0; i < global.failedDescriptors.length; i += 1) {
                log('\nFailed Descriptor Path : ' + global.failedDescriptors[i].desc);
                log('Total Number of Failed Tests : ' + global.failedDescriptors[i].failures);
                log("-----------------------------------------------------------------------");
            }
            log('\n');

        }

    }

    testSuiteName = "";
    if (this.reportObj.testSuiteName) {
        testSuiteName = this.reportObj.testSuiteName;
    } else {
        testSuiteName = "TestSuite";
    }
    this.errorCount = this.totalCount - this.passCount - this.failCount - this.skipCount;

    // Store report files in user specified location, if explicitly specified, otherwise store in arrow-target/arrow-report
    if (global.reportFolder) {

        this.xw.startElement("properties");
        this.addProperty("descriptor", this.reportObj.descriptor);
        this.addProperty("parallel", this.reportObj.parallel);
        this.addProperty("driver", this.reportObj.driver);
        this.addProperty("browser", this.reportObj.browser);
        this.addProperty("reuseSession", this.reportObj.reuseSession);
        this.addProperty("activeSeleniumSessionCount", wdSessions.length);
        this.addProperty("seleniumSessionIds", wdSessions.join());
        this.addProperty("group", this.reportObj.group);
        this.addProperty("testName", this.reportObj.testName);
        this.xw.endElement();
        //collecting all report
        strReport = xw.toString();

        //starting report root
        xwRoot.startDocument();
        xwRoot.startElement("testsuite");
        xwRoot.writeAttribute('failures', this.failCount.toString());
        xwRoot.writeAttribute('time', this.totalTimeTaken.toString());
        xwRoot.writeAttribute('errors', this.errorCount.toString());
        xwRoot.writeAttribute('skipped', this.skipCount.toString());
        xwRoot.writeAttribute('tests', this.totalCount.toString());
        xwRoot.writeAttribute('name', testSuiteName.toString());
        xwRoot.text("$$report$$");
        xwRoot.endElement();
        xwRoot.endDocument();
        strJunitReport = xwRoot.toString().replace("$$report$$", strReport);

        xmlReportName = path.resolve(global.reportFolder, 'arrow-report', xmlReportName);
        jsonReportName = path.resolve(global.reportFolder, 'arrow-report', jsonReportName);

        log('\n');
        writeFile(xmlReportName, strJunitReport);

        //writing json file
        for (i = 0; i < testSessions.length; i = i + 1) {
            jsonReport[testSessions[i].driver.testName] = JSON.parse(JSON.stringify(testSessions[i].driver.getReports()));
        }
        jsonReport.testSuiteName = testSuiteName;
        writeFile(jsonReportName, JSON.stringify(jsonReport));
        log('\n');

    }

};

ReportManager.prototype.writeTimeReport = function () {

    var timeReportJsonStr,
        descriptor,
        testSessionTimeArr,
        testName;

    timeReportJsonStr = '{ "descriptors" : [';

    for (descriptor in this.timeReport) {

        timeReportJsonStr += "{";
        timeReportJsonStr += ('"descriptor": ' + ' "' + descriptor + '"' + ' ,');
        timeReportJsonStr += ('"time": ' + ' "' + this.timeReport[descriptor].timeTaken + ' seconds' + '",');

        testSessionTimeArr = this.timeReport[descriptor].testSessionTimeArr;

        timeReportJsonStr += '"tests": [';

        for (testName in testSessionTimeArr) {
            timeReportJsonStr += '{';
            timeReportJsonStr += ('"Testname" :' + ' "' + testName + '"' + ',');
            timeReportJsonStr += ('"Time" :' + ' "' + testSessionTimeArr[testName].timeTaken + ' seconds' + '"');
            timeReportJsonStr += '} ,';
        }

        if (timeReportJsonStr.charAt(timeReportJsonStr.length - 1) === ",") {
            timeReportJsonStr = timeReportJsonStr.slice(0, -1);
        }

        timeReportJsonStr += " ] } ,";
    }

    if (timeReportJsonStr.charAt(timeReportJsonStr.length - 1) === ",") {
        timeReportJsonStr = timeReportJsonStr.slice(0, -1);
    }

    timeReportJsonStr += ('] ,"Total time":' + ' "' + this.totalTimeTaken + ' seconds' + '" ');
    timeReportJsonStr += ' }';

    fs.writeFileSync(path.resolve(global.reportFolder, 'arrow-report', 'timeReport.json'), timeReportJsonStr, 'utf8');

};

module.exports = ReportManager;
<|endoftext|>


<commit_before>var EtherSheetService = require('./ethersheet').EtherSheetService;

module.exports = function(socket,io,config){
  var es = new EtherSheetService(config);

<commit_msg>removing some foo<commit_after><|endoftext|>


<commit_before>/**
  This file is part of the "FnordMetric" project
    Copyright (c) 2014 Laura Schlimmer
    Copyright (c) 2014 Paul Asmuth, Google Inc.

  FnordMetric is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License v3.0. You should have received a
  copy of the GNU General Public License along with this program. If not, see
  <http://www.gnu.org/licenses/>.
**/
var ModalComponent = function() {
  this.createdCallback = function() {
    var base = this;

    //customisable
    this.closeElems = [
      this.querySelector("fn-modal-close-icon"), this.parentNode
    ];

    this.closeElems.forEach(function(elem) {
      if (elem) {
        elem.onclick = function() {
          base.close();
        }
      }
    });

    this.onclick = function(e) {
      e.stopPropagation();
    };
  };

  this.keyListener;

  this.listener = function(e) {
    //ESC
    if (e.keyCode == 27) {
      this.close();
    }
  };

  this.show = function() {
    console.log("show modal");
    var dimmer = this.parentNode;
    if (dimmer && dimmer.tagName == 'FN-MODAL-DIMMER') {
      dimmer.setAttribute('data-active', 'active');
    } else {
      this.setAttribute('data-active', 'active');
    }

    //place modal
    var height = this.getBoundingClientRect().height;
    var mtop = ((window.innerHeight - height) / 4);
    this.style.marginTop = mtop + "px";

    var _this = this;
    this.keyListener = this.listener.bind(this);
    document.addEventListener('keyup', _this.keyListener, false);
  };

  this.close = function() {
    var dimmer = this.parentNode;
    if (dimmer) {
      dimmer.removeAttribute('data-active');
    } else {
      this.removeAttribute('data-active');
    }

    var _this = this;
    document.removeEventListener('keyup', _this.keyListener, false);
  };
};

var proto = Object.create(HTMLElement.prototype);
ModalComponent.apply(proto);
document.registerElement("fn-modal", { prototype: proto });
<commit_msg>remove debug print<commit_after>/**
  This file is part of the "FnordMetric" project
    Copyright (c) 2014 Laura Schlimmer
    Copyright (c) 2014 Paul Asmuth, Google Inc.

  FnordMetric is free software: you can redistribute it and/or modify it under
  the terms of the GNU General Public License v3.0. You should have received a
  copy of the GNU General Public License along with this program. If not, see
  <http://www.gnu.org/licenses/>.
**/
var ModalComponent = function() {
  this.createdCallback = function() {
    var base = this;

    //customisable
    this.closeElems = [
      this.querySelector("fn-modal-close-icon"), this.parentNode
    ];

    this.closeElems.forEach(function(elem) {
      if (elem) {
        elem.onclick = function() {
          base.close();
        }
      }
    });

    this.onclick = function(e) {
      e.stopPropagation();
    };
  };

  this.keyListener;

  this.listener = function(e) {
    //ESC
    if (e.keyCode == 27) {
      this.close();
    }
  };

  this.show = function() {
    var dimmer = this.parentNode;
    if (dimmer && dimmer.tagName == 'FN-MODAL-DIMMER') {
      dimmer.setAttribute('data-active', 'active');
    } else {
      this.setAttribute('data-active', 'active');
    }

    //place modal
    var height = this.getBoundingClientRect().height;
    var mtop = ((window.innerHeight - height) / 4);
    this.style.marginTop = mtop + "px";

    var _this = this;
    this.keyListener = this.listener.bind(this);
    document.addEventListener('keyup', _this.keyListener, false);
  };

  this.close = function() {
    var dimmer = this.parentNode;
    if (dimmer) {
      dimmer.removeAttribute('data-active');
    } else {
      this.removeAttribute('data-active');
    }

    var _this = this;
    document.removeEventListener('keyup', _this.keyListener, false);
  };
};

var proto = Object.create(HTMLElement.prototype);
ModalComponent.apply(proto);
document.registerElement("fn-modal", { prototype: proto });
<|endoftext|>


<commit_before>const {
        DefinePlugin,
        ProgressPlugin
      }                          = require("webpack");
const ScriptExtHtmlWebpackPlugin = require("script-ext-html-webpack-plugin");
const StyleLintPlugin            = require("stylelint-webpack-plugin");
const {
        root,
        DEFAULT_RESOLVE_EXTENSIONS,
        NODE_CONFIG,
        getHtmlTemplatePlugin,
        getLoaderOptionsPlugin,
        getPerformanceOptions,
        getDefaultContextReplacementPlugin,
        getTsCheckerPlugin,
        RULE_LIB_SOURCE_MAP_LOADING,
        RULE_TS_LOADING,
        RULE_HTML_LOADING,
        RULE_MAIN_SASS_LOADING,
        RULE_COMPONENT_SASS_LOADING
      }                          = require("./constants");

/**
 * It might seem a little bit suspicious to use a mode-specific parameterized function in a "common"
 * config part. However, there are some plugins (HTML, LoaderOptions, ...) that cannot be easily merged,
 * even if provided by different modes, since only the parameters passed to them differ and not the plugins
 * themselves. Thus, we're using the `isDev` parameter to determine the exact target mode and simplify the
 * option details this way.
 * @param env Bundle environment options.
 */
module.exports = function (env) {
  const isDev  = env.isDev,
        useAot = env.useAot;

  const plugins = [
    // HTML plugin to generate proper index.html files w.r.t. the output of this build.
    getHtmlTemplatePlugin(isDev),
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: "defer"
    }),
    // Plugin to provide options to our loaders.
    getLoaderOptionsPlugin(isDev),
    /**
     * Plugin to define several variables. "process.env.NODE_ENV" is forwarded so that libraries may
     * react on it (e.g. by skipping some of their code). Please keep in mind that this is only possible
     * since our node config enables shimming the "process" variable.
     *
     * Note: Webpack is capable of conditionally dropping code w.r.t. these variables.
     * E.g. if a variable `ENV` is defined as `"whatever"`, and you have some code like:
     *
     *     if (ENV !== "whatever") {...}
     *
     * Then the code inside the braces will be dropped during the bundle process.
     * We're using this for conditionally executing development / production code.
     */
    new DefinePlugin({
      ENV: JSON.stringify(process.env.NODE_ENV || "development"),
      "process.env": {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV || "development")
      }
    }),
    // Plugin for displaying bundle process stage.
    new ProgressPlugin(),
    getTsCheckerPlugin(env),
    new StyleLintPlugin({
      quiet: false,
      failOnError: !isDev,
      configFile: root(".stylelintrc"),
      files: "src/**/*.scss",
      syntax: "scss"
    })
  ];

  if (!useAot) {
    // Fix the angular2 context w.r.t. to webpack and the usage of System.import in their "load a component lazily" code.
    // Note: Since a version > 1.2.4 of the @ngtools/webpack plugin, the context replacement conflicts with it (seems to deal with it itself).
    // Thus, we only add this plugin in case we're NOT aiming at AoT compilation.
    plugins.push(getDefaultContextReplacementPlugin());
  }

  return {
    entry: {
      bundle: root("src/main.ts")
    },
    /**
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {
      /**
       * An array of extensions that should be used to resolve modules.
       * Note that this only affects files that are referenced <without> a particular extension.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: DEFAULT_RESOLVE_EXTENSIONS
    },
    /**
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {
      /**
       * An array of rules to be applied..
       * Note that the syntax has changed in 2.1.0-beta.24 : https://github.com/webpack/webpack/releases/tag/v2.1.0-beta.24
       * Since this release, you no longer have to define preloaders and postloaders separately; just add
       * `enforce: "pre"` or `enforce: "post"` to a particular rule.
       *
       * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
       */
      rules: [
        RULE_LIB_SOURCE_MAP_LOADING,
        RULE_TS_LOADING, // This will get overridden by RULE_TS_AOT_LOADING if AoT mode is activated.
        RULE_HTML_LOADING,
        RULE_MAIN_SASS_LOADING(isDev),
        RULE_COMPONENT_SASS_LOADING
      ]
    },
    /**
     * Include polyfills or mocks for various node stuff
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: NODE_CONFIG,
    /**
     * Any plugins to be used in this build.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: plugins,
    performance: getPerformanceOptions(!isDev)
  };
};<commit_msg>fix(stylelint): Avoid duplicate linter output.<commit_after>const {
        DefinePlugin,
        ProgressPlugin
      }                          = require("webpack");
const ScriptExtHtmlWebpackPlugin = require("script-ext-html-webpack-plugin");
const StyleLintPlugin            = require("stylelint-webpack-plugin");
const {
        root,
        DEFAULT_RESOLVE_EXTENSIONS,
        NODE_CONFIG,
        getHtmlTemplatePlugin,
        getLoaderOptionsPlugin,
        getPerformanceOptions,
        getDefaultContextReplacementPlugin,
        getTsCheckerPlugin,
        RULE_LIB_SOURCE_MAP_LOADING,
        RULE_TS_LOADING,
        RULE_HTML_LOADING,
        RULE_MAIN_SASS_LOADING,
        RULE_COMPONENT_SASS_LOADING
      }                          = require("./constants");

/**
 * It might seem a little bit suspicious to use a mode-specific parameterized function in a "common"
 * config part. However, there are some plugins (HTML, LoaderOptions, ...) that cannot be easily merged,
 * even if provided by different modes, since only the parameters passed to them differ and not the plugins
 * themselves. Thus, we're using the `isDev` parameter to determine the exact target mode and simplify the
 * option details this way.
 * @param env Bundle environment options.
 */
module.exports = function (env) {
  const isDev  = env.isDev,
        useAot = env.useAot;

  const plugins = [
    // HTML plugin to generate proper index.html files w.r.t. the output of this build.
    getHtmlTemplatePlugin(isDev),
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: "defer"
    }),
    // Plugin to provide options to our loaders.
    getLoaderOptionsPlugin(isDev),
    /**
     * Plugin to define several variables. "process.env.NODE_ENV" is forwarded so that libraries may
     * react on it (e.g. by skipping some of their code). Please keep in mind that this is only possible
     * since our node config enables shimming the "process" variable.
     *
     * Note: Webpack is capable of conditionally dropping code w.r.t. these variables.
     * E.g. if a variable `ENV` is defined as `"whatever"`, and you have some code like:
     *
     *     if (ENV !== "whatever") {...}
     *
     * Then the code inside the braces will be dropped during the bundle process.
     * We're using this for conditionally executing development / production code.
     */
    new DefinePlugin({
      ENV: JSON.stringify(process.env.NODE_ENV || "development"),
      "process.env": {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV || "development")
      }
    }),
    // Plugin for displaying bundle process stage.
    new ProgressPlugin(),
    getTsCheckerPlugin(env),
    new StyleLintPlugin({
      failOnError: !isDev,
      configFile: root(".stylelintrc"),
      files: "src/**/*.scss",
      syntax: "scss"
    })
  ];

  if (!useAot) {
    // Fix the angular2 context w.r.t. to webpack and the usage of System.import in their "load a component lazily" code.
    // Note: Since a version > 1.2.4 of the @ngtools/webpack plugin, the context replacement conflicts with it (seems to deal with it itself).
    // Thus, we only add this plugin in case we're NOT aiming at AoT compilation.
    plugins.push(getDefaultContextReplacementPlugin());
  }

  return {
    entry: {
      bundle: root("src/main.ts")
    },
    /**
     * Options affecting the resolving of modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#resolve
     */
    resolve: {
      /**
       * An array of extensions that should be used to resolve modules.
       * Note that this only affects files that are referenced <without> a particular extension.
       *
       * See: http://webpack.github.io/docs/configuration.html#resolve-extensions
       */
      extensions: DEFAULT_RESOLVE_EXTENSIONS
    },
    /**
     * Options affecting the normal modules.
     *
     * See: http://webpack.github.io/docs/configuration.html#module
     */
    module: {
      /**
       * An array of rules to be applied..
       * Note that the syntax has changed in 2.1.0-beta.24 : https://github.com/webpack/webpack/releases/tag/v2.1.0-beta.24
       * Since this release, you no longer have to define preloaders and postloaders separately; just add
       * `enforce: "pre"` or `enforce: "post"` to a particular rule.
       *
       * See: http://webpack.github.io/docs/configuration.html#module-preloaders-module-postloaders
       */
      rules: [
        RULE_LIB_SOURCE_MAP_LOADING,
        RULE_TS_LOADING, // This will get overridden by RULE_TS_AOT_LOADING if AoT mode is activated.
        RULE_HTML_LOADING,
        RULE_MAIN_SASS_LOADING(isDev),
        RULE_COMPONENT_SASS_LOADING
      ]
    },
    /**
     * Include polyfills or mocks for various node stuff
     *
     * See: https://webpack.github.io/docs/configuration.html#node
     */
    node: NODE_CONFIG,
    /**
     * Any plugins to be used in this build.
     *
     * See: http://webpack.github.io/docs/configuration.html#plugins
     */
    plugins: plugins,
    performance: getPerformanceOptions(!isDev)
  };
};<|endoftext|>


<commit_before>var SysLogger = require('ain2');
var console = new SysLogger({tag: 's3rp', facility: 'local2'});

var sys     = require('sys'),
    http    = require('http'),
    port    = 8000,
    upstreamHost = process.argv[2];

var main = function() {
    http.createServer(handle_request).listen(port);
    console.log("101\tSTART\t-\t-\treverse proxy to " + upstreamHost + " http://localhost:" + port );
};

var handle_request = function (client_request, client_response) {
    var localhost = client_request.headers.host;
    client_request.headers.host = upstreamHost;

    var options = {
	host: upstreamHost,
	port: 80,
	method: client_request.method,
        path: client_request.url,
        headers: client_request.headers
    };
    var upstream_request = http.request(options);

    client_request.addListener("data", function(chunk) {
        upstream_request.write(chunk)
    });
    client_request.addListener("end", function() {
        upstream_request.end();
    });

    upstream_request.addListener("response", function (upstream_response) {
        proxy_pass_reverse(upstream_response, localhost);
        client_response.writeHead(
            upstream_response.statusCode,
            upstream_response.headers
        );
        var size = 0;
        upstream_response.addListener("data", function(chunk) {
            client_response.write(chunk);
            size += chunk.length;
        });
        upstream_response.addListener("end", function() {
	    console.log(upstream_response.statusCode +"\t"+ client_request.method + "\t" + client_request.url + "\t" + size);
            client_response.end();
        });
    });
};

// Last-Modifiedヘッダを抜き出して、それをx-last-modifiedとしてみた
var proxy_pass_reverse = function(upstream_response, localhost) {
    var xlm = upstream_response.headers["x-amz-meta-mtime"];
    if (xlm) {
	upstream_response.headers['last-modified'] = xlm;
	upstream_response.headers['server'] = "s3rp";
    }
};

main();
<commit_msg>listen only 127.0.0.1:port<commit_after>var SysLogger = require('ain2');
var console = new SysLogger({tag: 's3rp', facility: 'local2'});

var sys     = require('sys'),
    http    = require('http'),
    port    = 8000,
    upstreamHost = process.argv[2];

var main = function() {
    http.createServer(handle_request).listen(port, '127.0.0.1');
    console.log("101\tSTART\t-\t-\treverse proxy to " + upstreamHost + " http://localhost:" + port );
};

var handle_request = function (client_request, client_response) {
    var localhost = client_request.headers.host;
    client_request.headers.host = upstreamHost;

    var options = {
	host: upstreamHost,
	port: 80,
	method: client_request.method,
        path: client_request.url,
        headers: client_request.headers
    };
    var upstream_request = http.request(options);

    client_request.addListener("data", function(chunk) {
        upstream_request.write(chunk)
    });
    client_request.addListener("end", function() {
        upstream_request.end();
    });

    upstream_request.addListener("response", function (upstream_response) {
        proxy_pass_reverse(upstream_response, localhost);
        client_response.writeHead(
            upstream_response.statusCode,
            upstream_response.headers
        );
        var size = 0;
        upstream_response.addListener("data", function(chunk) {
            client_response.write(chunk);
            size += chunk.length;
        });
        upstream_response.addListener("end", function() {
	    console.log(upstream_response.statusCode +"\t"+ client_request.method + "\t" + client_request.url + "\t" + size);
            client_response.end();
        });
    });
};

// Last-Modifiedヘッダを抜き出して、それをx-last-modifiedとしてみた
var proxy_pass_reverse = function(upstream_response, localhost) {
    var xlm = upstream_response.headers["x-amz-meta-mtime"];
    if (xlm) {
	upstream_response.headers['last-modified'] = xlm;
	upstream_response.headers['server'] = "s3rp";
    }
};

main();
<|endoftext|>


<commit_before>function customCredit(info) {
  var default_info = {
    "ttl" : 20,
    "name": "puff",
    "frame" : 0,
    "frame_n" : 4,
    "delay" : 20,
    "delayN" : 20,
    "x" : 0,
    "y" : 0,
    "w" : 4,
    "h" : 4,
    "action" : "once" // loop, etc.
  };

  this.info = ((typeof info === "undefined") ? default_info : info);

  this.ttl = this.info.ttl;
  this.x = this.info.x;
  this.y = this.info.y;

  this.credit_text = [];
  this.credit_idx = 0;

  var msg = [
    "Main overworld tileset by....\n" +
    "             interdimensional\n" +
    "\n" +
    "Main dungeon tileset by......\n" +
    "                         Buch\n",

    "Music by.....................\n" +
    "                      Airglow\n",
    "Programming by ..............\n" +
    "                      abetusk",
    "All code under agpl",
    "All art under\n" +
    "  cc by, cc by sa\n" +
    "  or cc zero\n",
    "All music under cc by sa",
    "See credits.txt for\n" +
    " full list of credits",
    "dolor",
  ];

  for (var i=0; i<msg.length; i++) {
    this.credit_text.push( new messageBubble({
      x:this.x,
      y:this.y-16,
      easeIn: "fade",
      easeOut: "fade",
      origin: "lower_left",
      style: "center",
      message: msg[i]
    }) );
    this.credit_text[0].text_src_y = 6;
  }

  this.delay = 0;
  this.delay_state = -1;
  this.delayTrigger = [60, 240, 120];

}

customCredit.prototype.update = function() {
  if (this.ttl<=0) { return; }

  var x = 100;
  var y = 200;
  var scale = 12;

  if (this.delay_state == -1) {
    this.delay_state = 0;
    this.credit_text[0].start({x:x, y:y, bubble_type:"none", scale:scale});
    this.credit_text[0].text_src_y = 6;
  }

  this.delay++;
  if (this.delay >= this.delayTrigger[this.delay_state]) {
    this.delay_state = (this.delay_state + 1)%3;
    if (this.delay_state == 0) {
      this.credit_idx++;
      if (this.credit_idx >= this.credit_text.length) {
        this.credit_idx = 0;
        this.ttl=0;
      }

      this.credit_text[this.credit_idx].start({x:x, y:y, bubble_type:"none", scale:scale});
      this.credit_text[this.credit_idx].text_src_y = 6;

    } else if (this.delay_state==2) {
      this.credit_text[this.credit_idx].stop();
    }

    this.delay=0;
  }

  this.credit_text[this.credit_idx].update();
}

customCredit.prototype.draw = function() {
  if (this.ttl<=0) { return; }

  this.credit_text[this.credit_idx].draw();
}
<commit_msg>fiddling<commit_after>function customCredit(info) {
  var default_info = {
    "ttl" : 20,
    "name": "puff",
    "frame" : 0,
    "frame_n" : 4,
    "delay" : 20,
    "delayN" : 20,
    "x" : 0,
    "y" : 0,
    "w" : 4,
    "h" : 4,
    "action" : "once" // loop, etc.
  };

  this.info = ((typeof info === "undefined") ? default_info : info);

  this.ttl = this.info.ttl;
  this.x = this.info.x;
  this.y = this.info.y;

  this.credit_text = [];
  this.credit_idx = 0;

  var msg = [
    "Main overworld tileset by ...\n" +
    "   interdimensional\n",
    "Main dungeon tileset by ...\n" +
    "   Buch\n",
    "Music by ...\n" +
    "   Airglow\n",
    "Programming by ...\n" +
    "   abetusk",
    "All code under agpl",
    "All art under\n" +
    "  cc by, cc by sa\n" +
    "  or cc zero\n",
    "All music under cc by sa",
    "See credits.txt for\n" +
    " full list of credits",
    "dolor",
  ];

  for (var i=0; i<msg.length; i++) {
    this.credit_text.push( new messageBubble({
      x:this.x,
      y:this.y-16,
      easeIn: "fade",
      easeOut: "fade",
      origin: "lower_left",
      style: "center",
      message: msg[i]
    }) );
    this.credit_text[0].text_src_y = 6;
  }

  this.delay = 0;
  this.delay_state = -1;
  this.delayTrigger = [60, 240, 120];

}

customCredit.prototype.update = function() {
  if (this.ttl<=0) { return; }

  var x = 100;
  var y = 200;
  var scale = 12;

  if (this.delay_state == -1) {
    this.delay_state = 0;
    this.credit_text[0].start({x:x, y:y, bubble_type:"none", scale:scale});
    this.credit_text[0].text_src_y = 6;
  }

  this.delay++;
  if (this.delay >= this.delayTrigger[this.delay_state]) {
    this.delay_state = (this.delay_state + 1)%3;
    if (this.delay_state == 0) {
      this.credit_idx++;
      if (this.credit_idx >= this.credit_text.length) {
        this.credit_idx = 0;
        this.ttl=0;
      }

      this.credit_text[this.credit_idx].start({x:x, y:y, bubble_type:"none", scale:scale});
      this.credit_text[this.credit_idx].text_src_y = 6;

    } else if (this.delay_state==2) {
      this.credit_text[this.credit_idx].stop();
    }

    this.delay=0;
  }

  this.credit_text[this.credit_idx].update();
}

customCredit.prototype.draw = function() {
  if (this.ttl<=0) { return; }

  this.credit_text[this.credit_idx].draw();
}
<|endoftext|>


<commit_before>exports = module.exports = function(csrfProtection) {
  var path = require('path');

  function prompt(req, res, next) {
    res.locals.state = req.query.state;
    res.locals.csrfToken = req.csrfToken();

    console.log(req.session);
    var view = path.join(__dirname, '../../../views/oob/prompt.ejs');
    console.log(view);

    //res.render('loginx');
    res.render(view);
  }

  return [
    csrfProtection(),
    prompt
  ];
};

exports['@require'] = [
  'http://i.bixbyjs.org/http/middleware/csrfProtection'
];
<commit_msg>Loading authenticators.<commit_after>exports = module.exports = function(Authenticators, initialize, csrfProtection) {
  var path = require('path');

  function loadAuthenticators(req, res, next) {
    // TODO: Determine user correctly.
    var user = req.user;
    user = { id: '1' }

    Authenticators.list(user, function(err, authnrs) {
      if (err) { return next(err); }
      res.locals.authnrs = authnrs;

      if (!authnrs || authnrs.length == 0 || authnrs[0].active === false) {
        // TODO: Make this a better error.
        res.json({ error: 'enrollment_required' });
        return;
      }

      next();
    });
  }

  function selectAuthenticator(req, res, next) {
    req.locals.authnr = res.locals.authnrs[0];
    next();
  }

  function prompt(req, res, next) {
    res.locals.state = req.query.state;
    res.locals.csrfToken = req.csrfToken();

    console.log(req.session);
    var view = path.join(__dirname, '../../../views/oob/prompt.ejs');
    console.log(view);

    //res.render('loginx');
    res.render(view);
  }

  return [
    initialize(),
    csrfProtection(),
    loadAuthenticators,
    selectAuthenticator,
    prompt
  ];
};

exports['@require'] = [
  'http://schemas.authnomicon.org/js/login/mfa/opt/auth0/UserAuthenticatorsDirectory',
  'http://i.bixbyjs.org/http/middleware/initialize',
  'http://i.bixbyjs.org/http/middleware/csrfProtection'
];
<|endoftext|>


<commit_before>/**
 * Created by AlexanderC on 5/25/15.
 */

'use strict';

/**
 * Base exception
 */
export class Exception extends Error {
  /**
   * @returns {String}
   */
  static get CODE_KEY() {
    return '_deep_error_code_';
  }

  /**
   * @returns {Number}
   */
  static get DEFAULT_CODE() {
    return 400;
  }

  /**
   * @param {String} message
   * @param {Number} code
   */
  constructor(message, code = null) {
    super();

    if (Error.hasOwnProperty('captureStackTrace')) {
      Error.captureStackTrace(this, this.constructor);
    } else {
      Object.defineProperty(this, 'stack', {
        value: (new Error()).stack,
      });
    }

    Object.defineProperty(this, 'message', {
      value: message,
    });

    // It's used to map error codes to API Gateway http status codes
    this._code = code;
  }

  /**
   * @returns {String}
   */
  get name() {
    return this.constructor.name;
  }

  /**
   * @param {Number} code
   */
  set code(code) {
    this._code = code;
  }

  /**
   * @returns {Number}
   */
  get code() {
    return this._code;
  }
}
<commit_msg># Fix babel@6 issue: `instanceof check` for error objects<commit_after>/**
 * Created by AlexanderC on 5/25/15.
 */

'use strict';

/**
 * Base exception
 */
export class Exception extends Extendable(Error) {
  /**
   * @returns {String}
   */
  static get CODE_KEY() {
    return '_deep_error_code_';
  }

  /**
   * @returns {Number}
   */
  static get DEFAULT_CODE() {
    return 400;
  }

  /**
   * @param {String} message
   * @param {Number} code
   */
  constructor(message, code = null) {
    super();

    if (Error.hasOwnProperty('captureStackTrace')) {
      Error.captureStackTrace(this, this.constructor);
    } else {
      Object.defineProperty(this, 'stack', {
        value: (new Error()).stack,
      });
    }

    Object.defineProperty(this, 'message', {
      value: message,
    });

    // It's used to map error codes to API Gateway http status codes
    this._code = code;
  }

  /**
   * @returns {String}
   */
  get name() {
    return this.constructor.name;
  }

  /**
   * @param {Number} code
   */
  set code(code) {
    this._code = code;
  }

  /**
   * @returns {Number}
   */
  get code() {
    return this._code;
  }
}

// Fixes babel@6 issue: https://phabricator.babeljs.io/T3083
function Extendable(errorClass){
  function Extendable(){
    errorClass.apply(this, arguments);
  }

  Extendable.prototype = Object.create(errorClass.prototype);
  Object.setPrototypeOf(Extendable, errorClass);

  return Extendable;
}
<|endoftext|>


<commit_before>var fibonacciSquareSketch = function ( fsq ) {

  var f0, f1, x, y, f0Scaled, f1Scaled;
  var scale = 3;

  fsq.setup = function() {
    fsq.createCanvas(500, 500);
    fsq.frameRate(10);
    fsq.background(0);
    fsq.noFill();
    fsq.stroke(255);
    fsq.smooth();
    fsq.noLoop();
  };

  fsq.draw = function() {
    fsq.rect(x, y, f1Scaled, f1Scaled);

    //iterate up the fibonacci sequence
    var fibStep = fsq.fibIterator(f0Scaled, f1Scaled);
    f0Scaled = fibStep[0];
    f1Scaled = fibStep[1];

    //scale the starting point of the next square
    x = x + (2 * f0Scaled);
    y = y + (2 * f0Scaled);
  };

  fsq.fibIterator = function( fI, fJ ) {
    fibs = [
      fJ,
      fI + fJ
    ];

    return fibs;
  };

  fsq.mousePressed = function() {
    x = fsq.mouseX;
    y = fsq.mouseY;

    f0 = 0;
    f1 = 1;
    f0Scaled = f0 * scale;
    f1Scaled = f1 * scale;

    fsq.loop();
  };

  fsq.mouseReleased = function() {
    fsq.noLoop();
  };

};

var fibonacciSquare = new p5(fibonacciSquareSketch, 'fibonacci-square');
<commit_msg>Attempting to correct active mouse across all canvases -- Incomplete<commit_after>var fibonacciSquareSketch = function ( fsq ) {

  var canvas, f0, f1, x, y, f0Scaled, f1Scaled;
  var scale = 3;

  fsq.setup = function() {
    canvas = fsq.createCanvas(500, 500);
    fsq.frameRate(10);
    fsq.background(0);
    fsq.noFill();
    fsq.stroke(255);
    fsq.smooth();
    fsq.noLoop();
  };

  fsq.draw = function() {

    fsq.rect(x, y, f1Scaled, f1Scaled);

    //iterate up the fibonacci sequence
    var fibStep = fsq.fibIterator(f0Scaled, f1Scaled);
    f0Scaled = fibStep[0];
    f1Scaled = fibStep[1];

    //scale the starting point of the next square
    x = x + (2 * f0Scaled);
    y = y + (2 * f0Scaled);
  };

  fsq.fibIterator = function( fI, fJ ) {
    fibs = [
      fJ,
      fI + fJ
    ];

    return fibs;
  };

  fsq.mousePressed = function() {
    x = fsq.mouseX;
    y = fsq.mouseY;

    f0 = 0;
    f1 = 1;
    f0Scaled = f0 * scale;
    f1Scaled = f1 * scale;

    fsq.loop();
  };

  fsq.mouseReleased = function() {
    fsq.noLoop();
  };

};

var fibonacciSquare = new p5(fibonacciSquareSketch, 'fibonacci-square');
<|endoftext|>


<commit_before>"use strict";
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var userSchema = new Schema({
    name: {
        Type: String,
        required: true
    },
    email: {
        Type: String,
        required: true
    },
    username: {
        Type: String,
        required: true
    },
    dateAccessed: {
        Type: Date,
        default: Date.now
    },
    coverPhotoURL: {
        Type: String,
        required: true
    }
    facebook: Object,
    publicKey: {
        Type: String
    },
    token: {
        Type String
    }
});

mongoose.model('User', userSchema);
<commit_msg>Updated user Schema<commit_after>"use strict";
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var userSchema = new Schema({
    name: {
        Type: String,
        required: true
    },
    email: {
        Type: String
    },
    coverPhotoURL: {
        Type: String,
        required: true
    },
    facebook: Object,
    publicKey: {
        Type: String
    },
    token: {
        Type String,
        require: true
    }
});

mongoose.model('User', userSchema);
<|endoftext|>


<commit_before>
/**
 * A simulation of Particle Filter --
 * A representation of nonparametric implementation of the Bayes filter
 * @constructor
 * @param {int} particleCount - The total number of particles that can present in a time.
 * @param {OdometryModel} motionModel - The motion model that is used to calculate its motion over time.
 * @param {BeamModel} sensorModel - The sensor model that is used to measure environment over time.
 * @param {RobotState} robotState - The state of the robot while creating the particle filter
 */
function ParticleFilter(particleCount, motionModel, sensorModel, robotState){
    this.count = particleCount;
    // Init the array that stores particles
    this.particles = new Array(particleCount);

    this.motionModel = motionModel;
    this.sensorModel = sensorModel;

    if(typeof robotState !== 'undefined'){
        // If current robot state is already defined
        // generate initial particles around the robot
        for (var i = particleCount - 1; i >= 0; i--){
            this.particles[i] = new Particle(robotState.x, robotState.y, robotState.dir, 1);
        }
    }else{
    	// generate random particles within the map
        var weight = 1.0/particleCount;
        for (var i = particleCount - 1; i >= 0; i--){
            this.particles[i] = this.newParticle();
        }
    }
}

/**
 * Draws the particles on the context
 * @function
 * @param {Context} ctx - The context that the particles will be drawn on
 */
ParticleFilter.prototype.draw = function(ctx){
    for (var i = this.particles.length - 1; i >= 0; i--){
        this.particles[i].draw(ctx);
    }
};

/**
 * Regenerate all particles of the Particle filter
 * @function
 */
ParticleFilter.prototype.regenrateAll = function() {
    // generate random particles within the map
    var weight = 1.0/this.count;
    for (var i = this.count - 1; i >= 0; i--){
        this.particles[i] = this.newParticle();
    }
}

/**
 * Refill all particles of the Particle filter
 * @function
 */
ParticleFilter.prototype.refillAll = function() {
    // generate random particles within the map
    var weight = 1.0/this.count;
    while (this.particles.length < this.count){
        this.particles.push(this.newParticle());
    }
}

/**
 * Return a new random particle
 * @function
 * @return {Particle} newParticle - A random generated particle
 */
ParticleFilter.prototype.newParticle = function() {
    return new Particle(this.sensorModel.width*random(),
            this.sensorModel.height*random(), TWO_PI*random(), 1.0);
}

/**
 * Update the state of particles based on the odometry reading
 * @function
 * @param {Odometry} u - The odometry reading from the motion sensor
 * @param {float[]} z - An array of distance reading from the sensor
 */
ParticleFilter.prototype.update = function(u, z){
    if(typeof this.motionModel !== 'undefined')
        this.motionUpdate(u);

    if(typeof this.sensorModel !== 'undefined')
        this.sensorUpdate(z);
};

/**
 * Update the state of particles based on the odometry reading
 * @function
 * @param {Odometry} u - The odometry reading from the motion sensor
 */
ParticleFilter.prototype.motionUpdate = function(u){
    // Update the state of all particles base on the estimated motion
    for (var i = this.particles.length - 1; i >= 0; i--){
        var p = this.particles[i];
        var state = new RobotState(p.x, p.y, p.dir);
        // Draw sample from p(x_t, u, x_t-1)
        var newState = this.motionModel.sample(u, state);
        p.setState(newState);
    }
};

/**
 * Update the probabilities of particles based on the sensor readings
 * @function
 * @param {float[]} z - An array of distance reading from the sensor
 */
ParticleFilter.prototype.sensorUpdate = function(z){
    // Calculate the logs of weights
    for(var i = this.particles.length-1; i >= 0; i--){
        var p = this.particles[i];
        p.w = this.sensorModel.probability(z, new RobotState(p.x, p.y, p.dir));
    }

    // To ensure the probability is in the range of (0,1)
    // this.normalizeWeights();

    // Resample the particles
    this.normalizeWeights();
    this.resample(0.9);
};

/**
 * Resample a part of the particles base on input
 * @function
 * @param {float} percent - The ratio of which will be resampled
 */
ParticleFilter.prototype.resample = function(percent){
    // Initiate array for updated particles
    var z_t = new Array(this.count);

    // Resample most of all particles, the rest will be randomly generated
    const resNum = z_t.length * percent;

    const step = 1.0/resNum;

    var cur = random() * step;

    // Running sum
    var cumulativeProbability = this.particles[0].w;

    // For the first part, resample
    for(var i = 0, j = 0; i < resNum; i++){

   //      while(j < this.particles.length-1 && cumulativeProbability < cur){
			// j++;
			// cumulativeProbability += this.particles[j].w;
   //      }
        j++;
        // Elluminate low weight particles
        if (this.particles[j].w < 0.1) {
            z_t[i] = this.newParticle();
        } else {
            z_t[i] = this.particles[j];
        }
        // cur += step;
    }

    // regenerate the rest
    for (var i = resNum; i < this.count; i++){
        z_t[i] = this.newParticle();
    }

    //Assign it to particles
    this.particles = z_t;

    // this.refillAll();
};

/**
 * Normalize the weight of the particles to range (1,0)
 * @function
 */
ParticleFilter.prototype.normalizeWeights = function (){
	var max = 0;
	// Convert logs back to weights
	for(var i = this.particles.length-1; i >= 0; i--)
	{
		var p = this.particles[i];
		// Normalize the logs
		// p.w -= max;

		// Exponentiation to recover relative proportion
		// p.w = Math.exp(p.w);
		// sum += p.w;

        if (max<p.w) max = p.w;
	}

	if(max === 0)
	{
	    // If every particle has a probability of 0,
        // just regenrate all particles
        this.regenrateAll();
	}else
	{
	    // Otherwise normalize the weights
		this.particles.forEach(function(p){p.w /= max});
	}
};
<commit_msg>minor fix<commit_after>
/**
 * A simulation of Particle Filter --
 * A representation of nonparametric implementation of the Bayes filter
 * @constructor
 * @param {int} particleCount - The total number of particles that can present in a time.
 * @param {OdometryModel} motionModel - The motion model that is used to calculate its motion over time.
 * @param {BeamModel} sensorModel - The sensor model that is used to measure environment over time.
 * @param {RobotState} robotState - The state of the robot while creating the particle filter
 */
function ParticleFilter(particleCount, motionModel, sensorModel, robotState){
    this.count = particleCount;
    // Init the array that stores particles
    this.particles = new Array(particleCount);

    this.motionModel = motionModel;
    this.sensorModel = sensorModel;

    if(typeof robotState !== 'undefined'){
        // If current robot state is already defined
        // generate initial particles around the robot
        for (var i = particleCount - 1; i >= 0; i--){
            this.particles[i] = new Particle(robotState.x, robotState.y, robotState.dir, 1);
        }
    }else{
    	// generate random particles within the map
        var weight = 1.0/particleCount;
        for (var i = particleCount - 1; i >= 0; i--){
            this.particles[i] = this.newParticle();
        }
    }
}

/**
 * Draws the particles on the context
 * @function
 * @param {Context} ctx - The context that the particles will be drawn on
 */
ParticleFilter.prototype.draw = function(ctx){
    for (var i = this.particles.length - 1; i >= 0; i--){
        this.particles[i].draw(ctx);
    }
};

/**
 * Regenerate all particles of the Particle filter
 * @function
 */
ParticleFilter.prototype.regenrateAll = function() {
    // generate random particles within the map
    var weight = 1.0/this.count;
    for (var i = this.count - 1; i >= 0; i--){
        this.particles[i] = this.newParticle();
    }
}

/**
 * Refill all particles of the Particle filter
 * @function
 */
ParticleFilter.prototype.refillAll = function() {
    // generate random particles within the map
    var weight = 1.0/this.count;
    while (this.particles.length < this.count){
        this.particles.push(this.newParticle());
    }
}

/**
 * Return a new random particle
 * @function
 * @return {Particle} newParticle - A random generated particle
 */
ParticleFilter.prototype.newParticle = function() {
    return new Particle(this.sensorModel.width*random(),
            this.sensorModel.height*random(), TWO_PI*random(), 1.0);
}

/**
 * Update the state of particles based on the odometry reading
 * @function
 * @param {Odometry} u - The odometry reading from the motion sensor
 * @param {float[]} z - An array of distance reading from the sensor
 */
ParticleFilter.prototype.update = function(u, z){
    if(typeof this.motionModel !== 'undefined')
        this.motionUpdate(u);

    if(typeof this.sensorModel !== 'undefined')
        this.sensorUpdate(z);
};

/**
 * Update the state of particles based on the odometry reading
 * @function
 * @param {Odometry} u - The odometry reading from the motion sensor
 */
ParticleFilter.prototype.motionUpdate = function(u){
    // Update the state of all particles base on the estimated motion
    for (var i = this.particles.length - 1; i >= 0; i--){
        var p = this.particles[i];
        var state = new RobotState(p.x, p.y, p.dir);
        // Draw sample from p(x_t, u, x_t-1)
        var newState = this.motionModel.sample(u, state);
        p.setState(newState);
    }
};

/**
 * Update the probabilities of particles based on the sensor readings
 * @function
 * @param {float[]} z - An array of distance reading from the sensor
 */
ParticleFilter.prototype.sensorUpdate = function(z){
    // Calculate the logs of weights
    for(var i = this.particles.length-1; i >= 0; i--){
        var p = this.particles[i];
        p.w = this.sensorModel.probability(z, new RobotState(p.x, p.y, p.dir));
    }

    // To ensure the probability is in the range of (0,1)
    // this.normalizeWeights();

    // Resample the particles
    this.normalizeWeights();
    this.resample(0.9);
};

/**
 * Resample a part of the particles base on input
 * @function
 * @param {float} percent - The ratio of which will be resampled
 */
ParticleFilter.prototype.resample = function(percent){
    // Initiate array for updated particles
    var z_t = new Array(this.count);

    // Resample most of all particles, the rest will be randomly generated
    const resNum = z_t.length * percent;

    const step = 1.0/resNum;

    var cur = random() * step;

    // Running sum
    var cumulativeProbability = this.particles[0].w;

    // For the first part, resample
    for(var i = 0, j = 0; i < resNum; i++){

        while(j < this.particles.length-1 && cumulativeProbability < cur){
			j++;
			cumulativeProbability += this.particles[j].w;
        }
        // Elluminate low weight particles
        if (this.particles[j].w < 0.1) {
            z_t[i] = this.newParticle();
        } else {
            z_t[i] = this.particles[j];
        }
        // cur += step;
    }

    // regenerate the rest
    for (var i = resNum; i < this.count; i++){
        z_t[i] = this.newParticle();
    }

    //Assign it to particles
    this.particles = z_t;

    // this.refillAll();
};

/**
 * Normalize the weight of the particles to range (1,0)
 * @function
 */
ParticleFilter.prototype.normalizeWeights = function (){
	var max = 0;
	// Convert logs back to weights
	for(var i = this.particles.length-1; i >= 0; i--)
	{
		var p = this.particles[i];
		// Normalize the logs
		// p.w -= max;

		// Exponentiation to recover relative proportion
		// p.w = Math.exp(p.w);
		// sum += p.w;

        if (max<p.w) max = p.w;
	}

	if(max === 0)
	{
	    // If every particle has a probability of 0,
        // just regenrate all particles
        this.regenrateAll();
	}else
	{
	    // Otherwise normalize the weights
		this.particles.forEach(function(p){p.w /= max});
	}
};
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import {convertSampleValuesToSurveyQuestions} from "./utils/surveyUtils";
class InstitutionDashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            details:[]
        };
    };

    componentDidMount() {
        this.getProjectList();
        if (this.state.projectList.length>0) {
            this.setDetails();
        }
    }

    getProjectList = () => {
        //get projects
        fetch(this.props.documentRoot + "/get-all-projects?userId="
            + this.props.userId + "&institutionId=" + this.props.institutionId
        )
            .then(response => response.ok ? response.json() : Promise.reject(response))
            .then(data => this.setState({ projectList: data }))
            .catch(response => {
                console.log(response);
                alert("Error retrieving the project info. See console for details.");
            });
    }

    getProjectStats = (projectId) => {
        alert("hello");
        fetch(this.props.documentRoot + "/get-project-stats/" + projectId)
            .then(response => {
                if (response.ok) {
                    return response.json()
                } else {
                    console.log(response);
                    alert("Error retrieving project stats. See console for details.");
                }
            })
            .then(data => {
                const details = this.state.details;
                let x = {id:projectId, stats: data};
                details.push({ id:projectId, stats: data});
                this.setState({ details: details });
            });
        alert("project stats");

    };

    getProjectById = (projectId) => {
        alert("hey");
        fetch(this.props.documentRoot + "/get-project-by-id/" + projectId)
            .then(response => {
                if (response.ok) {
                    return response.json()
                } else {
                    console.log(response);
                    alert("Error retrieving the project info. See console for details.");
                }
            })
            .then(data => {
                if (data == "") {
                    alert("No project found with ID " + projectId + ".");
                    window.location = this.props.documentRoot + "/home";
                } else {
                    const details = this.state.details;
                    details.push({ id:projectId, numPlots:data.numPlots});
                    this.setState({details: details});
                }
            });
        alert(this.state.details);

    };

    setDetails = () => {
        let details = this.state.details;

        this.state.projectList.map( proj => {
            let x = {id:proj.id,projectDetails: {},stats:[]};
            fetch(this.props.documentRoot + "/get-project-by-id/" + proj.id)
                .then(response => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        console.log(response);
                        alert("Error retrieving the project info. See console for details.");
                    }
                })
                .then(data => {
                    if (data == "") {
                        alert("No project found with ID " + proj.id + ".");
                        window.location = this.props.documentRoot + "/home";
                    } else {
                        x.projectDetails = data;
                    }
                });
            fetch(this.props.documentRoot + "/get-project-stats/" + proj.id)
                .then(response => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        console.log(response);
                        alert("Error retrieving project stats. See console for details.");
                    }
                })
                .then(data => {
                    x.stats = data;
                });
            details.push(x);
        });
        this.setState({details: details});

    };

    render() {
        return (

Project Name

Project Stats

                        <Project projects={this.state.projectList} details={this.state.details}/>

        );
    }
}

function Project(props) {
    return props.projects.map((p, uid) =>

            {p.name}

                <ProjectStats details={props.details}/>

    );
}

function ProjectStats(props) {
    return (

                        Members
                        {props.details.stats? props.details.stats.members:""}

                        Contributors
                        {props.details.stats? props.details.stats.contributors:""}

                        Total Plots
                        {props.details.stats? props.details.projectDetails.numPlots:""}

                        Flagged Plots
                        {props.details.stats? props.details.stats.flaggedPlots:""}

                        Analyzed Plots
                        {props.details.stats? props.details.stats.analyzedPlots:""}

                        Unanalyzed Plots
                        {props.details.stats? props.details.stats.unanalyzedPlots:""}

    );
}

export function renderInstitutionDashboardPage(args) {
    ReactDOM.render(
        <InstitutionDashboard documentRoot={args.documentRoot} userId={args.userId} institutionId={args.institutionId}/>,
        document.getElementById("institution_dashboard")
    );
}
<commit_msg>working on dashboard<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import {convertSampleValuesToSurveyQuestions} from "./utils/surveyUtils";
class InstitutionDashboard extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            projectList: [],
            details:[]
        };
    };

    componentDidMount() {
        this.getProjectList();

    }
    componentDidUpdate(){
        if (this.state.projectList.length>0) {
            this.setDetails();
        }
    }

    getProjectList = () => {
        //get projects
        fetch(this.props.documentRoot + "/get-all-projects?userId="
            + this.props.userId + "&institutionId=" + this.props.institutionId
        )
            .then(response => response.ok ? response.json() : Promise.reject(response))
            .then(data => this.setState({ projectList: data }))
            .catch(response => {
                console.log(response);
                alert("Error retrieving the project info. See console for details.");
            });
    }

    getProjectStats = (projectId) => {
        alert("hello");
        fetch(this.props.documentRoot + "/get-project-stats/" + projectId)
            .then(response => {
                if (response.ok) {
                    return response.json()
                } else {
                    console.log(response);
                    alert("Error retrieving project stats. See console for details.");
                }
            })
            .then(data => {
                const details = this.state.details;
                let x = {id:projectId, stats: data};
                details.push({ id:projectId, stats: data});
                this.setState({ details: details });
            });
        alert("project stats");

    };

    getProjectById = (projectId) => {
        alert("hey");

        fetch(this.props.documentRoot + "/get-project-by-id/" + projectId)
            .then(response => {
                if (response.ok) {
                    return response.json()
                } else {
                    console.log(response);
                    alert("Error retrieving the project info. See console for details.");
                }
            })
            .then(data => {
                if (data == "") {
                    alert("No project found with ID " + projectId + ".");
                    window.location = this.props.documentRoot + "/home";
                } else {
                    const details = this.state.details;
                    details.push({ id:projectId, numPlots:data.numPlots});
                    this.setState({details: details});
                }
            });
        alert(this.state.details);

    };

    setDetails = () => {
        const details = [];
        this.state.projectList.map( proj => {
            let x = {id:proj.id,projectDetails: {},stats:[]};
            fetch(this.props.documentRoot + "/get-project-by-id/" + proj.id)
                .then(response => {
                    if (response.ok) {
                        return response.json()
                    } else {
                        console.log(response);
                        alert("Error retrieving the project info. See console for details.");
                    }
                })
                .then(data => {
                    if (data == "") {
                        alert("No project found with ID " + proj.id + ".");
                        window.location = this.props.documentRoot + "/home";
                    } else {
                        x.projectDetails = data;
                    }
                    fetch(this.props.documentRoot + "/get-project-stats/" + proj.id)
                        .then(response => {
                            if (response.ok) {
                                return response.json()
                            } else {
                                console.log(response);
                                alert("Error retrieving project stats. See console for details.");
                            }
                        })
                        .then(data => {
                            x.stats = data;
                        });
                });

            details.push(x);
        });
        this.setState({details: details});

    };

    render() {
        return (

Project Name

Project Stats

                        <Project projects={this.state.projectList} details={this.state.details}/>

        );
    }
}

function Project(props) {
    return props.projects.map((p, uid) =>

            {p.name}

                {props.details.filter(d => d.id === p.id).length > 0} && <ProjectStats details={props.details.find(d => d.id === p.id)}/>

    );
}

function ProjectStats(props) {
    return (

                        Members
                        {props.details.stats? props.details.stats.members:""}

                        Contributors
                        {props.details.stats? props.details.stats.contributors:""}

                        Total Plots
                        {props.details.stats? props.details.projectDetails.numPlots:""}

                        Flagged Plots
                        {props.details.stats? props.details.stats.flaggedPlots:""}

                        Analyzed Plots
                        {props.details.stats? props.details.stats.analyzedPlots:""}

                        Unanalyzed Plots
                        {props.details.stats? props.details.stats.unanalyzedPlots:""}

    );
}

export function renderInstitutionDashboardPage(args) {
    ReactDOM.render(
        <InstitutionDashboard documentRoot={args.documentRoot} userId={args.userId} institutionId={args.institutionId}/>,
        document.getElementById("institution_dashboard")
    );
}
<|endoftext|>