<commit_before>/**
 * @license almond 0.3.0 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/almond for details
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */

// Inserted to expose all modules
var almondAmdModules = {};
// Activate all modules at the end.
window.setTimeout(function () {
  var keys = Object.keys(almondAmdModules);
  require(keys);
}, 0);

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = almondAmdModules,
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice,
        jsSuffixRegExp = /\.js$/;

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap, lastIndex,
            foundI, foundStarMap, starI, i, j, part,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") {
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseParts = baseParts.slice(0, baseParts.length - 1);
                name = name.split('/');
                lastIndex = name.length - 1;

                // Node .js allowance:
                if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                    name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
                }

                name = baseParts.concat(name);

                //start trimDots
                for (i = 0; i < name.length; i += 1) {
                    part = name[i];
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            break;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            } else if (name.indexOf('./') === 0) {
                // No baseName, so this is ID is resolved relative
                // to baseUrl, pull off the leading dot.
                name = name.substring(2);
            }
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            var args = aps.call(arguments, 0);

            //If first arg is not require('string'), and there is only
            //one arg, it is the array form without a callback. Insert
            //a null so that the following concat is correct.
            if (typeof args[0] !== 'string' && args.length === 1) {
                args.push(null);
            }
            return req.apply(undef, args.concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) && !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index > -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relName) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relName));
            } else {
                name = normalize(name, relName);
            }
        } else {
            name = normalize(name, relName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i,
            args = [],
            callbackType = typeof callback,
            usingExports;

        //Use name if no relName
        relName = relName || name;

        //Call the callback to define the module, if necessary.
        if (callbackType === 'undefined' || callbackType === 'function') {
            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i += 1) {
                map = makeMap(deps[i], relName);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback ? callback.apply(defined[name], args) : undefined;

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, callback).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (config.deps) {
                req(config.deps, config.callback);
            }
            if (!callback) {
                return;
            }

            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        return req(cfg);
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) && !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());
<commit_msg>Bring auto-requiring into scope and document the difference in banner<commit_after>/**
 * NOTE: THIS FILE HAS BEEN MODIFIED FOR DUPLO. ALL MODULES ARE RUN (i.e.
 * `require()`ed) ON NEXT TICK TO MAKE SURE IT BEHAVES THE SAME AS CODE
 * GENERATED BY amdclean.
 *
 * @license almond 0.3.0 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved.
 * Available via the MIT or new BSD license.
 * see: http://github.com/jrburke/almond for details
 */
//Going sloppy to avoid 'use strict' string cost, but strict practices should
//be followed.
/*jslint sloppy: true */
/*global setTimeout: false */

var requirejs, require, define;
(function (undef) {
    var main, req, makeMap, handlers,
        defined = {},
        waiting = {},
        config = {},
        defining = {},
        hasOwn = Object.prototype.hasOwnProperty,
        aps = [].slice,
        jsSuffixRegExp = /\.js$/;

    // Activate all modules at the end.
    window.setTimeout(function () {
      require(Object.keys(waiting));
    }, 0);

    function hasProp(obj, prop) {
        return hasOwn.call(obj, prop);
    }

    /**
     * Given a relative module name, like ./something, normalize it to
     * a real name that can be mapped to a path.
     * @param {String} name the relative name
     * @param {String} baseName a real name that the name arg is relative
     * to.
     * @returns {String} normalized name
     */
    function normalize(name, baseName) {
        var nameParts, nameSegment, mapValue, foundMap, lastIndex,
            foundI, foundStarMap, starI, i, j, part,
            baseParts = baseName && baseName.split("/"),
            map = config.map,
            starMap = (map && map['*']) || {};

        //Adjust any relative paths.
        if (name && name.charAt(0) === ".") {
            //If have a base name, try to normalize against it,
            //otherwise, assume it is a top-level require that will
            //be relative to baseUrl in the end.
            if (baseName) {
                //Convert baseName to array, and lop off the last part,
                //so that . matches that "directory" and not name of the baseName's
                //module. For instance, baseName of "one/two/three", maps to
                //"one/two/three.js", but we want the directory, "one/two" for
                //this normalization.
                baseParts = baseParts.slice(0, baseParts.length - 1);
                name = name.split('/');
                lastIndex = name.length - 1;

                // Node .js allowance:
                if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
                    name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
                }

                name = baseParts.concat(name);

                //start trimDots
                for (i = 0; i < name.length; i += 1) {
                    part = name[i];
                    if (part === ".") {
                        name.splice(i, 1);
                        i -= 1;
                    } else if (part === "..") {
                        if (i === 1 && (name[2] === '..' || name[0] === '..')) {
                            //End of the line. Keep at least one non-dot
                            //path segment at the front so it can be mapped
                            //correctly to disk. Otherwise, there is likely
                            //no path mapping for a path starting with '..'.
                            //This can still fail, but catches the most reasonable
                            //uses of ..
                            break;
                        } else if (i > 0) {
                            name.splice(i - 1, 2);
                            i -= 2;
                        }
                    }
                }
                //end trimDots

                name = name.join("/");
            } else if (name.indexOf('./') === 0) {
                // No baseName, so this is ID is resolved relative
                // to baseUrl, pull off the leading dot.
                name = name.substring(2);
            }
        }

        //Apply map config if available.
        if ((baseParts || starMap) && map) {
            nameParts = name.split('/');

            for (i = nameParts.length; i > 0; i -= 1) {
                nameSegment = nameParts.slice(0, i).join("/");

                if (baseParts) {
                    //Find the longest baseName segment match in the config.
                    //So, do joins on the biggest to smallest lengths of baseParts.
                    for (j = baseParts.length; j > 0; j -= 1) {
                        mapValue = map[baseParts.slice(0, j).join('/')];

                        //baseName segment has  config, find if it has one for
                        //this name.
                        if (mapValue) {
                            mapValue = mapValue[nameSegment];
                            if (mapValue) {
                                //Match, update name to the new value.
                                foundMap = mapValue;
                                foundI = i;
                                break;
                            }
                        }
                    }
                }

                if (foundMap) {
                    break;
                }

                //Check for a star map match, but just hold on to it,
                //if there is a shorter segment match later in a matching
                //config, then favor over this star map.
                if (!foundStarMap && starMap && starMap[nameSegment]) {
                    foundStarMap = starMap[nameSegment];
                    starI = i;
                }
            }

            if (!foundMap && foundStarMap) {
                foundMap = foundStarMap;
                foundI = starI;
            }

            if (foundMap) {
                nameParts.splice(0, foundI, foundMap);
                name = nameParts.join('/');
            }
        }

        return name;
    }

    function makeRequire(relName, forceSync) {
        return function () {
            //A version of a require function that passes a moduleName
            //value for items that may need to
            //look up paths relative to the moduleName
            var args = aps.call(arguments, 0);

            //If first arg is not require('string'), and there is only
            //one arg, it is the array form without a callback. Insert
            //a null so that the following concat is correct.
            if (typeof args[0] !== 'string' && args.length === 1) {
                args.push(null);
            }
            return req.apply(undef, args.concat([relName, forceSync]));
        };
    }

    function makeNormalize(relName) {
        return function (name) {
            return normalize(name, relName);
        };
    }

    function makeLoad(depName) {
        return function (value) {
            defined[depName] = value;
        };
    }

    function callDep(name) {
        if (hasProp(waiting, name)) {
            var args = waiting[name];
            delete waiting[name];
            defining[name] = true;
            main.apply(undef, args);
        }

        if (!hasProp(defined, name) && !hasProp(defining, name)) {
            throw new Error('No ' + name);
        }
        return defined[name];
    }

    //Turns a plugin!resource to [plugin, resource]
    //with the plugin being undefined if the name
    //did not have a plugin prefix.
    function splitPrefix(name) {
        var prefix,
            index = name ? name.indexOf('!') : -1;
        if (index > -1) {
            prefix = name.substring(0, index);
            name = name.substring(index + 1, name.length);
        }
        return [prefix, name];
    }

    /**
     * Makes a name map, normalizing the name, and using a plugin
     * for normalization if necessary. Grabs a ref to plugin
     * too, as an optimization.
     */
    makeMap = function (name, relName) {
        var plugin,
            parts = splitPrefix(name),
            prefix = parts[0];

        name = parts[1];

        if (prefix) {
            prefix = normalize(prefix, relName);
            plugin = callDep(prefix);
        }

        //Normalize according
        if (prefix) {
            if (plugin && plugin.normalize) {
                name = plugin.normalize(name, makeNormalize(relName));
            } else {
                name = normalize(name, relName);
            }
        } else {
            name = normalize(name, relName);
            parts = splitPrefix(name);
            prefix = parts[0];
            name = parts[1];
            if (prefix) {
                plugin = callDep(prefix);
            }
        }

        //Using ridiculous property names for space reasons
        return {
            f: prefix ? prefix + '!' + name : name, //fullName
            n: name,
            pr: prefix,
            p: plugin
        };
    };

    function makeConfig(name) {
        return function () {
            return (config && config.config && config.config[name]) || {};
        };
    }

    handlers = {
        require: function (name) {
            return makeRequire(name);
        },
        exports: function (name) {
            var e = defined[name];
            if (typeof e !== 'undefined') {
                return e;
            } else {
                return (defined[name] = {});
            }
        },
        module: function (name) {
            return {
                id: name,
                uri: '',
                exports: defined[name],
                config: makeConfig(name)
            };
        }
    };

    main = function (name, deps, callback, relName) {
        var cjsModule, depName, ret, map, i,
            args = [],
            callbackType = typeof callback,
            usingExports;

        //Use name if no relName
        relName = relName || name;

        //Call the callback to define the module, if necessary.
        if (callbackType === 'undefined' || callbackType === 'function') {
            //Pull out the defined dependencies and pass the ordered
            //values to the callback.
            //Default to [require, exports, module] if no deps
            deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
            for (i = 0; i < deps.length; i += 1) {
                map = makeMap(deps[i], relName);
                depName = map.f;

                //Fast path CommonJS standard dependencies.
                if (depName === "require") {
                    args[i] = handlers.require(name);
                } else if (depName === "exports") {
                    //CommonJS module spec 1.1
                    args[i] = handlers.exports(name);
                    usingExports = true;
                } else if (depName === "module") {
                    //CommonJS module spec 1.1
                    cjsModule = args[i] = handlers.module(name);
                } else if (hasProp(defined, depName) ||
                           hasProp(waiting, depName) ||
                           hasProp(defining, depName)) {
                    args[i] = callDep(depName);
                } else if (map.p) {
                    map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
                    args[i] = defined[depName];
                } else {
                    throw new Error(name + ' missing ' + depName);
                }
            }

            ret = callback ? callback.apply(defined[name], args) : undefined;

            if (name) {
                //If setting exports via "module" is in play,
                //favor that over return value and exports. After that,
                //favor a non-undefined return value over exports use.
                if (cjsModule && cjsModule.exports !== undef &&
                        cjsModule.exports !== defined[name]) {
                    defined[name] = cjsModule.exports;
                } else if (ret !== undef || !usingExports) {
                    //Use the return value from the function.
                    defined[name] = ret;
                }
            }
        } else if (name) {
            //May just be an object definition for the module. Only
            //worry about defining if have a module name.
            defined[name] = callback;
        }
    };

    requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
        if (typeof deps === "string") {
            if (handlers[deps]) {
                //callback in this case is really relName
                return handlers[deps](callback);
            }
            //Just return the module wanted. In this scenario, the
            //deps arg is the module name, and second arg (if passed)
            //is just the relName.
            //Normalize module name, if it contains . or ..
            return callDep(makeMap(deps, callback).f);
        } else if (!deps.splice) {
            //deps is a config object, not an array.
            config = deps;
            if (config.deps) {
                req(config.deps, config.callback);
            }
            if (!callback) {
                return;
            }

            if (callback.splice) {
                //callback is an array, which means it is a dependency list.
                //Adjust args if there are dependencies
                deps = callback;
                callback = relName;
                relName = null;
            } else {
                deps = undef;
            }
        }

        //Support require(['a'])
        callback = callback || function () {};

        //If relName is a function, it is an errback handler,
        //so remove it.
        if (typeof relName === 'function') {
            relName = forceSync;
            forceSync = alt;
        }

        //Simulate async callback;
        if (forceSync) {
            main(undef, deps, callback, relName);
        } else {
            //Using a non-zero value because of concern for what old browsers
            //do, and latest browsers "upgrade" to 4 if lower value is used:
            //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
            //If want a value immediately, use require('id') instead -- something
            //that works in almond on the global level, but not guaranteed and
            //unlikely to work in other AMD implementations.
            setTimeout(function () {
                main(undef, deps, callback, relName);
            }, 4);
        }

        return req;
    };

    /**
     * Just drops the config on the floor, but returns req in case
     * the config return value is used.
     */
    req.config = function (cfg) {
        return req(cfg);
    };

    /**
     * Expose module registry for debugging and tooling
     */
    requirejs._defined = defined;

    define = function (name, deps, callback) {

        //This module may not have dependencies
        if (!deps.splice) {
            //deps is not an array, so probably means
            //an object literal or factory function for
            //the value. Adjust args.
            callback = deps;
            deps = [];
        }

        if (!hasProp(defined, name) && !hasProp(waiting, name)) {
            waiting[name] = [name, deps, callback];
        }
    };

    define.amd = {
        jQuery: true
    };
}());
<|endoftext|>


<commit_before>/*
* BrainBrowser: Web-based Neurological Visualization Tools
* (https://brainbrowser.cbrain.mcgill.ca)
*
* Copyright (C) 2011 McGill University
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

"use strict";

var fs = require("fs");
var pkg = require("../package.json");
var info = require("../canarie-rpi/info.json");

info.version = "BrainBrowser v" + pkg.version + ", Web Service v" + pkg.webServiceVersion;

exports.info = function(req, res) {

  res.format({
    html: function(){
      res.render("canarie/info", { info: info });
    },

    json: function(){
      res.send(JSON.stringify(info, null, 2));
    }
  });

};

exports.stats = function(req, res) {
  fs.readFile("canarie-rpi/stats.json", { encoding: "utf8" }, function(err, data) {
    var stats;

    if (err) {
      stats = {
        invocations: 0,
        lastReset: new Date().toISOString().replace(/\.\d+Z/, "Z")
      };
    } else {
      stats = JSON.parse(data);
    }
    res.send(JSON.stringify(stats, null, 2));
  });
};

exports.doc = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/#web-service");
};

exports.releasenotes = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/#web-service");
};

exports.support = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/#credits");
};

exports.source = function(req, res) {
  res.status(204).send("Not available.");
};

exports.tryme = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/surface-viewer");
};

exports.license = function(req, res) {
  fs.readFile("LICENSE", { encoding: "utf8" }, function(err, data) {
    res.type("text/plain").send(data);
  });
};

<commit_msg>Another fix for bugs in Canaries's validator.<commit_after>/*
* BrainBrowser: Web-based Neurological Visualization Tools
* (https://brainbrowser.cbrain.mcgill.ca)
*
* Copyright (C) 2011 McGill University
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

"use strict";

var fs = require("fs");
var pkg = require("../package.json");
var info = require("../canarie-rpi/info.json");

info.version = "BrainBrowser v" + pkg.version + ", Web Service v" + pkg.webServiceVersion;

exports.info = function(req, res) {

  res.format({
    html: function(){
      res.render("canarie/info", { info: info });
    },

    json: function(){
      res.type("application/json").send(JSON.stringify(info, null, 2));
    }
  });

};

exports.stats = function(req, res) {
  fs.readFile("canarie-rpi/stats.json", { encoding: "utf8" }, function(err, data) {
    var stats;

    if (err) {
      stats = {
        invocations: 0,
        lastReset: new Date().toISOString().replace(/\.\d+Z/, "Z")
      };
    } else {
      stats = JSON.parse(data);
    }
    res.send(JSON.stringify(stats, null, 2));
  });
};

exports.doc = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/#web-service");
};

exports.releasenotes = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/#web-service");
};

exports.support = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/#credits");
};

exports.source = function(req, res) {
  res.status(204).send("Not available.");
};

exports.tryme = function(req, res) {
  res.redirect("https://brainbrowser.cbrain.mcgill.ca/surface-viewer");
};

exports.license = function(req, res) {
  fs.readFile("LICENSE", { encoding: "utf8" }, function(err, data) {
    res.type("text/plain").send(data);
  });
};

<|endoftext|>


<commit_before>var Token          = require('../models/token').model;
var Bitcoin        = require('../lib/bitcoin');
var config         = require('../lib/config');
var BillingService = require('../lib/billing_service');
var features       = require('../lib/features');
var _              = require('lodash')

module.exports = function(req, res, next) {

  var token = req.params.token;
  if (!token) {
    res.status(400).json({
      message: "Must supply contract token to retrieve metadata"
    });
    return;
  }

  new Token({token: token}).fetch({
    withRelated: ['balance', 'contract']
  }).then(function (model) {
    if (!model) {
      res.status(404).json({
        message: "Token not found"
      });
      return;
    } else {
      new BillingService().getBalance(model).then(function(balance) {
        var metadata = {
          token: token,
          hash: model.related('contract').get('hash'),
          compute_units: balance.get('balance')
        }
        model.related('addresses').fetch({ withRelated: ['ledger'] }).then(function(addresses) {
          if (addresses.models.length > 0) {
            metadata.payment_addresses = _.map(addresses.models, function(address) {
              return address.related('ledger').get('name')+':'+address.get('address')
            })
          }
          res.status(200).json(metadata);
        })
      })
    }
  });
};
<commit_msg>[FEATURE] Return realtime balance in contract metadata [Finishes #88802586]<commit_after>var Token          = require('../models/token').model;
var Bitcoin        = require('../lib/bitcoin');
var config         = require('../lib/config');
var amortizer      = require('../lib/amortizer');
var BillingService = require('../lib/billing_service');
var features       = require('../lib/features');
var _              = require('lodash')

module.exports = function(req, res, next) {

  var token = req.params.token;
  if (!token) {
    res.status(400).json({
      message: "Must supply contract token to retrieve metadata"
    });
    return;
  }

  new Token({token: token}).fetch({
    withRelated: ['balance', 'contract']
  }).then(function (model) {
    if (!model) {
      res.status(404).json({
        message: "Token not found"
      });
      return;
    } else {
      new BillingService().getBalance(model).then(function(balance) {
        var metadata = {
          token: token,
          hash: model.related('contract').get('hash'),
          compute_units: balance.get('balance')
        }
        model.related('addresses').fetch({ withRelated: ['ledger'] }).then(function(addresses) {
          if (addresses.models.length > 0) {
            metadata.payment_addresses = _.map(addresses.models, function(address) {
              return address.related('ledger').get('name')+':'+address.get('address')
            })
          }
          if (features.isEnabled('BILLING_GENERIC')) {
            amortizer.checkTokenBalance(model).then(function(balance){
              metadata.compute_units = balance;
              res.status(200).json(metadata);
            });
          } else {
            res.status(200).json(metadata);
          }
        })
      })
    }
  });
};
<|endoftext|>


<commit_before>import { applyAsyncLoading } from './loading.js';
import app from 'ampersand-app';

export const ADD_PROJECT = 'ADD_PROJECT';
export const _addProject = (project) => ({ type: ADD_PROJECT, project });

export const SET_PROJECTS = 'SET_PROJECTS';
export const setProjects = (projects) => ({ type: SET_PROJECTS, projects });

export const REMOVE_PROJECT = 'REMOVE_PROJECT';
export const removeProject = (project) => ({ type: REMOVE_PROJECT, project });

export const UPDATE_PROJECT_STATUS = 'UPDATE_PROJECT_STATUS';

/**
 * @param {Object} options
 * @param {string} options.id Project's ID
 * @param {string} options.status Status
 * @returns {Object}
 * @property {string} id
 * @property {string} status
 * @property {string} type
 */
export function updateProjectStatus({ id, status }) {
  return {
    id,
    status,
    type: UPDATE_PROJECT_STATUS,
  };
}

/**
 * Map project model.
 *
 * This decorates the `Project` model with computated properties:
 *
 * - `allowComputationRun`: Determine whether computations can be run.
 *   Determined via async request.
 * - `status`: project's "state"
 *
 * @todo This is an _awful hack_ as it requires network requests to
 * determine whether a computation can run. Derive this information from
 * already stored state or add a computed property to the `Project`
 * model.
 *
 * @param {Object} project Project-like POJO.
 * @returns {Promise} Resolves to project
 */
export function mapProject(project) {
  function getProject(allowComputationRun = false) {
    return Object.assign(
      { status: 'waiting' },
      project,
      { allowComputationRun }
    );
  }

  if (project.consortiumId) {
    return app.core.computations
      .canStartComputation(project.consortiumId)
      .then(() => getProject(true))
      .catch(() => getProject());
  }

  return Promise.resolve(getProject());
}

export const addProject = applyAsyncLoading(function addProject(project) {
  return (dispatch) => {
    return app.core.projects.save(project)
      .then(mapProject)
      .then((proj) => {
        app.notify('success', `Project '${project.name}' created`);
        dispatch(_addProject(proj));
        return proj;
      });
  };
});

export const remove = applyAsyncLoading(function remove(project) {
  return (dispatch) => {
    return app.core.projects.delete(project)
    .then((rslt) => {
      app.notify('success', `Project '${project.name}' removed`);
      dispatch(removeProject(project));
      return rslt;
    })
    .catch((err) => {
      app.notify('error', err.message);
      throw err;
    });
  };
});

export const fetch = applyAsyncLoading(function fetchProjects(cb) {
  return (dispatch) => {
    return app.core.projects.all()
      .then(projects => Promise.all(projects.map(mapProject)))
      .then(projects => {
        dispatch(setProjects(projects));
        cb(null, projects);
      })
      .catch(error => {
        cb(error);
      });
  };
});

/**
 * Projects reducer.
 *
 * @param {Project[]} [projects]
 * @param {Object} action
 * @param {string} action.type One of the projects' actions
 * @param {Project} action.project
 * @param {Projects[]} action.projects ?
 * @returns {Project[]}
 */
export default function reducer(projects = [], action) {
  switch (action.type) {
    case ADD_PROJECT:
      return projects.concat(action.project);
    case SET_PROJECTS:
      if (!action.projects) {
        return projects;
      }
      return [...action.projects];
    case REMOVE_PROJECT:
      return projects.filter(p => p.name !== action.project.name);
    case UPDATE_PROJECT_STATUS:
      return projects.map(p => {
        return p._id === action.id ?
          Object.assign({}, p, { status: action.status }) :
          p;
      });
    default:
      return projects;
  }
}
<commit_msg>Strip computed `Project` model props before saving.<commit_after>import { applyAsyncLoading } from './loading.js';
import app from 'ampersand-app';
import omit from 'lodash/omit';

export const ADD_PROJECT = 'ADD_PROJECT';
export const _addProject = (project) => ({ type: ADD_PROJECT, project });

export const SET_PROJECTS = 'SET_PROJECTS';
export const setProjects = (projects) => ({ type: SET_PROJECTS, projects });

export const REMOVE_PROJECT = 'REMOVE_PROJECT';
export const removeProject = (project) => ({ type: REMOVE_PROJECT, project });

export const UPDATE_PROJECT_STATUS = 'UPDATE_PROJECT_STATUS';

/**
 * @param {Object} options
 * @param {string} options.id Project's ID
 * @param {string} options.status Status
 * @returns {Object}
 * @property {string} id
 * @property {string} status
 * @property {string} type
 */
export function updateProjectStatus({ id, status }) {
  return {
    id,
    status,
    type: UPDATE_PROJECT_STATUS,
  };
}

/**
 * Map project model.
 *
 * This decorates the `Project` model with computated properties:
 *
 * - `allowComputationRun`: Determine whether computations can be run.
 *   Determined via async request.
 * - `status`: project's "state"
 *
 * @todo This is an _awful hack_ as it requires network requests to
 * determine whether a computation can run. Derive this information from
 * already stored state or add a computed property to the `Project`
 * model.
 *
 * @param {Object} project Project-like POJO.
 * @returns {Promise} Resolves to project
 */
export function mapProject(project) {
  function getProject(allowComputationRun = false) {
    return Object.assign(
      { status: 'waiting' },
      project,
      { allowComputationRun }
    );
  }

  if (project.consortiumId) {
    return app.core.computations
      .canStartComputation(project.consortiumId)
      .then(() => getProject(true))
      .catch(() => getProject());
  }

  return Promise.resolve(getProject());
}

export const addProject = applyAsyncLoading(function addProject(project) {
  return (dispatch) => {
    /**
     * @todo: The `Project` model is decorated with `allowComputationRun` and
     * `status` properties for the UI. Determine a consistent way to add/strip
     * these props when dealing with the storage layer.
     */
    return app.core.projects.save(
      omit(project, ['allowComputationRun', 'status'])
    )
      .then(mapProject)
      .then((proj) => {
        app.notify('success', `Project '${project.name}' created`);
        dispatch(_addProject(proj));
        return proj;
      });
  };
});

export const remove = applyAsyncLoading(function remove(project) {
  return (dispatch) => {
    return app.core.projects.delete(project)
    .then((rslt) => {
      app.notify('success', `Project '${project.name}' removed`);
      dispatch(removeProject(project));
      return rslt;
    })
    .catch((err) => {
      app.notify('error', err.message);
      throw err;
    });
  };
});

export const fetch = applyAsyncLoading(function fetchProjects(cb) {
  return (dispatch) => {
    return app.core.projects.all()
      .then(projects => Promise.all(projects.map(mapProject)))
      .then(projects => {
        dispatch(setProjects(projects));
        cb(null, projects);
      })
      .catch(error => {
        cb(error);
      });
  };
});

/**
 * Projects reducer.
 *
 * @param {Project[]} [projects]
 * @param {Object} action
 * @param {string} action.type One of the projects' actions
 * @param {Project} action.project
 * @param {Projects[]} action.projects ?
 * @returns {Project[]}
 */
export default function reducer(projects = [], action) {
  switch (action.type) {
    case ADD_PROJECT:
      return projects.concat(action.project);
    case SET_PROJECTS:
      if (!action.projects) {
        return projects;
      }
      return [...action.projects];
    case REMOVE_PROJECT:
      return projects.filter(p => p.name !== action.project.name);
    case UPDATE_PROJECT_STATUS:
      return projects.map(p => {
        return p._id === action.id ?
          Object.assign({}, p, { status: action.status }) :
          p;
      });
    default:
      return projects;
  }
}
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import coalesceNonElementChildren from './coalesceNonElementChildren';

const systemButtonOpacity = 0.2;

export default class Button extends Component {
  static propTypes = {
    ...TouchableOpacity.propTypes,
    containerStyle: View.propTypes.style,
    disabled: PropTypes.bool,
    style: Text.propTypes.style,
    styleDisabled: Text.propTypes.style,
  };

  render() {
    let touchableProps = {
      activeOpacity: this._computeActiveOpacity(),
    };
    if (!this.props.disabled) {
      touchableProps.onPress = this.props.onPress;
      touchableProps.onPressIn = this.props.onPressIn;
      touchableProps.onPressOut = this.props.onPressOut;
      touchableProps.onLongPress = this.props.onLongPress;
    }

    return (
      <TouchableOpacity {...touchableProps} testID={this.props.testID} style={this.props.containerStyle}>
        {this._renderGroupedChildren()}
      </TouchableOpacity>
    );
  }

  _renderGroupedChildren() {
    let { disabled } = this.props;
    let style = [
      styles.text,
      disabled ? styles.disabledText : null,
      this.props.style,
      disabled ? this.props.styleDisabled : null,
    ];

    let children = coalesceNonElementChildren(this.props.children, (children, index) => {
      return (
        <Text key={index} style={style}>
          {children}
        </Text>
      );
    });

    switch (children.length) {
      case 0:
        return null;
      case 1:
        return children[0];
      default:
        return <View style={styles.group}>{children}</View>;
    }
  }

  _computeActiveOpacity() {
    if (this.props.disabled) {
      return 1;
    }
    return this.props.activeOpacity != null ?
      this.props.activeOpacity :
      systemButtonOpacity;
  }
};

const styles = StyleSheet.create({
  text: {
    color: '#007aff',
    fontFamily: '.HelveticaNeueInterface-MediumP4',
    fontSize: 17,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  disabledText: {
    color: '#dcdcdc',
  },
  group: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
});
<commit_msg>Add accessibilityTraits to support screen readers (#45)<commit_after>import React, { Component, PropTypes } from 'react';
import {
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import coalesceNonElementChildren from './coalesceNonElementChildren';

const systemButtonOpacity = 0.2;

export default class Button extends Component {
  static propTypes = {
    ...TouchableOpacity.propTypes,
    containerStyle: View.propTypes.style,
    disabled: PropTypes.bool,
    style: Text.propTypes.style,
    styleDisabled: Text.propTypes.style,
  };

  render() {
    let touchableProps = {
      activeOpacity: this._computeActiveOpacity(),
    };
    if (!this.props.disabled) {
      touchableProps.onPress = this.props.onPress;
      touchableProps.onPressIn = this.props.onPressIn;
      touchableProps.onPressOut = this.props.onPressOut;
      touchableProps.onLongPress = this.props.onLongPress;
    }

    return (
      <TouchableOpacity
        {...touchableProps}
        testID={this.props.testID}
        style={this.props.containerStyle}
        accessibilityTraits="button"
        accessibilityComponentType="button"
      >
        {this._renderGroupedChildren()}
      </TouchableOpacity>
    );
  }

  _renderGroupedChildren() {
    let { disabled } = this.props;
    let style = [
      styles.text,
      disabled ? styles.disabledText : null,
      this.props.style,
      disabled ? this.props.styleDisabled : null,
    ];

    let children = coalesceNonElementChildren(this.props.children, (children, index) => {
      return (
        <Text key={index} style={style}>
          {children}
        </Text>
      );
    });

    switch (children.length) {
      case 0:
        return null;
      case 1:
        return children[0];
      default:
        return <View style={styles.group}>{children}</View>;
    }
  }

  _computeActiveOpacity() {
    if (this.props.disabled) {
      return 1;
    }
    return this.props.activeOpacity != null ?
      this.props.activeOpacity :
      systemButtonOpacity;
  }
};

const styles = StyleSheet.create({
  text: {
    color: '#007aff',
    fontFamily: '.HelveticaNeueInterface-MediumP4',
    fontSize: 17,
    fontWeight: 'bold',
    textAlign: 'center',
  },
  disabledText: {
    color: '#dcdcdc',
  },
  group: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
});
<|endoftext|>


<commit_before>var keystone = require('keystone');
var async = require('async');

exports = module.exports = function(req, res) {

	var locals = res.locals, view = new keystone.View(req, res);

	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'Missions';
	console.log(locals.page.path.split('/').slice(-1)[0]);
	var mission_slug = locals.page.path.split('/').slice(-1)[0];
	console.log(mission_slug);

	var locals = res.locals,
			view = new keystone.View(req, res);
  var outcome = {};
	mid = mission_slug;
  var getMissionInfo = function(callback) {
    keystone.list('Mission').model.findOne({ 'missionId': mid }).exec(function(err, mission){
      if (err) {
        return callback(err, null);
      }
      outcome.mission = mission;
      return callback(null, 'done');
    });
  };

  var getTAPDescriptors = function(callback) {
    keystone.list('TAP').model.where('ID').regex(/TAP_\d+/).sort('ID').select('name ID').exec(function(err, taps){
      if (err) {
        return callback(err, null);
      }
      taps.sort(function(a,b){
        return a.toObject().ID.split('_')[1] - b.toObject().ID.split('_')[1];
      });
      console.log(taps);
      var temp = {};
      for (var i = 0; i < taps.length; i++) {
        temp[taps[i].ID] = taps[i].toObject();
      }
      outcome.tap_descs = temp;
      return callback(null, 'done');
    });
  };
    var getCAPDescriptors = function(callback) {
    keystone.list('CAP').model.where('ID').regex(/CAP_\d+/).sort('ID').exec(function(err, caps){
      if (err) {
        return callback(err, null);
      }
      caps.sort(function(a,b){
        return a.toObject().ID.split('_')[1] - b.toObject().ID.split('_')[1];
      });
      console.log(caps);
      outcome.cap_descs = caps;
      return callback(null, 'done');
    });
  };

  function asyncFinally(err, results){
    view.render('view_mission', {
      data: outcome
    });
  }

  async.parallel([getMissionInfo, getCAPDescriptors, getTAPDescriptors], asyncFinally);
}
/*var keystone = require('keystone');

exports = module.exports = function(req, res) {

	var locals = res.locals,
		view = new keystone.View(req, res);

	// locals.section is used to set the currently selected
	// item in the header navigation.
	view.query('missions', keystone.list('Mission').model.find());
	locals.section = 'missions';
	// Render the view
	view.render('missions', {title: 'Missions'});
};
*/

exports.tap = function(req, res){
  function tapFinally(err, results){
    var output = {};
    for (var i = 0; i < results.length; i++) {
      if(results[i]) { output[results[i].h.t] = results[i]; } // filters out a null result
    }
    res.send(output);
  }

  if(req.params.t === 'all') {
    req.app.db.models.TAP.distinct( '_t', { 'h.mid': parseInt(req.params.mid) } ).sort( { '_t': 1 } ).exec( function(err, taps) {
      async.map(taps, function(tap, callback){
      	console.log(tap);
        keystone.list('TAP').model.findOne( { 'h.mid': parseInt(req.params.mid), '_t': tap } ).sort( { '_t': -1 } ).exec( function(err, doc) {
          callback(null, doc);
        });
      }, tapFinally);
    });
  } else {
    var taplist = req.params.t.split(',');
    async.map(taplist, function(tap, callback){
      tap = 'TAP_' + tap;
      keystone.list('TAP').model.findOne( { 'h.mid': parseInt(req.params.mid), '_t': tap } ).sort( { '_id': -1 } ).exec( function(err, doc) {
        callback(null, doc);
      });
    }, tapFinally);
  }
};

exports.cap = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    workflow.emit('findTAP');
  });

  workflow.on('findTAP', function() {
    var outcome = {};

    function getNextCAPSeq(callback) {
      req.app.db.models.CAP.findOne( { 'h.mid': parseInt(req.params.mid) }, {}, {sort: { '_id': -1 } } ).exec( function(err, cap) {
        if (err) {
          return callback(err, null);
        }
        outcome.s = (cap ? cap.toObject().h.s + 1 : 1);
        return callback(null, 'done');

      });
    }

    function getLastTAPSNAP(callback) {
      req.app.db.models.TAP.findOne( { 'h.mid': parseInt(req.params.mid) }, {}, {sort: { '_id': -1 } } ).exec( function(err, tap) {
        if (err) {
          return callback(err, null);
        }
        outcome.xt_snap = (tap ? tap.getNewSNAPTime(req.body.cap.h.xt) : 0);
        return callback(null, 'done');
      });
    }

    function asyncFinally(err, results){
      if(err) {
        return workflow.emit('exception', err);
      }

      return workflow.emit('logCAP', outcome);
    }

    async.parallel([getNextCAPSeq, getLastTAPSNAP], asyncFinally);
  });

  workflow.on('logCAP', function(newdata) {
    var cap = req.body.cap;
    cap.h.s = newdata.s;
    cap.h.xt = newdata.xt_snap;
    cap.h.mid = parseInt(req.params.mid);

    req.app.db.models['CAP_'+cap.h.t].create(cap, function(err, newcap) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.cap = newcap;
      //if(req.app.httpio)  req.app.httpio.of('/gs').emit('cap', newcap);
      //if(req.app.httpsio) req.app.httpsio.of('/gs').emit('cap', newcap);
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<commit_msg>small<commit_after>var keystone = require('keystone');
var async = require('async');

exports = module.exports = function(req, res) {

	var locals = res.locals, view = new keystone.View(req, res);

	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'Missions';
	console.log(locals.page.path.split('/').slice(-1)[0]);
	var mission_slug = locals.page.path.split('/').slice(-1)[0];
	console.log(mission_slug);

	var locals = res.locals,
			view = new keystone.View(req, res);
  var outcome = {};
	mid = mission_slug;
  var getMissionInfo = function(callback) {
    keystone.list('Mission').model.findOne({ 'missionId': mid }).exec(function(err, mission){
      if (err) {
        return callback(err, null);
      }
      outcome.mission = mission;
      return callback(null, 'done');
    });
  };

  var getTAPDescriptors = function(callback) {
    keystone.list('TAP').model.where('ID').regex(/TAP_\d+/).sort('ID').select('name ID').exec(function(err, taps){
      if (err) {
        return callback(err, null);
      }
      taps.sort(function(a,b){
        return a.toObject().ID.split('_')[1] - b.toObject().ID.split('_')[1];
      });
      console.log(taps);
      var temp = {};
      for (var i = 0; i < taps.length; i++) {
        temp[taps[i].ID] = taps[i].toObject();
      }
      outcome.tap_descs = temp;
      return callback(null, 'done');
    });
  };
    var getCAPDescriptors = function(callback) {
    keystone.list('CAP').model.where('ID').regex(/CAP_\d+/).sort('ID').exec(function(err, caps){
      if (err) {
        return callback(err, null);
      }
      caps.sort(function(a,b){
        return a.toObject().ID.split('_')[1] - b.toObject().ID.split('_')[1];
      });
      console.log(caps);
      outcome.cap_descs = caps;
      return callback(null, 'done');
    });
  };

  function asyncFinally(err, results){
    view.render('view_mission', {
      data: outcome
    });
  }

  async.parallel([getMissionInfo, getCAPDescriptors, getTAPDescriptors], asyncFinally);
}
/*var keystone = require('keystone');

exports = module.exports = function(req, res) {

	var locals = res.locals,
		view = new keystone.View(req, res);

	// locals.section is used to set the currently selected
	// item in the header navigation.
	view.query('missions', keystone.list('Mission').model.find());
	locals.section = 'missions';
	// Render the view
	view.render('missions', {title: 'Missions'});
};
*/

exports.tap = function(req, res){
  function tapFinally(err, results){
    var output = {};
    console.log(results);
    for (var i = 0; i < results.length; i++) {
      if(results[i]) { output[results[i].h.t] = results[i]; } // filters out a null result
    }
    res.send(output);
  }

  if(req.params.t === 'all') {
    req.app.db.models.TAP.distinct( '_t', { 'h.mid': parseInt(req.params.mid) } ).sort( { '_t': 1 } ).exec( function(err, taps) {
      async.map(taps, function(tap, callback){
      	console.log(tap);
        keystone.list('TAP').model.findOne( { 'h.mid': parseInt(req.params.mid), '_t': tap } ).sort( { '_t': -1 } ).exec( function(err, doc) {
          callback(null, doc);
        });
      }, tapFinally);
    });
  } else {
    var taplist = req.params.t;
    console.log(req.params);
    //console.log(keystone.db.models);
    console.log(req.params.mid + '-TAP_' + req.params.t);
    //console.log(keystone.db.models[req.params.mid + '-TAP_' + req.params.t]);
    console.log("break1");
    //console.log(keystone.db.models);
    console.log("break2");
    keystone.db.models[req.params.mid + '-TAP_' + req.params.t].findOne({}).exec(function(err,doc) {// { 'h.mid': req.params.mid } ).sort( { 'h.s': -1 } ).exec( function(err, doc) {
        console.log("hello");
        console.log(doc);
        console.log("hello2");
      });
    async.map(req.params, function(tap, callback){
    	console.log("hello");
      keystone.db.models[tap.mid + '-TAP_' + tap.t].findOne( { 'h.mid': parseInt(tap.mid), 'ID': tap } ).sort( { 'h.s': -1 } ).exec( function(err, doc) {
        callback(null, doc);
      });
    }, tapFinally);
  }
};

exports.cap = function(req, res, next){
  var workflow = req.app.utility.workflow(req, res);

  workflow.on('validate', function() {
    workflow.emit('findTAP');
  });

  workflow.on('findTAP', function() {
    var outcome = {};

    function getNextCAPSeq(callback) {
      req.app.db.models.CAP.findOne( { 'h.mid': parseInt(req.params.mid) }, {}, {sort: { '_id': -1 } } ).exec( function(err, cap) {
        if (err) {
          return callback(err, null);
        }
        outcome.s = (cap ? cap.toObject().h.s + 1 : 1);
        return callback(null, 'done');

      });
    }

    function getLastTAPSNAP(callback) {
      req.app.db.models.TAP.findOne( { 'h.mid': parseInt(req.params.mid) }, {}, {sort: { '_id': -1 } } ).exec( function(err, tap) {
        if (err) {
          return callback(err, null);
        }
        outcome.xt_snap = (tap ? tap.getNewSNAPTime(req.body.cap.h.xt) : 0);
        return callback(null, 'done');
      });
    }

    function asyncFinally(err, results){
      if(err) {
        return workflow.emit('exception', err);
      }

      return workflow.emit('logCAP', outcome);
    }

    async.parallel([getNextCAPSeq, getLastTAPSNAP], asyncFinally);
  });

  workflow.on('logCAP', function(newdata) {
    var cap = req.body.cap;
    cap.h.s = newdata.s;
    cap.h.xt = newdata.xt_snap;
    cap.h.mid = parseInt(req.params.mid);

    req.app.db.models['CAP_'+cap.h.t].create(cap, function(err, newcap) {
      if (err) {
        return workflow.emit('exception', err);
      }

      workflow.outcome.cap = newcap;
      //if(req.app.httpio)  req.app.httpio.of('/gs').emit('cap', newcap);
      //if(req.app.httpsio) req.app.httpsio.of('/gs').emit('cap', newcap);
      return workflow.emit('response');
    });
  });

  workflow.emit('validate');
};
<|endoftext|>


<commit_before>import {ClientResultFactory} from '../../../lib/ClientResultProvider.js'

Template.redlinkQuery.helpers({
	hasResult(){
		const results = Template.instance().state.get('results');
		if (results) {
			return results.length > 0;
		} else {
			return false;
		}
	},

	isDirty(){
		return Template.instance().state.get('status') === 'dirty'
	},

	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('resultsExpanded') ? 'expanded' : 'collapsed';
	},

	queryPreviewHeadline(){
		const instance = Template.instance();
		const results = instance.state.get('results');
		if (results) {
			const creator = results[0].creator; //all results have got the same creator
			switch (creator) {
				case 'community.bahn.de':
					return t('results_community_bahn_de');
				case 'bahn.de':
					return t('results_bahn_de');
				default:
					return t('results');
			}
		}
	},

	navigationOptions(){
		const instance = Template.instance();
		const results = instance.state.get('results');
		if (results) {
			const creator = results[0].creator; //all results have got the same creator
			let options = {
				results: results,
				roomId: instance.data.roomId
			};

			switch (creator) {
				case 'bahn.de':
					options.template = 'redlinkResultContainer_Slider';
					options.stepping = 2;
					break;
				case 'VKL':
					options.template = 'redlinkResultContainer_Slider';
					options.stepping = 3;
					break;
				default:
					options.template = 'redlinkResultContainer_Slider';
					options.stepping = 5;
			}
			return options;
		}
	},
	getCreatorText(){
		const instance = Template.instance();
		if(instance.data.query.creator === 'Hasso-MLT' || instance.data.query.creator === 'Hasso-Search'){
			return "";
		} else {
			return TAPi18n.__(instance.data.query.replacedCreator);
		}
	},
	getQueryDisplayTitle(){
		const instance = Template.instance();
		if(instance.data.query.creator === 'Hasso-MLT'){
			return 'Ähnliche Fragen';
		}
		if(instance.data.query.creator === 'Hasso-Search'){
			return instance.data.query.displayTitle
				.replace("Conversationen zum", "Zum")
				.replace(/[|]/g, "");
		}

		// else
		return instance.data.query.displayTitle;
	}
});

Template.redlinkQuery.events({
	'click .js-toggle-results-expanded': function (event, instance) {
		const current = instance.state.get('resultsExpanded');
		instance.state.set('resultsExpanded', !current);
	}
});

Template.redlinkQuery.clientResult = function(creator){
	switch(creator) {
		case 'dbsearch': return true;
		default: return false;
	}
};

Template.redlinkQuery.onCreated(function () {
	const instance = this;

	this.state = new ReactiveDict();
	this.state.setDefault({
		resultsExpanded: instance.data.query.inlineResultSupport && ( instance.data.maxConfidence === instance.data.query.confidence ),
		results: [],
		status: 'initial'
	});

	// Asynchronously load the results.
	instance.autorun(()=> {
		if (instance.data && instance.data.query && instance.data.roomId) {
			//subscribe to the external messages for the room in order to re-fetch the results once the result
			// of the knowledge provider changes
			this.subscribe('livechat:externalMessages', Template.currentData().roomId);

			//issue a request to the redlink results-service and buffer the potential results in a reactive variable
			//which then can be forwarded to the results-template
			if (instance.data.query.inlineResultSupport) {
				instance.state.set('status', 'dirty');
				Meteor.call('redlink:retrieveResults', instance.data.roomId, instance.data.templateIndex, instance.data.query.creator, (err, results)=> {
					instance.state.set('results', results);
					instance.state.set('status', 'fetched');
				});
			}
			if(Template.redlinkQuery.clientResult(instance.data.query.creator)){
				instance.state.set('status', 'dirty');
				ClientResultFactory.getInstance(instance.data.query.creator, instance.data.query.url)
					.executeQuery([], (results)=>{
						instance.state.set('results',results);
					});
			}
		}
	})

});
<commit_msg>set results ready for client-retrieved results<commit_after>import {ClientResultFactory} from '../../../lib/ClientResultProvider.js'

Template.redlinkQuery.helpers({
	hasResult(){
		const results = Template.instance().state.get('results');
		if (results) {
			return results.length > 0;
		} else {
			return false;
		}
	},

	isDirty(){
		return Template.instance().state.get('status') === 'dirty'
	},

	classExpanded(){
		const instance = Template.instance();
		return instance.state.get('resultsExpanded') ? 'expanded' : 'collapsed';
	},

	queryPreviewHeadline(){
		const instance = Template.instance();
		const results = instance.state.get('results');
		if (results) {
			const creator = results[0].creator; //all results have got the same creator
			switch (creator) {
				case 'community.bahn.de':
					return t('results_community_bahn_de');
				case 'bahn.de':
					return t('results_bahn_de');
				default:
					return t('results');
			}
		}
	},

	navigationOptions(){
		const instance = Template.instance();
		const results = instance.state.get('results');
		if (results) {
			const creator = results[0].creator; //all results have got the same creator
			let options = {
				results: results,
				roomId: instance.data.roomId
			};

			switch (creator) {
				case 'bahn.de':
					options.template = 'redlinkResultContainer_Slider';
					options.stepping = 2;
					break;
				case 'VKL':
					options.template = 'redlinkResultContainer_Slider';
					options.stepping = 3;
					break;
				default:
					options.template = 'redlinkResultContainer_Slider';
					options.stepping = 5;
			}
			return options;
		}
	},
	getCreatorText(){
		const instance = Template.instance();
		if(instance.data.query.creator === 'Hasso-MLT' || instance.data.query.creator === 'Hasso-Search'){
			return "";
		} else {
			return TAPi18n.__(instance.data.query.replacedCreator);
		}
	},
	getQueryDisplayTitle(){
		const instance = Template.instance();
		if(instance.data.query.creator === 'Hasso-MLT'){
			return 'Ähnliche Fragen';
		}
		if(instance.data.query.creator === 'Hasso-Search'){
			return instance.data.query.displayTitle
				.replace("Conversationen zum", "Zum")
				.replace(/[|]/g, "");
		}

		// else
		return instance.data.query.displayTitle;
	}
});

Template.redlinkQuery.events({
	'click .js-toggle-results-expanded': function (event, instance) {
		const current = instance.state.get('resultsExpanded');
		instance.state.set('resultsExpanded', !current);
	}
});

Template.redlinkQuery.clientResult = function(creator){
	switch(creator) {
		case 'dbsearch': return true;
		default: return false;
	}
};

Template.redlinkQuery.onCreated(function () {
	const instance = this;

	this.state = new ReactiveDict();
	this.state.setDefault({
		resultsExpanded: instance.data.query.inlineResultSupport && ( instance.data.maxConfidence === instance.data.query.confidence ),
		results: [],
		status: 'initial'
	});

	// Asynchronously load the results.
	instance.autorun(()=> {
		if (instance.data && instance.data.query && instance.data.roomId) {
			//subscribe to the external messages for the room in order to re-fetch the results once the result
			// of the knowledge provider changes
			this.subscribe('livechat:externalMessages', Template.currentData().roomId);

			//issue a request to the redlink results-service and buffer the potential results in a reactive variable
			//which then can be forwarded to the results-template
			if (instance.data.query.inlineResultSupport) {
				instance.state.set('status', 'dirty');
				Meteor.call('redlink:retrieveResults', instance.data.roomId, instance.data.templateIndex, instance.data.query.creator, (err, results)=> {
					instance.state.set('results', results);
					instance.state.set('status', 'fetched');
				});
			}
			if(Template.redlinkQuery.clientResult(instance.data.query.creator)){
				instance.state.set('status', 'dirty');
				ClientResultFactory.getInstance(instance.data.query.creator, instance.data.query.url)
					.executeQuery([], (results)=>{
						instance.state.set('results',results);
						instance.state.set('status', 'fetched');
					});
			}
		}
	})

});
<|endoftext|>


<commit_before>const asciidoc = require(`asciidoctor.js`)()

async function onCreateNode(
  {
    node,
    actions,
    loadNodeContent,
    createNodeId,
    reporter,
    createContentDigest,
  },
  pluginOptions
) {
  // Filter out non-adoc content
  if (!node.extension || node.extension !== `adoc`) {
    return
  }

  const { createNode, createParentChildLink } = actions
  // Load Asciidoc contents
  const content = await loadNodeContent(node)
  // Load Asciidoc file for extracting
  // https://asciidoctor-docs.netlify.com/asciidoctor.js/processor/extract-api/
  const doc = await asciidoc.loadFile(node.absolutePath)

  try {
    const html = asciidoc.convert(content, pluginOptions)
    // Use "partition" option to be able to get title, subtitle, combined
    const title = doc.getDocumentTitle({ partition: true })

    let revision = null
    let author = null

    if (doc.hasRevisionInfo()) {
      revision = {
        date: doc.getRevisionDate(),
        number: doc.getRevisionNumber(),
        remark: doc.getRevisionRemark(),
      }
    }

    if (doc.getAuthor()) {
      author = {
        fullName: doc.getAttribute(`author`),
        firstName: doc.getAttribute(`firstname`),
        lastName: doc.getAttribute(`lastname`) || ``,
        middleName: doc.getAttribute(`middlename`) || ``,
        authorInitials: doc.getAttribute(`authorinitials`) || ``,
        email: doc.getAttribute(`email`) || ``,
      }
    }

    const asciiNode = {
      id: createNodeId(`${node.id} >>> ASCIIDOC`),
      parent: node.id,
      internal: {
        type: `Asciidoc`,
        mediaType: `text/html`,
      },
      children: [],
      html,
      document: {
        title: title.getCombined(),
        subtitle: title.hasSubtitle() ? title.getSubtitle() : ``,
        main: title.getMain(),
      },
      revision,
      author,
    }

    asciiNode.internal.contentDigest = createContentDigest(asciiNode)

    createNode(asciiNode)
    createParentChildLink({ parent: node, child: asciiNode })
  } catch (err) {
    reporter.panicOnBuild(
      `Error processing Asciidoc ${
        node.absolutePath ? `file ${node.absolutePath}` : `in node ${node.id}`
      }:\n
      ${err.message}`
    )
  }
}

exports.onCreateNode = onCreateNode
<commit_msg>fix(gatsby-transformer-asciidoc): abstract the source of asciidoc transformer (#11531)<commit_after>const asciidoc = require(`asciidoctor.js`)()

async function onCreateNode(
  {
    node,
    actions,
    loadNodeContent,
    createNodeId,
    reporter,
    createContentDigest,
  },
  pluginOptions
) {
  // Filter out non-adoc content
  if (!node.extension || node.extension !== `adoc`) {
    return
  }

  const { createNode, createParentChildLink } = actions
  // Load Asciidoc contents
  const content = await loadNodeContent(node)
  // Load Asciidoc file for extracting
  // https://asciidoctor-docs.netlify.com/asciidoctor.js/processor/extract-api/
  // We use a `let` here as a warning: some operations, like .convert() mutate the document
  let doc = await asciidoc.load(content, pluginOptions)

  try {
    const html = doc.convert()
    // Use "partition" option to be able to get title, subtitle, combined
    const title = doc.getDocumentTitle({ partition: true })

    let revision = null
    let author = null

    if (doc.hasRevisionInfo()) {
      revision = {
        date: doc.getRevisionDate(),
        number: doc.getRevisionNumber(),
        remark: doc.getRevisionRemark(),
      }
    }

    if (doc.getAuthor()) {
      author = {
        fullName: doc.getAttribute(`author`),
        firstName: doc.getAttribute(`firstname`),
        lastName: doc.getAttribute(`lastname`) || ``,
        middleName: doc.getAttribute(`middlename`) || ``,
        authorInitials: doc.getAttribute(`authorinitials`) || ``,
        email: doc.getAttribute(`email`) || ``,
      }
    }

    const asciiNode = {
      id: createNodeId(`${node.id} >>> ASCIIDOC`),
      parent: node.id,
      internal: {
        type: `Asciidoc`,
        mediaType: `text/html`,
      },
      children: [],
      html,
      document: {
        title: title.getCombined(),
        subtitle: title.hasSubtitle() ? title.getSubtitle() : ``,
        main: title.getMain(),
      },
      revision,
      author,
    }

    asciiNode.internal.contentDigest = createContentDigest(asciiNode)

    createNode(asciiNode)
    createParentChildLink({ parent: node, child: asciiNode })
  } catch (err) {
    reporter.panicOnBuild(
      `Error processing Asciidoc ${
        node.absolutePath ? `file ${node.absolutePath}` : `in node ${node.id}`
      }:\n
      ${err.message}`
    )
  }
}

exports.onCreateNode = onCreateNode
<|endoftext|>


<commit_before>/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import React from 'react';
import Checkbox from '../Checkbox';
import CheckboxSkeleton from '../Checkbox/Checkbox.Skeleton';
import { mount } from 'enzyme';
import { settings } from 'carbon-components';

const { prefix } = settings;

describe('Checkbox', () => {
  describe('Renders as expected', () => {
    const wrapper = mount(
      <Checkbox id="testing" labelText="testingLabel" className="extra-class" />
    );
    const label = wrapper.find('label');

    describe('label', () => {
      it('renders a label', () => {
        expect(label.length).toEqual(1);
      });

      it('has the expected classes', () => {
        expect(label.hasClass(`${prefix}--checkbox-label`)).toEqual(true);
      });

      it('applies extra classes to label', () => {
        expect(label.hasClass('extra-class')).toEqual(true);
      });

      describe('input', () => {
        const input = () => wrapper.find('input');

        it('defaultChecked prop sets defaultChecked on input', () => {
          expect(input().props().defaultChecked).toBeUndefined();
          wrapper.setProps({ defaultChecked: true });
          expect(input().props().defaultChecked).toEqual(true);
        });
      });
    });
  });

  it('disabled prop on component sets disabled prop on input', () => {
    const wrapper = mount(
      <Checkbox id="test" labelText="testlabel" disabled />
    );

    const input = () => wrapper.find('input');
    expect(input().props().disabled).toEqual(true);

    wrapper.setProps({ disabled: false });
    expect(input().props().disabled).toEqual(false);
  });

  it('checked prop on component sets checked prop on input', () => {
    const wrapper = mount(<Checkbox id="test" labelText="testlabel" checked />);

    const input = () => wrapper.find('input');
    expect(input().props().checked).toEqual(true);

    wrapper.setProps({ checked: false });
    expect(input().props().checked).toEqual(false);
  });

  it('hideLabel hides the label visually', () => {
    const wrapper = mount(
      <Checkbox id="test" labelText="testlabel" hideLabel />
    );

    const label = wrapper.find('label');
    expect(label.length).toEqual(1);
    const span = wrapper.find('span');
    expect(span.hasClass(`${prefix}--visually-hidden`)).toEqual(true);
  });

  describe('events', () => {
    it('should invoke onChange with expected arguments', () => {
      const onChange = jest.fn();
      const id = 'test-input';
      const wrapper = mount(
        <Checkbox labelText="testlabel" id={id} onChange={onChange} />
      );

      const input = wrapper.find('input');
      const inputElement = input.instance();

      inputElement.checked = true;
      wrapper.find('input').simulate('change');

      const call = onChange.mock.calls[0];

      expect(call[0]).toEqual(true);
      expect(call[1]).toEqual(id);
      expect(call[2].target).toBe(inputElement);
    });
  });
});

describe('refs', () => {
  let container;

  it('should accept refs', () => {
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
        this.focus = this.focus.bind(this);
      }
      focus() {
        this.myRef.current.focus();
      }
      render() {
        return (
          <Checkbox
            id="test"
            labelText="testlabel"
            hideLabel
            ref={this.myRef}
          />
        );
      }
    }
    container = document.createElement('div');
    container.id = 'container';
    document.body.appendChild(container);
    const wrapper = mount(<MyComponent />, {
      attachTo: document.querySelector('#container'),
    });
    expect(document.activeElement.type).toBeUndefined();
    wrapper.instance().focus();
    expect(document.activeElement.type).toEqual('checkbox');
  });

  it('should set indeterminate when accepting refs', () => {
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
      render() {
        return (
          <Checkbox
            id="test-id"
            labelText="test"
            indeterminate
            ref={this.myRef}
          />
        );
      }
    }
    const wrapper = mount(<MyComponent />);
    expect(wrapper.find('input').getDOMNode().indeterminate).toBe(true);
  });

  afterEach(() => {
    if (container && container.parentNode) {
      container.parentNode.removeChild(container);
    }
    container = null;
  });
});

describe('CheckboxSkeleton', () => {
  describe('Renders as expected', () => {
    const wrapper = mount(<CheckboxSkeleton />);
    const label = wrapper.find('span');

    describe('label', () => {
      it('renders a label', () => {
        expect(label.length).toEqual(1);
      });

      it('has the expected classes', () => {
        expect(label.hasClass(`${prefix}--checkbox-label-text`)).toEqual(true);
        expect(label.hasClass(`${prefix}--skeleton`)).toEqual(true);
      });
    });
  });
});
<commit_msg>test(checkbox): restore id and htmlFor tests (#6052)<commit_after>/**
 * Copyright IBM Corp. 2016, 2018
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import React from 'react';
import Checkbox from '../Checkbox';
import CheckboxSkeleton from '../Checkbox/Checkbox.Skeleton';
import { mount } from 'enzyme';
import { settings } from 'carbon-components';

const { prefix } = settings;

describe('Checkbox', () => {
  describe('Renders as expected', () => {
    const wrapper = mount(
      <Checkbox id="testing" labelText="testingLabel" className="extra-class" />
    );
    const label = wrapper.find('label');

    describe('label', () => {
      it('renders a label', () => {
        expect(label.length).toEqual(1);
      });

      it('has the expected classes', () => {
        expect(label.hasClass(`${prefix}--checkbox-label`)).toEqual(true);
      });

      it('has the expected htmlFor value', () => {
        expect(label.props().htmlFor).toEqual('testing');
      });

      it('applies extra classes to label', () => {
        expect(label.hasClass('extra-class')).toEqual(true);
      });

      describe('input', () => {
        const input = () => wrapper.find('input');

        it('has id set as expected', () => {
          expect(input().props().id).toEqual('testing');
        });

        it('defaultChecked prop sets defaultChecked on input', () => {
          expect(input().props().defaultChecked).toBeUndefined();
          wrapper.setProps({ defaultChecked: true });
          expect(input().props().defaultChecked).toEqual(true);
        });
      });
    });
  });

  it('disabled prop on component sets disabled prop on input', () => {
    const wrapper = mount(
      <Checkbox id="test" labelText="testlabel" disabled />
    );

    const input = () => wrapper.find('input');
    expect(input().props().disabled).toEqual(true);

    wrapper.setProps({ disabled: false });
    expect(input().props().disabled).toEqual(false);
  });

  it('checked prop on component sets checked prop on input', () => {
    const wrapper = mount(<Checkbox id="test" labelText="testlabel" checked />);

    const input = () => wrapper.find('input');
    expect(input().props().checked).toEqual(true);

    wrapper.setProps({ checked: false });
    expect(input().props().checked).toEqual(false);
  });

  it('hideLabel hides the label visually', () => {
    const wrapper = mount(
      <Checkbox id="test" labelText="testlabel" hideLabel />
    );

    const label = wrapper.find('label');
    expect(label.length).toEqual(1);
    const span = wrapper.find('span');
    expect(span.hasClass(`${prefix}--visually-hidden`)).toEqual(true);
  });

  describe('events', () => {
    it('should invoke onChange with expected arguments', () => {
      const onChange = jest.fn();
      const id = 'test-input';
      const wrapper = mount(
        <Checkbox labelText="testlabel" id={id} onChange={onChange} />
      );

      const input = wrapper.find('input');
      const inputElement = input.instance();

      inputElement.checked = true;
      wrapper.find('input').simulate('change');

      const call = onChange.mock.calls[0];

      expect(call[0]).toEqual(true);
      expect(call[1]).toEqual(id);
      expect(call[2].target).toBe(inputElement);
    });
  });
});

describe('refs', () => {
  let container;

  it('should accept refs', () => {
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
        this.focus = this.focus.bind(this);
      }
      focus() {
        this.myRef.current.focus();
      }
      render() {
        return (
          <Checkbox
            id="test"
            labelText="testlabel"
            hideLabel
            ref={this.myRef}
          />
        );
      }
    }
    container = document.createElement('div');
    container.id = 'container';
    document.body.appendChild(container);
    const wrapper = mount(<MyComponent />, {
      attachTo: document.querySelector('#container'),
    });
    expect(document.activeElement.type).toBeUndefined();
    wrapper.instance().focus();
    expect(document.activeElement.type).toEqual('checkbox');
  });

  it('should set indeterminate when accepting refs', () => {
    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
      render() {
        return (
          <Checkbox
            id="test-id"
            labelText="test"
            indeterminate
            ref={this.myRef}
          />
        );
      }
    }
    const wrapper = mount(<MyComponent />);
    expect(wrapper.find('input').getDOMNode().indeterminate).toBe(true);
  });

  afterEach(() => {
    if (container && container.parentNode) {
      container.parentNode.removeChild(container);
    }
    container = null;
  });
});

describe('CheckboxSkeleton', () => {
  describe('Renders as expected', () => {
    const wrapper = mount(<CheckboxSkeleton />);
    const label = wrapper.find('span');

    describe('label', () => {
      it('renders a label', () => {
        expect(label.length).toEqual(1);
      });

      it('has the expected classes', () => {
        expect(label.hasClass(`${prefix}--checkbox-label-text`)).toEqual(true);
        expect(label.hasClass(`${prefix}--skeleton`)).toEqual(true);
      });
    });
  });
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';

export default Ember.Component.extend({
  layout: layout,
  tagName: 'div',
  classNames: 'dropdown-menu',
  classNameBindings: 'alignComputed',
  attributeBindings: ['aria-labelledby'],

  // Defaults
  prefixClass: 'dropdown-menu-',
  align: null,

  // Constructors
  alignments: ['left', 'right'],

  // Accessibility
  'aria-labelledby': null,

  // Computed
  alignComputed: Ember.computed('align', function(){
    var alignments = this.get('alignments');
    var align = this.get('align');

    if (!align) {
      return null;
    }

    if (alignments.indexOf(align) === -1) {
      Ember.Logger.warn('rui-dropdown-menu: You specified and unsupported `align` property so we`ve defaulted to the standard left alignment. Choose from `left` or `right.`');
      return null;
    }

    return this.get('prefixClass') + align;
  })
});
<commit_msg>Adds data-test-id to dropdown menu component<commit_after>import Ember from 'ember';
import layout from './template';

export default Ember.Component.extend({
  layout: layout,
  tagName: 'div',
  classNames: 'dropdown-menu',
  classNameBindings: 'alignComputed',
  attributeBindings: [
    'aria-labelledby',
    'data-test-id'
  ],

  // Defaults
  prefixClass: 'dropdown-menu-',
  align: null,

  // Constructors
  alignments: ['left', 'right'],

  // Accessibility
  'aria-labelledby': null,

  // Computed
  alignComputed: Ember.computed('align', function(){
    var alignments = this.get('alignments');
    var align = this.get('align');

    if (!align) {
      return null;
    }

    if (alignments.indexOf(align) === -1) {
      Ember.Logger.warn('rui-dropdown-menu: You specified and unsupported `align` property so we`ve defaulted to the standard left alignment. Choose from `left` or `right.`');
      return null;
    }

    return this.get('prefixClass') + align;
  })
});
<|endoftext|>


<commit_before>var root = require('root-path')
require(root('test/setup'))
var factories = require(root('test/setup/factories'))
var InvitationController = require(root('api/controllers/InvitationController'))

describe('InvitationController', () => {
  describe('.use', () => {
    var user, community, invitation, inviter, req, res

    before(() => {
      req = factories.mock.request()
      res = factories.mock.response()
      user = factories.user()
      inviter = factories.user()
      community = factories.community()
      return Promise.join(inviter.save(), user.save(), community.save())
      .then(() => {
        req.login(user.id)

        return Invitation.create({
          communityId: community.id,
          userId: inviter.id,
          email: 'foo@bar.com'
        }).tap(i => {
          invitation = i
          req.params.token = invitation.get('token')
        })
      })
    })

    it('adds the user to the community and creates a welcome post', () => {
      return InvitationController.use(req, res)
      .then(() => {
        expect(res.ok).to.have.been.called()
        expect(res.body).to.deep.equal({})
        return user.load(['followedPosts', 'followedPosts.relatedUsers', 'communities'])
      })
      .then(() => {
        expect(user.relations.communities.first().id).to.equal(community.id)
        var post = user.relations.followedPosts.first()
        expect(post).to.exist
        expect(post.get('type')).to.equal('welcome')
        var relatedUser = post.relations.relatedUsers.first()
        expect(relatedUser.id).to.equal(user.id)
      })
    })
  })
})
<commit_msg>fix tests<commit_after>var root = require('root-path')
require(root('test/setup'))
var factories = require(root('test/setup/factories'))
var InvitationController = require(root('api/controllers/InvitationController'))

describe('InvitationController', () => {
  describe('.use', () => {
    var user, community, invitation, inviter, req, res

    before(() => {
      req = factories.mock.request()
      res = factories.mock.response()
      user = factories.user()
      inviter = factories.user()
      community = factories.community()
      return Promise.join(inviter.save(), user.save(), community.save())
      .then(() => {
        req.login(user.id)

        return Invitation.create({
          communityId: community.id,
          userId: inviter.id,
          email: 'foo@bar.com'
        }).tap(i => {
          invitation = i
          req.params.token = invitation.get('token')
        })
      })
    })

    it('adds the user to the community and creates a welcome post', () => {
      return InvitationController.use(req, res)
      .then(() => {
        expect(res.ok).to.have.been.called()
        return user.load(['followedPosts', 'followedPosts.relatedUsers', 'communities'])
      })
      .then(() => {
        expect(user.relations.communities.first().id).to.equal(community.id)
        var post = user.relations.followedPosts.first()
        expect(post).to.exist
        expect(post.get('type')).to.equal('welcome')
        var relatedUser = post.relations.relatedUsers.first()
        expect(relatedUser.id).to.equal(user.id)
      })
    })
  })
})
<|endoftext|>


<commit_before>/*jshint node:true, mocha:true */

'use strict';

require('should');

var adapter = require('floating-adapter');
var Decimal = require('../src/arbitrary-precision')(adapter);

describe('linear operations with floating', function() {
  var ONE = new Decimal('1');

  it('should have all linear arbitrary precision methods', function() {
    ONE.plus.should.have.type('function');
    ONE.minus.should.have.type('function');
    ONE.times.should.have.type('function');
    ONE.div.should.have.type('function');
    ONE.equals.should.have.type('function');
  });

  it('should extend linear arbitrary precision', function() {
    ONE.pow.should.have.type('function');
    ONE.sqrt.should.have.type('function');
  });
});
<commit_msg>test: presence of mod<commit_after>/*jshint node:true, mocha:true */

'use strict';

require('should');

var adapter = require('floating-adapter');
var Decimal = require('../src/arbitrary-precision')(adapter);

describe('linear operations with floating', function() {
  var ONE = new Decimal('1');

  it('should have all linear arbitrary precision methods', function() {
    ONE.plus.should.have.type('function');
    ONE.minus.should.have.type('function');
    ONE.times.should.have.type('function');
    ONE.div.should.have.type('function');
    ONE.mod.should.have.type('function');
    ONE.equals.should.have.type('function');
  });

  it('should extend linear arbitrary precision', function() {
    ONE.pow.should.have.type('function');
    ONE.sqrt.should.have.type('function');
  });
});
<|endoftext|>