<commit_before>// itertool.js
// (c) 2011 OnesimusUnbound <marcelino dat deseo aet gmail dat com>
// itertools.js is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/OnesimusUnbound/itertool.js

// Version 0.0.1

(function(){
    // ------------------------- Baseline setup ---------------------------------

    var ObjectProto = Object.prototype,
        ArrayProto = Array.prototype;

    var __hasOwns = ObjectProto.hasOwnProperty,

        __type = function(obj){
            if (typeof obj === 'undefined') {
                return "Undefined";
            } else if (obj === null) {
                return "Null";
            } else if (typeof obj.next === 'function') {
                return "Iterator";
            } else {
                return ObjectProto.toString.call(obj).match(/^\[object (.*)\]$/)[1];
            }
        },

        __extend = function(obj, other){
            for (var prop in other){
                if (__hasOwns.call(other, prop)) {
                    obj[prop] = other[prop];
                }
            }
            return obj;
        },

        __map = function(items, callback){
            var result = [];

            for (var i = 0; i < items.length; i++){
                result[i] = callback(items[i]);
            }

            return result;
        },

        __slice = ArrayProto.slice,

        __truthy = function(item){ return !!item; },

        __identity = function(x){ return x; };

    var root = this,
        __previous_itertool = root.itertool,
        itertool = {};

    var StopIteration;
    if (!root.StopIteration) {
        StopIteration = root.StopIteration = Error('StopIteration');
    } else {
        StopIteration = root.StopIteration;
    }
    itertool.StopIteration = StopIteration;
    var Iterator = itertool.Iterator = function(){};

    Iterator.prototype.next = function(){ throw StopIteration; };
    Iterator.prototype.__iterator__ = function(){ return this; };

    var extendIterator = function(nextImpl) {
        return __extend(new Iterator, {next: nextImpl});
    };

    var ArrayIterator = itertool.ArrayIterator = function(array) {
        if(__type(array) === 'Undefined') throw new TypeError;

        var size = array.length,
            idx = 0;

        return extendIterator(function(){
            if (size > idx) return array[idx++];
            throw StopIteration;
        });
    };

    var StringIterator = itertool.StringIterator = function(string, option){
        if(__type(string) === 'Undefined') throw new TypeError;

        var items = [];
        option = option || "";

        switch(__type(option)){
            case 'String':
            case 'RegExp':
                items = string.split(option);
                break;
        }

        return ArrayIterator(items);
    }

    var ObjectIterator = itertool.ObjectIterator = function(obj, option) {
        if(__type(obj) === 'Undefined') throw new TypeError;

        var items = [];
        for (var key in obj){
            if (__hasOwns.call(obj, key)){
                switch(option){
                    case 'keys' : items.push(key); break;
                    case 'all'  : items.push([key, obj[key]]); break;
                    default     : items.push(obj[key]);
                }
            }
        }

        return ArrayIterator(items);
    };

    var toIterator = itertool.toIterator = function(obj){
        switch(__type(obj)){
            case 'String':
                return StringIterator.apply(root, arguments);

            case 'Array':
                return ArrayIterator.apply(root, arguments);

            case 'Iterator':
                return obj;

            default:
                return ObjectIterator.apply(root, arguments);
        }
    };

    var toArray = itertool.toArray = function(iterable){
        var array = [];

        try {
            while (true) {
                array.push(iterable.next());
            }
        } catch(err) {
            if (err !== StopIteration) throw err;
            return array;
        }
    };

    // Utility functions
    // =================

    itertool.noConflict = function() {
        root.itertool = __previous_itertool;
        return this;
    };

    var ieach = itertool.ieach = function(iterable, callback) {
        try {
            while(true) callback(iterable.next());
        } catch(err) {
            if (err !== StopIteration) throw err;
        }
    };

    // Infinite Iterators
    // ==================

    // counter
    var counter = itertool.counter = function(start, step){
        start = start || 0;
        step  = step  || 1;
        start -= step;

        return extendIterator(function(){
            return (start += step);
        });
    };

    // cycle
    var cycle = itertool.cycle = function(obj){
        var type = __type(obj);

        if (type === 'Number' || type === 'RegExp' || type === 'Null')
            throw new TypeError;

        var iter = toIterator(obj),
            gen, size, idx, items = [];

        gen = extendIterator(function(){
            try {
                var item = iter.next();
                items.push(item);
                return item;
            } catch (err) {
                if (err !== StopIteration) throw err;

                size = items.length;
                if (!size) throw err;

                idx = 0;
                gen.next = function(){
                    if (idx >= size) idx = 0;
                    return items[idx++];
                };

                return gen.next();
            }
        });

        return gen;
    };

    // repeat
    var repeat = itertool.repeat = function(element, n){
        var count = 0;

        if (__type(n) === 'Undefined') {
            return extendIterator(function() { return element; });
        } else {
            return extendIterator(function(){
                if (count < n) {
                    count++;
                    return element;
                }
                throw StopIteration;
            });
        }
    };

    // Terminating Iterators
    // =====================
    // chain
    var chain = itertool.chain = function(){
        var iterables = __slice.call(arguments),
            size, iterIdx = 0, currentIter;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);
            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable)
        });

        size = iterables.length;
        currentIter = iterables[iterIdx++];

        gen = extendIterator(function(){
            try {
                return currentIter.next();
            } catch (err) {
                if (err !== StopIteration) throw err;
                if (size > iterIdx) {
                    currentIter = iterables[iterIdx++];
                    return gen.next();
                }
                throw StopIteration;
            }
        });

        return gen;
    };

    // irange
    var irange = itertool.irange = function(start, stop, step) {
        if (arguments.length <= 1) {
            stop = start || 0;
            start = 0;
        }
        step = step || 1;

        var len = Math.max(Math.ceil((stop - start) / step), 0);
        var idx = 0;

        start -= step;
        return extendIterator(function(){
            if (idx < len) {
                idx++;
                return (start += step);
            }
            throw StopIteration;
        });
    };

    var compress = itertool.compress = function(data, selectors) {
        var iterData = toIterator(data),
            iterSelector = toIterator(selectors);

        return extendIterator(function(){
            while(!iterSelector.next()) {
                iterData.next();
            }
            return iterData.next();
        });
    };

    var dropwhile = itertool.dropwhile = function(predicate, iterable) {
        if (__type(predicate) !== 'Function') throw new TypeError;

        iterable = toIterator(iterable);
        var firstValid,
            gen = extendIterator(function(){
                while(predicate(firstValid = iterable.next()));
                gen.next = function(){
                    return iterable.next();
                };
                return firstValid;
            });

        return gen;
    };

    var takewhile = itertool.takewhile = function(predicate, iterable) {
        if (__type(predicate) !== 'Function') throw new TypeError;

        iterable = toIterator(iterable);
        var takenItem,
            gen = extendIterator(function(){
                if (predicate(takenItem = iterable.next()))
                    return takenItem;

                throw StopIteration;
            });

        return gen;
    };

    var ifilter = itertool.ifilter = function(predicate, iterable) {
        iterable = toIterator(iterable || predicate);
        predicate = arguments.length === 2 ? predicate : __truthy;
        if (typeof predicate !== 'function') throw new TypeError;

        var validItem;
        return extendIterator(function(){
            while(!predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    var ifilterfalse = itertool.ifilterfalse = function(predicate, iterable) {
        iterable = toIterator(iterable || predicate);
        predicate = arguments.length === 2 ? predicate : __truthy;
        if (typeof predicate !== 'function') throw new TypeError;

        var validItem;
        return extendIterator(function(){
            while(predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    var imap = itertool.imap = function(callback) {
        var iterables = __slice.call(arguments, 1),
            size = iterables.length;

        if (__type(callback) !== 'Function') throw new TypeError;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);
            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var args = __map(iterables, function(iterable){
                return iterable.next();
            });

            return callback.apply(root, args);
        });
    };

    var islice = itertool.islice = function(iterable) {
        iterable = toIterator(iterable);
        var iterRange = irange.apply(root, __slice.call(arguments, 1)),
            validIdx,
            idx = -1;

        return extendIterator(function(){
            var item;

            validIdx = iterRange.next();
            while (true) {
                item = iterable.next();
                idx++;
                if (idx === validIdx) return item;
            }
        });
    };

    var izip = itertool.izip = function() {
        var iterables = __slice.call(arguments),
            size = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            if (size > 0)
                return __map(iterables, function(iterable){
                    return iterable.next();
                });

            throw StopIteration;
        });
    };

    var izip_longest = itertool.izip_longest = function() {
        var iterables = __slice.call(arguments, 1),
            fillvalue = arguments[0] || "";
            numIterables = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var numEndedIter = 0;
            if (numIterables > 0)
                result = __map(iterables, function(iterable){
                    try {
                        return iterable.next();
                    } catch(err) {
                        if (err !== StopIteration) throw err;
                        if (numEndedIter < numIterables) {
                            numEndedIter++;
                            return fillvalue;
                        }
                    }
                });

            if (numEndedIter < numIterables)
                return result;

            throw StopIteration;
        });
    };

    var starmap = itertool.starmap = function(callback, argList) {
        if (__type(callback) !== 'Function') throw new TypeError;

        var iterable = toIterator(argList);

        return extendIterator(function(){
            return callback.apply(root, iterable.next());
        });
    };

    var tee = itertool.tee = function(iterable, n) {
        n = n || 2;
        iterable = toIterator(iterable);

        var queue = [],
            teeItrables = [],
            gen = function(idx){
                return extendIterator(function(){
                    if (idx >= queue.length)
                        queue.push(iterable.next());

                    return queue[idx++];
                });
            };

        for(var i = 0; i < n; i++) {
            teeItrables.push(gen(0));
        }

        return teeItrables;
    };

    var groupby = itertool.groupby = function(iterable, key) {
        var keyfunc = key || __identity,
            tgtkey, currkey, currvalue, grouper;

        iterable = toIterator(iterable);
        tgtkey = currkey = currvalue = {};

        grouper = function(ptgtkey, continueIter){
            return extendIterator(function(){
                var retvalue;
                if (currkey === ptgtkey && continueIter) {
                    retvalue = currvalue;
                    try {
                        currvalue = iterable.next();
                    } catch (err) {
                        if (err !== StopIteration) throw err;
                        continueIter = false;
                    }
                    currkey = keyfunc(currvalue);
                    return retvalue;
                }

                throw StopIteration;
            });
        };

        return extendIterator(function(){
            if (currkey == tgtkey) {
                currvalue = iterable.next();
                currkey = keyfunc(currvalue);
            }
            tgtkey = currkey;
            return [currkey, grouper(tgtkey, true)];
        });
    };

    // CommonJS module is defined
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = itertool;

    } else if (typeof exports !== 'undefined') {
        exports = itertool;

    } else {
        root.itertool = itertool;
    }
}());
<commit_msg>cleanup code<commit_after>// itertool.js
// (c) 2011 OnesimusUnbound <marcelino dat deseo aet gmail dat com>
// itertools.js is freely distributable under the terms of the MIT license.
// Documentation: https://github.com/OnesimusUnbound/itertool.js

// Version 0.0.1

(function(){
    // ------------------------- Baseline setup ---------------------------------

    var ObjectProto = Object.prototype,
        ArrayProto = Array.prototype;

    var __hasOwns = ObjectProto.hasOwnProperty,

        __type = function(obj){
            if (typeof obj === 'undefined') {
                return "Undefined";
            } else if (obj === null) {
                return "Null";
            } else if (typeof obj.next === 'function') {
                return "Iterator";
            } else {
                return ObjectProto.toString.call(obj).match(/^\[object (.*)\]$/)[1];
            }
        },

        __extend = function(obj, other){
            for (var prop in other){
                if (__hasOwns.call(other, prop)) {
                    obj[prop] = other[prop];
                }
            }
            return obj;
        },

        __map = function(items, callback){
            var result = [];

            for (var i = 0; i < items.length; i++){
                result[i] = callback(items[i]);
            }

            return result;
        },

        __slice = ArrayProto.slice,

        __truthy = function(item){ return !!item; },

        __identity = function(x){ return x; };

    var root = this,
        __previous_itertool = root.itertool,
        itertool = {};

    var StopIteration;
    if (!root.StopIteration) {
        StopIteration = root.StopIteration = Error('StopIteration');
    } else {
        StopIteration = root.StopIteration;
    }
    itertool.StopIteration = StopIteration;
    var Iterator = itertool.Iterator = function(){};

    Iterator.prototype.next = function(){ throw StopIteration; };
    Iterator.prototype.__iterator__ = function(){ return this; };

    var extendIterator = function(nextImpl) {
        return __extend(new Iterator, {next: nextImpl});
    };

    var ArrayIterator = itertool.ArrayIterator = function(array) {
        if(__type(array) === 'Undefined') throw new TypeError;

        var size = array.length,
            idx = 0;

        return extendIterator(function(){
            if (size > idx) return array[idx++];
            throw StopIteration;
        });
    };

    var StringIterator = itertool.StringIterator = function(string, option){
        if(__type(string) === 'Undefined') throw new TypeError;

        var items = [];
        option = option || "";

        switch(__type(option)){
            case 'String':
            case 'RegExp':
                items = string.split(option);
                break;
        }

        return ArrayIterator(items);
    }

    var ObjectIterator = itertool.ObjectIterator = function(obj, option) {
        if(__type(obj) === 'Undefined') throw new TypeError;

        var items = [];
        for (var key in obj){
            if (__hasOwns.call(obj, key)){
                switch(option){
                    case 'keys' : items.push(key); break;
                    case 'all'  : items.push([key, obj[key]]); break;
                    default     : items.push(obj[key]);
                }
            }
        }

        return ArrayIterator(items);
    };

    var toIterator = itertool.toIterator = function(obj){
        switch(__type(obj)){
            case 'String':      return StringIterator.apply(root, arguments);
            case 'Array':       return ArrayIterator.apply(root, arguments);
            case 'Iterator':    return obj;
            default:            return ObjectIterator.apply(root, arguments);
        }
    };

    var toArray = itertool.toArray = function(iterable){
        var array = [];

        try {
            while (true) array.push(iterable.next());

        } catch(err) {
            if (err !== StopIteration) throw err;
            return array;
        }
    };

    // Utility functions
    // =================

    itertool.noConflict = function() {
        root.itertool = __previous_itertool;
        return this;
    };

    var ieach = itertool.ieach = function(iterable, callback) {
        try {
            while(true) callback(iterable.next());
        } catch(err) {
            if (err !== StopIteration) throw err;
        }
    };

    // Infinite Iterators
    // ==================

    // counter
    var counter = itertool.counter = function(start, step){
        start = start || 0;
        step  = step  || 1;
        start -= step;

        return extendIterator(function(){
            return (start += step);
        });
    };

    // cycle
    var cycle = itertool.cycle = function(obj){
        var type = __type(obj);

        if (type === 'Number' || type === 'RegExp' || type === 'Null')
            throw new TypeError;

        var iter = toIterator(obj),
            gen, size, idx, items = [];

        gen = extendIterator(function(){
            try {
                var item = iter.next();
                items.push(item);
                return item;
            } catch (err) {
                if (err !== StopIteration) throw err;

                size = items.length;
                if (!size) throw err;

                idx = 0;
                gen.next = function(){
                    if (idx >= size) idx = 0;
                    return items[idx++];
                };

                return gen.next();
            }
        });

        return gen;
    };

    // repeat
    var repeat = itertool.repeat = function(element, n){
        var count = 0;

        if (__type(n) === 'Undefined') {
            return extendIterator(function() { return element; });
        } else {
            return extendIterator(function(){
                if (count < n) {
                    count++;
                    return element;
                }
                throw StopIteration;
            });
        }
    };

    // Terminating Iterators
    // =====================
    // chain
    var chain = itertool.chain = function(){
        var iterables = __slice.call(arguments),
            size, iterIdx = 0, currentIter;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);
            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable)
        });

        size = iterables.length;
        currentIter = iterables[iterIdx++];

        gen = extendIterator(function(){
            try {
                return currentIter.next();
            } catch (err) {
                if (err !== StopIteration) throw err;
                if (size > iterIdx) {
                    currentIter = iterables[iterIdx++];
                    return gen.next();
                }
                throw StopIteration;
            }
        });

        return gen;
    };

    // irange
    var irange = itertool.irange = function(start, stop, step) {
        if (arguments.length <= 1) {
            stop = start || 0;
            start = 0;
        }
        step = step || 1;

        var len = Math.max(Math.ceil((stop - start) / step), 0);
        var idx = 0;

        start -= step;
        return extendIterator(function(){
            if (idx < len) {
                idx++;
                return (start += step);
            }
            throw StopIteration;
        });
    };

    var compress = itertool.compress = function(data, selectors) {
        var iterData = toIterator(data),
            iterSelector = toIterator(selectors);

        return extendIterator(function(){
            while(!iterSelector.next()) {
                iterData.next();
            }
            return iterData.next();
        });
    };

    var dropwhile = itertool.dropwhile = function(predicate, iterable) {
        if (__type(predicate) !== 'Function') throw new TypeError;

        iterable = toIterator(iterable);
        var firstValid,
            gen = extendIterator(function(){
                while(predicate(firstValid = iterable.next()));
                gen.next = function(){
                    return iterable.next();
                };
                return firstValid;
            });

        return gen;
    };

    var takewhile = itertool.takewhile = function(predicate, iterable) {
        if (__type(predicate) !== 'Function') throw new TypeError;

        iterable = toIterator(iterable);
        var takenItem,
            gen = extendIterator(function(){
                if (predicate(takenItem = iterable.next()))
                    return takenItem;

                throw StopIteration;
            });

        return gen;
    };

    var ifilter = itertool.ifilter = function(predicate, iterable) {
        iterable = toIterator(iterable || predicate);
        predicate = arguments.length === 2 ? predicate : __truthy;
        if (typeof predicate !== 'function') throw new TypeError;

        var validItem;
        return extendIterator(function(){
            while(!predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    var ifilterfalse = itertool.ifilterfalse = function(predicate, iterable) {
        iterable = toIterator(iterable || predicate);
        predicate = arguments.length === 2 ? predicate : __truthy;
        if (typeof predicate !== 'function') throw new TypeError;

        var validItem;
        return extendIterator(function(){
            while(predicate(validItem = iterable.next()));
            return validItem;
        });
    };

    var imap = itertool.imap = function(callback) {
        var iterables = __slice.call(arguments, 1),
            size = iterables.length;

        if (__type(callback) !== 'Function') throw new TypeError;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);
            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var args = __map(iterables, function(iterable){
                return iterable.next();
            });

            return callback.apply(root, args);
        });
    };

    var islice = itertool.islice = function(iterable) {
        iterable = toIterator(iterable);
        var iterRange = irange.apply(root, __slice.call(arguments, 1)),
            validIdx,
            idx = -1;

        return extendIterator(function(){
            var item;

            validIdx = iterRange.next();
            while (true) {
                item = iterable.next();
                idx++;
                if (idx === validIdx) return item;
            }
        });
    };

    var izip = itertool.izip = function() {
        var iterables = __slice.call(arguments),
            size = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            if (size > 0)
                return __map(iterables, function(iterable){
                    return iterable.next();
                });

            throw StopIteration;
        });
    };

    var izip_longest = itertool.izip_longest = function() {
        var iterables = __slice.call(arguments, 1),
            fillvalue = arguments[0] || "";
            numIterables = iterables.length;

        iterables = __map(iterables, function(iterable){
            var type = __type(iterable);

            if (type === 'Number' || type === 'RegExp')
                throw new TypeError;

            return toIterator(iterable);
        });

        return extendIterator(function(){
            var numEndedIter = 0;
            if (numIterables > 0)
                result = __map(iterables, function(iterable){
                    try {
                        return iterable.next();
                    } catch(err) {
                        if (err !== StopIteration) throw err;
                        if (numEndedIter < numIterables) {
                            numEndedIter++;
                            return fillvalue;
                        }
                    }
                });

            if (numEndedIter < numIterables)
                return result;

            throw StopIteration;
        });
    };

    var starmap = itertool.starmap = function(callback, argList) {
        if (__type(callback) !== 'Function') throw new TypeError;

        var iterable = toIterator(argList);

        return extendIterator(function(){
            return callback.apply(root, iterable.next());
        });
    };

    var tee = itertool.tee = function(iterable, n) {
        n = n || 2;
        iterable = toIterator(iterable);

        var queue = [],
            teeItrables = [],
            gen = function(idx){
                return extendIterator(function(){
                    if (idx >= queue.length)
                        queue.push(iterable.next());

                    return queue[idx++];
                });
            };

        for(var i = 0; i < n; i++) {
            teeItrables.push(gen(0));
        }

        return teeItrables;
    };

    var groupby = itertool.groupby = function(iterable, key) {
        var keyfunc = key || __identity,
            tgtkey, currkey, currvalue, grouper;

        iterable = toIterator(iterable);
        tgtkey = currkey = currvalue = {};

        grouper = function(ptgtkey, continueIter){
            return extendIterator(function(){
                var retvalue;
                if (currkey === ptgtkey && continueIter) {
                    retvalue = currvalue;
                    try {
                        currvalue = iterable.next();
                    } catch (err) {
                        if (err !== StopIteration) throw err;
                        continueIter = false;
                    }
                    currkey = keyfunc(currvalue);
                    return retvalue;
                }

                throw StopIteration;
            });
        };

        return extendIterator(function(){
            if (currkey == tgtkey) {
                currvalue = iterable.next();
                currkey = keyfunc(currvalue);
            }
            tgtkey = currkey;
            return [currkey, grouper(tgtkey, true)];
        });
    };

    // CommonJS module is defined
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = itertool;

    } else if (typeof exports !== 'undefined') {
        exports = itertool;

    } else {
        root.itertool = itertool;
    }
}());
<|endoftext|>


<commit_before>$(function() {
    var viewport;
    var nominalWidth = 700;
    var charts = {};
    // Global options for markdown charts
    Highcharts.setOptions({
        lang: {
            thousandsSep: ','
        }
    });

    var chartContainer = $(".markdown-chart");
    if (!chartContainer.length) {
        return;
    }

    //set the annotation and chart size based on the viewport
    if ($("body").hasClass("viewport-sm")) {
        viewport = 'sm';
        nominalWidth = 360;
    }else if ($("body").hasClass("viewport-md")) {
        viewport = 'md';
        nominalWidth = 520;
    }else  {
        viewport = 'lg';
    }
    //console.log('viewport ' + viewport);

    /**
     * Create a global getSVG method that takes an array of charts as an
     * argument
     */
    Highcharts.getSVG = function (charts) {

        console.log('get SVG');
        var svgArr = [],
        topBorder =20,
            top = topBorder,
            left = 0,
            width = 0,
            height = 0,
            columns = 0,
            rows = 0,
            maxColumns = 3;

        Highcharts.each(charts, function (chart) {
            var svg = chart.getSVG(),
                // Get width/height of SVG for export
                svgWidth = +svg.match(
                    /^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/
                )[1],
                svgHeight = +svg.match(
                    /^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/
                )[1];

            svg = svg.replace(
                '<svg',
                '<g transform="translate(' + left + ',' + top + ')" '
            );
            svg = svg.replace('</svg>', '</g>');

            //lay out the svg in columns and rows
            columns++;
            if(columns>=maxColumns){
                columns = 0;
                left = 0;
                rows++;
                top = svgHeight * rows + topBorder;
                height = top + svgHeight;
            }else{
                left += svgWidth;
                width += svgWidth;
            }

            svgArr.push(svg);
        });

        return '<svg height="' + height + '" width="' + width +
            '" version="1.1" xmlns="http://www.w3.org/2000/svg">' +
            '<rect x="0" y="0" width="' + width + '" height="' + height + '" fill="white" />' +
            svgArr.join('') + '</svg>';
    };

    /**
     * Create a global exportCharts method that takes an array of charts as an
     * argument, and exporting options as the second argument
     */
    Highcharts.exportCharts = function (charts, options) {
        var svg;
        // Merge the options
        options = Highcharts.merge(Highcharts.getOptions().exporting, options);

        // get export url fromm the chart config
        if(options.exporting.url){
            options.url = options.exporting.url;
        }

        if(charts.length>1){
            svg = Highcharts.getSVG(charts)
        }else{
            svg = charts[0];
        }

        console.log('____________');
        console.log(svg);
        // Post to export server
        Highcharts.post(options.url, {
            filename: options.filename || 'chart',
            type: options.type,
            width: options.width,
            svg: svg
        });
    };

    $('#export-png').click(function () {
        Highcharts.exportCharts(chartList, chartConfig);
    });

    $('.export-svg').click(function () {
        console.log('export svg');
        var id = this.dataset.filename;
        var chart = charts[id];
        var svg = chart.getSVG();
        console.log(svg);
        // a bit dirty - pass the svg into the charts array
        Highcharts.exportCharts([svg], chartConfig);

    });

    var chartList = [];
    var chartConfig;
    var chart;

    chartContainer.each(function() {
        var $this = $(this);
        var id = $this.attr('id');
        var chartId = $this.data('filename');
        var chartWidth = $this.width();
        var chartUri = $this.data('uri');

        $this.empty();

        //Read chart configuration from server using container's width
        var jqxhr = $.get("/chartconfig", {
                uri: chartUri,
                width: nominalWidth//chartWidth
            },
            function() {
             chartConfig = window["chart-" + chartId];

                if (chartConfig) {
                    // small multiples have an attribute to show specific series
                    var smallMultipleSeries = $this.data('series');
                    var smallMultipleRef = id.split("-")[2];

                    //adjust size and notes to match viewport

                    var aspectRatio = 1;
                    var labelInterval = 1;
                    //if we have devices then set annotations dependant on viewport
                    if(chartConfig.devices){
                        if(chartConfig.devices[viewport]){

                            if(!chartConfig.devices[viewport].isHidden){

                                //set the aspect ratio
                                aspectRatio = chartConfig.devices[viewport].aspectRatio;
                                chartConfig.xAxis.tickInterval = chartConfig.devices[viewport].labelInterval;

                                //loop thru and update annotations if reqd
                                if(chartConfig.annotations.length>0){
                                    $.each(chartConfig.annotations, function(idx, itm){
                                        chartConfig.annotations[idx].x = chartConfig.annotations[idx]['position_'+viewport].x;
                                        chartConfig.annotations[idx].y = chartConfig.annotations[idx]['position_'+viewport].y;
                                    })
                                }
                                //loop thru X AXIS plotline/plotbands
                                if(chartConfig.xAxis.plotLines){

                                    if(chartConfig.xAxis.plotLines.length>0){
                                        $.each(chartConfig.xAxis.plotLines, function(idx, itm){
                                            chartConfig.xAxis.plotLines[idx].value = chartConfig.xAxis.plotLines[idx]['position_'+viewport].x;
                                        })
                                    }

                                }
                                if(chartConfig.xAxis.plotBands){

                                    if(chartConfig.xAxis.plotBands.length>0){
                                        $.each(chartConfig.xAxis.plotBands, function(idx, itm){
                                            chartConfig.xAxis.plotBands[idx].value = chartConfig.xAxis.plotBands[idx]['position_'+viewport].x;
                                        })
                                    }

                                }
                                //loop thru Y AXIS plotline/plotbands
                                if(chartConfig.yAxis.plotLines){

                                    if(chartConfig.yAxis.plotLines.length>0){
                                        $.each(chartConfig.yAxis.plotLines, function(idx, itm){
                                            chartConfig.yAxis.plotLines[idx].value = chartConfig.yAxis.plotLines[idx]['position_'+viewport].y;
                                        })
                                    }

                                }
                                if(chartConfig.yAxis.plotBands){

                                    if(chartConfig.yAxis.plotBands.length>0){
                                        $.each(chartConfig.yAxis.plotBands, function(idx, itm){
                                            chartConfig.yAxis.plotBands[idx].value = chartConfig.yAxis.plotBands[idx]['position_'+viewport].y;
                                        })
                                    }

                                }

                            }else{
                                //add hidden notes to footnotes
                                var str = '';

                                //add a header if required
                                if(!$('.js-notes-title')){
                                    str = '
Notes:
';
                                }
                                $.each(chartConfig.annotations, function(idx, itm){
                                    str+= itm.title+'
'
                                })
                                $.each(chartConfig.xAxis.plotBands, function(idx, itm){
                                    str+= itm.label.text+'
'
                                })
                                $.each(chartConfig.xAxis.plotLines, function(idx, itm){
                                    str+= itm.label.text+'
'
                                })
                                $.each(chartConfig.yAxis.plotBands, function(idx, itm){
                                    str+= itm.label.text+'
'
                                })
                                $.each(chartConfig.yAxis.plotLines, function(idx, itm){
                                    str+= itm.label.text+'
'
                                })
                                $('#notes-'+chartId).append(str);
                                // clear any defaults
                                chartConfig.xAxis.plotBands = [];
                                chartConfig.xAxis.plotLines = [];
                                chartConfig.yAxis.plotBands = [];
                                chartConfig.yAxis.plotLines = [];
                                chartConfig.annotations = [];
                            }
                        }
                    }

                    if(smallMultipleSeries){
                        //console.log("small multiples ");
                        //loop through series and create mini-charts
                        var tempSeries = chartConfig.series;
                        chartConfig.chart.width = chartWidth/3;
                        chartConfig.chart.height = chartWidth/3;
                        chartConfig.isSmallMultiple = 'small-multiples';

                        chartConfig.series = [tempSeries[smallMultipleRef]];
                        chartConfig.chart.renderTo = id;
                        chart = new Highcharts.Chart(chartConfig);
                        chartList.push(chart);

                    }else{

                        if(chartConfig.chart.type==='table'){

                        }else{
                            //console.log('push chart ' + chartConfig.chart.type);
                            //chartList = [];
                            // Build chart from config endpoint
                            chartConfig.chart.renderTo = id;
                            chartConfig.chart.height = chartConfig.chart.width * aspectRatio;
                            chart = new Highcharts.Chart(chartConfig);
                            //chartList.push(chart);

                            charts[chartId] = chart;
                        }
                    }

                    delete window["chart-" + chartId]; //clear data from window object after rendering

                }
            }, "script");

    });
});
<commit_msg>Style hidden annotations as ordered list<commit_after>$(function() {
    var viewport;
    var nominalWidth = 700;
    var charts = {};
    // Global options for markdown charts
    Highcharts.setOptions({
        lang: {
            thousandsSep: ','
        }
    });

    var chartContainer = $(".markdown-chart");
    if (!chartContainer.length) {
        return;
    }

    //set the annotation and chart size based on the viewport
    if ($("body").hasClass("viewport-sm")) {
        viewport = 'sm';
        nominalWidth = 360;
    }else if ($("body").hasClass("viewport-md")) {
        viewport = 'md';
        nominalWidth = 520;
    }else  {
        viewport = 'lg';
    }
    //console.log('viewport ' + viewport);

    /**
     * Create a global getSVG method that takes an array of charts as an
     * argument
     */
    Highcharts.getSVG = function (charts) {

        console.log('get SVG');
        var svgArr = [],
        topBorder =20,
            top = topBorder,
            left = 0,
            width = 0,
            height = 0,
            columns = 0,
            rows = 0,
            maxColumns = 3;

        Highcharts.each(charts, function (chart) {
            var svg = chart.getSVG(),
                // Get width/height of SVG for export
                svgWidth = +svg.match(
                    /^<svg[^>]*width\s*=\s*\"?(\d+)\"?[^>]*>/
                )[1],
                svgHeight = +svg.match(
                    /^<svg[^>]*height\s*=\s*\"?(\d+)\"?[^>]*>/
                )[1];

            svg = svg.replace(
                '<svg',
                '<g transform="translate(' + left + ',' + top + ')" '
            );
            svg = svg.replace('</svg>', '</g>');

            //lay out the svg in columns and rows
            columns++;
            if(columns>=maxColumns){
                columns = 0;
                left = 0;
                rows++;
                top = svgHeight * rows + topBorder;
                height = top + svgHeight;
            }else{
                left += svgWidth;
                width += svgWidth;
            }

            svgArr.push(svg);
        });

        return '<svg height="' + height + '" width="' + width +
            '" version="1.1" xmlns="http://www.w3.org/2000/svg">' +
            '<rect x="0" y="0" width="' + width + '" height="' + height + '" fill="white" />' +
            svgArr.join('') + '</svg>';
    };

    /**
     * Create a global exportCharts method that takes an array of charts as an
     * argument, and exporting options as the second argument
     */
    Highcharts.exportCharts = function (charts, options) {
        var svg;
        // Merge the options
        options = Highcharts.merge(Highcharts.getOptions().exporting, options);

        // get export url fromm the chart config
        if(options.exporting.url){
            options.url = options.exporting.url;
        }

        if(charts.length>1){
            svg = Highcharts.getSVG(charts)
        }else{
            svg = charts[0];
        }

        console.log('____________');
        console.log(svg);
        // Post to export server
        Highcharts.post(options.url, {
            filename: options.filename || 'chart',
            type: options.type,
            width: options.width,
            svg: svg
        });
    };

    $('#export-png').click(function () {
        Highcharts.exportCharts(chartList, chartConfig);
    });

    $('.export-svg').click(function () {
        console.log('export svg');
        var id = this.dataset.filename;
        var chart = charts[id];
        var svg = chart.getSVG();
        console.log(svg);
        // a bit dirty - pass the svg into the charts array
        Highcharts.exportCharts([svg], chartConfig);

    });

    var chartList = [];
    var chartConfig;
    var chart;

    chartContainer.each(function() {
        var $this = $(this);
        var id = $this.attr('id');
        var chartId = $this.data('filename');
        var chartWidth = $this.width();
        var chartUri = $this.data('uri');

        $this.empty();

        //Read chart configuration from server using container's width
        var jqxhr = $.get("/chartconfig", {
                uri: chartUri,
                width: nominalWidth//chartWidth
            },
            function() {
             chartConfig = window["chart-" + chartId];

                if (chartConfig) {
                    // small multiples have an attribute to show specific series
                    var smallMultipleSeries = $this.data('series');
                    var smallMultipleRef = id.split("-")[2];

                    //adjust size and notes to match viewport

                    var aspectRatio = 1;
                    var labelInterval = 1;
                    //if we have devices then set annotations dependant on viewport
                    if(chartConfig.devices){
                        if(chartConfig.devices[viewport]){

                            if(!chartConfig.devices[viewport].isHidden){

                                //set the aspect ratio
                                aspectRatio = chartConfig.devices[viewport].aspectRatio;
                                chartConfig.xAxis.tickInterval = chartConfig.devices[viewport].labelInterval;

                                //loop thru and update annotations if reqd
                                if(chartConfig.annotations.length>0){
                                    $.each(chartConfig.annotations, function(idx, itm){
                                        chartConfig.annotations[idx].x = chartConfig.annotations[idx]['position_'+viewport].x;
                                        chartConfig.annotations[idx].y = chartConfig.annotations[idx]['position_'+viewport].y;
                                    })
                                }
                                //loop thru X AXIS plotline/plotbands
                                if(chartConfig.xAxis.plotLines){

                                    if(chartConfig.xAxis.plotLines.length>0){
                                        $.each(chartConfig.xAxis.plotLines, function(idx, itm){
                                            chartConfig.xAxis.plotLines[idx].value = chartConfig.xAxis.plotLines[idx]['position_'+viewport].x;
                                        })
                                    }

                                }
                                if(chartConfig.xAxis.plotBands){

                                    if(chartConfig.xAxis.plotBands.length>0){
                                        $.each(chartConfig.xAxis.plotBands, function(idx, itm){
                                            chartConfig.xAxis.plotBands[idx].value = chartConfig.xAxis.plotBands[idx]['position_'+viewport].x;
                                        })
                                    }

                                }
                                //loop thru Y AXIS plotline/plotbands
                                if(chartConfig.yAxis.plotLines){

                                    if(chartConfig.yAxis.plotLines.length>0){
                                        $.each(chartConfig.yAxis.plotLines, function(idx, itm){
                                            chartConfig.yAxis.plotLines[idx].value = chartConfig.yAxis.plotLines[idx]['position_'+viewport].y;
                                        })
                                    }

                                }
                                if(chartConfig.yAxis.plotBands){

                                    if(chartConfig.yAxis.plotBands.length>0){
                                        $.each(chartConfig.yAxis.plotBands, function(idx, itm){
                                            chartConfig.yAxis.plotBands[idx].value = chartConfig.yAxis.plotBands[idx]['position_'+viewport].y;
                                        })
                                    }

                                }

                            }else{
                                //add hidden notes to footnotes
                                var str = '
Annotations:

';

                                //add a header if required
                                //if(!$('.js-notes-title')){
                                //    str = '
Notes:

';
                                //}
                                $.each(chartConfig.annotations, function(idx, itm){
                                    str+= '
'+itm.title+'
'
                                })
                               /* $.each(chartConfig.xAxis.plotBands, function(idx, itm){
                                    str+= '
'+itm.label.text+'
'
                                })
                                $.each(chartConfig.xAxis.plotLines, function(idx, itm){
                                    str+= '
'+itm.label.text+'
'
                                })
                                $.each(chartConfig.yAxis.plotBands, function(idx, itm){
                                    str+= '
'+itm.label.text+'
'
                                })
                                $.each(chartConfig.yAxis.plotLines, function(idx, itm){
                                    str+= '
'+itm.label.text+'
'
                                })*/
                                str+='
';
                                $('#notes-'+chartId).append(str);
                                // clear any defaults
                                chartConfig.xAxis.plotBands = [];
                                chartConfig.xAxis.plotLines = [];
                                chartConfig.yAxis.plotBands = [];
                                chartConfig.yAxis.plotLines = [];
                                chartConfig.annotations = [];
                            }
                        }
                    }

                    if(smallMultipleSeries){
                        //console.log("small multiples ");
                        //loop through series and create mini-charts
                        var tempSeries = chartConfig.series;
                        chartConfig.chart.width = chartWidth/3;
                        chartConfig.chart.height = chartWidth/3;
                        chartConfig.isSmallMultiple = 'small-multiples';

                        chartConfig.series = [tempSeries[smallMultipleRef]];
                        chartConfig.chart.renderTo = id;
                        chart = new Highcharts.Chart(chartConfig);
                        chartList.push(chart);

                    }else{

                        if(chartConfig.chart.type==='table'){

                        }else{
                            //console.log('push chart ' + chartConfig.chart.type);
                            //chartList = [];
                            // Build chart from config endpoint
                            chartConfig.chart.renderTo = id;
                            chartConfig.chart.height = chartConfig.chart.width * aspectRatio;
                            chart = new Highcharts.Chart(chartConfig);
                            //chartList.push(chart);

                            charts[chartId] = chart;
                        }
                    }

                    delete window["chart-" + chartId]; //clear data from window object after rendering

                }
            }, "script");

    });
});
<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Completed Mutability<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe('Alan');
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };
    // Shouldn't this be "John Smith"?
    // Variables inside a constructor should be private, it isn't stated that
    // functions are immutable but changing it seems to have permitted changes to variables
    expect(aPerson.getFullName()).toBe("Andrews, Penny");
  });

});
<|endoftext|>


<commit_before>var currentPage, pages;
var pageNextHtml = "<button onclick='getCategoryByPage(currentPage+1)'>下一页</button>";
var pagePreviousHtml = "<button onclick='getCategoryByPage(currentPage-1)'>上一页</button>";
var searchKey;
var categories;

$(function () {
    $("#add-category-form").submit(function () {
        $.ajax({
            type          : "POST",
            url           : "add.do",
            data          : new FormData($("#add-category-form")[0]),
            processData   : false,
            contentType   : false,
            success       : function (msg) {
                alert("add success");
                if (pages == 0) {
                    getCategoryByPage(1);
                } else {
                    getCategoryByPage(currentPage);
                }
            }
        });

        return false;
    });

    getCategoryByPage(1);

});
function getCategoryByPage(page) {
    var dataJSON;
    if (searchKey != "" && searchKey != null) {
        dataJSON = JSON.stringify({"page":page, "categoryName":searchKey});
    } else {
        dataJSON = JSON.stringify({"page":page});
    }
    $.ajax({
        type        : "POST",
        url         : "page.do",
        success     : function (msg) {
            refresh(msg);

        },
        data        : dataJSON,
        dataType    : "json",
        contentType : "application/json; charset=utf-8"
    });
}

function refresh(msg) {
    categories = msg.categories;
    pages = msg.pages;
    currentPage = msg.page;

    var table = "
" +
        "
" +
        "
" +
        "ID	" +
        "分类	" +
        "创建时间	" +
        "修改时间	" +
        "操作	" +
        "
" +
        "
";
    for (var index = 0; index < categories.length; index++) {
        var id = categories[index].id;
        var categoryName = categories[index].categoryName;
        table += "
" +
            "" + id + "	" +
            "<input id='category-input-" + id + "' value='" +
            categoryName + "' style='border-width: 0px;'>	" +
            "" + categories[index].createTime + "	" +
            "" + categories[index].updateTime + "	" +
            "" +
            "<button type='button' class='btn btn-primary btn-lg'" +
            "onclick='modifyMode(" + id + ")' " +
            "data-toggle='modal' data-target='#modify-category-modal'>修改" +
            "</button>" +
            "<button type='button' class='btn btn-primary btn-lg'" +
            "onclick='deleteMode(" + id + ")' " +
            "data-toggle='modal' data-target='#delete-category-modal'>删除" +
            "</button>" +
            "	" +
            "
";
    }
    table += "
";

    $("#category-table-div").html(table);

    $("#page-next").html(pageNextHtml);
    $("#page-previous").html(pagePreviousHtml);
    if (currentPage == 1 || pages <= 1) {
        $("#page-previous").html("");
    }
    if (currentPage == pages || pages == 0) {
        $("#page-next").html("");
    }
}

function search() {
    searchKey = $("#searchKey").val();
    getCategoryByPage(1);
}

function modifyMode(id) {
    var categoryName = $("#category-input-"+id).val();
    $("#category-input").val(categoryName);
    $("#modify-id").val(id);
}

function modifySubmit() {
    var categoryName = $("#category-input").val();
    var id = $("#modify-id").val();
    $("#modify-category-modal").modal('hide');
    $.ajax({
        type        : "POST",
        url         : "update.do",
        success     : function (msg) {
            if (msg > 0) {
                alert("modify success");
                $("#category-input" + id).val(categoryName);
            } else {
                alert("modify failure");
            }
        },
        error       : function () {
            alert("服务器请求失败!");
        },
        data        : JSON.stringify({"id":id, "categoryName":categoryName}),
        dataType    : "json",
        contentType : "application/json; charset=utf-8"
    });
}

function deleteMode(id) {
    var categoryName = $("#category-input-"+id).val();
    var deleteWarning = "您确定删除" + categoryName + "及其有关的文章？";
    $("#delete-warning").html(deleteWarning);
    $("#delete-id").val(id);
}

function deleteSubmit() {
    var id = $("#delete-id").val();
    $("#delete-category-modal").modal('hide');
    $.ajax({
        type        : "POST",
        url         : "delete/" + id + ".do",
        success     : function(msg) {
            if (msg > 0) {
                alert("delete success");
                if (categories.length == 1 && currentPage > 1 && currentPage == pages) {
                    getCategoryByPage(currentPage - 1);
                } else if (currentPage != 0) {
                    getCategoryByPage(currentPage);
                }
            } else {
                alert("delete failure");
            }
        },
        error       : function () {
            alert("服务器请求失败!");
        }
    });
}

<commit_msg>update category-manage.js<commit_after>var currentPage, pages;
var pageNextHtml = "<button onclick='getCategoryByPage(currentPage+1)'>下一页</button>";
var pagePreviousHtml = "<button onclick='getCategoryByPage(currentPage-1)'>上一页</button>";
var searchKey;
var categories;

$(function () {
    $("#add-category-form").submit(function () {
        $.ajax({
            type          : "POST",
            url           : "add.do",
            data          : new FormData($("#add-category-form")[0]),
            processData   : false,
            contentType   : false,
            success       : function (msg) {
                                alert("add success");
                                if (pages == 0) {
                                    getCategoryByPage(1);
                                } else {
                                    getCategoryByPage(currentPage);
                                }
                            },
            error         : function () {
                                alert("服务器请求失败");
                            }
        });

        return false;
    });

    getCategoryByPage(1);

});
function getCategoryByPage(page) {
    var dataJSON;
    if (searchKey != "" && searchKey != null) {
        dataJSON = JSON.stringify({"page":page, "categoryName":searchKey});
    } else {
        dataJSON = JSON.stringify({"page":page});
    }
    $.ajax({
        type        : "POST",
        url         : "page.do",
        success     : function (msg) {
                        refresh(msg);
                    },
        error       : function () {
                        alert("服务器请求失败");
                    },
        data        : dataJSON,
        dataType    : "json",
        contentType : "application/json; charset=utf-8"
    });
}

function refresh(msg) {
    categories = msg.categories;
    pages = msg.pages;
    currentPage = msg.page;

    var table = "
" +
        "
" +
        "
" +
        "ID	" +
        "分类	" +
        "创建时间	" +
        "修改时间	" +
        "操作	" +
        "
" +
        "
";
    for (var index = 0; index < categories.length; index++) {
        var category = categories[index];
        var id = category.id;
        var categoryName = category.categoryName;
        table += "
" +
            "" + id + "	" +
            "<input id='category-input-" + id + "' value='" +
            categoryName + "' style='border-width: 0px;'>	" +
            "" + category.createTime + "	" +
            "" + category.updateTime + "	" +
            "" +
            "<button type='button' class='btn btn-primary btn-lg'" +
            "onclick='modifyMode(" + id + ")' " +
            "data-toggle='modal' data-target='#modify-category-modal'>修改" +
            "</button>" +
            "<button type='button' class='btn btn-primary btn-lg'" +
            "onclick='deleteMode(" + id + ")' " +
            "data-toggle='modal' data-target='#delete-category-modal'>删除" +
            "</button>" +
            "	" +
            "
";
    }
    table += "
";

    $("#category-table-div").html(table);

    $("#page-next").html(pageNextHtml);
    $("#page-previous").html(pagePreviousHtml);
    if (currentPage == 1 || pages <= 1) {
        $("#page-previous").html("");
    }
    if (currentPage == pages || pages == 0) {
        $("#page-next").html("");
    }
}

function search() {
    searchKey = $("#searchKey").val();
    getCategoryByPage(1);
}

function modifyMode(id) {
    var categoryName = $("#category-input-"+id).val();
    $("#category-input").val(categoryName);
    $("#modify-id").val(id);
}

function modifySubmit() {
    var categoryName = $("#category-input").val();
    var id = $("#modify-id").val();
    $("#modify-category-modal").modal('hide');
    $.ajax({
        type        : "POST",
        url         : "update.do",
        success     : function (msg) {
                        if (msg > 0) {
                            alert("modify success");
                            $("#category-input" + id).val(categoryName);
                        } else {
                            alert("modify failure");
                        }
                    },
        error       : function () {
                        alert("服务器请求失败!");
                    },
        data        : JSON.stringify({"id":id, "categoryName":categoryName}),
        dataType    : "json",
        contentType : "application/json; charset=utf-8"
    });
}

function deleteMode(id) {
    var categoryName = $("#category-input-"+id).val();
    var deleteWarning = "您确定删除" + categoryName + "及其有关的文章？";
    $("#delete-warning").html(deleteWarning);
    $("#delete-id").val(id);
}

function deleteSubmit() {
    var id = $("#delete-id").val();
    $("#delete-category-modal").modal('hide');
    $.ajax({
        type        : "POST",
        url         : "delete/" + id + ".do",
        success     : function(msg) {
                        if (msg > 0) {
                            alert("delete success");
                            if (categories.length == 1 && currentPage > 1 && currentPage == pages) {
                                getCategoryByPage(currentPage - 1);
                            } else if (currentPage != 0) {
                                getCategoryByPage(currentPage);
                            }
                        } else {
                            alert("delete failure");
                        }
                    },
        error       : function () {
                        alert("服务器请求失败!");
                    }
    });
}

<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe(FILL_ME_IN);
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>Add solutions for AboutMutability koan<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe('Alan');
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe('Alan');
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe('John Smith');

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe('Smith, John');
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe('John');
    expect(aPerson.getLastName()).toBe('Smith');
    expect(aPerson.getFullName()).toBe('John Smith');

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe('Andrews, Penny');
  });

});
<|endoftext|>


<commit_before>/*global $*/

/*global WebSocket*/
/*global createChessBoard*/
/*global updatePlayer*/
/*global console*/
/*global Stomp*/
/*global SockJS*/
/*global headers*/

function StompActions(gameUID, playerName, opponentName, playerColour) {
    "use strict";
    this.oldChessBoard = {};
    this.alertBox = $("#my-alert");
    this.alertBoxText = $("#my-alert .alert");
    this.GAME_STATUS = {
        WHITE_CHECKMATE : "WHITE_CHECKMATE",
        BLACK_CHECKMATE : "BLACK_CHECKMATE",
        STALEMATE : "STALEMATE",
        WHITE_IN_CHECK : "WHITE_IN_CHECK",
        BLACK_IN_CHECK : "BLACK_IN_CHECK"
    };
    this.gameUID = gameUID;
    this.playerName = playerName;
    this.opponentName = opponentName;
    this.playerColour = playerColour;
}

StompActions.prototype = {
    showFadingAlertMessage : function (message) {
        "use strict";
        this.alertBoxText.html(message);
        this.alertBox.css("display", "block");
        this.alertBox.css("opacity", "1");
        this.alertBox.fadeOut(5000);
    },

    showAlertMessage : function (message) {
        "use strict";
        this.alertBoxText.html(message);
        this.alertBox.css("display", "block");
        this.alertBox.css("opacity", "1");
    },

    updateChessBoard : function (chessBoardJson) {
        "use strict";
        createChessBoard(this.playerColour, chessBoardJson);
        this.oldChessBoard = chessBoardJson;
        updatePlayer(chessBoardJson);
    },

    userUpdate : function (message) {
        "use strict";
        if (message.headers.TYPE === "ERROR") {
            this.showFadingAlertMessage(message.body);
            if (this.oldChessBoard !== undefined && !$.isEmptyObject(this.oldChessBoard)) {
                createChessBoard(this.playerColour, this.oldChessBoard);
            }
        } else if (message.headers.TYPE === "UPDATE") {
            this.updateChessBoard(message.body);
        } else if (message.headers.TYPE === "INFO") {
            console.log(message.body);
        }
    },
    topicUpdate : function (message) {
        "use strict";
        if (message.headers.TYPE === "ERROR") {
            this.updateChessBoard(message.body);
        } else if (message.headers.TYPE === "STATUS") {
            switch (message.body) {
            case this.GAME_STATUS.WHITE_CHECKMATE:
                this.showAlertMessage(this.opponentName + " has won the game");
                break;
            case this.GAME_STATUS.BLACK_CHECKMATE:
                this.showAlertMessage(this.playerName + " has won the game");
                break;
            case this.GAME_STATUS.STALEMATE:
                this.showAlertMessage("Game has ended in a draw");
                break;
            case this.GAME_STATUS.WHITE_IN_CHECK:
                this.showFadingAlertMessage(this.playerName + "'s king is in check");
                break;
            case this.GAME_STATUS.BLACK_IN_CHECK:
                this.showFadingAlertMessage(this.opponentName + "'s king is in check");
                break;
            default:
                break;
            }
        } else if (message.headers.TYPE === "INFO") {
            if (/has quit the game$/.test(message.body)) {
                this.showAlertMessage(message.body);
            } else {
                console.log("INFO:" + message.body);
            }
        } else if (message.headers.TYPE === "UPDATE") {
            this.updateChessBoard(message.body);
        }
    }
};

function openStompConnection(websocketURL, headers, stompCallBack) {
    "use strict";
    var stompClient,
        socket,
        USER_UPDATES = "/user/queue/updates",
        TOPIC_UPDATES = "/topic/updates/",
        APP_GET = "/app/get/",
        PRIORITY = {priority : 9},
        APP_QUIT = "/app/quit/";

    if (!(typeof stompCallBack === 'object' && stompCallBack instanceof StompActions)) {
        throw "callback function isn't an instance of StompActions";
    }
    socket = new SockJS(websocketURL);
    stompClient = Stomp.over(socket);
    stompClient.connect(headers, function onStompConnect() {
        stompClient.subscribe(USER_UPDATES, function (message) {
            stompCallBack.userUpdate.call(stompCallBack, message);
        });

        stompClient.subscribe(TOPIC_UPDATES + stompCallBack.gameUID, function (message) {
            stompCallBack.topicUpdate.call(stompCallBack, message);
        });

        $("#quit-btn").click(function () {
            stompClient.send(APP_QUIT + stompCallBack.gameUID, PRIORITY, "quit");
        });
        stompClient.send(APP_GET + stompCallBack.gameUID, PRIORITY, "Get ChessBoard");
    }, function onStompError() {
        stompCallBack.showAlertMessage.call(stompCallBack, "Couldn't connect to the STOMP server");
        console.log("Stomp connection failure");
    });
    return stompClient;
}

function setupStompConnection(stompObject) {
    "use strict";
    var stompCallBack = new StompActions(stompObject.gameUUID, stompObject.playerName, stompObject.opponentName, stompObject.playerColour),
        stompClient = openStompConnection(stompObject.URL, stompObject.headers, stompCallBack);
    return stompClient;
}<commit_msg>replace fading message with fixed message<commit_after>/*global $*/

/*global WebSocket*/
/*global createChessBoard*/
/*global updatePlayer*/
/*global console*/
/*global Stomp*/
/*global SockJS*/
/*global headers*/

/* makes Message disappear when chessboard is clicked*/
function addMessageDialogListener() {
    "use strict";
    $("#chessboard-surround").click(function () {
        $("#my-alert").css("opacity", "0");
    });
}

function StompActions(gameUID, playerName, opponentName, playerColour) {
    "use strict";
    this.oldChessBoard = {};
    this.alertBox = $("#my-alert");
    this.alertBoxText = $("#my-alert .alert");
    this.GAME_STATUS = {
        WHITE_CHECKMATE : "WHITE_CHECKMATE",
        BLACK_CHECKMATE : "BLACK_CHECKMATE",
        STALEMATE : "STALEMATE",
        WHITE_IN_CHECK : "WHITE_IN_CHECK",
        BLACK_IN_CHECK : "BLACK_IN_CHECK"
    };
    this.gameUID = gameUID;
    this.playerName = playerName;
    this.opponentName = opponentName;
    this.playerColour = playerColour;
}

StompActions.prototype = {
    showFadingAlertMessage : function (message) {
        "use strict";
        this.alertBoxText.html(message);
        this.alertBox.css("display", "block");
        this.alertBox.css("opacity", "1");
    },

    showAlertMessage : function (message) {
        "use strict";
        this.alertBoxText.html(message);
        this.alertBox.css("display", "block");
        this.alertBox.css("opacity", "1");
    },

    updateChessBoard : function (chessBoardJson) {
        "use strict";
        createChessBoard(this.playerColour, chessBoardJson);
        this.oldChessBoard = chessBoardJson;
        updatePlayer(chessBoardJson);
    },

    userUpdate : function (message) {
        "use strict";
        if (message.headers.TYPE === "ERROR") {
            this.showFadingAlertMessage(message.body);
            if (this.oldChessBoard !== undefined && !$.isEmptyObject(this.oldChessBoard)) {
                createChessBoard(this.playerColour, this.oldChessBoard);
            }
        } else if (message.headers.TYPE === "UPDATE") {
            this.updateChessBoard(message.body);
        } else if (message.headers.TYPE === "INFO") {
            console.log(message.body);
        }
    },
    topicUpdate : function (message) {
        "use strict";
        if (message.headers.TYPE === "ERROR") {
            this.updateChessBoard(message.body);
        } else if (message.headers.TYPE === "STATUS") {
            switch (message.body) {
            case this.GAME_STATUS.WHITE_CHECKMATE:
                this.showAlertMessage(this.opponentName + " has won the game");
                break;
            case this.GAME_STATUS.BLACK_CHECKMATE:
                this.showAlertMessage(this.playerName + " has won the game");
                break;
            case this.GAME_STATUS.STALEMATE:
                this.showAlertMessage("Game has ended in a draw");
                break;
            case this.GAME_STATUS.WHITE_IN_CHECK:
                this.showFadingAlertMessage(this.playerName + "'s king is in check");
                break;
            case this.GAME_STATUS.BLACK_IN_CHECK:
                this.showFadingAlertMessage(this.opponentName + "'s king is in check");
                break;
            default:
                break;
            }
        } else if (message.headers.TYPE === "INFO") {
            if (/has quit the game$/.test(message.body)) {
                this.showAlertMessage(message.body);
            } else {
                console.log("INFO:" + message.body);
            }
        } else if (message.headers.TYPE === "UPDATE") {
            this.updateChessBoard(message.body);
        }
    }
};

function openStompConnection(websocketURL, headers, stompCallBack) {
    "use strict";
    var stompClient,
        socket,
        USER_UPDATES = "/user/queue/updates",
        TOPIC_UPDATES = "/topic/updates/",
        APP_GET = "/app/get/",
        PRIORITY = {priority : 9},
        APP_QUIT = "/app/quit/";

    if (!(typeof stompCallBack === 'object' && stompCallBack instanceof StompActions)) {
        throw "callback function isn't an instance of StompActions";
    }
    socket = new SockJS(websocketURL);
    stompClient = Stomp.over(socket);
    stompClient.connect(headers, function onStompConnect() {
        stompClient.subscribe(USER_UPDATES, function (message) {
            stompCallBack.userUpdate.call(stompCallBack, message);
        });

        stompClient.subscribe(TOPIC_UPDATES + stompCallBack.gameUID, function (message) {
            stompCallBack.topicUpdate.call(stompCallBack, message);
        });

        $("#quit-btn").click(function () {
            stompClient.send(APP_QUIT + stompCallBack.gameUID, PRIORITY, "quit");
        });
        stompClient.send(APP_GET + stompCallBack.gameUID, PRIORITY, "Get ChessBoard");
    }, function onStompError() {
        stompCallBack.showAlertMessage.call(stompCallBack, "Couldn't connect to the STOMP server");
        console.log("Stomp connection failure");
    });
    return stompClient;
}

function setupStompConnection(stompObject) {
    "use strict";
    var stompCallBack = new StompActions(stompObject.gameUUID, stompObject.playerName, stompObject.opponentName, stompObject.playerColour),
        stompClient = openStompConnection(stompObject.URL, stompObject.headers, stompCallBack);
    return stompClient;
}<|endoftext|>


<commit_before>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe(FILL_ME_IN);
    expect(aPerson.getLastName()).toBe(FILL_ME_IN);
    expect(aPerson.getFullName()).toBe(FILL_ME_IN);

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe(FILL_ME_IN);
  });

});
<commit_msg>answered 4th mutability<commit_after>describe("About Mutability", function() {

  it("should expect object properties to be public and mutable", function () {
    var aPerson = {firstname: "John", lastname: "Smith" };
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should understand that constructed properties are public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    var aPerson = new Person ("John", "Smith");
    aPerson.firstname = "Alan";

    expect(aPerson.firstname).toBe("Alan");
  });

  it("should expect prototype properties to be public and mutable", function () {
    function Person(firstname, lastname)
    {
      this.firstname = firstname;
      this.lastname = lastname;
    }
    Person.prototype.getFullName = function () {
      return this.firstname + " " + this.lastname;
    };

    var aPerson = new Person ("John", "Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return this.lastname + ", " + this.firstname;
    };

    expect(aPerson.getFullName()).toBe("Smith, John");
  });

  it("should know that variables inside a constructor and constructor args are private", function () {
    function Person(firstname, lastname)
    {
      var fullName = firstname + " " + lastname;

      this.getFirstName = function () { return firstname; };
      this.getLastName = function () { return lastname; };
      this.getFullName = function () { return fullName; };
    }
    var aPerson = new Person ("John", "Smith");

    aPerson.firstname = "Penny";
    aPerson.lastname = "Andrews";
    aPerson.fullName = "Penny Andrews";

    expect(aPerson.getFirstName()).toBe("John");
    expect(aPerson.getLastName()).toBe("Smith");
    expect(aPerson.getFullName()).toBe("John Smith");

    aPerson.getFullName = function () {
      return aPerson.lastname + ", " + aPerson.firstname;
    };

    expect(aPerson.getFullName()).toBe("Andrews, Penny");
  });

});
<|endoftext|>