<commit_before>/**
 * @name App
 * @memberOf {Enpowi}
 * @constructor
 */
Namespace('Enpowi').
    Class('App', {
		Static: {
			m: null,
			c: null,
			subs: {},
			one: function(eventName, callback) {
				var parentCallback = function() {
					callback.apply(this, arguments);

					var array = this.subs[eventName];

					array.splice(array.indexOf(parentCallback), 1);
				};

				return this.sub(eventName, parentCallback);
			},
			sub: function(eventName, callback) {
				var subs;
				if ((subs = this.subs[eventName]) === undefined) subs = this.subs[eventName] = [];
				subs.push(callback);

				return this;
			},
			pub: function(eventName, data) {
				var subs,
					max,
					i;

				if ((subs = this.subs[eventName]) === undefined) return this;

				i = 0;
				max = subs.length;

				for (;i <max;i++) {
					subs[i].apply(this, data);
				}

				return this;
			},

			oneTo: function() {
				var caller = {},
					me = this,
					n;

				for (n in this.event) if (this.event.hasOwnProperty(n)) {
					caller[n] = (function(eventName) {
						return function(callback) {
							me.one(eventName, callback);
							return caller;
						};
					})(n);
				}

				return caller;
			},

			subTo: function() {
				var caller = {},
					me = this,
					n;

				for (n in this.event) if (this.event.hasOwnProperty(n)) {
					caller[n] = (function (eventName) {
						return function (callback) {
							me.sub(eventName, callback);
							return caller;
						};
					})(n);
				}

				return caller;
			},

			pubTo: function() {
				var caller = {},
					me = this,
					n;

				for (n in this.event) if (this.event.hasOwnProperty(n)) {
					caller[n] = (function (eventName) {
						return function (args) {
							me.pub(eventName, args);
							return caller;
						};
					})(n);
				}

				return caller;
			},

			event: {
				_continue: 'continue',
				delay: 'delay',
				deny: 'deny',
				go: 'go',
				land: 'land',
				listened: 'listened',
				listen: 'listen',
				paramResponse: 'paramResponse',
				process: 'process',
				processed: 'processed',
				sessionChange: 'sessionChange',
				successResponse: 'successResponse'
			},

			nonPersistentEvents: {
				paramResponse: 'paramResponse',
				successResponse: 'successResponse'
			},

			garbageEvents: function() {
				var nPE = this.nonPersistentEvents,
					i;

				for (i in nPE) if (nPE.hasOwnProperty(i)) {
					this.subs[i] = [];
				}

				return this;
			}
		},
        construct: function(callback) {
            Enpowi.app = this;

	        this.titleElement = document.querySelector('title');
            this.router = crossroads;
            this.routes = [];
            this.hasher = hasher;
            this.loadingElement = null;
            this.routeCallback = callback;

            Enpowi.directives.setup();
            Enpowi.translation.setup();

            this.setupRoutes();
        },

		changeTitle: function(title) {
			this.titleElement.textContent = title;

			return this;
		},

        setupRoutes: function() {
            //setup router
            var router = this.router,
                app = this,
                landRoute = function(url, route, m, c) {
	                app.garbageEvents();

	                var init = false,
		                completed = false,
		                timer = setInterval(function() {
			                if (!init) {
				                init = true;
				                app.setLoading(true);
			                }

			                if (completed) {
				                clearInterval(timer);
				                app.setLoading(false);
			                }
		                }, 500);

                    app.load(url, function(data) {
	                    var pubTo = app.pubTo();
	                    if (data == -1) {
		                    var result = pubTo.deny([url]);
		                    if (result === false) {
			                    return;
		                    }
	                    }
                        app.loadScript('modules/?module=app&component=session.js', function() {
	                        completed = true;
	                        Enpowi.App.m = m;
	                        Enpowi.App.c = c;
                            var result = app.process(data, m, c),
	                            title = result.querySelector('title');

	                        if (title) {
		                        app.changeTitle(title.textContent);
		                        result.removeChild(title);
	                        } else {
		                        app.changeTitle(Enpowi.session.siteName);
	                        }

                            app.routeCallback(result);
                            pubTo.land([route]);
                        });
                    });
                };

            this.hasher = hasher;

            this.bindRouteUrls(router, landRoute);

            //setup hasher
            function parseHash(newHash, oldHash){
                router.parse(newHash);
            }

            hasher.initialized.add(parseHash); //parse initial hash
            hasher.changed.add(parseHash); //parse hash changes
            hasher.init(); //start listening for history change

        },

        bindRouteUrls: function(router, callback) {
	        var pubTo = this.pubTo();
            //none
            //moduleName
            //moduleName/component
            //moduleName/component/id
            //moduleName/component?querystring
            router.normalizeFn = crossroads.NORM_AS_OBJECT;

            router.addRoute('/', function() {
                callback('modules/?module=' + Enpowi.session.theme + '&component=index', '', '', '');
            });
            router.addRoute('/{m}', function(path) {
                callback('modules/?module=' + path.m, path.request_, path.m, '');
            });
            router.addRoute('/{m}{?query}', function(path) {
                callback('modules/?module=' + path.m + '&'  + path['?query_'], path.request_, path.m, '');
            });
            router.addRoute('/{m}/{c}', function(path) {
                callback('modules/?module=' + path.m + '&component=' + path.c, path.request_, path.m, path.c);
            });
            router.addRoute('/{m}/{c}/{id}', function(path) {
                callback('modules/?module=' + path.m + '&component=' + path.c + '&id' + path.id, path.request_, path.m, path.c);
            });
            router.addRoute('/{m}/{c}{?query}', function(path) {
                callback('modules/?module=' + path.m + '&component=' + path.c + '&'  + path['?query_'], path.request_, path.m, path.c);
            });

	        router.routed.add(function(route) {
		        pubTo.go([route]);
	        });
        },

        logRoutes: function() {
            this.router.routed.add(console.log, console); //log all routes

            return this;
        },

        loadScripts: function(urls, callback) {
            this.loadAll(urls, function(results) {
                var i = 0,
                    max = results.length;

                for(;i < max; i++) {
                    (new Function(results[i]))();
                }

                if (callback) callback();
            });
        },
        loadStyles: function(urls) {
            var i = 0,
                max = urls.length,
                style,
                styles = document.createDocumentFragment();

            for(;i<max;i++) {
                style = document.createElement('link');
                style.setAttribute('href', urls[i]);
                style.setAttribute('rel', 'stylesheet');
                styles.appendChild(style);
            }

            return styles;
        },
		/**
		 * @type {DocumentFragment}
		 */
		processContainer: null,
        process: function(html, m, c) {
            var el = document.createElement('div'),
                frag = this.processContainer = document.createDocumentFragment(),
                child,
	            scripts,
	            script,
	            i = 0,
	            max,
	            scriptXSS = [],
	            scriptsRemote = [],
	            scriptsLocal = [],
	            vues = [],
                datas = [],
                elements = [],
                runJS = function() {
                    if (scriptsLocal.length > 0) {
                        for(var i = 0; i < scriptsLocal.length; i++) {
                            try {
                                (new Function('datas', 'vues', 'elements', scriptsLocal[i]))
                                (datas, vues, elements);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    }
                };

            el.innerHTML = html;

	        this.pubTo().process([el]);

	        //obtain scripts
	        scripts = el.querySelectorAll('script');

	        max = scripts.length;

	        for(;i<max;i++) {
		        script = scripts[i];
		        if (script.hasAttribute('src')) {
			        if (script.hasAttribute('xss')) {
				        scriptXSS.push(script);
			        } else {
				        scriptsRemote.push(script.getAttribute('src'));
			        }
		        } else {
			        scriptsLocal.push(script.innerHTML);
		        }
	        }

	        //process html
            while (el.children.length > 0) {
                child = el.firstChild;
                el.removeChild(child);
                elements.push(child);
                frag.appendChild(child);

                if (child.nodeType === 1) {
                    vues.push(new Vue({
                        el: child,
                        data: (function () {
                            var data = {
                                    'session': Enpowi.session,
		                            'module': m,
		                            'component': c,
		                            'appModule': Enpowi.App.m,
		                            'appComponent': Enpowi.App.c
                                },
                                jsonEncoded = child.getAttribute('data'),
                                jsonDecoded,
                                moduleData,
                                i;

                            if (jsonEncoded) {
                                child.removeAttribute('data');

                                jsonDecoded = decodeURIComponent(jsonEncoded);
                                moduleData = JSON.parse(jsonDecoded);

                                for (i in moduleData) if (i && moduleData.hasOwnProperty(i)) {
                                    data[i] = moduleData[i];
                                }
	                            datas.push(data);
                            }

                            return data;
                        })(),
                        methods: {
                            go: function (sig) {
                                app.go(sig);
                            },
                            stringify: function (json) {
                                return JSON.stringify(json);
                            },
                            arrayLookup: function(array, key, value) {
                                var i = 0,
                                    max = array.length;

                                for(;i < max; i++) {
                                    if (array[i][key] === value) return array[i];
                                }

                                return null;
                            },
                            hasPerm: function (m, c) {
                                var hasPerm = false;
                                $.each(Enpowi.session.user.groups, function () {
                                    $.each(this.perms, function () {
                                        if (this['module'] === m || this['module'] === '*') {
                                            if (this['component'] === c || this['component'] === '*') {
                                                hasPerm = true;
                                            }
                                        }
                                    });
                                });

                                return hasPerm;
                            },
                            hasKey: function (key, array) {
                                return array[key] !== undefined;
                            },
	                        indexOf: function (array, value) {
		                        return array.indexOf(value);
	                        },
	                        inArray: function (array, value) {
		                        return array.indexOf(value) > -1;
	                        }
                        }
                    }));
                }
            }

	        //process scripts
	        if (scriptsRemote.length > 0) {
		        this.loadScripts(scriptsRemote, function() {
                    runJS();
		        });
	        } else {
                runJS();
	        }

	        if (scriptXSS.length > 0) {
		        $('body').append(scriptXSS);
	        }

	        this.pubTo().processed([vues]);

            return frag;
        },

        go: function(route) {
	        var existingHash = window.location.hash.toString(),
		        hasSlashes = existingHash.match(/\/$/);

            if ('#/' + route === existingHash) {
	            if (hasSlashes) {
		            this.hasher.setHash(route.substring(0, route.length - 1));
	            } else {
		            this.hasher.setHash(route + '/');
	            }
            } else {
                this.hasher.setHash(route);
            }

            return this;
        },

        loadScript: function(url, callback) {
            this.load(url, function(scriptHTML) {
                (new Function(scriptHTML))();
                if (callback !== undefined) callback();
            });
        },

        loadAll: function(urls, callback) {
            var app = this,
                i = 0,
                progress = 0,
                max = urls.length,
                results = [];

            for (;i < max; i++) {
                (function(i) {
                    app.load(urls[i], function(result) {
                        results[i] = result;
                        progress++;
                        if (progress === max) {
                            callback(results);
                        }
                    });
                })(i);
            }

            return this;
        },
        load: function(url, callback, usePost) {
            var request = new XMLHttpRequest();

            request.open((usePost ? 'POST' : 'GET'), url, true);

            request.onload = function() {
                if (request.status >= 200 && request.status < 400) {
                    // Success!
                    callback(request.responseText);
                } else {
                    // Error
                    callback(null, request.responseText);

                }
            };

            request.onerror = function() {};

            request.send();

            return this;
        },
		getElementById: function(id) {
			var el = document.getElementById(id);

			if (el !== null) return el;

			if (this.processContainer !== null) {
				return this.processContainer.querySelector('#' + id);
			}
		},
        loadModule: function(urlRaw, callback) {
            var app = this,
	            url;

            this.load(url = Enpowi.utilities.url(urlRaw), function(moduleHtml) {
                callback(app.process(moduleHtml, url.m, url.c));
            });

            return this;
        },
        isLoading: false,
        /**
         *
         * @param {Boolean} isLoading
         * @returns {Enpowi.App}
         */
        setLoading: function(isLoading) {
            if (this.loadingElement === null) return this;

            if (this.isLoading === false && isLoading) {
                this.isLoading = isLoading;
	            this.pubTo().delay();
            }

            else if (this.isLoading && isLoading === false) {
                this.isLoading = isLoading;
	            this.pubTo()._continue();
            }

            return this;
        }
    });<commit_msg>moved hasPerm to app for global reuse<commit_after>/**
 * @name App
 * @memberOf {Enpowi}
 * @constructor
 */
Namespace('Enpowi').
    Class('App', {
		Static: {
			m: null,
			c: null,
			subs: {},
			one: function(eventName, callback) {
				var parentCallback = function() {
					callback.apply(this, arguments);

					var array = this.subs[eventName];

					array.splice(array.indexOf(parentCallback), 1);
				};

				return this.sub(eventName, parentCallback);
			},
			sub: function(eventName, callback) {
				var subs;
				if ((subs = this.subs[eventName]) === undefined) subs = this.subs[eventName] = [];
				subs.push(callback);

				return this;
			},
			pub: function(eventName, data) {
				var subs,
					max,
					i;

				if ((subs = this.subs[eventName]) === undefined) return this;

				i = 0;
				max = subs.length;

				for (;i <max;i++) {
					subs[i].apply(this, data);
				}

				return this;
			},

			oneTo: function() {
				var caller = {},
					me = this,
					n;

				for (n in this.event) if (this.event.hasOwnProperty(n)) {
					caller[n] = (function(eventName) {
						return function(callback) {
							me.one(eventName, callback);
							return caller;
						};
					})(n);
				}

				return caller;
			},

			subTo: function() {
				var caller = {},
					me = this,
					n;

				for (n in this.event) if (this.event.hasOwnProperty(n)) {
					caller[n] = (function (eventName) {
						return function (callback) {
							me.sub(eventName, callback);
							return caller;
						};
					})(n);
				}

				return caller;
			},

			pubTo: function() {
				var caller = {},
					me = this,
					n;

				for (n in this.event) if (this.event.hasOwnProperty(n)) {
					caller[n] = (function (eventName) {
						return function (args) {
							me.pub(eventName, args);
							return caller;
						};
					})(n);
				}

				return caller;
			},

			event: {
				_continue: 'continue',
				delay: 'delay',
				deny: 'deny',
				go: 'go',
				land: 'land',
				listened: 'listened',
				listen: 'listen',
				paramResponse: 'paramResponse',
				process: 'process',
				processed: 'processed',
				sessionChange: 'sessionChange',
				successResponse: 'successResponse'
			},

			nonPersistentEvents: {
				paramResponse: 'paramResponse',
				successResponse: 'successResponse'
			},

			garbageEvents: function() {
				var nPE = this.nonPersistentEvents,
					i;

				for (i in nPE) if (nPE.hasOwnProperty(i)) {
					this.subs[i] = [];
				}

				return this;
			}
		},
        construct: function(callback) {
            Enpowi.app = this;

	        this.titleElement = document.querySelector('title');
            this.router = crossroads;
            this.routes = [];
            this.hasher = hasher;
            this.loadingElement = null;
            this.routeCallback = callback;

            Enpowi.directives.setup();
            Enpowi.translation.setup();

            this.setupRoutes();
        },

		changeTitle: function(title) {
			this.titleElement.textContent = title;

			return this;
		},

        setupRoutes: function() {
            //setup router
            var router = this.router,
                app = this,
                landRoute = function(url, route, m, c) {
	                app.garbageEvents();

	                var init = false,
		                completed = false,
		                timer = setInterval(function() {
			                if (!init) {
				                init = true;
				                app.setLoading(true);
			                }

			                if (completed) {
				                clearInterval(timer);
				                app.setLoading(false);
			                }
		                }, 500);

                    app.load(url, function(data) {
	                    var pubTo = app.pubTo();
	                    if (data == -1) {
		                    var result = pubTo.deny([url]);
		                    if (result === false) {
			                    return;
		                    }
	                    }
                        app.loadScript('modules/?module=app&component=session.js', function() {
	                        completed = true;
	                        Enpowi.App.m = m;
	                        Enpowi.App.c = c;
                            var result = app.process(data, m, c),
	                            title = result.querySelector('title');

	                        if (title) {
		                        app.changeTitle(title.textContent);
		                        result.removeChild(title);
	                        } else {
		                        app.changeTitle(Enpowi.session.siteName);
	                        }

                            app.routeCallback(result);
                            pubTo.land([route]);
                        });
                    });
                };

            this.hasher = hasher;

            this.bindRouteUrls(router, landRoute);

            //setup hasher
            function parseHash(newHash, oldHash){
                router.parse(newHash);
            }

            hasher.initialized.add(parseHash); //parse initial hash
            hasher.changed.add(parseHash); //parse hash changes
            hasher.init(); //start listening for history change

        },

        bindRouteUrls: function(router, callback) {
	        var pubTo = this.pubTo();
            //none
            //moduleName
            //moduleName/component
            //moduleName/component/id
            //moduleName/component?querystring
            router.normalizeFn = crossroads.NORM_AS_OBJECT;

            router.addRoute('/', function() {
                callback('modules/?module=' + Enpowi.session.theme + '&component=index', '', '', '');
            });
            router.addRoute('/{m}', function(path) {
                callback('modules/?module=' + path.m, path.request_, path.m, '');
            });
            router.addRoute('/{m}{?query}', function(path) {
                callback('modules/?module=' + path.m + '&'  + path['?query_'], path.request_, path.m, '');
            });
            router.addRoute('/{m}/{c}', function(path) {
                callback('modules/?module=' + path.m + '&component=' + path.c, path.request_, path.m, path.c);
            });
            router.addRoute('/{m}/{c}/{id}', function(path) {
                callback('modules/?module=' + path.m + '&component=' + path.c + '&id' + path.id, path.request_, path.m, path.c);
            });
            router.addRoute('/{m}/{c}{?query}', function(path) {
                callback('modules/?module=' + path.m + '&component=' + path.c + '&'  + path['?query_'], path.request_, path.m, path.c);
            });

	        router.routed.add(function(route) {
		        pubTo.go([route]);
	        });
        },

        logRoutes: function() {
            this.router.routed.add(console.log, console); //log all routes

            return this;
        },

        loadScripts: function(urls, callback) {
            this.loadAll(urls, function(results) {
                var i = 0,
                    max = results.length;

                for(;i < max; i++) {
                    (new Function(results[i]))();
                }

                if (callback) callback();
            });
        },
        loadStyles: function(urls) {
            var i = 0,
                max = urls.length,
                style,
                styles = document.createDocumentFragment();

            for(;i<max;i++) {
                style = document.createElement('link');
                style.setAttribute('href', urls[i]);
                style.setAttribute('rel', 'stylesheet');
                styles.appendChild(style);
            }

            return styles;
        },
		/**
		 * @type {DocumentFragment}
		 */
		processContainer: null,
        process: function(html, m, c) {
            var el = document.createElement('div'),
                frag = this.processContainer = document.createDocumentFragment(),
                child,
	            scripts,
	            script,
	            i = 0,
	            max,
	            scriptXSS = [],
	            scriptsRemote = [],
	            scriptsLocal = [],
	            vues = [],
                datas = [],
                elements = [],
                runJS = function() {
                    if (scriptsLocal.length > 0) {
                        for(var i = 0; i < scriptsLocal.length; i++) {
                            try {
                                (new Function('datas', 'vues', 'elements', scriptsLocal[i]))
                                (datas, vues, elements);
                            } catch (e) {
                                console.log(e);
                            }
                        }
                    }
                };

            el.innerHTML = html;

	        this.pubTo().process([el]);

	        //obtain scripts
	        scripts = el.querySelectorAll('script');

	        max = scripts.length;

	        for(;i<max;i++) {
		        script = scripts[i];
		        if (script.hasAttribute('src')) {
			        if (script.hasAttribute('xss')) {
				        scriptXSS.push(script);
			        } else {
				        scriptsRemote.push(script.getAttribute('src'));
			        }
		        } else {
			        scriptsLocal.push(script.innerHTML);
		        }
	        }

	        //process html
            while (el.children.length > 0) {
                child = el.firstChild;
                el.removeChild(child);
                elements.push(child);
                frag.appendChild(child);

                if (child.nodeType === 1) {
                    vues.push(new Vue({
                        el: child,
                        data: (function () {
                            var data = {
                                    'session': Enpowi.session,
		                            'module': m,
		                            'component': c,
		                            'appModule': Enpowi.App.m,
		                            'appComponent': Enpowi.App.c
                                },
                                jsonEncoded = child.getAttribute('data'),
                                jsonDecoded,
                                moduleData,
                                i;

                            if (jsonEncoded) {
                                child.removeAttribute('data');

                                jsonDecoded = decodeURIComponent(jsonEncoded);
                                moduleData = JSON.parse(jsonDecoded);

                                for (i in moduleData) if (i && moduleData.hasOwnProperty(i)) {
                                    data[i] = moduleData[i];
                                }
	                            datas.push(data);
                            }

                            return data;
                        })(),
                        methods: {
                            go: function (sig) {
                                app.go(sig);
                            },
                            stringify: function (json) {
                                return JSON.stringify(json);
                            },
                            arrayLookup: function(array, key, value) {
                                var i = 0,
                                    max = array.length;

                                for(;i < max; i++) {
                                    if (array[i][key] === value) return array[i];
                                }

                                return null;
                            },
                            hasPerm: function (m, c) {
                                return app.hasPerm(m, c);
                            },
                            hasKey: function (key, array) {
                                return array[key] !== undefined;
                            },
	                        indexOf: function (array, value) {
		                        return array.indexOf(value);
	                        },
	                        inArray: function (array, value) {
		                        return array.indexOf(value) > -1;
	                        }
                        }
                    }));
                }
            }

	        //process scripts
	        if (scriptsRemote.length > 0) {
		        this.loadScripts(scriptsRemote, function() {
                    runJS();
		        });
	        } else {
                runJS();
	        }

	        if (scriptXSS.length > 0) {
		        $('body').append(scriptXSS);
	        }

	        this.pubTo().processed([vues]);

            return frag;
        },

        go: function(route) {
	        var existingHash = window.location.hash.toString(),
		        hasSlashes = existingHash.match(/\/$/);

            if ('#/' + route === existingHash) {
	            if (hasSlashes) {
		            this.hasher.setHash(route.substring(0, route.length - 1));
	            } else {
		            this.hasher.setHash(route + '/');
	            }
            } else {
                this.hasher.setHash(route);
            }

            return this;
        },

        loadScript: function(url, callback) {
            this.load(url, function(scriptHTML) {
                (new Function(scriptHTML))();
                if (callback !== undefined) callback();
            });
        },

        loadAll: function(urls, callback) {
            var app = this,
                i = 0,
                progress = 0,
                max = urls.length,
                results = [];

            for (;i < max; i++) {
                (function(i) {
                    app.load(urls[i], function(result) {
                        results[i] = result;
                        progress++;
                        if (progress === max) {
                            callback(results);
                        }
                    });
                })(i);
            }

            return this;
        },
        load: function(url, callback, usePost) {
            var request = new XMLHttpRequest();

            request.open((usePost ? 'POST' : 'GET'), url, true);

            request.onload = function() {
                if (request.status >= 200 && request.status < 400) {
                    // Success!
                    callback(request.responseText);
                } else {
                    // Error
                    callback(null, request.responseText);

                }
            };

            request.onerror = function() {};

            request.send();

            return this;
        },
		getElementById: function(id) {
			var el = document.getElementById(id);

			if (el !== null) return el;

			if (this.processContainer !== null) {
				return this.processContainer.querySelector('#' + id);
			}
		},
        loadModule: function(urlRaw, callback) {
            var app = this,
	            url;

            this.load(url = Enpowi.utilities.url(urlRaw), function(moduleHtml) {
                callback(app.process(moduleHtml, url.m, url.c));
            });

            return this;
        },
        isLoading: false,
        /**
         *
         * @param {Boolean} isLoading
         * @returns {Enpowi.App}
         */
        setLoading: function(isLoading) {
            if (this.loadingElement === null) return this;

            if (this.isLoading === false && isLoading) {
                this.isLoading = isLoading;
	            this.pubTo().delay();
            }

            else if (this.isLoading && isLoading === false) {
                this.isLoading = isLoading;
	            this.pubTo()._continue();
            }

            return this;
        },
        hasPerm: function (m, c) {
            var hasPerm = false;
            $.each(Enpowi.session.user.groups, function () {
                $.each(this.perms, function () {
                    if (this['module'] === m || this['module'] === '*') {
                        if (this['component'] === c || this['component'] === '*') {
                            hasPerm = true;
                        }
                    }
                });
            });

            return hasPerm;
        }
    });<|endoftext|>


<commit_before>'use strict';

// Notices controller
angular.module('notices').controller('NoticesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Notices',
	function($scope, $stateParams, $location, Authentication, Notices, Templates) {
		$scope.authentication = Authentication;

		// Create new Notice
		$scope.create = function() {
			// Create new Notice object
			var notice = new Notices ({
				notice_type: this.type,
				title: this.noticeForm.title,
				status: 'active',
				auto_update: this.update_time,
				ticket_number: this.ticket,
				priority: this.priority,
				services_affected: this.noticeForm.services,
				biz_impact: this.noticeForm.biz_impact,
				outage_start_time: this.data.date,
				regions_affected: this.noticeForm.regions,
				workaround: this.noticeForm.workaround

			});

			// Redirect after save
			notice.$save(function(response) {
				// $location.path('notices/' + response._id);
				//redirect to dashboard
				$location.path('/');

				// Clear form fields
				$scope.type = '';
				$scope.noticeForm.title = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Notice
		$scope.remove = function(notice) {
			if ( notice ) {
				notice.$remove();

				for (var i in $scope.notices) {
					if ($scope.notices [i] === notice) {
						$scope.notices.splice(i, 1);
					}
				}
			} else {
				$scope.notice.$remove(function() {
					$location.path('notices');
				});
			}
		};

		// Update existing Notice
		$scope.update = function() {
			var notice = $scope.notice;

			notice.$update(function() {
				$location.path('notices/' + notice._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Notices
		$scope.find = function() {
			$scope.notices = Notices.query();
		};

		// Find existing Notice
		$scope.findOne = function() {
			$scope.notice = Notices.get({
				noticeId: $stateParams.noticeId
			});
		};

		// find latest notice based on state (active | closed)
		$scope.findOneActive = function() {
			$scope.notice = Notices.active();
		};

		// get template info
		$scope.templates = Notices.getTemplates();

	}

]);<commit_msg>fix create notice params<commit_after>'use strict';

// Notices controller
angular.module('notices').controller('NoticesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Notices',
	function($scope, $stateParams, $location, Authentication, Notices, Templates) {
		$scope.authentication = Authentication;

		// Create new Notice
		$scope.create = function() {
			// Create new Notice object
			var notice = new Notices ({
				notice_type: this.type,
				title: this.noticeForm.title,
				status: 'active',
				auto_update: this.update_time,
				ticket_number: this.ticket,
				priority: this.priority,
				services_affected: this.noticeForm.services_affected,
				biz_impact: this.noticeForm.biz_impact,
				outage_start_time: this.data.date,
				regions_affected: this.noticeForm.regions_affected,
				workaround: this.noticeForm.workaround

			});

			// Redirect after save
			notice.$save(function(response) {
				// $location.path('notices/' + response._id);
				//redirect to dashboard
				$location.path('/');

				// Clear form fields
				$scope.type = '';
				$scope.noticeForm.title = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Notice
		$scope.remove = function(notice) {
			if ( notice ) {
				notice.$remove();

				for (var i in $scope.notices) {
					if ($scope.notices [i] === notice) {
						$scope.notices.splice(i, 1);
					}
				}
			} else {
				$scope.notice.$remove(function() {
					$location.path('notices');
				});
			}
		};

		// Update existing Notice
		$scope.update = function() {
			var notice = $scope.notice;

			notice.$update(function() {
				$location.path('notices/' + notice._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Notices
		$scope.find = function() {
			$scope.notices = Notices.query();
		};

		// Find existing Notice
		$scope.findOne = function() {
			$scope.notice = Notices.get({
				noticeId: $stateParams.noticeId
			});
		};

		// find latest notice based on state (active | closed)
		$scope.findOneActive = function() {
			$scope.notice = Notices.active();
		};

		// get template info
		$scope.templates = Notices.getTemplates();

	}

]);<|endoftext|>


<commit_before>import Dexie from "src/external/dexie3.js"

export default class Literature {

  static async ensureCache() {
    if (!this.cachedPapers || !this.cachedPapersById) {

      var start = Date.now()
      this.cachedPapers = await this.db.papers.toArray()
      console.log("[literature] ensureCache indexdb " + (Date.now() - start))

      this.cachedPapersById = new Map()
      for(var ea of this.cachedPapers) {
        this.cachedPapersById.set(ea.microsoftid, ea)
      }
      console.log("[literature] ensureCache total " + (Date.now() - start))
    }
  }

  static async papers() {
    await this.ensureCache()
    return this.cachedPapers
  }

  static async papersById() {
    await this.ensureCache()
    return this.cachedPapersById
  }

  static invalidateCache() {
    this.cachedPapers = null
  }

  static async ensurePaperEntry(paper) {
    var raw = await this.db.papers.get(paper.microsoftid)
    if (!raw) {
      raw = this.addPaper(paper)
    }
    return  raw
  }

  static async deleteEmptyAuthorPapers() {
    var entries = await this.papers()
    this.invalidateCache()
    return entries
      .filter(ea => !ea.authors)
      .forEach(ea => Literature.db.papers.delete(ea.microsoftid))

  }

  static async addPaper(paper) {
    var raw = {
        microsoftid: paper.microsoftid,
        authors: paper.authorNames,
        year: paper.year,
        title: paper.title,
        key: paper.key,
        keywords: paper.keywords,
        booktitle: paper.booktitle,
        value: paper.value,
        abstract: paper.abstract
    }
    await this.db.papers.put(raw)
    this.invalidateCache()
    return raw
  }

  static async patchPaper(id, obj) {
    var raw = await this.ensurePaperEntry({microsoftid: id})
    raw = Object.assign(raw, obj)
    this.invalidateCache()
    return this.db.papers.put(raw)
  }

  static async getPaperEntry(id) {
    var map = await this.papersById()
    var entry = map.get(id)
    if (entry) return entry
    // maybe something ch
    // return this.db.papers.get({microsoftid: id})
  }

  static async getPaperEntries(references) {
    var all = await this.papers()
    return all.filter(ea => references.includes(ea.microsoftid))

    // (reasonably fast)
    // return this.db.papers.bulkGet(references)

    // (SLOW)
    // return (await this.db.papers.toArray())
    //     .filter(ea => references.includes(ea.microsoftid))
  }

  static get db() {
    var db = new Dexie("literature");

    db.version(1).stores({
        papers: 'microsoftid,authors,year,title,key,keywords,booktitle',
    }).upgrade(function () {
    })

    return db
  }
}

// import Tracing from "src/client/tracing.js"
// Tracing.traceObject(Literature)
<commit_msg>[academic] guard caching with promise<commit_after>import Dexie from "src/external/dexie3.js"

export default class Literature {

  static async ensureCache() {
    if (this.isLoadingCache) {
      await this.isLoadingCache
    }

    if (!this.cachedPapers || !this.cachedPapersById) {
      this.isLoadingCache = new Promise(async resolve => {
        try {
          var start = Date.now()
          this.cachedPapers = await this.db.papers.toArray()
          console.log("[literature] ensureCache indexdb " + (Date.now() - start))

          this.cachedPapersById = new Map()
          for(var ea of this.cachedPapers) {
            this.cachedPapersById.set(ea.microsoftid, ea)
          }
          console.log("[literature] ensureCache total " + (Date.now() - start))
        } finally {
          resolve()
        }
      })
      await this.isLoadingCache
      this.isLoadingCache = false
    }
  }

  static async papers() {
    await this.ensureCache()
    return this.cachedPapers
  }

  static async papersById() {
    await this.ensureCache()
    return this.cachedPapersById
  }

  static invalidateCache() {
    this.cachedPapers = null
    this.cachedPapersById  = null
    this.isLoadingCache = false
  }

  static async ensurePaperEntry(paper) {
    var raw = await this.db.papers.get(paper.microsoftid)
    if (!raw) {
      raw = this.addPaper(paper)
    }
    return  raw
  }

  static async deleteEmptyAuthorPapers() {
    var entries = await this.papers()
    this.invalidateCache()
    return entries
      .filter(ea => !ea.authors)
      .forEach(ea => Literature.db.papers.delete(ea.microsoftid))

  }

  static async addPaper(paper) {
    var raw = {
        microsoftid: paper.microsoftid,
        authors: paper.authorNames,
        year: paper.year,
        title: paper.title,
        key: paper.key,
        keywords: paper.keywords,
        booktitle: paper.booktitle,
        value: paper.value,
        abstract: paper.abstract
    }
    await this.db.papers.put(raw)
    this.invalidateCache()
    return raw
  }

  static async patchPaper(id, obj) {
    var raw = await this.ensurePaperEntry({microsoftid: id})
    raw = Object.assign(raw, obj)
    this.invalidateCache()
    return this.db.papers.put(raw)
  }

  static async getPaperEntry(id) {
    var map = await this.papersById()
    var entry = map.get(id)
    if (entry) return entry
    // maybe something ch
    // return this.db.papers.get({microsoftid: id})
  }

  static async getPaperEntries(references) {
    var all = await this.papers()
    return all.filter(ea => references.includes(ea.microsoftid))

    // (reasonably fast)
    // return this.db.papers.bulkGet(references)

    // (SLOW)
    // return (await this.db.papers.toArray())
    //     .filter(ea => references.includes(ea.microsoftid))
  }

  static get db() {
    var db = new Dexie("literature");

    db.version(1).stores({
        papers: 'microsoftid,authors,year,title,key,keywords,booktitle',
    }).upgrade(function () {
    })

    return db
  }
}

// import Tracing from "src/client/tracing.js"
// Tracing.traceObject(Literature)
<|endoftext|>


<commit_before>var fs = require("fs");
var http = require("http");
var https = require("https");
var path = require("path");

var sessions = {};
var usersInSessionLimit = 2;

var port = process.env.PORT || 8080;
var httpsPort = process.env.HTTPS_PORT || 8443;
var httpsKeyPath = process.env.HTTPS_KEY || '';
var httpsCertPath = process.env.HTTPS_CERT || '';

if (process.argv.length >= 3) {
    port = process.argv[2];
}
if (process.argv.length >= 6) {
    httpsPort = process.argv[3];
    httpsKeyPath = process.argv[4];
    httpsCertPath = process.argv[5];
}

var serverDir = path.dirname(__filename)
var clientDir = path.join(serverDir, "client/");

var contentTypeMap = {
    ".html": "text/html;charset=utf-8",
    ".js": "text/javascript",
    ".css": "text/css"
};

function requestListener(request, response) {
    var headers = {
        "Cache-Control": "no-cache, no-store",
        "Pragma": "no-cache",
        "Expires": "0"
    };

    var parts = request.url.split("/");

    // handle "client to server" and "server to client"
    if (parts[1] == "ctos" || parts[1] == "stoc") {
        var sessionId = parts[2];
        var userId = parts[3];
        if (!sessionId || !userId) {
            response.writeHead(400);
            response.end();
            return;
        }

        if (parts[1] == "stoc") {
            console.log("@" + sessionId + " - " + userId + " joined.");

            headers["Content-Type"] = "text/event-stream";
            response.writeHead(200, headers);
            function keepAlive(resp) {
                resp.write(":\n");
                resp.keepAliveTimer = setTimeout(arguments.callee, 30000, resp);
            }
            keepAlive(response);  // flush headers + keep-alive

            var session = sessions[sessionId];
            if (!session)
                session = sessions[sessionId] = {"users" : {}};

            if (Object.keys(session.users).length > usersInSessionLimit - 1) {
                console.log("user limit for session reached (" + usersInSessionLimit + ")");
                response.write("event:busy\ndata:" + sessionId + "\n\n");
                clearTimeout(response.keepAliveTimer);
                response.end();
                return;
            }

            var user = session.users[userId];
            if (!user) {
                user = session.users[userId] = {};
                for (var pname in session.users) {
                    var esResp = session.users[pname].esResponse;
                    if (esResp) {
                        clearTimeout(esResp.keepAliveTimer);
                        keepAlive(esResp);
                        esResp.write("event:join\ndata:" + userId + "\n\n");
                        response.write("event:join\ndata:" + pname + "\n\n");
                    }
                }
            }
            else if (user.esResponse) {
                user.esResponse.end();
                clearTimeout(user.esResponse.keepAliveTimer);
                user.esResponse = null;
            }
            user.esResponse = response;

            request.on("close", function () {
                for (var pname in session.users) {
                    if (pname == userId)
                        continue;
                    var esResp = session.users[pname].esResponse;
                    esResp.write("event:leave\ndata:" + userId + "\n\n");
                }
                delete session.users[userId];
                clearTimeout(response.keepAliveTimer);
                console.log("@" + sessionId + " - " + userId + " left.");
                console.log("users in session " + sessionId + ": " + Object.keys(session.users).length);
            });

        } else { // parts[1] == "ctos"
            var peerId = parts[4];
            var peer;
            var session = sessions[sessionId];
            if (!session || !(peer = session.users[peerId])) {
                response.writeHead(400, headers);
                response.end();
                return;
            }

            var body = "";
            request.on("data", function (data) { body += data; });
            request.on("end", function () {
                console.log("@" + sessionId + " - " + userId + " => " + peerId + " :");
                // console.log(body);
                var evtdata = "data:" + body.replace(/\n/g, "\ndata:") + "\n";
                peer.esResponse.write("event:user-" + userId + "\n" + evtdata + "\n");
            });

            // to avoid "no element found" warning in Firefox (bug 521301)
            headers["Content-Type"] = "text/plain";
            response.writeHead(204, headers);
            response.end();
        }

        return;
    }

    var url = request.url.split("?", 1)[0];
    var filePath = path.join(clientDir, url);
    if (filePath.indexOf(clientDir) != 0 || filePath == clientDir)
        filePath = path.join(clientDir, "/webrtc_example.html");

    fs.stat(filePath, function (err, stats) {
        if (err || !stats.isFile()) {
            response.writeHead(404);
            response.end("404 Not found");
            return;
        }

        var contentType = contentTypeMap[path.extname(filePath)] || "text/plain";
        response.writeHead(200, { "Content-Type": contentType });

        var readStream = fs.createReadStream(filePath);
        readStream.on("error", function () {
            response.writeHead(500);
            response.end("500 Server error");
        });
        readStream.pipe(response);
    });
};

console.log('The HTTP server is listening on port ' + port);
http.createServer(requestListener).listen(port);

if (httpsKeyPath && httpsCertPath) {
    var options = {
        key: fs.readFileSync(httpsKeyPath),
        cert: fs.readFileSync(httpsCertPath)
    };

    console.log('The HTTPS server is listening on port ' + httpsPort);
    https.createServer(options, requestListener).listen(httpsPort);
}<commit_msg>web: Add support for intermediate CA certs in channel_server.js<commit_after>var fs = require("fs");
var http = require("http");
var https = require("https");
var path = require("path");

var sessions = {};
var usersInSessionLimit = 2;

var port = process.env.PORT || 8080;
var httpsPort = process.env.HTTPS_PORT || 8443;
var httpsKeyPath = process.env.HTTPS_KEY || '';
var httpsCertPath = process.env.HTTPS_CERT || '';
var httpsCACertPath = process.env.HTTPS_CA_CERT || '';

if (process.argv.length >= 3) {
    port = process.argv[2];
}
if (process.argv.length >= 6) {
    httpsPort = process.argv[3];
    httpsKeyPath = process.argv[4];
    httpsCertPath = process.argv[5];
    if (process.argv.length >= 7) {
        httpsCACertPath = process.argv[6];
    }
}

var serverDir = path.dirname(__filename)
var clientDir = path.join(serverDir, "client/");

var contentTypeMap = {
    ".html": "text/html;charset=utf-8",
    ".js": "text/javascript",
    ".css": "text/css"
};

function requestListener(request, response) {
    var headers = {
        "Cache-Control": "no-cache, no-store",
        "Pragma": "no-cache",
        "Expires": "0"
    };

    var parts = request.url.split("/");

    // handle "client to server" and "server to client"
    if (parts[1] == "ctos" || parts[1] == "stoc") {
        var sessionId = parts[2];
        var userId = parts[3];
        if (!sessionId || !userId) {
            response.writeHead(400);
            response.end();
            return;
        }

        if (parts[1] == "stoc") {
            console.log("@" + sessionId + " - " + userId + " joined.");

            headers["Content-Type"] = "text/event-stream";
            response.writeHead(200, headers);
            function keepAlive(resp) {
                resp.write(":\n");
                resp.keepAliveTimer = setTimeout(arguments.callee, 30000, resp);
            }
            keepAlive(response);  // flush headers + keep-alive

            var session = sessions[sessionId];
            if (!session)
                session = sessions[sessionId] = {"users" : {}};

            if (Object.keys(session.users).length > usersInSessionLimit - 1) {
                console.log("user limit for session reached (" + usersInSessionLimit + ")");
                response.write("event:busy\ndata:" + sessionId + "\n\n");
                clearTimeout(response.keepAliveTimer);
                response.end();
                return;
            }

            var user = session.users[userId];
            if (!user) {
                user = session.users[userId] = {};
                for (var pname in session.users) {
                    var esResp = session.users[pname].esResponse;
                    if (esResp) {
                        clearTimeout(esResp.keepAliveTimer);
                        keepAlive(esResp);
                        esResp.write("event:join\ndata:" + userId + "\n\n");
                        response.write("event:join\ndata:" + pname + "\n\n");
                    }
                }
            }
            else if (user.esResponse) {
                user.esResponse.end();
                clearTimeout(user.esResponse.keepAliveTimer);
                user.esResponse = null;
            }
            user.esResponse = response;

            request.on("close", function () {
                for (var pname in session.users) {
                    if (pname == userId)
                        continue;
                    var esResp = session.users[pname].esResponse;
                    esResp.write("event:leave\ndata:" + userId + "\n\n");
                }
                delete session.users[userId];
                clearTimeout(response.keepAliveTimer);
                console.log("@" + sessionId + " - " + userId + " left.");
                console.log("users in session " + sessionId + ": " + Object.keys(session.users).length);
            });

        } else { // parts[1] == "ctos"
            var peerId = parts[4];
            var peer;
            var session = sessions[sessionId];
            if (!session || !(peer = session.users[peerId])) {
                response.writeHead(400, headers);
                response.end();
                return;
            }

            var body = "";
            request.on("data", function (data) { body += data; });
            request.on("end", function () {
                console.log("@" + sessionId + " - " + userId + " => " + peerId + " :");
                // console.log(body);
                var evtdata = "data:" + body.replace(/\n/g, "\ndata:") + "\n";
                peer.esResponse.write("event:user-" + userId + "\n" + evtdata + "\n");
            });

            // to avoid "no element found" warning in Firefox (bug 521301)
            headers["Content-Type"] = "text/plain";
            response.writeHead(204, headers);
            response.end();
        }

        return;
    }

    var url = request.url.split("?", 1)[0];
    var filePath = path.join(clientDir, url);
    if (filePath.indexOf(clientDir) != 0 || filePath == clientDir)
        filePath = path.join(clientDir, "/webrtc_example.html");

    fs.stat(filePath, function (err, stats) {
        if (err || !stats.isFile()) {
            response.writeHead(404);
            response.end("404 Not found");
            return;
        }

        var contentType = contentTypeMap[path.extname(filePath)] || "text/plain";
        response.writeHead(200, { "Content-Type": contentType });

        var readStream = fs.createReadStream(filePath);
        readStream.on("error", function () {
            response.writeHead(500);
            response.end("500 Server error");
        });
        readStream.pipe(response);
    });
};

console.log('The HTTP server is listening on port ' + port);
http.createServer(requestListener).listen(port);

if (httpsKeyPath && httpsCertPath) {
    var options = {
        key: fs.readFileSync(httpsKeyPath),
        cert: fs.readFileSync(httpsCertPath)
    };
    if (httpsCACertPath) {
        options.ca = fs.readFileSync(httpsCACertPath)
    }

    console.log('The HTTPS server is listening on port ' + httpsPort);
    https.createServer(options, requestListener).listen(httpsPort);
}
<|endoftext|>


<commit_before>;(function($$){ 'use strict';

  $$.fn.eles({
    nodes: function( selector ){
      return this.filter(function(i, element){
        return element.isNode();
      }).filter(selector);
    },

    edges: function( selector ){
      return this.filter(function(i, element){
        return element.isEdge();
      }).filter(selector);
    },

    filter: function( filter ){
      var cy = this._private.cy;

      if( $$.is.fn(filter) ){
        var elements = [];

        for( var i = 0; i < this.length; i++ ){
          var ele = this[i];

          if( filter.apply(ele, [i, ele]) ){
            elements.push(ele);
          }
        }

        return new $$.Collection(cy, elements);

      } else if( $$.is.string(filter) || $$.is.elementOrCollection(filter) ){
        return new $$.Selector(filter).filter(this);

      } else if( filter === undefined ){
        return this;
      }

      return new $$.Collection( cy ); // if not handled by above, give 'em an empty collection
    },

    not: function( toRemove ){
      var cy = this._private.cy;

      if( !toRemove ){
        return this;
      } else {

        if( $$.is.string( toRemove ) ){
          toRemove = this.filter( toRemove );
        }

        var elements = [];

        for( var i = 0; i < this.length; i++ ){
          var element = this[i];

          var remove = toRemove._private.ids[ element.id() ];
          if( !remove ){
            elements.push( element );
          }
        }

        return new $$.Collection( cy, elements );
      }

    },

    absoluteComplement: function(){
      var cy = this._private.cy;

      return cy.elements().not( this );
    },

    intersect: function( other ){
      var cy = this._private.cy;

      // if a selector is specified, then filter by it instead
      if( $$.is.string(other) ){
        var selector = other;
        return this.filter( selector );
      }

      var elements = [];
      var col1 = this;
      var col2 = other;
      var col1Smaller = this.length < other.length;
      // var ids1 = col1Smaller ? col1._private.ids : col2._private.ids;
      var ids2 = col1Smaller ? col2._private.ids : col1._private.ids;
      var col = col1Smaller ? col1 : col2;

      for( var i = 0; i < col.length; i++ ){
        var id = col[i]._private.data.id;
        var ele = ids2[ id ];

        if( ele ){
          elements.push( ele );
        }
      }

      return new $$.Collection( cy, elements );
    },

    xor: function( other ){
      var cy = this._private.cy;

      if( $$.is.string(other) ){
        other = cy.$( other );
      }

      var elements = [];
      var col1 = this;
      var col2 = other;

      var add = function( col, other ){

        for( var i = 0; i < col.length; i++ ){
          var ele = col[i];
          var id = ele._private.data.id;
          var inOther = other._private.ids[ id ];

          if( !inOther ){
            elements.push( ele );
          }
        }

      };

      add( col1, col2 );
      add( col2, col1 );

      return new $$.Collection( cy, elements );
    },

    diff: function( other ){
      var cy = this._private.cy;

      if( $$.is.string(other) ){
        other = cy.$( other );
      }

      var left = [];
      var right = [];
      var both = [];
      var col1 = this;
      var col2 = other;

      var add = function( col, other, retEles ){

        for( var i = 0; i < col.length; i++ ){
          var ele = col[i];
          var id = ele._private.data.id;
          var inOther = other._private.ids[ id ];

          if( inOther ){
            both.push( ele );
          } else {
            retEles.push( ele );
          }
        }

      };

      add( col1, col2, left );
      add( col2, col1, right );

      return {
        left: new $$.Collection( cy, left, { unique: true } ),
        right: new $$.Collection( cy, right, { unique: true } ),
        both: new $$.Collection( cy, both, { unique: true } )
      };
    },

    add: function( toAdd ){
      var cy = this._private.cy;

      if( !toAdd ){
        return this;
      }

      if( $$.is.string(toAdd) ){
        var selector = toAdd;
        toAdd = cy.elements(selector);
      }

      var elements = [];

      for( var i = 0; i < this.length; i++ ){
        elements.push( this[i] );
      }

      for( var i = 0; i < toAdd.length; i++ ){

        var add = !this._private.ids[ toAdd[i].id() ];
        if( add ){
          elements.push( toAdd[i] );
        }
      }

      return new $$.Collection(cy, elements);
    },

    // in place merge on calling collection
    merge: function( toAdd ){
      var _p = this._private;
      var cy = _p.cy;

      if( !toAdd ){
        return this;
      }

      if( $$.is.string(toAdd) ){
        var selector = toAdd;
        toAdd = cy.elements(selector);
      }

      for( var i = 0; i < toAdd.length; i++ ){
        var toAddEle = toAdd[i];
        var id = toAddEle.id();
        var add = !_p.ids[ id ];

        if( add ){
          var index = this.length++;

          this[ index ] = toAddEle;
          _p.ids[ id ] = toAddEle;
          _p.indexes[ id ] = index;
        }
      }

      return this; // chaining
    },

    // remove single ele in place in calling collection
    unmergeOne: function( ele ){
      ele = ele[0];

      var _p = this._private;
      var id = ele.id();
      var i = _p.indexes[ id ];

      if( i == null ){
        return this; // no need to remove
      }

      // remove ele
      this[i] = undefined;
      _p.ids[ id ] = undefined;
      _p.indexes[ id ] = undefined;

      var unmergedLastEle = i === this.length - 1;

      // replace empty spot with last ele in collection
      if( this.length > 1 && !unmergedLastEle ){
        var lastEleI = this.length - 1;
        var lastEle = this[ lastEleI ];

        this[ lastEleI ] = undefined;
        this[i] = lastEle;
        _p.indexes[ lastEle.id() ] = i;
      }

      // the collection is now 1 ele smaller
      this.length--;

      return this;
    },

    // remove eles in place on calling collection
    unmerge: function( toRemove ){
      var cy = this._private.cy;

      if( !toRemove ){
        return this;
      }

      if( $$.is.string(toRemove) ){
        var selector = toRemove;
        toRemove = cy.elements(selector);
      }

      for( var i = 0; i < toRemove.length; i++ ){
        this.unmergeOne( toRemove[i] );
      }

      return this; // chaining
    },

    map: function( mapFn, thisArg ){
      var arr = [];
      var eles = this;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var ret = mapFn.apply( thisArg, [ele, i, eles] );

        arr.push( ret );
      }

      return arr;
    },

    stdFilter: function( fn, thisArg ){
      var filterEles = [];
      var eles = this;
      var cy = this._private.cy;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var include = fn.apply( thisArg, [ele, i, eles] );

        if( include ){
          filterEles.push( ele );
        }
      }

      return new $$.Collection( cy, filterEles );
    },

    max: function( valFn, thisArg ){
      var max = -Infinity;
      var maxEle;
      var eles = this;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var val = valFn.apply( thisArg, [ ele, i, eles ] );

        if( val > max ){
          max = val;
          maxEle = ele;
        }
      }

      return {
        value: max,
        ele: maxEle
      };
    },

    min: function( valFn, thisArg ){
      var min = Infinity;
      var minEle;
      var eles = this;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var val = valFn.apply( thisArg, [ ele, i, eles ] );

        if( val < min ){
          min = val;
          minEle = ele;
        }
      }

      return {
        value: min,
        ele: minEle
      };
    }
  });

  // aliases
  var fn = $$.elesfn;
  fn['u'] = fn['|'] = fn['+'] = fn.union = fn.or = fn.add;
  fn['\\'] = fn['!'] = fn['-'] = fn.difference = fn.relativeComplement = fn.not;
  fn['n'] = fn['&'] = fn['.'] = fn.and = fn.intersection = fn.intersect;
  fn['^'] = fn['(+)'] = fn['(-)'] = fn.symmetricDifference = fn.symdiff = fn.xor;
  fn.fnFilter = fn.filterFn = fn.stdFilter;
  fn.complement = fn.abscomp = fn.absoluteComplement;

})( cytoscape );<commit_msg> Improve performance of functions where thisArg === undefined #756<commit_after>;(function($$){ 'use strict';

  $$.fn.eles({
    nodes: function( selector ){
      return this.filter(function(i, element){
        return element.isNode();
      }).filter(selector);
    },

    edges: function( selector ){
      return this.filter(function(i, element){
        return element.isEdge();
      }).filter(selector);
    },

    filter: function( filter ){
      var cy = this._private.cy;

      if( $$.is.fn(filter) ){
        var elements = [];

        for( var i = 0; i < this.length; i++ ){
          var ele = this[i];

          if( filter.apply(ele, [i, ele]) ){
            elements.push(ele);
          }
        }

        return new $$.Collection(cy, elements);

      } else if( $$.is.string(filter) || $$.is.elementOrCollection(filter) ){
        return new $$.Selector(filter).filter(this);

      } else if( filter === undefined ){
        return this;
      }

      return new $$.Collection( cy ); // if not handled by above, give 'em an empty collection
    },

    not: function( toRemove ){
      var cy = this._private.cy;

      if( !toRemove ){
        return this;
      } else {

        if( $$.is.string( toRemove ) ){
          toRemove = this.filter( toRemove );
        }

        var elements = [];

        for( var i = 0; i < this.length; i++ ){
          var element = this[i];

          var remove = toRemove._private.ids[ element.id() ];
          if( !remove ){
            elements.push( element );
          }
        }

        return new $$.Collection( cy, elements );
      }

    },

    absoluteComplement: function(){
      var cy = this._private.cy;

      return cy.elements().not( this );
    },

    intersect: function( other ){
      var cy = this._private.cy;

      // if a selector is specified, then filter by it instead
      if( $$.is.string(other) ){
        var selector = other;
        return this.filter( selector );
      }

      var elements = [];
      var col1 = this;
      var col2 = other;
      var col1Smaller = this.length < other.length;
      // var ids1 = col1Smaller ? col1._private.ids : col2._private.ids;
      var ids2 = col1Smaller ? col2._private.ids : col1._private.ids;
      var col = col1Smaller ? col1 : col2;

      for( var i = 0; i < col.length; i++ ){
        var id = col[i]._private.data.id;
        var ele = ids2[ id ];

        if( ele ){
          elements.push( ele );
        }
      }

      return new $$.Collection( cy, elements );
    },

    xor: function( other ){
      var cy = this._private.cy;

      if( $$.is.string(other) ){
        other = cy.$( other );
      }

      var elements = [];
      var col1 = this;
      var col2 = other;

      var add = function( col, other ){

        for( var i = 0; i < col.length; i++ ){
          var ele = col[i];
          var id = ele._private.data.id;
          var inOther = other._private.ids[ id ];

          if( !inOther ){
            elements.push( ele );
          }
        }

      };

      add( col1, col2 );
      add( col2, col1 );

      return new $$.Collection( cy, elements );
    },

    diff: function( other ){
      var cy = this._private.cy;

      if( $$.is.string(other) ){
        other = cy.$( other );
      }

      var left = [];
      var right = [];
      var both = [];
      var col1 = this;
      var col2 = other;

      var add = function( col, other, retEles ){

        for( var i = 0; i < col.length; i++ ){
          var ele = col[i];
          var id = ele._private.data.id;
          var inOther = other._private.ids[ id ];

          if( inOther ){
            both.push( ele );
          } else {
            retEles.push( ele );
          }
        }

      };

      add( col1, col2, left );
      add( col2, col1, right );

      return {
        left: new $$.Collection( cy, left, { unique: true } ),
        right: new $$.Collection( cy, right, { unique: true } ),
        both: new $$.Collection( cy, both, { unique: true } )
      };
    },

    add: function( toAdd ){
      var cy = this._private.cy;

      if( !toAdd ){
        return this;
      }

      if( $$.is.string(toAdd) ){
        var selector = toAdd;
        toAdd = cy.elements(selector);
      }

      var elements = [];

      for( var i = 0; i < this.length; i++ ){
        elements.push( this[i] );
      }

      for( var i = 0; i < toAdd.length; i++ ){

        var add = !this._private.ids[ toAdd[i].id() ];
        if( add ){
          elements.push( toAdd[i] );
        }
      }

      return new $$.Collection(cy, elements);
    },

    // in place merge on calling collection
    merge: function( toAdd ){
      var _p = this._private;
      var cy = _p.cy;

      if( !toAdd ){
        return this;
      }

      if( $$.is.string(toAdd) ){
        var selector = toAdd;
        toAdd = cy.elements(selector);
      }

      for( var i = 0; i < toAdd.length; i++ ){
        var toAddEle = toAdd[i];
        var id = toAddEle.id();
        var add = !_p.ids[ id ];

        if( add ){
          var index = this.length++;

          this[ index ] = toAddEle;
          _p.ids[ id ] = toAddEle;
          _p.indexes[ id ] = index;
        }
      }

      return this; // chaining
    },

    // remove single ele in place in calling collection
    unmergeOne: function( ele ){
      ele = ele[0];

      var _p = this._private;
      var id = ele.id();
      var i = _p.indexes[ id ];

      if( i == null ){
        return this; // no need to remove
      }

      // remove ele
      this[i] = undefined;
      _p.ids[ id ] = undefined;
      _p.indexes[ id ] = undefined;

      var unmergedLastEle = i === this.length - 1;

      // replace empty spot with last ele in collection
      if( this.length > 1 && !unmergedLastEle ){
        var lastEleI = this.length - 1;
        var lastEle = this[ lastEleI ];

        this[ lastEleI ] = undefined;
        this[i] = lastEle;
        _p.indexes[ lastEle.id() ] = i;
      }

      // the collection is now 1 ele smaller
      this.length--;

      return this;
    },

    // remove eles in place on calling collection
    unmerge: function( toRemove ){
      var cy = this._private.cy;

      if( !toRemove ){
        return this;
      }

      if( $$.is.string(toRemove) ){
        var selector = toRemove;
        toRemove = cy.elements(selector);
      }

      for( var i = 0; i < toRemove.length; i++ ){
        this.unmergeOne( toRemove[i] );
      }

      return this; // chaining
    },

    map: function( mapFn, thisArg ){
      var arr = [];
      var eles = this;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var ret = thisArg ? mapFn.apply( thisArg, [ele, i, eles] ) : mapFn( ele, i, eles );

        arr.push( ret );
      }

      return arr;
    },

    stdFilter: function( fn, thisArg ){
      var filterEles = [];
      var eles = this;
      var cy = this._private.cy;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var include = thisArg ? fn.apply( thisArg, [ele, i, eles] ) : fn( ele, i, eles );

        if( include ){
          filterEles.push( ele );
        }
      }

      return new $$.Collection( cy, filterEles );
    },

    max: function( valFn, thisArg ){
      var max = -Infinity;
      var maxEle;
      var eles = this;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var val = thisArg ? valFn.apply( thisArg, [ ele, i, eles ] ) : valFn( ele, i, eles );

        if( val > max ){
          max = val;
          maxEle = ele;
        }
      }

      return {
        value: max,
        ele: maxEle
      };
    },

    min: function( valFn, thisArg ){
      var min = Infinity;
      var minEle;
      var eles = this;

      for( var i = 0; i < eles.length; i++ ){
        var ele = eles[i];
        var val = thisArg ? valFn.apply( thisArg, [ ele, i, eles ] ) : valFn( ele, i, eles );

        if( val < min ){
          min = val;
          minEle = ele;
        }
      }

      return {
        value: min,
        ele: minEle
      };
    }
  });

  // aliases
  var fn = $$.elesfn;
  fn['u'] = fn['|'] = fn['+'] = fn.union = fn.or = fn.add;
  fn['\\'] = fn['!'] = fn['-'] = fn.difference = fn.relativeComplement = fn.not;
  fn['n'] = fn['&'] = fn['.'] = fn.and = fn.intersection = fn.intersect;
  fn['^'] = fn['(+)'] = fn['(-)'] = fn.symmetricDifference = fn.symdiff = fn.xor;
  fn.fnFilter = fn.filterFn = fn.stdFilter;
  fn.complement = fn.abscomp = fn.absoluteComplement;

})( cytoscape );<|endoftext|>


<commit_before>/**
 * @name mainApp
 * @requieres
 * @type {angular.Module}
 * @description Main module of the application
 */
var mainApp = angular.module('mainApp',[
    'ngRoute',
    'mainAppCtrls',
    'mgcrea.ngStrap',
    'ui.router',
    'angular-jwt',
    'restSvcs',
    'angular-storage',
    'pascalprecht.translate',
    'textAngular'
]);
/**
 * @name mainAppCtrls
 * @type {angular.Module}
 * @description Module containg all controller of the application
 */
var mainAppCtrls = angular.module('mainAppCtrls',["pascalprecht.translate"]);

mainApp.config(['$urlRouterProvider','$stateProvider',
    function($urlRouterProvider,$stateProvider)
    {
        var prefix = "resources/views/";

        $stateProvider
            .state('workshops',{
                url: '/workshops',
                controller: 'WorkshopListCtrl',
                templateUrl: prefix.concat('workshopList.html')
            })
            .state('workshopsdetails',{
                url: '/workshops/details/:id',
                controller: 'WorkshopDetailsCtrl',
                templateUrl: prefix.concat('workshopDetails.html')
            })
            .state('login',{
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: prefix.concat('login.html')
            })
            .state('enrollment_confirm',{
                url: '/enrollment_confirm/:id/:token',
                templateUrl: prefix.concat('enrollmentConfirm.html'),
                controller: 'EnrollmentConfirm'
            })
            .state('unsubscribe',{
                url: '/unsubscribe/:id/:workshopid/:token',
                templateUrl: prefix.concat('unsubscribemessage.html'),
                controller: 'UnsubscribeController'
            })
            .state('password_reset',{
                url: '/password_reset/:token',
                templateUrl: prefix.concat('passwordReset.html'),
                controller: 'PasswordRestCtrl'
            })
            .state('dashboard',{
                url: '/dashboard',
                controller: 'DashboardCtrl',
                templateUrl: prefix.concat('adminDashboard.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template',{
                url:'/workshop_template',
                controller:'WorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminWorkshopTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template_new', {
                url: 'workshop/template/new',
                controller: 'NewWorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminNewWorkshopTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })

            .state('workshop_template.edit', {
                url: '/edit/:id',
                controller: 'EditWorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template', {
                url: '/email_template',
                controller: 'EmailTemplateCtrl',
                templateUrl: prefix.concat('adminEmailTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.new', {
                url: '/new',
                controller: 'NewEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.edit', {
                url: '/edit/:id',
                controller: 'EditEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('blacklist',{
                url: '/blacklist',
                controller: 'BlacklistCtrl',
                templateUrl: prefix.concat('adminBlacklist.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('administrator_management', {
                    url: '/administrator_management',
                    controller: 'AdministratorManagementCtrl',
                    templateUrl: prefix.concat('administratorManagement.html'),
                data: {
                    //requiresLogin: true
                }
                })
            .state('settings', {
                url: '/settings',
                controller: 'SettingsCtrl',
                templateUrl: prefix.concat('adminSettings.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_managment',{
                url: '/workshop_managment',
                controller: 'WorkshopManagmentCtrl',
                templateUrl: prefix.concat('adminWorkshopManagement.html')
            })
            .state('admininvite',{
                url: '/admin/create/:token',
                controller: 'AdminCreateCtrl',
                templateUrl: prefix.concat('adminInvite.html')
            })
            .state('legalnotice',{
                url: '/legalnotice',
                controller: 'LegalNoticeCtrl',
                templateUrl: prefix.concat('legalNotice.html')
            })
            .state('contact',{
                url: '/contact',
                controller: 'ContactCtrl',
                templateUrl: prefix.concat('contact.html')
            });

        $urlRouterProvider.otherwise('/workshops');

    }
]);

mainApp.config(['jwtInterceptorProvider','$httpProvider','$urlRouterProvider',function(jwtInterceptorProvider,$httpProvider,$urlRouterProvider){
    jwtInterceptorProvider.tokenGetter = function(store) {
        return store.get('jwt');
    }

    $httpProvider.interceptors.push('jwtInterceptor');
}])
    .run(['$rootScope','$state','store','jwtHelper','UIHelper',function($rootScope, $state, store, jwtHelper,UIHelper) {
        UIHelper.ToggleLogout();
        $rootScope.$on('$stateChangeStart', function(e, to) {
            if (to.data.requiresLogin) {
                if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                    e.preventDefault();
                    $state.go('login');
                }
            }

        });
    }]);

mainApp.config(['$translateProvider', function($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/local/lang-',
        suffix: '.json'
    });
    $translateProvider.preferredLanguage('en');
}]);
/**
 * @ngdoc service
 * @descrption Helper service to show or hide User UI elements
 * @name  mainApp.UIHelper
 */
mainApp.factory('UIHelper',['$rootScope','store','jwtHelper',function($rootScope,store,jwtHelper){
    return {
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#HideUserUI
         * @description hide the user UI
         * @methodOf mainApp.UIHelper
         */
        HideUserUI: function(){
            $rootScope.hide_user_ui = true;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ShowUserUI
         * @description show the user UI
         * @methodOf mainApp.UIHelper
         */
        ShowUserUI: function(){
            $rootScope.hide_user_ui = false;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleUserUI
         * @description toggle the user UI
         * @methodOf mainApp.UIHelper
         */
        ToggleUserUI: function(){
            $rootScope.hide_user_ui = ! $rootScope.hide_user_ui;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleLogout
         * @description Toggles, if the Logout or the Login Button is shown
         * @methodOf mainApp.UIHelper
         */
        ToggleLogout: function(){
            var jwt  = store.get('jwt');
            if(!jwt){
                $rootScope.logged_in = false;
                return;
            }
            $rootScope.logged_in = jwtHelper.isTokenExpired(jwt);
        }
    }
}]);
/**
 * @ngdoc directive
 * @name mainApp.compare-to
 */
mainApp.directive('compareTo',[function(){
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {

            ngModel.$validators.compareTo = function(modelValue) {
                return modelValue == scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {
                ngModel.$validate();
            });
        }
    };
    }
]);
<commit_msg>fixed typo<commit_after>/**
 * @name mainApp
 * @requieres
 * @type {angular.Module}
 * @description Main module of the application
 */
var mainApp = angular.module('mainApp',[
    'ngRoute',
    'mainAppCtrls',
    'mgcrea.ngStrap',
    'ui.router',
    'angular-jwt',
    'restSvcs',
    'angular-storage',
    'pascalprecht.translate',
    'textAngular'
]);
/**
 * @name mainAppCtrls
 * @type {angular.Module}
 * @description Module containg all controller of the application
 */
var mainAppCtrls = angular.module('mainAppCtrls',["pascalprecht.translate"]);

mainApp.config(['$urlRouterProvider','$stateProvider',
    function($urlRouterProvider,$stateProvider)
    {
        var prefix = "resources/views/";

        $stateProvider
            .state('workshops',{
                url: '/workshops',
                controller: 'WorkshopListCtrl',
                templateUrl: prefix.concat('workshopList.html')
            })
            .state('workshopsdetails',{
                url: '/workshops/details/:id',
                controller: 'WorkshopDetailsCtrl',
                templateUrl: prefix.concat('workshopDetails.html')
            })
            .state('login',{
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: prefix.concat('login.html')
            })
            .state('enrollment_confirm',{
                url: '/enrollment_confirm/:id/:token',
                templateUrl: prefix.concat('enrollmentConfirm.html'),
                controller: 'EnrollmentConfirm'
            })
            .state('unsubscribe',{
                url: '/unsubscribe/:id/:workshopid/:token',
                templateUrl: prefix.concat('unsubscribemessage.html'),
                controller: 'UnsubscribeController'
            })
            .state('password_reset',{
                url: '/password_reset/:token',
                templateUrl: prefix.concat('passwordReset.html'),
                controller: 'PasswordRestCtrl'
            })
            .state('dashboard',{
                url: '/dashboard',
                controller: 'DashboardCtrl',
                templateUrl: prefix.concat('adminDashboard.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template',{
                url:'/workshop_template',
                controller:'WorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminWorkshopTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template_new', {
                url: '/workshop/template/new',
                controller: 'NewWorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminNewWorkshopTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })

            .state('workshop_template.edit', {
                url: '/edit/:id',
                controller: 'EditWorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template', {
                url: '/email_template',
                controller: 'EmailTemplateCtrl',
                templateUrl: prefix.concat('adminEmailTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.new', {
                url: '/new',
                controller: 'NewEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.edit', {
                url: '/edit/:id',
                controller: 'EditEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('blacklist',{
                url: '/blacklist',
                controller: 'BlacklistCtrl',
                templateUrl: prefix.concat('adminBlacklist.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('administrator_management', {
                    url: '/administrator_management',
                    controller: 'AdministratorManagementCtrl',
                    templateUrl: prefix.concat('administratorManagement.html'),
                data: {
                    //requiresLogin: true
                }
                })
            .state('settings', {
                url: '/settings',
                controller: 'SettingsCtrl',
                templateUrl: prefix.concat('adminSettings.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_managment',{
                url: '/workshop_managment',
                controller: 'WorkshopManagmentCtrl',
                templateUrl: prefix.concat('adminWorkshopManagement.html')
            })
            .state('admininvite',{
                url: '/admin/create/:token',
                controller: 'AdminCreateCtrl',
                templateUrl: prefix.concat('adminInvite.html')
            })
            .state('legalnotice',{
                url: '/legalnotice',
                controller: 'LegalNoticeCtrl',
                templateUrl: prefix.concat('legalNotice.html')
            })
            .state('contact',{
                url: '/contact',
                controller: 'ContactCtrl',
                templateUrl: prefix.concat('contact.html')
            });

        $urlRouterProvider.otherwise('/workshops');

    }
]);

mainApp.config(['jwtInterceptorProvider','$httpProvider','$urlRouterProvider',function(jwtInterceptorProvider,$httpProvider,$urlRouterProvider){
    jwtInterceptorProvider.tokenGetter = function(store) {
        return store.get('jwt');
    }

    $httpProvider.interceptors.push('jwtInterceptor');
}])
    .run(['$rootScope','$state','store','jwtHelper','UIHelper',function($rootScope, $state, store, jwtHelper,UIHelper) {
        UIHelper.ToggleLogout();
        $rootScope.$on('$stateChangeStart', function(e, to) {
            if (to.data.requiresLogin) {
                if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                    e.preventDefault();
                    $state.go('login');
                }
            }

        });
    }]);

mainApp.config(['$translateProvider', function($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/local/lang-',
        suffix: '.json'
    });
    $translateProvider.preferredLanguage('en');
}]);
/**
 * @ngdoc service
 * @descrption Helper service to show or hide User UI elements
 * @name  mainApp.UIHelper
 */
mainApp.factory('UIHelper',['$rootScope','store','jwtHelper',function($rootScope,store,jwtHelper){
    return {
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#HideUserUI
         * @description hide the user UI
         * @methodOf mainApp.UIHelper
         */
        HideUserUI: function(){
            $rootScope.hide_user_ui = true;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ShowUserUI
         * @description show the user UI
         * @methodOf mainApp.UIHelper
         */
        ShowUserUI: function(){
            $rootScope.hide_user_ui = false;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleUserUI
         * @description toggle the user UI
         * @methodOf mainApp.UIHelper
         */
        ToggleUserUI: function(){
            $rootScope.hide_user_ui = ! $rootScope.hide_user_ui;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleLogout
         * @description Toggles, if the Logout or the Login Button is shown
         * @methodOf mainApp.UIHelper
         */
        ToggleLogout: function(){
            var jwt  = store.get('jwt');
            if(!jwt){
                $rootScope.logged_in = false;
                return;
            }
            $rootScope.logged_in = jwtHelper.isTokenExpired(jwt);
        }
    }
}]);
/**
 * @ngdoc directive
 * @name mainApp.compare-to
 */
mainApp.directive('compareTo',[function(){
    return {
        require: "ngModel",
        scope: {
            otherModelValue: "=compareTo"
        },
        link: function(scope, element, attributes, ngModel) {

            ngModel.$validators.compareTo = function(modelValue) {
                return modelValue == scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {
                ngModel.$validate();
            });
        }
    };
    }
]);
<|endoftext|>


<commit_before>const skip = (spec, stack) => {
  let s = stack;
  while(s.length && s[0].length < 2)
    s = s.slice(1);

  if (s.length)
    return backtracker(spec, [s[0].slice(1)].concat(s.slice(1)));
};

const step = (spec, stack) => {
  const children = spec.children(stack[0][0]);

  if (children && children.length)
    return backtracker(spec, [children].concat(stack));
  else
    return skip(spec, stack);
};

export const backtracker = (spec, stack=[[spec.root]]) => ({
  current: () => stack[0][0],
  result : () => spec.extract(stack[0][0]),
  step   : () => step(spec, stack),
  skip   : () => skip(spec, stack)
});

export function* results(gen, pred) {
  let g = gen;

  while (g) {
    if (!pred || pred(g.current())) {
      const val = g.result();
      g = g.step();
      if (val !== undefined)
        yield val;
    } else
      g = g.skip();
  }
};

export const empty = () => backtracker({
  root    : null,
  extract : () => {},
  children: () => {}
});

export const singleton = x => backtracker({
  root    : x,
  extract : x => x,
  children: () => {}
});

if (require.main == module) {
  const n = parseInt(process.argv[2]) || 4;

  const gen = backtracker({
    root: {
      xs: [],
      sz: 0,
      mx: 1
    },
    extract(node) {
      if (node.sz == n)
        return node.xs;
    },
    children(node) {
      const ch = [];

      for (let i = node.mx; i < n - node.sz + 1; ++i)
        ch.push({
          xs: node.xs.concat(i),
          sz: node.sz + i,
          mx: Math.max(node.mx, i)
        });

      return ch;
    }
  });

  const out = [];
  for (const a of results(gen))
    out.push(a);

  console.log(JSON.stringify(out));
}
<commit_msg>further simplification of backtracker implementation<commit_after>const skip = (spec, stack) => {
  const k = stack.findIndex(a => a.length >= 2);
  if (k >= 0)
    return backtracker(spec, [stack[k].slice(1)].concat(stack.slice(k + 1)));
};

const step = (spec, stack) => {
  const children = spec.children(stack[0][0]);

  if (children && children.length)
    return backtracker(spec, [children].concat(stack));
  else
    return skip(spec, stack);
};

export const backtracker = (spec, stack=[[spec.root]]) => ({
  current: () => stack[0][0],
  result : () => spec.extract(stack[0][0]),
  step   : () => step(spec, stack),
  skip   : () => skip(spec, stack)
});

export function* results(gen, pred) {
  let g = gen;

  while (g) {
    if (!pred || pred(g.current())) {
      const val = g.result();
      g = g.step();
      if (val !== undefined)
        yield val;
    } else
      g = g.skip();
  }
};

export const empty = () => backtracker({
  root    : null,
  extract : () => {},
  children: () => {}
});

export const singleton = x => backtracker({
  root    : x,
  extract : x => x,
  children: () => {}
});

if (require.main == module) {
  const n = parseInt(process.argv[2]) || 4;

  const gen = backtracker({
    root: {
      xs: [],
      sz: 0,
      mx: 1
    },
    extract(node) {
      if (node.sz == n)
        return node.xs;
    },
    children(node) {
      const ch = [];

      for (let i = node.mx; i < n - node.sz + 1; ++i)
        ch.push({
          xs: node.xs.concat(i),
          sz: node.sz + i,
          mx: Math.max(node.mx, i)
        });

      return ch;
    }
  });

  const out = [];
  for (const a of results(gen))
    out.push(a);

  console.log(JSON.stringify(out));
}
<|endoftext|>


<commit_before>import _ from 'intl'
import ActionButton from 'action-button'
import Icon from 'icon'
import React from 'react'
import { Link } from 'react-router'

const COMMON_PROPS = {
  size: 'large',
  style: {
    marginBottom: '1em',
    marginLeft: '1em'
  }
}
const TabButton = ({
  labelId,
  ...props
}) => (
  <ActionButton
    {...props}
    {...COMMON_PROPS}
  >{_(labelId)}</ActionButton>
)
export { TabButton as default }

export const TabButtonLink = ({
  labelId,
  icon,
  ...props
}) => (
  <Link
    {...props}
    {...COMMON_PROPS}
    className='btn btn-lg btn-primary'
  >

      {icon && (

          <Icon icon={icon} />
          {' '}

      )}
      {_(labelId)}

  </Link>
)
<commit_msg>chore(tab-button): inline props<commit_after>import _ from 'intl'
import ActionButton from 'action-button'
import Icon from 'icon'
import React from 'react'
import { Link } from 'react-router'

const STYLE = {
  marginBottom: '1em',
  marginLeft: '1em'
}

const TabButton = ({
  labelId,
  ...props
}) => (
  <ActionButton
    {...props}
    size='large'
    style={STYLE}
  >{_(labelId)}</ActionButton>
)
export { TabButton as default }

export const TabButtonLink = ({
  labelId,
  icon,
  ...props
}) => (
  <Link
    {...props}
    className='btn btn-lg btn-primary'
    style={STYLE}
  >

      {icon && (

          <Icon icon={icon} />
          {' '}

      )}
      {_(labelId)}

  </Link>
)
<|endoftext|>