<commit_before>;(function (define) {

    define([
        'underscore',
        'backbone',
        'js/discovery/models/course_card',
        'js/discovery/models/facet_option',
    ], function (_, Backbone, CourseCard, FacetOption) {
        'use strict';
        var facet_row_temp = {};
        var facet_row_temp_set = {};
        var facet_row_set = {};

        return Backbone.Model.extend({
            url: '/search/course_discovery/',
            jqhxr: null,

            defaults: {
                totalCount: 0,
                latestCount: 0
            },

            initialize: function () {
                this.courseCards = new Backbone.Collection([], {model: CourseCard});
                this.facetOptions = new Backbone.Collection([], {model: FacetOption});
            },

            parse: function (response) {
                var courses = response.results || [];
                var facets = response.facets || {};
                this.courseCards.add(_.pluck(courses, 'data'));

                this.set({
                    totalCount: response.total,
                    latestCount: courses.length
                });

                var options = this.facetOptions;

                var cnt = 0;

                facet_row_temp = {};
                facet_row_temp_set = {};
                facet_row_set = {};

                _(facets).each(function (obj, key) {

                    // console.log("obj: " + obj + ", key: " + key + "  [case 1 ]");

                    if (key == 'org') {

                        var count2 = 0;
                        var count3 = 0;

                        // skp, smu hard coding
                        //console.log("_(obj.terms) ==>"+_(obj.terms));

                        _(obj.terms).each(function (count, term) {

                            //console.log("1 _(obj.terms).each --------" + "term:" + term + ", count:" + count);

                            if (term.match(/^SKP.*/)) {
                                count2 += count;
                                return true;
                            }
                            if (term === 'SMUk' || term === 'SMUCk') {
                                count3 += count;
                                return true;
                            }
                            options.add({
                                facet: key,
                                term: term,
                                count: count
                            }, {merge: true});
                        });

                        // skp, smu hard coding
                        if (count2 > 0) {
                            options.add({
                                facet: key,
                                term: 'SKP',
                                count: count2
                            }, {merge: true});
                        }
                        if (count3 > 0) {
                            options.add({
                                facet: key,
                                term: 'SMUk',
                                count: count3
                            }, {merge: true});
                        }

                    } else if (key == 'classfysub' || key == 'middle_classfysub') {
                        return true;

                    } else {
                        _(obj.terms).each(function (count, term) {

                            if(key == 'fourth_industry_yn' && term == 'Y')
                                term = 'fourth_industry_y';
                            else if (key == 'job_edu_yn' && term == 'Y')
                                term = 'job_edu_y';

                            options.add({
                                facet: key,
                                term: term,
                                count: count
                            }, {merge: true});
                        });
                    }
                });

                /* 융복합의 경우 하위 분류에 해당하는 내용으로 데이터를 업데이트 */
                _(facets).each(function (obj, key) {
                    if (key == 'classfysub') {
                        _(obj.terms).each(function (count, term) {
                            // 융복합이 아닌경우 term 이 공백으로 넘어옴
                            if (term) {
                                let t = term.split(',');
                                for (let i in t) {
                                    if (options.get(t[i])) {
                                        options.get(t[i]).attributes.count += 1;
                                    } else {
                                        options.add({
                                            facet: 'classfy',
                                            term: t[i],
                                            count: 1
                                        }, {merge: true});
                                    }
                                }
                            }
                        });

                    } else if (key == 'middle_classfysub') {
                        _(obj.terms).each(function (count, term) {
                            // 융복합이 아닌경우 term 이 공백으로 넘어옴
                            if (term) {
                                let t = term.split(',');
                                for (let i in t) {
                                    if (options.get(t[i])) {
                                        options.get(t[i]).attributes.count += 1;
                                    } else {
                                        options.add({
                                            facet: 'middle_classfy',
                                            term: t[i],
                                            count: 1
                                        }, {merge: true});
                                    }
                                }
                            }
                        });
                    }
                });

            },

            reset: function () {
                this.set({
                    totalCount: 0,
                    latestCount: 0
                });
                this.courseCards.reset();
                this.facetOptions.reset();
            },

            latest: function () {
                return this.courseCards.last(this.get('latestCount'));
            }

        });

    });

})(define || RequireJS.define);
<commit_msg>강좌검색 facet 중복 값 변경<commit_after>;(function (define) {

    define([
        'underscore',
        'backbone',
        'js/discovery/models/course_card',
        'js/discovery/models/facet_option',
    ], function (_, Backbone, CourseCard, FacetOption) {
        'use strict';
        var facet_row_temp = {};
        var facet_row_temp_set = {};
        var facet_row_set = {};

        return Backbone.Model.extend({
            url: '/search/course_discovery/',
            jqhxr: null,

            defaults: {
                totalCount: 0,
                latestCount: 0
            },

            initialize: function () {
                this.courseCards = new Backbone.Collection([], {model: CourseCard});
                this.facetOptions = new Backbone.Collection([], {model: FacetOption});
            },

            parse: function (response) {
                var courses = response.results || [];
                var facets = response.facets || {};
                this.courseCards.add(_.pluck(courses, 'data'));

                this.set({
                    totalCount: response.total,
                    latestCount: courses.length
                });

                var options = this.facetOptions;

                var cnt = 0;

                facet_row_temp = {};
                facet_row_temp_set = {};
                facet_row_set = {};

                _(facets).each(function (obj, key) {

                    // console.log("obj: " + obj + ", key: " + key + "  [case 1 ]");

                    if (key == 'org') {

                        var count2 = 0;
                        var count3 = 0;

                        // skp, smu hard coding
                        //console.log("_(obj.terms) ==>"+_(obj.terms));

                        _(obj.terms).each(function (count, term) {

                            //console.log("1 _(obj.terms).each --------" + "term:" + term + ", count:" + count);

                            if (term.match(/^SKP.*/)) {
                                count2 += count;
                                return true;
                            }
                            if (term === 'SMUk' || term === 'SMUCk') {
                                count3 += count;
                                return true;
                            }
                            options.add({
                                facet: key,
                                term: term,
                                count: count
                            }, {merge: true});
                        });

                        // skp, smu hard coding
                        if (count2 > 0) {
                            options.add({
                                facet: key,
                                term: 'SKP',
                                count: count2
                            }, {merge: true});
                        }
                        if (count3 > 0) {
                            options.add({
                                facet: key,
                                term: 'SMUk',
                                count: count3
                            }, {merge: true});
                        }

                    } else if (key == 'classfysub' || key == 'middle_classfysub') {
                        return true;

                    } else {
                        _(obj.terms).each(function (count, term) {

                            if(key == 'fourth_industry_yn' && term == 'Y')
                                term = 'fourth_industry_y';
                            else if (key == 'job_edu_yn' && term == 'Y')
                                term = 'job_edu_y';
                            else if (key == 'ai_yn' && term == 'Y')
                                term = 'ai_y';
                            else if (key == 'basic_science_yn' && term == 'Y')
                                term = 'basic_science_y';

                            options.add({
                                facet: key,
                                term: term,
                                count: count
                            }, {merge: true});
                        });
                    }
                });

                /* 융복합의 경우 하위 분류에 해당하는 내용으로 데이터를 업데이트 */
                _(facets).each(function (obj, key) {
                    if (key == 'classfysub') {
                        _(obj.terms).each(function (count, term) {
                            // 융복합이 아닌경우 term 이 공백으로 넘어옴
                            if (term) {
                                let t = term.split(',');
                                for (let i in t) {
                                    if (options.get(t[i])) {
                                        options.get(t[i]).attributes.count += 1;
                                    } else {
                                        options.add({
                                            facet: 'classfy',
                                            term: t[i],
                                            count: 1
                                        }, {merge: true});
                                    }
                                }
                            }
                        });

                    } else if (key == 'middle_classfysub') {
                        _(obj.terms).each(function (count, term) {
                            // 융복합이 아닌경우 term 이 공백으로 넘어옴
                            if (term) {
                                let t = term.split(',');
                                for (let i in t) {
                                    if (options.get(t[i])) {
                                        options.get(t[i]).attributes.count += 1;
                                    } else {
                                        options.add({
                                            facet: 'middle_classfy',
                                            term: t[i],
                                            count: 1
                                        }, {merge: true});
                                    }
                                }
                            }
                        });
                    }
                });

            },

            reset: function () {
                this.set({
                    totalCount: 0,
                    latestCount: 0
                });
                this.courseCards.reset();
                this.facetOptions.reset();
            },

            latest: function () {
                return this.courseCards.last(this.get('latestCount'));
            }

        });

    });

})(define || RequireJS.define);
<|endoftext|>


<commit_before>/*
 @author Zakai Hamilton
 @component CoreString
 */

screens.core.string = function CoreString(me, { core }) {
    me.delimiters = function () {
        var delimiters = [
            "\n", ";", ":", ".", ",", "—", "–", "-", "(", ")", "[", "]", "{", "}", "+", "<", ">", "?", "/", "\\", "”", "“", "!", "\"", "…", "'", "‘", "’", "\x09"
        ];
        return delimiters;
    };
    me.hasDelimiter = function (string) {
        var delimiters = me.delimiters();
        var result = false;
        for (var index = 0; index < delimiters.length - 1; index++) {
            var delimiter = delimiters[index];
            if (string.includes(delimiter)) {
                result = true;
                break;
            }
        }
        return result;
    };
    me.unparseWords = function (string) {
        var delimiters = me.delimiters();
        for (let index = 0; index < delimiters.length; index++) {
            let delimiter = delimiters[index];
            string = string.split(" " + delimiter + " ").join(delimiter);
        }
        return string;
    };
    me.parseWords = function (callback, string) {
        var delimiters = me.delimiters();
        for (let index = 0; index < delimiters.length; index++) {
            let delimiter = delimiters[index];
            string = string.split(delimiter).join(" " + delimiter + " ");
        }
        var words = string.split(" ");
        callback(words);
        string = words.join(" ");
        for (let index = 0; index < delimiters.length; index++) {
            let delimiter = delimiters[index];
            string = string.split(" " + delimiter + " ").join(delimiter);
        }
        return string;
    };
    me.nextWord = function (string) {
        var nextWord = "";
        core.string.parseWords(function (words) {
            if (words.length > 0) {
                nextWord = words[0];
            }
        }, string);
        return nextWord;
    };
    me.direction = function (string) {
        if (!string) {
            return "ltr";
        }
        var position = string.search(/[A-Za-z]/);
        if (position >= 0) {
            return "ltr";
        }
        return "rtl";
    };
    me.language = function (string) {
        if (!string) {
            return "english";
        }
        var position = string.search(/[A-Za-z]/);
        if (position >= 0) {
            return "english";
        }
        position = string.search(/[ֿ\u0590-\u05FF]/);
        if (position >= 0) {
            return "hebrew";
        }
        return "english";
    };
    me.regex = function (string, options = "g") {
        if (string.startsWith("/")) {
            string = string.slice(1);
            string = new RegExp(string, options);
        }
        return string;
    };
    me.escape = function (string) {
        return string.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
    };
    me.match = function (source, target, wordStyle) {
        if (wordStyle === "whole") {
            return source === target;
        } else if (wordStyle === "prefix") {
            return source.beginsWith(target);
        } else if (wordStyle === "suffix") {
            return source.endsWith(target);
        } else {
            return source.includes(target);
        }
    };
    me.middleLetters = function (source, target) {
        var index = source.toUpperCase().indexOf(target.toUpperCase());
        if (index !== -1) {
            return source.substring(index, index + target.length);
        }
        return "";
    };
    me.prefixLetters = function (source, target) {
        var index = source.toUpperCase().indexOf(target.toUpperCase());
        if (index !== -1 && index) {
            return source.substring(0, index);
        }
        return "";
    };
    me.suffixLetters = function (source, target) {
        var index = source.toUpperCase().indexOf(target.toUpperCase());
        if (index !== -1 && index + target.length < source.length) {
            return source.substring(index + target.length);
        }
        return "";
    };
    me.prefix = function (string, separator) {
        var prefix = string;
        if (string) {
            var tokens = string.split(separator);
            if (tokens && tokens.length > 1) {
                prefix = tokens[0];
            }
        }
        return prefix;
    };
    me.suffix = function (string, separator) {
        var suffix = "";
        if (string) {
            var tokens = string.split(separator);
            if (tokens && tokens.length > 1) {
                suffix = tokens[1];
            }
        }
        return suffix;
    };
    me.encode = function (string) {
        if (me.platform === "server" || me.platform === "service") {
            return Buffer.from((unescape(encodeURIComponent(string))), "binary").toString("base64");
        }
        else {
            return window.btoa(unescape(encodeURIComponent(string)));
        }
    };
    me.decode = function (string) {
        if (me.platform === "server" || me.platform === "service") {
            return decodeURIComponent(escape(Buffer.from(string, "base64").toString("binary")));
        }
        else {
            return decodeURIComponent(escape(window.atob(string)));
        }
    };
    me.blobToString = function (blob) {
        var url, request;
        url = URL.createObjectURL(blob);
        request = new XMLHttpRequest();
        request.open("GET", url, false);
        request.send();
        URL.revokeObjectURL(url);
        return request.responseText;
    };
    me.caselessCompare = function (source, target) {
        if ((source && !target) || (!source && target)) {
            return false;
        }
        if (!source && !target) {
            return true;
        }
        return source.toLowerCase() === target.toLowerCase();
    };
    me.optional = function (string, check) {
        var result = "";
        if (check) {
            result = string;
        }
        return result;
    };
    me.split = function (string, delimiter = " ", quote = "\"") {
        if (string) {
            return [].concat.apply([], string.split(quote).map(function (v, i) {
                return i % 2 ? v : v.split(delimiter);
            })).filter(Boolean);
        }
        else {
            return [];
        }
    };
    me.fill = function (string, params, prefix = "") {
        for (var param in params) {
            string = string.split(prefix + param).join(params[param]);
        }
        return string;
    };
    me.padNumber = function (string, size, char = " ") {
        string = String(string);
        var index = 0;
        for (; string[index] >= "0" && string[index] <= "9"; index++);
        var number = string.slice(0, index);
        while (number.length < size) { number = char + number; }
        string = number + string.slice(index);
        return string;
    };
    me.title = function (string) {
        string = string.split("_").map(token => {
            return token.charAt(0).toUpperCase() + token.slice(1);
        }).join(" ");
        string = string.replace(/([a-z])([A-Z])/g, "$1 $2").trim();
        string = string.replace(/\s\s/g, " ");
        return string;
    };
    me.trimEnd = function (string, character) {
        var position = string.indexOf(character);
        if (position != -1) {
            string = string.substring(0, position);
        }
        return string;
    };
    me.formatDuration = function (duration, long = false, noSeconds = false) {
        duration = parseInt(duration);
        var sec = duration % 60;
        var min = parseInt(duration / 60) % 60;
        var hour = parseInt(duration / (60 * 60)) % 24;
        var days = parseInt(duration / (24 * 60 * 60));
        if (hour < 10 && !long) {
            hour = "0" + hour;
        }
        if (min < 10 && !long) {
            min = "0" + min;
        }
        if (sec < 10 && !long) {
            sec = "0" + sec;
        }
        var formattedString = "";
        if (days) {
            formattedString = days + " days" + " + ";
        }
        if (!long) {
            formattedString = hour + ":" + min;
            if (!noSeconds) {
                formattedString = + ":" + sec;
            }
        }
        else {
            if (hour) {
                formattedString += hour + " hours ";
            }
            if (min) {
                formattedString += min + " minutes ";
            }
            if (sec && !noSeconds) {
                formattedString += sec + " seconds";
            }
            if (!formattedString) {
                formattedString = "now";
            }
        }
        formattedString = formattedString.trim();
        return formattedString;
    };
    me.formatBytes = function (number) {
        var set = false;
        if (number < 1000) {
            number = parseInt(number) + " B";
            set = true;
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " KB";
                set = true;
            }
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " MB";
                set = true;
            }
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " GB";
                set = true;
            }
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " TB";
                set = true;
            }
        }
        return number;
    };
    me.charArray = function (first, last) {
        var a = [], i = first.charCodeAt(0), j = last.charCodeAt(0);
        for (; i <= j; ++i) {
            a.push(String.fromCharCode(i));
        }
        return a;
    };
    me.hash = function (string) {
        var i = string.length;
        var hash1 = 5381;
        var hash2 = 52711;
        let char = null;
        while (i--) {
            if (typeof Buffer === "function" && string instanceof Buffer) {
                char = string[i];
            }
            else {
                char = string.charCodeAt(i);
            }
            hash1 = (hash1 * 33) ^ char;
            hash2 = (hash2 * 33) ^ char;
        }

        var hash = (hash1 >>> 0) * 4096 + (hash2 >>> 0);
        hash = String(hash);
        return hash;
    };
    me.token = function (string, start, end) {
        let startIndex = string.indexOf(start);
        let endIndex = string.lastIndexOf(end);
        let prefix = "", token = "", suffix = "";
        if (startIndex === -1 || endIndex === -1) {
            prefix = string;
            token = "";
            suffix = "";
        }
        else {
            prefix = string.substring(0, startIndex);
            token = string.substring(startIndex, endIndex + 1);
            suffix = string.substring(endIndex + 1);
        }
        return [prefix, token, suffix];
    };
};<commit_msg>bug fix<commit_after>/*
 @author Zakai Hamilton
 @component CoreString
 */

screens.core.string = function CoreString(me, { core }) {
    me.delimiters = function () {
        var delimiters = [
            "\n", ";", ":", ".", ",", "—", "–", "-", "(", ")", "[", "]", "{", "}", "+", "<", ">", "?", "/", "\\", "”", "“", "!", "\"", "…", "'", "‘", "’", "\x09"
        ];
        return delimiters;
    };
    me.hasDelimiter = function (string) {
        var delimiters = me.delimiters();
        var result = false;
        for (var index = 0; index < delimiters.length - 1; index++) {
            var delimiter = delimiters[index];
            if (string.includes(delimiter)) {
                result = true;
                break;
            }
        }
        return result;
    };
    me.unparseWords = function (string) {
        var delimiters = me.delimiters();
        for (let index = 0; index < delimiters.length; index++) {
            let delimiter = delimiters[index];
            string = string.split(" " + delimiter + " ").join(delimiter);
        }
        return string;
    };
    me.parseWords = function (callback, string) {
        var delimiters = me.delimiters();
        for (let index = 0; index < delimiters.length; index++) {
            let delimiter = delimiters[index];
            string = string.split(delimiter).join(" " + delimiter + " ");
        }
        var words = string.split(" ");
        callback(words);
        string = words.join(" ");
        for (let index = 0; index < delimiters.length; index++) {
            let delimiter = delimiters[index];
            string = string.split(" " + delimiter + " ").join(delimiter);
        }
        return string;
    };
    me.nextWord = function (string) {
        var nextWord = "";
        core.string.parseWords(function (words) {
            if (words.length > 0) {
                nextWord = words[0];
            }
        }, string);
        return nextWord;
    };
    me.direction = function (string) {
        if (!string) {
            return "ltr";
        }
        var position = string.search(/[A-Za-z]/);
        if (position >= 0) {
            return "ltr";
        }
        return "rtl";
    };
    me.language = function (string) {
        if (!string) {
            return "english";
        }
        var position = string.search(/[A-Za-z]/);
        if (position >= 0) {
            return "english";
        }
        position = string.search(/[ֿ\u0590-\u05FF]/);
        if (position >= 0) {
            return "hebrew";
        }
        return "english";
    };
    me.regex = function (string, options = "g") {
        if (string.startsWith("/")) {
            string = string.slice(1);
            string = new RegExp(string, options);
        }
        return string;
    };
    me.escape = function (string) {
        return string.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
    };
    me.match = function (source, target, wordStyle) {
        if (wordStyle === "whole") {
            return source === target;
        } else if (wordStyle === "prefix") {
            return source.beginsWith(target);
        } else if (wordStyle === "suffix") {
            return source.endsWith(target);
        } else {
            return source.includes(target);
        }
    };
    me.middleLetters = function (source, target) {
        var index = source.toUpperCase().indexOf(target.toUpperCase());
        if (index !== -1) {
            return source.substring(index, index + target.length);
        }
        return "";
    };
    me.prefixLetters = function (source, target) {
        var index = source.toUpperCase().indexOf(target.toUpperCase());
        if (index !== -1 && index) {
            return source.substring(0, index);
        }
        return "";
    };
    me.suffixLetters = function (source, target) {
        var index = source.toUpperCase().indexOf(target.toUpperCase());
        if (index !== -1 && index + target.length < source.length) {
            return source.substring(index + target.length);
        }
        return "";
    };
    me.prefix = function (string, separator) {
        var prefix = string;
        if (string) {
            var tokens = string.split(separator);
            if (tokens && tokens.length > 1) {
                prefix = tokens[0];
            }
        }
        return prefix;
    };
    me.suffix = function (string, separator) {
        var suffix = "";
        if (string) {
            var tokens = string.split(separator);
            if (tokens && tokens.length > 1) {
                suffix = tokens[1];
            }
        }
        return suffix;
    };
    me.encode = function (string) {
        if (me.platform === "server" || me.platform === "service") {
            return Buffer.from((unescape(encodeURIComponent(string))), "binary").toString("base64");
        }
        else {
            return window.btoa(unescape(encodeURIComponent(string)));
        }
    };
    me.decode = function (string) {
        if (me.platform === "server" || me.platform === "service") {
            return decodeURIComponent(escape(Buffer.from(string, "base64").toString("binary")));
        }
        else {
            return decodeURIComponent(escape(window.atob(string)));
        }
    };
    me.blobToString = function (blob) {
        var url, request;
        url = URL.createObjectURL(blob);
        request = new XMLHttpRequest();
        request.open("GET", url, false);
        request.send();
        URL.revokeObjectURL(url);
        return request.responseText;
    };
    me.caselessCompare = function (source, target) {
        if ((source && !target) || (!source && target)) {
            return false;
        }
        if (!source && !target) {
            return true;
        }
        return source.toLowerCase() === target.toLowerCase();
    };
    me.optional = function (string, check) {
        var result = "";
        if (check) {
            result = string;
        }
        return result;
    };
    me.split = function (string, delimiter = " ", quote = "\"") {
        if (string) {
            return [].concat.apply([], string.split(quote).map(function (v, i) {
                return i % 2 ? v : v.split(delimiter);
            })).filter(Boolean);
        }
        else {
            return [];
        }
    };
    me.fill = function (string, params, prefix = "") {
        for (var param in params) {
            string = string.split(prefix + param).join(params[param]);
        }
        return string;
    };
    me.padNumber = function (string, size, char = " ") {
        string = String(string);
        var index = 0;
        for (; string[index] >= "0" && string[index] <= "9"; index++);
        var number = string.slice(0, index);
        while (number.length < size) { number = char + number; }
        string = number + string.slice(index);
        return string;
    };
    me.title = function (string) {
        string = string.split("_").map(token => {
            return token.charAt(0).toUpperCase() + token.slice(1);
        }).join(" ");
        string = string.replace(/([a-z])([A-Z])/g, "$1 $2").trim();
        string = string.replace(/\s\s/g, " ");
        return string;
    };
    me.trimEnd = function (string, character) {
        var position = string.indexOf(character);
        if (position != -1) {
            string = string.substring(0, position);
        }
        return string;
    };
    me.formatDuration = function (duration, long = false, noSeconds = false) {
        duration = parseInt(duration);
        var sec = duration % 60;
        var min = parseInt(duration / 60) % 60;
        var hour = parseInt(duration / (60 * 60)) % 24;
        var days = parseInt(duration / (24 * 60 * 60));
        if (hour < 10 && !long) {
            hour = "0" + hour;
        }
        if (min < 10 && !long) {
            min = "0" + min;
        }
        if (sec < 10 && !long) {
            sec = "0" + sec;
        }
        var formattedString = "";
        if (days) {
            formattedString = days + " days" + " + ";
        }
        if (!long) {
            formattedString = hour + ":" + min;
            if (!noSeconds) {
                formattedString += ":" + sec;
            }
        }
        else {
            if (hour) {
                formattedString += hour + " hours ";
            }
            if (min) {
                formattedString += min + " minutes ";
            }
            if (sec && !noSeconds) {
                formattedString += sec + " seconds";
            }
            if (!formattedString) {
                formattedString = "now";
            }
        }
        formattedString = formattedString.trim();
        return formattedString;
    };
    me.formatBytes = function (number) {
        var set = false;
        if (number < 1000) {
            number = parseInt(number) + " B";
            set = true;
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " KB";
                set = true;
            }
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " MB";
                set = true;
            }
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " GB";
                set = true;
            }
        }
        if (!set) {
            number /= 1000;
            if (number < 1000) {
                number = parseInt(number) + " TB";
                set = true;
            }
        }
        return number;
    };
    me.charArray = function (first, last) {
        var a = [], i = first.charCodeAt(0), j = last.charCodeAt(0);
        for (; i <= j; ++i) {
            a.push(String.fromCharCode(i));
        }
        return a;
    };
    me.hash = function (string) {
        var i = string.length;
        var hash1 = 5381;
        var hash2 = 52711;
        let char = null;
        while (i--) {
            if (typeof Buffer === "function" && string instanceof Buffer) {
                char = string[i];
            }
            else {
                char = string.charCodeAt(i);
            }
            hash1 = (hash1 * 33) ^ char;
            hash2 = (hash2 * 33) ^ char;
        }

        var hash = (hash1 >>> 0) * 4096 + (hash2 >>> 0);
        hash = String(hash);
        return hash;
    };
    me.token = function (string, start, end) {
        let startIndex = string.indexOf(start);
        let endIndex = string.lastIndexOf(end);
        let prefix = "", token = "", suffix = "";
        if (startIndex === -1 || endIndex === -1) {
            prefix = string;
            token = "";
            suffix = "";
        }
        else {
            prefix = string.substring(0, startIndex);
            token = string.substring(startIndex, endIndex + 1);
            suffix = string.substring(endIndex + 1);
        }
        return [prefix, token, suffix];
    };
};<|endoftext|>


<commit_before>
// Javascript for the NGI Stockholm Internal Dashboard

setTimeout(function(){ location.reload(); }, 300000); // 300 seconds - 5 minutes

$(function () {

    try {

        Highcharts.setOptions({
            chart: {
                style: {
                    fontFamily:'"Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif'
                }
            }
        });

        // Header clock
        updateClock();

        // Collect data into shorter variable names
        tat = data['turnaround_times']
        tat_l = data['limits']['turnaround_times'];
        p_opened = data['projects']['opened_n_weeks_ago']
        p_closed = data['projects']['closed_n_weeks_ago']
        oc_labels = data['projects']['labels']
        pl = data['process_load']
        pl_l = data['limits']['process_load']
        suc = data['success_rate']

        // Top row
        make_tat_plot('#finished_proj_tat', tat_l['finished_library_project'], tat['finished_library_project'],  'Finished Lib
'+Math.round(tat['finished_library_project'])+' days');
        make_tat_plot('#lp_proj_tats',      tat_l['library_prep_project'], tat['library_prep_project'],      'Prep Projects
'+Math.round(tat['library_prep_project'])+' days');
        make_tat_plot('#rc_tat',            tat_l['initial_qc'],     tat['initial_qc'],     Math.round(tat['initial_qc'])+' days');
        make_tat_plot('#lp_tat',            tat_l['library_prep'],   tat['library_prep'],   Math.round(tat['library_prep'])+' days');
        make_tat_plot('#seq_tat',           tat_l['sequencing'],     tat['sequencing'],     Math.round(tat['sequencing'])+' days');
        make_tat_plot('#bioinfo_tat',       tat_l['bioinformatics'], tat['bioinformatics'], Math.round(tat['bioinformatics'])+' days');

        // Middle row, projects openend / closed
        try {
            make_proj_open_close_plot(
                '#proj_openclose',
                [ p_opened['3'], p_opened['2'], p_opened['1'], p_opened['0'] ],
                [ p_closed['3']*-1, p_closed['2']*-1, p_closed['1']*-1, p_closed['0']*-1 ],
                // [ oc_labels['3'], oc_labels['2'], oc_labels['1'], oc_labels['0'] ]
                [ '3 weeks ago', '2 weeks ago', '1 week ago', 'this week' ]
            );
        } catch(err) {
            $('#proj_openclose').addClass('coming_soon').text('coming soon');
        }
        try {
            $('#projects-open-production').text(data['projects']['in_production']);
            $('#projects-open-applications').text(data['projects']['in_applications']);
        } catch(err) {
            console.log('Could not get number of opened and closed projects.')
        }

        // Middle Row - Queue plots
        // Max - 5 * pulse
        make_queue_plot('#lp_queue',      pl_l['library_prep'],   pl['library_prep_queue'],   pl['library_prep_queue']+' samples in queue');
        make_queue_plot('#seq_queue',     pl_l['sequencing'],     pl['sequencing_queue'],     pl['sequencing_queue']+' lanes in queue');
        make_queue_plot('#bioinfo_queue', pl_l['bioinformatics'], pl['bioinformatics_queue'], pl['bioinformatics_queue']+' lanes in queue');

        // Middle Row - Balance plots
        make_balance_plot('#rc_finished_balance', pl_l['initial_qc_lanes'],   pl['initial_qc_lanes'],   undefined, pl['initial_qc_lanes']+' lanes in progress');
        make_balance_plot('#rc_balance',          pl_l['initial_qc_samples'], pl['initial_qc_samples'], undefined, pl['initial_qc_samples']+' samples in progress');
        make_balance_plot('#lp_balance',          pl_l['library_prep'],       pl['library_prep'],       undefined, pl['library_prep']+' samples in progress');
        make_balance_plot('#seq_balance',         pl_l['sequencing'],         pl['sequencing'],         undefined, pl['sequencing']+' lanes in progress');
        make_balance_plot('#bioinfo_balance',     pl_l['bioinformatics'],     pl['bioinformatics'],     undefined, pl['bioinformatics']+' lanes in progress');

        // Bottom row
        make_success_plot('#rc_success', suc['initial_qc']*100);
        make_success_plot('#lp_success', suc['library_prep']*100);
        make_success_plot('#seq_success', suc['sequencing']*100);
        make_success_plot('#bioinfo_success', suc['bioinformatics']*100);

    } catch(err){
        $('.main-page').html('

Error loading dashboard data

'+err+'
');
        console.log(err);
    }
});

// Make a speedometer plot to show turnaround times
function make_tat_plot(target, aim, now, title){
    try {
        var overTop = false;
        if(target === undefined){ throw 'Target missing'; }
        if(aim === undefined){ throw 'aim missing'; }
        if(now === undefined){ throw 'now missing'; }
        if(now > aim * 2.5){
            now = aim * 2.6;
            overTop = true;
        }
        $(target).highcharts({
            chart: {
                type: 'gauge',
                height: 120,
                backgroundColor:'rgba(255, 255, 255, 0.1)'
            },
            title: {
                text: title,
                floating: true,
                y: 60
            },
            pane: {
                startAngle: -45,
                endAngle: 45,
                background: null,
                center: ['50%', '170%'],
                size: 270
            },
            tooltip: { enabled: false },
            credits: { enabled: false },
            yAxis: {
                min: 0,
                max: aim * 2.5,
                minorTickWidth: 0,
                tickPosition: 'outside',
                tickPositions: [0, aim],
                labels: {
                    rotation: 'auto',
                    distance: 20
                },
                plotBands: [{
                    from: 0,
                    to: aim,
                    color: '#55BF3B',
                    innerRadius: '100%',
                    outerRadius: '105%'
                },
                {
                    from: aim,
                    to: aim * 2,
                    color: '#DDDF0D',
                    innerRadius: '100%',
                    outerRadius: '105%'
                },
                {
                    from: aim * 2,
                    to: aim * 3,
                    color: '#DF5353',
                    innerRadius: '100%',
                    outerRadius: '105%'
                }]
            },
            plotOptions: {
                gauge: {
                    dataLabels: { enabled: false },
                    dial: { radius: '100%' }
                }
            },
            series: [{
                name: 'Turn Around Time',
                data: [now],
            }]
        },
        // Move needle if over limit
        function (chart) {
            if(overTop){
                var mul = 2.6
                setInterval(function () {
                    if(mul == 2.6){ mul = 2.52; }
                    else { mul = 2.6; }
                    chart.series[0].points[0].update(aim * mul, false);
                    chart.redraw();
                }, 200);
            }
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

function make_queue_plot(target, aim, now, subtext){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(aim === undefined){ throw 'aim missing'; }
        if(now === undefined){ throw 'now missing'; }
        var max = aim * 5;
        $(target).highcharts({
            chart: {
                type: 'bar',
                height: 95,
                spacingBottom: 10,
                spacingTop: 0,
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                plotBackgroundColor:'#f2f2f2',
            },
            xAxis: {
                categories: ['Queue'],
                title: { text: null },
                labels: { enabled: false },
                tickWidth: 0
            },
            yAxis: [{
                min: 0,
                max: max,
                tickInterval: aim,
                title: { text: null },
                opposite: true,
                labels: {
                    y: -3,
                    overflow: 'justify'
                }
            },{
                title: {
                    text: subtext,
                    y: 5,
                    style: { 'font-size': 14 }
                }
            }],
            title: { text: null },
            plotOptions: {
                series: {
                    pointPadding: 0,
                    groupPadding: 0,
                    color: '#7cb5ec',
                    states: { hover: { enabled: false } }
                },
            },
            legend: { enabled: false },
            credits: { enabled: false },
            tooltip: { enabled: false },
            series: [{
                name: 'Queue',
                data: [now]
            }]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

// Function to make the load balancing plots
function make_balance_plot(target, aim, now, prev, subtext){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(aim === undefined){ throw 'aim missing'; }
        if(now === undefined){ throw 'now missing'; }
        $(target).highcharts({
            chart: {
                type: 'bar',
                height: 95,
                spacingBottom: 10,
                spacingTop: 0,
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                plotBackgroundColor:'#ed8c83',
            },
            xAxis: {
                categories: ['Queue'],
                title: { text: null },
                labels: { enabled: false },
                tickWidth: 0
            },
            yAxis: [{
                min: 0,
                max: aim * 5,
                title: { text: null },
                opposite: true,
                labels: {
                    y: -3,
                },
                tickPositions: [ 0, aim, aim * 4, aim * 5 ],
                plotBands: [{
                    color: '#8ad88b',
                    from: aim,
                    to: aim * 4
                }],
                plotLines: [{
                    color: '#000',
                    width: 2,
                    value: now,
                    zIndex: 1000
                }]
            },{
                min: 0,
                max: aim * 5,
                title: {
                    text: subtext,
                    y: 5,
                    style: { 'font-size': 14 }
                },
                labels: { enabled: false },
                gridLineWidth: 0,
                plotLines: [{
                    color: '#999',
                    width: 1,
                    value: prev,
                    zIndex: 1000
                }]
            }],
            title: { text: null },
            legend: { enabled: false },
            credits: { enabled: false },
            series: [
                { data: [0] },
                { data: [0], yAxis: 1 }
            ]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

function make_proj_open_close_plot(target, opened, closed, categories){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(opened === undefined){ throw 'opened missing'; }
        if(closed === undefined){ throw 'closed missing'; }
        if(categories === undefined){ throw 'categories missing'; }
        $(target).highcharts({
            chart: {
                type: 'column',
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                height: 240,
                spacingBottom: 0,
            },
            title: { text: null },
            credits: { enabled: false },
            tooltip: { enabled: false },
            xAxis: [{
                categories: categories,
                reversed: false,
                labels: {
                    step: 1,
                    rotation: -45,
                }
            }],
            yAxis: {
                title: {
                    text: '#Projects'
                },
                allowDecimals: false,
                // minorTickInterval: 1
            },
            plotOptions: {
                series: {
                    stacking: 'normal',
                    states: { hover: { enabled: false } }
                }
            },
            legend: {
                reversed: true,
                floating: true,
                layout: 'horizontal',
                align: 'right',
                verticalAlign: 'top',
                labelFormat: '{name}',
                useHTML: true
            },
            series: [{
                name: 'Closed',
                data: closed
            }, {
                name: 'Opened',
                data: opened
            }]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

// Make an arc plot to show percentage success
function make_success_plot(target, now){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(isNaN(now)){ throw 'now missing'; }
        $(target).highcharts({
            chart: {
                type: 'solidgauge',
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                height: 140
            },
            title: null,
            pane: {
                startAngle: -90,
                endAngle: 90,
                background: {
                    backgroundColor: '#EEE',
                    innerRadius: '60%',
                    outerRadius: '100%',
                    shape: 'arc'
                },
                center: ['50%', '88%'],
                size: 200
            },
            tooltip: { enabled: false },
            credits: { enabled: false },

            // the value axis
            yAxis: {
                stops: [
                    [0.1, '#DF5353'], // green
                    [0.5, '#DDDF0D'], // yellow
                    [0.9, '#55BF3B'] // red
                ],
                lineWidth: 0,
                minorTickInterval: null,
                tickPixelInterval: 400,
                tickWidth: 0,
                labels: {
                    enabled: false
                },
                min: 0,
                max: 100
            },
            plotOptions: {
                solidgauge: {
                    dataLabels: {
                        y: -40,
                        borderWidth: 0,
                        useHTML: true
                    }
                }
            },
            series: [{
                name: 'Success Rate',
                data: [now],
                dataLabels: { format: '
{y}%
' },
            }]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

function updateClock(){
    var now = moment(),
        second = now.seconds() * 6,
        minute = now.minutes() * 6 + second / 60,
        hour = ((now.hours() % 12) / 12) * 360 + 90 + minute / 12;

    $('#hour').css("transform", "rotate(" + hour + "deg)");
    $('#minute').css("transform", "rotate(" + minute + "deg)");
    $('#second').css("transform", "rotate(" + second + "deg)");
    $('#clock_time').text( moment().format('HH:mm') );
    $('#clock_date').text( moment().format('dddd Do MMMM') );
    setTimeout(updateClock, 1000);
}<commit_msg>Fixed number precision in success plot. Fixes #25.<commit_after>
// Javascript for the NGI Stockholm Internal Dashboard

setTimeout(function(){ location.reload(); }, 300000); // 300 seconds - 5 minutes

$(function () {

    try {

        Highcharts.setOptions({
            chart: {
                style: {
                    fontFamily:'"Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif'
                }
            }
        });

        // Header clock
        updateClock();

        // Collect data into shorter variable names
        tat = data['turnaround_times']
        tat_l = data['limits']['turnaround_times'];
        p_opened = data['projects']['opened_n_weeks_ago']
        p_closed = data['projects']['closed_n_weeks_ago']
        oc_labels = data['projects']['labels']
        pl = data['process_load']
        pl_l = data['limits']['process_load']
        suc = data['success_rate']

        // Top row
        make_tat_plot('#finished_proj_tat', tat_l['finished_library_project'], tat['finished_library_project'],  'Finished Lib
'+Math.round(tat['finished_library_project'])+' days');
        make_tat_plot('#lp_proj_tats',      tat_l['library_prep_project'], tat['library_prep_project'],      'Prep Projects
'+Math.round(tat['library_prep_project'])+' days');
        make_tat_plot('#rc_tat',            tat_l['initial_qc'],     tat['initial_qc'],     Math.round(tat['initial_qc'])+' days');
        make_tat_plot('#lp_tat',            tat_l['library_prep'],   tat['library_prep'],   Math.round(tat['library_prep'])+' days');
        make_tat_plot('#seq_tat',           tat_l['sequencing'],     tat['sequencing'],     Math.round(tat['sequencing'])+' days');
        make_tat_plot('#bioinfo_tat',       tat_l['bioinformatics'], tat['bioinformatics'], Math.round(tat['bioinformatics'])+' days');

        // Middle row, projects openend / closed
        try {
            make_proj_open_close_plot(
                '#proj_openclose',
                [ p_opened['3'], p_opened['2'], p_opened['1'], p_opened['0'] ],
                [ p_closed['3']*-1, p_closed['2']*-1, p_closed['1']*-1, p_closed['0']*-1 ],
                // [ oc_labels['3'], oc_labels['2'], oc_labels['1'], oc_labels['0'] ]
                [ '3 weeks ago', '2 weeks ago', '1 week ago', 'this week' ]
            );
        } catch(err) {
            $('#proj_openclose').addClass('coming_soon').text('coming soon');
        }
        try {
            $('#projects-open-production').text(data['projects']['in_production']);
            $('#projects-open-applications').text(data['projects']['in_applications']);
        } catch(err) {
            console.log('Could not get number of opened and closed projects.')
        }

        // Middle Row - Queue plots
        // Max - 5 * pulse
        make_queue_plot('#lp_queue',      pl_l['library_prep'],   pl['library_prep_queue'],   pl['library_prep_queue']+' samples in queue');
        make_queue_plot('#seq_queue',     pl_l['sequencing'],     pl['sequencing_queue'],     pl['sequencing_queue']+' lanes in queue');
        make_queue_plot('#bioinfo_queue', pl_l['bioinformatics'], pl['bioinformatics_queue'], pl['bioinformatics_queue']+' lanes in queue');

        // Middle Row - Balance plots
        make_balance_plot('#rc_finished_balance', pl_l['initial_qc_lanes'],   pl['initial_qc_lanes'],   undefined, pl['initial_qc_lanes']+' lanes in progress');
        make_balance_plot('#rc_balance',          pl_l['initial_qc_samples'], pl['initial_qc_samples'], undefined, pl['initial_qc_samples']+' samples in progress');
        make_balance_plot('#lp_balance',          pl_l['library_prep'],       pl['library_prep'],       undefined, pl['library_prep']+' samples in progress');
        make_balance_plot('#seq_balance',         pl_l['sequencing'],         pl['sequencing'],         undefined, pl['sequencing']+' lanes in progress');
        make_balance_plot('#bioinfo_balance',     pl_l['bioinformatics'],     pl['bioinformatics'],     undefined, pl['bioinformatics']+' lanes in progress');

        // Bottom row
        make_success_plot('#rc_success', suc['initial_qc']*100);
        make_success_plot('#lp_success', suc['library_prep']*100);
        make_success_plot('#seq_success', suc['sequencing']*100);
        make_success_plot('#bioinfo_success', suc['bioinformatics']*100);

    } catch(err){
        $('.main-page').html('

Error loading dashboard data

'+err+'
');
        console.log(err);
    }
});

// Make a speedometer plot to show turnaround times
function make_tat_plot(target, aim, now, title){
    try {
        var overTop = false;
        if(target === undefined){ throw 'Target missing'; }
        if(aim === undefined){ throw 'aim missing'; }
        if(now === undefined){ throw 'now missing'; }
        if(now > aim * 2.5){
            now = aim * 2.6;
            overTop = true;
        }
        $(target).highcharts({
            chart: {
                type: 'gauge',
                height: 120,
                backgroundColor:'rgba(255, 255, 255, 0.1)'
            },
            title: {
                text: title,
                floating: true,
                y: 60
            },
            pane: {
                startAngle: -45,
                endAngle: 45,
                background: null,
                center: ['50%', '170%'],
                size: 270
            },
            tooltip: { enabled: false },
            credits: { enabled: false },
            yAxis: {
                min: 0,
                max: aim * 2.5,
                minorTickWidth: 0,
                tickPosition: 'outside',
                tickPositions: [0, aim],
                labels: {
                    rotation: 'auto',
                    distance: 20
                },
                plotBands: [{
                    from: 0,
                    to: aim,
                    color: '#55BF3B',
                    innerRadius: '100%',
                    outerRadius: '105%'
                },
                {
                    from: aim,
                    to: aim * 2,
                    color: '#DDDF0D',
                    innerRadius: '100%',
                    outerRadius: '105%'
                },
                {
                    from: aim * 2,
                    to: aim * 3,
                    color: '#DF5353',
                    innerRadius: '100%',
                    outerRadius: '105%'
                }]
            },
            plotOptions: {
                gauge: {
                    dataLabels: { enabled: false },
                    dial: { radius: '100%' }
                }
            },
            series: [{
                name: 'Turn Around Time',
                data: [now],
            }]
        },
        // Move needle if over limit
        function (chart) {
            if(overTop){
                var mul = 2.6
                setInterval(function () {
                    if(mul == 2.6){ mul = 2.52; }
                    else { mul = 2.6; }
                    chart.series[0].points[0].update(aim * mul, false);
                    chart.redraw();
                }, 200);
            }
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

function make_queue_plot(target, aim, now, subtext){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(aim === undefined){ throw 'aim missing'; }
        if(now === undefined){ throw 'now missing'; }
        var max = aim * 5;
        $(target).highcharts({
            chart: {
                type: 'bar',
                height: 95,
                spacingBottom: 10,
                spacingTop: 0,
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                plotBackgroundColor:'#f2f2f2',
            },
            xAxis: {
                categories: ['Queue'],
                title: { text: null },
                labels: { enabled: false },
                tickWidth: 0
            },
            yAxis: [{
                min: 0,
                max: max,
                tickInterval: aim,
                title: { text: null },
                opposite: true,
                labels: {
                    y: -3,
                    overflow: 'justify'
                }
            },{
                title: {
                    text: subtext,
                    y: 5,
                    style: { 'font-size': 14 }
                }
            }],
            title: { text: null },
            plotOptions: {
                series: {
                    pointPadding: 0,
                    groupPadding: 0,
                    color: '#7cb5ec',
                    states: { hover: { enabled: false } }
                },
            },
            legend: { enabled: false },
            credits: { enabled: false },
            tooltip: { enabled: false },
            series: [{
                name: 'Queue',
                data: [now]
            }]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

// Function to make the load balancing plots
function make_balance_plot(target, aim, now, prev, subtext){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(aim === undefined){ throw 'aim missing'; }
        if(now === undefined){ throw 'now missing'; }
        $(target).highcharts({
            chart: {
                type: 'bar',
                height: 95,
                spacingBottom: 10,
                spacingTop: 0,
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                plotBackgroundColor:'#ed8c83',
            },
            xAxis: {
                categories: ['Queue'],
                title: { text: null },
                labels: { enabled: false },
                tickWidth: 0
            },
            yAxis: [{
                min: 0,
                max: aim * 5,
                title: { text: null },
                opposite: true,
                labels: {
                    y: -3,
                },
                tickPositions: [ 0, aim, aim * 4, aim * 5 ],
                plotBands: [{
                    color: '#8ad88b',
                    from: aim,
                    to: aim * 4
                }],
                plotLines: [{
                    color: '#000',
                    width: 2,
                    value: now,
                    zIndex: 1000
                }]
            },{
                min: 0,
                max: aim * 5,
                title: {
                    text: subtext,
                    y: 5,
                    style: { 'font-size': 14 }
                },
                labels: { enabled: false },
                gridLineWidth: 0,
                plotLines: [{
                    color: '#999',
                    width: 1,
                    value: prev,
                    zIndex: 1000
                }]
            }],
            title: { text: null },
            legend: { enabled: false },
            credits: { enabled: false },
            series: [
                { data: [0] },
                { data: [0], yAxis: 1 }
            ]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

function make_proj_open_close_plot(target, opened, closed, categories){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(opened === undefined){ throw 'opened missing'; }
        if(closed === undefined){ throw 'closed missing'; }
        if(categories === undefined){ throw 'categories missing'; }
        $(target).highcharts({
            chart: {
                type: 'column',
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                height: 240,
                spacingBottom: 0,
            },
            title: { text: null },
            credits: { enabled: false },
            tooltip: { enabled: false },
            xAxis: [{
                categories: categories,
                reversed: false,
                labels: {
                    step: 1,
                    rotation: -45,
                }
            }],
            yAxis: {
                title: {
                    text: '#Projects'
                },
                allowDecimals: false,
                // minorTickInterval: 1
            },
            plotOptions: {
                series: {
                    stacking: 'normal',
                    states: { hover: { enabled: false } }
                }
            },
            legend: {
                reversed: true,
                floating: true,
                layout: 'horizontal',
                align: 'right',
                verticalAlign: 'top',
                labelFormat: '{name}',
                useHTML: true
            },
            series: [{
                name: 'Closed',
                data: closed
            }, {
                name: 'Opened',
                data: opened
            }]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

// Make an arc plot to show percentage success
function make_success_plot(target, now){
    try {
        if(target === undefined){ throw 'Target missing'; }
        if(isNaN(now)){ throw 'now missing'; }
        $(target).highcharts({
            chart: {
                type: 'solidgauge',
                backgroundColor:'rgba(255, 255, 255, 0.1)',
                height: 140
            },
            title: null,
            pane: {
                startAngle: -90,
                endAngle: 90,
                background: {
                    backgroundColor: '#EEE',
                    innerRadius: '60%',
                    outerRadius: '100%',
                    shape: 'arc'
                },
                center: ['50%', '88%'],
                size: 200
            },
            tooltip: { enabled: false },
            credits: { enabled: false },

            // the value axis
            yAxis: {
                stops: [
                    [0.1, '#DF5353'], // green
                    [0.5, '#DDDF0D'], // yellow
                    [0.9, '#55BF3B'] // red
                ],
                lineWidth: 0,
                minorTickInterval: null,
                tickPixelInterval: 400,
                tickWidth: 0,
                labels: {
                    enabled: false
                },
                min: 0,
                max: 100
            },
            plotOptions: {
                solidgauge: {
                    dataLabels: {
                        y: -40,
                        borderWidth: 0,
                        useHTML: true
                    }
                }
            },
            series: [{
                name: 'Success Rate',
                data: [now],
                dataLabels: { format: '
{y:,.0f}%
' },
            }]
        });
    } catch(err) {
        $(target).addClass('coming_soon').text('coming soon');
    }
}

function updateClock(){
    var now = moment(),
        second = now.seconds() * 6,
        minute = now.minutes() * 6 + second / 60,
        hour = ((now.hours() % 12) / 12) * 360 + 90 + minute / 12;

    $('#hour').css("transform", "rotate(" + hour + "deg)");
    $('#minute').css("transform", "rotate(" + minute + "deg)");
    $('#second').css("transform", "rotate(" + second + "deg)");
    $('#clock_time').text( moment().format('HH:mm') );
    $('#clock_date').text( moment().format('dddd Do MMMM') );
    setTimeout(updateClock, 1000);
}<|endoftext|>


<commit_before>var React = require('react-native');
var { StyleSheet, requireNativeComponent, PropTypes, NativeModules, DeviceEventEmitter } = React;
var merge = require('merge');

var CAMERA_REF = 'camera';

var constants = {
  Aspect: NativeModules.CameraManager.Aspect,
  BarCodeType: NativeModules.CameraManager.BarCodeType,
  Type: NativeModules.CameraManager.Type,
  CaptureMode: NativeModules.CameraManager.CaptureMode,
  CaptureTarget: NativeModules.CameraManager.CaptureTarget,
  Orientation: NativeModules.CameraManager.Orientation,
  FlashMode: NativeModules.CameraManager.FlashMode,
  TorchMode: NativeModules.CameraManager.TorchMode,
};

var Camera = React.createClass({
  propTypes: {
    aspect: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    captureAudio: PropTypes.bool,
    captureMode: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    captureTarget: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    type: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    orientation: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    flashMode: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    torchMode: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ])
  },

  setNativeProps(props) {
    this.refs[CAMERA_REF].setNativeProps(props);
  },

  getDefaultProps() {
    return {
      aspect: constants.Aspect.fill,
      type: constants.Type.back,
      orientation: constants.Orientation.auto,
      captureAudio: true,
      captureMode: constants.CaptureMode.still,
      captureTarget: constants.CaptureTarget.cameraRoll,
      flashMode: constants.FlashMode.off,
      torchMode: constants.TorchMode.off
    };
  },

  getInitialState() {
    return {
      isAuthorized: false,
      isRecording: false
    };
  },

  componentWillMount() {
    NativeModules.CameraManager.checkDeviceAuthorizationStatus((function(err, isAuthorized) {
      this.state.isAuthorized = isAuthorized;
      this.setState(this.state);
    }).bind(this));
    this.cameraBarCodeReadListener = DeviceEventEmitter.addListener('CameraBarCodeRead', this._onBarCodeRead);
  },

  componentWillUnmount() {
    this.cameraBarCodeReadListener.remove();

    if (this.state.isRecording) {
      this.stopRecording();
    }
  },

  render() {
    var style = [styles.base, this.props.style];

    var aspect = this.props.aspect,
        type = this.props.type,
        orientation = this.props.orientation,
        flashMode = this.props.flashMode,
        torchMode = this.props.torchMode;

    var legacyProps = {
      aspect: {
        Fill: 'fill',
        Fit: 'fit',
        Stretch: 'stretch'
      },
      orientation: {
        LandscapeLeft: 'landscapeLeft',
        LandscapeRight: 'landscapeRight',
        Portrait: 'portrait',
        PortraitUpsideDown: 'portraitUpsideDown'
      },
      type: {
        Front: 'front',
        Back: 'back'
      }
    };

    if (typeof aspect === 'string') {
      aspect = constants.Aspect[aspect];
    }

    if (typeof flashMode === 'string') {
      flashMode = constants.FlashMode[flashMode];
    }

    if (typeof orientation === 'string') {
      orientation = constants.Orientation[orientation];
    }

    if (typeof torchMode === 'string') {
      torchMode = constants.TorchMode[torchMode];
    }

    if (typeof type === 'string') {
      type = constants.Type[type];
    }

    var nativeProps = merge(this.props, {
      style,
      aspect: aspect,
      type: type,
      orientation: orientation,
      flashMode: flashMode,
      torchMode: torchMode
    });

    return <RCTCamera ref={CAMERA_REF} {... nativeProps} />;
  },

  _onBarCodeRead(e) {
    this.props.onBarCodeRead && this.props.onBarCodeRead(e);
  },

  capture(options, cb) {

    if (arguments.length == 1) {
      cb = options;
      options = {};
    }

    options = Object.assign({}, {
      audio: this.props.captureAudio,
      mode: this.props.captureMode,
      target: this.props.captureTarget
    }, options);

    if (typeof options.mode === 'string') {
      options.mode = constants.CaptureMode[options.mode];
    }

    if (options.mode === constants.CaptureMode.video) {
      options.totalSeconds = (options.totalSeconds > -1 ? options.totalSeconds : -1);
      options.preferredTimeScale = options.preferredTimeScale || 30;
      this.setState({ isRecording: true });
    }

    if (typeof options.target === 'string') {
      options.target = constants.CaptureTarget[options.target];
    }

    NativeModules.CameraManager.capture(options, cb);
  },

  stopCapture() {
    if (this.state.isRecording) {
      NativeModules.CameraManager.stopCapture();
      this.setState({ isRecording: false });
    }
  }

});

var RCTCamera = requireNativeComponent('RCTCamera', Camera);

var styles = StyleSheet.create({
  base: { },
});

Camera.constants = constants;
module.exports = Camera;
<commit_msg>(fix) stopRecording method is not defined, switched to stopCapture to fix.<commit_after>var React = require('react-native');
var { StyleSheet, requireNativeComponent, PropTypes, NativeModules, DeviceEventEmitter } = React;
var merge = require('merge');

var CAMERA_REF = 'camera';

var constants = {
  Aspect: NativeModules.CameraManager.Aspect,
  BarCodeType: NativeModules.CameraManager.BarCodeType,
  Type: NativeModules.CameraManager.Type,
  CaptureMode: NativeModules.CameraManager.CaptureMode,
  CaptureTarget: NativeModules.CameraManager.CaptureTarget,
  Orientation: NativeModules.CameraManager.Orientation,
  FlashMode: NativeModules.CameraManager.FlashMode,
  TorchMode: NativeModules.CameraManager.TorchMode,
};

var Camera = React.createClass({
  propTypes: {
    aspect: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    captureAudio: PropTypes.bool,
    captureMode: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    captureTarget: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    type: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    orientation: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    flashMode: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ]),
    torchMode: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.number
    ])
  },

  setNativeProps(props) {
    this.refs[CAMERA_REF].setNativeProps(props);
  },

  getDefaultProps() {
    return {
      aspect: constants.Aspect.fill,
      type: constants.Type.back,
      orientation: constants.Orientation.auto,
      captureAudio: true,
      captureMode: constants.CaptureMode.still,
      captureTarget: constants.CaptureTarget.cameraRoll,
      flashMode: constants.FlashMode.off,
      torchMode: constants.TorchMode.off
    };
  },

  getInitialState() {
    return {
      isAuthorized: false,
      isRecording: false
    };
  },

  componentWillMount() {
    NativeModules.CameraManager.checkDeviceAuthorizationStatus((function(err, isAuthorized) {
      this.state.isAuthorized = isAuthorized;
      this.setState(this.state);
    }).bind(this));
    this.cameraBarCodeReadListener = DeviceEventEmitter.addListener('CameraBarCodeRead', this._onBarCodeRead);
  },

  componentWillUnmount() {
    this.cameraBarCodeReadListener.remove();

    if (this.state.isRecording) {
      this.stopCapture();
    }
  },

  render() {
    var style = [styles.base, this.props.style];

    var aspect = this.props.aspect,
        type = this.props.type,
        orientation = this.props.orientation,
        flashMode = this.props.flashMode,
        torchMode = this.props.torchMode;

    var legacyProps = {
      aspect: {
        Fill: 'fill',
        Fit: 'fit',
        Stretch: 'stretch'
      },
      orientation: {
        LandscapeLeft: 'landscapeLeft',
        LandscapeRight: 'landscapeRight',
        Portrait: 'portrait',
        PortraitUpsideDown: 'portraitUpsideDown'
      },
      type: {
        Front: 'front',
        Back: 'back'
      }
    };

    if (typeof aspect === 'string') {
      aspect = constants.Aspect[aspect];
    }

    if (typeof flashMode === 'string') {
      flashMode = constants.FlashMode[flashMode];
    }

    if (typeof orientation === 'string') {
      orientation = constants.Orientation[orientation];
    }

    if (typeof torchMode === 'string') {
      torchMode = constants.TorchMode[torchMode];
    }

    if (typeof type === 'string') {
      type = constants.Type[type];
    }

    var nativeProps = merge(this.props, {
      style,
      aspect: aspect,
      type: type,
      orientation: orientation,
      flashMode: flashMode,
      torchMode: torchMode
    });

    return <RCTCamera ref={CAMERA_REF} {... nativeProps} />;
  },

  _onBarCodeRead(e) {
    this.props.onBarCodeRead && this.props.onBarCodeRead(e);
  },

  capture(options, cb) {

    if (arguments.length == 1) {
      cb = options;
      options = {};
    }

    options = Object.assign({}, {
      audio: this.props.captureAudio,
      mode: this.props.captureMode,
      target: this.props.captureTarget
    }, options);

    if (typeof options.mode === 'string') {
      options.mode = constants.CaptureMode[options.mode];
    }

    if (options.mode === constants.CaptureMode.video) {
      options.totalSeconds = (options.totalSeconds > -1 ? options.totalSeconds : -1);
      options.preferredTimeScale = options.preferredTimeScale || 30;
      this.setState({ isRecording: true });
    }

    if (typeof options.target === 'string') {
      options.target = constants.CaptureTarget[options.target];
    }

    NativeModules.CameraManager.capture(options, cb);
  },

  stopCapture() {
    if (this.state.isRecording) {
      NativeModules.CameraManager.stopCapture();
      this.setState({ isRecording: false });
    }
  }

});

var RCTCamera = requireNativeComponent('RCTCamera', Camera);

var styles = StyleSheet.create({
  base: { },
});

Camera.constants = constants;
module.exports = Camera;
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

function FileListCtrl($scope, $rootScope, $routeParams, $filter, $http, MediaFiles, LocalFiles) {

	var MEDIA_LIBRARY_URL = 'http://commondatastorage.googleapis.com/';

	$rootScope.bucketName = 'risemedialibrary-' + $routeParams.companyId;
	$rootScope.bucketUrl = MEDIA_LIBRARY_URL + $rootScope.bucketName + '/';
	$scope.mediaFiles = [];
	$rootScope.actionsDisabled = false;

	$rootScope.updateList = function() {
		if ($routeParams.companyId) {

			MediaFiles.query({companyId: $routeParams.companyId}, function(response) {

//			$scope.phonesGroupBy4 = $filter('groupBy')(phones, 4);

				if (response.status == 200) {

					checkTermsCheckbox();

					$scope.mediaFiles = response.mediaFiles;
					$rootScope.librarySize = getLibrarySize($scope.mediaFiles);

				}
				// Authentication failed
				else if (response.status == 403 || response.status == 401) {

					$rootScope.authenticationError = true;
					$rootScope.actionsDisabled = true;

				}
				// Bucket not found
				else if (response.status == 404) {

					checkTermsCheckbox();

				}
				// Media Library feature not enabled
				else if (response.status == 412) {

					$rootScope.actionsDisabled = true;

				}

	  	});

		}
		else {

			$scope.mediaFiles = LocalFiles.query(function(mediaFiles) {

				checkTermsCheckbox();
				$rootScope.actionsDisabled = true;

				$rootScope.librarySize = getLibrarySize(mediaFiles);

			});

		}
	};

	$rootScope.updateList();

  $scope.orderByAttribute = 'key';
  $scope.reverseSort = false;

	initActions($scope, $rootScope, $routeParams, $http);

}

//FileListCtrl.$inject = ['$scope', 'Phone'];

//function FileDetailCtrl($scope, $rootScope, $routeParams, MediaFile) {
//
//  $scope.mediaFiles = MediaFile.query();
//
//	initScope($scope, $rootScope);
//
//}

//PhoneDetailCtrl.$inject = ['$scope', '$routeParams', 'Phone'];

function initActions($scope, $rootScope, $routeParams, $http) {

	$scope.$watch('mediaFiles', function(items) {

		var checkedCount = 0;

		items.forEach(function(item) {
			if (item.checked) {
				checkedCount++;
			}
		});

		$rootScope.$broadcast('CheckedCountChange', checkedCount);

	}, true);

	$scope.$watch('selectAll', function(v) {

    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
        $scope.mediaFiles[ i ].checked = v;
    }

	});

	$rootScope.$on('FileSelectAction', function(event, file) {

		if (!file) {

		  for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
        if ($scope.mediaFiles[ i ].checked) {
					file = $scope.mediaFiles[ i ];
				}
			}

		}

		if (file) {
			var fileUrl = $rootScope.bucketUrl + file.key;
			var data = { params: fileUrl };
			gadgets.rpc.call('', 'rscmd_saveSettings', null, data);

		}

	});

	$rootScope.$on('FileDeleteAction', function(event) {

		var selectedFiles = new Array();

		for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
			if ($scope.mediaFiles[ i ].checked) {
				selectedFiles.push($scope.mediaFiles[ i ].key);
			}
		}

		if (confirm('Are you sure you want to delete the ' + selectedFiles.length + ' files selected?')) {

			$http({

				url: 'deleteFiles',
				method: 'POST',
				data: selectedFiles,
				params:{companyId:$routeParams.companyId},
				headers: {'Content-Type': 'application/octet-stream'}

			}).success(function (data, status, headers, config) {

				$scope.mediaFiles = data;

			}).error(function (data, status, headers, config) {

				$scope.status = status;

			});

		}

	});

	$rootScope.closeButtonClick = function() {

		gadgets.rpc.call('', 'rscmd_closeSettings', null);

	}

}

function checkTermsCheckbox() {

	$('#termsCheckbox').attr('checked', true);
	$('#termsCheckbox').attr('disabled', true);

}

function getLibrarySize(mediaFiles) {

	var size = 0;
	for ( var i = 0; i < mediaFiles.length; ++i ) {
		size += mediaFiles[ i ].size;
	}

	return size;

}

function ButtonsController($scope, $rootScope) {

//	$scope.selectDisabled = true;
	$scope.downloadDisabled = true;
	$scope.deleteDisabled = true;

	$rootScope.$on('CheckedCountChange', function(event, count)	 {

//		$scope.selectDisabled = count != 1;
		$scope.downloadDisabled = !count;
		$scope.deleteDisabled = !count;

	});

	$scope.uploadButtonClick = function() {

//		$('#uploaddialog').modal('show');
		$('#file').click();

	}

}

function ProgressController($scope, $rootScope) {
	$rootScope.uploadProgress = 0;
}

function NavController($scope, $location) {

	$scope.isActive = function (viewLocation) {
      return viewLocation === $location.path();
	};

}

function ViewController($scope) {
	//$scope.thumbnailView = false;

	$('#view-toggle').bootstrapSwitch();

	$('#view-toggle').on('switch-change', function (e, data) {
		$scope.thumbnailView = data.value;

		if (data.value) {
			showListView();
		}
		else {
			showThumbView();
		}
	});

}

function showThumbView() {
	$(".has-switch label").html("");
	$('#thumbnails').show();
	$('#list').hide();
}

function showListView() {
	$(".has-switch label").html("");
	$('#thumbnails').hide();
	$('#list').show();

}

function UploadController($scope, $rootScope, $http, $timeout) {

/*
	Dropzone.options.myAwesomeDropzone = {
		multipleUploads: false,
		init: function() {
			this.on("addedfile", function(file) { alert("Added file."); });
		}
	};
*/

	$scope.googleAccessId = '452091732215@developer.gserviceaccount.com';
	$scope.responseUrl = location.protocol + '//' + location.hostname + '/uploadComplete';
	$scope.fileName = '';
	$scope.contentType = '';

	$scope.uploadFiles = function() {

		//$("#uploadform").submit();
		//$('#file').click();

	}

/*
	$('#uploadform').ajaxForm({
		beforeSend: function() {
			$rootScope.uploadProgress = 0;
		},
		uploadProgress: function(event, position, total, percentComplete) {
			$rootScope.uploadStatus = "Uploading";
			$rootScope.uploadProgress = percentComplete;
		},
		complete: function(xhr) {
			$rootScope.uplodaProgress = 100;
			$rootScope.uploadStatus = xhr.responseText;
		}
	});
*/

	$scope.loadFiles = function(element) {
	//	$('#uploadcompleteframe').contentWindow.name = 'uploadCompleteFrame';

		$('#uploadform').attr('action', $rootScope.bucketUrl);

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

			$rootScope.uploadFileName = element.files[i].name;
			$rootScope.uploadFileSize = element.files[i].size;
			$scope.contentType = element.files[i].type;

			$rootScope.uploadActive = true;
			$rootScope.uploadComplete = false;
			$rootScope.uploadError = false;

			var policyString = '{' +
				'  "expiration": "2020-01-01T12:00:00.000Z",' +
				'  "conditions": [' +
				'    {"bucket": "' + $rootScope.bucketName + '" },' +
				'    {"acl": "public-read" },' +
				'    ["eq", "$key", "' + $rootScope.uploadFileName + '"],' +
				'    ["starts-with", "$Content-Type", "' + $scope.contentType + '"],' +
				'    ["starts-with", "$Cache-Control", "public, max-age=60"],' +
				'    {"success_action_redirect": "' + $scope.responseUrl + '" },' +
				'  ]' +
				'}';

			$scope.policyBase64 = utf8_to_b64(policyString);

			$http({
				url: 'getSignedPolicy',
				method: "POST",
				data: "policyBase64=" + $scope.policyBase64,
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).success(function (data, status, headers, config) {

				$scope.signature = data.trim();

				if ($scope.signature) {

					$timeout(function() {

						$("#uploadform").submit();

					});

				}

			}).error(function (data, status, headers, config) {

				$scope.uploadError(status);

			});

/*
			var reader = new FileReader();
			reader.readAsBinaryString(element.files[i]);

			reader.onload = function(e){

				$scope.fileContent = e.target.result;

				$http({
					url: 'getSignedPolicy',
					method: "POST",
					data: "policyBase64=" + $scope.policyBase64,
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				}).success(function (data, status, headers, config) {

					$scope.signature = data.trim();

					if ($scope.signature) {

						$timeout(function() {
							$("#uploadform").submit();
						});

					}

				}).error(function (data, status, headers, config) {

					$scope.status = status;

				});

			};
*/

			break;

		}

	}

	$('#uploadcompleteframe').load(function(event) {

		try {
			if (event.target.contentWindow.name) {
				$scope.uploadComplete();
			}
			else {
				$scope.uploadError();
			}
		} catch (err) {
			$scope.uploadError();
		}

	});

	$scope.uploadComplete = function() {

		$("#uploadform").trigger("reset");

		$rootScope.updateList();
		$rootScope.uploadComplete = true;

	}

	$scope.uploadError = function() {

		$("#uploadform").trigger("reset");

		$rootScope.uploadError = true;

	}

/*
	$scope.uploadComplete = function(element) {

		try {
			if (element.contentWindow.name) {

				$("#uploadform").reset();

			}
			else {
				return false;
			}
		} catch (err) {
			return false;
		}

	}
*/

/*
	// below code requires OAuth token, which cannot be obtained for Anonymous uploads
	$scope.tok = "<token>";
	$scope.boundary = "---======= rv-upload12034245623562346 ====---";
	$scope.consolidated_request = '';

	$scope.fileCount = 0;
//	$scope.uploadDisabled = !$scope.fileCount > 0;

	$scope.loadFiles = function(element) {

//		var input = $('fileInput');
		$scope.consolidated_request = "";

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

			var f = element.files[i];

			var reader = new FileReader();
			reader.readAsBinaryString(f);

			reader.onload = function(e){

				var fbinary = e.target.result;
				var fsize = f.size;

				var url = '/upload/storage/v1beta2/b/' + 'risemedialibrary-' + '17899fe3-db05-4ecd-ade4-a7106fe53784/o?';
				url += 'uploadType=media&name='+f.name+ ' HTTP/1.1';

				var req = $scope.boundary +
				'\r\nContent-Type: application/http'+
				'\r\nContent-Transfer-Encoding: binary'+
				'\r\n\nPOST ' + url +
				'\r\nContent-Type: image/jpeg'+
				'\r\nContent-Length: '+ f.size +
				'\r\nAuthorization: '+ $scope.tok +
				'\r\n\n'+ fbinary + '\n';

				$scope.consolidated_request += req;
				$scope.fileCount++;

			};

		}

	}

	$scope.uploadFiles = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'https://www.googleapis.com/batch', true);
    xhr.setRequestHeader("Authorization", $scope.tok);
    xhr.setRequestHeader("Content-Type", "multipart/mixed;boundary=" + $scope.boundary);
    xhr.send($scope.consolidated_request);

		$scope.fileCount = 0;
	}
*/

}

function UploadInfoController($scope, $rootScope) {
	$rootScope.uploadFileName = "";
	$rootScope.uploadFileSize = "";
	$rootScope.uploadComplete = false;
	$rootScope.uploadActive = false;
	$rootScope.uploadError = false;

	$scope.uploadInfoClose = function() {
		$rootScope.uploadActive = false;
	};
}

function utf8_to_b64( str ) {
	return window.btoa(unescape(encodeURIComponent( str )));
}

<commit_msg>Disabling buttons on startup<commit_after>'use strict';

/* Controllers */

function FileListCtrl($scope, $rootScope, $routeParams, $filter, $http, MediaFiles, LocalFiles) {

	var MEDIA_LIBRARY_URL = 'http://commondatastorage.googleapis.com/';

	$rootScope.bucketName = 'risemedialibrary-' + $routeParams.companyId;
	$rootScope.bucketUrl = MEDIA_LIBRARY_URL + $rootScope.bucketName + '/';
	$scope.mediaFiles = [];
	$rootScope.actionsDisabled = true;

	$rootScope.updateList = function() {
		if ($routeParams.companyId) {

			MediaFiles.query({companyId: $routeParams.companyId}, function(response) {

//			$scope.phonesGroupBy4 = $filter('groupBy')(phones, 4);

				if (response.status == 200) {

					checkTermsCheckbox();
					$rootScope.actionsDisabled = false;

					$scope.mediaFiles = response.mediaFiles;
					$rootScope.librarySize = getLibrarySize($scope.mediaFiles);

				}
				// Authentication failed
				else if (response.status == 403 || response.status == 401) {

					$rootScope.authenticationError = true;

				}
				// Bucket not found
				else if (response.status == 404) {

					checkTermsCheckbox();
					$rootScope.actionsDisabled = false;

				}
				// Media Library feature not enabled
				else if (response.status == 412) {

				}

	  	});

		}
		else {

			$scope.mediaFiles = LocalFiles.query(function(mediaFiles) {

				checkTermsCheckbox();
				$rootScope.actionsDisabled = true;

				$rootScope.librarySize = getLibrarySize(mediaFiles);

			});

		}
	};

	$rootScope.updateList();

  $scope.orderByAttribute = 'key';
  $scope.reverseSort = false;

	initActions($scope, $rootScope, $routeParams, $http);

}

//FileListCtrl.$inject = ['$scope', 'Phone'];

//function FileDetailCtrl($scope, $rootScope, $routeParams, MediaFile) {
//
//  $scope.mediaFiles = MediaFile.query();
//
//	initScope($scope, $rootScope);
//
//}

//PhoneDetailCtrl.$inject = ['$scope', '$routeParams', 'Phone'];

function initActions($scope, $rootScope, $routeParams, $http) {

	$scope.$watch('mediaFiles', function(items) {

		var checkedCount = 0;

		items.forEach(function(item) {
			if (item.checked) {
				checkedCount++;
			}
		});

		$rootScope.$broadcast('CheckedCountChange', checkedCount);

	}, true);

	$scope.$watch('selectAll', function(v) {

    for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
        $scope.mediaFiles[ i ].checked = v;
    }

	});

	$rootScope.$on('FileSelectAction', function(event, file) {

		if (!file) {

		  for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
        if ($scope.mediaFiles[ i ].checked) {
					file = $scope.mediaFiles[ i ];
				}
			}

		}

		if (file) {
			var fileUrl = $rootScope.bucketUrl + file.key;
			var data = { params: fileUrl };
			gadgets.rpc.call('', 'rscmd_saveSettings', null, data);

		}

	});

	$rootScope.$on('FileDeleteAction', function(event) {

		var selectedFiles = new Array();

		for ( var i = 0; i < $scope.mediaFiles.length; ++i ) {
			if ($scope.mediaFiles[ i ].checked) {
				selectedFiles.push($scope.mediaFiles[ i ].key);
			}
		}

		if (confirm('Are you sure you want to delete the ' + selectedFiles.length + ' files selected?')) {

			$http({

				url: 'deleteFiles',
				method: 'POST',
				data: selectedFiles,
				params:{companyId:$routeParams.companyId},
				headers: {'Content-Type': 'application/octet-stream'}

			}).success(function (data, status, headers, config) {

				$scope.mediaFiles = data;

			}).error(function (data, status, headers, config) {

				$scope.status = status;

			});

		}

	});

	$rootScope.closeButtonClick = function() {

		gadgets.rpc.call('', 'rscmd_closeSettings', null);

	}

}

function checkTermsCheckbox() {

	$('#termsCheckbox').attr('checked', true);
	$('#termsCheckbox').attr('disabled', true);

}

function getLibrarySize(mediaFiles) {

	var size = 0;
	for ( var i = 0; i < mediaFiles.length; ++i ) {
		size += mediaFiles[ i ].size;
	}

	return size;

}

function ButtonsController($scope, $rootScope) {

//	$scope.selectDisabled = true;
	$scope.downloadDisabled = true;
	$scope.deleteDisabled = true;

	$rootScope.$on('CheckedCountChange', function(event, count)	 {

//		$scope.selectDisabled = count != 1;
		$scope.downloadDisabled = !count;
		$scope.deleteDisabled = !count;

	});

	$scope.uploadButtonClick = function() {

//		$('#uploaddialog').modal('show');
		$('#file').click();

	}

}

function ProgressController($scope, $rootScope) {
	$rootScope.uploadProgress = 0;
}

function NavController($scope, $location) {

	$scope.isActive = function (viewLocation) {
      return viewLocation === $location.path();
	};

}

function ViewController($scope) {
	//$scope.thumbnailView = false;

	$('#view-toggle').bootstrapSwitch();

	$('#view-toggle').on('switch-change', function (e, data) {
		$scope.thumbnailView = data.value;

		if (data.value) {
			showListView();
		}
		else {
			showThumbView();
		}
	});

}

function showThumbView() {
	$(".has-switch label").html("");
	$('#thumbnails').show();
	$('#list').hide();
}

function showListView() {
	$(".has-switch label").html("");
	$('#thumbnails').hide();
	$('#list').show();

}

function UploadController($scope, $rootScope, $http, $timeout) {

/*
	Dropzone.options.myAwesomeDropzone = {
		multipleUploads: false,
		init: function() {
			this.on("addedfile", function(file) { alert("Added file."); });
		}
	};
*/

	$scope.googleAccessId = '452091732215@developer.gserviceaccount.com';
	$scope.responseUrl = location.protocol + '//' + location.hostname + '/uploadComplete';
	$scope.fileName = '';
	$scope.contentType = '';

	$scope.uploadFiles = function() {

		//$("#uploadform").submit();
		//$('#file').click();

	}

/*
	$('#uploadform').ajaxForm({
		beforeSend: function() {
			$rootScope.uploadProgress = 0;
		},
		uploadProgress: function(event, position, total, percentComplete) {
			$rootScope.uploadStatus = "Uploading";
			$rootScope.uploadProgress = percentComplete;
		},
		complete: function(xhr) {
			$rootScope.uplodaProgress = 100;
			$rootScope.uploadStatus = xhr.responseText;
		}
	});
*/

	$scope.loadFiles = function(element) {
	//	$('#uploadcompleteframe').contentWindow.name = 'uploadCompleteFrame';

		$('#uploadform').attr('action', $rootScope.bucketUrl);

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

			$rootScope.uploadFileName = element.files[i].name;
			$rootScope.uploadFileSize = element.files[i].size;
			$scope.contentType = element.files[i].type;

			$rootScope.uploadActive = true;
			$rootScope.uploadComplete = false;
			$rootScope.uploadError = false;

			var policyString = '{' +
				'  "expiration": "2020-01-01T12:00:00.000Z",' +
				'  "conditions": [' +
				'    {"bucket": "' + $rootScope.bucketName + '" },' +
				'    {"acl": "public-read" },' +
				'    ["eq", "$key", "' + $rootScope.uploadFileName + '"],' +
				'    ["starts-with", "$Content-Type", "' + $scope.contentType + '"],' +
				'    ["starts-with", "$Cache-Control", "public, max-age=60"],' +
				'    {"success_action_redirect": "' + $scope.responseUrl + '" },' +
				'  ]' +
				'}';

			$scope.policyBase64 = utf8_to_b64(policyString);

			$http({
				url: 'getSignedPolicy',
				method: "POST",
				data: "policyBase64=" + $scope.policyBase64,
				headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			}).success(function (data, status, headers, config) {

				$scope.signature = data.trim();

				if ($scope.signature) {

					$timeout(function() {

						$("#uploadform").submit();

					});

				}

			}).error(function (data, status, headers, config) {

				$scope.uploadError(status);

			});

/*
			var reader = new FileReader();
			reader.readAsBinaryString(element.files[i]);

			reader.onload = function(e){

				$scope.fileContent = e.target.result;

				$http({
					url: 'getSignedPolicy',
					method: "POST",
					data: "policyBase64=" + $scope.policyBase64,
					headers: {'Content-Type': 'application/x-www-form-urlencoded'}
				}).success(function (data, status, headers, config) {

					$scope.signature = data.trim();

					if ($scope.signature) {

						$timeout(function() {
							$("#uploadform").submit();
						});

					}

				}).error(function (data, status, headers, config) {

					$scope.status = status;

				});

			};
*/

			break;

		}

	}

	$('#uploadcompleteframe').load(function(event) {

		try {
			if (event.target.contentWindow.name) {
				$scope.uploadComplete();
			}
			else {
				$scope.uploadError();
			}
		} catch (err) {
			$scope.uploadError();
		}

	});

	$scope.uploadComplete = function() {

		$("#uploadform").trigger("reset");

		$rootScope.updateList();
		$rootScope.uploadComplete = true;

	}

	$scope.uploadError = function() {

		$("#uploadform").trigger("reset");

		$rootScope.uploadError = true;

	}

/*
	$scope.uploadComplete = function(element) {

		try {
			if (element.contentWindow.name) {

				$("#uploadform").reset();

			}
			else {
				return false;
			}
		} catch (err) {
			return false;
		}

	}
*/

/*
	// below code requires OAuth token, which cannot be obtained for Anonymous uploads
	$scope.tok = "<token>";
	$scope.boundary = "---======= rv-upload12034245623562346 ====---";
	$scope.consolidated_request = '';

	$scope.fileCount = 0;
//	$scope.uploadDisabled = !$scope.fileCount > 0;

	$scope.loadFiles = function(element) {

//		var input = $('fileInput');
		$scope.consolidated_request = "";

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

			var f = element.files[i];

			var reader = new FileReader();
			reader.readAsBinaryString(f);

			reader.onload = function(e){

				var fbinary = e.target.result;
				var fsize = f.size;

				var url = '/upload/storage/v1beta2/b/' + 'risemedialibrary-' + '17899fe3-db05-4ecd-ade4-a7106fe53784/o?';
				url += 'uploadType=media&name='+f.name+ ' HTTP/1.1';

				var req = $scope.boundary +
				'\r\nContent-Type: application/http'+
				'\r\nContent-Transfer-Encoding: binary'+
				'\r\n\nPOST ' + url +
				'\r\nContent-Type: image/jpeg'+
				'\r\nContent-Length: '+ f.size +
				'\r\nAuthorization: '+ $scope.tok +
				'\r\n\n'+ fbinary + '\n';

				$scope.consolidated_request += req;
				$scope.fileCount++;

			};

		}

	}

	$scope.uploadFiles = function() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", 'https://www.googleapis.com/batch', true);
    xhr.setRequestHeader("Authorization", $scope.tok);
    xhr.setRequestHeader("Content-Type", "multipart/mixed;boundary=" + $scope.boundary);
    xhr.send($scope.consolidated_request);

		$scope.fileCount = 0;
	}
*/

}

function UploadInfoController($scope, $rootScope) {
	$rootScope.uploadFileName = "";
	$rootScope.uploadFileSize = "";
	$rootScope.uploadComplete = false;
	$rootScope.uploadActive = false;
	$rootScope.uploadError = false;

	$scope.uploadInfoClose = function() {
		$rootScope.uploadActive = false;
	};
}

function utf8_to_b64( str ) {
	return window.btoa(unescape(encodeURIComponent( str )));
}

<|endoftext|>


<commit_before>	function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}
	var changecolor = function(){
	var r=parseInt(255*Math.random());
	var g=parseInt(255*Math.random());
	var b=parseInt(255*Math.random());
	$(".bdy").css("background-color",rgb(r,g,b));
	$(".fa-quote-left").css("color",rgb(r,g,b));
	$(".fa-quote-right").css("color",rgb(r,g,b));
	$("#add-content").css("color",rgb(r,g,b));
	$(".next-button").css("background-color",rgb(r,g,b));
	$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=?",function(a){
		$("#add-content").html("a[0].content");
	});
}

$(document).ready(function(){
	changecolor();
	$(".next-button").on("click",function(){
		changecolor();
	});

});<commit_msg>Update js<commit_after>	function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}
	var changecolor = function(){
	var r=parseInt(255*Math.random());
	var g=parseInt(255*Math.random());
	var b=parseInt(255*Math.random());
	$(".bdy").css("background-color",rgb(r,g,b));
	$(".fa-quote-left").css("color",rgb(r,g,b));
	$(".fa-quote-right").css("color",rgb(r,g,b));
	$("#add-content").css("color",rgb(r,g,b));
	$(".next-button").css("background-color",rgb(r,g,b));
	$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=?",function(a){
		$("#add-content").html("a[0].content");
	});
}

$(document).ready(function(){
	changecolor();
	$(".next-button").on("click",function(){
		changecolor();
	});

});
<|endoftext|>