<commit_before>/**
 * Stack
 * notation key
 * a                    = function 'a'
 * [a]                  = an instance of Stack with the function 'a'
 * <action> => <result> = a transformation of the Stack/Stack sequence
 * <action> // <result> = a return value
 * <action> || <result> = the effect of the <action>
 * [a,b,c]              = an array of functions 'a', 'b', 'c'
 * [identity]            = an instance of Stack with 'identity' function
 * [a[b]]               = an instance of Stack with function 'a' and a next [b]
 * [a[b[c]]]            = an instance of Stack with the head [a] and tail [c]
 * {x}                  = some value x
 * [{x},{y}]            = an array of values {x} and {y}
 * a(x)                 = function 'a' invoked with argument {x}
 * a(x, y)              = function 'a' invoked with arguments {x} and {y}
 * ?                    = an object
 * &&                   = logical and
 */
(function(global, undef) {
    function makeArray(val) {
        return Array.isArray(val) ? val : val ? [val] : [];
    }
    function identity() {
        return arguments.length > 1 ? arguments : arguments[0];
    }
    function recur(fn) {
        return function () {
            var bounce = fn.apply(this, arguments);
            while (typeof bounce === "function") {
                bounce = bounce();
            }
            return bounce;
        };
    }
    /**
     * Stack
     * Stack() => [identity] // [identity]
     * Stack(a) => [a] // [a]
     * Stack([a,b,c]) => [c[b[a]]] // [c[b[a]]]
     * Stack(a, [b]) => [a[b]] // [a[b]]
     * @param fn {Function|Array}
     * @param [next {Stack}]
     * @returns {Stack}
     * @constructor
     */
    function Stack(fn, next) {
        if (Array.isArray(fn)) {
            return fn.reduce(function (stack, f) {
                return stack.push(f);
            }, new Stack(fn.shift()));
        }
        if (!(this instanceof Stack)) {
            return new Stack(fn, next);
        }
        this.fn = fn || identity;
        this.next = next || undef;
    }

    /**
     * mung
     * @param prop
     * @param rename
     * @static
     * @returns Stack
     */
    Stack.mung = function (prop, rename) {
        this.prototype[rename] = this.prototype[prop];
        return this;
    };
    /**
     * push
     * [a].push(b) => [b[a]].push(c) => [c[b[a]]] // [c[b[a]]]
     * @param fn {Function}
     * @returns {Stack}
     */
    Stack.prototype.push = function(fn) {
        return new Stack(fn, this);
    };
    /**
     * insert
     * [a].insert(b) => [a[b]] // [b].insert(c) => [a[b[c]]] // [c]
     * @param fn
     * @returns {Stack}
     */
    Stack.prototype.insert = function (fn) {
        return this.next = new Stack(fn, this.next);
    };
    /**
     * index
     * [a[b[c]]].index(1) // [b]
     * @param idx
     * @returns {Stack|undefined}
     */
    Stack.prototype.index = recur(function index(idx) {
        var self = this;
        return function () {
            return !idx ? self : self.next && index.call(self.next, idx - 1);
        };
    });
    /**
     * priorNext
     * [a[b[c[d]]]].priorNext([d]) // [b]
     * @param [stack]
     * @returns {Stack|undefined}
     */
    Stack.prototype.priorNext = recur(function priorNext(stack) {
        var self = this;
        return function () {
            return self.next && self.next.next === stack ? self : self.next && priorNext.call(self.next, stack);
        };
    });
    /**
     * priorFn
     * [a[b[c]]].priorFn(b) // [a]
     * @param fn
     * @returns {Stack|undefined}
     */
    Stack.prototype.priorFn = recur(function priorFn(fn) {
        var self = this;
        return function () {
            return (self.next && self.next.fn === fn) ? self : self.next && priorFn.call(self.next, fn);
        };
    });
    /**
     * isNext
     * [a[b]].isNext([b]) // true
     * @param stack
     * @returns {boolean}
     */
    Stack.prototype.isNext = function (stack) {
        return stack === this.next;
    };
    /**
     * isFn
     * [a].isFn(a) // true
     * @param fn
     * @returns {boolean}
     */
    Stack.prototype.isFn = function (fn) {
        return fn === this.fn;
    };
    /**
     * searchNext
     * [a[b[c]]].searchNext([c]) // [b]
     * @param [stack]
     * @returns {Stack|undefined}
     */
    Stack.prototype.searchNext = recur(function searchNext(stack) {
        var self = this;
        return function () {
            return self.isNext(stack) && self || self.next && searchNext.call(self.next, stack);
        };
    });
    /**
     * searchFn
     * [a[b[c]]].searchFn(b) // [b]
     * @param fn
     * @returns {Stack|undefined}
     */
    Stack.prototype.searchFn = recur(function searchFn(fn) {
        var self = this;
        return function () {
            return self.isFn(fn) && self || self.next && searchFn.call(self.next, fn);
        };
    });
    /**
     * distribute
     * [a[b[c]]].distribute({x}) || a(x), b(x), c(x)
     * [a[b[c]]].distribute({x}, ?) || ?.a(x), ?.b(x), ?.c(x)
     * @param arg
     * @param receiver
     * @returns {undefined}
     */
    Stack.prototype.distribute = recur(function distribute(arg, receiver) {
        var self = this;
        return function () {
            self.fn.call(receiver || self, arg);
            return self.next && distribute.call(self.next, arg, receiver || self);
        };
    });
    /**
     * distributeAll
     * [a[b[c]]].distribute([{x},{y},{z}]) || a(x,y,z), b(x,y,z), c(x,y,z)
     * [a[b[c]]].distribute([{x},{y},{z}], ?) || ?.a(x,y,z), ?.b(x,y,z), ?.c(x,y,z)
     * @param args
     * @param receiver
     * @returns {undefined}
     */
    Stack.prototype.distributeAll = recur(function distributeAll(args, receiver) {
        var self = this;
        return function () {
            self.fn.apply(receiver|| self, args);
            return self.next && distributeAll.call(self.next, makeArray(args), receiver || self);
        };
    });
    /**
     * call
     * [a[b[c]]].call({x}) // c(b(a(x)))
     * [a[b[c]]].call({x}, ?) // ?.c(?.b(?.a(x)))
     * @param arg
     * @param receiver
     * @returns {*}
     */
    Stack.prototype.call = recur(function call(arg, receiver) {
        var self = this;
        return function () {
            var val = self.fn.call(receiver || self, arg);
            return self.next && call.call(self.next, val, receiver) || val;
        };
    });
    /**
     * apply
     * [a[b[c]]].apply([{x},{y},{z}]) // c(b(a(x,y,z)))
     * [a[b[c]]].apply([{x},{y},{z}], ?) // ?.c(?.b(?.a(x,y,z)))
     * @param args
     * @param receiver
     * @returns {*}
     */
    Stack.prototype.apply = recur(function apply(args, receiver) {
        var self = this;
        return function () {
            var val = self.fn.apply(receiver|| self, args);
            return self.next && apply.call(self.next, makeArray(val), receiver) || val;
        }
    });
    /**
     * clone
     * [a[b[c]]].clone() // [a[b[c]]]
     * [a[b[c]]].clone(d) // [d[b[c]]]
     * [a[b[c]]].clone(null, [d]) // [a[d]]
     * [a[b[c]]].clone(d, [e]) // [d[e]]
     * @param fn
     * @param next
     * @returns {Stack}
     */
    Stack.prototype.clone = function (fn, next) {
        return new Stack(fn || this.fn, next || this.next);
    };
    /**
     * tail
     * [a[b[c]]].tail() // [c]
     * @returns {Stack|undefined}
     */
    Stack.prototype.tail = function () {
        return this.searchNext();
    };
    /**
     * unshift
     * [a[b]].unshift(c) => [a[b[c]]] // [c]
     * @param fn
     * @returns {Stack}
     */
    Stack.prototype.unshift = function (fn) {
        return this.tail().insert(fn);
    };
    /**
     * before
     * [a[b[c]]].before(b, d) => [a[d[b[c]]]] // [d[b[c]]]
     * @param a
     * @param b
     * @returns {Stack}
     */
    Stack.prototype.before = function (a, b) {
        return (this.searchFn(a || undef) || this).insert(b);
    };
    /**
     * shift
     * [a[b[c]]].shift() => [a[b]] // [c]
     * @returns {Stack}
     */
    Stack.prototype.shift = function () {
        var p = this.priorNext();
        var removed = p.next;
        p.next = undef;
        return removed;
    };
    /**
     * [a[b[c]]].pop() => [a], [b[c]] // [a]
     * @returns {Stack}
     */
    Stack.prototype.pop = function () {
        this.next = undef;
        return this;
    };
    /**
     * some
     * [a[b[c]]].some() || !c() && !b() && !c() // true|false
     * [a[b[c]]].some({x}) || !c(x) && !b(x) && !c(x) // true|false
     * @param arg
     * @param receiver
     * @returns {boolean}
     */
    Stack.prototype.some = recur(function some(arg, receiver) {
        var self = this;
        return function () {
            var val = self.fn.call(receiver || self, arg);
            return val !== true && !self.next ? false :
                self.next && val !== true ? some.call(self.next, arg, receiver) :
                    true;
        };
    });
    /**
     * every
     * [a[b[c]]].every() || c() && b() && c() // true|false
     * [a[b[c]]].every({x}) || c(x) && b(x) && c(x) // true|false
     * @param arg
     * @param receiver
     * @returns {boolean}
     */
    Stack.prototype.every = recur(function every(arg, receiver) {
        var self = this;
        return function () {
            var val = self.fn.call(receiver || self, arg);
            return val !== false && !self.next ? true :
                self.next && val !== false ? every.call(self.next, arg, receiver) :
                    false;
        };
    });
    /**
     * [a].push(b) = [a].after(b) = [a].composedWith(b) => [b[a]] // [b[a]]            t o h      a o b
     * [a].insert(b) = [a].before(b) = [a].then(b) => [a[b]] // [b]
     * [a[b]].isNext([b]) = [a[b]].composes([b]) // true
     * [a].isFn(a) = [a].with(a) = [a].uses(a) // true
     * [a[b]].searchNext([b]) =
     */
    Stack.mung("push", "of")
        .mung("push", "after")
        .mung("insert", "to")
        .mung("insert", "compose")
        .mung("insert", "before");

//        .mung("isNext", "follows")
//        .mung("isFn", "with")
//        .mung("isFn", "uses")
//        .mung("searchNext", "of")
//        .mung("searchFn", "using")
//        .mung("priorNext", "previousActsOn")
//        .mung("priorFn", "composedWith");

    global.Stack = Stack;
}(this));
<commit_msg>Update stack.js<commit_after>/**
 * Stack
 * notation key
 * a                    = function 'a'
 * [a]                  = an instance of Stack with the function 'a'
 * <action> => <result> = a transformation of the Stack/Stack sequence
 * <action> // <result> = a return value
 * <action> || <result> = the effect of the <action>
 * [a,b,c]              = an array of functions 'a', 'b', 'c'
 * [identity]            = an instance of Stack with 'identity' function
 * [a[b]]               = an instance of Stack with function 'a' and a next [b]
 * [a[b[c]]]            = an instance of Stack with the head [a] and tail [c]
 * {x}                  = some value x
 * [{x},{y}]            = an array of values {x} and {y}
 * a(x)                 = function 'a' invoked with argument {x}
 * a(x, y)              = function 'a' invoked with arguments {x} and {y}
 * ?                    = an object
 * &&                   = logical and
 */
(function(global, undef) {
    function makeArray(val) {
        return Array.isArray(val) ? val : val ? [val] : [];
    }
    function identity() {
        return arguments.length > 1 ? arguments : arguments[0];
    }
    function recur(fn) {
        return function () {
            var bounce = fn.apply(this, arguments);
            while (typeof bounce === "function") {
                bounce = bounce();
            }
            return bounce;
        };
    }
    /**
     * Stack
     * Stack() => [identity] // [identity]
     * Stack(a) => [a] // [a]
     * Stack([a,b,c]) => [c[b[a]]] // [c[b[a]]]
     * Stack(a, [b]) => [a[b]] // [a[b]]
     * @param fn {Function|Array}
     * @param [next {Stack}]
     * @returns {Stack}
     * @constructor
     */
    function Stack(fn, next) {
        if (Array.isArray(fn)) {
            return fn.reduce(function (stack, f) {
                return stack.push(f);
            }, new Stack(fn.shift()));
        }
        if (!(this instanceof Stack)) {
            return new Stack(fn, next);
        }
        this.fn = fn || identity;
        this.next = next || undef;
    }

    /**
     * mung
     * @param prop
     * @param rename
     * @static
     * @returns Stack
     */
    Stack.mung = function (prop, rename) {
        this.prototype[rename] = this.prototype[prop];
        return this;
    };
    /**
     * push
     * [a].push(b) => [b[a]].push(c) => [c[b[a]]] // [c[b[a]]]
     * @param fn {Function}
     * @returns {Stack}
     */
    Stack.prototype.push = function(fn) {
        return new Stack(fn, this);
    };
    /**
     * insert
     * [a].insert(b) => [a[b]] // [b].insert(c) => [a[b[c]]] // [c]
     * @param fn
     * @returns {Stack}
     */
    Stack.prototype.insert = function (fn) {
        return this.next = new Stack(fn, this.next);
    };
    /**
     * index
     * [a[b[c]]].index(1) // [b]
     * @param idx
     * @returns {Stack|undefined}
     */
    Stack.prototype.index = recur(function index(idx) {
        var self = this;
        return function () {
            return !idx ? self : self.next && index.call(self.next, idx - 1);
        };
    });
    /**
     * priorNext
     * [a[b[c[d]]]].priorNext([d]) // [b]
     * @param [stack]
     * @returns {Stack|undefined}
     */
    Stack.prototype.priorNext = recur(function priorNext(stack) {
        var self = this;
        return function () {
            return self.next && self.next.next === stack ? self : self.next && priorNext.call(self.next, stack);
        };
    });
    /**
     * priorFn
     * [a[b[c]]].priorFn(b) // [a]
     * @param fn
     * @returns {Stack|undefined}
     */
    Stack.prototype.priorFn = recur(function priorFn(fn) {
        var self = this;
        return function () {
            return (self.next && self.next.fn === fn) ? self : self.next && priorFn.call(self.next, fn);
        };
    });
    /**
     * isNext
     * [a[b]].isNext([b]) // true
     * @param stack
     * @returns {boolean}
     */
    Stack.prototype.isNext = function (stack) {
        return stack === this.next;
    };
    /**
     * isFn
     * [a].isFn(a) // true
     * @param fn
     * @returns {boolean}
     */
    Stack.prototype.isFn = function (fn) {
        return fn === this.fn;
    };
    /**
     * searchNext
     * [a[b[c]]].searchNext([c]) // [b]
     * @param [stack]
     * @returns {Stack|undefined}
     */
    Stack.prototype.searchNext = recur(function searchNext(stack) {
        var self = this;
        return function () {
            return self.isNext(stack) && self || self.next && searchNext.call(self.next, stack);
        };
    });
    /**
     * searchFn
     * [a[b[c]]].searchFn(b) // [b]
     * @param fn
     * @returns {Stack|undefined}
     */
    Stack.prototype.searchFn = recur(function searchFn(fn) {
        var self = this;
        return function () {
            return self.isFn(fn) && self || self.next && searchFn.call(self.next, fn);
        };
    });
    /**
     * distribute
     * [a[b[c]]].distribute({x}) || a(x), b(x), c(x)
     * [a[b[c]]].distribute({x}, ?) || ?.a(x), ?.b(x), ?.c(x)
     * @param arg
     * @param receiver
     * @returns {undefined}
     */
    Stack.prototype.distribute = recur(function distribute(arg, receiver) {
        var self = this;
        return function () {
            self.fn.call(receiver || self, arg);
            return self.next && distribute.call(self.next, arg, receiver || self);
        };
    });
    /**
     * distributeAll
     * [a[b[c]]].distribute([{x},{y},{z}]) || a(x,y,z), b(x,y,z), c(x,y,z)
     * [a[b[c]]].distribute([{x},{y},{z}], ?) || ?.a(x,y,z), ?.b(x,y,z), ?.c(x,y,z)
     * @param args
     * @param receiver
     * @returns {undefined}
     */
    Stack.prototype.distributeAll = recur(function distributeAll(args, receiver) {
        var self = this;
        return function () {
            self.fn.apply(receiver|| self, args);
            return self.next && distributeAll.call(self.next, makeArray(args), receiver || self);
        };
    });
    /**
     * call
     * [a[b[c]]].call({x}) // c(b(a(x)))
     * [a[b[c]]].call({x}, ?) // ?.c(?.b(?.a(x)))
     * @param arg
     * @param receiver
     * @returns {*}
     */
    Stack.prototype.call = recur(function call(arg, receiver) {
        var self = this;
        return function () {
            var val = self.fn.call(receiver || self, arg);
            return self.next && call.call(self.next, val, receiver) || val;
        };
    });
    /**
     * apply
     * [a[b[c]]].apply([{x},{y},{z}]) // c(b(a(x,y,z)))
     * [a[b[c]]].apply([{x},{y},{z}], ?) // ?.c(?.b(?.a(x,y,z)))
     * @param args
     * @param receiver
     * @returns {*}
     */
    Stack.prototype.apply = recur(function apply(args, receiver) {
        var self = this;
        return function () {
            var val = self.fn.apply(receiver|| self, args);
            return self.next && apply.call(self.next, makeArray(val), receiver) || val;
        }
    });
    /**
     * clone
     * [a[b[c]]].clone() // [a[b[c]]]
     * [a[b[c]]].clone(d) // [d[b[c]]]
     * [a[b[c]]].clone(null, [d]) // [a[d]]
     * [a[b[c]]].clone(d, [e]) // [d[e]]
     * @param fn
     * @param next
     * @returns {Stack}
     */
    Stack.prototype.clone = function (fn, next) {
        return new Stack(fn || this.fn, next || this.next);
    };
    /**
     * tail
     * [a[b[c]]].tail() // [c]
     * @returns {Stack|undefined}
     */
    Stack.prototype.tail = function () {
        return this.searchNext();
    };
    /**
     * unshift
     * [a[b]].unshift(c) => [a[b[c]]] // [c]
     * @param fn
     * @returns {Stack}
     */
    Stack.prototype.unshift = function (fn) {
        return this.tail().insert(fn);
    };
    /**
     * before
     * [a[b[c]]].before(b, d) => [a[d[b[c]]]] // [d[b[c]]]
     * @param a
     * @param b
     * @returns {Stack}
     */
    Stack.prototype.before = function (a, b) {
        return (this.searchFn(a || undef) || this).insert(b);
    };
    /**
     * shift
     * [a[b[c]]].shift() => [a[b]] // [c]
     * @returns {Stack}
     */
    Stack.prototype.shift = function () {
        var p = this.priorNext();
        var removed = p.next;
        p.next = undef;
        return removed;
    };
    /**
     * [a[b[c]]].pop() => [a], [b[c]] // [a]
     * @returns {Stack}
     */
    Stack.prototype.pop = function () {
        this.next = undef;
        return this;
    };
    /**
     * some
     * [a[b[c]]].some() || !c() && !b() && !c() // true|false
     * [a[b[c]]].some({x}) || !c(x) && !b(x) && !c(x) // true|false
     * @param arg
     * @param receiver
     * @returns {boolean}
     */
    Stack.prototype.some = recur(function some(arg, receiver) {
        var self = this;
        return function () {
            var val = self.fn.call(receiver || self, arg);
            return val !== true && !self.next ? false :
                self.next && val !== true ? some.call(self.next, arg, receiver) :
                    true;
        };
    });
    /**
     * every
     * [a[b[c]]].every() || c() && b() && c() // true|false
     * [a[b[c]]].every({x}) || c(x) && b(x) && c(x) // true|false
     * @param arg
     * @param receiver
     * @returns {boolean}
     */
    Stack.prototype.every = recur(function every(arg, receiver) {
        var self = this;
        return function () {
            var val = self.fn.call(receiver || self, arg);
            return val !== false && !self.next ? true :
                self.next && val !== false ? every.call(self.next, arg, receiver) :
                    false;
        };
    });
    /**
     * [a].push(b) = [a].after(b) = [a].composedWith(b) => [b[a]] // [b[a]]            t o h      a o b
     * [a].insert(b) = [a].before(b) = [a].then(b) => [a[b]] // [b]
     * [a[b]].isNext([b]) = [a[b]].composes([b]) // true
     * [a].isFn(a) = [a].with(a) = [a].uses(a) // true
     * [a[b]].searchNext([b]) =
     */
    Stack.mung("push", "of")
        .mung("push", "after")
        .mung("insert", "to")
        .mung("insert", "compose");
        //.mung("insert", "before"); before already used, aop-style, should add after in the same vein
        //insert, push, etc. operations should take Stack; insertFn, pushFn, etc. should take Fn
        //need a way to name and index stacks for reporting/debugging/graphing
        //setup tests for alternate grammars
        //add branching logic (probably limited by the stack limits on # of branches)

//        .mung("isNext", "follows")
//        .mung("isFn", "with")
//        .mung("isFn", "uses")
//        .mung("searchNext", "of")
//        .mung("searchFn", "using")
//        .mung("priorNext", "previousActsOn")
//        .mung("priorFn", "composedWith");

    global.Stack = Stack;
}(this));
<|endoftext|>


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

//var exec = require('child_process').exec;
var fs = require('fs');

//var security = keystone.security;

//var Page = keystone.list('Page');

var privateSettings = require('../../private/privatesettings.json');
var publicSettings = require('../../public/js/publicsettings.json');

exports.getprivate = function(req, res) {
  debugger;

  //Ensure the user making the request is a Keystone Admin
  var isAdmin = req.user.get('isAdmin');
  if(!isAdmin) {
    return res.apiError(403, 'Not allowed to access this API. Not Keystone Admin.');
  }

  //Since it's possible to spoof the Keystone Admin setting in the current version of the User model,
  //This is a check to make sure the user is a ConnexstCMS Superuser
  var suPromise = verifySuperUser(req, res);

  //Executes if the user is a verified superuser.
  suPromise.then(function(result) {
    debugger;

    //Read in the privatesettings.json file.
    fs.readFile('private/privatesettings.json', 'utf8', function(err, data) {

      //Error Handling.
      if(err) {
        console.log('Error in /api/serversettings/getprivate while trying to read privatesettings.json file.');
        console.log(err);
        //response.send(false); //Send failure
        res.apiError('file error', err);

      } else {

        //Parse the JSON data into an object.
        privateSettings = JSON.parse(data);

        //Send the data stored in the JSON file.
        res.apiResponse({
          privateSettings: privateSettings
        });
      }
    });

  //Rejects the API if the user is not a superuser.
  }, function(err) {
    console.log('/api/serversettings/getprivate exited with error '+err);
  });

}

exports.saveprivate = function(req, res) {
  //Ensure the user making the request is a Keystone Admin
  var isAdmin = req.user.get('isAdmin');
  if(!isAdmin) {
    return res.apiError(403, 'Not allowed to access this API. Not Keystone Admin.');
  }

  //Since it's possible to spoof the Keystone Admin setting in the current version of the User model,
  //This is a check to make sure the user is a ConnexstCMS Superuser
  //var admins = keystone.get('admins');
  var superusers = getSuperuserList();
  var userId = req.user.get('id');
  if(superusers.indexOf(userId) == -1) {
    return res.apiError(403, 'Not allowed to access this API. Not ConnextCMS Superuser')
  }

  var data = req.query;

  //Write out the server_settings.json file.
  fs.writeFile('private/privatesettings.json', JSON.stringify(data, null, 4), function (err) {
    if(err) {
      console.log('Error in /api/serversettings/save while trying to write serversettings.json file.');
      console.log(err);
      //response.send(false); //Send failure
      res.apiError('file error', err);

    } else {
      console.log('/api/serversettings/save executed. privatesettings.json updated.');
      //response.send(true); //Send acknowledgement that setting were saved successfully.
      res.apiResponse({
        success: true,
      });
    }
  });
}

exports.savepublic = function(req, res) {
  //Ensure the user making the request is a Keystone Admin
  var isAdmin = req.user.get('isAdmin');
  if(!isAdmin) {
    return res.apiError(403, 'Not allowed to access this API. Not Keystone Admin.');
  }

  //Since it's possible to spoof the Keystone Admin setting in the current version of the User model,
  //This is a check to make sure the user is a ConnexstCMS Superuser
  //var admins = keystone.get('admins');
  var superusers = getSuperuserList();
  var userId = req.user.get('id');
  if(superusers.indexOf(userId) == -1) {
    return res.apiError(403, 'Not allowed to access this API. Not ConnextCMS Superuser')
  }

  var data = req.query;

  //Write out the server_settings.json file.
  fs.writeFile('public/js/publicsettings.json', JSON.stringify(data, null, 4), function (err) {
    if(err) {
      console.log('Error in /api/serversettings/savepublic while trying to write serversettings.json file.');
      console.log(err);
      //response.send(false); //Send failure
      res.apiError('file error', err);

    } else {
      console.log('/api/serversettings/savepublic executed. publicsettings.json updated.');
      //response.send(true); //Send acknowledgement that setting were saved successfully.
      res.apiResponse({
        success: true,
      });
    }
  });
}

//This function reads in the publicsettings.json file and returns the list of superusers as a csv separated string.
var verifySuperUser = function(req, res) {
  var promise = new Promise;

  //Read in the publicsettings.json file.
  fs.readFile('public/js/publicsettings.json', 'utf8', function(err, data) {
    debugger;

    //Error handling
    if(err) {
      console.log('Error in routes/api/serversetting.js/verifySuperUser() while trying to read publicsettings.json file.');
      console.log(err);

      res.apiError(404, err)
      promise.reject(404);

    } else {

      //Parse the JSON data into an object.
      publicSettings = JSON.parse(data);

      //Handle different permutations of the superUsers array/string.
      if(typeof(publicSettings.superUsers) == "string") {
        var superusers = publicSettings.superUsers;
      } else {
        var superusers = publicSettings.superUsers.join();
      }

      //Get the userID for user making this API request.
      var userId = req.user.get('id');

      //Reject if user ID is not listed in the superusers list.
      if(superusers.indexOf(userId) == -1) {
        res.apiError(403, 'Not allowed to access this API. Not ConnextCMS Superuser');
        promise.reject(403);
      //Resolve if the user ID *is* listed in the superusers list.
      } else {
        promise.resolve();
      }
    }
  });

  return promise;
}<commit_msg>Refining the serversettings.js API and permissions<commit_after>var async = require('async'),
        keystone = require('keystone');

//var exec = require('child_process').exec;
var fs = require('fs');
var Promise = require('mpromise');

//var security = keystone.security;

//var Page = keystone.list('Page');

var privateSettings = require('../../private/privatesettings.json');
var publicSettings = require('../../public/js/publicsettings.json');

exports.getprivate = function(req, res) {
  debugger;

  //Ensure the user making the request is a Keystone Admin
  var isAdmin = req.user.get('isAdmin');
  if(!isAdmin) {
    return res.apiError(403, 'Not allowed to access this API. Not Keystone Admin.');
  }

  //Since it's possible to spoof the Keystone Admin setting in the current version of the User model,
  //This is a check to make sure the user is a ConnexstCMS Superuser
  var suPromise = verifySuperUser(req, res);

  //Executes if the user is a verified superuser.
  suPromise.then(function(result) {
    debugger;

    //Read in the privatesettings.json file.
    fs.readFile('private/privatesettings.json', 'utf8', function(err, data) {

      //Error Handling.
      if(err) {
        console.log('Error in /api/serversettings/getprivate while trying to read privatesettings.json file.');
        console.log(err);
        //response.send(false); //Send failure
        res.apiError('file error', err);

      } else {

        //Parse the JSON data into an object.
        privateSettings = JSON.parse(data);

        //Send the data stored in the JSON file.
        res.apiResponse({
          privateSettings: privateSettings
        });
      }
    });

  //Rejects the API if the user is not a superuser.
  }, function(err) {
    console.log('/api/serversettings/getprivate exited with error '+err);
  });

}

exports.saveprivate = function(req, res) {
  //Ensure the user making the request is a Keystone Admin
  var isAdmin = req.user.get('isAdmin');
  if(!isAdmin) {
    return res.apiError(403, 'Not allowed to access this API. Not Keystone Admin.');
  }

  //Since it's possible to spoof the Keystone Admin setting in the current version of the User model,
  //This is a check to make sure the user is a ConnexstCMS Superuser
  //var admins = keystone.get('admins');
  var superusers = getSuperuserList();
  var userId = req.user.get('id');
  if(superusers.indexOf(userId) == -1) {
    return res.apiError(403, 'Not allowed to access this API. Not ConnextCMS Superuser')
  }

  var data = req.query;

  //Write out the server_settings.json file.
  fs.writeFile('private/privatesettings.json', JSON.stringify(data, null, 4), function (err) {
    if(err) {
      console.log('Error in /api/serversettings/save while trying to write serversettings.json file.');
      console.log(err);
      //response.send(false); //Send failure
      res.apiError('file error', err);

    } else {
      console.log('/api/serversettings/save executed. privatesettings.json updated.');
      //response.send(true); //Send acknowledgement that setting were saved successfully.
      res.apiResponse({
        success: true,
      });
    }
  });
}

exports.savepublic = function(req, res) {
  //Ensure the user making the request is a Keystone Admin
  var isAdmin = req.user.get('isAdmin');
  if(!isAdmin) {
    return res.apiError(403, 'Not allowed to access this API. Not Keystone Admin.');
  }

  //Since it's possible to spoof the Keystone Admin setting in the current version of the User model,
  //This is a check to make sure the user is a ConnexstCMS Superuser
  //var admins = keystone.get('admins');
  var superusers = getSuperuserList();
  var userId = req.user.get('id');
  if(superusers.indexOf(userId) == -1) {
    return res.apiError(403, 'Not allowed to access this API. Not ConnextCMS Superuser')
  }

  var data = req.query;

  //Write out the server_settings.json file.
  fs.writeFile('public/js/publicsettings.json', JSON.stringify(data, null, 4), function (err) {
    if(err) {
      console.log('Error in /api/serversettings/savepublic while trying to write serversettings.json file.');
      console.log(err);
      //response.send(false); //Send failure
      res.apiError('file error', err);

    } else {
      console.log('/api/serversettings/savepublic executed. publicsettings.json updated.');
      //response.send(true); //Send acknowledgement that setting were saved successfully.
      res.apiResponse({
        success: true,
      });
    }
  });
}

//This function reads in the publicsettings.json file and returns the list of superusers as a csv separated string.
var verifySuperUser = function(req, res) {
  debugger;
  var promise = new Promise;

  //Read in the publicsettings.json file.
  fs.readFile('public/js/publicsettings.json', 'utf8', function(err, data) {
    debugger;

    //Error handling
    if(err) {
      console.log('Error in routes/api/serversetting.js/verifySuperUser() while trying to read publicsettings.json file.');
      console.log(err);

      res.apiError(404, err)
      promise.reject(404);

    } else {

      //Parse the JSON data into an object.
      publicSettings = JSON.parse(data);

      //Handle different permutations of the superUsers array/string.
      if(typeof(publicSettings.superUsers) == "string") {
        var superusers = publicSettings.superUsers;
      } else {
        var superusers = publicSettings.superUsers.join();
      }

      //Get the userID for user making this API request.
      var userId = req.user.get('id');

      //Reject if user ID is not listed in the superusers list.
      if(superusers.indexOf(userId) == -1) {
        res.apiError(403, 'Not allowed to access this API. Not ConnextCMS Superuser');
        promise.reject(403);
      //Resolve if the user ID *is* listed in the superusers list.
      } else {
        promise.resolve();
      }
    }
  });

  return promise;
}<|endoftext|>


<commit_before>(function (window, io, $, _, Backbone, Lawnchair, location, app) {
    "use strict";

    var DB = "store:",
        ID = "id",
        SECURE = "{{secure}}" == "true",
        PORT = "{{port}}";

    app.middle = app.middle || {};
    app.middle.session = app.utils.uuid();

    _.extend(app.middle, Backbone.Events);

    // *******************************************************************************
    // using socket.io for Backbone.sync
    // *******************************************************************************

    function readAsync(store, segments, options) {
        var url = segments.join('/');

        return store.get(DB + url, function (result) {
            return options && options.success && options.success(result && result.val);
        });
    }

    function updateLocal(store, model, segments, options, changed, url, data) {
        changed = changed || model.changedAttributes();

        if (!changed) {
            return;
        }

        url = url || segments.join('/');
        data = data || model.toJSON();

        return store.save({
            key:DB + url,
            val:data
        }, function (result) {
            app.log("local update", result);
            return options && options.success && options.success(result);
        });
    }

    function updateRemote(socket, model, segments, options, changed, url, data) {
        changed = changed || model.changedAttributes();

        if (!changed) {
            return;
        }

        url = url || segments.join('/');
        data = data || model.toJSON();

        return socket.emit("store-update", url, data, changed, function (err, result) {
            if (err) {
                if (options && options.errror) {
                    return options.errror(err);
                }

                return app.error("sync failed", url, data, changed, err);
            }

            app.log("remote update", result);

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

    function updateAsync(socket, store, model, segments, options) {
        var changed = model.changedAttributes();

        if (!changed) {
            return;
        }

        var url = segments.join('/'),
            data = model.toJSON();

        updateRemote(socket, model, segments, {}, changed, url, data);
        updateLocal(store, model, segments, options, changed, url, data);
    }

    function asyncSync(socket, store, method, model, segments, options) {
        if ('read' === method) {
            return readAsync(store, segments, options);
        }

        if ("update" === method) {
            return updateAsync(socket, store, model, segments, options);
        }

        throw new Error("not yet supported");
    }

    function sync(socket, store) {
        return function (method, model, options) {
            var url = model.url(),
                segments = url.split('/'),
                base = segments.shift();

            if (base === 'async') {
                return asyncSync(socket, store, method, model, segments, options);
            }

            var data = model.toJSON(),
                changed = model.changedAttributes();

            socket.emit("store", url, data, changed, function (err, result) {
                if (err) {
                    if (options && options.errror) {
                        return options.errror(err);
                    }

                    return app.error("sync failed", url, data, changed, err);
                }

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

            return undefined;
        };
    }

    // *******************************************************************************
    // Starting connections. loading device id, etc.
    // *******************************************************************************

    function getServerURL() {
        var protocol = SECURE ? "https://" : "http://",
            port = PORT || location.port;

        if (port) {
            port = ":" + port;
        }

        return protocol + location.hostname + port;
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, _args) {
        var args = Array.prototype.slice.call(_args),
            params = [
                "log",
                level,
                app.middle.id,
                app.middle.session,
                new Date()
            ];

        args.forEach(function (arg) {
            var param = convert(arg);

            params.push(param);
        });

        return socket.emit.apply(socket, params);
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function decorate(socket) {
        return {
            emit:emitter(socket)
        };
    }

    app.starter.$(function (next) {
        new Lawnchair({ name: "middle" }, function (store) {
            store.get(ID, function (device) {
                app.middle.id = (device && device.id) || app.utils.uuid();

                if (!device) {
                    store.save({
                        key:ID,
                        id:app.middle.id
                    });
                }

                var url = getServerURL(),
                    socket = io.connect(url),
                    app_log = app.log,
                    app_debug = app.debug,
                    app_error = app.error;

                app.middle.emit = emitter(socket);

                var decorated = decorate(socket, store);

                app.middle.sync = sync(decorated);

                socket.on('connect', function (props) {
                    app.log = function () {
                        return log(socket, "info", arguments);
                    };
                    app.debug = function () {
                        return log(socket, "debug", arguments);
                    };
                    app.error = function () {
                        return log(socket, "error", arguments);
                    };
                    app.middle.trigger("online", app.middle.id, app.middle.session)
                    app.log("online");
                });
                socket.on('disconnect', function (props) {
                    app.log = app_log;
                    app.debug = app_debug;
                    app.error = app_error;
                    app.middle.trigger("offline", app.middle.id, app.middle.session)
                    app.log("offline", app.middle.id, app.middle.session);
                });

                return next();
            });
        });
    });
})(window, io, $, _, Backbone, Lawnchair, window.location, window["jolira-app"]);
<commit_msg>cleanup & simplification<commit_after>(function (window, io, $, _, Backbone, Lawnchair, location, app) {
    "use strict";

    var ID = "id",
        SECURE = "{{secure}}" == "true",
        PORT = "{{port}}";

    app.middle = app.middle || {};
    app.middle.session = app.utils.uuid();

    _.extend(app.middle, Backbone.Events);

    // *******************************************************************************
    // using socket.io for Backbone.sync
    // *******************************************************************************

    function open(name, cb) {
        new Lawnchair({ name: name }, cb);
    }

    function readAsync(collection, id, options) {
        return open(collection, function(store) {
            return store.get(id, function (result) {
                return options && options.success && options.success(result && result.val);
            });
        });
    }

    function updateLocal(model, collection, id, options, changed, data) {
        changed = changed || model.changedAttributes();

        if (!changed) {
            return;
        }

        return open(collection, function(store) {
            data = data || model.toJSON();

            return store.save({
                key:id,
                val:data
            }, function (result) {
                app.log("local update", result);
                return options && options.success && options.success(result);
            });
        });
    }

    function updateRemote(socket, model, collection, id, options, changed, data) {
        changed = changed || model.changedAttributes();

        if (!changed) {
            return;
        }

        data = data || model.toJSON();

        return socket.emit("store-update", id, data, changed, function (err, result) {
            if (err) {
                if (options && options.errror) {
                    return options.errror(err);
                }

                return app.error("sync failed", collection, id, data, changed, err);
            }

            app.log("remote update", result);

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

    function updateAsync(socket, model, collection, id, options) {
        var changed = model.changedAttributes();

        if (!changed) {
            return;
        }

        var data = model.toJSON();

        updateRemote(socket, model, collection, id, undefined, changed, data);
        updateLocal(model, collection, id, options, changed, data);
    }

    function asyncSync(socket, method, model, collection, id, options) {
        if ('read' === method) {
            return readAsync(collection, id, options);
        }

        if ("update" === method) {
            return updateAsync(socket, model, collection, id, options);
        }

        throw new Error("not yet supported");
    }

    function sync(socket) {
        return function (method, model, options) {
            var url = model.url(),
                segments = url.split('/'),
                type = segments.shift(),
                collection = segments.shift(),
                id = segments.join('/');

            if (type === 'async') {
                return asyncSync(socket, method, model, collection, id, options);
            }

            throw new Error("unsupported url " + url);
        };
    }

    // *******************************************************************************
    // Starting connections. loading device id, etc.
    // *******************************************************************************

    function getServerURL() {
        var protocol = SECURE ? "https://" : "http://",
            port = PORT || location.port;

        if (port) {
            port = ":" + port;
        }

        return protocol + location.hostname + port;
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, _args) {
        var args = Array.prototype.slice.call(_args),
            params = [
                "log",
                level,
                app.middle.id,
                app.middle.session,
                new Date()
            ];

        args.forEach(function (arg) {
            var param = convert(arg);

            params.push(param);
        });

        return socket.emit.apply(socket, params);
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function decorate(socket) {
        return {
            emit:emitter(socket)
        };
    }

    app.starter.$(function (next) {
        new Lawnchair({ name: "middle" }, function (store) {
            store.get(ID, function (device) {
                app.middle.id = (device && device.id) || app.utils.uuid();

                if (!device) {
                    store.save({
                        key:ID,
                        id:app.middle.id
                    });
                }

                var url = getServerURL(),
                    socket = io.connect(url),
                    app_log = app.log,
                    app_debug = app.debug,
                    app_error = app.error;

                app.middle.emit = emitter(socket);

                var decorated = decorate(socket, store);

                app.middle.sync = sync(decorated);

                socket.on('connect', function (props) {
                    app.log = function () {
                        return log(socket, "info", arguments);
                    };
                    app.debug = function () {
                        return log(socket, "debug", arguments);
                    };
                    app.error = function () {
                        return log(socket, "error", arguments);
                    };
                    app.middle.trigger("online", app.middle.id, app.middle.session)
                    app.log("online");
                });
                socket.on('disconnect', function (props) {
                    app.log = app_log;
                    app.debug = app_debug;
                    app.error = app_error;
                    app.middle.trigger("offline", app.middle.id, app.middle.session)
                    app.log("offline", app.middle.id, app.middle.session);
                });

                return next();
            });
        });
    });
})(window, io, $, _, Backbone, Lawnchair, window.location, window["jolira-app"]);
<|endoftext|>


<commit_before>var ignoreUrlChange = false;
var ignoreWaypoints = true;

var deHash = function (hashString) {
  return hashString.slice(1);
};

Session.setDefault('urlHash', location.hash);
$(window).on('hashchange', function () {
  Session.set('urlHash', location.hash);
});

// need an actual function to only debounce inside the if statement
var actuallyUpdateUrl = _.debounce(function (el) {
  var docsType = Session.get("fullApi") ? "full" : "basic";
  ignoreUrlChange = true;
  window.location.replace("#/" + docsType + "/" + el.id);
}, 100);

var updateUrlFromWaypoint = function (el) {
  if (! ignoreWaypoints) {
    actuallyUpdateUrl(el);
  }
};

Meteor.startup(function () {
  Tracker.autorun(function () {
    var docsType = Session.get("fullApi") ? "full" : "basic";
    Tracker.afterFlush(function () {
      $.waypoints('destroy');

      setTimeout(function () {
        $('.main-content :not(.hidden) [id]').each(function (i, el) {
          if (! $("#nav [href='#/" + docsType + '/' + el.id + "']").get(0)) {
            // only add waypoints to things that have sidebar links
            return;
          }

          $(el).waypoint(function() {
            updateUrlFromWaypoint(this);
          }, { context: $('.main-content') });
        });
      }, 0);
    });
  });
});

Tracker.autorun(function () {
  // returns a "location" like object with all of the url parts
  var current = Session.get('urlHash');

  // If the URL changes from a waypoint, do nothing
  if (ignoreUrlChange) {
    ignoreUrlChange = false;
    return;
  }

  // If the URL changes, close the sidebar
  Session.set("sidebarOpen", false);

  // redirect routes with no trailing slash
  if (current === "#/basic") {
    navigate("#/basic/");
    return;
  } else if (current === "#/full") {
    navigate("#/full/");
    return;
  }

  if (current.match(/^#\/basic\//)) {
    Session.set("fullApi", false);
  } else if (current.match(/^#\/full\//)) {
    Session.set("fullApi", true);
  } else {
    if (current) {
      // XXX COMPAT WITH old docs
      navigate("#/full/" + deHash(current));
    } else {
      navigate("#/basic/");
    }
    return;
  }

  Tracker.afterFlush(function () {
    setTimeout(function () {
      var targetLocation;

      var id = current.split('/')[2];

      if (! id) {
        // will scroll to the very top
        id = "main";
      }

      var selector = '#' + id;
      var foundElement = $(selector);
      if (foundElement.get(0)) {
        targetLocation = $(".main-content").scrollTop() + foundElement.offset().top - $(".main-content").offset().top;
      }

      ignoreWaypoints = true;
      $(".main-content").animate({
          scrollTop: targetLocation
      }, 500, function () {
        ignoreWaypoints = false;
      });
    }, 0);
  });
});
<commit_msg>Make the scrolling selector more specific<commit_after>var ignoreUrlChange = false;
var ignoreWaypoints = true;

var deHash = function (hashString) {
  return hashString.slice(1);
};

Session.setDefault('urlHash', location.hash);
$(window).on('hashchange', function () {
  Session.set('urlHash', location.hash);
});

// need an actual function to only debounce inside the if statement
var actuallyUpdateUrl = _.debounce(function (el) {
  var docsType = Session.get("fullApi") ? "full" : "basic";
  ignoreUrlChange = true;
  window.location.replace("#/" + docsType + "/" + el.id);
}, 100);

var updateUrlFromWaypoint = function (el) {
  if (! ignoreWaypoints) {
    actuallyUpdateUrl(el);
  }
};

Meteor.startup(function () {
  Tracker.autorun(function () {
    var docsType = Session.get("fullApi") ? "full" : "basic";
    Tracker.afterFlush(function () {
      $.waypoints('destroy');

      setTimeout(function () {
        $('.main-content :not(.hidden) [id]').each(function (i, el) {
          if (! $("#nav [href='#/" + docsType + '/' + el.id + "']").get(0)) {
            // only add waypoints to things that have sidebar links
            return;
          }

          $(el).waypoint(function() {
            updateUrlFromWaypoint(this);
          }, { context: $('.main-content') });
        });
      }, 0);
    });
  });
});

Tracker.autorun(function () {
  // returns a "location" like object with all of the url parts
  var current = Session.get('urlHash');

  // If the URL changes from a waypoint, do nothing
  if (ignoreUrlChange) {
    ignoreUrlChange = false;
    return;
  }

  // If the URL changes, close the sidebar
  Session.set("sidebarOpen", false);

  // redirect routes with no trailing slash
  if (current === "#/basic") {
    navigate("#/basic/");
    return;
  } else if (current === "#/full") {
    navigate("#/full/");
    return;
  }

  if (current.match(/^#\/basic\//)) {
    Session.set("fullApi", false);
  } else if (current.match(/^#\/full\//)) {
    Session.set("fullApi", true);
  } else {
    if (current) {
      // XXX COMPAT WITH old docs
      navigate("#/full/" + deHash(current));
    } else {
      navigate("#/basic/");
    }
    return;
  }

  Tracker.afterFlush(function () {
    setTimeout(function () {
      var targetLocation;

      var id = current.split('/')[2];

      if (! id) {
        // will scroll to the very top
        id = "main";
      }

      // XXX this selector is tied to the structure of the document so tightly
      // because sometimes we have two elements with the same id.
      // For example: "Quick start" section appears in both basic docs and full
      // docs. Since we hide parts of DOM with CSS the user doesn't see both at
      // the same time but they are still both in the DOM. New browsers allow us
      // to query by id even if ids repeat themselves. We cannot change it
      // easily because the markdown parser always produces an id for headings.
      var selector = "#main>:not(.hidden) #" + id;
      var foundElement = $(selector);
      if (foundElement.get(0)) {
        targetLocation = $(".main-content").scrollTop() + foundElement.offset().top - $(".main-content").offset().top;
      }

      ignoreWaypoints = true;
      $(".main-content").animate({
          scrollTop: targetLocation
      }, 500, function () {
        ignoreWaypoints = false;
      });
    }, 0);
  });
});
<|endoftext|>


<commit_before>const mkdirp = require('mkdirp')
const rollup = require('rollup').rollup
const vue = require('rollup-plugin-vue')
const buble = require('rollup-plugin-buble')
const replace = require('rollup-plugin-replace')
const cjs = require('rollup-plugin-commonjs')
const node = require('rollup-plugin-node-resolve')
const scss = require('rollup-plugin-scss')
const uglify = require('uglify-js')

// Make sure dist dir exists
mkdirp('dist')

const {
  logError,
  write,
  banner,
  name,
  moduleName,
  version,
} = require('./utils')

function rollupBundle ({ env, entry }) {
  return rollup({
    entry: entry || 'src/index.js',
    plugins: [
      scss({ output: false }),
      node(),
      cjs(),
      vue({ compileTemplate: true, css: false }),
      replace(Object.assign({
        __VERSION__: version,
      }, env)),
      buble({
        objectAssign: 'Object.assign',
      }),
    ],
  })
}

const bundleOptions = {
  banner,
  exports: 'named',
  format: 'umd',
  moduleName,
}

function createBundle ({ name, env, entry }) {
  return rollupBundle({
    env,
    entry,
  }).then(function (bundle) {
    const code = bundle.generate(bundleOptions).code
    if (/min$/.test(name)) {
      const minified = uglify.minify(code, {
        fromString: true,
        output: {
          preamble: banner,
          ascii_only: true, // eslint-disable-line camelcase
        },
      }).code
      return write(`dist/${name}.js`, minified)
    } else {
      return write(`dist/${name}.js`, code)
    }
  }).catch(logError)
}

// Browser bundle (can be used with script)
createBundle({
  name: `${name}`,
  env: {
    'process.env.NODE_ENV': '"development"',
  },
})

// Commonjs bundle (preserves process.env.NODE_ENV) so
// the user can replace it in dev and prod mode
createBundle({
  name: `${name}.esm`,
  env: {},
})

// Minified version for browser
createBundle({
  name: `${name}.min`,
  env: {
    'process.env.NODE_ENV': '"production"',
  },
})
<commit_msg>🔧 Handle vue and jsx files with rollup<commit_after>const mkdirp = require('mkdirp')
const rollup = require('rollup').rollup
const vue = require('rollup-plugin-vue')
const buble = require('rollup-plugin-buble')
const replace = require('rollup-plugin-replace')
const cjs = require('rollup-plugin-commonjs')
const node = require('rollup-plugin-node-resolve')
const scss = require('rollup-plugin-scss')
const uglify = require('uglify-js')

// Make sure dist dir exists
mkdirp('dist')

const {
  logError,
  write,
  banner,
  name,
  moduleName,
  version,
} = require('./utils')

function rollupBundle ({ env, entry }) {
  return rollup({
    entry: entry || 'src/index.js',
    plugins: [
      scss({ output: false }),
      node({
        extensions: ['.js', '.jsx', '.vue'],
      }),
      cjs(),
      vue({ compileTemplate: true, css: false }),
      replace(Object.assign({
        __VERSION__: version,
      }, env)),
      buble({
        objectAssign: 'Object.assign',
      }),
    ],
  })
}

const bundleOptions = {
  banner,
  exports: 'named',
  format: 'umd',
  moduleName,
}

function createBundle ({ name, env, entry }) {
  return rollupBundle({
    env,
    entry,
  }).then(function (bundle) {
    const code = bundle.generate(bundleOptions).code
    if (/min$/.test(name)) {
      const minified = uglify.minify(code, {
        fromString: true,
        output: {
          preamble: banner,
          ascii_only: true, // eslint-disable-line camelcase
        },
      }).code
      return write(`dist/${name}.js`, minified)
    } else {
      return write(`dist/${name}.js`, code)
    }
  }).catch(logError)
}

// Browser bundle (can be used with script)
createBundle({
  name: `${name}`,
  env: {
    'process.env.NODE_ENV': '"development"',
  },
})

// Commonjs bundle (preserves process.env.NODE_ENV) so
// the user can replace it in dev and prod mode
createBundle({
  name: `${name}.esm`,
  env: {},
})

// Minified version for browser
createBundle({
  name: `${name}.min`,
  env: {
    'process.env.NODE_ENV': '"production"',
  },
})
<|endoftext|>


<commit_before>module.exports = function(app, request, async, ght, passport) {

    ///////////////////////////////////////////
    ///      Default landing page / login   ///
    ///////////////////////////////////////////
    app.get('/', function(req, res) {
        res.sendfile('./public/index.html');
    });

    //////////////////////////////////////////
    ///             LOGIN                  ///
    //////////////////////////////////////////
    app.get('/auth/github', passport.authenticate('github'));

    /////////////////////////////////////////
    ///             CALL BACK             ///
    /////////////////////////////////////////

    app.get('/auth/github/callback', passport.authenticate('github', {
        successRedirect : '/app',
        failureRedirect : '/'
    }));

    //////////////////////////////////////////
    ///             LOGOUT                 ///
    //////////////////////////////////////////
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

    ///////////////////////////////////////////
    ///               APP                   ///
    ///////////////////////////////////////////
    app.get('/app', isLoggedIn, function(req, res) {
        res.sendfile('./public/app.html');
    });

    /////////////////////////////////////
    ///  Returns a single user's info ///
    /////////////////////////////////////
    app.get('/git', function(req, res) {
        var name = req.query.name;
        var gitUrl = "https://api.github.com/users/"+ name +"/events?access_token="+ght;
        var options = {
            url: gitUrl,
            headers: {
                'User-Agent': name
            }
        };
        request.get(options,  function(error, response, body){
            if(!error) {
                var data = JSON.parse(body);
                console.log("made it");
                var count = 0;
                var found = false;

                while(found != true && count < data.length) {
                    console.log(data[count].type);
                    if(data[count].type == "PushEvent") {
                        found = true;
                        break;
                    }
                    count++;
                }

                res.send(data[count]);
            }
            console.log(response);
            //console.log(data[count]);
        });
    });

    ///////////////////////////////////////
    /// Returns info of users following ///
    ///////////////////////////////////////
    app.get('/geet', function(req, res) {
        console.log("MADE IT TO GEET");
        var name = req.query.name;
        var gitUrl = 'https://api.github.com/users/'+ name +"/following?access_token="+ght;
        console.log("GitURL "+gitUrl);
        var options = {
            url: gitUrl,
            headers: {
                'User-Agent': name
            }
        };
        request.get(options, function(error, response, body) {
            if(!error) {
                var data = JSON.parse(body);
                var names = [];
                for (i in data) {
                    names.push(data[i].login);
                }
                // To loop through array of names
                var count = 0;
                async.times(names.length, function(_, next) {
                    var gitUrl = 'https://api.github.com/users/'+names[count]+'/events?access_token='+ght;
                    var options = {
                        url: gitUrl,
                        headers: {
                            'User-Agent': name
                        }
                    };
                    count++;
                    request.get(options, function(error, response, body) {
                        var data = JSON.parse(body);
                        var pushEventNum = findPush(data);
                        var watchEventNum = findWatch(data);

                        var pushEvent = data[pushEventNum];
                        var watchEventNum = data[watchEventNum];
                        return next(error, ({pushEvents: pushEvent, watchEvents: watchEventNum}));
                    });
                }, function(err, results) {
                    res.send(results);
                });
            }
        });
    });

    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        }
        res.redirect('/');
    };

    function findPush(data) {
        var count = 0;
        var found = false;
        while(found != true && count < data.length) {
            if(data[count].type == "PushEvent") {
                found = true;
                break;
            }
            count++;
        }
        return count;
    };

    function findWatch(data) {
        var count = 0;
        var found = false;
        while(found != true && count < data.length) {
            if(data[count].type == "WatchEvent") {
                found = true;
                break;
            }
            count++;
        }
        return count;
    };

};
<commit_msg>update<commit_after>module.exports = function(app, request, async, ght, passport) {

    ///////////////////////////////////////////
    ///      Default landing page / login   ///
    ///////////////////////////////////////////
    app.get('/', function(req, res) {
        res.sendfile('./public/index.html');
    });

    //////////////////////////////////////////
    ///             LOGIN                  ///
    //////////////////////////////////////////
    app.get('/auth/github', passport.authenticate('github'));

    /////////////////////////////////////////
    ///             CALL BACK             ///
    /////////////////////////////////////////

    app.get('/auth/github/callback',
        passport.authenticate('github', { failureRedirect : '/'}),
        function(req, res) {
            res.redirect('/app');
    });

    //////////////////////////////////////////
    ///             LOGOUT                 ///
    //////////////////////////////////////////
    app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

    ///////////////////////////////////////////
    ///               APP                   ///
    ///////////////////////////////////////////
    app.get('/app', isLoggedIn, function(req, res) {
        res.sendfile('./public/app.html');
    });

    /////////////////////////////////////
    ///  Returns a single user's info ///
    /////////////////////////////////////
    app.get('/git', function(req, res) {
        var name = req.query.name;
        var gitUrl = "https://api.github.com/users/"+ name +"/events?access_token="+ght;
        var options = {
            url: gitUrl,
            headers: {
                'User-Agent': name
            }
        };
        request.get(options,  function(error, response, body){
            if(!error) {
                var data = JSON.parse(body);
                console.log("made it");
                var count = 0;
                var found = false;

                while(found != true && count < data.length) {
                    console.log(data[count].type);
                    if(data[count].type == "PushEvent") {
                        found = true;
                        break;
                    }
                    count++;
                }

                res.send(data[count]);
            }
            console.log(response);
            //console.log(data[count]);
        });
    });

    ///////////////////////////////////////
    /// Returns info of users following ///
    ///////////////////////////////////////
    app.get('/geet', function(req, res) {
        console.log("MADE IT TO GEET");
        var name = req.query.name;
        var gitUrl = 'https://api.github.com/users/'+ name +"/following?access_token="+ght;
        console.log("GitURL "+gitUrl);
        var options = {
            url: gitUrl,
            headers: {
                'User-Agent': name
            }
        };
        request.get(options, function(error, response, body) {
            if(!error) {
                var data = JSON.parse(body);
                var names = [];
                for (i in data) {
                    names.push(data[i].login);
                }
                // To loop through array of names
                var count = 0;
                async.times(names.length, function(_, next) {
                    var gitUrl = 'https://api.github.com/users/'+names[count]+'/events?access_token='+ght;
                    var options = {
                        url: gitUrl,
                        headers: {
                            'User-Agent': name
                        }
                    };
                    count++;
                    request.get(options, function(error, response, body) {
                        var data = JSON.parse(body);
                        var pushEventNum = findPush(data);
                        var watchEventNum = findWatch(data);

                        var pushEvent = data[pushEventNum];
                        var watchEventNum = data[watchEventNum];
                        return next(error, ({pushEvents: pushEvent, watchEvents: watchEventNum}));
                    });
                }, function(err, results) {
                    res.send(results);
                });
            }
        });
    });

    function isLoggedIn(req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        }
        res.redirect('/');
    };

    function findPush(data) {
        var count = 0;
        var found = false;
        while(found != true && count < data.length) {
            if(data[count].type == "PushEvent") {
                found = true;
                break;
            }
            count++;
        }
        return count;
    };

    function findWatch(data) {
        var count = 0;
        var found = false;
        while(found != true && count < data.length) {
            if(data[count].type == "WatchEvent") {
                found = true;
                break;
            }
            count++;
        }
        return count;
    };

};
<|endoftext|>


<commit_before>import Vue from 'vue';
import $ from 'jquery';
import NProgress from 'nprogress';

import { event } from '../utils';
import { ls } from '../services';

/**
 * Responsible for all HTTP requests.
 */
export const http = {
  request(method, url, data, successCb = null, errorCb = null) {
    return $.ajax({
      data,
      dataType: 'json',
      url: `/api/${url}`,
      method: method.toUpperCase(),
      headers: {
        Authorization: `Bearer ${ls.get('jwt-token')}`,
      }
    }).done(successCb).fail(errorCb);
  },

  get(url, successCb = null, errorCb = null) {
    return this.request('get', url, {}, successCb, errorCb);
  },

  post(url, data, successCb = null, errorCb = null) {
    return this.request('post', url, data, successCb, errorCb);
  },

  put(url, data, successCb = null, errorCb = null) {
    return this.request('put', url, data, successCb, errorCb);
  },

  delete(url, data = {}, successCb = null, errorCb = null) {
    return this.request('delete', url, data, successCb, errorCb);
  },

  /**
   * A shortcut method to ping and check if the user session is still valid.
   */
  ping() {
    return this.get('/');
  },

  /**
   * Init the service.
   */
  init() {
    $(document).ajaxComplete((e, r, settings) => {
      NProgress.done();

      if (r.status === 400 || r.status === 401) {
        if (!(settings.method === 'POST' && /\/api\/me\/?/.test(settings.url))) {
          // This is not a failed login. Log out then.
          event.emit('logout');
          return;
        }
      }

      const token = r.getResponseHeader('Authorization');
      if (token) {
        ls.set('jwt-token', token);
      }

      if (r.responseJSON && r.responseJSON.token && r.responseJSON.token.length > 10) {
        ls.set('jwt-token', r.responseJSON.token);
      }
    });
  },
};
<commit_msg>Remove redundant method<commit_after>import Vue from 'vue';
import $ from 'jquery';
import NProgress from 'nprogress';

import { event } from '../utils';
import { ls } from '../services';

/**
 * Responsible for all HTTP requests.
 */
export const http = {
  request(method, url, data, successCb = null, errorCb = null) {
    return $.ajax({
      data,
      dataType: 'json',
      url: `/api/${url}`,
      method: method.toUpperCase(),
      headers: {
        Authorization: `Bearer ${ls.get('jwt-token')}`,
      }
    }).done(successCb).fail(errorCb);
  },

  get(url, successCb = null, errorCb = null) {
    return this.request('get', url, {}, successCb, errorCb);
  },

  post(url, data, successCb = null, errorCb = null) {
    return this.request('post', url, data, successCb, errorCb);
  },

  put(url, data, successCb = null, errorCb = null) {
    return this.request('put', url, data, successCb, errorCb);
  },

  delete(url, data = {}, successCb = null, errorCb = null) {
    return this.request('delete', url, data, successCb, errorCb);
  },

  /**
   * Init the service.
   */
  init() {
    $(document).ajaxComplete((e, r, settings) => {
      NProgress.done();

      if (r.status === 400 || r.status === 401) {
        if (!(settings.method === 'POST' && /\/api\/me\/?/.test(settings.url))) {
          // This is not a failed login. Log out then.
          event.emit('logout');
          return;
        }
      }

      const token = r.getResponseHeader('Authorization');
      if (token) {
        ls.set('jwt-token', token);
      }

      if (r.responseJSON && r.responseJSON.token && r.responseJSON.token.length > 10) {
        ls.set('jwt-token', r.responseJSON.token);
      }
    });
  },
};
<|endoftext|>


<commit_before>"use strict";
const fn = require('ndk.fn');
const fs = require('ndk.fs');
const src = require('ndk.src');
const it = require('./it');
const helper = require('./helper');
fn.execute(function* () {
   var buildDate = new Date();
   var mode = helper.mode;
   var script = yield fs.readText('source/sbis-ui-customizer.template.user.js');
   var scriptData = yield fs.readJSON('source/sbis-ui-customizer.template.json');
   var localData = yield fs.readJSON('source/local-sbis-ui-customizer.template.json', {});
   var notes = yield fs.readJSON('release-notes.json');
   var build = helper.setBuild(yield fs.readJSON('bin/build.json', {}));
   var version = helper.setVersion(yield fs.readJSON('source/version.json', {}), notes);
   Object.assign(scriptData, localData);
   scriptData.VERSION = helper.getVersionName(version, build);
   scriptData.BUILD = build.number;
   scriptData.DATE = helper.getDateTime(buildDate);
   scriptData.DISPLAYDATE = helper.getDisplayDateTime(buildDate);
   scriptData.ICON = yield src.readDataImageBase64('source/image/script-icon16.png');
   scriptData.ICON64 = yield src.readDataImageBase64('source/image/script-icon64.png');
   scriptData.SCRIPT = helper.minimize(yield helper.parse(yield fs.readText('source/script.js'), {
      VERINFO: ', ' + helper.getVerInfo(scriptData, notes),
      SETTINGS: ', ' + (yield fs.readText('settings.json')),
      JS: ', ' + (yield it.readSources('source/js')),
      XHTML: ', ' + (yield it.readSources('source/xhtml')),
      CSS: ', ' + (yield it.readSources('source/css')),
      SVG: ', ' + (yield it.readSources('source/svg'))
   }));
   script = yield helper.parse(script, scriptData);
   yield fs.makeDir('bin');
   yield fs.writeText(`bin/${mode}_sbis-ui-customizer.user.js`, script);
   var meta = script.replace(/^(\/\/ ==UserScript==[\s\S]*==\/UserScript==)[\s\S]*$/, '$1');
   yield fs.writeText(`bin/${mode}_sbis-ui-customizer.meta.js`, meta);
   console.log('Скрипт успешно собран v' + scriptData.VERSION);
   if (yield require('./publish').push(version, build, scriptData, notes)) {
      yield fs.writeJSON('bin/build.json', build);
   }
}).catch(err => {
   console.error(err);
});
<commit_msg>кусочек оптимизации =)<commit_after>"use strict";
const fn = require('ndk.fn');
const fs = require('ndk.fs');
const src = require('ndk.src');
const it = require('./it');
const helper = require('./helper');
fn.execute(function* () {
   var buildDate = new Date();
   var script = yield fs.readText('source/sbis-ui-customizer.template.user.js');
   var scriptData = yield fs.readJSON('source/sbis-ui-customizer.template.json');
   var localData = yield fs.readJSON('source/local-sbis-ui-customizer.template.json', {});
   var notes = yield fs.readJSON('release-notes.json');
   var build = helper.setBuild(yield fs.readJSON('bin/build.json', {}));
   var version = helper.setVersion(yield fs.readJSON('source/version.json', {}), notes);
   Object.assign(scriptData, localData);
   scriptData.VERSION = helper.getVersionName(version, build);
   scriptData.BUILD = build.number;
   scriptData.DATE = helper.getDateTime(buildDate);
   scriptData.DISPLAYDATE = helper.getDisplayDateTime(buildDate);
   scriptData.ICON = yield src.readDataImageBase64('source/image/script-icon16.png');
   scriptData.ICON64 = yield src.readDataImageBase64('source/image/script-icon64.png');
   scriptData.SCRIPT = helper.minimize(yield helper.parse(yield fs.readText('source/script.js'), {
      VERINFO: ', ' + helper.getVerInfo(scriptData, notes),
      SETTINGS: ', ' + (yield fs.readText('settings.json')),
      JS: ', ' + (yield it.readSources('source/js')),
      XHTML: ', ' + (yield it.readSources('source/xhtml')),
      CSS: ', ' + (yield it.readSources('source/css')),
      SVG: ', ' + (yield it.readSources('source/svg'))
   }));
   script = yield helper.parse(script, scriptData);
   yield fs.makeDir('bin');
   yield fs.writeText(`bin/${helper.mode}_sbis-ui-customizer.user.js`, script);
   var meta = script.replace(/^(\/\/ ==UserScript==[\s\S]*==\/UserScript==)[\s\S]*$/, '$1');
   yield fs.writeText(`bin/${helper.mode}_sbis-ui-customizer.meta.js`, meta);
   console.log('Скрипт успешно собран v' + scriptData.VERSION);
   if (yield require('./publish').push(version, build, scriptData, notes)) {
      yield fs.writeJSON('bin/build.json', build);
   }
}).catch(err => {
   console.error(err);
});
<|endoftext|>


<commit_before>$(document).ready(function(){

//define our team list!
var teams = ['(1) FLA', '(16) ALBY', '(8) COLO', '(9) PITT', '(5) VCU', '(12) SFA', '(4) UCLA', '(13) TLSA',
		'(6) OSU', '(11) DAY', '(3) SYR', '(14) WMU', '(7) UNM', '(10) STAN', '(2) KU', '(15) EKY',
'(1) UVA', '(16) CCAR', '(8) MEM', ' (9) GW', '(5) CIN', ' (12) HARV', '(4) MSU', '(13) DEL',
		'(6) UNC', '(11) PROV', '(3) ISU', '(14) NCCU', '(7) CONN', '(10) JOES', '(2) VILL', '(15) MILW',
'(1) ARIZ', '(16) WEB', '(8) GONZ', '(9) OKST', '(5) OKLA', '(12) NDSU', '(4) SDSU', '(13) NMSU',
	'(6) BAY', '(11) NEB', '(3) CREI', '(14) ULL', '(7) ORE', '(10) BYU', '(2) WIS', '(15) AMER',
'(1) WICH', '(16) CP/TXSO', '(8) UK', '(9) KSU', '(5) SLU', '(12) NCST', '(4) LOU', '(13) MAN',
		'(6) MASS', '(11) IOWA/TENN', '(3) DUKE', '(14) MER', '(7) TEX', '(10) ASU', '(2) MICH', '(15) WOF', ]

var seeds = [1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15,
			1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15,
			1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15,
			1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15]

//set up inital matchups
var matchups = []
var seedMatchups = []
var results = []
//iterate through the list of teams, and pair them off into matchups 2 at a time
for (var n=0;n<teams.length;n+=2){
	var newMatchup = [teams[n], teams[n + 1]]
	var seedMatchup = [seeds[n], seeds[n+1]]

	console.log('creating matchup ' + newMatchup)
	//take our new matchup and add it to our list of matchups
	matchups.push(newMatchup);
	seedMatchups.push(seedMatchup);
}

//using these matchups, create a tournament object. It has no results yet.
var tournament = { teams: matchups, results: []}
console.log(tournament)
refreshBracket();

//on button press
$('#simulateRound').click(function(){
	if ($('td').hasClass('has-error')){
		console.log('Error with probabilities chart')
		alert('Please fix errors in probabilities chart. All values must be numbers between 0 and 1. You can refresh the page to reset the defaults.')
		return;
	}
	simulateRound()
	refreshBracket();
});
$('#simulateTournament').click(function(){
	if ($('td').hasClass('has-error')){
		console.log('Error with probabilities chart')
		alert('Please fix errors in probabilities chart. All values must be numbers between 0 and 1. You can refresh the page to reset the defaults.')
		return;
	}
	resetBracket();
	for (var x=0; x<6; x++){
		simulateRound();
	}
	refreshBracket();
})
$('#resetBracket').click(function() {resetBracket()})

//validation for inputs
$('input').change(function() {
    $input = $(this);
	n= $input.val()
	console.log(n)
	if (!isNaN(parseFloat(n)) && isFinite(n) && n <= 1 && n >= 0){
		console.log('Valid input')
		$input.parent('td').removeClass('has-error').addClass('has-success');
	} else {
		console.log('Invalid input')
		$input.parent('td').removeClass('has-success').addClass('has-error');
	}
})

function simulateRound() {
	console.log('Running round simulation')

	roundResults = {scores: [], nextSeeds: []};
	//iterate through each matchup
	for (var x=0; x<seedMatchups.length; x++){
		//get the seeds
		//get the probability for those seeds
		var highSeed = Math.min(seedMatchups[x][0], seedMatchups[x][1])
		var lowSeed = Math.max(seedMatchups[x][0], seedMatchups[x][1])
		var upsetPercentage = $('#'+ lowSeed + '-' + highSeed).val()
		console.log('High seed ' + highSeed + ' vs low seed ' + lowSeed + ' with upset % ' + upsetPercentage);
		//calculate who won
		//push results
		//push matchup and seeds
		var matchupResult = [1, 1]
		//Handle mirror matchups
		if (highSeed == lowSeed){
			console.log('Mirror matchup!')
			if (Math.random() > .5){
				roundResults.scores.push([1,2])
				//roundResults.nextTeams.push
			} else {
				roundResults.scores.push([2,1])
			}
			roundResults.nextSeeds.push(highSeed)
		} else if (Math.random() > upsetPercentage)
		{
			matchupResult[seedMatchups[x].indexOf(highSeed)] = 2
			//console.log(matchupResult)
			roundResults.scores.push(matchupResult)
			roundResults.nextSeeds.push(highSeed)

		} else {
			matchupResult[seedMatchups[x].indexOf(lowSeed)] = 2
			//console.log(matchupResult)
			roundResults.scores.push(matchupResult)
			roundResults.nextSeeds.push(lowSeed)
		}
	}
	//set up next seedMatchups
	seedMatchups = []
	for (var x=0; x<roundResults.nextSeeds.length; x+=2){
		seedMatchups.push([roundResults.nextSeeds[x], roundResults.nextSeeds[x+1]])
	}
	//update results and bracket
	console.log(roundResults)
	results.push(roundResults.scores)
	tournament.results= results;
}

function resetBracket(){
	//reset tourney
	console.log('Resetting bracket');
	matchups = []
	seedMatchups = []
	results = []
	for (var n=0;n<teams.length;n+=2){
		var newMatchup = [teams[n], teams[n + 1]]
		var seedMatchup = [seeds[n], seeds[n+1]]
		console.log('creating matchup ' + newMatchup)
		matchups.push(newMatchup);
		seedMatchups.push(seedMatchup);
	}
	tournament = { teams: matchups, results: []}
	refreshBracket()
}

function setTeamsTable(){
var teamsHtml = ""

	teams.forEach(function(team){
		teamsHtml = teamsHtml.concat('
'+team+'	<input id="' + team + 'hcap" value="0" type="number" class="form-control"></input>
')
	})

$('#teams').append(teamsHtml);
}

function createSeedHandicaps(){

}

//setTeamsTable()

/* Called whenever bracket is modified
 *
 * data:     changed bracket object in format given to init
 * userData: optional data given when bracket is created.
 */
function saveFn(data, userData) {
  var json = jQuery.toJSON(data)
  $('#saveOutput').text('POST '+userData+' '+json)
  /* You probably want to do something like this
  jQuery.ajax("rest/"+userData, {contentType: 'application/json',
                                dataType: 'json',
                                type: 'post',
                                data: json})
  */
}

function refreshBracket() {
	var $bracket = $('#bracket');
	$bracket.empty()
    $bracket.bracket({
	  skipConsolationRound: true,
      init: tournament,
	  save: saveFn,
      userData: "http://myapi"})
  }

})<commit_msg>Getting rid of final playin teams<commit_after>$(document).ready(function(){

//define our team list!
var teams = ['(1) FLA', '(16) ALBY', '(8) COLO', '(9) PITT', '(5) VCU', '(12) SFA', '(4) UCLA', '(13) TLSA',
		'(6) OSU', '(11) DAY', '(3) SYR', '(14) WMU', '(7) UNM', '(10) STAN', '(2) KU', '(15) EKY',
'(1) UVA', '(16) CCAR', '(8) MEM', ' (9) GW', '(5) CIN', ' (12) HARV', '(4) MSU', '(13) DEL',
		'(6) UNC', '(11) PROV', '(3) ISU', '(14) NCCU', '(7) CONN', '(10) JOES', '(2) VILL', '(15) MILW',
'(1) ARIZ', '(16) WEB', '(8) GONZ', '(9) OKST', '(5) OKLA', '(12) NDSU', '(4) SDSU', '(13) NMSU',
	'(6) BAY', '(11) NEB', '(3) CREI', '(14) ULL', '(7) ORE', '(10) BYU', '(2) WIS', '(15) AMER',
'(1) WICH', '(16) CP', '(8) UK', '(9) KSU', '(5) SLU', '(12) NCST', '(4) LOU', '(13) MAN',
		'(6) MASS', '(11) TENN', '(3) DUKE', '(14) MER', '(7) TEX', '(10) ASU', '(2) MICH', '(15) WOF', ]

var seeds = [1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15,
			1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15,
			1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15,
			1, 16, 8, 9, 5, 12, 4, 13, 6, 11, 3, 14, 7, 10, 2, 15]

//set up inital matchups
var matchups = []
var seedMatchups = []
var results = []
//iterate through the list of teams, and pair them off into matchups 2 at a time
for (var n=0;n<teams.length;n+=2){
	var newMatchup = [teams[n], teams[n + 1]]
	var seedMatchup = [seeds[n], seeds[n+1]]

	console.log('creating matchup ' + newMatchup)
	//take our new matchup and add it to our list of matchups
	matchups.push(newMatchup);
	seedMatchups.push(seedMatchup);
}

//using these matchups, create a tournament object. It has no results yet.
var tournament = { teams: matchups, results: []}
console.log(tournament)
refreshBracket();

//on button press
$('#simulateRound').click(function(){
	if ($('td').hasClass('has-error')){
		console.log('Error with probabilities chart')
		alert('Please fix errors in probabilities chart. All values must be numbers between 0 and 1. You can refresh the page to reset the defaults.')
		return;
	}
	simulateRound()
	refreshBracket();
});
$('#simulateTournament').click(function(){
	if ($('td').hasClass('has-error')){
		console.log('Error with probabilities chart')
		alert('Please fix errors in probabilities chart. All values must be numbers between 0 and 1. You can refresh the page to reset the defaults.')
		return;
	}
	resetBracket();
	for (var x=0; x<6; x++){
		simulateRound();
	}
	refreshBracket();
})
$('#resetBracket').click(function() {resetBracket()})

//validation for inputs
$('input').change(function() {
    $input = $(this);
	n= $input.val()
	console.log(n)
	if (!isNaN(parseFloat(n)) && isFinite(n) && n <= 1 && n >= 0){
		console.log('Valid input')
		$input.parent('td').removeClass('has-error').addClass('has-success');
	} else {
		console.log('Invalid input')
		$input.parent('td').removeClass('has-success').addClass('has-error');
	}
})

function simulateRound() {
	console.log('Running round simulation')

	roundResults = {scores: [], nextSeeds: []};
	//iterate through each matchup
	for (var x=0; x<seedMatchups.length; x++){
		//get the seeds
		//get the probability for those seeds
		var highSeed = Math.min(seedMatchups[x][0], seedMatchups[x][1])
		var lowSeed = Math.max(seedMatchups[x][0], seedMatchups[x][1])
		var upsetPercentage = $('#'+ lowSeed + '-' + highSeed).val()
		console.log('High seed ' + highSeed + ' vs low seed ' + lowSeed + ' with upset % ' + upsetPercentage);
		//calculate who won
		//push results
		//push matchup and seeds
		var matchupResult = [1, 1]
		//Handle mirror matchups
		if (highSeed == lowSeed){
			console.log('Mirror matchup!')
			if (Math.random() > .5){
				roundResults.scores.push([1,2])
				//roundResults.nextTeams.push
			} else {
				roundResults.scores.push([2,1])
			}
			roundResults.nextSeeds.push(highSeed)
		} else if (Math.random() > upsetPercentage)
		{
			matchupResult[seedMatchups[x].indexOf(highSeed)] = 2
			//console.log(matchupResult)
			roundResults.scores.push(matchupResult)
			roundResults.nextSeeds.push(highSeed)

		} else {
			matchupResult[seedMatchups[x].indexOf(lowSeed)] = 2
			//console.log(matchupResult)
			roundResults.scores.push(matchupResult)
			roundResults.nextSeeds.push(lowSeed)
		}
	}
	//set up next seedMatchups
	seedMatchups = []
	for (var x=0; x<roundResults.nextSeeds.length; x+=2){
		seedMatchups.push([roundResults.nextSeeds[x], roundResults.nextSeeds[x+1]])
	}
	//update results and bracket
	console.log(roundResults)
	results.push(roundResults.scores)
	tournament.results= results;
}

function resetBracket(){
	//reset tourney
	console.log('Resetting bracket');
	matchups = []
	seedMatchups = []
	results = []
	for (var n=0;n<teams.length;n+=2){
		var newMatchup = [teams[n], teams[n + 1]]
		var seedMatchup = [seeds[n], seeds[n+1]]
		console.log('creating matchup ' + newMatchup)
		matchups.push(newMatchup);
		seedMatchups.push(seedMatchup);
	}
	tournament = { teams: matchups, results: []}
	refreshBracket()
}

function setTeamsTable(){
var teamsHtml = ""

	teams.forEach(function(team){
		teamsHtml = teamsHtml.concat('
'+team+'	<input id="' + team + 'hcap" value="0" type="number" class="form-control"></input>
')
	})

$('#teams').append(teamsHtml);
}

function createSeedHandicaps(){

}

//setTeamsTable()

/* Called whenever bracket is modified
 *
 * data:     changed bracket object in format given to init
 * userData: optional data given when bracket is created.
 */
function saveFn(data, userData) {
  var json = jQuery.toJSON(data)
  $('#saveOutput').text('POST '+userData+' '+json)
  /* You probably want to do something like this
  jQuery.ajax("rest/"+userData, {contentType: 'application/json',
                                dataType: 'json',
                                type: 'post',
                                data: json})
  */
}

function refreshBracket() {
	var $bracket = $('#bracket');
	$bracket.empty()
    $bracket.bracket({
	  skipConsolationRound: true,
      init: tournament,
	  save: saveFn,
      userData: "http://myapi"})
  }

})<|endoftext|>