<commit_before>/*
 * Cookie Calculator / units.js
 * copyright (c) 2016 Susisu
 */

"use strict";

function endModule() {
    module.exports = Object.freeze({
        Dimension,
        Quantity,
        Unit,
        Synonym,
        Prefactored,
        UnitMul,
        UnitDiv,
        Prefix,
        Prefixed,
        autoPrefix,
        SIPrefix,
        ONE,
        SIUnit
    });
}

/*
    A dimension of a quantity is described as an object with symbol keys.
    example:
        {
            [Dimension.MASS]  : 1,
            [Dimension.LENGTH]: 1,
            [Dimension.TIME]  : -2
        }
*/
const Dimension = Object.freeze({
    AMOUNT     : Symbol("amount"),
    MASS       : Symbol("mass"),
    LENGTH     : Symbol("length"),
    TIME       : Symbol("time"),
    TEMPERATURE: Symbol("temperature"),
    CURRENT    : Symbol("current"),
    LUMINOUS   : Symbol("luminous"),

    toString: (dim) => {
        let basis = Object.getOwnPropertySymbols(dim);
        let str   = "";
        for (let b of DIMENSION_ORDER) {
            if (dim[b] !== undefined && dim[b] !== 0) {
                str += DIMENSION_SYMBOL[b] + dim[b].toString();
            }
        }
        return str;
    },

    equal: (dimA, dimB) => {
        let basisA = Object.getOwnPropertySymbols(dimA),
            basisB = Object.getOwnPropertySymbols(dimB);
        for (let b of basisA) {
            if (dimA[b] === 0) {
                if (dimB[b] !== 0 && dimB[b] !== undefined){
                    return false;
                }
            }
            else if (dimA[b] !== dimB[b]) {
                return false;
            }
        }
        for (let b of basisB) {
            if (dimB[b] === 0) {
                if (dimA[b] !== 0 && dimA[b] !== undefined){
                    return false;
                }
            }
            else if (dimB[b] !== dimA[b]) {
                return false;
            }
        }
        return true;
    },

    mul: (dimA, dimB) => {
        let basisA = Object.getOwnPropertySymbols(dimA),
            basisB = Object.getOwnPropertySymbols(dimB);
        let newDim = {};
        for (let b of basisA) {
            newDim[b] = dimA[b];
        }
        for (let b of basisB) {
            if (newDim[b] === undefined) {
                newDim[b] = dimB[b];
            }
            else {
                newDim[b] += dimB[b];
                if (newDim[b] === 0) {
                    delete newDim[b];
                }
            }
        }
        return newDim;
    },

    div: (dimA, dimB) => {
        let basisA = Object.getOwnPropertySymbols(dimA),
            basisB = Object.getOwnPropertySymbols(dimB);
        let newDim = {};
        for (let b of basisA) {
            newDim[b] = dimA[b];
        }
        for (let b of basisB) {
            if (newDim[b] === undefined) {
                newDim[b] = -dimB[b];
            }
            else {
                newDim[b] -= dimB[b];
                if (newDim[b] === 0) {
                    delete newDim[b];
                }
            }
        }
        return newDim;
    }
});

const DIMENSION_SYMBOL = Object.freeze({
    [Dimension.AMOUNT]     : "N",
    [Dimension.MASS]       : "M",
    [Dimension.LENGTH]     : "L",
    [Dimension.TIME]       : "T",
    [Dimension.TEMPERATURE]: "Θ",
    [Dimension.CURRENT]    : "I",
    [Dimension.LUMINOUS]   : "J"
});

const DIMENSION_ORDER = [
    Dimension.MASS,
    Dimension.LENGTH,
    Dimension.CURRENT,
    Dimension.LUMINOUS,
    Dimension.AMOUNT,
    Dimension.TEMPERATURE,
    Dimension.TIME
];

class Quantity {
    constructor(value, dimension) {
        this.value      = value;
        this.dimension  = dimension;
    }

    static add(x, y) {
        if (!Dimension.equal(x.dimension, y.dimension)) {
            throw new Error("dimension mismatch");
        }
        return new Quantity(x.value + y.value, x.dimension);
    }

    static sub(x, y) {
        if (!Dimension.equal(x.dimension, y.dimension)) {
            throw new Error("dimension mismatch");
        }
        return new Quantity(x.value - y.value, x.dimension);
    }

    static mul(x, y) {
        return new Quantity(x.value * y.value, Dimension.mul(x.dimension, y.dimension));
    }

    static div(x, y) {
        return new Quantity(x.value / y.value, Dimension.div(x.dimension, y.dimension));
    }

    add(x) {
        return Quantity.add(this, x);
    }

    sub(x) {
        return Quantity.sub(this, x);
    }

    mul(x) {
        return Quantity.mul(this, x);
    }

    div(x) {
        return Quantity.div(this, x);
    }

    in(unit) {
        if (!Dimension.equal(this.dimension, unit.dimension)) {
            throw new Error("dimension mismatch");
        }
        return this.value / unit.factor;
    }

    toStringIn(unit) {
        if (!Dimension.equal(this.dimension, unit.dimension)) {
            throw new Error("dimension mismatch");
        }
        return this.in(unit).toString() + " " + unit.symbol;
    }

    toStringInAutoPrefixed(unit) {
        if (!Dimension.equal(this.dimension, unit.dimension)) {
            throw new Error("dimension mismatch");
        }
        let prefixedUnit = autoPrefix(this, unit);
        return this.in(prefixedUnit).toString() + " " + prefixedUnit.symbol;
    }
}

class Unit {
    constructor(dimension, name, symbol, factor) {
        this.dimension = dimension;
        this.name      = name;
        this.symbol    = symbol;
        this.factor    = factor;
    }

    toString() {
        return this.name;
    }

    value(value) {
        return new Quantity(value * this.factor, this.dimension);
    }

    addPrefix(prefix) {
        return new Prefixed(prefix, this);
    }

    scale(factor) {
        return new Prefactored(factor, this);
    }

    mul(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(unit.prefactor, new UnitMul(this, unit.unit));
        }
        else {
            return new UnitMul(this, unit);
        }
    }

    div(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(1.0 / unit.prefactor, new UnitDiv(this, unit.unit));
        }
        else {
            return new UnitDiv(this, unit);
        }
    }
}

class One extends Unit {
    constructor() {
        super({}, "1", "", 1.0);
    }

    mul(unit) {
        return unit;
    }

    div(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(1.0 / unit.prefactor, new UnitDiv(this, unit.unit));
        }
        else {
            return new UnitDiv(this, unit);
        }
    }
}

class Synonym extends Unit {
    constructor(name, symbol, unit) {
        super(unit.dimension, name, symbol, unit.factor);
        this.unit = unit;
    }
}

class Prefactored extends Unit {
    constructor(prefactor, unit) {
        super(
            unit.dimension,
            prefactor.toString() + unit.name,
            prefactor.toString() + unit.symbol,
            prefactor * unit.factor
        );
        this.prefactor = prefactor;
        this.unit      = unit;
    }

    addPrefix(prefix) {
        return new Prefactored(this.prefactor, this.unit.addPrefix(prefix));
    }

    scale(factor) {
        return new Prefactored(factor * this.prefactor, this.unit);
    }

    mul(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(this.prefactor * unit.prefactor, new UnitMul(this.unit, unit.unit));
        }
        else {
            return new Prefactored(this.prefactor, UnitMul(this.unit, unit));
        }
    }

    div(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(this.prefactor / unit.prefactor, new UnitDiv(this.unit, unit.unit));
        }
        else {
            return new Prefactored(this.prefactor, UnitDiv(this.unit, unit));
        }
    }
}

class UnitMul extends Unit {
    constructor(unitA, unitB) {
        super(
            Dimension.mul(unitA.dimension, unitB.dimension),
            (unitA instanceof UnitDiv ? "(" + unitA.name + ")" : unitA.name) + " " + unitB.name,
            (unitA instanceof UnitDiv ? "(" + unitA.symbol + ")" : unitA.symbol) + "." + unitB.symbol,
            unitA.factor * unitB.factor
        );
        this.unitA = unitA;
        this.unitB = unitB;
    }

    addPrefix(prefix) {
        return new UnitMul(this.unitA.addPrefix(prefix), this.unitB);
    }
}

class UnitDiv extends Unit {
    constructor(unitA, unitB) {
        super(
            Dimension.div(unitA.dimension, unitB.dimension),
            unitA.name + " per " + unitB.name,
            unitA.symbol + "/" + unitB.symbol,
            unitA.factor / unitB.factor
        );
        this.unitA = unitA;
        this.unitB = unitB;
    }

    addPrefix(prefix) {
        return new UnitDiv(this.unitA.addPrefix(prefix), this.unitB);
    }
}

class Prefix {
    constructor(name, symbol, factor) {
        this.name   = name;
        this.symbol = symbol;
        this.factor = factor;
    }

    add(unit) {
        return unit.addPrefix(this);
    }
}

class Prefixed extends Unit {
    constructor(prefix, unit) {
        super(
            unit.dimension,
            prefix.name + unit.name,
            prefix.symbol + unit.symbol,
            prefix.factor * unit.factor
        );
        this.prefix = prefix;
        this.unit   = unit;
    }

    addPrefix(prefix) {
        let factor = prefix.factor * this.prefix.factor;
        let appPrefix = AUTO_PREFIX_LIST.find(prefix => prefix.factor <= factor);
        if (appPrefix === undefined) {
            appPrefix = AUTO_PREFIX_LIST[AUTO_PREFIX_LIST.length - 1];
        }
        if (appPrefix.name === "") {
            return this.unit;
        }
        return new Prefixed(appPrefix, this.unit);
    }
}

function autoPrefix(quantity, unit) {
    let value = quantity.in(unit);
    if (value === 0.0) {
        return unit;
    }
    let prefix = AUTO_PREFIX_LIST.find(prefix => prefix.factor <= value);
    if (prefix === undefined) {
        prefix = AUTO_PREFIX_LIST[AUTO_PREFIX_LIST.length - 1];
    }
    if (prefix.name === "") {
        return unit;
    }
    return unit.addPrefix(prefix);
}

const SIPrefix = Object.freeze({
    YOTTA: new Prefix("yotta",  "Y", 1e+24),
    ZETTA: new Prefix("zetta",  "Z", 1e+21),
    EXA  : new Prefix(  "exa",  "E", 1e+18),
    PETA : new Prefix( "peta",  "P", 1e+15),
    TERA : new Prefix( "tera",  "T", 1e+12),
    GIGA : new Prefix( "giga",  "G", 1e+9),
    MEGA : new Prefix( "mega",  "M", 1e+6),
    KILO : new Prefix( "kilo",  "k", 1e+3),
    HECTO: new Prefix("hecto",  "h", 1e+2),
    DECA : new Prefix( "deca", "da", 1e+1),
    DECI : new Prefix( "deci",  "d", 1e-1),
    CENTI: new Prefix("centi",  "c", 1e-2),
    MILLI: new Prefix("milli",  "m", 1e-3),
    MICRO: new Prefix("micro",  "μ", 1e-6),
    NANO : new Prefix( "nano",  "n", 1e-9),
    PICO : new Prefix( "pico",  "p", 1e-12),
    FEMTO: new Prefix("femto",  "f", 1e-15),
    ATTO : new Prefix( "atto",  "a", 1e-18),
    ZEPTO: new Prefix("zepto",  "z", 1e-21),
    YOCTO: new Prefix("yocto",  "y", 1e-24)
});

const AUTO_PREFIX_LIST = [
    SIPrefix.YOTTA,
    SIPrefix.ZETTA,
    SIPrefix.EXA,
    SIPrefix.PETA,
    SIPrefix.TERA,
    SIPrefix.GIGA,
    SIPrefix.MEGA,
    SIPrefix.KILO,
    new Prefix("", "", 1e+0),   // dummy
    SIPrefix.MILLI,
    SIPrefix.MICRO,
    SIPrefix.NANO,
    SIPrefix.PICO,
    SIPrefix.FEMTO,
    SIPrefix.ATTO,
    SIPrefix.ZEPTO,
    SIPrefix.YOCTO
];

const ONE = new One();

const SIUnit = {
    MOLE   : new Unit({ [Dimension.AMOUNT]     : 1 },    "mole", "mol", 1.0),
    GRAM   : new Unit({ [Dimension.MASS]       : 1 },    "gram",   "g", 1e-3),
    METER  : new Unit({ [Dimension.LENGTH]     : 1 },   "meter",   "m", 1.0),
    SECOND : new Unit({ [Dimension.TIME]       : 1 },  "second", "sec", 1.0),
    KELVIN : new Unit({ [Dimension.TEMPERATURE]: 1 },  "kelvin",   "K", 1.0),
    AMPERE : new Unit({ [Dimension.CURRENT]    : 1 },  "ampere",   "A", 1.0),
    CANDELA: new Unit({ [Dimension.LUMINOUS]   : 1 }, "candela",  "cd", 1.0)
};
SIUnit.KILOGRAM = SIPrefix.KILO.add(SIUnit.GRAM);
SIUnit.NEWTON   = new Synonym("newton", "N",
        SIUnit.KILOGRAM.mul(SIUnit.METER).div(SIUnit.SECOND).div(SIUnit.SECOND)
);
Object.freeze(SIUnit);

endModule();
<commit_msg>Change second symbol<commit_after>/*
 * Cookie Calculator / units.js
 * copyright (c) 2016 Susisu
 */

"use strict";

function endModule() {
    module.exports = Object.freeze({
        Dimension,
        Quantity,
        Unit,
        Synonym,
        Prefactored,
        UnitMul,
        UnitDiv,
        Prefix,
        Prefixed,
        autoPrefix,
        SIPrefix,
        ONE,
        SIUnit
    });
}

/*
    A dimension of a quantity is described as an object with symbol keys.
    example:
        {
            [Dimension.MASS]  : 1,
            [Dimension.LENGTH]: 1,
            [Dimension.TIME]  : -2
        }
*/
const Dimension = Object.freeze({
    AMOUNT     : Symbol("amount"),
    MASS       : Symbol("mass"),
    LENGTH     : Symbol("length"),
    TIME       : Symbol("time"),
    TEMPERATURE: Symbol("temperature"),
    CURRENT    : Symbol("current"),
    LUMINOUS   : Symbol("luminous"),

    toString: (dim) => {
        let basis = Object.getOwnPropertySymbols(dim);
        let str   = "";
        for (let b of DIMENSION_ORDER) {
            if (dim[b] !== undefined && dim[b] !== 0) {
                str += DIMENSION_SYMBOL[b] + dim[b].toString();
            }
        }
        return str;
    },

    equal: (dimA, dimB) => {
        let basisA = Object.getOwnPropertySymbols(dimA),
            basisB = Object.getOwnPropertySymbols(dimB);
        for (let b of basisA) {
            if (dimA[b] === 0) {
                if (dimB[b] !== 0 && dimB[b] !== undefined){
                    return false;
                }
            }
            else if (dimA[b] !== dimB[b]) {
                return false;
            }
        }
        for (let b of basisB) {
            if (dimB[b] === 0) {
                if (dimA[b] !== 0 && dimA[b] !== undefined){
                    return false;
                }
            }
            else if (dimB[b] !== dimA[b]) {
                return false;
            }
        }
        return true;
    },

    mul: (dimA, dimB) => {
        let basisA = Object.getOwnPropertySymbols(dimA),
            basisB = Object.getOwnPropertySymbols(dimB);
        let newDim = {};
        for (let b of basisA) {
            newDim[b] = dimA[b];
        }
        for (let b of basisB) {
            if (newDim[b] === undefined) {
                newDim[b] = dimB[b];
            }
            else {
                newDim[b] += dimB[b];
                if (newDim[b] === 0) {
                    delete newDim[b];
                }
            }
        }
        return newDim;
    },

    div: (dimA, dimB) => {
        let basisA = Object.getOwnPropertySymbols(dimA),
            basisB = Object.getOwnPropertySymbols(dimB);
        let newDim = {};
        for (let b of basisA) {
            newDim[b] = dimA[b];
        }
        for (let b of basisB) {
            if (newDim[b] === undefined) {
                newDim[b] = -dimB[b];
            }
            else {
                newDim[b] -= dimB[b];
                if (newDim[b] === 0) {
                    delete newDim[b];
                }
            }
        }
        return newDim;
    }
});

const DIMENSION_SYMBOL = Object.freeze({
    [Dimension.AMOUNT]     : "N",
    [Dimension.MASS]       : "M",
    [Dimension.LENGTH]     : "L",
    [Dimension.TIME]       : "T",
    [Dimension.TEMPERATURE]: "Θ",
    [Dimension.CURRENT]    : "I",
    [Dimension.LUMINOUS]   : "J"
});

const DIMENSION_ORDER = [
    Dimension.MASS,
    Dimension.LENGTH,
    Dimension.CURRENT,
    Dimension.LUMINOUS,
    Dimension.AMOUNT,
    Dimension.TEMPERATURE,
    Dimension.TIME
];

class Quantity {
    constructor(value, dimension) {
        this.value      = value;
        this.dimension  = dimension;
    }

    static add(x, y) {
        if (!Dimension.equal(x.dimension, y.dimension)) {
            throw new Error("dimension mismatch");
        }
        return new Quantity(x.value + y.value, x.dimension);
    }

    static sub(x, y) {
        if (!Dimension.equal(x.dimension, y.dimension)) {
            throw new Error("dimension mismatch");
        }
        return new Quantity(x.value - y.value, x.dimension);
    }

    static mul(x, y) {
        return new Quantity(x.value * y.value, Dimension.mul(x.dimension, y.dimension));
    }

    static div(x, y) {
        return new Quantity(x.value / y.value, Dimension.div(x.dimension, y.dimension));
    }

    add(x) {
        return Quantity.add(this, x);
    }

    sub(x) {
        return Quantity.sub(this, x);
    }

    mul(x) {
        return Quantity.mul(this, x);
    }

    div(x) {
        return Quantity.div(this, x);
    }

    in(unit) {
        if (!Dimension.equal(this.dimension, unit.dimension)) {
            throw new Error("dimension mismatch");
        }
        return this.value / unit.factor;
    }

    toStringIn(unit) {
        if (!Dimension.equal(this.dimension, unit.dimension)) {
            throw new Error("dimension mismatch");
        }
        return this.in(unit).toString() + " " + unit.symbol;
    }

    toStringInAutoPrefixed(unit) {
        if (!Dimension.equal(this.dimension, unit.dimension)) {
            throw new Error("dimension mismatch");
        }
        let prefixedUnit = autoPrefix(this, unit);
        return this.in(prefixedUnit).toString() + " " + prefixedUnit.symbol;
    }
}

class Unit {
    constructor(dimension, name, symbol, factor) {
        this.dimension = dimension;
        this.name      = name;
        this.symbol    = symbol;
        this.factor    = factor;
    }

    toString() {
        return this.name;
    }

    value(value) {
        return new Quantity(value * this.factor, this.dimension);
    }

    addPrefix(prefix) {
        return new Prefixed(prefix, this);
    }

    scale(factor) {
        return new Prefactored(factor, this);
    }

    mul(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(unit.prefactor, new UnitMul(this, unit.unit));
        }
        else {
            return new UnitMul(this, unit);
        }
    }

    div(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(1.0 / unit.prefactor, new UnitDiv(this, unit.unit));
        }
        else {
            return new UnitDiv(this, unit);
        }
    }
}

class One extends Unit {
    constructor() {
        super({}, "1", "", 1.0);
    }

    mul(unit) {
        return unit;
    }

    div(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(1.0 / unit.prefactor, new UnitDiv(this, unit.unit));
        }
        else {
            return new UnitDiv(this, unit);
        }
    }
}

class Synonym extends Unit {
    constructor(name, symbol, unit) {
        super(unit.dimension, name, symbol, unit.factor);
        this.unit = unit;
    }
}

class Prefactored extends Unit {
    constructor(prefactor, unit) {
        super(
            unit.dimension,
            prefactor.toString() + unit.name,
            prefactor.toString() + unit.symbol,
            prefactor * unit.factor
        );
        this.prefactor = prefactor;
        this.unit      = unit;
    }

    addPrefix(prefix) {
        return new Prefactored(this.prefactor, this.unit.addPrefix(prefix));
    }

    scale(factor) {
        return new Prefactored(factor * this.prefactor, this.unit);
    }

    mul(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(this.prefactor * unit.prefactor, new UnitMul(this.unit, unit.unit));
        }
        else {
            return new Prefactored(this.prefactor, UnitMul(this.unit, unit));
        }
    }

    div(unit) {
        if (unit instanceof One) {
            return this;
        }
        else if (unit instanceof Prefactored) {
            return new Prefactored(this.prefactor / unit.prefactor, new UnitDiv(this.unit, unit.unit));
        }
        else {
            return new Prefactored(this.prefactor, UnitDiv(this.unit, unit));
        }
    }
}

class UnitMul extends Unit {
    constructor(unitA, unitB) {
        super(
            Dimension.mul(unitA.dimension, unitB.dimension),
            (unitA instanceof UnitDiv ? "(" + unitA.name + ")" : unitA.name) + " " + unitB.name,
            (unitA instanceof UnitDiv ? "(" + unitA.symbol + ")" : unitA.symbol) + "." + unitB.symbol,
            unitA.factor * unitB.factor
        );
        this.unitA = unitA;
        this.unitB = unitB;
    }

    addPrefix(prefix) {
        return new UnitMul(this.unitA.addPrefix(prefix), this.unitB);
    }
}

class UnitDiv extends Unit {
    constructor(unitA, unitB) {
        super(
            Dimension.div(unitA.dimension, unitB.dimension),
            unitA.name + " per " + unitB.name,
            unitA.symbol + "/" + unitB.symbol,
            unitA.factor / unitB.factor
        );
        this.unitA = unitA;
        this.unitB = unitB;
    }

    addPrefix(prefix) {
        return new UnitDiv(this.unitA.addPrefix(prefix), this.unitB);
    }
}

class Prefix {
    constructor(name, symbol, factor) {
        this.name   = name;
        this.symbol = symbol;
        this.factor = factor;
    }

    add(unit) {
        return unit.addPrefix(this);
    }
}

class Prefixed extends Unit {
    constructor(prefix, unit) {
        super(
            unit.dimension,
            prefix.name + unit.name,
            prefix.symbol + unit.symbol,
            prefix.factor * unit.factor
        );
        this.prefix = prefix;
        this.unit   = unit;
    }

    addPrefix(prefix) {
        let factor = prefix.factor * this.prefix.factor;
        let appPrefix = AUTO_PREFIX_LIST.find(prefix => prefix.factor <= factor);
        if (appPrefix === undefined) {
            appPrefix = AUTO_PREFIX_LIST[AUTO_PREFIX_LIST.length - 1];
        }
        if (appPrefix.name === "") {
            return this.unit;
        }
        return new Prefixed(appPrefix, this.unit);
    }
}

function autoPrefix(quantity, unit) {
    let value = quantity.in(unit);
    if (value === 0.0) {
        return unit;
    }
    let prefix = AUTO_PREFIX_LIST.find(prefix => prefix.factor <= value);
    if (prefix === undefined) {
        prefix = AUTO_PREFIX_LIST[AUTO_PREFIX_LIST.length - 1];
    }
    if (prefix.name === "") {
        return unit;
    }
    return unit.addPrefix(prefix);
}

const SIPrefix = Object.freeze({
    YOTTA: new Prefix("yotta",  "Y", 1e+24),
    ZETTA: new Prefix("zetta",  "Z", 1e+21),
    EXA  : new Prefix(  "exa",  "E", 1e+18),
    PETA : new Prefix( "peta",  "P", 1e+15),
    TERA : new Prefix( "tera",  "T", 1e+12),
    GIGA : new Prefix( "giga",  "G", 1e+9),
    MEGA : new Prefix( "mega",  "M", 1e+6),
    KILO : new Prefix( "kilo",  "k", 1e+3),
    HECTO: new Prefix("hecto",  "h", 1e+2),
    DECA : new Prefix( "deca", "da", 1e+1),
    DECI : new Prefix( "deci",  "d", 1e-1),
    CENTI: new Prefix("centi",  "c", 1e-2),
    MILLI: new Prefix("milli",  "m", 1e-3),
    MICRO: new Prefix("micro",  "μ", 1e-6),
    NANO : new Prefix( "nano",  "n", 1e-9),
    PICO : new Prefix( "pico",  "p", 1e-12),
    FEMTO: new Prefix("femto",  "f", 1e-15),
    ATTO : new Prefix( "atto",  "a", 1e-18),
    ZEPTO: new Prefix("zepto",  "z", 1e-21),
    YOCTO: new Prefix("yocto",  "y", 1e-24)
});

const AUTO_PREFIX_LIST = [
    SIPrefix.YOTTA,
    SIPrefix.ZETTA,
    SIPrefix.EXA,
    SIPrefix.PETA,
    SIPrefix.TERA,
    SIPrefix.GIGA,
    SIPrefix.MEGA,
    SIPrefix.KILO,
    new Prefix("", "", 1e+0),   // dummy
    SIPrefix.MILLI,
    SIPrefix.MICRO,
    SIPrefix.NANO,
    SIPrefix.PICO,
    SIPrefix.FEMTO,
    SIPrefix.ATTO,
    SIPrefix.ZEPTO,
    SIPrefix.YOCTO
];

const ONE = new One();

const SIUnit = {
    MOLE   : new Unit({ [Dimension.AMOUNT]     : 1 },    "mole", "mol", 1.0),
    GRAM   : new Unit({ [Dimension.MASS]       : 1 },    "gram",   "g", 1e-3),
    METER  : new Unit({ [Dimension.LENGTH]     : 1 },   "meter",   "m", 1.0),
    SECOND : new Unit({ [Dimension.TIME]       : 1 },  "second",   "s", 1.0),
    KELVIN : new Unit({ [Dimension.TEMPERATURE]: 1 },  "kelvin",   "K", 1.0),
    AMPERE : new Unit({ [Dimension.CURRENT]    : 1 },  "ampere",   "A", 1.0),
    CANDELA: new Unit({ [Dimension.LUMINOUS]   : 1 }, "candela",  "cd", 1.0)
};
SIUnit.KILOGRAM = SIPrefix.KILO.add(SIUnit.GRAM);
SIUnit.NEWTON   = new Synonym("newton", "N",
        SIUnit.KILOGRAM.mul(SIUnit.METER).div(SIUnit.SECOND).div(SIUnit.SECOND)
);
Object.freeze(SIUnit);

endModule();
<|endoftext|>


<commit_before>function run(code){
  if(typeof code !== "object")
    return code;
  var key;
  var args = [];
  if(typeof code[0] === "object"){
    key = run(code[0]);
  }else{
    key = code[0];
  }
  var temp =function(b){
              var c;
              return function(){
                if(!c)
                  c = run(code[b]);
                return c;
              };
            };
  for(var i = 1;i<code.length;i++){
    args[i-1]=temp(i);
  }
  return env[key](args);
}
var env = {};
<commit_msg>put in piece for stateful code<commit_after>function run(code){
  if(typeof code !== "object")
    return code;
  var key;
  var args = [];
  if(typeof code[0] === "object"){
    key = run(code[0]);
  }else{
    key = code[0];
  }
  var temp =function(b){
              var c;
              return function(rerun){
                if(!c || rerun)
                  c = run(code[b]);
                return c;
              };
            };
  for(var i = 1;i<code.length;i++){
    args[i-1]=temp(i);
  }
  return env[key](args);
}
var env = {};
<|endoftext|>


<commit_before>export default class DepthShader {
  static packing() {
    return `
      vec4 pack (float depth)
      {
        const vec4 bitSh = vec4(256 * 256 * 256,
          256 * 256,
          256,
          1.0);
          const vec4 bitMsk = vec4(0,
            1.0 / 256.0,
            1.0 / 256.0,
            1.0 / 256.0);
            vec4 comp = fract(depth * bitSh);
            comp -= comp.xxyz * bitMsk;
            return comp;
        }

        float unpack (vec4 colour)
        {
          const vec4 bitShifts = vec4(1.0 / (256.0 * 256.0 * 256.0),
          1.0 / (256.0 * 256.0),
          1.0 / 256.0,
          1);
          return dot(colour , bitShifts);
        }
    `;
  }

  static bumpFromDepth() {
    return `
      vec4 bumpFromDepth(sampler2D texture, vec2 uv, vec2 resolution) {
        vec2 size = vec2(.5, .0);
        vec2 offset = vec2(.5, 0.);

        float s11 = texture2D(texture, uv).r;
        float s01 = texture2D(texture, uv + -offset.xy / resolution).r;
        float s21 = texture2D(texture, uv + offset.xy / resolution).r;
        float s10 = texture2D(texture, uv - offset.yx / resolution).r;
        float s12 = texture2D(texture, uv + offset.yx / resolution).r;
        vec3 va = normalize(vec3(size.xy / resolution, s21 - s01));
        vec3 vb = normalize(vec3(size.yx / resolution, s12 - s10));
        vec4 bump = vec4(cross(va,vb), s11);
        return bump;
      }
    `;
  }

  static bumpFromPackedDepth() {
    return `
      vec4 bumpFromDepth(sampler2D texture, vec2 uv, float scale) {
        vec2 size = vec2(.002, .0) * scale;
        vec3 off = vec3(-.001, 0., .001) * scale;

        float s11 = unpack(texture2D(texture, uv));
        float s01 = unpack(texture2D(texture, uv + off.xy));
        float s21 = unpack(texture2D(texture, uv + off.zy));
        float s10 = unpack(texture2D(texture, uv + off.yx));
        float s12 = unpack(texture2D(texture, uv + off.yz));
        vec3 va = normalize(vec3(size.xy, s21 - s01));
        vec3 vb = normalize(vec3(size.yx, s12 - s10));
        vec4 bump = vec4(cross(va,vb), s11);
        return bump;
      }
    `;
  }
}
<commit_msg>clean depth shader<commit_after>const bumpFromDepth = (packed) => {
  return `
    vec4 bumpFrom${packed ? "Packed" : ""}Depth(sampler2D texture, vec2 uv, vec2 resolution) {
      vec3 size = vec3(.5, .5, 0.);
      size.xy /= resolution;

      float s11 = ${packed ? "unpack(" : ""}texture2D(texture, uv)${packed ? ")" : ".r"};
      float s01 = ${packed ? "unpack(" : ""}texture2D(texture, uv - size.xz)${packed ? ")" : ".r"};
      float s21 = ${packed ? "unpack(" : ""}texture2D(texture, uv + size.xz)${packed ? ")" : ".r"};
      float s10 = ${packed ? "unpack(" : ""}texture2D(texture, uv - size.zy)${packed ? ")" : ".r"};
      float s12 = ${packed ? "unpack(" : ""}texture2D(texture, uv + size.zy)${packed ? ")" : ".r"};
      vec3 va = normalize(vec3(size.xz, s21 - s01));
      vec3 vb = normalize(vec3(size.zy, s12 - s10));
      vec4 bump = vec4(cross(va,vb), s11);
      return bump;
    }
  `;
}

export default class DepthShader {
  static packing() {
    return `
      vec4 pack (float depth) {
        const vec4 bitSh = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);
        const vec4 bitMsk = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);
        vec4 comp = fract(depth * bitSh);
        comp -= comp.xxyz * bitMsk;
        return comp;
      }

      float unpack (vec4 packedDepth) {
        const vec4 bitShifts = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1);
        return dot(packedDepth, bitShifts);
      }
    `;
  }

  static bumpFromDepth() {
    return bumpFromDepth(false);
  }

  static bumpFromPackedDepth() {
    return bumpFromDepth(true);
  }
}
<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

//Please keep the owner names consistent with phonebook names

var OWNERS = {
  "AudioChannel": "Eric Chou", // Firefox OS
  // "BetaTriage": "?", // Firefox OS
  "Bluetooth": "Eric Chou", // Firefox OS
  "Build Config": "Dylan Oliver", // Core
  "Canvas: 2D": "Milan Sreckovic (Benoit Jacob, Jeff Muizelaar)",
  "Canvas: WebGL": "Milan Sreckovic (Benoit Jacob, Jeff Gilbert)",
  "CSS Parsing and Computation": "Jet Villegas",
  // "Emulator": "?", // Firefox OS
  // "FxA": "?", // Firefox OS
  "DOM: Apps": "Fabrice Desré",
  "DOM: Core & HTML": "Andrew Overholt (Johnny Stenback)", // DOM
  "DOM": "Andrew Overholt (2nd: Johnny Stenback)", // DOM
  "DOM: Contacts": "David Scravaglieri (Francisco Jordano)", // DOM
  "DOM: Device Interfaces": "Andrew Overholt (Johnny Stenback)", // DOM
  "DOM: Events": "Andrew Overholt (Johnny Stenback)",
  "Gaia": "David Scravaglieri (Francisco Jordano)",
  "Gaia::Bluetooth File Transfer": "Tim Guan-tin Chien (Ian Liu)",
  "Gaia::Browser": "Gregor Wagner (Ben Francis)",
  "Gaia::Build": "Tim Guan-tin Chien (Yuren Ju)",
  "Gaia::Calendar": "Dylan Oliver (Gareth Aye)",
  "Gaia::Camera": "Hema Koka (David Flanagan)",
  "Gaia::Clock": "Dylan Oliver (Marcus Cavanaugh)",
  "Gaia::Contacts": "David Scravaglieri (Francisco Jordano)",
  "Gaia::Cost Control": "David Scravaglieri (Francisco Jordano)",
  "Gaia::Dialer": "David Scravaglieri (Francisco Jordano)",
  "Gaia::E-Mail": "Dylan Oliver (Andrew Sutherland)",
  "Gaia::Everything.me": "Gregor Wagner (Michael Henretty)",
  "Gaia::First Time Experience": "Gregor Wagner (Michael Henretty)",
  "Gaia::FMRadio": "Hema Koka (David Flanagan)",
  "Gaia::Gallery": "Hema Koka (David Flanagan)",
  // "Gaia::GithubBot": "?",ven
  "Gaia::Homescreen": "Gregor Wagner (Kevin Grandon)",
  "Gaia::Keyboard": "Tim Guan-tin Chien (Rudy Lu)",
  "Gaia::Music": "Hema Koka (David Flanagan)",
  "Gaia::Notes": "Dylan Oliver",
  // "Gaia::PDF Viewer": "?",
  // "Gaia::PerformanceTest": "?",
  "Gaia::Ringtones": "Hema Koka (David Flanagan)",
  "Gaia::Search": "Gregor Wagner (Kevin Grandon)",
  "Gaia::Settings": "Tim Guan-tin Chien (Arthur Chen)",
  "Gaia::SMS": "David Scravaglieri (Francisco Jordano)",
  "Gaia::System": "Gregor Wagner (Michael Henretty)", //  Tim relies on Gregor to actively throwing bugs over.
  "Gaia::System::Browser Chrome": "Gregor Wagner (Ben Francis)",
  "Gaia::System::Input Mgmt": "Tim Guan-tin Chien (Rudy Lu)",
  "Gaia::System::Lockscreen": "Tim Guan-tin Chien (Greg Weng)",
  "Gaia::System::Window Mgmt": "Tim Guan-tin Chien (Alive Kuo)",
  // "Gaia::TestAgent": "?",
  // "Gaia::UI Tests": "?",
  "Gaia::Video": "Hema Koka (David Flanagan)",
  // "Gaia::Wallpaper": "?",
  "Gaia::Wappush": "David Scravaglieri (Francisco Jordano)",
  "General (Firefox OS)": "Lawrence Mandel (Bhavana, Preeti)",
//  "General (Core)": "Lawrence Mandel",
//  "General (Loop+)": "Lawrence Mandel",

  "GonkIntegration": "Thomas Tsai", // Firefox OS
  "General Automation": "Jonathan Griffin", // Release Engineering
  "Geolocation": "Doug Turner", // Core
  "Graphics": "Milan Sreckovic (Jeff Muizelaar, Benoit Girard)", // Core
  "Graphics: Layers": "Milan Sreckovic (Bas Schouten, Benoit Girard)", // Core
  // "Hardware": "?", // Firefox OS
  "Hardware Abstraction Layer (HAL)": "Dave Hylands", // Core
  "ImageLib": "Milan Sreckovic (Jeff Muizelaar, Seth Fowler)",
  "IPC": "Andrew Overholt (Johnny Stenback)",
  "JavaScript Engine": "Naveed Ihsanullah", // Core
  "JavaScript: GC": "Naveed Ihsanullah", // Core
  "Layout": "Jet Villegas", // Core
  "MFBT": "Naveed Ihsanullah",
  "Networking": "Jason Duell", // Core
  "NFC": "Ken Chang", // Firefox OS
  "Panning and Zooming": "Milan Sreckovic (Kartikaya Gupta, Botond Ballo)", // Core
  "Performance": "Mike Lee (Mason Chang)", // Firefox OS
  "Runtime": "Gregor Wagner (Fabrice Desré)", // Firefox OS
  // "Simulator": "?", // Firefox OS
  "RIL": "Ken Chang", // Firefox OS
  "Video/Audio": "Jet Villegas", // Core
  "Video/Audio: Recording": "CJ Ku", // Core
  "Vendcom": "Vance Chen", // Firefox OS
  "Widget: Gonk": "Mike Wu",
  "Wifi": "Ken Chang", // Firefox OS
  // "WMF": "?" // Firefox OS
};
<commit_msg>Add owners for RIL, wifi, nfc, and RTSP.<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */

//Please keep the owner names consistent with phonebook names

var OWNERS = {
  "AudioChannel": "Eric Chou", // Firefox OS
  // "BetaTriage": "?", // Firefox OS
  "Bluetooth": "Eric Chou", // Firefox OS
  "Build Config": "Dylan Oliver", // Core
  "Canvas: 2D": "Milan Sreckovic (Benoit Jacob, Jeff Muizelaar)",
  "Canvas: WebGL": "Milan Sreckovic (Benoit Jacob, Jeff Gilbert)",
  "CSS Parsing and Computation": "Jet Villegas",
  // "Emulator": "?", // Firefox OS
  // "FxA": "?", // Firefox OS
  "DOM: Apps": "Fabrice Desré",
  "DOM: Core & HTML": "Andrew Overholt (Johnny Stenback)", // DOM
  "DOM": "Andrew Overholt (2nd: Johnny Stenback)", // DOM
  "DOM: Contacts": "David Scravaglieri (Francisco Jordano)", // DOM
  "DOM: Device Interfaces": "Andrew Overholt (Johnny Stenback)", // DOM
  "DOM: Events": "Andrew Overholt (Johnny Stenback)",
  "Gaia": "David Scravaglieri (Francisco Jordano)",
  "Gaia::Bluetooth File Transfer": "Tim Guan-tin Chien (Ian Liu)",
  "Gaia::Browser": "Gregor Wagner (Ben Francis)",
  "Gaia::Build": "Tim Guan-tin Chien (Yuren Ju)",
  "Gaia::Calendar": "Dylan Oliver (Gareth Aye)",
  "Gaia::Camera": "Hema Koka (David Flanagan)",
  "Gaia::Clock": "Dylan Oliver (Marcus Cavanaugh)",
  "Gaia::Contacts": "David Scravaglieri (Francisco Jordano)",
  "Gaia::Cost Control": "David Scravaglieri (Francisco Jordano)",
  "Gaia::Dialer": "David Scravaglieri (Francisco Jordano)",
  "Gaia::E-Mail": "Dylan Oliver (Andrew Sutherland)",
  "Gaia::Everything.me": "Gregor Wagner (Michael Henretty)",
  "Gaia::First Time Experience": "Gregor Wagner (Michael Henretty)",
  "Gaia::FMRadio": "Hema Koka (David Flanagan)",
  "Gaia::Gallery": "Hema Koka (David Flanagan)",
  // "Gaia::GithubBot": "?",ven
  "Gaia::Homescreen": "Gregor Wagner (Kevin Grandon)",
  "Gaia::Keyboard": "Tim Guan-tin Chien (Rudy Lu)",
  "Gaia::Music": "Hema Koka (David Flanagan)",
  "Gaia::Notes": "Dylan Oliver",
  // "Gaia::PDF Viewer": "?",
  // "Gaia::PerformanceTest": "?",
  "Gaia::Ringtones": "Hema Koka (David Flanagan)",
  "Gaia::Search": "Gregor Wagner (Kevin Grandon)",
  "Gaia::Settings": "Tim Guan-tin Chien (Arthur Chen)",
  "Gaia::SMS": "David Scravaglieri (Francisco Jordano)",
  "Gaia::System": "Gregor Wagner (Michael Henretty)", //  Tim relies on Gregor to actively throwing bugs over.
  "Gaia::System::Browser Chrome": "Gregor Wagner (Ben Francis)",
  "Gaia::System::Input Mgmt": "Tim Guan-tin Chien (Rudy Lu)",
  "Gaia::System::Lockscreen": "Tim Guan-tin Chien (Greg Weng)",
  "Gaia::System::Window Mgmt": "Tim Guan-tin Chien (Alive Kuo)",
  // "Gaia::TestAgent": "?",
  // "Gaia::UI Tests": "?",
  "Gaia::Video": "Hema Koka (David Flanagan)",
  // "Gaia::Wallpaper": "?",
  "Gaia::Wappush": "David Scravaglieri (Francisco Jordano)",
  "General (Firefox OS)": "Lawrence Mandel (Bhavana, Preeti)",
//  "General (Core)": "Lawrence Mandel",
//  "General (Loop+)": "Lawrence Mandel",

  "GonkIntegration": "Thomas Tsai", // Firefox OS
  "General Automation": "Jonathan Griffin", // Release Engineering
  "Geolocation": "Doug Turner", // Core
  "Graphics": "Milan Sreckovic (Jeff Muizelaar, Benoit Girard)", // Core
  "Graphics: Layers": "Milan Sreckovic (Bas Schouten, Benoit Girard)", // Core
  // "Hardware": "?", // Firefox OS
  "Hardware Abstraction Layer (HAL)": "Dave Hylands", // Core
  "ImageLib": "Milan Sreckovic (Jeff Muizelaar, Seth Fowler)",
  "IPC": "Andrew Overholt (Johnny Stenback)",
  "JavaScript Engine": "Naveed Ihsanullah", // Core
  "JavaScript: GC": "Naveed Ihsanullah", // Core
  "Layout": "Jet Villegas", // Core
  "MFBT": "Naveed Ihsanullah",
  "Networking": "Jason Duell", // Core
  "NFC": "Ken Chang(Vincent Chang)", // Firefox OS
  "rtsp": "Ken Chang(Vincent Chang)", // Firefox OS
  "Panning and Zooming": "Milan Sreckovic (Kartikaya Gupta, Botond Ballo)", // Core
  "Performance": "Mike Lee (Mason Chang)", // Firefox OS
  "Runtime": "Gregor Wagner (Fabrice Desré)", // Firefox OS
  // "Simulator": "?", // Firefox OS
  "RIL": "Ken Chang(Hsinyi Tsai)", // Firefox OS
  "Video/Audio": "Jet Villegas", // Core
  "Video/Audio: Recording": "CJ Ku", // Core
  "Vendcom": "Vance Chen", // Firefox OS
  "Widget: Gonk": "Mike Wu",
  "Wifi": "Ken Chang (Vincent Chang)", // Firefox OS
  // "WMF": "?" // Firefox OS
};
<|endoftext|>


<commit_before>import childProcess from 'child_process'
import fs from 'fs'
import path from 'path'

// CREATE TASK
// this is the first task you can call from teleport to build  project.
// - it decides if the name of the project is good set
// (and if not, it will give you one random)
// - it checks if there is folder with the same project name here.
// - it checks if there are no such project already refered into the .projects.json
// of your teleport
// - it create your folder that will contain the file system
// - it calls the sub tasks init

export function create () {
  this.getLevelMethod('create')()
  this.consoleInfo('Your teleport create was sucessful !')
}

export function createProject () {
  // unpack
  const { app, project, program } = this
  // check if such a project exists already here
  project.dir = path.join(this.currentDir, program.project)
  this.consoleInfo(`wait a second... We create your ${program.project} project !`)
  if (fs.existsSync(project.dir)) {
    this.consoleWarn(`There is already a ${program.project} here...`)
    process.exit()
  }
  const projectsByName = app.projectsByName
  const previousProject = projectsByName[program.project]
  if (previousProject) {
    this.consoleWarn(`There is already a ${program.project} here ${previousProject.dir}...`)
    process.exit()
  }
  projectsByName[program.project] = {
    dir: project.dir
  }
  this.writeProjectsByName(projectsByName)
  // mkdir the folder app
  childProcess.execSync(`mkdir -p ${program.project}`)
  // write default package
  this.init()
  // info
  this.consoleInfo(`Your ${program.project} was successfully created, go inside with \'cd ${program.project}\' !`)
}
<commit_msg>simplified create method<commit_after>import childProcess from 'child_process'
import fs from 'fs'
import path from 'path'

// CREATE TASK
// this is the first task you can call from teleport to build  project.
// - it decides if the name of the project is good set
// (and if not, it will give you one random)
// - it checks if there is folder with the same project name here.
// - it checks if there are no such project already refered into the .projects.json
// of your teleport
// - it create your folder that will contain the file system
// - it calls the sub tasks init

export function create () {
  // unpack
  const { app, project, program } = this
  // check if such a project exists already here
  project.dir = path.join(this.currentDir, program.project)
  this.consoleInfo(`wait a second... We create your ${program.project} project !`)
  if (fs.existsSync(project.dir)) {
    this.consoleWarn(`There is already a ${program.project} here...`)
    process.exit()
  }
  const projectsByName = app.projectsByName
  const previousProject = projectsByName[program.project]
  if (previousProject) {
    this.consoleWarn(`There is already a ${program.project} here ${previousProject.dir}...`)
    process.exit()
  }
  projectsByName[program.project] = {
    dir: project.dir
  }
  this.writeProjectsByName(projectsByName)
  // mkdir the folder app
  childProcess.execSync(`mkdir -p ${program.project}`)
  // write default package
  this.init()
  // info
  this.consoleInfo(`Your ${program.project} was successfully created, go inside with \'cd ${program.project}\' !`)
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require("fs");
const os = require("os");

let log = fs.readFileSync(`${os.homedir()}/.keys.log`, "utf8")
// Remove instances of three repeated characters in a row
log = log.replace(/(.)\1{2,}/g, " ");

function getScore(string, frequency) {
    return string.length * frequency;
}

const counts = new Map();
for (let i = 0; i < log.length; i++) {
    for (let j = i + 3; j < i + 40; j++) {
        const substring = log.slice(i, j);
        if (!/^\s+$/g.test(substring)) {
            const currentValue = counts.get(substring);
            const newFrequency = currentValue ? currentValue.frequency + 1 : 1;
            counts.set(substring, {
                score: getScore(substring, newFrequency),
                frequency: newFrequency
            });
        }
   }
}

const sorted = new Map([...counts].sort((a, b) => {
    return b[1].score - a[1].score;
}));

let count = 0;
for (const entry of sorted) {
    console.log(entry);
    count++;
    if (count > 1000) {
        break;
    }
}
<commit_msg>Ignore directional sequences in the key log<commit_after>#!/usr/bin/env node

const fs = require("fs");
const os = require("os");

let log = fs.readFileSync(`${os.homedir()}/.keys.log`, "utf8")
// Remove instances of three repeated characters in a row
log = log.replace(/(.)\1{2,}/g, " ");

function getScore(string, frequency) {
    return string.length * frequency;
}

const counts = new Map();
for (let i = 0; i < log.length; i++) {
    for (let j = i + 3; j < i + 40; j++) {
        const substring = log.slice(i, j);
        // Ignore directional sequences
        if (!/^[hjkl\s]+$/g.test(substring)) {
            const currentValue = counts.get(substring);
            const newFrequency = currentValue ? currentValue.frequency + 1 : 1;
            counts.set(substring, {
                score: getScore(substring, newFrequency),
                frequency: newFrequency
            });
        }
   }
}

const sorted = new Map([...counts].sort((a, b) => {
    return b[1].score - a[1].score;
}));

let count = 0;
for (const entry of sorted) {
    console.log(entry);
    count++;
    if (count > 300) {
        break;
    }
}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL

 Permission to use this software for any purpose without fee is hereby granted, provided
 that the above copyright notice and this permission notice appear in all copies.

 Permission to copy and/or edit this software or parts of it for any purpose is permitted,
 provided that the following points are followed.
 - The above copyright notice and this permission notice appear in all copies
 - Within two (2) days after modification is proven working, any modifications are send back
   to the original authors to be inspected with the goal of inclusion in the official software
 - Any edited version are only test versions and not permitted to be run as a final product
 - Any edited version aren't to be distributed
 - Any edited version have the prerelease version set to something that can be distinguished
   from a version used in the original software

 TERMS OF REPRODUCTION USE

 Failure to follow these terms will result in me getting very angry at you
 and having your software tweaked or removed if possible. Either way, you're
 still an idiot for not following such a basic rule.
 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
 BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 * @Author:    Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)

 * [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
 *         WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
 */

var path = 'http://pastebin.com/raw.php?i=';

function message(contents) {
        var msg = '
Plugwoot™  '+ contents +'
';
        $('#chat-messages').append(msg);
}

var scriptFail = window.setTimeout(function() {
  //message("Oops! Something has gone wrong!")
  $('#chat-messages').append('
Plugwoot™  Hey guys!
 We apologies about plugwoot. Due to 8 minute request, AutoJoin may cause some of the spams problem to plug.dj\'s website
 When this occurs users may get banned at certain point. So we advice you to use our Plugwoot Alpha version. Thanks for understanding!
 More info will be release soon.
');
  }, 2500);

if(window.location.hostname === "plug.dj"){
 $.getScript(path + '9X4yAhEa', function() {
   message("version "+ PlugStation.version +" is now activated!");
   console.log("Plugwoot "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
 window.clearTimeout(scriptFail);
 });
 }else{
  alert("This script can only be functioned at http://plug.dj/communities/");
 }
<commit_msg>Update Plugwoot.js<commit_after>/*
 Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL

 Permission to use this software for any purpose without fee is hereby granted, provided
 that the above copyright notice and this permission notice appear in all copies.

 Permission to copy and/or edit this software or parts of it for any purpose is permitted,
 provided that the following points are followed.
 - The above copyright notice and this permission notice appear in all copies
 - Within two (2) days after modification is proven working, any modifications are send back
   to the original authors to be inspected with the goal of inclusion in the official software
 - Any edited version are only test versions and not permitted to be run as a final product
 - Any edited version aren't to be distributed
 - Any edited version have the prerelease version set to something that can be distinguished
   from a version used in the original software

 TERMS OF REPRODUCTION USE

 Failure to follow these terms will result in me getting very angry at you
 and having your software tweaked or removed if possible. Either way, you're
 still an idiot for not following such a basic rule.
 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
 INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
 BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
 RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 * @Author:    Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)

 * [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
 *         WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
 */

var path = 'http://pastebin.com/raw.php?i=';

function message(contents) {
        var msg = '
Plugwoot™  '+ contents +'
';
        $('#chat-messages').append(msg);
}

var scriptFail = window.setTimeout(function() {
  //message("Oops! Something has gone wrong!")
  $('#chat-messages').append('
Plugwoot™  Hey guys!
 We apologies about plugwoot. Due to 8 minute request, AutoJoin may cause some of the spams problem to plug.dj\'s website
 When this occurs users may get banned at certain point. So we advice you to use our Plugwoot Alpha version. Thanks for understanding!
 More info will be release soon.
');
  }, 3700);

if(window.location.hostname === "plug.dj"){
 $.getScript(path + '9X4yAhEa', function() {
   message("version "+ PlugStation.version +" is now activated!");
   console.log("Plugwoot "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
 window.clearTimeout(scriptFail);
 });
 }else{
  alert("This script can only be functioned at http://plug.dj/communities/");
 }
<|endoftext|>


<commit_before>'use strict';

//const _ = require('lodash');
//var pg = require('pg');
//var extend = require('util')._extend;

//postgress client connection

var pg = require('pg');
var Client = require('pg').Client;

pg.defaults.ssl = true;

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

  function schedConv(newBot, response) {
    var client = new Client(process.env.DATABASE_URL);
    client.connect();
    var mess = [{uid:"",msg:""}];
    var query1 = client.query("SELECT message FROM batchmessage WHERE sendtime >= CURRENT_TIMESTAMP - INTERVAL '299.999 seconds' AND sendtime <= CURRENT_TIMESTAMP + INTERVAL '5 minutes' ORDER BY sendtime");
        //query1.on('row', function(row1) {
          //var query2 = client.query("SELECT DISTINCT smoochid FROM conversation;");
        //  var query2 = client.query("select smoochid from conversation WHERE smoochid = 'a30fa820d0a0f0216fa26070' LIMIT 30;");
        //    query2.on('row',function(row2) {
                //console.log("before adding to array");
        //        mess.push(row2.smoochid, process.env.SCHED_PREFIX + row1.message);
                //console.log("after adding to array");
        //    });
        //    query2.on('end', function(result) {
                //fired once and only once, after the last row has been returned and after all 'row' events are emitted
                //in this example, the 'rows' array now contains an ordered set of all the rows which we received from postgres
        //        console.log(result.rowCount + ' rows were received');
        //        sendSched(newBot, mess);
        //      })
        //});
      console.log(query1.text);
      client.on('drain', client.end.bind(client));

  }

  function sendSched (bot,msg) {
    console.log("sendSched was called");
    var arrayLength = msg.length;
    for (var i = 0; i < arrayLength; i++) {
        console.log(msg[i].uid);
        bot.userId = msg[i].msg;
        bot.say(msg[i][1]).then(console.log(msg[i][1]),() => 'speak');
    }
  }

module.exports = {schedConv};
<commit_msg>restart 1<commit_after>'use strict';

//const _ = require('lodash');
//var pg = require('pg');
//var extend = require('util')._extend;

//postgress client connection

var pg = require('pg');
var Client = require('pg').Client;

pg.defaults.ssl = true;

function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

  function schedConv(newBot, response) {
    var client = new Client(process.env.DATABASE_URL);
    client.connect();
    var mess = "";
    var uid = [];
    var query1 = client.query("SELECT message FROM batchmessage WHERE sendtime >= CURRENT_TIMESTAMP - INTERVAL '299.999 seconds' AND sendtime <= CURRENT_TIMESTAMP + INTERVAL '5 minutes' ORDER BY sendtime");
        query1.on('row', function(row1) {
          mess = process.env.SCHED_PREFIX + row1.message
        }
        //var query2 = client.query("SELECT DISTINCT smoochid FROM conversation;");
    var query2 = client.query("select smoochid from conversation WHERE smoochid = 'a30fa820d0a0f0216fa26070' LIMIT 30;");
      query2.on('row',function(row2) {
                //console.log("before adding to array");
        mess.push(row2.smoochid);
                //console.log("after adding to array");
      });
        //    query2.on('end', function(result) {
                //fired once and only once, after the last row has been returned and after all 'row' events are emitted
                //in this example, the 'rows' array now contains an ordered set of all the rows which we received from postgres
        //        console.log(result.rowCount + ' rows were received');
      sendSched(newBot, uid, mess);
        //      })
        //});
      console.log(mess);
      client.on('drain', client.end.bind(client));

  }

  function sendSched (bot, uid, msg) {
    console.log("sendSched was called");
    var arrayLength = uid.length;
    for (var i = 0; i < arrayLength; i++) {
        console.log(msg);
        bot.userId = uid[i];
        bot.say(msg).then(console.log(msg),() => 'speak');
    }
  }

module.exports = {schedConv};
<|endoftext|>


<commit_before>/**
 * @class Backbone.PropertiesView
 * @extends Backbone.View
 */
Backbone.PropertiesView = Backbone.View.redefine(function (origin) {
    return /**@lends Backbone.View*/{

        initialize: function () {
            this._initProperties();
            return origin.initialize.apply(this, arguments);
        },

        /**
         * method for view properties initialisation
         * @protected
         */
        _initProperties: function () {
        }
    }
});<commit_msg>PSDJS-5885 multiform second step<commit_after><|endoftext|>


<commit_before>/* GET 'home' page */
module.exports.homelist = function(req, res) {
    res.render('locations-list', {
        title: 'Loc8r - find a place to work with wifi',
        pageHeader: {
            title: 'Loc8r',
            strapline: 'Find places to work with wifi near you!'
        },
        sidebar: "Looking for wifi and a seat? Loc8r helps you find places to work when out and about. Perhaps with coffee, cake or a pint? Let Loc8r help you find the place you're looking for.",
        locations: [{
            name: 'Starcups',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 3,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            distance: '100m'
        }, {
            name: 'Cafe Hero',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 4,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            distance: '200m'
        }, {
            name: 'Burger Queen',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 2,
            facilities: ['Food', 'Premium wifi'],
            distance: '250m'
        }]
    });
};

/* GET 'Location info' page */
module.exports.locationInfo = function(req, res) {
    res.render('location-info', {
        title: 'Starcups',
        pageHeader: {
            title: 'Starcups'
        },
        sidebar: {
            context: 'is on Loc8r because it has accessible wifi and space to sit down with your laptop and get some work done.',
            callToAction: 'If you\'ve been and you like it - or if you don\'t - please leave a review to help other people just like you.'
        },
        location: {
            name: 'Starcups',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 3,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            coords: {
                lat: 51.455041,
                lng: -0.9690884
            },
            openingTimes: [{
                days: 'Monday - Friday',
                opening: '7:00am',
                closing: '7:00pm',
                closed: false
            }, {
                days: 'Saturday',
                opening: '8:00am',
                closing: '5:00pm',
                closed: false
            }, {
                days: 'Sunday',
                closed: true
            }],
            reviews: [{
                author: 'Simon Holmes',
                rating: 5,
                timestamp: '16 July 2013',
                reviewText: 'What a great place. I can\'t say enough good things about it.'
            }, {
                author: 'Charlie Chaplin',
                rating: 3,
                timestamp: '16 June 2013',
                reviewText: 'It was okay. Coffee wasn\'t great, but the wifi was fast.'
            }]
        }
    });
};

/* GET 'Add review' page */
module.exports.addReview = function(req, res) {
    res.render('location-review-form', {
        title: 'Review Starcups on Loc8r',
        pageHeader: {
            title: 'Review Starcups'
        }
    });
};
<commit_msg>Add request<commit_after>var request = require('request');

/* GET 'home' page */
module.exports.homelist = function(req, res) {
    res.render('locations-list', {
        title: 'Loc8r - find a place to work with wifi',
        pageHeader: {
            title: 'Loc8r',
            strapline: 'Find places to work with wifi near you!'
        },
        sidebar: "Looking for wifi and a seat? Loc8r helps you find places to work when out and about. Perhaps with coffee, cake or a pint? Let Loc8r help you find the place you're looking for.",
        locations: [{
            name: 'Starcups',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 3,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            distance: '100m'
        }, {
            name: 'Cafe Hero',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 4,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            distance: '200m'
        }, {
            name: 'Burger Queen',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 2,
            facilities: ['Food', 'Premium wifi'],
            distance: '250m'
        }]
    });
};

/* GET 'Location info' page */
module.exports.locationInfo = function(req, res) {
    res.render('location-info', {
        title: 'Starcups',
        pageHeader: {
            title: 'Starcups'
        },
        sidebar: {
            context: 'is on Loc8r because it has accessible wifi and space to sit down with your laptop and get some work done.',
            callToAction: 'If you\'ve been and you like it - or if you don\'t - please leave a review to help other people just like you.'
        },
        location: {
            name: 'Starcups',
            address: '125 High Street, Reading, RG6 1PS',
            rating: 3,
            facilities: ['Hot drinks', 'Food', 'Premium wifi'],
            coords: {
                lat: 51.455041,
                lng: -0.9690884
            },
            openingTimes: [{
                days: 'Monday - Friday',
                opening: '7:00am',
                closing: '7:00pm',
                closed: false
            }, {
                days: 'Saturday',
                opening: '8:00am',
                closing: '5:00pm',
                closed: false
            }, {
                days: 'Sunday',
                closed: true
            }],
            reviews: [{
                author: 'Simon Holmes',
                rating: 5,
                timestamp: '16 July 2013',
                reviewText: 'What a great place. I can\'t say enough good things about it.'
            }, {
                author: 'Charlie Chaplin',
                rating: 3,
                timestamp: '16 June 2013',
                reviewText: 'It was okay. Coffee wasn\'t great, but the wifi was fast.'
            }]
        }
    });
};

/* GET 'Add review' page */
module.exports.addReview = function(req, res) {
    res.render('location-review-form', {
        title: 'Review Starcups on Loc8r',
        pageHeader: {
            title: 'Review Starcups'
        }
    });
};
<|endoftext|>


<commit_before>exports.config = {
  baseUrl: 'http://localhost:8080',
  specs: ['test/e2e/*Spec.js']
};
if (process.env.TRAVIS){
  exports.config.sauceUser = process.env.SAUCE_USERNAME;
  exports.config.sauceKey = process.env.SAUCE_ACCESS_KEY;
  exports.config.capabilities = {
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
    'build': process.env.TRAVIS_BUILD_NUMBER
  };
}
<commit_msg>add seleniumAddress that uses SauceConnect<commit_after>exports.config = {
  baseUrl: 'http://localhost:8080',
  specs: ['test/e2e/*Spec.js']
};
if (process.env.TRAVIS){
  var sauceUser = process.env.SAUCE_USERNAME;
  var sauceKey = process.env.SAUCE_ACCESS_KEY;

  exports.config.sauceUser = sauceUser;
  exports.config.sauceKey = sauceKey;
  exports.config.seleniumAddress = 'http://' + sauceUser + ':' + sauceKey + '@localhost:4445/wd/hub';
  exports.config.capabilities = {
    'tunnel-identifier': process.env.TRAVIS_JOB_NUMBER,
    'build': process.env.TRAVIS_BUILD_NUMBER
  };
}
<|endoftext|>


<commit_before>"use strict";
var __version__='1.0.1';
function isChainable(name){
	name=name[0]=='.'?name.slice(1).split("(")[0]:name.split("(")[0];//remove '.' and "(" and ")"
	var tools={"activateGenerator":true,"deactivateGenerator":true,"setAxisValues":true,"resetGenerator":true,"addToFavourites":true,"removeFavourites":true,"getId":false,"getFavourites":false,
	"getBackup":false,"restoreBackup":false};
	return tools[name] != undefined ?tools[name]:false;//if the key does not exist in the above dictionary return  false else return its value
}
function TextShadow(args){
	function val(o){return $(o).val();}
	function abs(a){return Math.abs(a);}
	function bind(container,evnt,item,fn){
		$(function(){
			if(item)
				$(container).on(evnt,item,fn);
			else
				$(container).on(evnt,fn);
		});
	}
	var self=this;
	var host=null;
	self.generator_markup=""+
	"
 "+
		"
"+
			"
Text shadow Generator
"+
			"
"+
			"
 "+
				"
 "+
					"
X-axis
 "+
					"<input type='range' class='text-shadow-sliders x-axis' min='-100' max='150' value=0>"+
				"
 "+
				"
"+
					"
Y-axis
 "+
					"<input type='range' class='text-shadow-sliders y-axis' min='-100' max='150' value=0> "
				+"
"
				+"
"+
					"
Blur
"+
					"<input type='range' class='text-shadow-sliders blur' min='0' max='10' step='0.1' value='0'> "+
				"
"+
			"
"+
			"

Shadow is applied here

 "+
			"
 "+
			"
"+
				"
Red
 "+
				"<input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
"+
			"
 "+
				"
Green
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'>"+
			"
 "+
			"
 "+
				"
Blue
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
 "+
			"
 "+
				"
Opacity
 "+
				"<input type='range' class='text-shadow-color-sliders opacity' min='0' max='1' step='0.1' value='1'> "+
			"
"+
			"
"+
		"
  "+
			"
text-shadow:0px 0px rgb(0,0,0);
  "+
		"
"+
	"
 ";
	self.host_id=null;
	if(typeof args != 'string' || !args || args[0]=='.' || !args[0]=="#"){
		throw new Error("Invalid id!!!"+args);
	}
	else
		self.host_id=host=args;
	self.shadow_code="none";
	self.content_backup=null;
	self.favourites=[];
	for(var i=1;i<=30;i++)self.favourites.push(i);
	self.getId=function(){
		return self.host_id;
	};
	var render=function(){
		if(host != null && host[0]=='#')
			bind(document,"ready",null,function(){
				self.content_backup=$(host).html();
				$(host).html(self.generator_markup);
			});
		return self;
	};
	self.getBackup=function(){
		return self.content_backup;
	}
	self.restoreBackup=function(destination){
		var backup=self.getBackup();
		if(!destination)
			throw new Error("Wrong destination");
		var isClass=destination[0]=='.';
		if(isClass){
			var answer=confirm("You are going to create duplicates of your backed content.Are you sure you want to continue");
			if(answer)
				$(destination).html(backup);
		}
		else
			$(destination).html(backup);
		return self;
	};
	self.getCode=function(){
		return self.shadow_code;
	};
	self.activateGenerator=function(){
		var code=self.getCode();
		bind(host,"mousemove touchmove",null,function(){
			var sliders=$(host+" .panel-body .text-shadow-sliders");
			var color_sliders=$(host+" .panel-body .text-shadow-color-sliders");
			var color=val(color_sliders[3]) != '1'?"rgba("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+","+val(color_sliders[3])+")":"rgb("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+")";
			self.shadow_code=val(sliders[0])+"px "+val(sliders[1])+"px ";
			if(val(sliders[2])!= '0')
				self.shadow_code+=val(sliders[2])+"px ";
			self.shadow_code+=color;
			$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
			$(host+ " .panel .text-shadow-output").css("text-shadow",self.shadow_code);
		});
		return self;
	};
	self.deactivateGenerator=function(){
		$(host).off();
		return self;
	};
	self.setAxisValues=function(limit,value){
		//more validations to come here
		var sliders=$(host+" .text-shadow-sliders");
		if(isNaN(value) || !value || !limit)
			throw new Error("An error occured.");
		var value=abs(value);
		switch(limit.toUpperCase()){
			//we use for loop because we do not want to target every single slider
			case "MIN":
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("min",value * -1);
				break;
			default:
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("max",value);
		}//switch
		return self;
	};
	self.resetGenerator=function(){
		$(host+" .text-shadow-sliders").val(0);
		$(host+" .text-shadow-color-sliders").val(0);
		$(host+" .opacity").val(1);
		self.shadow_code="0px 0px rgb(0,0,0)";
		$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
		$(host+ " .panel .text-shadow-output").css("text-shadow","none");
		return self;
	};
	self.addToFavourites=function(append){
		var code=self.getCode();
		if(self.favourites.indexOf(code)== -1 && code != "none")
			self.favourites.push(code);
		return self;
	};
	self.getFavourites=function(){
		return self.favourites;
	};
	self.removeFavourites=function(){
		var del;
		if( del=confirm("Are you sure you want to erase your favourites?"))
			self.favourites.length=0;
		return self;
	};
	self.showFavourites=function(){
		var error="Function has not been implemented yet and it is not part of the public API!!!!";
		var index=0;
		/*try{
			bootbox.alert("
"+error+"
");
		}
		catch(e){
			setTimeout(function(){
				console.warning(error);
			},3000);
		}*/
		var favourites=self.getFavourites();
		var total=favourites.length;
		if(favourites.length<1)
			bootbox.alert("No favourites  to show!!!");
		else{
			var list_items;
			function renderlist(){
				var ul="
";
				var carrets="

"
				+"

";
				for(var i=0;i<10;i++)
					ul+="
text-shadow:"+favourites[i]+";
";
				ul+="
"+carrets;
				list_items=$(".favourite_item");
				return ul;
			}
			bootbox.alert(renderlist());
			bind(".list-group","click",".list-group-item",function(){
				$(".list-group li").removeClass('active');
				$(this).addClass('active');
			});
			bind(".show_less","click",null,function(){
				console.log("Total:"+favourites.length);
			});
			bind(".show_more","click",null,function(){
				var current_list="";
				list_items=$(".favourite_item");
				for(var i=index;i<total-(total-10);i++){
					current_list+="
"+favourites[i]+"
";
				}
				$(".fix").html(current_list);
				console.log(current_list);
				index+=10;
			});
		}
		return self;
	};
	self.downloadFavourites=function(){
		var file="/********\n";
		var items=self.getFavourites();
		if(items.length<1)
			return "No favourites found";
		for(var i=0;i<items.length;i++)
			file+="text-shadow:"+items[i]+";\n";
		file+="**************\n";
		try{
			saveAs(new Blob([file], {type: "text/plain;charset=utf-8"}),"favourites.css");
		}
		catch(e){
			alert("Filesaver is missing!!!");
		}
	};
	render();
}<commit_msg>fixed show more function now show less is left<commit_after>"use strict";
var __version__='1.0.1';
function isChainable(name){
	name=name[0]=='.'?name.slice(1).split("(")[0]:name.split("(")[0];//remove '.' and "(" and ")"
	var tools={"activateGenerator":true,"deactivateGenerator":true,"setAxisValues":true,"resetGenerator":true,"addToFavourites":true,"removeFavourites":true,"getId":false,"getFavourites":false,
	"getBackup":false,"restoreBackup":false};
	return tools[name] != undefined ?tools[name]:false;//if the key does not exist in the above dictionary return  false else return its value
}
function TextShadow(args){
	function val(o){return $(o).val();}
	function abs(a){return Math.abs(a);}
	function bind(container,evnt,item,fn){
		$(function(){
			if(item)
				$(container).on(evnt,item,fn);
			else
				$(container).on(evnt,fn);
		});
	}
	var self=this;
	var host=null;
	self.generator_markup=""+
	"
 "+
		"
"+
			"
Text shadow Generator
"+
			"
"+
			"
 "+
				"
 "+
					"
X-axis
 "+
					"<input type='range' class='text-shadow-sliders x-axis' min='-100' max='150' value=0>"+
				"
 "+
				"
"+
					"
Y-axis
 "+
					"<input type='range' class='text-shadow-sliders y-axis' min='-100' max='150' value=0> "
				+"
"
				+"
"+
					"
Blur
"+
					"<input type='range' class='text-shadow-sliders blur' min='0' max='10' step='0.1' value='0'> "+
				"
"+
			"
"+
			"

Shadow is applied here

 "+
			"
 "+
			"
"+
				"
Red
 "+
				"<input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
"+
			"
 "+
				"
Green
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'>"+
			"
 "+
			"
 "+
				"
Blue
 "+
				" <input type='range' class='text-shadow-color-sliders' min='0' max='255' step='1' value='0'> "+
			"
 "+
			"
 "+
				"
Opacity
 "+
				"<input type='range' class='text-shadow-color-sliders opacity' min='0' max='1' step='0.1' value='1'> "+
			"
"+
			"
"+
		"
  "+
			"
text-shadow:0px 0px rgb(0,0,0);
  "+
		"
"+
	"
 ";
	self.host_id=null;
	if(typeof args != 'string' || !args || args[0]=='.' || !args[0]=="#"){
		throw new Error("Invalid id!!!"+args);
	}
	else
		self.host_id=host=args;
	self.shadow_code="none";
	self.content_backup=null;
	self.favourites=[];
	for(var i=1;i<=30;i++)self.favourites.push(i);
	self.getId=function(){
		return self.host_id;
	};
	var render=function(){
		if(host != null && host[0]=='#')
			bind(document,"ready",null,function(){
				self.content_backup=$(host).html();
				$(host).html(self.generator_markup);
			});
		return self;
	};
	self.getBackup=function(){
		return self.content_backup;
	}
	self.restoreBackup=function(destination){
		var backup=self.getBackup();
		if(!destination)
			throw new Error("Wrong destination");
		var isClass=destination[0]=='.';
		if(isClass){
			var answer=confirm("You are going to create duplicates of your backed content.Are you sure you want to continue");
			if(answer)
				$(destination).html(backup);
		}
		else
			$(destination).html(backup);
		return self;
	};
	self.getCode=function(){
		return self.shadow_code;
	};
	self.activateGenerator=function(){
		var code=self.getCode();
		bind(host,"mousemove touchmove",null,function(){
			var sliders=$(host+" .panel-body .text-shadow-sliders");
			var color_sliders=$(host+" .panel-body .text-shadow-color-sliders");
			var color=val(color_sliders[3]) != '1'?"rgba("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+","+val(color_sliders[3])+")":"rgb("+val(color_sliders[0])+","+val(color_sliders[1])+","+val(color_sliders[2])+")";
			self.shadow_code=val(sliders[0])+"px "+val(sliders[1])+"px ";
			if(val(sliders[2])!= '0')
				self.shadow_code+=val(sliders[2])+"px ";
			self.shadow_code+=color;
			$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
			$(host+ " .panel .text-shadow-output").css("text-shadow",self.shadow_code);
		});
		return self;
	};
	self.deactivateGenerator=function(){
		$(host).off();
		return self;
	};
	self.setAxisValues=function(limit,value){
		//more validations to come here
		var sliders=$(host+" .text-shadow-sliders");
		if(isNaN(value) || !value || !limit)
			throw new Error("An error occured.");
		var value=abs(value);
		switch(limit.toUpperCase()){
			//we use for loop because we do not want to target every single slider
			case "MIN":
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("min",value * -1);
				break;
			default:
				for(var i=0;i<sliders.length-1;i++)
					$(sliders[i]).prop("max",value);
		}//switch
		return self;
	};
	self.resetGenerator=function(){
		$(host+" .text-shadow-sliders").val(0);
		$(host+" .text-shadow-color-sliders").val(0);
		$(host+" .opacity").val(1);
		self.shadow_code="0px 0px rgb(0,0,0)";
		$(host+ " .text-shadow-code-output").text("text-shadow:"+self.shadow_code+";");
		$(host+ " .panel .text-shadow-output").css("text-shadow","none");
		return self;
	};
	self.addToFavourites=function(append){
		var code=self.getCode();
		if(self.favourites.indexOf(code)== -1 && code != "none")
			self.favourites.push(code);
		return self;
	};
	self.getFavourites=function(){
		return self.favourites;
	};
	self.removeFavourites=function(){
		var del;
		if( del=confirm("Are you sure you want to erase your favourites?"))
			self.favourites.length=0;
		return self;
	};
	self.showFavourites=function(){
		var error="Function has not been implemented yet and it is not part of the public API!!!!";
		var index=10;
		/*try{
			bootbox.alert("
"+error+"
");
		}
		catch(e){
			setTimeout(function(){
				console.warning(error);
			},3000);
		}*/
		var favourites=self.getFavourites();
		var total=favourites.length;
		if(favourites.length<1)
			bootbox.alert("No favourites  to show!!!");
		else{
			var list_items;
			function renderlist(){
				var ul="
";
				var carrets="

"
				+"

";
				for(var i=0;i<10;i++)
					ul+="
text-shadow:"+favourites[i]+";
";
				ul+="
"+carrets;
				list_items=$(".favourite_item");
				return ul;
			}
			bootbox.alert(renderlist());
			bind(".list-group","click",".list-group-item",function(){
				$(".list-group li").removeClass('active');
				$(this).addClass('active');
			});
			bind(".show_less","click",null,function(){
				console.log("Total:"+favourites.length);
			});
			bind(".show_more","click",null,function(){
				if(index>=favourites.length)
					return;//max items displayed so exit the function
				var current_list="";
				var total=favourites.length;
				var diff=total-index;
				var end;
				if(diff > 9)
					end=index+10;
				else
					end=index+diff;
				for(var i=index;i<end;i++)
					current_list+="
text-shadow:"+favourites[i]+";
";
				if(diff>9)
					index+=10
				else
					index+=diff
				$(".fix").html(current_list);
				//console.log(current_list);
			});
		}
		return self;
	};
	self.downloadFavourites=function(){
		var file="/********\n";
		var items=self.getFavourites();
		if(items.length<1)
			return "No favourites found";
		for(var i=0;i<items.length;i++)
			file+="text-shadow:"+items[i]+";\n";
		file+="**************\n";
		try{
			saveAs(new Blob([file], {type: "text/plain;charset=utf-8"}),"favourites.css");
		}
		catch(e){
			alert("Filesaver is missing!!!");
		}
	};
	render();
}<|endoftext|>