<commit_before>"use strict";

/**
 * 查找字串所在位置（从 0 开始索引）。
 * @param {string} p_text 待查文本。
 * @param {string} p_pattern 子串。
 * @param {boolean} [p_recursive] 查找所有字串的位置。
 * @returns {Number|Array}
 */
module.exports.boyer_moore = function (p_text, p_pattern, p_recursive)
{
    // 非法字符串，返回 -1。
    if (!p_text || typeof p_text !== "string" || p_text === "" || !p_pattern || typeof p_pattern !== "string" || p_pattern === "")
    {
        return -1;
    }
    else
    {
        const recursive = p_recursive || false;
        let result = recursive ? [] : -1;

        const lengthT = p_text.length;
        const lengthP = p_pattern.length;
        const suffixPosition = lengthP - 1;

        const badCharacters = _badCharacters(p_pattern);
        const goodIndex = _getGoodIndex(p_pattern);

        let i = 0;
        let shift;
        let badShift = -1;
        let goodShift = -1;
        let goodSuffix = "";
        let currentCharT;
        let currentCharP;
        while (i <= lengthT - lengthP)
        {
            for (let j = lengthP - 1; j >= 0; j--)
            {
                currentCharP = p_pattern[j];
                currentCharT = p_text[i + j];

                if (currentCharP === currentCharT)
                {
                    // 如果全部相等，就输出匹配。
                    if (j === 0)
                    {
                        // 如果需递归查找，则保存结果（并不需要重置 goodSuffix）。
                        if (recursive)
                        {
                            result.push(i);
                        }
                        else
                        {
                            return i;
                        }
                    }
                    else
                    {
                        // 好后缀。
                        goodSuffix = currentCharP + goodSuffix;
                    }
                }
                else
                {
                    // 坏字符。
                    badShift = j - _getBadIndex(currentCharT, badCharacters);
                    if (goodSuffix !== "")
                    {
                        goodShift = suffixPosition - goodIndex;
                        goodSuffix = "";
                        shift = Math.max(badShift, goodShift);
                    }
                    else
                    {
                        shift = badShift;
                    }
                    break;
                }
            }

            i = i + shift;
        }

        if (recursive && result.length === 0)
        {
            result = -1;
        }

        return result;
    }
};

/**
 * 查找“坏字符”第一次出现的位置。
 */
function _getBadIndex(p_char, p_badCharacters)
{
    const index = p_badCharacters[p_char];
    return (index === undefined) ? -1 : index;
}

/**
 * 计算“坏字符规则表”。
 */
function _badCharacters(p_pattern)
{
    const result = {};
    const length = p_pattern.length;
    for (let i = 0; i < length; i++)
    {
        result[p_pattern[i]] = i;
    }
    return result;
}

/**
 * 计算“好后缀规则表”，实际上就是一个整数值。
 */
function _getGoodIndex(p_pattern)
{
    let goodIndex = -1;

    let affix;
    let suffix;
    let subAffix;
    let lengthAffix;
    let lengthSuffix;
    const lengthP = p_pattern.length;
    for (let i = lengthP - 1; i > 0; i--)
    {
        affix = p_pattern.slice(0, i);
        suffix = p_pattern.slice(i);
        lengthAffix = affix.length;
        lengthSuffix = suffix.length;

        subAffix = affix.slice(0, lengthSuffix);
        if (subAffix === suffix)
        {
            // 从最短的后缀找起，如果找到与 pattern 的首位匹配，直接结束。
            goodIndex = lengthSuffix - 1;
            break;
        }
        else
        {
            for (let j = 1; j < lengthAffix - lengthSuffix + 1; j++)
            {
                subAffix = affix.slice(j, j + lengthSuffix);
                if (subAffix === suffix)
                {
                    if (goodIndex === -1)
                    {
                        goodIndex = j + lengthSuffix - 1;
                    }
                    else
                    {
                        // 在没有找到首位出现的情况下，取最小值。
                        goodIndex = Math.min(goodIndex, j + lengthSuffix - 1);
                    }
                    break;
                }
            }
        }
    }

    return goodIndex;
}

/**
 * 计算“好后缀规则表”。
 * 方法：拿到当前所有“好后缀”，从最长的开始，搜索其在 Pattern 中的“上一次出现位置”；如果未找到，则选短一点的，以此类推，直到最短的好后缀；如果都未找到，
 */
function _getGoodSuffixShifts(p_pattern)
{
}<commit_msg>fixed bugs<commit_after>"use strict";

/**
 * 查找字串所在位置（从 0 开始索引）。
 * @param {string} p_text 待查文本。
 * @param {string} p_pattern 子串。
 * @param {boolean} [p_recursive] 查找所有字串的位置。
 * @returns {Number|Array}
 */
module.exports.boyer_moore = function (p_text, p_pattern, p_recursive)
{
    // 非法字符串，返回 -1。
    if (!p_text || typeof p_text !== "string" || p_text === "" || !p_pattern || typeof p_pattern !== "string" || p_pattern === "")
    {
        return -1;
    }
    else
    {
        const recursive = p_recursive || false;
        let result = recursive ? [] : -1;

        const lengthT = p_text.length;
        const lengthP = p_pattern.length;

        const badCharacters = _badCharacters(p_pattern);
        const goodSuffixes = _goodSuffixes(p_pattern);

        let i = 0;
        let shift;
        let goodShift;
        let currentCharT;
        let currentCharP;
        const n = lengthT - lengthP;
        while (i <= n)
        {
            for (let j = lengthP - 1; j >= 0; j--)
            {
                currentCharP = p_pattern[j];
                currentCharT = p_text[i + j];

                if (currentCharP === currentCharT)
                {
                    // 如果全部相等，就输出匹配。
                    if (j === 0)
                    {
                        // 如果需递归查找，则保存结果。
                        if (recursive)
                        {
                            result.push(i);
                        }
                        else
                        {
                            return i;
                        }
                    }
                }
                else
                {
                    // 先按坏字符来计算位移。
                    shift = j - _getBadIndex(currentCharT, badCharacters);

                    // 如果出现好后缀，则计算是否按好后缀来位移。
                    if (j !== lengthP - 1)
                    {
                        goodShift = _getGoodSuffixShift((lengthP - 1) - (j + 1), goodSuffixes, lengthP);
                        shift = goodShift > shift ? goodShift : shift;
                    }
                    break;
                }
            }

            i = i + shift;
        }

        if (recursive && result.length === 0)
        {
            result = -1;
        }

        return result;
    }
};

/**
 * 查找“坏字符”第一次出现的位置。
 */
function _getBadIndex(p_char, p_badCharacters)
{
    const index = p_badCharacters[p_char];
    return (index === undefined) ? -1 : index;
}

/**
 * 计算“坏字符规则表”。
 * 规则：计算 Pattern 中每一个字符的索引。如果出现重复的字符，以最右侧的字符索引为准。
 */
function _badCharacters(p_pattern)
{
    const result = {};
    const length = p_pattern.length;
    for (let i = 0; i < length; i++)
    {
        result[p_pattern[i]] = i;
    }
    return result;
}

/**
 * 计算“好字符”位移。
 */
function _getGoodSuffixShift(p_index, p_goodSuffixes, p_lengthP)
{
    let result = p_goodSuffixes[p_index];

    if (result === undefined)
    {
        result = p_goodSuffixes[p_goodSuffixes.length - 1];
    }

    if (result === undefined)
    {
        result = p_lengthP;
    }

    return result;
}

/**
 * 计算“好后缀规则表”，记录了所有后缀的位移。该数组的“索引 = 前搜索到的“好后缀”的长度 - 1”，例如：好后缀“MPLE”，对应为 [3]。
 * 规则：
 * 数组元素按“好后缀”从短到长排序，索引即：length - 1，取到的值就是 shift。例如：好后缀“E”，就是 [0]。
 * 这里为了节省资源，并没有保存所有“好后缀”的 shift。
 * 因此当未在结果集中找到指定的“好后缀”时，相当于索引为 -1，那么 shift = lengthP - (-1)。
 */
function _goodSuffixes(p_pattern)
{
    const result = [];
    const lengthP = p_pattern.length;

    const suffixes = _suffixes(p_pattern);
    const length = suffixes.length;

    let shift;
    let suffix;
    let suffixLength;
    let suffixIndex;
    let subSuffix;
    let subSuffixIndex;
    let subSuffixLength;
    for (let i = 0; i < length; i++)
    {
        suffix = suffixes[i];
        shift = lengthP - (suffixes[suffix] + suffix.length);
        result[suffix] = shift;
        result.push(shift);
    }
    return result;
}

/**
 * 计算“后缀列表”。
 *
 * 规则：
 * 从最短的 suffix 开始遍历，向前（左侧）中查找是否存在。
 * 如果存在，则记录第一次找到时的索引（从 0 开始，从左向右计算 suffix 首字符所在索引）；
 * 如果不存在，不计入返回值。
 * 如果未找到任何重复的 suffix，则返回值为空。即所有后缀都为 -1，这里为了节省资源，不保存未重复出现的 suffix 索引。
 */
function _suffixes(p_pattern)
{
    const result = [];

    let suffix;
    let subPrefix;
    let suffixIndex;
    let prefix;
    let lengthSuffix;
    let lengthPrefix;

    // 从最短的 suffix 开始遍历。
    for (let i = p_pattern.length - 1; i >= 1; i--)
    {
        suffix = p_pattern.slice(i);
        prefix = p_pattern.slice(0, i);
        lengthSuffix = suffix.length;
        lengthPrefix = prefix.length;

        suffixIndex = -1;
        // 从 prefix 的右侧向左侧查询。
        for (let j = lengthPrefix; j >= lengthSuffix ; j--)
        {
            subPrefix = prefix.slice(j - lengthSuffix, j);
            if (subPrefix === suffix)
            {
                suffixIndex = j - lengthSuffix;
                break;
            }
        }

        if (suffixIndex === -1)
        {
            // 遇到第一个不重复的 suffix 后，后续 suffix 都不用查了，肯定是不重复，都是 -1。
            break;
        }
        else
        {
            result[suffix] = suffixIndex;
            result.push(suffix);
        }
    }
    return result;
}<|endoftext|>


<commit_before><commit_msg>Add Bgm support.<commit_after><|endoftext|>


<commit_before>(function () {
    var app = angular.module('weather-module', []);

    //injector passes these services at load time by dependency injection into the controller as arguments
    app.controller('WeatherController', ['$http', function ($http) {
        var weatherUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22brooklyn%2C%20ny%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

        var weatherCtrl = this;
        this.prettyWeather = [];
        this.weather = [];
        this.outfit = [];

        this.toCelsius = function (text) {
            var f = parseFloat(text);
            var c = ((f - 32) * 5 ) / 9;
            c = c.toFixed(0);
            return c.toString();
        };

        this.toMillibars = function (text) {
            var inches = parseFloat(text);
            var mb = 33.8637526 * inches;
            mb = mb.toFixed(0);
            return mb;
        };

        this.toKnots = function (mph) {
            var mph = parseFloat(mph);
            return (mph / 1.151).toFixed(0);
        }

        this.toKph = function (mph) {
            var mph = parseFloat(mph);
            return (mph * 1.609).toFixed(0);
        }

        this.makeWeatherPretty = function (data) {
            var x = data;
            var str = "
" + x.query.results.channel.item.title + "
";
            str += "
";
            str += "
	Imperial	Metric

";
            str += "
";
            str += "Temp	";
            str += x.query.results.channel.item.condition.temp + "°F";
            str += "	" + this.toCelsius(x.query.results.channel.item.condition.temp) + "°C";
            str += "	";
            str += "
";
            str += "
";
            str += "Pressure	";
            str += x.query.results.channel.atmosphere.pressure + "\"";
            str += "	" + this.toMillibars(x.query.results.channel.atmosphere.pressure) + " MB";
            str += "	";
            str += "
";
            str += "
";
            str += "Humidity	";
            str += x.query.results.channel.atmosphere.humidity + "%";
            str += "	";
            str += x.query.results.channel.atmosphere.humidity + "%";
            str += "	";
            str += "
";
            str += "
";
            str += "Wind	";
            str += this.toKnots(x.query.results.channel.wind.speed) + " knots";
            str += "	";
            str += this.toKph(x.query.results.channel.wind.speed) + " km/h";
            str += "
";
            str += "
";
            console.log(typeof x);

            return (str);
        };

        this.getOutfit = function (data) {
            var x = data;
            var o = [];
            var temperature = x.query.results.channel.item.condition.temp;

            if (temperature > 110)
            {
                o.push("No shirt");
                o.push("Short shorts");
            }
            if (temperature >= 60 && temperature < 110)
            {
                o.push("Singlet/Sports Bra");
                o.push("Short Shorts");
                o.push("Ankle Socks");
            }
            else if (temperature >= 52 && temperature < 60)
            {
                o.push("Light long sleeve");
                o.push("Short Shorts");
                o.push("Ankle Socks");
            }
            else if (temperature >= 44 && temperature < 52)
            {
                o.push("Thin gloves");
                o.push("Nike Combat Turtleneck");
                o.push("Light long sleeve");
                o.push("Shorts (or tights)");
                o.push("1/4 length socks");
            }
            else if (temperature >= 38 && temperature < 44)
            {
                o.push("Hat");
                o.push("Thin gloves");
                o.push("Nike Combat Turtleneck");
                o.push("Light long sleeve");
                o.push("Tights");
                o.push("1/4 length socks");
            }
            else if (temperature >= 32 && temperature < 38)
            {
                o.push("Hat");
                o.push("Medium gloves");
                o.push("Nike Combat Turtleneck");
                o.push("Quarter-zip long sleeve");
                o.push("Tights");
                o.push("1/4 length socks");
            }
            else if (temperature >= 26 && temperature < 32)
            {
                o.push("hat");
                o.push("Medium gloves");
                o.push("Light jacket");
                o.push("Nike Combat Turtleneck");
                o.push("Quarter-zip long sleeve");
                o.push("Tights");
                o.push("1/4 length socks");

            }
            else if (temperature >= 0 && temperature < 26)
            {
                o.push("Hat");
                o.push("Mittens/gloves");
                o.push("Light jacket");
                o.push("Nike Combat Turtleneck");
                o.push("Quarter-zip long sleeve");
                o.push("Tights");
                o.push("Under-tights");
                o.push("1/4 length socks");
            }
            else {
                o.push("you're on your own today");
            }

            return o;
        };

        weatherCtrl.errors = null;
        $http({method: 'GET', url: weatherUrl})
            .success(function (data) {
                weatherCtrl.errors = null;
                weatherCtrl.weather = data;
                weatherCtrl.prettyWeather = weatherCtrl.makeWeatherPretty(weatherCtrl.weather);
                weatherCtrl.outfit = weatherCtrl.getOutfit(weatherCtrl.weather);
            })
            .catch(function(data) {
                weatherCtrl.errors = "Error retrieving data from yahoo weather API";
            });
    }]);
})();

<commit_msg>fix the weather<commit_after>(function () {
    var app = angular.module('weather-module', []);

    //injector passes these services at load time by dependency injection into the controller as arguments
    app.controller('WeatherController', ['$http', function ($http) {
        var weatherUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22brooklyn%2C%20ny%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

        var weatherCtrl = this;
        this.prettyWeather = [];
        this.weather = [];
        this.outfit = [];

        this.toCelsius = function (text) {
            var f = parseFloat(text);
            var c = ((f - 32) * 5 ) / 9;
            c = c.toFixed(0);
            return c.toString();
        };

        this.toInchesOfMercury = function (text) {
            var mb = parseFloat(text);
            var inches =  mb / 33.8637526;
            inches = inches.toFixed(2);
            return inches;
        };

        this.toKnots = function (mph) {
            var mph = parseFloat(mph);
            return (mph / 1.151).toFixed(0);
        }

        this.toKph = function (mph) {
            var mph = parseFloat(mph);
            return (mph * 1.609).toFixed(0);
        }

        this.makeWeatherPretty = function (data) {
            var x = data;
            var str = "
" + x.query.results.channel.item.title + "
";
            str += "
";
            str += "
	Imperial	Metric

";
            str += "
";
            str += "Temp	";
            str += x.query.results.channel.item.condition.temp + "°F";
            str += "	" + this.toCelsius(x.query.results.channel.item.condition.temp) + "°C";
            str += "	";
            str += "
";
            str += "
";
            str += "Pressure	";
            str += this.toInchesOfMercury(x.query.results.channel.atmosphere.pressure) + "\"";
            str += "	" + x.query.results.channel.atmosphere.pressure + " MB";
            str += "	";
            str += "
";
            str += "
";
            str += "Humidity	";
            str += x.query.results.channel.atmosphere.humidity + "%";
            str += "	";
            str += x.query.results.channel.atmosphere.humidity + "%";
            str += "	";
            str += "
";
            str += "
";
            str += "Wind	";
            str += this.toKnots(x.query.results.channel.wind.speed) + " knots";
            str += "	";
            str += this.toKph(x.query.results.channel.wind.speed) + " km/h";
            str += "
";
            str += "
";
            console.log(typeof x);

            return (str);
        };

        this.getOutfit = function (data) {
            var x = data;
            var o = [];
            var temperature = x.query.results.channel.item.condition.temp;

            if (temperature >= 100)
            {
                o.push("No shirt");
                o.push("Short shorts");
            }
            if (temperature >= 60 && temperature < 100)
            {
                o.push("Singlet/Sports Bra");
                o.push("Short Shorts");
                o.push("Ankle Socks");
            }
            else if (temperature >= 52 && temperature < 60)
            {
                o.push("Light long sleeve");
                o.push("Short Shorts");
                o.push("Ankle Socks");
            }
            else if (temperature >= 44 && temperature < 52)
            {
                o.push("Thin gloves");
                o.push("Nike Combat Turtleneck");
                o.push("Light long sleeve");
                o.push("Shorts (or tights)");
                o.push("Ankle or 1/4 length socks");
            }
            else if (temperature >= 38 && temperature < 44)
            {
                o.push("Hat");
                o.push("Thin gloves");
                o.push("Nike Combat Turtleneck");
                o.push("Light long sleeve");
                o.push("Tights");
                o.push("1/4 length socks");
            }
            else if (temperature >= 32 && temperature < 38)
            {
                o.push("Hat");
                o.push("Medium gloves");
                o.push("Nike Combat Turtleneck");
                o.push("Quarter-zip long sleeve");
                o.push("Tights");
                o.push("1/4 length socks");
            }
            else if (temperature >= 26 && temperature < 32)
            {
                o.push("hat");
                o.push("Medium gloves");
                o.push("Light jacket");
                o.push("Nike Combat Turtleneck");
                o.push("Quarter-zip long sleeve");
                o.push("Tights");
                o.push("1/4 length socks");

            }
            else if (temperature >= 0 && temperature < 26)
            {
                o.push("Hat");
                o.push("Mittens/gloves");
                o.push("Light jacket");
                o.push("Nike Combat Turtleneck");
                o.push("Quarter-zip long sleeve");
                o.push("Tights");
                o.push("Under-tights");
                o.push("1/4 length socks");
            }
            else {
                o.push("you're on your own today");
            }

            return o;
        };

        weatherCtrl.errors = null;
        $http({method: 'GET', url: weatherUrl})
            .success(function (data) {
                weatherCtrl.errors = null;
                weatherCtrl.weather = data;
                weatherCtrl.prettyWeather = weatherCtrl.makeWeatherPretty(weatherCtrl.weather);
                weatherCtrl.outfit = weatherCtrl.getOutfit(weatherCtrl.weather);
            })
            .catch(function(data) {
                weatherCtrl.errors = "Error retrieving data from yahoo weather API";
            });
    }]);
})();

<|endoftext|>


<commit_before>'use strict';

const test = require('tape');
const sinon = require('sinon');

const smalltalk = require('../lib/smalltalk.native');

global.window = {};

test('smalltalk.native: alert', (t) => {
    const alert = sinon.stub();
    global.alert = alert;

    smalltalk.alert('title', 'message');
    t.ok(alert.calledWith('message'), 'alert should have been called with message');
    t.end();
});

test('smalltalk.native: alert: result', (t) => {
    const alert = sinon.stub();
    global.alert = alert;

    smalltalk.alert('title', 'message').then(() => {
        t.pass('promise should have been resolved');
        t.end();
    }).catch((e) => {
        t.fail(`should not reject ${e.message}`);
        t.end();
    });
});

test('smalltalk.native: confirm', (t) => {
    const confirm = sinon.stub().returns(false);
    global.confirm = confirm;

    smalltalk.confirm('title', 'message')
        .catch(() => {
            t.ok(confirm.calledWith('message'), 'confirm should have been called with message');
            t.end();
        });
});

test('smalltalk.native: confirm: result: ok', (t) => {
    const confirm = sinon.stub().returns(true);
    global.confirm = confirm;

    smalltalk.confirm('title', 'message').then(() => {
        t.pass('should resolve');
        t.end();
    }).catch((e) => {
        t.notOk(e, 'should reject');
        t.end();
    });
});

test('smalltalk.native: confirm: result: cancel', (t) => {
    const confirm = sinon.stub().returns(false);
    global.confirm = confirm;

    smalltalk.confirm('title', 'message').then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch((e) => {
        t.notOk(e, 'should reject');
        t.end();
    });
});

test('smalltalk.native: confirm: options: cancel', (t) => {
    const confirm = sinon.stub().returns(false);
    global.confirm = confirm;

    const cancel = false;

    smalltalk.confirm('title', 'message', {cancel}).then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch(() => {
        t.fail('should not reject');
        t.end();
    });

    t.pass('should do nothing');

    t.end();
});

test('smalltalk.native: prompt', (t) => {
    const prompt = sinon.stub();
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value');
    t.ok(prompt.calledWith('message', 'value'), 'prompt should have been called with message');
    t.end();
});

test('smalltalk.native: prompt: result: ok', (t) => {
    const prompt = sinon.stub().returns('hello');
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value').then((value) => {
        t.equal(value, 'hello', 'should resolve value');
        t.end();
    }).catch((e) => {
        t.fail(`should not reject ${e.message}`);
        t.end();
    });
});

test('smalltalk.native: prompt: result: cancel', (t) => {
    const prompt = sinon.stub().returns(null);
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value').then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch((e) => {
        t.notOk(e, 'should reject');
        t.end();
    });
});

test('smalltalk.native: prompt: options: cancel', (t) => {
    const prompt = sinon.stub().returns();
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value', {
        cancel: false
    }).then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch((e) => {
        t.fail(`should not reject ${e.message}`);
        t.end();
    });

    t.pass('should do nothing');
    t.end();
});

<commit_msg>test(smalltalk.native) coverage<commit_after>'use strict';

const test = require('tape');
const sinon = require('sinon');

const smalltalk = require('../lib/smalltalk.native');

global.window = {};

test('smalltalk.native: Promise', (t) => {
    global.window.Promise = null;
    reload();
    t.pass('load with no Promise support');
    t.end();
});

test('smalltalk.native: alert', (t) => {
    const alert = sinon.stub();
    global.alert = alert;

    smalltalk.alert('title', 'message');
    t.ok(alert.calledWith('message'), 'alert should have been called with message');
    t.end();
});

test('smalltalk.native: alert: result', (t) => {
    const alert = sinon.stub();
    global.alert = alert;

    smalltalk.alert('title', 'message').then(() => {
        t.pass('promise should have been resolved');
        t.end();
    }).catch((e) => {
        t.fail(`should not reject ${e.message}`);
        t.end();
    });
});

test('smalltalk.native: confirm', (t) => {
    const confirm = sinon.stub().returns(false);
    global.confirm = confirm;

    smalltalk.confirm('title', 'message')
        .catch(() => {
            t.ok(confirm.calledWith('message'), 'confirm should have been called with message');
            t.end();
        });
});

test('smalltalk.native: confirm: result: ok', (t) => {
    const confirm = sinon.stub().returns(true);
    global.confirm = confirm;

    smalltalk.confirm('title', 'message').then(() => {
        t.pass('should resolve');
        t.end();
    }).catch((e) => {
        t.notOk(e, 'should reject');
        t.end();
    });
});

test('smalltalk.native: confirm: result: cancel', (t) => {
    const confirm = sinon.stub().returns(false);
    global.confirm = confirm;

    smalltalk.confirm('title', 'message').then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch((e) => {
        t.notOk(e, 'should reject');
        t.end();
    });
});

test('smalltalk.native: confirm: options: cancel', (t) => {
    const confirm = sinon.stub().returns(false);
    global.confirm = confirm;

    const cancel = false;

    smalltalk.confirm('title', 'message', {cancel}).then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch(() => {
        t.fail('should not reject');
        t.end();
    });

    t.pass('should do nothing');

    t.end();
});

test('smalltalk.native: prompt', (t) => {
    const prompt = sinon.stub();
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value');
    t.ok(prompt.calledWith('message', 'value'), 'prompt should have been called with message');
    t.end();
});

test('smalltalk.native: prompt: result: ok', (t) => {
    const prompt = sinon.stub().returns('hello');
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value').then((value) => {
        t.equal(value, 'hello', 'should resolve value');
        t.end();
    }).catch((e) => {
        t.fail(`should not reject ${e.message}`);
        t.end();
    });
});

test('smalltalk.native: prompt: result: cancel', (t) => {
    const prompt = sinon.stub().returns(null);
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value').then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch((e) => {
        t.notOk(e, 'should reject');
        t.end();
    });
});

test('smalltalk.native: prompt: options: cancel', (t) => {
    const prompt = sinon.stub().returns();
    global.prompt = prompt;

    smalltalk.prompt('title', 'message', 'value', {
        cancel: false
    }).then(() => {
        t.fail('should not resolve');
        t.end();
    }).catch((e) => {
        t.fail(`should not reject ${e.message}`);
        t.end();
    });

    t.pass('should do nothing');
    t.end();
});

function reload() {
    clean();
    return require('../lib/smalltalk.native');
}

function clean() {
    delete require.cache[require.resolve('../lib/smalltalk.native')];
}
<|endoftext|>


<commit_before>var yo = require('yo-yo')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var styleGuide = require('./style-guide')
var styles = styleGuide()

var css = csjs`
  .settingsTabView {
    padding: 2%;
    display: flex;
  }
  .info extends ${styles.infoTextBox} {
    margin-bottom: 2em;
  }
  .crow {
    margin-top: 1em;
    display: flex;
  }
  .select extends ${styles.dropdown} {
    float: left;
    max-width: 90%;
  }
  .button extends ${styles.button} {
    background-color: #C6CFF7;
    width: 100%;
    align-self: center;
    text-align: -webkit-center;
  }
  .col1 extends ${styles.titleL} {
    float: left;
    align-self: center;
  }
  .checkboxText {
    margin-left: 3px;
  }
  #warnCompilationSlow {
    color: #FF8B8B;
  }
}
`
module.exports = settingsTab

function settingsTab () {
  return yo`

Your current Solidity version is

        <select class="${css.select}" id="versionSelector"></select>

<input class="${css.col1}" id="editorWrap" type="checkbox">

        Text Wrap

<input class="${css.col1}" id="optimize" type="checkbox">

        Enable Optimization

<input class="${css.col1}" id="autoCompile" type="checkbox" checked>

        Auto Compile

Compile

  `
}
<commit_msg>Restyle compilation warning<commit_after>var yo = require('yo-yo')

// -------------- styling ----------------------
var csjs = require('csjs-inject')
var styleGuide = require('./style-guide')
var styles = styleGuide()

var css = csjs`
  .settingsTabView {
    padding: 2%;
    display: flex;
  }
  .info extends ${styles.infoTextBox} {
    margin-bottom: 2em;
  }
  .crow {
    margin-top: 1em;
    display: flex;
  }
  .select extends ${styles.dropdown} {
    float: left;
    max-width: 90%;
  }
  .button extends ${styles.button} {
    background-color: #C6CFF7;
    width: 100%;
    align-self: center;
    text-align: -webkit-center;
  }
  .col1 extends ${styles.titleL} {
    float: left;
    align-self: center;
  }
  .checkboxText {
    margin-left: 3px;
  }
  .compilationWarning extends ${styles.warningTextBox} {
    margin-top: 1em;
  }
}
`
module.exports = settingsTab

function settingsTab () {
  return yo`

Your current Solidity version is

        <select class="${css.select}" id="versionSelector"></select>

<input class="${css.col1}" id="editorWrap" type="checkbox">

        Text Wrap

<input class="${css.col1}" id="optimize" type="checkbox">

        Enable Optimization

<input class="${css.col1}" id="autoCompile" type="checkbox" checked>

        Auto Compile

Compile

  `
}
<|endoftext|>


<commit_before>define([
  'lib/underscore',
  'lib/jquery',
  'lib/backbone',
], function (_, $, Backbone) {
  var View = Backbone.View.extend({
    events: {
      'click th': 'thClick',
      'click td': 'tdClick',
      'change td>input.grid-text-input': 'editableStringChange',
    },

    initialize: function (options) {
      _.bindAll(this, 'update', 'thClick', 'tdClick', 'dataFor');

      this.options = _.extend(this.options, options);

      // TODO [akamel] rename? this isn't a backbone data obj?
      this.data = undefined;

      this.container = options.container;
      this.grid = options.grid;

      this.renderers = _.map(this.options.renderers, function (Renderer) {
        return new Renderer({ layout: this });
      }.bind(this));

      // TODO [akamel] make this conditional if these renderes are enabled
      this.onViewPortChange = this.onViewPortChange.bind(this);
      this.listenTo(this.container, 'scroll:container', this.onViewPortChange);
      this.listenTo(this.container, 'resize:container', this.onViewPortChange);
    },

    onViewPortChange: function () {
      this.scheduleDraw();
    },

    remove: function () {
      this.container.stopListening(this.container);
      Backbone.View.prototype.remove.apply(this, arguments);
    },

    thClick: function (e) {
      var arg = this.dataFor(e.currentTarget);

      if (arg.column) {
        this.trigger('click:header', e, arg);
      }
    },

    tdClick: function (e) {
      var arg = this.dataFor(e.currentTarget);

      if (arg.column) {
        this.trigger('click:cell', e, arg);
      }
    },

    editableStringChange: function (e) {
      var arg = this.dataFor(e.currentTarget);
      var colEditableStr = this.grid.projection.get('column.editable.string');

      if (arg.column) {
        if (_.isObject(colEditableStr) && !_.isUndefined(colEditableStr[arg.property])) {
          this.grid.projection.get('projection:column-editable-string').trigger('change:string', e, arg);
        } else {
          this.trigger('change:editable.string', e, arg);
        }
      }
    },

    dataFor: function (el) {
      if (!$.contains(this.el, el)) {
        return undefined;
      }

      var $el = $(el);
      // TODO [akamel] can we use target instead?
      var $tr = $el.closest('tr', this.el);
      var $closestTD = $el.closest('td', this.el);
      var $closestTH = $el.closest('th', this.el);
      var $td = _.size($closestTD) ? $closestTD : $closestTH;
      var virtualizer = this.getRenderer('virtualization');
      var i = $tr.index() + (virtualizer ? virtualizer.first : 0);
      var j = $td.index();
      // TODO [akamel] 1- check if $td is th; 2- throw if el is neither th or td as it is assumed in this function
      var isHeader = $td.closest('thead', this.el).length;
      var ret = { header: isHeader };

      // we are not in header
      if (isHeader) {
        if (i === 0) {
          ret.property = this.data.select[j];
        } else if (i === 1) {
          ret.property = this.data.subSelect[j];
        } else {
          ret.property = this.data.selectExpand[j];
        }
      } else {
        ret.model = this.data.value[i];
        ret.property = this.data.select[j];
      }

      ret.column = this.data.columns[ret.property];
      if (ret.property === this.grid.projection.get('column.checked')) {
        // TODO [akamel] this shouldn't be here
        var checkbox = $el.find('.column-checkbox');
        if (checkbox.length) {
          ret.checked = checkbox[0].checked;
        }
      }
      ret.grid = this.grid;

      return ret;
    },

    // TODO [akamel] [perf] 8.5%
    toHTML: function (value) {
      var data = _.defaults({ value: value }, this.data);

      _.each(data.columns, function (col) {
        if (_.isObject(col.$metadata)) {
          if (_.has(col.$metadata['attr.head'], 'class') && _.isArray(col.$metadata['attr.head'].class)) {
            col.$metadata['attr.head'].class = col.$metadata['attr.head'].class.join(' ');
          }

          if (_.has(col.$metadata['attr.body'], 'class') && _.isArray(col.$metadata['attr.body'].class)) {
            col.$metadata['attr.body'].class = col.$metadata['attr.body'].class.join(' ');
          }

         // TODO [akamel] merge attr that are on $metadata['attr']
        }
      });

      return this.options.template(data);
    },

    update: function (model) {
      _.each(this.renderers, function (renderer) {
        renderer.update && renderer.update();
      });

      // TODO [akamel] consider moving this to a projection
      var value = model.get('value');
      // TODO [akamel] is this overriding the values we got from the projection //see column extend below
      var columns = model.get('columns');
      var colOptions = this.options.columns || {};
      var orderby = {};

      _.each(this.grid.projection.get('orderby'), function (element, index) {
        var key = _.first(_.keys(element));
        orderby[key] = {
          dir: element[key],
          index: index,
        };
      });

      _.each(columns, function (col, property) {
      // TODO [akamel] consider filtering which props to copy/override
        var delta = {};
        if (orderby[property]) {
          delta.$orderby = orderby[property];
        }

        columns[property] = _.extend(col, colOptions[property], delta);
      });

      if (_.has(this.options.$metadata, 'class') && _.isArray(this.options.$metadata.class)) {
        this.options.$metadata.class = this.options.$metadata.class.join(' ');
      }

      var delta = {
        'value': value,
        'columns': columns,
        'columns.lookup': _.indexBy(columns, function (col) {
          return col.property;
        }),
        '$metadata': this.options.$metadata,
        'hideHeaders': this.options.hideHeaders,
      };

      this.data = _.defaults(delta, model.toJSON());

      this.draw({ canSkipDraw: false });
    },

    scheduleDraw: function () {
      if (!this.scheduledDraw) {
        this.scheduledDraw = true;

        window.requestAnimationFrame(function () {
          this.scheduledDraw = false;
          this.draw();
        }.bind(this));
      }
    },

    drawable: function () {
      return this.data;
    },

    getRenderer: function (name) {
      return _.find(this.renderers, function (r) {
        return r.name === name;
      });
    },

    draw: function (options) {
      if (!this.drawable()) {
        return;
      }

      this.trigger('render:beginning');

      var renderers = this.renderers;
      var i = 0;

      var middleware = function (data, cb) {
        var r = renderers[i++];
        if (r) {
          var clone = _.defaults({}, data, { css: {} });
          delete clone.canSkipDraw;

          r.draw(clone, _.once(function (err, res) {
            res.canSkipDraw = data.canSkipDraw === true && res.canSkipDraw === true;
            if (err) {
              cb(err);
            } else {
              middleware(res || clone, cb);
            }
          }));
        } else {
          cb(undefined, data);
        }
      };

      var canSkipDraw = _.has(options, 'canSkipDraw') ? options.canSkipDraw : true;

      // this is _not_ and _cannot_ be async
      middleware({ rows: this.data.value, canSkipDraw: canSkipDraw }, function (err, res) {
        res.css && this.$el.css(res.css);

        if (err) {
          throw err;
        }

        if (res.canSkipDraw !== true) {
          this.el.innerHTML = this.toHTML(res.rows);
        }
      }.bind(this));

      this.trigger('render:finished');
    },

    render: function () {
      this.grid.on('change:data', this.update);

      // this.grid.projection.data.on('change', this.update);
    },
  });

  View.partial = function (options) {
    return View.extend({ options: options });
  };

  return View;
});
<commit_msg>fix issue 33 for expanded group columns<commit_after>define([
  'lib/underscore',
  'lib/jquery',
  'lib/backbone',
], function (_, $, Backbone) {
  var View = Backbone.View.extend({
    events: {
      'click th': 'thClick',
      'click td': 'tdClick',
      'change td>input.grid-text-input': 'editableStringChange',
    },

    initialize: function (options) {
      _.bindAll(this, 'update', 'thClick', 'tdClick', 'dataFor');

      this.options = _.extend(this.options, options);

      // TODO [akamel] rename? this isn't a backbone data obj?
      this.data = undefined;

      this.container = options.container;
      this.grid = options.grid;

      this.renderers = _.map(this.options.renderers, function (Renderer) {
        return new Renderer({ layout: this });
      }.bind(this));

      // TODO [akamel] make this conditional if these renderes are enabled
      this.onViewPortChange = this.onViewPortChange.bind(this);
      this.listenTo(this.container, 'scroll:container', this.onViewPortChange);
      this.listenTo(this.container, 'resize:container', this.onViewPortChange);
    },

    onViewPortChange: function () {
      this.scheduleDraw();
    },

    remove: function () {
      this.container.stopListening(this.container);
      Backbone.View.prototype.remove.apply(this, arguments);
    },

    thClick: function (e) {
      var arg = this.dataFor(e.currentTarget);

      if (arg.column) {
        this.trigger('click:header', e, arg);
      }
    },

    tdClick: function (e) {
      var arg = this.dataFor(e.currentTarget);

      if (arg.column) {
        this.trigger('click:cell', e, arg);
      }
    },

    editableStringChange: function (e) {
      var arg = this.dataFor(e.currentTarget);
      var colEditableStr = this.grid.projection.get('column.editable.string');

      if (arg.column) {
        if (_.isObject(colEditableStr) && !_.isUndefined(colEditableStr[arg.property])) {
          this.grid.projection.get('projection:column-editable-string').trigger('change:string', e, arg);
        } else {
          this.trigger('change:editable.string', e, arg);
        }
      }
    },

    dataFor: function (el) {
      if (!$.contains(this.el, el)) {
        return undefined;
      }

      var $el = $(el);
      // TODO [akamel] can we use target instead?
      var $tr = $el.closest('tr', this.el);
      var $closestTD = $el.closest('td', this.el);
      var $closestTH = $el.closest('th', this.el);
      var $td = _.size($closestTD) ? $closestTD : $closestTH;
      var virtualizer = this.getRenderer('virtualization');
      var i = $tr.index() + (virtualizer ? virtualizer.first : 0);
      var j = $td.index();
      // TODO [akamel] 1- check if $td is th; 2- throw if el is neither th or td as it is assumed in this function
      var isHeader = $td.closest('thead', this.el).length;
      var ret = { header: isHeader };

      // we are not in header
      if (isHeader) {
        if (i === 0) {
          ret.property = this.data.select[j];
        } else if (i === 1) {
          ret.property = this.data.subSelect[j];
        } else {
          ret.property = this.data.selectExpand[j];
        }
      } else {
        ret.model = this.data.value[i];
        if (this.data.selectExpand) {
          ret.property = this.data.selectExpand[j];
        } else {
          ret.property = this.data.select[j];
        }
      }

      ret.column = this.data.columns[ret.property];
      if (ret.property === this.grid.projection.get('column.checked')) {
        // TODO [akamel] this shouldn't be here
        var checkbox = $el.find('.column-checkbox');
        if (checkbox.length) {
          ret.checked = checkbox[0].checked;
        }
      }
      ret.grid = this.grid;

      return ret;
    },

    // TODO [akamel] [perf] 8.5%
    toHTML: function (value) {
      var data = _.defaults({ value: value }, this.data);

      _.each(data.columns, function (col) {
        if (_.isObject(col.$metadata)) {
          if (_.has(col.$metadata['attr.head'], 'class') && _.isArray(col.$metadata['attr.head'].class)) {
            col.$metadata['attr.head'].class = col.$metadata['attr.head'].class.join(' ');
          }

          if (_.has(col.$metadata['attr.body'], 'class') && _.isArray(col.$metadata['attr.body'].class)) {
            col.$metadata['attr.body'].class = col.$metadata['attr.body'].class.join(' ');
          }

         // TODO [akamel] merge attr that are on $metadata['attr']
        }
      });

      return this.options.template(data);
    },

    update: function (model) {
      _.each(this.renderers, function (renderer) {
        renderer.update && renderer.update();
      });

      // TODO [akamel] consider moving this to a projection
      var value = model.get('value');
      // TODO [akamel] is this overriding the values we got from the projection //see column extend below
      var columns = model.get('columns');
      var colOptions = this.options.columns || {};
      var orderby = {};

      _.each(this.grid.projection.get('orderby'), function (element, index) {
        var key = _.first(_.keys(element));
        orderby[key] = {
          dir: element[key],
          index: index,
        };
      });

      _.each(columns, function (col, property) {
      // TODO [akamel] consider filtering which props to copy/override
        var delta = {};
        if (orderby[property]) {
          delta.$orderby = orderby[property];
        }

        columns[property] = _.extend(col, colOptions[property], delta);
      });

      if (_.has(this.options.$metadata, 'class') && _.isArray(this.options.$metadata.class)) {
        this.options.$metadata.class = this.options.$metadata.class.join(' ');
      }

      var delta = {
        'value': value,
        'columns': columns,
        'columns.lookup': _.indexBy(columns, function (col) {
          return col.property;
        }),
        '$metadata': this.options.$metadata,
        'hideHeaders': this.options.hideHeaders,
      };

      this.data = _.defaults(delta, model.toJSON());

      this.draw({ canSkipDraw: false });
    },

    scheduleDraw: function () {
      if (!this.scheduledDraw) {
        this.scheduledDraw = true;

        window.requestAnimationFrame(function () {
          this.scheduledDraw = false;
          this.draw();
        }.bind(this));
      }
    },

    drawable: function () {
      return this.data;
    },

    getRenderer: function (name) {
      return _.find(this.renderers, function (r) {
        return r.name === name;
      });
    },

    draw: function (options) {
      if (!this.drawable()) {
        return;
      }

      this.trigger('render:beginning');

      var renderers = this.renderers;
      var i = 0;

      var middleware = function (data, cb) {
        var r = renderers[i++];
        if (r) {
          var clone = _.defaults({}, data, { css: {} });
          delete clone.canSkipDraw;

          r.draw(clone, _.once(function (err, res) {
            res.canSkipDraw = data.canSkipDraw === true && res.canSkipDraw === true;
            if (err) {
              cb(err);
            } else {
              middleware(res || clone, cb);
            }
          }));
        } else {
          cb(undefined, data);
        }
      };

      var canSkipDraw = _.has(options, 'canSkipDraw') ? options.canSkipDraw : true;

      // this is _not_ and _cannot_ be async
      middleware({ rows: this.data.value, canSkipDraw: canSkipDraw }, function (err, res) {
        res.css && this.$el.css(res.css);

        if (err) {
          throw err;
        }

        if (res.canSkipDraw !== true) {
          this.el.innerHTML = this.toHTML(res.rows);
        }
      }.bind(this));

      this.trigger('render:finished');
    },

    render: function () {
      this.grid.on('change:data', this.update);

      // this.grid.projection.data.on('change', this.update);
    },
  });

  View.partial = function (options) {
    return View.extend({ options: options });
  };

  return View;
});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var co = require('co');
var lookup = require('../');
var monogram = require('monogram');

describe('lookUp()', function() {
  it('works', function(done) {
    co(function*() {
      let db = yield monogram('mongodb://localhost:27017');
      let schema = new monogram.Schema({});

      lookup(schema);

      let Band = db.model({ schema: schema, collection: 'band' });
      let Person = db.model('people');

      yield Band.deleteMany({});
      yield Person.deleteMany({});

      let gnr = new Band({ _id: 1, name: `Guns N' Roses` });
      yield gnr.$save();

      yield [
        new Person({
          name: 'Axl Rose',
          role: 'Lead Singer',
          band: gnr._id
        }).$save(),
        new Person({
          name: 'Slash',
          role: 'Guitarist',
          band: gnr._id
        }).$save()
      ];

      let populated = yield Band.findOne({ _id: gnr._id }).
        lookUp(Person, 'members', { band: '$_id' });

      assert.equal(populated.members.length, 2);
      assert.equal(populated.members[0].name, 'Axl Rose');
      assert.equal(populated.members[1].name, 'Slash');

      done();
    }).catch(function(error) {
      done(error);
    });
  });
});
<commit_msg>use .create()<commit_after>'use strict';

var assert = require('assert');
var co = require('co');
var lookup = require('../');
var monogram = require('monogram');

describe('lookUp()', function() {
  it('works', function(done) {
    co(function*() {
      let db = yield monogram('mongodb://localhost:27017');
      let schema = new monogram.Schema({});

      lookup(schema);

      let Band = db.model({ schema: schema, collection: 'band' });
      let Person = db.model('people');

      yield Band.deleteMany({});
      yield Person.deleteMany({});

      let gnr = new Band({ _id: 1, name: `Guns N' Roses` });
      yield gnr.$save();

      yield Person.create([
        {
          name: 'Axl Rose',
          role: 'Lead Singer',
          band: gnr._id
        },
        {
          name: 'Slash',
          role: 'Guitarist',
          band: gnr._id
        }
      ]);

      let populated = yield Band.findOne({ _id: gnr._id }).
        lookUp(Person, 'members', { band: '$_id' });

      assert.equal(populated.members.length, 2);
      assert.equal(populated.members[0].name, 'Axl Rose');
      assert.equal(populated.members[1].name, 'Slash');

      done();
    }).catch(function(error) {
      done(error);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright 2006 The eFaps Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:          tmo
 * Revision:        $Rev:347 $
 * Last Changed:    $Date:2006-09-06 00:08:24 +0200 (Mi, 06 Sep 2006) $
 * Last Changed By: $Author:tmo $
 */

with (FORM)  {
  with (addField("type"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Type");
    addProperty("Searchable",             "false");
    addProperty("ShowTypeIcon",           "true");
  }
  with (addField("name"))  {
    addProperty("Columns",                "20");
    addProperty("Creatable",              "true");
    addProperty("Editable",               "true");
    addProperty("Expression",             "Name");
    addProperty("Required",               "true");
    addProperty("Searchable",             "true");
  }
  with (addField("uuid"))  {
    addProperty("Columns",                "20");
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "UUID");
    addProperty("Searchable",             "true");
  }
  with (addField("revision"))  {
    addProperty("Columns",                "20");
    addProperty("Creatable",              "true");
    addProperty("Editable",               "true");
    addProperty("Expression",             "Revision");
    addProperty("Searchable",             "true");
  }
  with (addField("createGroup"))  {
    addProperty("Creatable",              "false");
    addProperty("GroupCount",             "2");
  }
  with (addField("creator"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Creator");
    addProperty("Searchable",             "true");
  }
  with (addField("created"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Created");
    addProperty("Searchable",             "true");
  }
  with (addField("modifyGroup"))  {
    addProperty("Creatable",              "false");
    addProperty("GroupCount",             "2");
  }
  with (addField("modifier"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Modifier");
    addProperty("Searchable",             "true");
  }
  with (addField("modified"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Modified");
    addProperty("Searchable",             "true");
  }
}
<commit_msg>- uuid needs no column size<commit_after>/*
 * Copyright 2006 The eFaps Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:          tmo
 * Revision:        $Rev:347 $
 * Last Changed:    $Date:2006-09-06 00:08:24 +0200 (Mi, 06 Sep 2006) $
 * Last Changed By: $Author:tmo $
 */

with (FORM)  {
  with (addField("type"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Type");
    addProperty("Searchable",             "false");
    addProperty("ShowTypeIcon",           "true");
  }
  with (addField("name"))  {
    addProperty("Columns",                "20");
    addProperty("Creatable",              "true");
    addProperty("Editable",               "true");
    addProperty("Expression",             "Name");
    addProperty("Required",               "true");
    addProperty("Searchable",             "true");
  }
  with (addField("uuid"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "UUID");
    addProperty("Searchable",             "true");
  }
  with (addField("revision"))  {
    addProperty("Columns",                "20");
    addProperty("Creatable",              "true");
    addProperty("Editable",               "true");
    addProperty("Expression",             "Revision");
    addProperty("Searchable",             "true");
  }
  with (addField("createGroup"))  {
    addProperty("Creatable",              "false");
    addProperty("GroupCount",             "2");
  }
  with (addField("creator"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Creator");
    addProperty("Searchable",             "true");
  }
  with (addField("created"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Created");
    addProperty("Searchable",             "true");
  }
  with (addField("modifyGroup"))  {
    addProperty("Creatable",              "false");
    addProperty("GroupCount",             "2");
  }
  with (addField("modifier"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Modifier");
    addProperty("Searchable",             "true");
  }
  with (addField("modified"))  {
    addProperty("Creatable",              "false");
    addProperty("Editable",               "false");
    addProperty("Expression",             "Modified");
    addProperty("Searchable",             "true");
  }
}
<|endoftext|>


<commit_before>(function () {
  var _ = require('underscore');

  function sanitize_input(input) {
    // http://www.postgresql.org/docs/9.0/static/sql-syntax-lexical.html [4.1.2.1-4.1.2.2]
    // single quotes (') must be replaced with double single quotes ('')
    input = input.replace(/'/g, '\'\'');
    // backslashes (\) must be replaced with double backslashes (\\)
    input = input.replace(/\\/g, '\\\\');
    // double quotes (") must be replaced with escaped quotes (\\")
    input = input.replace(/"/g, '\\"');
    return input;
  }

  function to_string(input, sanitize) {
    switch(typeof input) {
      case 'boolean':
      case 'number':
      case 'object':
        return String(input);
      case 'string':
        return sanitize ? sanitize_input(input) : input;
      default:
        return '';
    }
  }

  module.exports = function (options) {
    options = _.defaults({}, options, { sanitize: false });

    return {
      stringify: function (data, callback) {
        var hstore = Object.keys(data).map(function (key) {
          if (data[key] === null) {
            return '"'+to_string(key, options.sanitize)+'"=>NULL';
          } else {
            return '"'+to_string(key, options.sanitize)+'"=>"'+to_string(data[key], options.sanitize)+'"';
          }
        });
        var joined = hstore.join();
        if (!callback || callback === null) return joined;
        callback(joined);
      },

      parse: function(string, callback) {
        var result = {},
        //using [\s\S] to match any character, including line feed and carriage return,
            r = /(["])(?:\\\1|\\\\|[\s\S])*?\1|NULL/g,
            matches = string.match(r),
            i,
            l,
            clean = function (value) {
                // Remove leading double quotes
                value = value.replace(/^\"|\"$/g, "");
                // Unescape quotes
                value = value.replace(/\\"/g, "\"");
                //Unescape backslashes
                value = value.replace(/\\\\/g,"\\");
                //Unescape single quotes
                value = value.replace(/''/g,"'");

                return value;
            };

        if(matches) {
          for (i = 0, l = matches.length; i < l; i+= 2) {
            var key = clean(matches[i]);
            var value = matches[i + 1];
            result[key] = value=="NULL"?null:clean(value);
          }
        }
        if (!callback || callback === null) return result;
        callback(result);
      }
    };
  };
})();
<commit_msg>Null checking to prevent crash<commit_after>(function () {
  var _ = require('underscore');

  function sanitize_input(input) {
    // http://www.postgresql.org/docs/9.0/static/sql-syntax-lexical.html [4.1.2.1-4.1.2.2]
    // single quotes (') must be replaced with double single quotes ('')
    input = input.replace(/'/g, '\'\'');
    // backslashes (\) must be replaced with double backslashes (\\)
    input = input.replace(/\\/g, '\\\\');
    // double quotes (") must be replaced with escaped quotes (\\")
    input = input.replace(/"/g, '\\"');
    return input;
  }

  function to_string(input, sanitize) {
    switch(typeof input) {
      case 'boolean':
      case 'number':
      case 'object':
        return String(input);
      case 'string':
        return sanitize ? sanitize_input(input) : input;
      default:
        return '';
    }
  }

  module.exports = function (options) {
    options = _.defaults({}, options, { sanitize: false });

    return {
      stringify: function (data, callback) {
        var hstore = Object.keys(data).map(function (key) {
          if (data[key] === null) {
            return '"'+to_string(key, options.sanitize)+'"=>NULL';
          } else {
            return '"'+to_string(key, options.sanitize)+'"=>"'+to_string(data[key], options.sanitize)+'"';
          }
        });
        var joined = hstore.join();
        if (!callback || callback === null) return joined;
        callback(joined);
      },

      parse: function(string, callback) {
        var result = {},
        //using [\s\S] to match any character, including line feed and carriage return,
            r = /(["])(?:\\\1|\\\\|[\s\S])*?\1|NULL/g,
            matches = string.match(r),
            i,
            l,
            clean = function (value) {
                // Remove leading double quotes
                value = value.replace(/^\"|\"$/g, "");
                // Unescape quotes
                value = value.replace(/\\"/g, "\"");
                //Unescape backslashes
                value = value.replace(/\\\\/g,"\\");
                //Unescape single quotes
                value = value.replace(/''/g,"'");

                return value;
            };

        if(matches) {
          for (i = 0, l = matches.length; i < l; i+= 2) {
            if (matches[i] && matches[i + 1]) {
              var key = clean(matches[i]);
              var value = matches[i + 1];
              result[key] = value=="NULL"?null:clean(value);
            }
          }
        }
        if (!callback || callback === null) return result;
        callback(result);
      }
    };
  };
})();
<|endoftext|>


<commit_before>var d = { x: 1, y: 0};			// player position
var e = [ 						// enemies
		{ x: 51, y: 23 },
		{ x: 121, y: 23 },
		{ x: 141, y: 12 }
	];
var G = { x: 239, y: 5 };		// Goal
var P = [						// platforms
	[ 0 ], // 0
	[ 0 ], // 1
	[ 0, 1, 2, 3, 4, 5 ], // 2
	[ 0 ], // 3
	[ 0, 6, 7, 8, 9, 10, 11, 241 ], // 4
	[ 0, 241 ], // 5
	[ 0, 241 ], // 6
	[ 0, 14, 15, 16, 17, 18, 241 ], // 7
	[ 0, 241 ], // 8
	[ 0, 241 ], // 9
	[ 0, 25, 26, 27, 105, 106, 107, 108, 109, 110, 120, 121, 122, 123, 124, 125, 241 ], // 10
	[ 0, 241 ], // 11
	[ 0, 140, 160, 241 ], // 12
	[ 0, 99, 100, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 241 ], // 13
	[ 0, 99, 241 ], // 14
	[ 0, 99, 235, 236, 237, 238, 239, 240, 241 ], // 15
	[ 0, 99 ], // 16
	[ 0, 99, 225, 226, 227, 228, 229, 230 ], // 17
	[ 0, 99 ], // 18
	[ 0, 99, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 215, 216, 217, 218, 219, 220 ], // 19
	[ 0, 99 ], // 20
	[ 0, 99, 205, 206, 207, 208, 209, 210 ], // 21
	[ 0, 99 ], // 22
	[ 0, 28, 29, 30, 50, 99, 120, 170 ], // 23
	[ ], // 24
	[ ] // 25
];

// floor
for(var i=0; i <= 350; i++) {
	if(i > 39 && i < 50 || i > 100 && i < 120 || i > 140 && i < 155 || i > 170 && i < 190 || i > 200) continue; // holes

	P[24][i] = i;
}<commit_msg>add enemies<commit_after>var d = { x: 1, y: 0};			// player position
var e = [ 						// enemies
		{ x: 51, y: 23 },
		{ x: 91, y: 19 },
		{ x: 31, y: 23 },
		{ x: 121, y: 23 },
		{ x: 141, y: 12 }
	];
var G = { x: 240, y: 5 };		// Goal
var P = [						// platforms
	[ 0 ], // 0
	[ 0 ], // 1
	[ 0, 1, 2, 3, 4, 5 ], // 2
	[ 0 ], // 3
	[ 0, 6, 7, 8, 9, 10, 11, 241 ], // 4
	[ 0, 241 ], // 5
	[ 0, 241 ], // 6
	[ 0, 14, 15, 16, 17, 18, 241 ], // 7
	[ 0, 241 ], // 8
	[ 0, 241 ], // 9
	[ 0, 25, 26, 27, 105, 106, 107, 108, 109, 110, 120, 121, 122, 123, 124, 125, 241 ], // 10
	[ 0, 241 ], // 11
	[ 0, 140, 160, 241 ], // 12
	[ 0, 99, 100, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 241 ], // 13
	[ 0, 99, 241 ], // 14
	[ 0, 99, 235, 236, 237, 238, 239, 240, 241 ], // 15
	[ 0, 99 ], // 16
	[ 0, 99, 225, 226, 227, 228, 229, 230 ], // 17
	[ 0, 99 ], // 18
	[ 0, 99, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 215, 216, 217, 218, 219, 220 ], // 19
	[ 0, 99 ], // 20
	[ 0, 99, 205, 206, 207, 208, 209, 210 ], // 21
	[ 0, 99 ], // 22
	[ 0, 28, 29, 30, 50, 99, 120, 170 ], // 23
	[ ], // 24
	[ ] // 25
];

// floor
for(var i=0; i <= 350; i++) {
	if(i > 39 && i < 50 || i > 100 && i < 120 || i > 140 && i < 155 || i > 170 && i < 190 || i > 200) continue; // holes

	P[24][i] = i;
}<|endoftext|>


<commit_before><commit_msg>Upgrade yarn in staging to 1.21.1<commit_after><|endoftext|>


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

	$.getJSON('/backend/complex/' + complex['complex_accession'], function(data) {

		document.getElementById("summary_paragraph").innerHTML = data['description'] + "

" + data['properties']

	  	var complex_table = create_complex_table(data);

		if(data != null && data["graph"]["nodes"].length > 1) {

		    var graph = create_cytoscape_vis("cy", layout, graph_style, data["graph"], null, true, "complex_diagram");
		    create_cy_download_button(graph, "cy_download", complex['complex_accession'] + '_subunit_graph')

		}
		else {
                    hide_section("diagram");
                }

		if (data != null && data["network_graph"]["nodes"].length > 1) {

		    var graph2 = create_cytoscape_vis("cy2", layout, graph_style, data["network_graph"], null, true, "complex_network");
		    var = create_slider("slider", graph2, data["network_graph"]["min_evidence_cutoff"], data["network_graph"]["max_evidence_cutoff"], function slider_filter(new_cutoff) {return "node, edge[evidence >= " + new_cutoff + "]";});
		    create_cy_download_button(graph2, "cy2_download", complex['complex_accession'] + '_complex_network_graph')

		    if (true) {
			create_discrete_filter_bar("union_radio", graph, all_filter, data["network_graph"]["max_evidence_cutoff"]);
			create_discrete_filter_bar("subunit_radio", graph, subunit_filter, data["network_graph"]["max_subunit_cutoff"]);
			create_discrete_filter_bar("go_radio", graph, go_filter, , data["network_graph"]["max_go_cutoff"]);
			$("#discrete_filter").show();
		    }
		    else {
			$("#discrete_filter").hide();
		    }
		}
		else {
		    hide_section("network");
		}
	});

});

function create_complex_table(data) {
    var evidence = data['subunit'];
    var datatable = [];
    var subunits = {};
    for (var i = 0; i < evidence.length; i++) {
	datatable.push(complex_subunit_data_to_table(evidence[i]));
	subunits[evidence[i]["display_name"]] = true;
    }

    set_up_header(
		  "complex_table",
		  datatable.length,
		  "entry",
		  "entries",
		  Object.keys(subunits).length,
		  "subunit",
		  "subunits"
		  );

    var options = {};
    options["bPaginate"] = false;
    options["bDestroy"] = true;
    options["aoColumns"] = [
			  null,
			  null,
			  null
			  ];
  options["aaData"] = datatable;
  options["oLanguage"] = {
      sEmptyTable: "No subunits for this complex???."
  };

  return create_table("complex_table", options);

}

function create_discrete_filter_bar(radio_id, graph, target_filter) {
    var radio = $("#" + radio_id);
    radio.click(function() {
	    graph.filters['discrete'] = target_filter();
	    graph.applyFilters();
	});
}

function all_filter() {
    return "node, edge";
}

function subunit_filter() {
    return "node, edge[class_type = 'complex_gene']";
}

function go_filter() {
    return "node, edge[class_type = 'complex_go']";
}

var graph_style = cytoscape.stylesheet()
    .selector('node')
    .css({
	    'content': 'data(name)',
	    'font-family': 'helvetica',
	    'font-size': 14,
	    'text-outline-width': 3,
	    'text-outline-color': '#888',
	    'text-valign': 'center',
	    'color': '#fff',
	    'width': 30,
	    'height': 30,
	    'border-color': '#fff'
        })
    .selector("node[type='smallmolecule']")
    .css({
	    'background-color': "#0D85F3",
	})
    .selector("node[type='subcomplex']")
    .css({
	    'background-color': "#F3750D",
        })
    .selector("node[type='othersubunit']")
    .css({
	    'background-color': "#35F30D",
        })

    .selector("node[type='Gene']")
    .css({
	    'background-color': "#FF8933",
        })
    .selector("node[type='Go']")
    .css({
	    'background-color': "#A133FF",
        })
    .selector("node[type='Complex']")
    .css({
            'background-color': "#86908C",
        })
    .selector("node[type='Current_complex']")
    .css({
	    'background-color': "#0E9F36",
        })
    .selector('edge')
    .css({
	    'width': 2,
	    'line-color': '#848484',

        })
    .selector("node[sub_type='FOCUS']")
    .css({
	    'background-color': "#0E9F36",
	    'text-outline-color': '#fff',
	    'color': '#888'
        })
    .selector("edge[class_type = 'complex_go']")
    .css({
            'line-color': "#7233FF"
        })
    .selector("edge[class_type = 'complex_gene']")
    .css({
            'line-color': "#FF8933"
        })
    .selector("edge[class_type = 'complex']")
    .css({
	    'line-color': "#74FF33"
        });

var layout = {
    "name": "arbor",
    "liveUpdate": true,
    "ungrabifyWhileSimulating": true,
    "nodeMass":function(data) {
	if(data.sub_type == 'FOCUS') {
	    return 10;
	}
	else {
	    return 1;
	}
    }
};
<commit_msg>testing<commit_after>
$(document).ready(function() {

	$.getJSON('/backend/complex/' + complex['complex_accession'], function(data) {

	  	var complex_table = create_complex_table(data);

		if(data != null && data["graph"]["nodes"].length > 1) {

		    var graph = create_cytoscape_vis("cy", layout, graph_style, data["graph"], null, true, "complex_diagram");
		    create_cy_download_button(graph, "cy_download", complex['complex_accession'] + '_subunit_graph')

		}
		else {
                    hide_section("diagram");
                }

		if (data != null && data["network_graph"]["nodes"].length > 1) {

		    var graph2 = create_cytoscape_vis("cy2", layout, graph_style, data["network_graph"], null, true, "complex_network");
		    create_cy_download_button(graph2, "cy2_download", complex['complex_accession'] + '_complex_network_graph')

		    if (true) {
			create_discrete_filter_bar("union_radio", graph, all_filter);
			create_discrete_filter_bar("subunit_radio", graph, subunit_filter);
			create_discrete_filter_bar("go_radio", graph, go_filter);
			$("#discrete_filter").show();
		    }
		    else {
			$("#discrete_filter").hide();
		    }
		}
		else {
		    hide_section("network");
		}
	});

});

function create_complex_table(data) {
    var evidence = data['subunit'];
    var datatable = [];
    var subunits = {};
    for (var i = 0; i < evidence.length; i++) {
	datatable.push(complex_subunit_data_to_table(evidence[i]));
	subunits[evidence[i]["display_name"]] = true;
    }

    set_up_header(
		  "complex_table",
		  datatable.length,
		  "entry",
		  "entries",
		  Object.keys(subunits).length,
		  "subunit",
		  "subunits"
		  );

    var options = {};
    options["bPaginate"] = false;
    options["bDestroy"] = true;
    options["aoColumns"] = [
			  null,
			  null,
			  null
			  ];
  options["aaData"] = datatable;
  options["oLanguage"] = {
      sEmptyTable: "No subunits for this complex???."
  };

  return create_table("complex_table", options);

}

function create_discrete_filter_bar(radio_id, graph, target_filter) {
    var radio = $("#" + radio_id);
    radio.click(function() {
	    graph.filters['discrete'] = target_filter();
	    graph.applyFilters();
	});
}

function all_filter() {
    return "node, edge";
}

function subunit_filter() {
    return "node, edge[class_type = 'complex_gene']";
}

function go_filter() {
    return "node, edge[class_type = 'complex_go']";
}

var graph_style = cytoscape.stylesheet()
    .selector('node')
    .css({
	    'content': 'data(name)',
	    'font-family': 'helvetica',
	    'font-size': 14,
	    'text-outline-width': 3,
	    'text-outline-color': '#888',
	    'text-valign': 'center',
	    'color': '#fff',
	    'width': 30,
	    'height': 30,
	    'border-color': '#fff'
        })
    .selector("node[type='smallmolecule']")
    .css({
	    'background-color': "#0D85F3",
	})
    .selector("node[type='subcomplex']")
    .css({
	    'background-color': "#F3750D",
        })
    .selector("node[type='othersubunit']")
    .css({
	    'background-color': "#35F30D",
        })

    .selector("node[type='Gene']")
    .css({
	    'background-color': "#FF8933",
        })
    .selector("node[type='Go']")
    .css({
	    'background-color': "#A133FF",
        })
    .selector("node[type='Complex']")
    .css({
            'background-color': "#86908C",
        })
    .selector("node[type='Current_complex']")
    .css({
	    'background-color': "#0E9F36",
        })
    .selector('edge')
    .css({
	    'width': 2,
	    'target-arrow-shape': 'triangle',
	    'line-color': '#848484',
	    'target-arrow-color': '#848484'
        })
    .selector("node[sub_type='FOCUS']")
    .css({
	    'background-color': "#0E9F36",
	    'text-outline-color': '#fff',
	    'color': '#888'
        })
    .selector("edge[class_type = 'complex_go']")
    .css({
            'line-color': "#7233FF"
        })
    .selector("edge[class_type = 'complex_gene']")
    .css({
            'line-color': "#FF8933"
        })
    .selector("edge[class_type = 'complex']")
    .css({
	    'line-color': "#74FF33"
        });

var layout = {
    "name": "arbor",
    "liveUpdate": true,
    "ungrabifyWhileSimulating": true,
    "nodeMass":function(data) {
	if(data.sub_type == 'FOCUS') {
	    return 10;
	}
	else {
	    return 1;
	}
    }
};
<|endoftext|>


<commit_before>$(function () {
    $(".ajaxed_pager").on( "click", ".pagination a, .sorter a", function (e) {
        var $a = $(this),
            $container = $a.closest(".ajaxed_pager"),
            url = $a.attr('href');
        $a.addClass("ui-icon-spinner");
        $container.load(url + ' #' + $container.attr('id') + " > *");
        return false;
    });
    $(".has-searcher").each( function () {
        var $grid = $(this),
            grid_id = this.id,
            input_id = "#" + $grid.data("searcher"),
            live = $grid.data("live-search"),
            events = (live ? "keyup search change" : "search change"),
            timer = null;
        $grid.parent().on(events, input_id, function (e) {
            var minLength = $(input_id).data("min-length") || 3,
                length = this.value.length,
                relevant = e.type == 'search' || e.type == 'change' ||
                            length >= minLength || length == 0,
                base_url = $grid.data("current"),
                params = {};
            if (relevant) {
                clearTimeout(timer);
                timer = setTimeout(function () {
                    var value = $(input_id).val()
                        url = base_url + "?";
                    params[grid_id + "_q"] = value;
                    url += $.param(params);
                    if ($grid.hasClass("ajaxed_pager")) {
                        $grid.load(url + ' #' + grid_id + ' > *', function () {
                            if (e.type == 'keyup') {
                                $(input_id).focus()[0].setSelectionRange(value.length, value.length);
                            }
                        });
                    } else {
                        window.location = url;
                    }
                }, 250);
            }
        });
    });
    $(".has-listeners").each( function () {
        var $grid = $(this),
            listeners = $grid.data("listeners"),
            grid_id = this.id
            base_url = $grid.data("current");
        for (var k in listeners) {
            $("#" + k).on("change", {"field": listeners[k]}, function (e) {
                var params = {},
                    key = /* grid_id + "_" + */ e.data.field,
                    value = this.value,
                    url = base_url + "?";
                params[key] = value;
                url += $.param(params);
                if ($grid.hasClass("ajaxed_pager")) {
                    $grid.load(url + ' #' + grid_id + " > *");
                } else {
                    window.location = url;
                }
            });
        }
    });
});
<commit_msg>Make search delay more intelligent<commit_after>$(function () {
    $(".ajaxed_pager").on( "click", ".pagination a, .sorter a", function (e) {
        var $a = $(this),
            $container = $a.closest(".ajaxed_pager"),
            url = $a.attr('href');
        $a.addClass("ui-icon-spinner");
        $container.load(url + ' #' + $container.attr('id') + " > *");
        return false;
    });
    $(".has-searcher").each( function () {
        var $grid = $(this),
            grid_id = this.id,
            input_id = "#" + $grid.data("searcher"),
            live = $grid.data("live-search"),
            events = (live ? "keyup search change" : "search change"),
            timer = null;
        $grid.parent().on(events, input_id, function (e) {
            var minLength = $(input_id).data("min-length") || 3,
                length = this.value.length,
                is_manual = (e.type == 'search' || e.type == 'change'),
                relevant =  is_manual || length >= minLength || length == 0,
                base_url = $grid.data("current"),
                params = {},
                //40 wpm typists == 280ms
                //90 wpm typists == 120ms
                delay = is_manual ? 0 : 250;
            if (relevant) {
                clearTimeout(timer);
                timer = setTimeout(function () {
                    var value = $(input_id).val()
                        url = base_url + "?";
                    params[grid_id + "_q"] = value;
                    url += $.param(params);
                    if ($grid.hasClass("ajaxed_pager")) {
                        $grid.load(url + ' #' + grid_id + ' > *', function () {
                            if (e.type == 'keyup') {
                                $(input_id).focus()[0].setSelectionRange(value.length, value.length);
                            }
                        });
                    } else {
                        window.location = url;
                    }
                }, delay);
            }
        });
    });
    $(".has-listeners").each( function () {
        var $grid = $(this),
            listeners = $grid.data("listeners"),
            grid_id = this.id
            base_url = $grid.data("current");
        for (var k in listeners) {
            $("#" + k).on("change", {"field": listeners[k]}, function (e) {
                var params = {},
                    key = /* grid_id + "_" + */ e.data.field,
                    value = this.value,
                    url = base_url + "?";
                params[key] = value;
                url += $.param(params);
                if ($grid.hasClass("ajaxed_pager")) {
                    $grid.load(url + ' #' + grid_id + " > *");
                } else {
                    window.location = url;
                }
            });
        }
    });
});
<|endoftext|>


<commit_before>import { NativeEventEmitter, NativeModules, View } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const { TrackPlayer } = NativeModules;
const eventEmitter = new NativeEventEmitter(TrackPlayer);

function resolveAsset(uri) {
    if(!uri) return undefined;
    return resolveAssetSource(uri);
}

function resolveUrl(url) {
    if(!url) return undefined;
    return resolveAssetSource(url) || url;
}

function updateOptions(data) {
    // Resolve the asset for each icon
    data.icon = resolveAsset(data.icon);
    data.playIcon = resolveAsset(data.playIcon);
    data.pauseIcon = resolveAsset(data.pauseIcon);
    data.stopIcon = resolveAsset(data.stopIcon);
    data.previousIcon = resolveAsset(data.previousIcon);
    data.nextIcon = resolveAsset(data.nextIcon);

    return TrackPlayer.updateOptions(data);
}

function add(tracks, insertBeforeId) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    // Resolve the URL for each track
    for(let i = 0; i < tracks.length; i++) {
        tracks[i].url = resolveUrl(tracks[i].url);
        tracks[i].artwork = resolveUrl(tracks[i].artwork);
    }

    return TrackPlayer.add(tracks, insertBeforeId);
}

function remove(tracks) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    return TrackPlayer.remove(tracks);
}

// We'll declare each one of the constants and functions manually so IDEs can show a list of them
// We should also add documentation here, but I'll leave this task to another day

// States
module.exports.STATE_NONE = TrackPlayer.STATE_NONE;
module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING;
module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED;
module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED;
module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING;

// Capabilities
module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY;
module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID;
module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH;
module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE;
module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP;
module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO;
module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP;
module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT;
module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS;
module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING;

// Rating Types
module.exports.RATING_HEART = TrackPlayer.RATING_HEART;
module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN;
module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS;
module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS;
module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS;
module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE;

// Cast States
module.exports.CAST_NO_DEVICES_AVAILABLE = TrackPlayer.CAST_NO_DEVICES_AVAILABLE;
module.exports.CAST_NOT_CONNECTED = TrackPlayer.CAST_NOT_CONNECTED;
module.exports.CAST_CONNECTING = TrackPlayer.CAST_CONNECTING;
module.exports.CAST_CONNECTED = TrackPlayer.CAST_CONNECTED;

// Player Lifecycle
module.exports.setupPlayer = TrackPlayer.setupPlayer;
module.exports.destroy = TrackPlayer.destroy;

// Player Options
module.exports.updateOptions = updateOptions;

// Player Queue Commands
module.exports.add = add;
module.exports.remove = remove;
module.exports.skip = TrackPlayer.skip;
module.exports.skipToNext = TrackPlayer.skipToNext;
module.exports.skipToPrevious = TrackPlayer.skipToPrevious;

// Player Playback Commands
module.exports.reset = TrackPlayer.reset;
module.exports.play = TrackPlayer.play;
module.exports.pause = TrackPlayer.pause;
module.exports.stop = TrackPlayer.stop;
module.exports.seekTo = TrackPlayer.seekTo;
module.exports.setVolume = TrackPlayer.setVolume;

// Player Getters
module.exports.getTrack = TrackPlayer.getTrack;
module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack;
module.exports.getVolume = TrackPlayer.getVolume;
module.exports.getDuration = TrackPlayer.getDuration;
module.exports.getPosition = TrackPlayer.getPosition;
module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition;
module.exports.getState = TrackPlayer.getState;

// Event Emitter
module.exports.eventEmitter = eventEmitter;

// Cast Getters
module.exports.getCastState = TrackPlayer.getCastState;

// Components
if(TrackPlayer.CAST_SUPPORT_AVAILABLE) {
    module.exports.CastButton = require('./CastButton');
} else {
    module.exports.CastButton = View; // Cast Unavailable
}
<commit_msg>Fix import name<commit_after>import { NativeEventEmitter, NativeModules, View } from 'react-native';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';

const { TrackPlayerModule: TrackPlayer } = NativeModules;
const eventEmitter = new NativeEventEmitter(TrackPlayer);

function resolveAsset(uri) {
    if(!uri) return undefined;
    return resolveAssetSource(uri);
}

function resolveUrl(url) {
    if(!url) return undefined;
    return resolveAssetSource(url) || url;
}

function updateOptions(data) {
    // Resolve the asset for each icon
    data.icon = resolveAsset(data.icon);
    data.playIcon = resolveAsset(data.playIcon);
    data.pauseIcon = resolveAsset(data.pauseIcon);
    data.stopIcon = resolveAsset(data.stopIcon);
    data.previousIcon = resolveAsset(data.previousIcon);
    data.nextIcon = resolveAsset(data.nextIcon);

    return TrackPlayer.updateOptions(data);
}

function add(tracks, insertBeforeId) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    // Resolve the URL for each track
    for(let i = 0; i < tracks.length; i++) {
        tracks[i].url = resolveUrl(tracks[i].url);
        tracks[i].artwork = resolveUrl(tracks[i].artwork);
    }

    return TrackPlayer.add(tracks, insertBeforeId);
}

function remove(tracks) {
    if(!Array.isArray(tracks)) {
        tracks = [tracks];
    }

    return TrackPlayer.remove(tracks);
}

// We'll declare each one of the constants and functions manually so IDEs can show a list of them
// We should also add documentation here, but I'll leave this task to another day

// States
module.exports.STATE_NONE = TrackPlayer.STATE_NONE;
module.exports.STATE_PLAYING = TrackPlayer.STATE_PLAYING;
module.exports.STATE_PAUSED = TrackPlayer.STATE_PAUSED;
module.exports.STATE_STOPPED = TrackPlayer.STATE_STOPPED;
module.exports.STATE_BUFFERING = TrackPlayer.STATE_BUFFERING;

// Capabilities
module.exports.CAPABILITY_PLAY = TrackPlayer.CAPABILITY_PLAY;
module.exports.CAPABILITY_PLAY_FROM_ID = TrackPlayer.CAPABILITY_PLAY_FROM_ID;
module.exports.CAPABILITY_PLAY_FROM_SEARCH = TrackPlayer.CAPABILITY_PLAY_FROM_SEARCH;
module.exports.CAPABILITY_PAUSE = TrackPlayer.CAPABILITY_PAUSE;
module.exports.CAPABILITY_STOP = TrackPlayer.CAPABILITY_STOP;
module.exports.CAPABILITY_SEEK_TO = TrackPlayer.CAPABILITY_SEEK_TO;
module.exports.CAPABILITY_SKIP = TrackPlayer.CAPABILITY_SKIP;
module.exports.CAPABILITY_SKIP_TO_NEXT = TrackPlayer.CAPABILITY_SKIP_TO_NEXT;
module.exports.CAPABILITY_SKIP_TO_PREVIOUS = TrackPlayer.CAPABILITY_SKIP_TO_PREVIOUS;
module.exports.CAPABILITY_SET_RATING = TrackPlayer.CAPABILITY_SET_RATING;

// Rating Types
module.exports.RATING_HEART = TrackPlayer.RATING_HEART;
module.exports.RATING_THUMBS_UP_DOWN = TrackPlayer.RATING_THUMBS_UP_DOWN;
module.exports.RATING_3_STARS = TrackPlayer.RATING_3_STARS;
module.exports.RATING_4_STARS = TrackPlayer.RATING_4_STARS;
module.exports.RATING_5_STARS = TrackPlayer.RATING_5_STARS;
module.exports.RATING_PERCENTAGE = TrackPlayer.RATING_PERCENTAGE;

// Cast States
module.exports.CAST_NO_DEVICES_AVAILABLE = TrackPlayer.CAST_NO_DEVICES_AVAILABLE;
module.exports.CAST_NOT_CONNECTED = TrackPlayer.CAST_NOT_CONNECTED;
module.exports.CAST_CONNECTING = TrackPlayer.CAST_CONNECTING;
module.exports.CAST_CONNECTED = TrackPlayer.CAST_CONNECTED;

// Player Lifecycle
module.exports.setupPlayer = TrackPlayer.setupPlayer;
module.exports.destroy = TrackPlayer.destroy;

// Player Options
module.exports.updateOptions = updateOptions;

// Player Queue Commands
module.exports.add = add;
module.exports.remove = remove;
module.exports.skip = TrackPlayer.skip;
module.exports.skipToNext = TrackPlayer.skipToNext;
module.exports.skipToPrevious = TrackPlayer.skipToPrevious;

// Player Playback Commands
module.exports.reset = TrackPlayer.reset;
module.exports.play = TrackPlayer.play;
module.exports.pause = TrackPlayer.pause;
module.exports.stop = TrackPlayer.stop;
module.exports.seekTo = TrackPlayer.seekTo;
module.exports.setVolume = TrackPlayer.setVolume;

// Player Getters
module.exports.getTrack = TrackPlayer.getTrack;
module.exports.getCurrentTrack = TrackPlayer.getCurrentTrack;
module.exports.getVolume = TrackPlayer.getVolume;
module.exports.getDuration = TrackPlayer.getDuration;
module.exports.getPosition = TrackPlayer.getPosition;
module.exports.getBufferedPosition = TrackPlayer.getBufferedPosition;
module.exports.getState = TrackPlayer.getState;

// Event Emitter
module.exports.eventEmitter = eventEmitter;

// Cast Getters
module.exports.getCastState = TrackPlayer.getCastState;

// Components
if(TrackPlayer.CAST_SUPPORT_AVAILABLE) {
    module.exports.CastButton = require('./CastButton');
} else {
    module.exports.CastButton = View; // Cast Unavailable
}
<|endoftext|>


<commit_before>var jsontl = (function () {

  var transforms = (function () {

    function getMatch(node, trans) {
      function nodeMatch(e) {
        return node[e] === match[e];
      }

      for (var prop in trans) {
        var newVal = trans[prop].with;
        var match = trans[prop].when;
        if (node.hasOwnProperty(prop)) {
          if (typeof match === 'object') {
            var matched = Object.keys(match).every(nodeMatch);
            if (matched) {
              node[prop] = newVal;
            }
          } else if (!match || (node[prop] == match)) {
            node[prop] = newVal;
          }
        }
      }
    }

    function replace(node, trans, key) {
      if (node[key] instanceof Array) {
        var i = -1,
          len = node[key].length;
        while (++i < len) {
          getMatch(node[key][i], trans);
        }
      } else if (typeof node[key] === 'object') {
        getMatch(node[key], trans);
      } else {
        var newVal = trans.with;
        var match = trans.when;
        if (!match || (node[key] == match)) {
          node[key] = newVal;
        }
      }
    }

    // add the specified data to the object provided
    var extend = function (data, trans, key) {
      if (typeof data[key] !== "object") {
        throw new TypeError("Cannot extend a scalar value.");
      }

      for (var prop in trans) {
        if (typeof trans[prop] === "object") {
          return extend(data[key], trans[prop], prop);
        }
        data[key][prop] = trans[prop];
      }
    }

    return {
      replace: replace,
      extend: extend
    };
  })();

  var locators = (function () {

    var _in = function (data, transform) {
      // look at the transform object for member to transform
      for (var definition in transform) {
        // each tranform definition contains an array of transform instruction objects
        transform[definition].forEach(function (def) {
          // perform each of the transform operations defined in `def`
          for (var op in def) {
            // ensure the operation or locator exists
            if (transforms[op]) {
              // perform the transform
              if (data instanceof Array) {
                data.forEach(function(d) {
                  transforms[op](d, def[op], definition);
                });
              } else {
                transforms[op](data, def[op], definition);
              }
            } else if (locators[op]) {
              // navigate to each location
              return locators[op](data[definition], def[op]);
            }
            // otherwise, move on
          }
        });
      }
      return data;
    }

    return {
			in : _in
    };
  })();

  var lib = {

    /**
     * Perform the provided transform on the data
     * @param   {Object} data  Data to transform
     * @param   {Object} trans Transform definition
     * @returns {Object} The transformed data
     */
    transform: function (data, transform) {
      if (typeof transform.jsontl !== "undefined") {
        if (typeof transform.jsontl.transform !== "undefined") {
          return locators.in(data, transform.jsontl.transform);
        }
      }
      throw Error("Tranform definition invalid");
    }
  };

  return lib;
})();

module.exports = jsontl;
<commit_msg>wrapped jsontl lib in an IIFE<commit_after>(function () {
	'use strict';

	var jsontl = (function () {

		var transforms = (function () {

			function getMatch(node, trans) {
				function nodeMatch(e) {
					return node[e] === match[e];
				}

				for (var prop in trans) {
					var newVal = trans[prop].with;
					var match = trans[prop].when;
					if (node.hasOwnProperty(prop)) {
						if (typeof match === 'object') {
							var matched = Object.keys(match).every(nodeMatch);
							if (matched) {
								node[prop] = newVal;
							}
						} else if (!match || (node[prop] == match)) {
							node[prop] = newVal;
						}
					}
				}
			}

			function replace(node, trans, key) {
				if (node[key] instanceof Array) {
					var i = -1,
						len = node[key].length;
					while (++i < len) {
						getMatch(node[key][i], trans);
					}
				} else if (typeof node[key] === 'object') {
					getMatch(node[key], trans);
				} else {
					var newVal = trans.with;
					var match = trans.when;
					if (!match || (node[key] == match)) {
						node[key] = newVal;
					}
				}
			}

			// add the specified data to the object provided
			var extend = function (data, trans, key) {
				if (typeof data[key] !== "object") {
					throw new TypeError("Cannot extend a scalar value.");
				}

				for (var prop in trans) {
					if (typeof trans[prop] === "object") {
						return extend(data[key], trans[prop], prop);
					}
					data[key][prop] = trans[prop];
				}
			}

			return {
				replace: replace,
				extend: extend
			};
		})();

		var locators = (function () {

			var _in = function (data, transform) {
				// look at the transform object for member to transform
				for (var definition in transform) {
					// each tranform definition contains an array of transform instruction objects
					transform[definition].forEach(function (def) {
						// perform each of the transform operations defined in `def`
						for (var op in def) {
							// ensure the operation or locator exists
							if (transforms[op]) {
								// perform the transform
								if (data instanceof Array) {
									data.forEach(function (d) {
										transforms[op](d, def[op], definition);
									});
								} else {
									transforms[op](data, def[op], definition);
								}
							} else if (locators[op]) {
								// navigate to each location
								return locators[op](data[definition], def[op]);
							}
							// otherwise, move on
						}
					});
				}
				return data;
			}

			return { in : _in
			};
		})();

		var lib = {

			/**
			 * Perform the provided transform on the data
			 * @param   {Object} data  Data to transform
			 * @param   {Object} trans Transform definition
			 * @returns {Object} The transformed data
			 */
			transform: function (data, transform) {
				if (typeof transform.jsontl !== "undefined") {
					if (typeof transform.jsontl.transform !== "undefined") {
						return locators.in(data, transform.jsontl.transform);
					}
				}
				throw Error("Tranform definition invalid");
			}
		};

		return lib;
	})();

	module.exports = jsontl;
})();
<|endoftext|>


<commit_before>'use strict'
// external modules
const crypto = require('crypto')
const randomcolor = require('randomcolor')
const config = require('./config')

// core
exports.generateAvatar = function (name) {
  const color = randomcolor({
    seed: name,
    luminosity: 'dark'
  })
  const letter = name.substring(0, 1).toUpperCase()

  let svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
  svg += '<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="96" width="96" version="1.1" viewBox="0 0 96 96">'
  svg += '<g>'
  svg += '<rect width="96" height="96" fill="' + color + '" />'
  svg += '<text font-size="64px" font-family="sans-serif" text-anchor="middle" fill="#ffffff">'
  svg += '<tspan x="48" y="72" stroke-width=".26458px" fill="#ffffff">' + letter + '</tspan>'
  svg += '</text>'
  svg += '</g>'
  svg += '</svg>'

  return svg
}

exports.generateAvatarURL = function (name, email = '', big = true) {
  let photo
  if (typeof email !== 'string') {
    email = '' + name + '@example.com'
  }
  name = encodeURIComponent(name)

  let hash = crypto.createHash('md5')
  hash.update(email.toLowerCase())
  let hexDigest = hash.digest('hex')

  if (email !== '' && config.allowGravatar) {
    photo = 'https://www.gravatar.com/avatar/' + hexDigest
    if (big) {
      photo += '?s=400'
    } else {
      photo += '?s=96'
    }
  } else {
    photo = config.serverURL + '/user/' + (name || email.substring(0, email.lastIndexOf('@')) || hexDigest) + '/avatar.svg'
  }
  return photo
}
<commit_msg>refactor: fix lint on lib/letter-avatars.js<commit_after>'use strict'
// external modules
const crypto = require('crypto')
const randomcolor = require('randomcolor')
const config = require('./config')

// core
exports.generateAvatar = function (name) {
  const color = randomcolor({
    seed: name,
    luminosity: 'dark'
  })
  const letter = name.substring(0, 1).toUpperCase()

  let svg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
  svg += '<svg xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://www.w3.org/2000/svg" height="96" width="96" version="1.1" viewBox="0 0 96 96">'
  svg += '<g>'
  svg += '<rect width="96" height="96" fill="' + color + '" />'
  svg += '<text font-size="64px" font-family="sans-serif" text-anchor="middle" fill="#ffffff">'
  svg += '<tspan x="48" y="72" stroke-width=".26458px" fill="#ffffff">' + letter + '</tspan>'
  svg += '</text>'
  svg += '</g>'
  svg += '</svg>'

  return svg
}

exports.generateAvatarURL = function (name, email = '', big = true) {
  let photo
  if (typeof email !== 'string') {
    email = '' + name + '@example.com'
  }
  name = encodeURIComponent(name)

  const hash = crypto.createHash('md5')
  hash.update(email.toLowerCase())
  const hexDigest = hash.digest('hex')

  if (email !== '' && config.allowGravatar) {
    photo = 'https://www.gravatar.com/avatar/' + hexDigest
    if (big) {
      photo += '?s=400'
    } else {
      photo += '?s=96'
    }
  } else {
    photo = config.serverURL + '/user/' + (name || email.substring(0, email.lastIndexOf('@')) || hexDigest) + '/avatar.svg'
  }
  return photo
}
<|endoftext|>