<commit_before>/**
 * ProjectUserController
 *
 * @module      :: Controller
 * @description :: Contains logic for handling requests.
 */
var jQuery = require("jquery");
var async = require("async");

module.exports = {
    /**
     * This actions makes view for project users. Note that 'projectId' parameter is
     * required for this action.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     */
    users: function(req, res) {
        var projectId = req.param("projectId");
        var data = {
            layout: req.isAjax ? "layout_ajax" : "layout",
            users: false,
            project: false,
            role: false,
            signedIn: req.user
        };

        async.parallel(
            {
                // Fetch project data
                project: function(callback) {
                    DataService.getProject(projectId, callback);
                },

                // Fetch current user role in project
                role: function(callback) {
                    AuthService.hasProjectAccess(req.user, projectId, callback, true);
                }
            },

            /**
             * Callback function that is called after all parallel jobs are done
             * or some error has happen in those
             *
             * @param   {Error} error   Error data
             * @param   {{}}    results Object that contains following data:
             *                           - project {sails.model.project}
             *                           - role, User role in current project
             */
            function callback(error, results) {
                if (error) {
                    res.send(error.status ? error.status : 500, error);
                } else {
                    data.project = results.project;
                    data.role = results.role;

                    fetchProjectUsers();
                }
            }
        );

        /**
         * Function to fetch project user data. Also note that this will add selected
         * project manager to this user list.
         *
         * todo:    potential bug for duplicate user, eg user is attached to project
         *          and afterwards this same user has been selected to project manager.
         *
         *          This is not a big deal yet, but remember to handle this :D
         */
        function fetchProjectUsers() {
            // Fetch all project user
            ProjectUser
                .find()
                .where({projectId: projectId})
                .done(function(error, /** sails.json.projectUser */projectUsers) {
                    if (error) {
                        res.send(error, 500);
                    } else {
                        data.users = projectUsers;

                        // Add project main manager to project users data
                        projectUsers.push({
                            projectId: data.project.id,
                            userId: data.project.managerId,
                            role: -1,
                            main: 1
                        });

                        // Fetch detailed user data
                        fetchUserData();
                    }
                });
        }

        /**
         * Function to fetch detailed user data from database.
         *
         * @todo refactor role text determination.
         * @todo change each to use async.map
         */
        function fetchUserData() {
            // Iterate project users, we have always at least one user
            _.each(data.users, function(/** sails.json.projectUser */projectUser) {
                // Initialize project user user property
                projectUser.data = false;

                var roleText = "Unknown";

                switch (projectUser.role) {
                    case -1:
                        roleText = "Manager";
                        break;
                    case 0:
                        roleText = "Viewer";
                        break;
                    case 1:
                        roleText = "User";
                        break;
                }

                projectUser.roleText = roleText;

                // Fetch single user data from database
                User
                    .findOne(projectUser.userId)
                    .done(function(error, user) {
                        if (error) {
                            res.send(error, 500);
                        } else if (!user) {
                            res.send("User not found.", 404);
                        } else {
                            jQuery.extend(projectUser, user, {data: true});

                            makeView();
                        }
                    });
            });
        }

        /**
         * Function makes actual view if all necessary data is fetched
         * from database for template.
         */
        function makeView() {
            if (data.users.length > 0) {
                var show = true;

                // Check that we have fetched all users data for project
                _.each(data.users, function(/** sails.json.projectUser */projectUser) {
                    // All user data are not yet fetched
                    if (projectUser.data === false) {
                        show = false;
                    }
                });

                if (show) {
                    // Sort user data
                    data.users = _.sortBy(data.users, function(user) {
                        return [user.role, user.fullName(), user.username].join("|");
                    });

                    res.view(data);
                }
            } else {
                res.view(data);
            }
        }
    },

    /**
     * This actions fetches available users for specified project. These users can be
     * attached to specified project.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     */
    availableUsers: function(req, res) {
        var projectId = parseInt(req.param('projectId'), 10);
        var userIds = [];

        // Fetch project data
        Project
            .findOne(projectId)
            .done(function(error, project) {
                if (error) {
                    res.send(error, 500);
                } else if (!project) {
                    res.send("Project not found.", 404);
                } else {
                    // Add project manager to "used" users
                    userIds.push({id: {"!": project.managerId}});

                    // Fetch current attached users
                    fetchCurrentUsers();
                }
            });

        /**
         * Private function to fetch all users who are already attached
         * to specified project.
         */
        function fetchCurrentUsers() {
            ProjectUser
                .find()
                .where({projectId: projectId})
                .done(function(error, users) {
                    if (error) {
                        res.send(error, 500);
                    } else {
                        // Iterate users and add those to "used" users
                        _.each(users, function(projectUser) {
                            userIds.push({id: {"!": projectUser.userId}});
                        });

                        // And finally fetch available users
                        fetchAvailableUsers();
                    }
                });
        }

        /**
         * Private function to fetch all available users for
         * specified project.
         *
         * @todo exclude admin users for this list
         */
        function fetchAvailableUsers() {
            User
                .find()
                .where({
                    and: userIds
                })
                .done(function(error, users) {
                    if (error) {
                        res.send(error, 500);
                    } else {
                        res.json(users);
                    }
                });
        }
    },

    /**
     * This actions fetches available users for specified project. These users can be
     * attached to specified project.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     */
    ownProjects: function(req, res) {
        var projectIds = [];

        // Make parallel call
        async.parallel([
            /**
             * First fetch all projects where current user is a contributor in
             * some role.
             *
             * @param   {Function}  callback
             */
            function(callback) {
                ProjectUser
                    .find()
                    .where({
                        userId: req.user.id
                    })
                    .done(function(error, /** sails.json.projectUser[] */projectUsers) {
                        if (error) {
                            return callback(error)
                        } else {
                            _.each(projectUsers, function(/** sails.json.projectUser */projectUser) {
                                projectIds.push({id: projectUser.projectId})
                            });

                            callback();
                        }
                    });
            },

            /**
             * Then fetch project id(s) where current user is a primary manager.
             *
             * @param   {Function}  callback
             */
            function(callback) {
                Project
                    .find()
                    .where({
                        managerId: req.user.id
                    })
                    .done(function(error, /** sails.json.project[] */projects) {
                        if (error) {
                            return callback(error)
                        } else {
                            _.each(projects, function(/** sails.json.project */project) {
                                projectIds.push({id: project.id})
                            });

                            callback();
                        }
                    });
            }
        ],
            /**
             * Callback function which is called when all parallel jobs are processed.
             *
             * @param error
             */
            function(error) {
                if (error) {
                    res.send(error, 500);
                }

                var where = null;

                // Admin user has all projects
                if (req.user.admin) {
                    where = {};
                } else if (projectIds.length > 0) { // Current user has "some" project(s)
                    where = {
                        or: projectIds
                    };
                } else { // Otherwise just send empty data
                    res.json([]);
                }

                // Fetch project data
                Project
                    .find()
                    .where(where)
                    .done(function(error, /** sails.json.project[] */projects) {
                        if (error) {
                            res.send(error, 500);
                        } else {
                            res.json(projects);
                        }
                    });
            }
        );
    },

    /**
     * Method returns user role in specified project. Successfully output is always
     * json which contains user role:
     *
     *  -3 = User is administrator
     *  -2 = Project manager (primary)
     *  -1 = Project manager
     *   0 = Only view rights
     *   1 = Normal user
     *
     * false if nothing matches.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     *
     * @constructor
     */
    getRole: function(req, res) {
        var projectId = parseInt(req.param("projectId"), 10);

        // Admin user, always return -3
        if (req.user.admin) {
            res.json(200, -3);
        } else { // Otherwise fetch user role
            async.parallel(
                {
                    /**
                     * Function to fetch possible Project object for signed in user and
                     * specified project. User must be project manager.
                     *
                     * Note that this query may return undefined.
                     *
                     * @param   {Function}  callback
                     */
                    primary: function(callback) {
                        Project
                            .findOne({
                                id: projectId,
                                managerId: req.user.id
                            })
                            .done(function(error, /** sails.model.project */project) {
                                if (error) {
                                    callback(error, null);
                                } else {
                                    callback(null, project)
                                }
                            });
                    },

                    /**
                     * Function to fetch possible ProjectUser object for signed in user
                     * and specified project.
                     *
                     * Note that this query may return undefined.
                     *
                     * @param   {Function}  callback
                     */
                    contributor: function(callback) {
                        ProjectUser
                            .findOne({
                                projectId: projectId,
                                userId: req.user.id
                            })
                            .done(function(error, /** sails.model.projectUser */projectUser) {
                                if (error) {
                                    callback(error, null);
                                } else {
                                    callback(null, projectUser)
                                }
                            });
                    }
                },

                /**
                 * Callback function which is been called after all parallel jobs are
                 * processed.
                 *
                 * @param   {Error} error
                 * @param   {{}}    results
                 */
                function(error, results) {
                    var output = false;

                    if (results.primary) {
                        output = -2;
                    } else if (results.contributor) {
                        output = results.contributor.role;
                    }

                    res.json(200, output);
                }
            );
        }
    }
};
<commit_msg>Filtered out administrator users from project user list.<commit_after>/**
 * ProjectUserController
 *
 * @module      :: Controller
 * @description :: Contains logic for handling requests.
 */
var jQuery = require("jquery");
var async = require("async");

module.exports = {
    /**
     * This actions makes view for project users. Note that 'projectId' parameter is
     * required for this action.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     */
    users: function(req, res) {
        var projectId = req.param("projectId");
        var data = {
            layout: req.isAjax ? "layout_ajax" : "layout",
            users: false,
            project: false,
            role: false,
            signedIn: req.user
        };

        async.parallel(
            {
                // Fetch project data
                project: function(callback) {
                    DataService.getProject(projectId, callback);
                },

                // Fetch current user role in project
                role: function(callback) {
                    AuthService.hasProjectAccess(req.user, projectId, callback, true);
                }
            },

            /**
             * Callback function that is called after all parallel jobs are done
             * or some error has happen in those
             *
             * @param   {Error} error   Error data
             * @param   {{}}    results Object that contains following data:
             *                           - project {sails.model.project}
             *                           - role, User role in current project
             */
            function callback(error, results) {
                if (error) {
                    res.send(error.status ? error.status : 500, error);
                } else {
                    data.project = results.project;
                    data.role = results.role;

                    fetchProjectUsers();
                }
            }
        );

        /**
         * Function to fetch project user data. Also note that this will add selected
         * project manager to this user list.
         *
         * todo:    potential bug for duplicate user, eg user is attached to project
         *          and afterwards this same user has been selected to project manager.
         *
         *          This is not a big deal yet, but remember to handle this :D
         */
        function fetchProjectUsers() {
            // Fetch all project user
            ProjectUser
                .find()
                .where({projectId: projectId})
                .done(function(error, /** sails.json.projectUser */projectUsers) {
                    if (error) {
                        res.send(error, 500);
                    } else {
                        data.users = projectUsers;

                        // Add project main manager to project users data
                        projectUsers.push({
                            projectId: data.project.id,
                            userId: data.project.managerId,
                            role: -1,
                            main: 1
                        });

                        // Fetch detailed user data
                        fetchUserData();
                    }
                });
        }

        /**
         * Function to fetch detailed user data from database.
         *
         * @todo refactor role text determination.
         * @todo change each to use async.map
         */
        function fetchUserData() {
            // Iterate project users, we have always at least one user
            _.each(data.users, function(/** sails.json.projectUser */projectUser) {
                // Initialize project user user property
                projectUser.data = false;

                var roleText = "Unknown";

                switch (projectUser.role) {
                    case -1:
                        roleText = "Manager";
                        break;
                    case 0:
                        roleText = "Viewer";
                        break;
                    case 1:
                        roleText = "User";
                        break;
                }

                projectUser.roleText = roleText;

                // Fetch single user data from database
                User
                    .findOne(projectUser.userId)
                    .done(function(error, user) {
                        if (error) {
                            res.send(error, 500);
                        } else if (!user) {
                            res.send("User not found.", 404);
                        } else {
                            jQuery.extend(projectUser, user, {data: true});

                            makeView();
                        }
                    });
            });
        }

        /**
         * Function makes actual view if all necessary data is fetched
         * from database for template.
         */
        function makeView() {
            if (data.users.length > 0) {
                var show = true;

                // Check that we have fetched all users data for project
                _.each(data.users, function(/** sails.json.projectUser */projectUser) {
                    // All user data are not yet fetched
                    if (projectUser.data === false) {
                        show = false;
                    }
                });

                if (show) {
                    // Sort user data
                    data.users = _.sortBy(data.users, function(user) {
                        return [user.role, user.fullName(), user.username].join("|");
                    });

                    res.view(data);
                }
            } else {
                res.view(data);
            }
        }
    },

    /**
     * This actions fetches available users for specified project. These users can be
     * attached to specified project.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     */
    availableUsers: function(req, res) {
        var projectId = parseInt(req.param('projectId'), 10);
        var userIds = [];

        // Fetch project data
        Project
            .findOne(projectId)
            .done(function(error, project) {
                if (error) {
                    res.send(error, 500);
                } else if (!project) {
                    res.send("Project not found.", 404);
                } else {
                    // Add project manager to "used" users
                    userIds.push({id: {"!": project.managerId}});

                    // Fetch current attached users
                    fetchCurrentUsers();
                }
            });

        /**
         * Private function to fetch all users who are already attached
         * to specified project.
         */
        function fetchCurrentUsers() {
            ProjectUser
                .find()
                .where({projectId: projectId})
                .done(function(error, users) {
                    if (error) {
                        res.send(error, 500);
                    } else {
                        // Iterate users and add those to "used" users
                        _.each(users, function(projectUser) {
                            userIds.push({id: {"!": projectUser.userId}});
                        });

                        // And finally fetch available users
                        fetchAvailableUsers();
                    }
                });
        }

        /**
         * Private function to fetch all available users for
         * specified project.
         */
        function fetchAvailableUsers() {
            User
                .find()
                .where({
                    and: userIds,
                    admin: 0
                })
                .done(function(error, users) {
                    if (error) {
                        res.send(error, 500);
                    } else {
                        res.json(users);
                    }
                });
        }
    },

    /**
     * This actions fetches available users for specified project. These users can be
     * attached to specified project.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     */
    ownProjects: function(req, res) {
        var projectIds = [];

        // Make parallel call
        async.parallel([
            /**
             * First fetch all projects where current user is a contributor in
             * some role.
             *
             * @param   {Function}  callback
             */
            function(callback) {
                ProjectUser
                    .find()
                    .where({
                        userId: req.user.id
                    })
                    .done(function(error, /** sails.json.projectUser[] */projectUsers) {
                        if (error) {
                            return callback(error)
                        } else {
                            _.each(projectUsers, function(/** sails.json.projectUser */projectUser) {
                                projectIds.push({id: projectUser.projectId})
                            });

                            callback();
                        }
                    });
            },

            /**
             * Then fetch project id(s) where current user is a primary manager.
             *
             * @param   {Function}  callback
             */
            function(callback) {
                Project
                    .find()
                    .where({
                        managerId: req.user.id
                    })
                    .done(function(error, /** sails.json.project[] */projects) {
                        if (error) {
                            return callback(error)
                        } else {
                            _.each(projects, function(/** sails.json.project */project) {
                                projectIds.push({id: project.id})
                            });

                            callback();
                        }
                    });
            }
        ],
            /**
             * Callback function which is called when all parallel jobs are processed.
             *
             * @param error
             */
            function(error) {
                if (error) {
                    res.send(error, 500);
                }

                var where = null;

                // Admin user has all projects
                if (req.user.admin) {
                    where = {};
                } else if (projectIds.length > 0) { // Current user has "some" project(s)
                    where = {
                        or: projectIds
                    };
                } else { // Otherwise just send empty data
                    res.json([]);
                }

                // Fetch project data
                Project
                    .find()
                    .where(where)
                    .done(function(error, /** sails.json.project[] */projects) {
                        if (error) {
                            res.send(error, 500);
                        } else {
                            res.json(projects);
                        }
                    });
            }
        );
    },

    /**
     * Method returns user role in specified project. Successfully output is always
     * json which contains user role:
     *
     *  -3 = User is administrator
     *  -2 = Project manager (primary)
     *  -1 = Project manager
     *   0 = Only view rights
     *   1 = Normal user
     *
     * false if nothing matches.
     *
     * @param   {Request}   req Request object
     * @param   {Response}  res Response object
     *
     * @constructor
     */
    getRole: function(req, res) {
        var projectId = parseInt(req.param("projectId"), 10);

        // Admin user, always return -3
        if (req.user.admin) {
            res.json(200, -3);
        } else { // Otherwise fetch user role
            async.parallel(
                {
                    /**
                     * Function to fetch possible Project object for signed in user and
                     * specified project. User must be project manager.
                     *
                     * Note that this query may return undefined.
                     *
                     * @param   {Function}  callback
                     */
                    primary: function(callback) {
                        Project
                            .findOne({
                                id: projectId,
                                managerId: req.user.id
                            })
                            .done(function(error, /** sails.model.project */project) {
                                if (error) {
                                    callback(error, null);
                                } else {
                                    callback(null, project)
                                }
                            });
                    },

                    /**
                     * Function to fetch possible ProjectUser object for signed in user
                     * and specified project.
                     *
                     * Note that this query may return undefined.
                     *
                     * @param   {Function}  callback
                     */
                    contributor: function(callback) {
                        ProjectUser
                            .findOne({
                                projectId: projectId,
                                userId: req.user.id
                            })
                            .done(function(error, /** sails.model.projectUser */projectUser) {
                                if (error) {
                                    callback(error, null);
                                } else {
                                    callback(null, projectUser)
                                }
                            });
                    }
                },

                /**
                 * Callback function which is been called after all parallel jobs are
                 * processed.
                 *
                 * @param   {Error} error
                 * @param   {{}}    results
                 */
                function(error, results) {
                    var output = false;

                    if (results.primary) {
                        output = -2;
                    } else if (results.contributor) {
                        output = results.contributor.role;
                    }

                    res.json(200, output);
                }
            );
        }
    }
};
<|endoftext|>


<commit_before><commit_msg>Fixed SwapSim POA case not checked to delete customer-agent<commit_after><|endoftext|>


<commit_before>if (! window.XOSLIB_LOADED ) {
    window.XOSLIB_LOADED=true;

    SLIVER_API = "/plstackapi/slivers/";
    SLICE_API = "/plstackapi/slices/";
    SLICEDEPLOYMENT_API = "/plstackapi/slice_deployments/";
    SLICEPRIVILEGE_API = "/plstackapi/slice_privileges/";
    SLICEROLE_API = "/plstackapi/slice_roles/";
    NODE_API = "/plstackapi/nodes/";
    SITE_API = "/plstackapi/sites/";
    USER_API = "/plstackapi/users/";
    USERDEPLOYMENT_API = "/plstackapi/user_deployments/";
    DEPLOYMENT_API = "/plstackapi/deployments/";
    IMAGE_API = "/plstackapi/images/";
    NETWORKTEMPLATE_API = "/plstackapi/networktemplates/";
    NETWORKDEPLOYMENT_API = "/plstackapi/networkdeployments/";
    NETWORK_API = "/plstackapi/networks/";
    NETWORKSLIVER_API = "/plstackapi/networkslivers/";
    SERVICE_API = "/plstackapi/services/";

    SLICEPLUS_API = "/xoslib/slicesplus/";

    XOSModel = Backbone.Model.extend({
        /* from backbone-tastypie.js */
        //idAttribute: 'resource_uri',

        /* from backbone-tastypie.js */
        url: function() {
                    var url = this.attributes.resource_uri;

                    if (!url) {
                        url = this.urlRoot + this.id;
                    }

                    if (!url) {
                        // XXX I'm not sure this does anything useful
                        url = ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
                        url = url || this.urlRoot;
                    }

                    // remove any existing query parameters
                    url && ( url.indexOf("?") > -1 ) && ( url = url.split("?")[0] );

                    url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );

                    url && ( url += "?no_hyperlinks=1" );

                    return url;
            },

            listMethods: function() {
                var res = [];
                for(var m in this) {
                    if(typeof this[m] == "function") {
                        res.push(m)
                    }
                }
                return res;
            }
    });

    XOSCollection = Backbone.Collection.extend({
        objects: function() {
                    return this.models.map(function(element) { return element.attributes; });
                 },

        initialize: function(){
          this.isLoaded = false;
          this.sortVar = 'name';
          this.sortOrder = 'asc';
          this.on( "sort", this.sorted );
        },

        relatedCollections: [],
        foreignCollections: [],

        sorted: function() {
            this.isLoaded = true;
        },

        simpleComparator: function( model ){
          parts=this.sortVar.split(".");
          result = model.get(parts[0]);
          for (index=1; index<parts.length; ++index) {
              result=result[parts[index]];
          }
          return result;
        },

        comparator: function (left, right) {
            var l = this.simpleComparator(left);
            var r = this.simpleComparator(right);

            if (l === void 0) return -1;
            if (r === void 0) return 1;

            if (this.sortOrder=="desc") {
                return l < r ? 1 : l > r ? -1 : 0;
            } else {
                return l < r ? -1 : l > r ? 1 : 0;
            }
        },

        startPolling: function() {
            if (!this._polling) {
                var collection=this;
                setInterval(function() { collection.fetch(); }, 10000);
                this._polling=true;
                this.fetch();
            }
        },

        maybeFetch: function(options){
                // Helper function to fetch only if this collection has not been fetched before.
            if(this._fetched){
                    // If this has already been fetched, call the success, if it exists
                options.success && options.success();
                console.log("alreadyFetched");
                return;
            }

                // when the original success function completes mark this collection as fetched
            var self = this,
            successWrapper = function(success){
                return function(){
                    self._fetched = true;
                    success && success.apply(this, arguments);
                };
            };
            options.success = successWrapper(options.success);
            console.log("call fetch");
            this.fetch(options);
        },

        getOrFetch: function(id, options){
                // Helper function to use this collection as a cache for models on the server
            var model = this.get(id);

            if(model){
                options.success && options.success(model);
                return;
            }

            model = new this.model({
                resource_uri: id
            });

            model.fetch(options);
        },

        filterBy: function(fieldName, value) {
             filtered = this.filter(function(obj) {
                 return obj.get(fieldName) == value;
                 });
             return new this.constructor(filtered);
        },

        /* from backbone-tastypie.js */
        url: function( models ) {
                    var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
                    url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );

                    // Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
                    // (set to 'resource_uri') contains the model's id.
                    if ( models && models.length ) {
                            var ids = _.map( models, function( model ) {
                                            var parts = _.compact( model.id.split('/') );
                                            return parts[ parts.length - 1 ];
                                    });
                            url += 'set/' + ids.join(';') + '/';
                    }

                    url && ( url += "?no_hyperlinks=1" );

                    return url;
            },

        listMethods: function() {
                var res = [];
                for(var m in this) {
                    if(typeof this[m] == "function") {
                        res.push(m)
                    }
                }
                return res;
            },
    });

    function xoslib() {
        // basic REST
        this.sliver = XOSModel.extend({ urlRoot: SLIVER_API, modelName: "sliver" });
        this.sliverCollection = XOSCollection.extend({ urlRoot: SLIVER_API,
                                                       relatedCollections: {"networkSlivers": "sliver"},
                                                       foreignCollections: ["slices", "deployments", "images", "nodes", "users"],
                                                       model: this.sliver});
        this.slivers = new this.sliverCollection();

        this.slice = XOSModel.extend({ urlRoot: SLICE_API, modelName: "slice" });
        this.sliceCollection = XOSCollection.extend({ urlRoot: SLICE_API,
                                                       relatedCollections: {"slivers": "slice", "sliceDeployments": "slice", "slicePrivileges": "slice", "networks": "owner"},
                                                       foreignCollections: ["services", "sites"],
                                                       model: this.slice});
        this.slices = new this.sliceCollection();

        this.sliceDeployment = XOSModel.extend({ urlRoot: SLICEDEPLOYMENT_API, modelName: "sliceDeployment" });
        this.sliceDeploymentCollection = XOSCollection.extend({ urlRoot: SLICEDEPLOYMENT_API,
                                                       foreignCollections: ["slices", "deployments"],
                                                       model: this.slice});
        this.sliceDeployments = new this.sliceDeploymentCollection();

        this.slicePrivilege = XOSModel.extend({ urlRoot: SLICEPRIVILEGE_API, modelName: "slicePrivilege" });
        this.slicePrivilegeCollection = XOSCollection.extend({ urlRoot: SLICEPRIVILEGE_API,
                                                       foreignCollections: ["slices", "users", "sliceRoles"],
                                                       model: this.slice});
        this.slicePrivileges = new this.slicePrivilegeCollection();

        this.sliceRole = XOSModel.extend({ urlRoot: SLICEROLE_API, modelName: "sliceRole" });
        this.sliceRoleCollection = XOSCollection.extend({ urlRoot: SLICEROLE_API,
                                                       model: this.slice});
        this.sliceRoles = new this.sliceRoleCollection();

        this.node = XOSModel.extend({ urlRoot: NODE_API, modelName: "node" });
        this.nodeCollection = XOSCollection.extend({ urlRoot: NODE_API,
                                                       foreignCollections: ["sites", "deployments"],
                                                       model: this.node});
        this.nodes = new this.nodeCollection();

        this.site = XOSModel.extend({ urlRoot: SITE_API, modelName: "site" });
        this.siteCollection = XOSCollection.extend({ urlRoot: SITE_API,
                                                       model: this.site});
        this.sites = new this.siteCollection();

        this.user = XOSModel.extend({ urlRoot: USER_API, modelName: "user" });
        this.userCollection = XOSCollection.extend({ urlRoot: USER_API,
                                                       relatedCollections: {"slicePrivileges": "user", "slices": "owner", "userDeployments": "user"},
                                                       foreignCollections: ["sites"],
                                                       model: this.user});
        this.users = new this.userCollection();

        this.userDeployment = XOSModel.extend({ urlRoot: USERDEPLOYMENT_API, modelName: "userDeployment" });
        this.userDeploymentCollection = XOSCollection.extend({ urlRoot: USERDEPLOYMENT_API,
                                                       foreignCollections: ["users","deployments"],
                                                       model: this.user});
        this.userDeployments = new this.userDeploymentCollection();

        this.deployment = XOSModel.extend({ urlRoot: DEPLOYMENT_API, modelName: "deployment" });
        this.deploymentCollection = XOSCollection.extend({ urlRoot: DEPLOYMENT_API,
                                                           relatedCollections: {"slivers": "deploymentNetwork", "networkDeployments": "deployment", "userDeployments": "deployment"},
                                                           model: this.deployment});
        this.deployments = new this.deploymentCollection();

        this.image = XOSModel.extend({ urlRoot: IMAGE_API, modelName: "image" });
        this.imageCollection = XOSCollection.extend({ urlRoot: IMAGE_API,
                                                           model: this.image});
        this.images = new this.imageCollection();

        this.networkTemplate = XOSModel.extend({ urlRoot: NETWORKTEMPLATE_API, modelName: "networkTemplate" });
        this.networkTemplateCollection = XOSCollection.extend({ urlRoot: NETWORKTEMPLATE_API,
                                                           model: this.networkTemplate});
        this.networkTemplates = new this.networkTemplateCollection();

        this.network = XOSModel.extend({ urlRoot: NETWORK_API, modelName: "network" });
        this.networkCollection = XOSCollection.extend({ urlRoot: NETWORK_API,
                                                           relatedCollections: {"networkDeployments": "network", "networkSlivers": "network"},
                                                           foreignCollections: ["slices", "networkTemplates"],
                                                           model: this.network});
        this.networks = new this.networkCollection();

        this.networkSliver = XOSModel.extend({ urlRoot: NETWORKSLIVER_API, modelName: "networkSliver" });
        this.networkSliverCollection = XOSCollection.extend({ urlRoot: NETWORKSLIVER_API,
                                                           model: this.networkSliver});
        this.networkSlivers = new this.networkSliverCollection();

        this.networkDeployment = XOSModel.extend({ urlRoot: NETWORKDEPLOYMENT_API, modelName: "networkDeployment" });
        this.networkDeploymentCollection = XOSCollection.extend({ urlRoot: NETWORKDEPLOYMENT_API,
                                                           model: this.networkDeployment});
        this.networkDeployments = new this.networkDeploymentCollection();

        this.service = XOSModel.extend({ urlRoot: SERVICE_API, modelName: "sliver" });
        this.serviceCollection = XOSCollection.extend({ urlRoot: SERVICE_API,
                                                       model: this.service});
        this.services = new this.serviceCollection();

        // enhanced REST
        this.slicePlus = XOSModel.extend({ urlRoot: SLICEPLUS_API, modelName: "slicePlus" });
        this.slicePlusCollection = XOSCollection.extend({ urlRoot: SLICEPLUS_API,
                                                          relatedCollections: {'slivers': "slice"},
                                                          model: this.slicePlus});
        this.slicesPlus = new this.slicePlusCollection();

        this.listObjects = function() { return ["slivers", "slices", "nodes", "sites", "users", "deployments"]; };
    };

    xos = new xoslib();

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    (function() {
      var _sync = Backbone.sync;
      Backbone.sync = function(method, model, options){
        options.beforeSend = function(xhr){
          var token = getCookie("csrftoken");
          xhr.setRequestHeader('X-CSRFToken', token);
        };
        return _sync(method, model, options);
      };
    })();
}
<commit_msg>more relatedCollections in xos-backbone.js<commit_after>if (! window.XOSLIB_LOADED ) {
    window.XOSLIB_LOADED=true;

    SLIVER_API = "/plstackapi/slivers/";
    SLICE_API = "/plstackapi/slices/";
    SLICEDEPLOYMENT_API = "/plstackapi/slice_deployments/";
    SLICEPRIVILEGE_API = "/plstackapi/slice_privileges/";
    SLICEROLE_API = "/plstackapi/slice_roles/";
    NODE_API = "/plstackapi/nodes/";
    SITE_API = "/plstackapi/sites/";
    USER_API = "/plstackapi/users/";
    USERDEPLOYMENT_API = "/plstackapi/user_deployments/";
    DEPLOYMENT_API = "/plstackapi/deployments/";
    IMAGE_API = "/plstackapi/images/";
    NETWORKTEMPLATE_API = "/plstackapi/networktemplates/";
    NETWORKDEPLOYMENT_API = "/plstackapi/networkdeployments/";
    NETWORK_API = "/plstackapi/networks/";
    NETWORKSLIVER_API = "/plstackapi/networkslivers/";
    SERVICE_API = "/plstackapi/services/";

    SLICEPLUS_API = "/xoslib/slicesplus/";

    XOSModel = Backbone.Model.extend({
        /* from backbone-tastypie.js */
        //idAttribute: 'resource_uri',

        /* from backbone-tastypie.js */
        url: function() {
                    var url = this.attributes.resource_uri;

                    if (!url) {
                        url = this.urlRoot + this.id;
                    }

                    if (!url) {
                        // XXX I'm not sure this does anything useful
                        url = ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
                        url = url || this.urlRoot;
                    }

                    // remove any existing query parameters
                    url && ( url.indexOf("?") > -1 ) && ( url = url.split("?")[0] );

                    url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );

                    url && ( url += "?no_hyperlinks=1" );

                    return url;
            },

            listMethods: function() {
                var res = [];
                for(var m in this) {
                    if(typeof this[m] == "function") {
                        res.push(m)
                    }
                }
                return res;
            }
    });

    XOSCollection = Backbone.Collection.extend({
        objects: function() {
                    return this.models.map(function(element) { return element.attributes; });
                 },

        initialize: function(){
          this.isLoaded = false;
          this.sortVar = 'name';
          this.sortOrder = 'asc';
          this.on( "sort", this.sorted );
        },

        relatedCollections: [],
        foreignCollections: [],

        sorted: function() {
            this.isLoaded = true;
        },

        simpleComparator: function( model ){
          parts=this.sortVar.split(".");
          result = model.get(parts[0]);
          for (index=1; index<parts.length; ++index) {
              result=result[parts[index]];
          }
          return result;
        },

        comparator: function (left, right) {
            var l = this.simpleComparator(left);
            var r = this.simpleComparator(right);

            if (l === void 0) return -1;
            if (r === void 0) return 1;

            if (this.sortOrder=="desc") {
                return l < r ? 1 : l > r ? -1 : 0;
            } else {
                return l < r ? -1 : l > r ? 1 : 0;
            }
        },

        startPolling: function() {
            if (!this._polling) {
                var collection=this;
                setInterval(function() { collection.fetch(); }, 10000);
                this._polling=true;
                this.fetch();
            }
        },

        maybeFetch: function(options){
                // Helper function to fetch only if this collection has not been fetched before.
            if(this._fetched){
                    // If this has already been fetched, call the success, if it exists
                options.success && options.success();
                console.log("alreadyFetched");
                return;
            }

                // when the original success function completes mark this collection as fetched
            var self = this,
            successWrapper = function(success){
                return function(){
                    self._fetched = true;
                    success && success.apply(this, arguments);
                };
            };
            options.success = successWrapper(options.success);
            console.log("call fetch");
            this.fetch(options);
        },

        getOrFetch: function(id, options){
                // Helper function to use this collection as a cache for models on the server
            var model = this.get(id);

            if(model){
                options.success && options.success(model);
                return;
            }

            model = new this.model({
                resource_uri: id
            });

            model.fetch(options);
        },

        filterBy: function(fieldName, value) {
             filtered = this.filter(function(obj) {
                 return obj.get(fieldName) == value;
                 });
             return new this.constructor(filtered);
        },

        /* from backbone-tastypie.js */
        url: function( models ) {
                    var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
                    url && ( url += ( url.length > 0 && url.charAt( url.length - 1 ) === '/' ) ? '' : '/' );

                    // Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
                    // (set to 'resource_uri') contains the model's id.
                    if ( models && models.length ) {
                            var ids = _.map( models, function( model ) {
                                            var parts = _.compact( model.id.split('/') );
                                            return parts[ parts.length - 1 ];
                                    });
                            url += 'set/' + ids.join(';') + '/';
                    }

                    url && ( url += "?no_hyperlinks=1" );

                    return url;
            },

        listMethods: function() {
                var res = [];
                for(var m in this) {
                    if(typeof this[m] == "function") {
                        res.push(m)
                    }
                }
                return res;
            },
    });

    function xoslib() {
        // basic REST
        this.sliver = XOSModel.extend({ urlRoot: SLIVER_API, modelName: "sliver" });
        this.sliverCollection = XOSCollection.extend({ urlRoot: SLIVER_API,
                                                       relatedCollections: {"networkSlivers": "sliver"},
                                                       foreignCollections: ["slices", "deployments", "images", "nodes", "users"],
                                                       model: this.sliver});
        this.slivers = new this.sliverCollection();

        this.slice = XOSModel.extend({ urlRoot: SLICE_API, modelName: "slice" });
        this.sliceCollection = XOSCollection.extend({ urlRoot: SLICE_API,
                                                       relatedCollections: {"slivers": "slice", "sliceDeployments": "slice", "slicePrivileges": "slice", "networks": "owner"},
                                                       foreignCollections: ["services", "sites"],
                                                       model: this.slice});
        this.slices = new this.sliceCollection();

        this.sliceDeployment = XOSModel.extend({ urlRoot: SLICEDEPLOYMENT_API, modelName: "sliceDeployment" });
        this.sliceDeploymentCollection = XOSCollection.extend({ urlRoot: SLICEDEPLOYMENT_API,
                                                       foreignCollections: ["slices", "deployments"],
                                                       model: this.slice});
        this.sliceDeployments = new this.sliceDeploymentCollection();

        this.slicePrivilege = XOSModel.extend({ urlRoot: SLICEPRIVILEGE_API, modelName: "slicePrivilege" });
        this.slicePrivilegeCollection = XOSCollection.extend({ urlRoot: SLICEPRIVILEGE_API,
                                                       foreignCollections: ["slices", "users", "sliceRoles"],
                                                       model: this.slice});
        this.slicePrivileges = new this.slicePrivilegeCollection();

        this.sliceRole = XOSModel.extend({ urlRoot: SLICEROLE_API, modelName: "sliceRole" });
        this.sliceRoleCollection = XOSCollection.extend({ urlRoot: SLICEROLE_API,
                                                       model: this.slice});
        this.sliceRoles = new this.sliceRoleCollection();

        this.node = XOSModel.extend({ urlRoot: NODE_API, modelName: "node" });
        this.nodeCollection = XOSCollection.extend({ urlRoot: NODE_API,
                                                       foreignCollections: ["sites", "deployments"],
                                                       model: this.node});
        this.nodes = new this.nodeCollection();

        this.site = XOSModel.extend({ urlRoot: SITE_API, modelName: "site" });
        this.siteCollection = XOSCollection.extend({ urlRoot: SITE_API,
                                                       relatedCollections: {"users": "site", "slices": "site", "nodes": "site"},
                                                       model: this.site});
        this.sites = new this.siteCollection();

        this.user = XOSModel.extend({ urlRoot: USER_API, modelName: "user" });
        this.userCollection = XOSCollection.extend({ urlRoot: USER_API,
                                                       relatedCollections: {"slicePrivileges": "user", "slices": "owner", "userDeployments": "user"},
                                                       foreignCollections: ["sites"],
                                                       model: this.user});
        this.users = new this.userCollection();

        this.userDeployment = XOSModel.extend({ urlRoot: USERDEPLOYMENT_API, modelName: "userDeployment" });
        this.userDeploymentCollection = XOSCollection.extend({ urlRoot: USERDEPLOYMENT_API,
                                                       foreignCollections: ["users","deployments"],
                                                       model: this.user});
        this.userDeployments = new this.userDeploymentCollection();

        this.deployment = XOSModel.extend({ urlRoot: DEPLOYMENT_API, modelName: "deployment" });
        this.deploymentCollection = XOSCollection.extend({ urlRoot: DEPLOYMENT_API,
                                                           relatedCollections: {"nodes": "deployment", "slivers": "deploymentNetwork", "networkDeployments": "deployment", "userDeployments": "deployment"},
                                                           model: this.deployment});
        this.deployments = new this.deploymentCollection();

        this.image = XOSModel.extend({ urlRoot: IMAGE_API, modelName: "image" });
        this.imageCollection = XOSCollection.extend({ urlRoot: IMAGE_API,
                                                           model: this.image});
        this.images = new this.imageCollection();

        this.networkTemplate = XOSModel.extend({ urlRoot: NETWORKTEMPLATE_API, modelName: "networkTemplate" });
        this.networkTemplateCollection = XOSCollection.extend({ urlRoot: NETWORKTEMPLATE_API,
                                                           model: this.networkTemplate});
        this.networkTemplates = new this.networkTemplateCollection();

        this.network = XOSModel.extend({ urlRoot: NETWORK_API, modelName: "network" });
        this.networkCollection = XOSCollection.extend({ urlRoot: NETWORK_API,
                                                           relatedCollections: {"networkDeployments": "network", "networkSlivers": "network"},
                                                           foreignCollections: ["slices", "networkTemplates"],
                                                           model: this.network});
        this.networks = new this.networkCollection();

        this.networkSliver = XOSModel.extend({ urlRoot: NETWORKSLIVER_API, modelName: "networkSliver" });
        this.networkSliverCollection = XOSCollection.extend({ urlRoot: NETWORKSLIVER_API,
                                                           model: this.networkSliver});
        this.networkSlivers = new this.networkSliverCollection();

        this.networkDeployment = XOSModel.extend({ urlRoot: NETWORKDEPLOYMENT_API, modelName: "networkDeployment" });
        this.networkDeploymentCollection = XOSCollection.extend({ urlRoot: NETWORKDEPLOYMENT_API,
                                                           model: this.networkDeployment});
        this.networkDeployments = new this.networkDeploymentCollection();

        this.service = XOSModel.extend({ urlRoot: SERVICE_API, modelName: "sliver" });
        this.serviceCollection = XOSCollection.extend({ urlRoot: SERVICE_API,
                                                       model: this.service});
        this.services = new this.serviceCollection();

        // enhanced REST
        this.slicePlus = XOSModel.extend({ urlRoot: SLICEPLUS_API, modelName: "slicePlus" });
        this.slicePlusCollection = XOSCollection.extend({ urlRoot: SLICEPLUS_API,
                                                          relatedCollections: {'slivers': "slice"},
                                                          model: this.slicePlus});
        this.slicesPlus = new this.slicePlusCollection();

        this.listObjects = function() { return ["slivers", "slices", "nodes", "sites", "users", "deployments"]; };
    };

    xos = new xoslib();

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    (function() {
      var _sync = Backbone.sync;
      Backbone.sync = function(method, model, options){
        options.beforeSend = function(xhr){
          var token = getCookie("csrftoken");
          xhr.setRequestHeader('X-CSRFToken', token);
        };
        return _sync(method, model, options);
      };
    })();
}
<|endoftext|>


<commit_before>export default class BaseApiService {
	constructor($http, $log, appConfig, websocket, path) {
		'ngInject';

		this.$http = $http;
		this.$log = $log;

		this._ = _;
		this.websocket = websocket;

		this.host = `${appConfig.host}:3000`;
		this.url = `http://${this.host}/api/${path}`;

		this.$log.info('constructor()', this);
	}

	get(query) {
		return this.$http.get(`${this.url}/${query}`);
	}

	update(data) {
		return this.$http.post(`${this.url}`, data);
	}
}
<commit_msg>Update the BaseApi service to accept 'id' for the update() method<commit_after>export default class BaseApiService {
	constructor($http, $log, appConfig, websocket, path) {
		'ngInject';

		this.$http = $http;
		this.$log = $log;

		this._ = _;
		this.websocket = websocket;

		this.host = `${appConfig.host}:3000`;
		this.url = `http://${this.host}/api/${path}`;

		this.$log.info('constructor()', this);
	}

	get(query) {
		return this.$http.get(`${this.url}/${query}`);
	}

	update(data, id = '') {
		return this.$http.post(`${this.url}/${id}`, data);
	}
}
<|endoftext|>


<commit_before>
var basal = require('./basal');
var targets = require('./targets');
var carbs = require('./carbs');
var isf = require('./isf');

function defaults ( ) {
    var profile = {
          max_iob: 0 // if max_iob.json is not profided, never give more insulin than the pump would have
        // , dia: pumpsettings_data.insulin_action_curve
        , type: "current"
    };
    return profile;
}

function generate (inputs, opts) {
  var profile = opts && opts.type ? opts : defaults( );

  if (inputs.settings.insulin_action_curve) {
    profile.dia =  pumpsettings_data.insulin_action_curve;
  }

  if (inputs.max_iob) {
    profile.max_iob = inputs.max_iob;
  }

  profile.current_basal = basal.basalLookup(inputs.basals);
  profile.max_daily_basal = basal.maxDailyBasal(inputs);
  profile.max_basal = basal.maxBasalLookup(inputs);

  var range = targets.bgTargetsLookup(inputs);
  profile.min_bg = range.min_bg;
  profile.max_bg = range.max_bg;
  profile.carbratio = carbs.carbRatioLookup(inputs);
  profile.sens = isf.isfLookup(inputs);

  return profile;
}

generate.defaults = defaults;
exports = module.exports = generate;

<commit_msg>fix finding all inputs<commit_after>
var basal = require('./basal');
var targets = require('./targets');
var carbs = require('./carbs');
var isf = require('./isf');

function defaults ( ) {
    var profile = {
          max_iob: 0 // if max_iob.json is not profided, never give more insulin than the pump would have
        // , dia: pumpsettings_data.insulin_action_curve
        , type: "current"
    };
    return profile;
}

function generate (inputs, opts) {
  var profile = opts && opts.type ? opts : defaults( );

  var pumpsettings_data = inputs.settings;
  if (inputs.settings.insulin_action_curve) {
    profile.dia =  pumpsettings_data.insulin_action_curve;
  }

  if (inputs.max_iob) {
    profile.max_iob = inputs.max_iob;
  }

  profile.current_basal = basal.basalLookup(inputs.basals);
  profile.max_daily_basal = basal.maxDailyBasal(inputs);
  profile.max_basal = basal.maxBasalLookup(inputs);

  var range = targets.bgTargetsLookup(inputs);
  profile.min_bg = range.min_bg;
  profile.max_bg = range.max_bg;
  profile.carbratio = carbs.carbRatioLookup(inputs);
  profile.sens = isf.isfLookup(inputs);

  return profile;
}

generate.defaults = defaults;
exports = module.exports = generate;

<|endoftext|>


<commit_before>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Aria.classDefinition({
    $classpath : "aria.templates.TemplateManager",
    $singleton : true,
    $events : {
        "unloadTemplate" : {
            description : "raised when unloadTemplate is finished"
        }
    },
    $prototype : {
        /**
         * Unload a template (cache/files/urls/scripts/CSS/resources associated)
         * @param {String} classpath the classpath of the class to be removed
         * @param {Boolean} timestampNextTime if true, the next time the class is loaded, browser and server cache will
         * be bypassed by adding a timestamp to the url.
         */
        unloadTemplate : function (classpath, timestampNextTime) {
            var classMgr = aria.core.ClassMgr;
            var scriptClasspath = classpath + "Script";
            // do some cleaning in cache
            if (Aria.nspace(scriptClasspath, false) || aria.core.Cache.getItem("classes", scriptClasspath)) {
                classMgr.unloadClass(scriptClasspath, timestampNextTime);
            }
            var itm = Aria.$classDefinitions[classpath];
            if (!Aria.nspace(classpath, false) && itm && itm.$css) {// when there is an error in the script, the class reference for
                // the template is not created, so the css would not be
                // unregistered in the unloadClass method
                aria.templates.CSSMgr.unregisterDependencies(classpath, itm.$css, true, timestampNextTime);
            }
            if (itm.$resources != null) {
                var resources = itm.$resources;
                for (var res in resources)
                    if (resources.hasOwnProperty(res)) {
                        classMgr.unloadClass(resources[res], timestampNextTime);
                    }
            }
            classMgr.unloadClass(classpath, timestampNextTime);
            // every thing is done : CSS are unhandled at classMgr level directly
            this.$raiseEvent("unloadTemplate");
        }
    }
});<commit_msg>Fix failing tests in Template Manager unload<commit_after>/*
 * Copyright 2012 Amadeus s.a.s.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

Aria.classDefinition({
    $classpath : "aria.templates.TemplateManager",
    $singleton : true,
    $events : {
        "unloadTemplate" : {
            description : "raised when unloadTemplate is finished"
        }
    },
    $prototype : {
        /**
         * Unload a template (cache/files/urls/scripts/CSS/resources associated)
         * @param {String} classpath the classpath of the class to be removed
         * @param {Boolean} timestampNextTime if true, the next time the class is loaded, browser and server cache will
         * be bypassed by adding a timestamp to the url.
         */
        unloadTemplate : function (classpath, timestampNextTime) {
            var classMgr = aria.core.ClassMgr;
            var scriptClasspath = classpath + "Script";
            // do some cleaning in cache
            if (Aria.nspace(scriptClasspath, false) || aria.core.Cache.getItem("classes", scriptClasspath)) {
                classMgr.unloadClass(scriptClasspath, timestampNextTime);
            }
            var itm = Aria.$classDefinitions[classpath];
            if (itm) {
                if (!Aria.nspace(classpath, false) && itm.$css) {
                    // when there is an error in the script, the class reference for the template is not created, so the
                    // css would not be unregistered in the unloadClass method
                    aria.templates.CSSMgr.unregisterDependencies(classpath, itm.$css, true, timestampNextTime);
                }
                if (itm.$resources != null) {
                    var resources = itm.$resources;
                    for (var res in resources)
                        if (resources.hasOwnProperty(res)) {
                            classMgr.unloadClass(resources[res], timestampNextTime);
                        }
                }
            }
            classMgr.unloadClass(classpath, timestampNextTime);
            // every thing is done : CSS are unhandled at classMgr level directly
            this.$raiseEvent("unloadTemplate");
        }
    }
});<|endoftext|>


<commit_before>const array = require("../lib/array");
const assert = require("assert");
const t = require("../lib/transducers");
const s = require("../lib/seq");
const n = require("../lib/type");

function assertEq(a,b){
	assert.equal(JSON.stringify(a),JSON.stringify(b));
}

var x = array.default("a","b","c");

assertEq(array.get(x,1),"a");
assertEq(array.append(x,"d").toJS(),["a","b","c","d"]);
assertEq(array.insertBefore(x,2,"d").toJS(),["a","d","b","c"]);
assertEq(array.remove(x,2).toJS(),["a","c"]);
assertEq(array.size(x),3);
assertEq(array.tail(x).toJS(),["b","c"]);
assertEq(array.head(x),"a");
assertEq(array.subarray(x,2).toJS(),["b","c"]);
assertEq(array.subarray(x,2,array.size(x) + 2 - 1).toJS(),["b","c"]);
assertEq(array.subarray(x,2,1).toJS(),["b"]);

console.log("all tests passed");

console.log(t.foldLeft(x,"",(a,b) => a + b));
console.log(t.transform(x,t.compose(t.filter(_ => _ != "a"),t.forEach(_ => _ + ".ok"))));

//console.log(array.default(n.string("a"),s.seq()));
<commit_msg>update test<commit_after>const array = require("../lib/array");
const n = require("../lib/index");
const shared = require("./shared");

const assertEq = shared.assertEq;
const assertThrows = shared.assertThrows;

var x = array.default(["a","b","c"]);
assertEq("array.get",array.get(x,1),"a");
assertEq("array.flatten",array.flatten(x,1),n.seq("a","b","c"));
assertEq("array.append",array.append(x,"d").concatAll(),n.seq("a","b","c","d"));
assertEq("array.insertBefore",array.insertBefore(x,2,"d").concatAll(),["a","d","b","c"]);
assertEq("array.remove",array.remove(x,2).concatAll(),n.seq("a","c"));
assertEq("array.size",array.size(x),3);
assertEq("array.tail",array.tail(x).concatAll(),n.seq("b","c"));
assertEq("array.head",array.head(x),"a");
assertEq("array.subarray 1",array.subarray(x,2).concatAll(),n.seq("b","c"));
assertEq("array.subarray 2",array.subarray(x,1,2).concatAll(),n.seq("a","b"));
assertEq("array.subarray 3", array.subarray(x,2,1).concatAll(),"b");
assertEq("transform", n.transform(x,
	n.compose(n.filter(_ => _ != "a"),n.forEach(_ => n.concat(_,".ok")))).concatAll(),n.seq("b.ok","c.ok"));
assertEq("array.reverse",array.reverse(x).concatAll(),n.seq("c","b","a"));
assertEq("array.foldLeft",array.foldLeft(x,"x",n.concat),"xabc");
assertEq("array.join",array.join(n.seq(x,x)).concatAll(),n.seq("a","b","c","a","b","c"));
assertThrows("not-list",() => array.head("a"));
console.log("all tests passed");
<|endoftext|>


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

function findArgValue(args, names) {
  let found = null;
  args.forEach((arg, index) => {
    if (names.indexOf(arg) > -1) {
      found = args[index + 1];
    }
  });
  return found;
}

function hasArg(args, names) {
  return !!args.find(arg => (names.indexOf(arg) > -1));
}

const args = process.argv.slice(2);
const country = findArgValue(args, ['-c', '--country']);
const queryCountry = hasArg(args, ['-q', '--query']);
const help = hasArg(args, ['-h', '--help']);

require('../index.js')(country, queryCountry);
<commit_msg>removed unused var<commit_after>#!/usr/bin/env node

function findArgValue(args, names) {
  let found = null;
  args.forEach((arg, index) => {
    if (names.indexOf(arg) > -1) {
      found = args[index + 1];
    }
  });
  return found;
}

function hasArg(args, names) {
  return !!args.find(arg => (names.indexOf(arg) > -1));
}

const args = process.argv.slice(2);
const country = findArgValue(args, ['-c', '--country']);
const queryCountry = hasArg(args, ['-q', '--query']);

require('../index.js')(country, queryCountry);
<|endoftext|>