<commit_before>/**********************************************************\
|                                                          |
| xxtea.js                                                 |
|                                                          |
| XXTEA encryption algorithm library for Node.js.          |
|                                                          |
| Encryption Algorithm Authors:                            |
|      David J. Wheeler                                    |
|      Roger M. Needham                                    |
|                                                          |
| Code Author: Ma Bingyao <mabingyao@gmail.com>            |
| LastModified: Dec 10, 2015                               |
|                                                          |
\**********************************************************/

/*jshint node:true, eqeqeq:true */
'use strict';

var delta = 0x9E3779B9;

function toUint8Array(v, includeLength) {
    var length = v.length;
    var n = length << 2;
    if (includeLength) {
        var m = v[length - 1];
        n -= 4;
        if ((m < n - 3) || (m > n)) {
            return null;
        }
        n = m;
    }
    var bytes = new Uint8Array(n);
    for (var i = 0; i < n; ++i) {
        bytes[i] = v[i >>> 2] >>> ((i & 3) << 3);
    }
    return bytes;
}

function toUint32Array(bytes, includeLength) {
    var length = bytes.length;
    var n = length >>> 2;
    if ((length & 3) !== 0) {
        ++n;
    }
    var v;
    if (includeLength) {
        v = new Uint32Array(n + 1);
        v[n] = length;
    }
     else {
        v = new Uint32Array(n);
    }
    for (var i = 0; i < length; ++i) {
        v[i >> 2] |= bytes[i] << ((i & 3) << 3);
    }
    return v;
}

function mx(sum, y, z, p, e, k) {
    return ((z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4)) ^ ((sum ^ y) + (k[p & 3 ^ e] ^ z));
}

function fixk(k) {
    if (k.length < 16) {
        var key = new Uint8Array(16);
        key.set(k);
        k = key;
    }
    return k;
}

function encryptUint32Array(v, k) {
    var length = v.length;
    var n = length - 1;
    var y, z, sum, e, p, q;
    z = v[n];
    sum = 0;
    for (q = Math.floor(6 + 52/length) | 0; q > 0; --q) {
        sum += delta;
        e = sum >>> 2 & 3;
        for (p = 0; p < n; ++p) {
            y = v[p + 1];
            z = v[p] += mx(sum, y, z, p, e, k);
        }
        y = v[0];
        z = v[n] += mx(sum, y, z, p, e, k);
    }
    return v;
}

function decryptUint32Array(v, k) {
    var length = v.length;
    var n = length - 1;
    var y, z, sum, e, p, q;
    y = v[0];
    q = Math.floor(6 + 52/length);
    for (sum = q * delta; sum !== 0; sum -= delta) {
        e = sum >>> 2 & 3;
        for (p = n; p > 0; --p) {
            z = v[p - 1];
            y = v[p] -= mx(sum, y, z, p, e, k);
        }
        z = v[n];
        y = v[0] -= mx(sum, y, z, p, e, k);
    }
    return v;
}

function toBytes(str) {
    var n = str.length;
    if (n === 0) return;
    // A single code unit uses at most 3 bytes.
    // Two code units at most 4.
    var bytes = new Uint8Array(n * 3);
    var length = 0;
    for (var i = 0; i < n; i++) {
        var codeUnit = str.charCodeAt(i);
        if (codeUnit < 0x80) {
            bytes[length++] = codeUnit;
        }
        else if (codeUnit < 0x800) {
            bytes[length++] = 0xC0 | (codeUnit >> 6);
            bytes[length++] = 0x80 | (codeUnit & 0x3F);
        }
        else if (codeUnit < 0xD800 || codeUnit > 0xDfff) {
            bytes[length++] = 0xE0 | (codeUnit >> 12);
            bytes[length++] = 0x80 | ((codeUnit >> 6) & 0x3F);
            bytes[length++] = 0x80 | (codeUnit & 0x3F);
        }
        else {
            if (i + 1 < length) {
                var nextCodeUnit = str.charCodeAt(i + 1);
                if (codeUnit < 0xDC00 && 0xDC00 <= nextCodeUnit && nextCodeUnit <= 0xDFFF) {
                    var rune = (((codeUnit & 0x03FF) << 10) | (nextCodeUnit & 0x03FF)) + 0x010000;
                    bytes[length++] = 0xF0 | (rune >> 18);
                    bytes[length++] = 0x80 | ((rune >> 12) & 0x3F);
                    bytes[length++] = 0x80 | ((rune >> 6) & 0x3F);
                    bytes[length++] = 0x80 | (rune & 0x3F);
                    i++;
                    continue;
                }
            }
            throw new Error('Malformed string');
        }
    }
    return bytes.subarray(0, length);
}

function toShortString(bytes, n) {
    var charCodes = new Uint16Array(n);
    var i = 0, off = 0;
    for (var len = bytes.length; i < n && off < len; i++) {
        var unit = bytes[off++];
        switch (unit >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            charCodes[i] = unit;
            break;
        case 12:
        case 13:
            if (off < len) {
                charCodes[i] = ((unit & 0x1F) << 6) |
                                (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 14:
            if (off + 1 < len) {
                charCodes[i] = ((unit & 0x0F) << 12) |
                               ((bytes[off++] & 0x3F) << 6) |
                               (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 15:
            if (off + 2 < len) {
                var rune = (((unit & 0x07) << 18) |
                            ((bytes[off++] & 0x3F) << 12) |
                            ((bytes[off++] & 0x3F) << 6) |
                            (bytes[off++] & 0x3F)) - 0x10000;
                if (0 <= rune && rune <= 0xFFFFF) {
                    charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800);
                    charCodes[i] = ((rune & 0x03FF) | 0xDC00);
                }
                else {
                    throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16));
                }
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        default:
            throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16));
        }
    }
    if (i < n) {
        charCodes = charCodes.subarray(0, i);
    }
    return String.fromCharCode.apply(String, charCodes);
}

function toLongString(bytes, n) {
    var buf = [];
    var charCodes = new Uint16Array(0xffff);
    var i = 0, off = 0;
    for (var len = bytes.length; i < n && off < len; i++) {
        var unit = bytes[off++];
        switch (unit >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            charCodes[i] = unit;
            break;
        case 12:
        case 13:
            if (off < len) {
                charCodes[i] = ((unit & 0x1F) << 6) |
                                (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 14:
            if (off + 1 < len) {
                charCodes[i] = ((unit & 0x0F) << 12) |
                               ((bytes[off++] & 0x3F) << 6) |
                               (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 15:
            if (off + 2 < len) {
                var rune = (((unit & 0x07) << 18) |
                            ((bytes[off++] & 0x3F) << 12) |
                            ((bytes[off++] & 0x3F) << 6) |
                            (bytes[off++] & 0x3F)) - 0x10000;
                if (0 <= rune && rune <= 0xFFFFF) {
                    charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800);
                    charCodes[i] = ((rune & 0x03FF) | 0xDC00);
                }
                else {
                    throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16));
                }
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        default:
            throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16));
        }
        if (i >= 65534) {
            var size = i + 1;
            buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, size)));
            n -= size;
            i = -1;
        }
    }
    if (i > 0) {
        buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, i)));
    }
    return buf.join('');
}

function toString(bytes) {
    var n = bytes.length;
    if (n === 0) return '';
    return ((n < 100000) ?
            toShortString(bytes, n) :
            toLongString(bytes, n));
}

function encrypt(data, key) {
    if (typeof data === 'string') data = toBytes(data);
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(encryptUint32Array(toUint32Array(data, true), toUint32Array(fixk(key), false)), false);
}

function encryptToString(data, key) {
    return new Buffer(encrypt(data, key)).toString('base64');
}

function decrypt(data, key) {
    if (typeof data === 'string') data = new Buffer(data, 'base64');
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(decryptUint32Array(toUint32Array(data, false), toUint32Array(fixk(key), false)), true);
}

function decryptToString(data, key) {
    return toString(decrypt(data, key));
}

module.exports = Object.create(null, {
    toBytes: { value: toBytes },
    toString: { value: toString },
    encrypt: { value: encrypt },
    encryptToString: { value: encryptToString },
    decrypt: { value: decrypt },
    decryptToString: { value: decryptToString }
});
<commit_msg>>>> can't work as expected on some platform.<commit_after>/**********************************************************\
|                                                          |
| xxtea.js                                                 |
|                                                          |
| XXTEA encryption algorithm library for Node.js.          |
|                                                          |
| Encryption Algorithm Authors:                            |
|      David J. Wheeler                                    |
|      Roger M. Needham                                    |
|                                                          |
| Code Author: Ma Bingyao <mabingyao@gmail.com>            |
| LastModified: Jan 28, 2016                               |
|                                                          |
\**********************************************************/

/*jshint node:true, eqeqeq:true */
'use strict';

var delta = 0x9E3779B9;

function toUint8Array(v, includeLength) {
    var length = v.length;
    var n = length << 2;
    if (includeLength) {
        var m = v[length - 1];
        n -= 4;
        if ((m < n - 3) || (m > n)) {
            return null;
        }
        n = m;
    }
    var bytes = new Uint8Array(n);
    for (var i = 0; i < n; ++i) {
        bytes[i] = v[i >> 2] >> ((i & 3) << 3);
    }
    return bytes;
}

function toUint32Array(bytes, includeLength) {
    var length = bytes.length;
    var n = length >> 2;
    if ((length & 3) !== 0) {
        ++n;
    }
    var v;
    if (includeLength) {
        v = new Uint32Array(n + 1);
        v[n] = length;
    }
     else {
        v = new Uint32Array(n);
    }
    for (var i = 0; i < length; ++i) {
        v[i >> 2] |= bytes[i] << ((i & 3) << 3);
    }
    return v;
}

function mx(sum, y, z, p, e, k) {
    return ((z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4)) ^ ((sum ^ y) + (k[p & 3 ^ e] ^ z));
}

function fixk(k) {
    if (k.length < 16) {
        var key = new Uint8Array(16);
        key.set(k);
        k = key;
    }
    return k;
}

function encryptUint32Array(v, k) {
    var length = v.length;
    var n = length - 1;
    var y, z, sum, e, p, q;
    z = v[n];
    sum = 0;
    for (q = Math.floor(6 + 52/length) | 0; q > 0; --q) {
        sum += delta;
        e = sum >>> 2 & 3;
        for (p = 0; p < n; ++p) {
            y = v[p + 1];
            z = v[p] += mx(sum, y, z, p, e, k);
        }
        y = v[0];
        z = v[n] += mx(sum, y, z, p, e, k);
    }
    return v;
}

function decryptUint32Array(v, k) {
    var length = v.length;
    var n = length - 1;
    var y, z, sum, e, p, q;
    y = v[0];
    q = Math.floor(6 + 52/length);
    for (sum = q * delta; sum !== 0; sum -= delta) {
        e = sum >>> 2 & 3;
        for (p = n; p > 0; --p) {
            z = v[p - 1];
            y = v[p] -= mx(sum, y, z, p, e, k);
        }
        z = v[n];
        y = v[0] -= mx(sum, y, z, p, e, k);
    }
    return v;
}

function toBytes(str) {
    var n = str.length;
    if (n === 0) return;
    // A single code unit uses at most 3 bytes.
    // Two code units at most 4.
    var bytes = new Uint8Array(n * 3);
    var length = 0;
    for (var i = 0; i < n; i++) {
        var codeUnit = str.charCodeAt(i);
        if (codeUnit < 0x80) {
            bytes[length++] = codeUnit;
        }
        else if (codeUnit < 0x800) {
            bytes[length++] = 0xC0 | (codeUnit >> 6);
            bytes[length++] = 0x80 | (codeUnit & 0x3F);
        }
        else if (codeUnit < 0xD800 || codeUnit > 0xDfff) {
            bytes[length++] = 0xE0 | (codeUnit >> 12);
            bytes[length++] = 0x80 | ((codeUnit >> 6) & 0x3F);
            bytes[length++] = 0x80 | (codeUnit & 0x3F);
        }
        else {
            if (i + 1 < length) {
                var nextCodeUnit = str.charCodeAt(i + 1);
                if (codeUnit < 0xDC00 && 0xDC00 <= nextCodeUnit && nextCodeUnit <= 0xDFFF) {
                    var rune = (((codeUnit & 0x03FF) << 10) | (nextCodeUnit & 0x03FF)) + 0x010000;
                    bytes[length++] = 0xF0 | (rune >> 18);
                    bytes[length++] = 0x80 | ((rune >> 12) & 0x3F);
                    bytes[length++] = 0x80 | ((rune >> 6) & 0x3F);
                    bytes[length++] = 0x80 | (rune & 0x3F);
                    i++;
                    continue;
                }
            }
            throw new Error('Malformed string');
        }
    }
    return bytes.subarray(0, length);
}

function toShortString(bytes, n) {
    var charCodes = new Uint16Array(n);
    var i = 0, off = 0;
    for (var len = bytes.length; i < n && off < len; i++) {
        var unit = bytes[off++];
        switch (unit >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            charCodes[i] = unit;
            break;
        case 12:
        case 13:
            if (off < len) {
                charCodes[i] = ((unit & 0x1F) << 6) |
                                (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 14:
            if (off + 1 < len) {
                charCodes[i] = ((unit & 0x0F) << 12) |
                               ((bytes[off++] & 0x3F) << 6) |
                               (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 15:
            if (off + 2 < len) {
                var rune = (((unit & 0x07) << 18) |
                            ((bytes[off++] & 0x3F) << 12) |
                            ((bytes[off++] & 0x3F) << 6) |
                            (bytes[off++] & 0x3F)) - 0x10000;
                if (0 <= rune && rune <= 0xFFFFF) {
                    charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800);
                    charCodes[i] = ((rune & 0x03FF) | 0xDC00);
                }
                else {
                    throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16));
                }
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        default:
            throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16));
        }
    }
    if (i < n) {
        charCodes = charCodes.subarray(0, i);
    }
    return String.fromCharCode.apply(String, charCodes);
}

function toLongString(bytes, n) {
    var buf = [];
    var charCodes = new Uint16Array(0xffff);
    var i = 0, off = 0;
    for (var len = bytes.length; i < n && off < len; i++) {
        var unit = bytes[off++];
        switch (unit >> 4) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
            charCodes[i] = unit;
            break;
        case 12:
        case 13:
            if (off < len) {
                charCodes[i] = ((unit & 0x1F) << 6) |
                                (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 14:
            if (off + 1 < len) {
                charCodes[i] = ((unit & 0x0F) << 12) |
                               ((bytes[off++] & 0x3F) << 6) |
                               (bytes[off++] & 0x3F);
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        case 15:
            if (off + 2 < len) {
                var rune = (((unit & 0x07) << 18) |
                            ((bytes[off++] & 0x3F) << 12) |
                            ((bytes[off++] & 0x3F) << 6) |
                            (bytes[off++] & 0x3F)) - 0x10000;
                if (0 <= rune && rune <= 0xFFFFF) {
                    charCodes[i++] = (((rune >> 10) & 0x03FF) | 0xD800);
                    charCodes[i] = ((rune & 0x03FF) | 0xDC00);
                }
                else {
                    throw new Error('Character outside valid Unicode range: 0x' + rune.toString(16));
                }
            }
            else {
                throw new Error('Unfinished UTF-8 octet sequence');
            }
            break;
        default:
            throw new Error('Bad UTF-8 encoding 0x' + unit.toString(16));
        }
        if (i >= 65534) {
            var size = i + 1;
            buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, size)));
            n -= size;
            i = -1;
        }
    }
    if (i > 0) {
        buf.push(String.fromCharCode.apply(String, charCodes.subarray(0, i)));
    }
    return buf.join('');
}

function toString(bytes) {
    var n = bytes.length;
    if (n === 0) return '';
    return ((n < 100000) ?
            toShortString(bytes, n) :
            toLongString(bytes, n));
}

function encrypt(data, key) {
    if (typeof data === 'string') data = toBytes(data);
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(encryptUint32Array(toUint32Array(data, true), toUint32Array(fixk(key), false)), false);
}

function encryptToString(data, key) {
    return new Buffer(encrypt(data, key)).toString('base64');
}

function decrypt(data, key) {
    if (typeof data === 'string') data = new Buffer(data, 'base64');
    if (typeof key === 'string') key = toBytes(key);
    if (data === undefined || data === null || data.length === 0) {
        return data;
    }
    return toUint8Array(decryptUint32Array(toUint32Array(data, false), toUint32Array(fixk(key), false)), true);
}

function decryptToString(data, key) {
    return toString(decrypt(data, key));
}

module.exports = Object.create(null, {
    toBytes: { value: toBytes },
    toString: { value: toString },
    encrypt: { value: encrypt },
    encryptToString: { value: encryptToString },
    decrypt: { value: decrypt },
    decryptToString: { value: decryptToString }
});
<|endoftext|>


<commit_before>var argv = require('yargs')
  .usage('Usage: $0 [options]')
  .env('OFSS')
  .config('c', 'JSON file with configuration.')
  .alias('c', 'config')
  .default('c', './okta-for-static-site.json')
  .option('i', {
    alias: 'oktaIssuer',
    description: 'From your Okta app.',
    demand: true
  })
  .option('u', {
    alias: 'oktaSingleSignOnUrl',
    description: 'From your Okta app.',
    demand: true
  })
  .option('t', {
    alias: 'oktaCert',
    description: 'From your Okta app. You can inform a path or the content of certificate.',
    demand: true
  })
  .option('f', {
    alias: 'staticSitePath',
    description: 'Path to files to serve.',
    default: '.'
  })
  .option('x', {
    alias: 'sessionSecret',
    description: 'Used to sign session cookie. Very important for your security!',
    default: 'secret'
  })
  .option('r', {
    alias: 'redisUrl',
    description: 'URL for connect with your Redis instance, in the format "redis://127.0.0.1:6379". We use Redis to manage sessions. Without Redis, session data is stored in memory, and doesn\'t have capacity to manage sessions for a production site.'
  })
  .option('n', {
    alias: 'custom404',
    description: 'Inform a custom 404 file to send to users in case of file not found.'
  })
  .option('z', {
    alias: 'compressionLevel',
    description: 'Compression level of served files. This is an integer in the range of 0 (no compression) to 9 (maximum compression).',
    default: '6'
  })
  .option('o', {
    alias: 'oktaCookieName',
    description: 'Name of the cookie with user info accessible from your static site.',
    default: 'okta-data'
  })
  .option('s', {
    alias: 'sessionCookieName',
    description: 'Name of signed cookie with session id.',
    default: 'session-id'
  })
  .option('p', {
    alias: 'serverPort',
    description: 'Port to use for the server.',
    default: '3000'
  })
  .option('j', {
    alias: 'serverSslCert',
    description: 'Cert to use if you want https. To enable https provide SSL certificate and key. You can inform a path or a string with content of certificate.'
  })
  .option('k', {
    alias: 'serverSslKey',
    description: 'Key to use if you want https. To enable https provide SSL certificate and key. You can inform a path or a string with content of key.'
  })
  .epilog('You can use enviroment variables too. For more info go to https://github.com/andreleite/okta-for-static-site/')
  .argv;

module.exports = argv;
<commit_msg>Adjusting cli help text<commit_after>var argv = require('yargs')
  .usage('Usage: $0 [options]')
  .env('OFSS')
  .config('c', 'JSON file with configuration.')
  .alias('c', 'config')
  .default('c', './okta-for-static-site.json')
  .option('i', {
    alias: 'oktaIssuer',
    description: 'From your Okta app.',
    demand: true
  })
  .option('u', {
    alias: 'oktaSingleSignOnUrl',
    description: 'From your Okta app.',
    demand: true
  })
  .option('t', {
    alias: 'oktaCert',
    description: 'From your Okta app. You can inform a path or the content of certificate.',
    demand: true
  })
  .option('f', {
    alias: 'staticSitePath',
    description: 'Path to files to serve.',
    default: '.'
  })
  .option('x', {
    alias: 'sessionSecret',
    description: 'Used to sign session cookie. Very important for your security!',
    default: 'secret'
  })
  .option('r', {
    alias: 'redisUrl',
    description: 'URL for connect with your Redis instance, in the format "redis://127.0.0.1:6379". We use Redis to manage sessions. Without Redis, session data is stored in memory, and doesn\'t have capacity to manage sessions for a production site.'
  })
  .option('n', {
    alias: 'custom404',
    description: 'Inform a custom 404 file to send to users in case of file not found.'
  })
  .option('z', {
    alias: 'compressionLevel',
    description: 'Compression level of served files. This is an integer in the range of 0 (no compression) to 9 (maximum compression).',
    default: '6'
  })
  .option('o', {
    alias: 'oktaCookieName',
    description: 'Name of the cookie with user info accessible from your static site.',
    default: 'okta-data'
  })
  .option('s', {
    alias: 'sessionCookieName',
    description: 'Name of signed cookie with session id.',
    default: 'session-id'
  })
  .option('p', {
    alias: 'serverPort',
    description: 'Port to use for the server.',
    default: '3000'
  })
  .option('j', {
    alias: 'serverSslCert',
    description: 'Certificate to use if you want https. To enable https provide SSL certificate and key. You can inform a path or a string with content of certificate.'
  })
  .option('k', {
    alias: 'serverSslKey',
    description: 'Key to use if you want https. To enable https provide SSL certificate and key. You can inform a path or a string with content of key.'
  })
  .epilog('You can use environment variables too. For more info go to https://github.com/andreleite/okta-for-static-site/')
  .argv;

module.exports = argv;
<|endoftext|>


<commit_before>/*!
 * zocci
 * Copyright(c) 2015-2016 Anatol Sommer <anatol@anatol.at>
 * MIT Licensed
 */

'use strict';

var fs=require('fs'), path=require('path'), EE=require('events'), util=require('util'),
  defaults={jsonSpaces:2, delimiter:'.'};

function Zocci(path, opts) {
  this.path=path;
  this.data={};
  this._resave=[];
  if (typeof opts==='object') {
    this.opts=opts;
    opts.jsonSpaces=isDef(opts.jsonSpaces) ? opts.jsonSpaces : defaults.jsonSpaces;
    opts.delimiter=opts.delimiter || defaults.delimiter;
  } else if (typeof opts==='string') {
    this.opts={jsonSpaces:defaults.jsonSpaces, delimiter:opts};
  } else if (typeof opts==='number') {
    this.opts={jsonSpaces:opts, delimiter:defaults.delimiter};
  } else {
    this.opts=defaults;
  }
  if (!this.reload()) {
    this.save();
  }
}

util.inherits(Zocci, EE);

Zocci.prototype.reload=function() {
  var data;
  if (fs.existsSync(this.path)) {
    data=fs.readFileSync(this.path).toString();
    try {
      this.data=JSON.parse(data);
    } catch(err) {
      return false;
    }
    return true;
  }
};

Zocci.prototype.save=function(cb) {
  var self=this, tmp=this.path+tmpName(), spaces=this.opts.jsonSpaces;
  spaces=(typeof spaces==='number' ? spaces : null);
  if (this._saving) {
    this._resave.push(cb || true);
    return;
  }
  this._saving=true;
  fs.writeFile(tmp, JSON.stringify(this.data, null, spaces), function(err) {
    if (err) {
      saved(self);
      if (cb) {
        return cb(err);
      }
      throw err;
    }
    fs.rename(tmp, self.path, function(err) {
      cb && cb(err);
      saved(self);
    });
  });
};

Zocci.prototype.access=function(key, def) {
  var data=this.data, curKey;
  key=key.split(this.opts.delimiter);
  while (data && key.length) {
    curKey=key.shift();
    data=data.hasOwnProperty(curKey) ? data[curKey] : null;
  }
  return typeof data!=='undefined' ? data : (def || null);
};

Zocci.prototype.get=function(key, def) {
  return copy(this.access(key, def));
};

Zocci.prototype.set=function(key, val, cb) {
  var data=this.data, curKey;
  this.emit('change', key, val);
  key=key.split(this.opts.delimiter);
  while (key.length>1) {
    curKey=key.shift();
    if (!isDef(data[curKey])) {
      data[curKey]={};
    }
    data=data[curKey];
  }
  data[key[0]]=copy(val);
  this.save(cb);
};

Zocci.prototype.remove=function(key, cb) {
  var data=this.data, curKey=key;
  this.emit('change', key, null);
  key=key.split(this.opts.delimiter);
  while (data && key.length>1) {
    curKey=key.shift();
    data=data.hasOwnProperty(curKey) ? data[curKey] : null;
  }
  if (data && isDef(data[key[0]])) {
    delete data[key[0]];
  }
  this.save(cb);
};

Zocci.prototype.find=function(find, returnKeys) {
  var self=this, keys;
  keys=Object.keys(this.data).filter(function(key) {
    if (typeof find==='string') {
      return key.substr(0, find.length)===find;
    } else if (find && find instanceof RegExp) {
      return !!find.exec(key);
    }
  });
  if (returnKeys) {
    return keys;
  }
  return copy(keys.map(function(key) {
    return self.data[key];
  }));
};

function tmpName() {
  return '.'+Date.now().toString(36)+'-'+Math.random().toString(36).substr(2);
}

function isDef(check) {
  return typeof check!=='undefined' && check!==null;
}

function copy(data) {
  return isDef(data) ? JSON.parse(JSON.stringify(data)) : null;
}

function saved(self) {
  var cbs;
  self._saving=false;
  if (!self._resave.length) {
    return;
  }
  cbs=self._resave;
  self._resave=[];
  self.save(function(saved) {
    cbs.forEach(function(cb) {
      if (typeof cb==='function') {
        cb(saved);
      }
    });
  });
}

module.exports=Zocci;
<commit_msg>implemented subSelector<commit_after>/*!
 * zocci
 * Copyright(c) 2015-2016 Anatol Sommer <anatol@anatol.at>
 * MIT Licensed
 */

'use strict';

var fs=require('fs'), EE=require('events'), util=require('util'),
  defaults={jsonSpaces:2, delimiter:'.'};

function Zocci(path, opts) {
  this.path=path;
  this.data={};
  this._resave=[];
  if (typeof opts==='object') {
    this.opts=opts;
    opts.jsonSpaces=isDef(opts.jsonSpaces) ? opts.jsonSpaces : defaults.jsonSpaces;
    opts.delimiter=opts.delimiter || defaults.delimiter;
  } else if (typeof opts==='string') {
    this.opts={jsonSpaces:defaults.jsonSpaces, delimiter:opts};
  } else if (typeof opts==='number') {
    this.opts={jsonSpaces:opts, delimiter:defaults.delimiter};
  } else {
    this.opts=defaults;
  }
  if (!this.reload()) {
    this.save();
  }
}

util.inherits(Zocci, EE);

Zocci.prototype.reload=function() {
  var data;
  if (fs.existsSync(this.path)) {
    data=fs.readFileSync(this.path).toString();
    try {
      this.data=JSON.parse(data);
    } catch(err) {
      return false;
    }
    return true;
  }
};

Zocci.prototype.save=function(cb) {
  var self=this, tmp=this.path+tmpName(), spaces=this.opts.jsonSpaces;
  spaces=(typeof spaces==='number' ? spaces : null);
  if (this._saving) {
    this._resave.push(cb || true);
    return;
  }
  this._saving=true;
  fs.writeFile(tmp, JSON.stringify(this.data, null, spaces), function(err) {
    if (err) {
      saved(self);
      if (cb) {
        return cb(err);
      }
      throw err;
    }
    fs.rename(tmp, self.path, function(err) {
      if (typeof cb==='function') {
        cb(err);
      }
      saved(self);
    });
  });
};

Zocci.prototype.access=function(key, def) {
  var data=this.data, curKey;
  key=key.split(this.opts.delimiter);
  while (data && key.length) {
    curKey=key.shift();
    data=data.hasOwnProperty(curKey) ? data[curKey] : null;
  }
  return typeof data!=='undefined' ? data : (def || null);
};

Zocci.prototype.get=function(key, def) {
  return copy(this.access(key, def));
};

Zocci.prototype.set=function(key, val, cb) {
  var data=this.data, curKey;
  this.emit('change', key, val);
  key=key.split(this.opts.delimiter);
  while (key.length>1) {
    curKey=key.shift();
    if (!isDef(data[curKey])) {
      data[curKey]={};
    }
    data=data[curKey];
  }
  data[key[0]]=copy(val);
  this.save(cb);
};

Zocci.prototype.remove=function(key, cb) {
  var data=this.data, curKey=key;
  this.emit('change', key, null);
  key=key.split(this.opts.delimiter);
  while (data && key.length>1) {
    curKey=key.shift();
    data=data.hasOwnProperty(curKey) ? data[curKey] : null;
  }
  if (data && isDef(data[key[0]])) {
    delete data[key[0]];
  }
  this.save(cb);
};

Zocci.prototype.find=function(find, returnKeys) {
  var self=this, keys;
  keys=Object.keys(this.data).filter(function(key) {
    if (typeof find==='string') {
      return key.substr(0, find.length)===find;
    } else if (find && find instanceof RegExp) {
      return !!find.exec(key);
    }
  });
  if (returnKeys) {
    return keys;
  }
  return copy(keys.map(function(key) {
    return self.data[key];
  }));
};

Zocci.prototype.subSelector=function(subKey) {
  var self=this;
  return function(subVal) {
    var delimiter=self.opts.delimiter;
    return {
      get:function(key) {
        return self.get(subKey+delimiter+subVal+(key ? delimiter+key : ''));
      },
      set:function(key, val, cb) {
        self.set(subKey+delimiter+subVal+(key ? delimiter+key : ''), val, cb);
      }
    };
  };
};

function tmpName() {
  return '.'+Date.now().toString(36)+'-'+Math.random().toString(36).substr(2);
}

function isDef(check) {
  return typeof check!=='undefined' && check!==null;
}

function copy(data) {
  return isDef(data) ? JSON.parse(JSON.stringify(data)) : null;
}

function saved(self) {
  var cbs;
  self._saving=false;
  if (!self._resave.length) {
    return;
  }
  cbs=self._resave;
  self._resave=[];
  self.save(function(saved) {
    cbs.forEach(function(cb) {
      if (typeof cb==='function') {
        cb(saved);
      }
    });
  });
}

module.exports=Zocci;
<|endoftext|>


<commit_before>(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('leaflet')) :
        typeof define === 'function' && define.amd ? define(['leaflet'], factory) :
            (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.L = global.L || {}, global.L.NonTiledUTFGrid = factory(global.L)));
})(this, (function (leaflet) {
    'use strict';

    /*
     * L.NonTiledLayer is an addon for leaflet which renders dynamic image overlays
     */
    const NonTiledUTFGrid = leaflet.Layer.extend({
        emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
        options: {
            attribution: '',
            opacity: 1.0,
            zIndex: undefined,
            minZoom: 0,
            maxZoom: 18,
            pointerEvents: undefined,
            errorImageUrl: 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
            bounds: new leaflet.LatLngBounds([-85.05, -180], [85.05, 180]),
            detectRetina: false,
        },
        key: '',
        _cache: null, // {<tileKey>: <utfgrid>}
        _map: null,

        _throttleMove: null, // holds throttled mousemove handler
        // override this method in the inherited class
        // getImageUrl: function (bounds, width, height) {},
        // getImageUrlAsync: function (bounds, width, height, f) {},
        initialize: function initialize(options) {

            leaflet.setOptions(this, options);
        },
        onAdd: function onAdd(map) {
            this._cache = {};
            this._map = map;

            this._updateCursor = function (cursor) {
                //console.log(this)
            }; //no-op, overridden below
            if (!this._div) {
                this._div = leaflet.DomUtil.create('div', 'leaflet-utfgrid-layer');
                if (this.options.pointerEvents) {
                    this._div.style['pointer-events'] = this.options.pointerEvents;
                }
                if (typeof this.options.zIndex !== 'undefined') {
                    this._div.style.zIndex = this.options.zIndex;
                }
                if (typeof this.options.opacity !== 'undefined') {
                    this._div.style.opacity = this.options.opacity;
                }
            }
            this._throttleMove = L.Util.throttle(this._move, 66, this);
            this.getPane().appendChild(this._div);
            // this._bufferImage = this._initImage();
            this._currentImage = this._initImage();
            this._update();
            this._connectMapEventHandlers();
        },
        _connectMapEventHandlers: function () {
            //this._map.on('click', this._onClick, this);
            this._map.on('mousemove', this._throttleMove, this);
        },
        _disconnectMapEventHandlers: function () {
            // this._map.off('click', this._onClick, this);
            this._map.off('mousemove', this._throttleMove, this);
        },
        onRemove: function onRemove() {
            this.getPane().removeChild(this._div);
            // this._div.removeChild(this._bufferImage);
            this._div.removeChild(this._currentImage);
            this._disconnectMapEventHandlers();
            // NonTiledUTFGrid.prototype.onRemove.call(this, map);
        },
        addTo: function addTo(map) {
            map.addLayer(this);
            return this;
        },
        _setZoom: function setZoom() {
            if (this._currentImage._bounds)
                this._resetImageScale(this._currentImage, true);
            // if (this._bufferImage._bounds)
            //     this._resetImageScale(this._bufferImage);
        },
        getEvents: function getEvents() {
            const events = {
                moveend: this._update,
            };
            if (this._zoomAnimated) {
                events.zoomanim = this._animateZoom;
            }
            events.zoom = this._setZoom;
            return events;
        },
        getElement: function getElement() {
            return this._div;
        },
        setOpacity: function setOpacity(opacity) {
            this.options.opacity = opacity;
            if (this._div) {
                leaflet.DomUtil.setOpacity(this._div, this.options.opacity);
            }
            return this;
        },
        _initImage: function initImage() {
            const image = leaflet.DomUtil.create('iframe', 'leaflet-utfgrid-layer');
            if (this.options.crossOrigin) {
                image.crossOrigin = this.options.crossOrigin;
            }
            //this._div.appendChild(image);
            if (this._map.options.zoomAnimation && leaflet.Browser.any3d) {
                leaflet.DomUtil.addClass(image, 'leaflet-zoom-animated');
            } else {
                leaflet.DomUtil.addClass(image, 'leaflet-zoom-hide');
            }
            // TODO createImage util method to remove duplication
            leaflet.extend(image, {
                galleryimg: 'no',
                onselectstart: leaflet.Util.falseFn,
                onmousemove: leaflet.Util.falseFn,
                onload: leaflet.bind(this._onImageLoad, this),
                onerror: leaflet.bind(this._onImageLoad, this),
            });
            return image;
        },
        redraw: function redraw() {
            if (this._map) {
                this._update();
            }
            return this;
        },
        _resetImageScale: function resetImageScale(image) {
            const bounds = new leaflet.Bounds(this._map.latLngToLayerPoint(image._bounds.getNorthWest()), this._map.latLngToLayerPoint(image._bounds.getSouthEast()));
            const orgSize = image._orgBounds.getSize().y;
            const scaledSize = bounds.getSize().y;
            const scale = scaledSize / orgSize;
            image._sscale = scale;
            leaflet.DomUtil.setTransform(image, bounds.min, scale);
        },
        _resetImage: function resetImage(image) {
            const bounds = new leaflet.Bounds(this._map.latLngToLayerPoint(image._bounds.getNorthWest()), this._map.latLngToLayerPoint(image._bounds.getSouthEast()));
            const size = bounds.getSize();
            leaflet.DomUtil.setPosition(image, bounds.min);
            image._orgBounds = bounds;
            image._sscale = 1;
            if (this._useCanvas) {
                image.width = size.x;
                image.height = size.y;
            } else {
                image.style.width = `${size.x}px`;
                image.style.height = `${size.y}px`;
            }
        },
        _getImageScale: function getImageScale() {
            return this.options.detectRetina && leaflet.Browser.retina ? 2 : 1;
        },
        _getClippedBounds: function getClippedBounds() {
            const wgsBounds = this._map.getBounds();
            // truncate bounds to valid wgs bounds
            let mSouth = wgsBounds.getSouth();
            let mNorth = wgsBounds.getNorth();
            let mWest = wgsBounds.getWest();
            let mEast = wgsBounds.getEast();
            const lSouth = this.options.bounds.getSouth();
            const lNorth = this.options.bounds.getNorth();
            const lWest = this.options.bounds.getWest();
            const lEast = this.options.bounds.getEast();
            // mWest = (mWest + 180) % 360 - 180;
            if (mSouth < lSouth)
                mSouth = lSouth;
            if (mNorth > lNorth)
                mNorth = lNorth;
            if (mWest < lWest)
                mWest = lWest;
            if (mEast > lEast)
                mEast = lEast;
            const world1 = new leaflet.LatLng(mNorth, mWest);
            const world2 = new leaflet.LatLng(mSouth, mEast);
            return new leaflet.LatLngBounds(world1, world2);
        },
        _update: function update() {
            const bounds = this._getClippedBounds();
            // re-project to corresponding pixel bounds
            const pix1 = this._map.latLngToContainerPoint(bounds.getNorthWest());
            const pix2 = this._map.latLngToContainerPoint(bounds.getSouthEast());
            // get pixel size
            let width = pix2.x - pix1.x;
            let height = pix2.y - pix1.y;
            let i;
            // set scales for zoom animation
            // this._bufferImage._scale = this._bufferImage._lastScale;
            this._currentImage._scale = 1;
            this._currentImage._lastScale = this._currentImage._scale;
            // this._bufferImage._sscale = 1;
            this._currentImage._bounds = bounds;
            this._resetImage(this._currentImage);
            i = this._currentImage;
            leaflet.DomUtil.setOpacity(i, 0);
            if (this._map.getZoom() < this.options.minZoom
                || this._map.getZoom() > this.options.maxZoom
                || width < 32
                || height < 32) {
                this._div.style.visibility = 'hidden';
                i.src = this.emptyImageUrl;
                i.key = '<empty>';
                this.key = i.key;
                i.tag = null;
                return;
            }
            // fire loading event
            this.fire('loading');
            width *= this._getImageScale();
            height *= this._getImageScale();
            // create a key identifying the current request
            this.key = [bounds.getNorthWest(), bounds.getSouthEast(), width, height].join(', ');
            let _self = this;
            if (this.getImageUrl) {
                i.src = this.getImageUrl(bounds, width, height);
                console.log(i.src)
                i.key = this.key;
                $.getJSON(i.src, function (data) {

                    _self._cache["test"] = data;
                });
            } else {
                this.getImageUrlAsync(bounds, width, height, this.key, (key, url, tag) => {
                    i.key = key;
                    i.src = url;
                    i.tag = tag;
                });
            }
        },
        _onImageError: function onImageError(e) {
            // this.fire('error', e);
            // leaflet.DomUtil.addClass(e.target, 'invalid');
            // prevent error loop if error image is not valid
            if (e.target.src !== this.options.errorImageUrl) {
                // e.target.src = this.options.errorImageUrl;
            }
        },
        _onImageLoad: function onImageLoad(e) {
            if (e.target.src !== this.options.errorImageUrl) {
                leaflet.DomUtil.removeClass(e.target, 'invalid');
                if (!e.target.key || e.target.key !== this.key) { // obsolete / outdated image
                    return;
                }
            }
            this._onImageDone(e);
            this.fire('load', e);
        },
        _onImageDone: function onImageDone(e) {
            this._cache["test"] = JSON.parse(e.target.contentWindow.document.body.innerText);
            // let tmp;
            // leaflet.DomUtil.setOpacity(this._currentImage, 1);
            // leaflet.DomUtil.setOpacity(this._bufferImage, 0);
            // if (this._addInteraction && this._currentImage.tag) {
            //     this._addInteraction(this._currentImage.tag);
            // }
            // tmp = this._bufferImage;
            // this._bufferImage = this._currentImage;
            // this._currentImage = tmp;
            // if (e.target.key !== '<empty>') {
            //     this._div.style.visibility = 'visible';
            // }
        },

        _move: function (e) {
            if (e.latlng == null) {
                return
            }

            var on = this._objectForEvent(e);

            if (on._tileCharCode !== this._tileCharCode) {
                if (this._mouseOn) {
                    this.fire('mouseout', {
                        latlng: e.latlng,
                        data: this._mouseOn,
                        _tile: this._mouseOnTile,
                        _tileCharCode: this._tileCharCode
                    });
                    this._updateCursor('');
                }
                if (on.data) {
                    this.fire('mouseover', on);
                    this._updateCursor('pointer');
                }

                this._mouseOn = on.data;
                this._mouseOnTile = on._tile;
                this._tileCharCode = on._tileCharCode;
            } else if (on.data) {
                this.fire('mousemove', on);
            }
        },
        _objectForEvent: function (e) {
            if (!e.latlng) return;  // keyboard <ENTER> events also pass through as click events but don't have latlng

            var map = this._map,
                point = map.latLngToContainerPoint(e.latlng),
                resolution = 4,
                gridX = Math.floor(point.x / resolution),
                gridY = Math.floor(point.y / resolution);

            var data = this._cache["test"];
            if (!data) {
                return {
                    latlng: e.latlng,
                    data: null,
                    _tile: null,
                    _tileCharCode: null
                };
            }

            var charCode;
            try {
                charCode = data.grid[gridY].charCodeAt(gridX);
            } catch (e) {
            }
            var idx = this._utfDecode(charCode),
                key = data.keys[idx],
                result = data.data[key];

            if (!data.data.hasOwnProperty(key)) {
                result = null;
            }

            return {
                latlng: e.latlng,
                data: result,
                id: (result) ? result.id : null,
                _tile: "test",
                _tileCharCode: "test" + ':' + charCode
            };
        },
        _dataForCharCode: function (tileKey, charCode) {
            var data = this._cache["test"];
            var idx = this._utfDecode(charCode),
                key = data.keys[idx],
                result = data.data[key];

            if (!data.data.hasOwnProperty(key)) {
                result = null;
            }
            return result;
        },

        _utfDecode: function (c) {
            if (c >= 93) {
                c--;
            }
            if (c >= 35) {
                c--;
            }
            return c - 32;
        },

        _utfEncode: function (c) {
            //reverse of above, returns charCode for c
            //derived from: https://github.com/mapbox/glower/blob/mb-pages/src/glower.js#L37
            var charCode = c + 32;
            if (charCode >= 34) {
                charCode++;
            }
            if (charCode >= 92) {
                charCode++;
            }
            return charCode;
        }
    });
    /*
     * L.NonTiledLayer.WMS is used for putting WMS non tiled layers on the map.
     */
    NonTiledUTFGrid.WMS = NonTiledUTFGrid.extend({
        defaultWmsParams: {
            service: 'WMS',
            request: 'GetMap',
            version: '1.1.1',
            layers: '',
            styles: '',
            format: 'image/jpeg',
            transparent: false,
        },
        options: {
            crs: null,
            uppercase: false,
        },
        initialize: function initialize(url, options) {
            let i;
            this._wmsUrl = url;
            const wmsParams = leaflet.extend({}, this.defaultWmsParams);
            // all keys that are not NonTiledLayer options go to WMS params
            for (i in options) {
                if (!Object.prototype.hasOwnProperty.call(NonTiledUTFGrid.prototype.options, i)
                    && !(leaflet.Layer && Object.prototype.hasOwnProperty.call(leaflet.Layer.prototype.options, i))) {
                    wmsParams[i] = options[i];
                }
            }
            this.wmsParams = wmsParams;
            leaflet.setOptions(this, options);
        },
        onAdd: function onAdd(map) {
            this._crs = this.options.crs || map.options.crs;
            this._wmsVersion = parseFloat(this.wmsParams.version);
            const projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
            this.wmsParams[projectionKey] = this._crs.code;
            NonTiledUTFGrid.prototype.onAdd.call(this, map);
        },
        getImageUrl: function getImageUrl(bounds, width, height) {
            const {wmsParams} = this;
            wmsParams.width = width;
            wmsParams.height = height;
            const nw = this._crs.project(bounds.getNorthWest());
            const se = this._crs.project(bounds.getSouthEast());
            const url = this._wmsUrl;
            const bbox = (this._wmsVersion >= 1.3 && this._crs === leaflet.CRS.EPSG4326
                ? [se.y, nw.x, nw.y, se.x]
                : [nw.x, se.y, se.x, nw.y]).join(',');
            return url + leaflet.Util.getParamString(this.wmsParams, url, this.options.uppercase) + (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
        },
        setParams: function setParams(params, noRedraw) {

            leaflet.extend(this.wmsParams, params);
            if (!noRedraw) {
                this.redraw();
            }
            return this;
        },
    });

    return NonTiledUTFGrid;

}));
<commit_msg>Clean up<commit_after>(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('leaflet')) :
        typeof define === 'function' && define.amd ? define(['leaflet'], factory) :
            (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.L = global.L || {}, global.L.NonTiledUTFGrid = factory(global.L)));
})(this, (function (leaflet) {
    'use strict';

    /*
     * L.NonTiledLayer is an addon for leaflet which renders dynamic image overlays
     */
    const NonTiledUTFGrid = leaflet.Layer.extend({
        emptyImageUrl: 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
        options: {
            attribution: '',
            opacity: 1.0,
            zIndex: undefined,
            minZoom: 0,
            maxZoom: 18,
            pointerEvents: undefined,
            errorImageUrl: 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',
            bounds: new leaflet.LatLngBounds([-85.05, -180], [85.05, 180]),
            detectRetina: false,
        },
        key: '',
        _cache: null, // {<tileKey>: <utfgrid>}
        _map: null,

        _throttleMove: null, // holds throttled mousemove handler
        // override this method in the inherited class
        // getImageUrl: function (bounds, width, height) {},
        // getImageUrlAsync: function (bounds, width, height, f) {},
        initialize: function initialize(options) {

            leaflet.setOptions(this, options);
        },
        onAdd: function onAdd(map) {
            this._cache = {};
            this._map = map;

            this._updateCursor = function (cursor) {
                //console.log(this)
            }; //no-op, overridden below
            if (!this._div) {
                this._div = leaflet.DomUtil.create('div', 'leaflet-utfgrid-layer');
                if (this.options.pointerEvents) {
                    this._div.style['pointer-events'] = this.options.pointerEvents;
                }
                if (typeof this.options.zIndex !== 'undefined') {
                    this._div.style.zIndex = this.options.zIndex;
                }
                if (typeof this.options.opacity !== 'undefined') {
                    this._div.style.opacity = this.options.opacity;
                }
            }
            this._throttleMove = L.Util.throttle(this._move, 66, this);
            this.getPane().appendChild(this._div);
            // this._bufferImage = this._initImage();
            this._currentImage = this._initImage();
            this._update();
            this._connectMapEventHandlers();
        },
        _connectMapEventHandlers: function () {
            //this._map.on('click', this._onClick, this);
            this._map.on('mousemove', this._throttleMove, this);
        },
        _disconnectMapEventHandlers: function () {
            // this._map.off('click', this._onClick, this);
            this._map.off('mousemove', this._throttleMove, this);
        },
        onRemove: function onRemove() {
            this.getPane().removeChild(this._div);
            // this._div.removeChild(this._bufferImage);
            this._div.removeChild(this._currentImage);
            this._disconnectMapEventHandlers();
            // NonTiledUTFGrid.prototype.onRemove.call(this, map);
        },
        addTo: function addTo(map) {
            map.addLayer(this);
            return this;
        },
        _setZoom: function setZoom() {
            if (this._currentImage._bounds)
                this._resetImageScale(this._currentImage, true);
            // if (this._bufferImage._bounds)
            //     this._resetImageScale(this._bufferImage);
        },
        getEvents: function getEvents() {
            const events = {
                moveend: this._update,
            };
            if (this._zoomAnimated) {
                events.zoomanim = this._animateZoom;
            }
            events.zoom = this._setZoom;
            return events;
        },
        getElement: function getElement() {
            return this._div;
        },
        setOpacity: function setOpacity(opacity) {
            this.options.opacity = opacity;
            if (this._div) {
                leaflet.DomUtil.setOpacity(this._div, this.options.opacity);
            }
            return this;
        },
        _initImage: function initImage() {
            const image = leaflet.DomUtil.create('iframe', 'leaflet-utfgrid-layer');
            if (this.options.crossOrigin) {
                image.crossOrigin = this.options.crossOrigin;
            }
            //this._div.appendChild(image);
            if (this._map.options.zoomAnimation && leaflet.Browser.any3d) {
                leaflet.DomUtil.addClass(image, 'leaflet-zoom-animated');
            } else {
                leaflet.DomUtil.addClass(image, 'leaflet-zoom-hide');
            }
            // TODO createImage util method to remove duplication
            leaflet.extend(image, {
                galleryimg: 'no',
                onselectstart: leaflet.Util.falseFn,
                onmousemove: leaflet.Util.falseFn,
                onload: leaflet.bind(this._onImageLoad, this),
                onerror: leaflet.bind(this._onImageLoad, this),
            });
            return image;
        },
        redraw: function redraw() {
            if (this._map) {
                this._update();
            }
            return this;
        },
        _resetImageScale: function resetImageScale(image) {
            const bounds = new leaflet.Bounds(this._map.latLngToLayerPoint(image._bounds.getNorthWest()), this._map.latLngToLayerPoint(image._bounds.getSouthEast()));
            const orgSize = image._orgBounds.getSize().y;
            const scaledSize = bounds.getSize().y;
            const scale = scaledSize / orgSize;
            image._sscale = scale;
            leaflet.DomUtil.setTransform(image, bounds.min, scale);
        },
        _resetImage: function resetImage(image) {
            const bounds = new leaflet.Bounds(this._map.latLngToLayerPoint(image._bounds.getNorthWest()), this._map.latLngToLayerPoint(image._bounds.getSouthEast()));
            const size = bounds.getSize();
            leaflet.DomUtil.setPosition(image, bounds.min);
            image._orgBounds = bounds;
            image._sscale = 1;
            if (this._useCanvas) {
                image.width = size.x;
                image.height = size.y;
            } else {
                image.style.width = `${size.x}px`;
                image.style.height = `${size.y}px`;
            }
        },
        _getImageScale: function getImageScale() {
            return this.options.detectRetina && leaflet.Browser.retina ? 2 : 1;
        },
        _getClippedBounds: function getClippedBounds() {
            const wgsBounds = this._map.getBounds();
            // truncate bounds to valid wgs bounds
            let mSouth = wgsBounds.getSouth();
            let mNorth = wgsBounds.getNorth();
            let mWest = wgsBounds.getWest();
            let mEast = wgsBounds.getEast();
            const lSouth = this.options.bounds.getSouth();
            const lNorth = this.options.bounds.getNorth();
            const lWest = this.options.bounds.getWest();
            const lEast = this.options.bounds.getEast();
            // mWest = (mWest + 180) % 360 - 180;
            if (mSouth < lSouth)
                mSouth = lSouth;
            if (mNorth > lNorth)
                mNorth = lNorth;
            if (mWest < lWest)
                mWest = lWest;
            if (mEast > lEast)
                mEast = lEast;
            const world1 = new leaflet.LatLng(mNorth, mWest);
            const world2 = new leaflet.LatLng(mSouth, mEast);
            return new leaflet.LatLngBounds(world1, world2);
        },
        _update: function update() {
            const bounds = this._getClippedBounds();
            // re-project to corresponding pixel bounds
            const pix1 = this._map.latLngToContainerPoint(bounds.getNorthWest());
            const pix2 = this._map.latLngToContainerPoint(bounds.getSouthEast());
            // get pixel size
            let width = pix2.x - pix1.x;
            let height = pix2.y - pix1.y;
            let i;
            // set scales for zoom animation
            // this._bufferImage._scale = this._bufferImage._lastScale;
            this._currentImage._scale = 1;
            this._currentImage._lastScale = this._currentImage._scale;
            // this._bufferImage._sscale = 1;
            this._currentImage._bounds = bounds;
            this._resetImage(this._currentImage);
            i = this._currentImage;
            leaflet.DomUtil.setOpacity(i, 0);
            if (this._map.getZoom() < this.options.minZoom
                || this._map.getZoom() > this.options.maxZoom
                || width < 32
                || height < 32) {
                this._div.style.visibility = 'hidden';
                i.src = this.emptyImageUrl;
                i.key = '<empty>';
                this.key = i.key;
                i.tag = null;
                return;
            }
            // fire loading event
            this.fire('loading');
            width *= this._getImageScale();
            height *= this._getImageScale();
            // create a key identifying the current request
            this.key = [bounds.getNorthWest(), bounds.getSouthEast(), width, height].join(', ');
            let _self = this;
            if (this.getImageUrl) {
                i.src = this.getImageUrl(bounds, width, height);
                i.key = this.key;
                $.getJSON(i.src, function (data) {
                    _self._cache["test"] = data;
                });
            } else {
                this.getImageUrlAsync(bounds, width, height, this.key, (key, url, tag) => {
                    i.key = key;
                    i.src = url;
                    i.tag = tag;
                });
            }
        },
        _onImageError: function onImageError(e) {
            // this.fire('error', e);
            // leaflet.DomUtil.addClass(e.target, 'invalid');
            // prevent error loop if error image is not valid
            if (e.target.src !== this.options.errorImageUrl) {
                // e.target.src = this.options.errorImageUrl;
            }
        },
        _onImageLoad: function onImageLoad(e) {
            if (e.target.src !== this.options.errorImageUrl) {
                leaflet.DomUtil.removeClass(e.target, 'invalid');
                if (!e.target.key || e.target.key !== this.key) { // obsolete / outdated image
                    return;
                }
            }
            this._onImageDone(e);
            this.fire('load', e);
        },
        _onImageDone: function onImageDone(e) {
            this._cache["test"] = JSON.parse(e.target.contentWindow.document.body.innerText);
            // let tmp;
            // leaflet.DomUtil.setOpacity(this._currentImage, 1);
            // leaflet.DomUtil.setOpacity(this._bufferImage, 0);
            // if (this._addInteraction && this._currentImage.tag) {
            //     this._addInteraction(this._currentImage.tag);
            // }
            // tmp = this._bufferImage;
            // this._bufferImage = this._currentImage;
            // this._currentImage = tmp;
            // if (e.target.key !== '<empty>') {
            //     this._div.style.visibility = 'visible';
            // }
        },

        _move: function (e) {
            if (e.latlng == null) {
                return
            }

            var on = this._objectForEvent(e);

            if (on._tileCharCode !== this._tileCharCode) {
                if (this._mouseOn) {
                    this.fire('mouseout', {
                        latlng: e.latlng,
                        data: this._mouseOn,
                        _tile: this._mouseOnTile,
                        _tileCharCode: this._tileCharCode
                    });
                    this._updateCursor('');
                }
                if (on.data) {
                    this.fire('mouseover', on);
                    this._updateCursor('pointer');
                }

                this._mouseOn = on.data;
                this._mouseOnTile = on._tile;
                this._tileCharCode = on._tileCharCode;
            } else if (on.data) {
                this.fire('mousemove', on);
            }
        },
        _objectForEvent: function (e) {
            if (!e.latlng) return;  // keyboard <ENTER> events also pass through as click events but don't have latlng

            var map = this._map,
                point = map.latLngToContainerPoint(e.latlng),
                resolution = 4,
                gridX = Math.floor(point.x / resolution),
                gridY = Math.floor(point.y / resolution);

            var data = this._cache["test"];
            if (!data) {
                return {
                    latlng: e.latlng,
                    data: null,
                    _tile: null,
                    _tileCharCode: null
                };
            }

            var charCode;
            try {
                charCode = data.grid[gridY].charCodeAt(gridX);
            } catch (e) {
            }
            var idx = this._utfDecode(charCode),
                key = data.keys[idx],
                result = data.data[key];

            if (!data.data.hasOwnProperty(key)) {
                result = null;
            }

            return {
                latlng: e.latlng,
                data: result,
                id: (result) ? result.id : null,
                _tile: "test",
                _tileCharCode: "test" + ':' + charCode
            };
        },
        _dataForCharCode: function (tileKey, charCode) {
            var data = this._cache["test"];
            var idx = this._utfDecode(charCode),
                key = data.keys[idx],
                result = data.data[key];

            if (!data.data.hasOwnProperty(key)) {
                result = null;
            }
            return result;
        },

        _utfDecode: function (c) {
            if (c >= 93) {
                c--;
            }
            if (c >= 35) {
                c--;
            }
            return c - 32;
        },

        _utfEncode: function (c) {
            //reverse of above, returns charCode for c
            //derived from: https://github.com/mapbox/glower/blob/mb-pages/src/glower.js#L37
            var charCode = c + 32;
            if (charCode >= 34) {
                charCode++;
            }
            if (charCode >= 92) {
                charCode++;
            }
            return charCode;
        }
    });
    /*
     * L.NonTiledLayer.WMS is used for putting WMS non tiled layers on the map.
     */
    NonTiledUTFGrid.WMS = NonTiledUTFGrid.extend({
        defaultWmsParams: {
            service: 'WMS',
            request: 'GetMap',
            version: '1.1.1',
            layers: '',
            styles: '',
            format: 'image/jpeg',
            transparent: false,
        },
        options: {
            crs: null,
            uppercase: false,
        },
        initialize: function initialize(url, options) {
            let i;
            this._wmsUrl = url;
            const wmsParams = leaflet.extend({}, this.defaultWmsParams);
            // all keys that are not NonTiledLayer options go to WMS params
            for (i in options) {
                if (!Object.prototype.hasOwnProperty.call(NonTiledUTFGrid.prototype.options, i)
                    && !(leaflet.Layer && Object.prototype.hasOwnProperty.call(leaflet.Layer.prototype.options, i))) {
                    wmsParams[i] = options[i];
                }
            }
            this.wmsParams = wmsParams;
            leaflet.setOptions(this, options);
        },
        onAdd: function onAdd(map) {
            this._crs = this.options.crs || map.options.crs;
            this._wmsVersion = parseFloat(this.wmsParams.version);
            const projectionKey = this._wmsVersion >= 1.3 ? 'crs' : 'srs';
            this.wmsParams[projectionKey] = this._crs.code;
            NonTiledUTFGrid.prototype.onAdd.call(this, map);
        },
        getImageUrl: function getImageUrl(bounds, width, height) {
            const {wmsParams} = this;
            wmsParams.width = width;
            wmsParams.height = height;
            const nw = this._crs.project(bounds.getNorthWest());
            const se = this._crs.project(bounds.getSouthEast());
            const url = this._wmsUrl;
            const bbox = (this._wmsVersion >= 1.3 && this._crs === leaflet.CRS.EPSG4326
                ? [se.y, nw.x, nw.y, se.x]
                : [nw.x, se.y, se.x, nw.y]).join(',');
            return url + leaflet.Util.getParamString(this.wmsParams, url, this.options.uppercase) + (this.options.uppercase ? '&BBOX=' : '&bbox=') + bbox;
        },
        setParams: function setParams(params, noRedraw) {

            leaflet.extend(this.wmsParams, params);
            if (!noRedraw) {
                this.redraw();
            }
            return this;
        },
    });

    return NonTiledUTFGrid;

}));
<|endoftext|>


<commit_before>// document ready event
$(document).ready(
	// inner function for the ready() event
	function() {

		// tell the validator to validate this form
		$("#register-form").validate({
			debug: true,
			// setup the formatting for the errors
			errorClass: "alert alert-danger",
			errorLabelContainer: "#registerError",
			wrapper: "li",

			// rules define what is good/bad input
			rules: {

				// each rule starts with the inputs name (NOT id)
				firstName: {
					minlength: 2,
					required: true
				},

				lastName: {
					minlength: 2,
					required: true
				},

				userName: {
					minlength: 5,
					required: true
				},

				email: {
					required: true,
					email: true
				},

				password: {
					minlength: 7,
					required: true
				},

				confirmPassword: {
					equalTo: "#password",
					required: true

				}

			},

			// error messages to display to the end user
			messages: {

				firstName: {
					minlength: "enter at least two characters",
					required: "please enter a valid first name"
				},

				lastName: {
					minlength: "enter at least two characters",
					required: "please enter a valid last name"
				},

				userName: {
					minlength: "enter at least five characters",
					required: "please enter a valid user name"

				},

				email: {
					required: "must enter email address",
					email: "please enter  a valid email address"
				},

				password: {
					minlength: "please enter 7 characters",
					required: "please enter valid password"
				},

				confirmPassword: {
					equalTo: "passwords do not match",
					required: "please re-enter the password"
				}

			},

			// setup an AJAX call to submit the form without reloading
			submitHandler: function(form) {
				$("#register-form").ajaxSubmit({
					// GET or POST
					type: "POST",
					// where to submit data
					url: $("#register-form").attr("action"),
					// this sends the XSRF token along with the form data
					headers: {
						"X-XSRF-TOKEN": Cookies.get("XSRF-TOKEN")
					},
					// success is an event that happens when the server replies
					success: function(ajaxOutput) {
						// clear the output area's formatting
						$("#registerError").css("display", "");
						// write the server's reply to the output area
						$("#registerError").html(ajaxOutput);
						$("#loginError").html(ajaxOutput);

					//	 reset the form if it was successful
					//	 this makes it easier to reuse the form again
				   		if($(".alert-success").length > 0) {
							$("#register-form")[0].reset();

							//refresh page on successful login
						setTimeout(function() {
								location.reload(true);
							}, 1000);
						}
					}
				});
				$("#register-submit").click(function() {
				});
			}
		});
	});<commit_msg>fixed register-controller.js.<commit_after>// document ready event
$(document).ready(
	// inner function for the ready() event
	function() {

		// tell the validator to validate this form
		$("#register-form").validate({
			debug: true,
			// setup the formatting for the errors
			errorClass: "alert alert-danger",
			errorLabelContainer: "#registerError",
			wrapper: "li",

			// rules define what is good/bad input
			rules: {

				// each rule starts with the inputs name (NOT id)
				firstName: {
					minlength: 2,
					required: true
				},

				lastName: {
					minlength: 2,
					required: true
				},

				userName: {
					minlength: 5,
					required: true
				},

				email: {
					required: true,
					email: true
				},

				password: {
					minlength: 7,
					required: true
				},

				confirmPassword: {
					equalTo: "#password",
					required: true

				}

			},

			// error messages to display to the end user
			messages: {

				firstName: {
					minlength: "enter at least two characters",
					required: "please enter a valid first name"
				},

				lastName: {
					minlength: "enter at least two characters",
					required: "please enter a valid last name"
				},

				userName: {
					minlength: "enter at least five characters",
					required: "please enter a valid user name"

				},

				email: {
					required: "must enter email address",
					email: "please enter  a valid email address"
				},

				password: {
					minlength: "please enter 7 characters",
					required: "please enter valid password"
				},

				confirmPassword: {
					equalTo: "passwords do not match",
					required: "please re-enter the password"
				}

			},

			// setup an AJAX call to submit the form without reloading
			submitHandler: function(form) {
				$("#register-form").ajaxSubmit({
					// GET or POST
					type: "POST",
					// where to submit data
					url: $("#register-form").attr("action"),
					// this sends the XSRF token along with the form data
					headers: {
						"X-XSRF-TOKEN": Cookies.get("XSRF-TOKEN")
					},
					// success is an event that happens when the server replies
					success: function(ajaxOutput) {
						// clear the output area's formatting
						$("#registerError").css("display", "");
						// write the server's reply to the output area
						$("#registerError").html(ajaxOutput);

					//	 reset the form if it was successful
					//	 this makes it easier to reuse the form again
			//	   		if($(".alert-success").length > 0) {
				//			$("#register-form")[0].reset();

							//refresh page on successful login
				//		setTimeout(function() {
				//				location.reload(true);
				//			}, 1000);
				//		}
					}
				});
				$("#register-submit").click(function() {
				});
			}
		});
	});<|endoftext|>


<commit_before>/* ========================================================================
 * listgroup.js v1.0.0
 * http://rickardn.github.io/listgroup.js
 * ========================================================================
 * Copyright 2014 Rickard Nilsson
 * Licensed under MIT (https://github.com/rickardn/listgroup.js/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
    "use strict";

    // LISTGROUP PUBLIC CLASS DEFINITION
    // =======================
    var ListGroup = function (element, options) {
        this.$element = $(element);
        this.options = options || {};
        this.init();
    };

    ListGroup.prototype.init = function() {
        var me = this;
        var $element = this.$element;
        var options = this.options;

        if (options.toggle)
            $element.data('toggle', options.toggle);

        $element.on('click', '.list-group-item', function () {
            var $item = $(this);

            if ($element.data('toggle') == 'buttons')
                $item.toggleClass('active');
            else
                me.unselect('*')
                  .select($item);

            $item.blur();

            if (options.click)
                options.click.apply(this);

            return false;
        });
    };

    ListGroup.prototype.select = function (item) {
        if (item instanceof $)
            item.addClass('active');

        if (typeof item === 'string')
            item = [item];

        if (Array.isArray(item)) {
            for (var i in item) {
                var val = item[i];
                this.$element
                    .find('.list-group-item[data-value=\'' + val + '\']')
                    .addClass('active');
            }
        }
        return this;
    };

    ListGroup.prototype.unselect = function (selector) {
        this.$element
                .find('.list-group-item')
                .filter(selector || '*')
                    .removeClass('active');
        return this;
    };

    // SELECTLIST PUBLIC CLASS DEFINITION
    // =======================
    var SelectList = function(element, options) {
        this.$element = $(element);
        this.options = options;
        this.$listGroup = this.createListGroup();
    };

    SelectList.prototype.select = function (values) {
        if (values instanceof $) {
            var vals = [];
            values.each(function(i, element) {
                vals.push($(element).val());
            });
            values = vals;
        }

        this.$element.val(values)
                     .change();
    };

    SelectList.prototype.unselect = function(values) {
        var value = this.$element.val();

        if (!Array.isArray(value)) value = [value];
        if (!Array.isArray(values)) values = [values];

        for (var i in values)
            value.pop(values[i]);

        this.$element.val(value)
                     .change();
    };

    SelectList.prototype.createListGroup = function() {
        var $select = this.$element;

        var $listGroup = $('

');

        if ($select.attr('multiple'))
            $listGroup.data('toggle', 'buttons');

        $select.find('option').each(function (i, item) {
            var $item = $(item);
            var $new = $(''
                       + $item.text() + '');
            $listGroup.append($new);
        });

        $select.change(function () {
            $listGroup.listgroup({
                unselect: '*',
                select: $select.val()
            });
        });

        $listGroup.listgroup({
            select: $select.val(),
            click: function () {
                var values = [];
                $listGroup.find('.list-group-item.active').each(function(i, item) {
                    var value = $(item).data('value');
                    values.push(value);
                });
                if (values.length == 1) values = values[0];
                $select.val(values);
            }
        });
        $select.before($listGroup);
        this.$listGroup = $listGroup;

        $select.hide();

        return $listGroup;
    };

    // LIST GROUP PLUGIN DEFINITION
    // =======================
    $.fn.listgroup = function (option) {
        return this.each(function (i, element) {
            var $element = $(element);

            var list = $element.data('listgroup');
            if (!list)
                $element.data('listgroup', (list = $element.is('select')
                    ? new SelectList(element, option)
                    : new ListGroup(element, option)));

            if (option) {

                if (option.unselect)
                    list.unselect(option.unselect);

                if (option.select)
                    list.select(option.select);
            }
        });
    };

    $(function () {
        $('.list-group').listgroup();
    });
}(jQuery);
<commit_msg>Started work on v1.1<commit_after>/*!========================================================================
 * listgroup.js v1.1.0
 * http://rickardn.github.io/listgroup.js
 * ========================================================================
 * Copyright 2014 Rickard Nilsson
 * Licensed under MIT (https://github.com/rickardn/listgroup.js/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
    "use strict";

    // LISTGROUP PUBLIC CLASS DEFINITION
    // =======================
    var ListGroup = function (element, options) {
        this.$element = $(element);
        this.options = options || {};
        this.init();
    };

    ListGroup.prototype.init = function() {
        var me = this;
        var $element = this.$element;
        var options = this.options;

        if (options.toggle)
            $element.data('toggle', options.toggle);

        $element.on('click', '.list-group-item', function () {
            var $item = $(this);

            if ($element.data('toggle') == 'buttons')
                $item.toggleClass('active');
            else
                me.unselect('*')
                  .select($item);

            $item.blur();

            if (options.click)
                options.click.apply(this);

            return false;
        });
    };

    ListGroup.prototype.select = function (item) {
        if (item instanceof $)
            item.addClass('active');

        if (typeof item === 'string')
            item = [item];

        if (Array.isArray(item)) {
            for (var i in item) {
                var val = item[i];
                this.$element
                    .find('.list-group-item[data-value=\'' + val + '\']')
                    .addClass('active');
            }
        }
        return this;
    };

    ListGroup.prototype.unselect = function (selector) {
        this.$element
                .find('.list-group-item')
                .filter(selector || '*')
                    .removeClass('active');
        return this;
    };

    // SELECTLIST PUBLIC CLASS DEFINITION
    // =======================
    var SelectList = function(element, options) {
        this.$element = $(element);
        this.options = options;
        this.$listGroup = this.createListGroup();
    };

    SelectList.prototype.select = function (values) {
        if (values instanceof $) {
            var vals = [];
            values.each(function(i, element) {
                vals.push($(element).val());
            });
            values = vals;
        }

        this.$element.val(values)
                     .change();
    };

    SelectList.prototype.unselect = function(values) {
        var value = this.$element.val();

        if (!Array.isArray(value)) value = [value];
        if (!Array.isArray(values)) values = [values];

        for (var i in values)
            value.pop(values[i]);

        this.$element.val(value)
                     .change();
    };

    SelectList.prototype.createListGroup = function() {
        var $select = this.$element;

        var $listGroup = $('

');

        if ($select.attr('multiple'))
            $listGroup.data('toggle', 'buttons');

        $select.find('option').each(function (i, item) {
            var $item = $(item);
            var $new = $(''
                       + $item.text() + '');
            $listGroup.append($new);
        });

        $select.change(function () {
            $listGroup.listgroup({
                unselect: '*',
                select: $select.val()
            });
        });

        $listGroup.listgroup({
            select: $select.val(),
            click: function () {
                var values = [];
                $listGroup.find('.list-group-item.active').each(function(i, item) {
                    var value = $(item).data('value');
                    values.push(value);
                });
                if (values.length == 1) values = values[0];
                $select.val(values);
            }
        });
        $select.before($listGroup);
        this.$listGroup = $listGroup;

        $select.hide();

        return $listGroup;
    };

    // LIST GROUP PLUGIN DEFINITION
    // =======================
    $.fn.listgroup = function (option) {
        return this.each(function (i, element) {
            var $element = $(element);

            var list = $element.data('listgroup');
            if (!list)
                $element.data('listgroup', (list = $element.is('select')
                    ? new SelectList(element, option)
                    : new ListGroup(element, option)));

            if (option) {

                if (option.unselect)
                    list.unselect(option.unselect);

                if (option.select)
                    list.select(option.select);
            }
        });
    };

    $(function () {
        $('.list-group').listgroup();
    });
}(jQuery);
<|endoftext|>


<commit_before>// Static file handler. Serves all of the files from `public/root` directory
// under the main application root path.

'use strict';

const path        = require('path');
const send        = require('send');
const stream      = require('stream');

module.exports = function (N) {
  let root = path.join(__dirname, '../../../../static');

  N.validate('server_bin:rco-nodeca.static', {
    // DON'T validate unknown params - those can exists,
    // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/
    additionalProperties: true,
    properties: {
      path: {
        type: 'string',
        required: true
      }
    }
  });

  N.wire.on('server_bin:rco-nodeca.static', async function static_file_send(env) {
    let req = env.origin.req,
        res = env.origin.res;

    if (req.method !== 'GET' && req.method !== 'HEAD') throw N.io.BAD_REQUEST;

    await new Promise((resolve, reject) => {
      let ss = send(req, env.params.path, { root, index: false, maxAge: '7d' });

      // Errors with status are not fatal,
      // rethrow those up as code, not as Error
      ss.on('error', err => reject(err.status || err));

      stream.finished(res, () => {
        if (res.statusCode) env.status = res.statusCode;
        resolve();
      });

      ss.pipe(res);
    });
  });
};
<commit_msg>.pipe() => pipeline()<commit_after>// Static file handler. Serves all of the files from `public/root` directory
// under the main application root path.

'use strict';

const path         = require('path');
const send         = require('send');
const { pipeline } = require('stream/promises');

module.exports = function (N) {
  let root = path.join(__dirname, '../../../../static');

  N.validate('server_bin:rco-nodeca.static', {
    // DON'T validate unknown params - those can exists,
    // if someone requests '/myfile.txt?xxxx' instead of '/myfile.txt/
    additionalProperties: true,
    properties: {
      path: {
        type: 'string',
        required: true
      }
    }
  });

  N.wire.on('server_bin:rco-nodeca.static', async function static_file_send(env) {
    let req = env.origin.req,
        res = env.origin.res;

    if (req.method !== 'GET' && req.method !== 'HEAD') throw N.io.BAD_REQUEST;

    try {
      const ss = send(req, env.params.path, { root, index: false, maxAge: '7d' });

      await pipeline(ss, res);
      if (res.statusCode) env.status = res.statusCode;

    } catch (err) {
      // Errors with status are not fatal,
      // rethrow those up as code, not as Error
      throw err.status || err;
    }
  });
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import SearchHeader from '../components/SearchHeader'
import * as LanguageActions from '../actions/LanguageActions'
import * as LibraryActions from '../actions/LibraryActions'
import * as MobileNavigationActions from '../actions/MobileNavigationActions'
import * as WindowActions from '../actions/WindowActions'
import * as SearchActions from '../actions/SearchActions'

import * as LoginActions from '../actions/LoginActions'
import ModalRoot from './ModalRoot'
import Footer from '../components/Footer'
import * as RegistrationActions from '../actions/RegistrationActions'

class App extends React.Component {
  constructor (props) {
    super(props)
    this.handleResizeWindowWidth = this.handleResizeWindowWidth.bind(this)
  }

  componentWillMount () {
    this.props.loginActions.updateLoginStatus()
    this.props.languageActions.loadLanguage()
    this.props.libraryActions.fetchLibraries()
    this.props.windowActions.resizeWindowWidth(window.innerWidth)
    window.addEventListener('resize', this.handleResizeWindowWidth)
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleResizeWindowWidth)
  }

  handleResizeWindowWidth (event) {
    this.props.windowActions.resizeWindowWidth(event.target.innerWidth)
  }

  render () {
    console.log(this.props)
    return (

        <ModalRoot />
        <SearchHeader path={this.props.location.pathname}
                      locationQuery={this.props.location.query}
                      dispatch={this.props.dispatch}
                      locale={this.props.locale}
                      isLoggedIn={this.props.isLoggedIn}
                      logout={this.props.loginActions.logout}
                      showLoginDialog={this.props.loginActions.showLoginDialog}
                      requireLoginBeforeAction={this.props.loginActions.requireLoginBeforeAction}
                      startRegistration={this.props.registrationActions.startRegistration}
                      showMobileNavigation={this.props.showMobileNavigation}
                      mobileNavigationActions={this.props.mobileNavigationActions}
                      borrowerName={this.props.borrowerName}
                      searchActions={this.props.searchActions}
                      isSearching={this.props.isSearching}
        />
        {this.props.children}

    )
  }
}

App.propTypes = {
  dispatch: PropTypes.func.isRequired,
  routing: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  children: PropTypes.node.isRequired,
  languageActions: PropTypes.object.isRequired,
  libraryActions: PropTypes.object.isRequired,
  loginActions: PropTypes.object.isRequired,
  locale: PropTypes.string.isRequired,
  isLoggedIn: PropTypes.bool.isRequired,
  registrationActions: PropTypes.object.isRequired,
  mobileNavigationActions: PropTypes.object.isRequired,
  showMobileNavigation: PropTypes.bool.isRequired,
  windowActions: PropTypes.object.isRequired,
  borrowerName: PropTypes.string,
  searchActions: PropTypes.object.isRequired,
  isSearching: PropTypes.bool.isRequired
}

function mapStateToProps (state) {
  return {
    routing: state.routing,
    locale: state.application.locale,
    isLoggedIn: state.application.isLoggedIn,
    showMobileNavigation: state.mobileNavigation.visible,
    borrowerName: state.profile.borrowerName,
    isSearching: state.search.isSearching
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch: dispatch,
    languageActions: bindActionCreators(LanguageActions, dispatch),
    loginActions: bindActionCreators(LoginActions, dispatch),
    libraryActions: bindActionCreators(LibraryActions, dispatch),
    registrationActions: bindActionCreators(RegistrationActions, dispatch),
    mobileNavigationActions: bindActionCreators(MobileNavigationActions, dispatch),
    windowActions: bindActionCreators(WindowActions, dispatch),
    searchActions: bindActionCreators(SearchActions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App)
<commit_msg>patron-client: remove console.log<commit_after>import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import SearchHeader from '../components/SearchHeader'
import * as LanguageActions from '../actions/LanguageActions'
import * as LibraryActions from '../actions/LibraryActions'
import * as MobileNavigationActions from '../actions/MobileNavigationActions'
import * as WindowActions from '../actions/WindowActions'
import * as SearchActions from '../actions/SearchActions'

import * as LoginActions from '../actions/LoginActions'
import ModalRoot from './ModalRoot'
import Footer from '../components/Footer'
import * as RegistrationActions from '../actions/RegistrationActions'

class App extends React.Component {
  constructor (props) {
    super(props)
    this.handleResizeWindowWidth = this.handleResizeWindowWidth.bind(this)
  }

  componentWillMount () {
    this.props.loginActions.updateLoginStatus()
    this.props.languageActions.loadLanguage()
    this.props.libraryActions.fetchLibraries()
    this.props.windowActions.resizeWindowWidth(window.innerWidth)
    window.addEventListener('resize', this.handleResizeWindowWidth)
  }

  componentWillUnmount () {
    window.removeEventListener('resize', this.handleResizeWindowWidth)
  }

  handleResizeWindowWidth (event) {
    this.props.windowActions.resizeWindowWidth(event.target.innerWidth)
  }

  render () {
    return (

        <ModalRoot />
        <SearchHeader path={this.props.location.pathname}
                      locationQuery={this.props.location.query}
                      dispatch={this.props.dispatch}
                      locale={this.props.locale}
                      isLoggedIn={this.props.isLoggedIn}
                      logout={this.props.loginActions.logout}
                      showLoginDialog={this.props.loginActions.showLoginDialog}
                      requireLoginBeforeAction={this.props.loginActions.requireLoginBeforeAction}
                      startRegistration={this.props.registrationActions.startRegistration}
                      showMobileNavigation={this.props.showMobileNavigation}
                      mobileNavigationActions={this.props.mobileNavigationActions}
                      borrowerName={this.props.borrowerName}
                      searchActions={this.props.searchActions}
                      isSearching={this.props.isSearching}
        />
        {this.props.children}

    )
  }
}

App.propTypes = {
  dispatch: PropTypes.func.isRequired,
  routing: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  children: PropTypes.node.isRequired,
  languageActions: PropTypes.object.isRequired,
  libraryActions: PropTypes.object.isRequired,
  loginActions: PropTypes.object.isRequired,
  locale: PropTypes.string.isRequired,
  isLoggedIn: PropTypes.bool.isRequired,
  registrationActions: PropTypes.object.isRequired,
  mobileNavigationActions: PropTypes.object.isRequired,
  showMobileNavigation: PropTypes.bool.isRequired,
  windowActions: PropTypes.object.isRequired,
  borrowerName: PropTypes.string,
  searchActions: PropTypes.object.isRequired,
  isSearching: PropTypes.bool.isRequired
}

function mapStateToProps (state) {
  return {
    routing: state.routing,
    locale: state.application.locale,
    isLoggedIn: state.application.isLoggedIn,
    showMobileNavigation: state.mobileNavigation.visible,
    borrowerName: state.profile.borrowerName,
    isSearching: state.search.isSearching
  }
}

function mapDispatchToProps (dispatch) {
  return {
    dispatch: dispatch,
    languageActions: bindActionCreators(LanguageActions, dispatch),
    loginActions: bindActionCreators(LoginActions, dispatch),
    libraryActions: bindActionCreators(LibraryActions, dispatch),
    registrationActions: bindActionCreators(RegistrationActions, dispatch),
    mobileNavigationActions: bindActionCreators(MobileNavigationActions, dispatch),
    windowActions: bindActionCreators(WindowActions, dispatch),
    searchActions: bindActionCreators(SearchActions, dispatch)
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App)
<|endoftext|>


<commit_before>export default notGTEmail => {
  return !notGTEmail.trim().endsWith('gatech.edu');
};<commit_msg>convert test string to lowercase before comparing<commit_after>export default notGTEmail => {
  return !notGTEmail.trim().toLowerCase().endsWith('gatech.edu');
};<|endoftext|>


<commit_before>var express = require('express');
var bodyParser = require('body-parser');
var routes = require('./../app/routes/users.route');

module.exports = (function() {
  'use strict';
  var app = express();
  var router = express.Router();
  app
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .use('/api/v1', router);

  routes(router);

  return app;
})();<commit_msg>require cors and restrict cors access to only the gateway<commit_after>var express = require('express');
var bodyParser = require('body-parser');
var routes = require('./../app/routes/users.route');
var cors = require('cors');
var corsConfig = {
  origin: 'http://user-subs.herokuapp.com'
};

module.exports = (function() {
  'use strict';
  var app = express();
  var router = express.Router();
  app
    .use(bodyParser.json())
    .use(bodyParser.urlencoded({extended: true}))
    .use(cors(corsConfig))
    .use('/api/v1', router);

  routes(router);

  return app;
})();<|endoftext|>


<commit_before>const deepmerge = require('deepmerge')

const webpackConfig = require('./webpack.config.development')
const specsGlob = 'src/app/**/*.specs.js'

// clear plugins
webpackConfig.plugins = []

// to debug open http://127.0.0.1:9876/debug.html and check console
module.exports = config => config.set({
    // specsGlob relative to this path
    basePath: '../',

    // run browserless
    browsers: ['PhantomJS'],

    // use the mocha test framework
    frameworks: ['mocha'],

    // report results in this format
    reporters: ['mocha'],

    // load spec files
    files: [
        specsGlob,
    ],

    // preprocess with webpack
    preprocessors: {
        [specsGlob]: ['webpack'],
    },

    // silence bundling output
    webpackMiddleware: {
        noInfo: true,
        quiet: true,
    },

    // use this webpack configuration
    webpack: deepmerge(webpackConfig, {
        module: {
            // some libraries don't like being run through babel.
            noParse: [
                /node_modules(\\|\/)acorn/,
            ],

            loaders: [
                {
                    query: {
                        plugins: [
                            // needed for power-assert
                            // (ref:https://github.com/power-assert-js/babel-plugin-espower)
                            'babel-plugin-espower',
                        ],
                    },
                },
                {
                    // needed for power-assert
                    test: /\.json$/,
                    loader: 'json',
                },
            ],
        },
    }),
})

<commit_msg>the quiet flag was also silencing any eslint errors, so silence everything else but errors<commit_after>const deepmerge = require('deepmerge')

const webpackConfig = require('./webpack.config.development')
const specsGlob = 'src/app/**/*.specs.js'

// clear plugins
webpackConfig.plugins = []

// to debug open http://127.0.0.1:9876/debug.html and check console
module.exports = config => config.set({
    // specsGlob relative to this path
    basePath: '../',

    // run browserless
    browsers: ['PhantomJS'],

    // use the mocha test framework
    frameworks: ['mocha'],

    // report results in this format
    reporters: ['mocha'],

    // load spec files
    files: [
        specsGlob,
    ],

    // preprocess with webpack
    preprocessors: {
        [specsGlob]: ['webpack'],
    },

    // silence bundling output except exceptions
    // ie. from eslint
    webpackMiddleware: {
        noInfo: true,
        stats: {
            errors: true,
            errorDetails: true,
            colors: true,
            hash: false,
            version: false,
            timings: false,
            assets: false,
            chunks: false,
            modules: false,
            reasons: false,
            source: false,
            warnings: false,
        },
    },

    // use this webpack configuration
    webpack: deepmerge(webpackConfig, {
        module: {
            // some libraries don't like being run through babel.
            noParse: [
                /node_modules(\\|\/)acorn/,
            ],

            loaders: [
                {
                    query: {
                        plugins: [
                            // needed for power-assert
                            // (ref:https://github.com/power-assert-js/babel-plugin-espower)
                            'babel-plugin-espower',
                        ],
                    },
                },
                {
                    // needed for power-assert
                    test: /\.json$/,
                    loader: 'json',
                },
            ],
        },
    }),
})

<|endoftext|>