<commit_before>    function safe_add(x, y) {
        var lsw = (x & 0xFFFF) + (y & 0xFFFF),
            msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xFFFF);
    }

    /*
     * Bitwise rotate a 32-bit number to the left.
     */

    function bit_rol(num, cnt) {
        return (num << cnt) | (num >>> (32 - cnt));
    }

    /*
     * These functions implement the four basic operations the algorithm uses.
     */

    function md5_cmn(q, a, b, x, s, t) {
        return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
    }

    function md5_ff(a, b, c, d, x, s, t) {
        return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
    }

    function md5_gg(a, b, c, d, x, s, t) {
        return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
    }

    function md5_hh(a, b, c, d, x, s, t) {
        return md5_cmn(b ^ c ^ d, a, b, x, s, t);
    }

    function md5_ii(a, b, c, d, x, s, t) {
        return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
    }

    /*
     * Calculate the MD5 of an array of little-endian words, and a bit length.
     */

    function binl_md5(x, len) {
        /* append padding */
        x[len >> 5] |= 0x80 << (len % 32);
        x[(((len + 64) >>> 9) << 4) + 14] = len;

        var i, olda, oldb, oldc, oldd,
            a = 1732584193,
            b = -271733879,
            c = -1732584194,
            d = 271733878;

        for (i = 0; i < x.length; i += 16) {
            olda = a;
            oldb = b;
            oldc = c;
            oldd = d;

            a = md5_ff(a, b, c, d, x[i], 7, -680876936);
            d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
            c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
            b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
            a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
            d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
            c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
            b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
            a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
            d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
            c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
            b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
            a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
            d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
            c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
            b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

            a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
            d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
            c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
            b = md5_gg(b, c, d, a, x[i], 20, -373897302);
            a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
            d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
            c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
            b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
            a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
            d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
            c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
            b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
            a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
            d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
            c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
            b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

            a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
            d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
            c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
            b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
            a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
            d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
            c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
            b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
            a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
            d = md5_hh(d, a, b, c, x[i], 11, -358537222);
            c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
            b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
            a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
            d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
            c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
            b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

            a = md5_ii(a, b, c, d, x[i], 6, -198630844);
            d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
            c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
            b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
            a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
            d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
            c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
            b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
            a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
            d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
            c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
            b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
            a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
            d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
            c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
            b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
        }
        return [a, b, c, d];
    }

    /*
     * Convert an array of little-endian words to a string
     */

    function binl2rstr(input) {
        var i,
            output = '';
        for (i = 0; i < input.length * 32; i += 8) {
            output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF);
        }
        return output;
    }

    /*
     * Convert a raw string to an array of little-endian words
     * Characters >255 have their high-byte silently ignored.
     */

    function rstr2binl(input) {
        var i,
            output = [];
        output[(input.length >> 2) - 1] = undefined;
        for (i = 0; i < output.length; i += 1) {
            output[i] = 0;
        }
        for (i = 0; i < input.length * 8; i += 8) {
            output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32);
        }
        return output;
    }

    /*
     * Calculate the MD5 of a raw string
     */

    function rstr_md5(s) {
        return binl2rstr(binl_md5(rstr2binl(s), s.length * 8));
    }

    /*
     * Calculate the HMAC-MD5, of a key and some data (raw strings)
     */

    function rstr_hmac_md5(key, data) {
        var i,
            bkey = rstr2binl(key),
            ipad = [],
            opad = [],
            hash;
        ipad[15] = opad[15] = undefined;
        if (bkey.length > 16) {
            bkey = binl_md5(bkey, key.length * 8);
        }
        for (i = 0; i < 16; i += 1) {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5C5C5C5C;
        }
        hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8);
        return binl2rstr(binl_md5(opad.concat(hash), 512 + 128));
    }

    /*
     * Convert a raw string to a hex string
     */

    function rstr2hex(input) {
        var hex_tab = '0123456789abcdef',
            output = '',
            x,
            i;
        for (i = 0; i < input.length; i += 1) {
            x = input.charCodeAt(i);
            output += hex_tab.charAt((x >>> 4) & 0x0F) +
                hex_tab.charAt(x & 0x0F);
        }
        return output;
    }

    /*
     * Encode a string as utf-8
     */

    function str2rstr_utf8(input) {
        return unescape(encodeURIComponent(input));
    }

    /*
     * Take string arguments and return either raw or hex encoded strings
     */

    function raw_md5(s) {
        return rstr_md5(str2rstr_utf8(s));
    }

    function hex_md5(s) {
        return rstr2hex(raw_md5(s));
    }

    function raw_hmac_md5(k, d) {
        return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d));
    }

    function hex_hmac_md5(k, d) {
        return rstr2hex(raw_hmac_md5(k, d));
    }

    function MD5(string, key, raw) {
        if (!key) {
            if (!raw) {
                return hex_md5(string);
            }
            return raw_md5(string);
        }
        if (!raw) {
            return hex_hmac_md5(key, string);
        }
        return raw_hmac_md5(key, string);
    }<commit_msg>Bot easying and rm MD5<commit_after><|endoftext|>


<commit_before>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true, unused: false*/
/*global prepros,  _ , $*/

//Files List controls
prepros.controller('OptimImageCtrl', [

    '$scope',
    'notification',
    'projectsManager',
    '$route',
    '$routeParams',
    '$filter',
    'config',

    function ($scope, notification, projectsManager, $route, $routeParams, $filter, config) {

        'use strict';

        var fs = require('fs-extra');
        var path = require('path');
        var cp = require('child_process');

        var platform = 'win';

        if(process.platform === 'darwin') {
            platform = 'osx';
        }

        if(process.platform === 'linux') {
            platform = 'linux';
        }

        var arch = (process.arch === 'x64') ? 'x64' : 'x86';

        var binPath =   path.join(config.basePath, '../bin');

        var jpegTranPath = path.join(binPath, 'jpegtran', platform, arch, 'jpegtran');

        var optipngPath = path.join(binPath, 'optipng', platform, 'optipng');

        if(platform === 'win') {
            jpegTranPath += '.exe';
            optipngPath += '.exe';
        }

        if(platform === 'osx') {
            jpegTranPath = path.join(binPath, 'jpegtran', platform, 'jpegtran');
        }

        if(platform === 'linux') {
            optipngPath = path.join(binPath, 'optipng', platform, arch, 'optipng');
        }

        $scope.projectImages = [];

        var jpg = ['jpg', 'jpeg'];

        var png = ['png', 'tif', 'tiff'];

        var supportedTypes = _.union(png, jpg);

        function get(dir) {

            var files = fs.readdirSync(dir);

            files.forEach(function (file) {

                var fp = dir + path.sep + file;

                if (fs.statSync(fp).isDirectory()) {

                    get(fp);

                } else {

                    if (_.contains(supportedTypes, path.extname(fp).slice(1).toLowerCase()) && !projectsManager.matchFilters($scope.selectedProject.id, fp)) {
                        $scope.projectImages.push({
                            path: fp,
                            type: path.extname(fp).slice(1),
                            shortPath: $filter('interpolatePath')(fp, {config: $scope.selectedProject.config, relative: true, basePath: $scope.selectedProject.path})
                        });
                    }
                }
            });
        }

        //Prevent subsequent optimizations
        var compileList = [];

        $scope.optimize = function (e, file) {

            if (!_.contains(compileList, file)) {

                compileList.push(file);

                var $target = $(e.currentTarget);

                $target.addClass('optimizing');
                $target.attr('disabled', 'true');
                $target.children('span').text('');

                var cmd = [];
                var executable;
                var ext = path.extname(file).slice(1);

                if (_.contains(png, ext)) {

                    executable = optipngPath;
                    cmd = [file];

                } else {

                    executable = jpegTranPath;
                    cmd = ['-outfile', file, '-optimize', file];

                }

                //Spawn child process to optimize image
                var optimizeProcess = cp.spawn(executable, cmd);

                var commonCall = function() {

                    compileList = _.without(compileList, file);

                    $target.delay(300)
                        .queue(function () {
                            $target.removeClass('optimizing');
                            $target.removeAttr('disabled');
                            $target.dequeue();
                        });
                };

                var errorCall = function(){

                    commonCall();

                    $target.delay(0)
                        .queue(function () {
                            $target.addClass('failed');
                            $target.children('span').text('Failed');
                            $target.dequeue();
                        });
                };

                var successCall= function() {

                    commonCall();

                    $target.delay(0)
                        .queue(function () {
                            $target.addClass('done');
                            $target.children('span').text('Done');
                            $target.dequeue();
                        });
                };

                optimizeProcess.on('error', function (e) {
                    errorCall();
                });

                optimizeProcess.on('exit', function (data) {

                    if (data.toString() !== '0') {
                        errorCall();
                    } else {
                        successCall();
                    }

                    optimizeProcess.removeAllListeners();
                    optimizeProcess = null;
                });
            }
        };

        $scope.$on('$routeChangeSuccess', function () {

            var projectExists = !_.isEmpty(_.findWhere($scope.projects, {id: $routeParams.pid}));

            if ($route.current.path === 'optim' && projectExists) {

                try {

                    $scope.projectImages = [];

                    get(_.findWhere($scope.projects, {id: $routeParams.pid}).path);

                } catch (e) {

                    notification.error('Error ! ', 'An error occurred while scanning project files', e.message);

                }
            } else {

                $scope.projectImages = [];

            }

        });

    }
]);<commit_msg>cleanup<commit_after>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true, unused: false*/
/*global prepros,  _ , $*/

//Files List controls
prepros.controller('OptimImageCtrl', [

    '$scope',
    'notification',
    'projectsManager',
    '$route',
    '$routeParams',
    '$filter',
    'config',

    function ($scope, notification, projectsManager, $route, $routeParams, $filter, config) {

        'use strict';

        var fs = require('fs-extra');
        var path = require('path');
        var cp = require('child_process');

        var platform = 'win';

        if(process.platform === 'darwin') {
            platform = 'osx';
        }

        if(process.platform === 'linux') {
            platform = 'linux';
        }

        var arch = (process.arch === 'x64') ? 'x64' : 'x86';

        var binPath =   path.join(config.basePath, '../bin');

        var jpegTranPath = path.join(binPath, 'jpegtran', platform, arch, 'jpegtran');

        var optipngPath = path.join(binPath, 'optipng', platform, 'optipng');

        if(platform === 'win') {
            jpegTranPath += '.exe';
            optipngPath += '.exe';
        }

        if(platform === 'osx') {
            jpegTranPath = path.join(binPath, 'jpegtran', platform, 'jpegtran');
        }

        if(platform === 'linux') {
            optipngPath = path.join(binPath, 'optipng', platform, arch, 'optipng');
        }

        $scope.projectImages = [];

        var jpg = ['jpg', 'jpeg'];

        var png = ['png', 'tif', 'tiff'];

        var supportedTypes = _.union(png, jpg);

        function get(dir) {

            var files = fs.readdirSync(dir);

            files.forEach(function (file) {

                var fp = dir + path.sep + file;

                if (fs.statSync(fp).isDirectory()) {

                    get(fp);

                } else {

                    if (_.contains(supportedTypes, path.extname(fp).slice(1).toLowerCase()) && !projectsManager.matchFilters($scope.selectedProject.id, fp)) {
                        $scope.projectImages.push({
                            path: fp,
                            type: path.extname(fp).slice(1),
                            shortPath: path.relative($scope.selectedProject.path, fp).replace('\\', '/')
                        });
                    }
                }
            });
        }

        //Prevent subsequent optimizations
        var compileList = [];

        $scope.optimize = function (e, file) {

            if (!_.contains(compileList, file)) {

                compileList.push(file);

                var $target = $(e.currentTarget);

                $target.addClass('optimizing');
                $target.attr('disabled', 'true');
                $target.children('span').text('');

                var cmd = [];
                var executable;
                var ext = path.extname(file).slice(1);

                if (_.contains(png, ext)) {

                    executable = optipngPath;
                    cmd = [file];

                } else {

                    executable = jpegTranPath;
                    cmd = ['-outfile', file, '-optimize', file];

                }

                //Spawn child process to optimize image
                var optimizeProcess = cp.spawn(executable, cmd);

                var commonCall = function() {

                    compileList = _.without(compileList, file);

                    $target.delay(300)
                        .queue(function () {
                            $target.removeClass('optimizing');
                            $target.removeAttr('disabled');
                            $target.dequeue();
                        });
                };

                var errorCall = function(){

                    commonCall();

                    $target.delay(0)
                        .queue(function () {
                            $target.addClass('failed');
                            $target.children('span').text('Failed');
                            $target.dequeue();
                        });
                };

                var successCall= function() {

                    commonCall();

                    $target.delay(0)
                        .queue(function () {
                            $target.addClass('done');
                            $target.children('span').text('Done');
                            $target.dequeue();
                        });
                };

                optimizeProcess.on('error', function (e) {
                    errorCall();
                });

                optimizeProcess.on('exit', function (data) {

                    if (data.toString() !== '0') {
                        errorCall();
                    } else {
                        successCall();
                    }

                    optimizeProcess.removeAllListeners();
                    optimizeProcess = null;
                });
            }
        };

        $scope.$on('$routeChangeSuccess', function () {

            var projectExists = !_.isEmpty(_.findWhere($scope.projects, {id: $routeParams.pid}));

            if ($route.current.path === 'optim' && projectExists) {

                try {

                    $scope.projectImages = [];

                    get(_.findWhere($scope.projects, {id: $routeParams.pid}).path);

                } catch (e) {

                    notification.error('Error ! ', 'An error occurred while scanning project files', e.message);

                }
            } else {

                $scope.projectImages = [];

            }

        });

    }
]);<|endoftext|>


<commit_before>/*--------------------------------------------------------------------------------------------------
|
| -> Инициализируем сокет
|
|-------------------------------------------------------------------------------------------------*/

Onloader.on(function() {
// Добавляем пользовательский обработчик состояний соединения
    Socket.onChange = function(status, error_msg) {
    // Скрываем весь контент
        gl.id('error').className = 'hidden';
        gl.id('loading').className = 'hidden';
        gl.id('content').className = 'hidden';

    // Обрабатываем ошибку
        if (status == 'Error') {
            gl.id('error').className = '';
            gl.id('error').innerHTML += '
' + error_msg + '
';
        }

    // Соединяемся с сервером
        if (status == 'Connect') {
            gl.id('loading').className = '';
            gl.id('loading').innerHTML = 'Соединение с сервером...';
        }

    // Переходим к авторизации
        if (status == 'Access') {
            gl.id('loading').className = '';
            gl.id('loading').innerHTML = 'Авторизация...';
        }

    // Переходим к инициализации
        if (status == 'Init') {
            gl.id('loading').className = '';
            gl.id('loading').innerHTML = 'Инициализация...';
        }

    // Переходим к завершению инициализации
        if (status == 'Complete') {
            gl.id('content').className = '';
        }
    };

// Инициализируем соединение с сервером
    Socket.connect({
    /* Консоль (вкл./выкл.)
     * -> all = все запросы
     * -> body = только тело запросов
     * -> false = выкл.
    **/
        console: 'body',

    // Адрес сервера
        host: 'wss://wordstat-server-classtype.c9.io',

    // Реквизиты для авторизации
        access: ['7011111', 'my_password'],

    // Реквизиты для инициализации
        init: {
            'war_id': 'war_id'// ID войны
        },

    // Обработчик загрузки после инициализации
        onload: function(success) {
            this.send('getName', {id:1});
            this.console('Собственный текст в консоли!');
            this.console('Собственный текст в консоли!');
            this.console('Собственный текст в консоли!');
        }
    });
});

//--------------------------------------------------------------------------------------------------<commit_msg>update SocketInit.js<commit_after>/*--------------------------------------------------------------------------------------------------
|
| -> Инициализируем сокет
|
|-------------------------------------------------------------------------------------------------*/

Onloader.on(function() {
// Добавляем пользовательский обработчик состояний соединения
    Socket.onChange = function(status, error_msg) {
    // Скрываем весь контент
        gl.id('error').className = 'hidden';
        gl.id('loading').className = 'hidden';
        gl.id('content').className = 'hidden';

    // Обрабатываем ошибку
        if (status == 'Error') {
            gl.id('error').className = '';
            gl.id('error').innerHTML += '
' + error_msg + '
';
        }

    // Соединяемся с сервером
        if (status == 'Connect') {
            gl.id('loading').className = '';
            gl.id('loading').innerHTML = 'Соединение с сервером...';
        }

    // Переходим к авторизации
        if (status == 'Access') {
            gl.id('loading').className = '';
            gl.id('loading').innerHTML = 'Авторизация...';
        }

    // Переходим к инициализации
        if (status == 'Init') {
            gl.id('loading').className = '';
            gl.id('loading').innerHTML = 'Инициализация...';
        }

    // Переходим к завершению инициализации
        if (status == 'Complete') {
            gl.id('content').className = '';
        }
    };

// Инициализируем соединение с сервером
    Socket.connect({
    /* Консоль (вкл./выкл.)
     * -> all = все запросы
     * -> body = только тело запросов
     * -> false = выкл.
    **/
        console: 'body',

    // Адрес сервера
        host: 'wss://wordstat-server-classtype.c9.io',

    // Реквизиты для авторизации
        access: ['701111', 'my_password'],

    // Реквизиты для инициализации
        init: ['war_id'],

    // Обработчик загрузки после инициализации
        onload: function(id, name) {
            this.console('ID: ' + id);
            this.console('name: ' + name);
            this.console('Собственный текст в консоли!');
            this.console('Собственный текст в консоли!');
            this.console('Собственный текст в консоли!');
            this.send('getName', 1, 'Вася');
        }
    });
});

Socket.on('setName', function(arg1, arg2, arg3) {
    this.console('arg1: ' + arg1);
    this.console('arg2: ' + arg2);
    this.console('arg3: ' + arg3);
});

//--------------------------------------------------------------------------------------------------<|endoftext|>


<commit_before>
// wrapper around the non-sync fs functions to gracefully handle
// having too many file descriptors open.  Note that this is
// *only* possible because async patterns let one interject timeouts
// and other cleverness anywhere in the process without disrupting
// anything else.
var fs = require("fs")
  , timeout = 0

Object.keys(fs)
  .forEach(function (i) {
    exports[i] = (typeof fs[i] !== "function") ? fs[i]
               : (i.match(/^[A-Z]|^create|Sync$/)) ? function () {
                   return fs[i].apply(fs, arguments)
                 }
               : graceful(fs[i])
  })

if (process.platform === "win32"
    && !process.binding("fs").lstat) {
  exports.lstat = exports.stat
  exports.lstatSync = exports.statSync
}

function graceful (fn) { return function GRACEFUL () {
  var args = Array.prototype.slice.call(arguments)
    , cb_ = args.pop()
  args.push(cb)
  function cb (er) {
    if (er && er.message.match(/^EMFILE, Too many open files/)) {
      setTimeout(function () {
        GRACEFUL.apply(fs, args)
      }, timeout ++)
      return
    }
    timer = 0
    cb_.apply(null, arguments)
  }
  fn.apply(fs, args)
}}
<commit_msg>mis-named timer variable never reset timeout<commit_after>// wrapper around the non-sync fs functions to gracefully handle
// having too many file descriptors open.  Note that this is
// *only* possible because async patterns let one interject timeouts
// and other cleverness anywhere in the process without disrupting
// anything else.
var fs = require("fs")
  , timeout = 0

Object.keys(fs)
  .forEach(function (i) {
    exports[i] = (typeof fs[i] !== "function") ? fs[i]
               : (i.match(/^[A-Z]|^create|Sync$/)) ? function () {
                   return fs[i].apply(fs, arguments)
                 }
               : graceful(fs[i])
  })

if (process.platform === "win32"
    && !process.binding("fs").lstat) {
  exports.lstat = exports.stat
  exports.lstatSync = exports.statSync
}

function graceful (fn) { return function GRACEFUL () {
  var args = Array.prototype.slice.call(arguments)
    , cb_ = args.pop()
  args.push(cb)
  function cb (er) {
    if (er && er.message.match(/^EMFILE, Too many open files/)) {
      setTimeout(function () {
        GRACEFUL.apply(fs, args)
      }, timeout ++)
      return
    }
    timeout = 0
    cb_.apply(null, arguments)
  }
  fn.apply(fs, args)
}}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Print component
 * Creates a AttributeList component
 * @author Roy Braam
 */
Ext.define ("viewer.components.Search",{
    extend: "viewer.components.Component",
    form: null,
    searchResult: null,
    results: null,
    margin: "0 5 0 0",
    resultPanelId: '',
    defaultFormHeight: MobileManager.isMobile() ? 100 : 90,
    config:{
        title: null,
        iconUrl: null,
        tooltip: null,
        searchconfigs: null,
        formHeight:null,
        label: ""
    },
    constructor: function (conf){
        viewer.components.Search.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.renderButton();
        this.loadWindow();
        return this;
    },
    renderButton: function() {
        var me = this;
        viewer.components.Search.superclass.renderButton.call(this,{
            text: me.title,
            icon: me.iconUrl,
            tooltip: me.tooltip,
            label: me.label,
            handler: function() {
                me.popup.show();
            }
        });
    },
    loadWindow : function(){
        var me = this;
        this.form = Ext.create("Ext.form.Panel",{
            frame: false,
            height: this.formHeight || this.defaultFormHeight,
            items: this.getFormItems(),
            border: 0,
            style: {
                padding: '0px 10px 0px 10px'
            }
        });
        this.resultPanelId = Ext.id();
        this.mainContainer = Ext.create('Ext.container.Container', {
            id: this.name + 'Container',
            width: '100%',
            height: '100%',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            style: {
                backgroundColor: 'White'
            },
            renderTo: this.getContentDiv(),
            items: [
                this.form, {
                    id: this.name + 'ContentPanel',
                    xtype: "container",
                    autoScroll: true,
                    width: '100%',
                    flex: 1,
                    html: '

'
                }, {
                    id: this.name + 'ClosingPanel',
                    xtype: "container",
                    width: '100%',
                    height: MobileManager.isMobile() ? 45 : 25,
                    style: {
                        marginTop: '10px',
                        marginRight: '5px'
                    },
                    layout: {
                        type:'hbox',
                        pack:'end'
                    },
                    items: [
                        {xtype: 'button', text: 'Sluiten', componentCls: 'mobileLarge', handler: function() {
                            me.popup.hide();
                        }}
                    ]
                }
            ]
        });
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
    },
    getFormItems: function(){
        var me = this;
        var itemList = new Array();
        if(this.searchconfigs.length == 1){
            itemList.push({
                xtype: 'label',
                text: 'Zoek op: '+ this.searchconfigs[0].name
            });
        }else if (this.searchconfigs.length > 1 ){
            var configs = Ext.create('Ext.data.Store', {
                fields: ['id', 'name', 'url'],
                data : this.searchconfigs
            });
            itemList.push({
                xtype: "flamingocombobox",
                fieldLabel: 'Zoek op',
                store: configs,
                queryMode: 'local',
                displayField: 'name',
                valueField: 'id',
                anchor: '100%',
                emptyText:'Maak uw keuze',
                id: 'searchName' + this.name
            });
        }
        if (this.searchconfigs.length> 0){
            itemList.push({
                xtype: 'textfield',
                name: 'searchfield',
                anchor: '100%',
                id: 'searchfield' + this.name,
                listeners: {
                    specialkey: function(field, e){
                        if (e.getKey() == e.ENTER) {
                            me.search();
                        }
                    }
                }
            });

            itemList.push({
                xtype: 'button',
                text: 'Zoeken',
                componentCls: 'mobileLarge',
                margin: this.margin,
                listeners: {
                    click:{
                        scope: this,
                        fn: this.search
                    }
                }
            });
        }
        itemList.push({
            xtype: 'button',
            text: 'Zoekactie afbreken',
            margin: this.margin,
            componentCls: 'mobileLarge',
            name: 'cancel',
            id: 'cancel'+ this.name,
            listeners: {
                click:{
                    scope: this,
                    fn: this.cancel
                }
            }
        });
        return itemList;
    },
    hideWindow : function(){
        this.popup.hide();
    },
    search : function(){
        if(this.results != null){
            this.results.destroy();
        }
        var searchText = this.form.getChildByElement("searchfield" + this.name).getValue();
        var searchName = '';
        if(this.searchconfigs.length == 1){
            searchName = this.searchconfigs[0].id;
        }else{
            searchName = this.form.getChildByElement("searchName" + this.name).getValue();
        }

        if(searchName != null && searchText != ""){
            var requestPath=  contextPath+"/action/search";
            var requestParams = {};

            requestParams["searchText"]= searchText;
            requestParams["searchName"]= searchName;
            requestParams["appId"]= appId;
            requestParams["componentName"]= this.name;
            var me = this;
            Ext.Ajax.request({
                url: requestPath,
                params: requestParams,
                success: function ( result, request ) {
                    var response = Ext.JSON.decode(result.responseText);
                    me.searchResult = response.results;
                    if (response.error){
                        Ext.MessageBox.alert("Foutmelding", response.error);
                    }
                    me.showSearchResults();
                },
                failure: function(result, request) {
                    var response = Ext.JSON.decode(result.responseText);
                    Ext.MessageBox.alert("Foutmelding", response.error);
                }
            });
            this.form.getChildByElement("cancel"+ this.name).setVisible(true);
        } else {
            Ext.MessageBox.alert("Foutmelding", "Alle velden dienen ingevult te worden.");
            // search request is not complete
        }
    },
    showSearchResults : function(){
        var html = "";
        if(this.searchResult.length <= 0){
            html = "
Er zijn geen resultaten gevonden.
";
        }
        var me = this;
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        var buttonList = new Array();
        for ( var i = 0 ; i < this.searchResult.length ; i ++){
            var result = this.searchResult[i];
            buttonList.push({
                text: result.label,
                xtype: 'button',
                margin: '10px 10px 0px 10px',
                componentCls: 'mobileLarge',
                tooltip: 'Zoom naar locatie',
                listeners: {
                    click:{
                        scope: me,
                        fn: function(){me.handleSearchResult(result.location);}
                    }
                }
            });
        }

        me.results = Ext.create('Ext.form.Panel', {
            title: 'Resultaten:',
            renderTo: this.resultPanelId,
            html: html,
            height: '100%',
            autoScroll: true,
            style: {
                padding: '0px 0px 10px 0px'
            },
            items: buttonList
        });

    },
    cancel : function(){
        this.form.getChildByElement("searchfield"+ this.name).setValue("");
        this.form.getChildByElement("searchName"+ this.name).setValue("");
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        this.results.destroy();
    },
    handleSearchResult : function(location){
        var newExtent = new Object();
        newExtent.minx=location.x-100;
        newExtent.miny=location.y-100;
        newExtent.maxx=location.x+100;
        newExtent.maxy=location.y+100;
        this.viewerController.mapComponent.getMap().zoomToExtent(newExtent);
        this.viewerController.mapComponent.getMap().removeMarker("searchmarker");
        this.viewerController.mapComponent.getMap().setMarker("searchmarker",location.x,location.y,"marker");
        this.popup.hide();
    },
    getExtComponents: function() {
        var c = [ this.mainContainer.getId(), this.form.getId() ];
        if(this.results) c.push(this.results.getId());
        return c;
    }
});

<commit_msg>fixed bug in search component. Always the last result is used.<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Print component
 * Creates a AttributeList component
 * @author Roy Braam
 */
Ext.define ("viewer.components.Search",{
    extend: "viewer.components.Component",
    form: null,
    searchResult: null,
    results: null,
    margin: "0 5 0 0",
    resultPanelId: '',
    defaultFormHeight: MobileManager.isMobile() ? 100 : 90,
    config:{
        title: null,
        iconUrl: null,
        tooltip: null,
        searchconfigs: null,
        formHeight:null,
        label: ""
    },
    constructor: function (conf){
        viewer.components.Search.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.renderButton();
        this.loadWindow();
        return this;
    },
    renderButton: function() {
        var me = this;
        viewer.components.Search.superclass.renderButton.call(this,{
            text: me.title,
            icon: me.iconUrl,
            tooltip: me.tooltip,
            label: me.label,
            handler: function() {
                me.popup.show();
            }
        });
    },
    loadWindow : function(){
        var me = this;
        this.form = Ext.create("Ext.form.Panel",{
            frame: false,
            height: this.formHeight || this.defaultFormHeight,
            items: this.getFormItems(),
            border: 0,
            style: {
                padding: '0px 10px 0px 10px'
            }
        });
        this.resultPanelId = Ext.id();
        this.mainContainer = Ext.create('Ext.container.Container', {
            id: this.name + 'Container',
            width: '100%',
            height: '100%',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            style: {
                backgroundColor: 'White'
            },
            renderTo: this.getContentDiv(),
            items: [
                this.form, {
                    id: this.name + 'ContentPanel',
                    xtype: "container",
                    autoScroll: true,
                    width: '100%',
                    flex: 1,
                    html: '

'
                }, {
                    id: this.name + 'ClosingPanel',
                    xtype: "container",
                    width: '100%',
                    height: MobileManager.isMobile() ? 45 : 25,
                    style: {
                        marginTop: '10px',
                        marginRight: '5px'
                    },
                    layout: {
                        type:'hbox',
                        pack:'end'
                    },
                    items: [
                        {xtype: 'button', text: 'Sluiten', componentCls: 'mobileLarge', handler: function() {
                            me.popup.hide();
                        }}
                    ]
                }
            ]
        });
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
    },
    getFormItems: function(){
        var me = this;
        var itemList = new Array();
        if(this.searchconfigs.length == 1){
            itemList.push({
                xtype: 'label',
                text: 'Zoek op: '+ this.searchconfigs[0].name
            });
        }else if (this.searchconfigs.length > 1 ){
            var configs = Ext.create('Ext.data.Store', {
                fields: ['id', 'name', 'url'],
                data : this.searchconfigs
            });
            itemList.push({
                xtype: "flamingocombobox",
                fieldLabel: 'Zoek op',
                store: configs,
                queryMode: 'local',
                displayField: 'name',
                valueField: 'id',
                anchor: '100%',
                emptyText:'Maak uw keuze',
                id: 'searchName' + this.name
            });
        }
        if (this.searchconfigs.length> 0){
            itemList.push({
                xtype: 'textfield',
                name: 'searchfield',
                anchor: '100%',
                id: 'searchfield' + this.name,
                listeners: {
                    specialkey: function(field, e){
                        if (e.getKey() == e.ENTER) {
                            me.search();
                        }
                    }
                }
            });

            itemList.push({
                xtype: 'button',
                text: 'Zoeken',
                componentCls: 'mobileLarge',
                margin: this.margin,
                listeners: {
                    click:{
                        scope: this,
                        fn: this.search
                    }
                }
            });
        }
        itemList.push({
            xtype: 'button',
            text: 'Zoekactie afbreken',
            margin: this.margin,
            componentCls: 'mobileLarge',
            name: 'cancel',
            id: 'cancel'+ this.name,
            listeners: {
                click:{
                    scope: this,
                    fn: this.cancel
                }
            }
        });
        return itemList;
    },
    hideWindow : function(){
        this.popup.hide();
    },
    search : function(){
        if(this.results != null){
            this.results.destroy();
        }
        var searchText = this.form.getChildByElement("searchfield" + this.name).getValue();
        var searchName = '';
        if(this.searchconfigs.length == 1){
            searchName = this.searchconfigs[0].id;
        }else{
            searchName = this.form.getChildByElement("searchName" + this.name).getValue();
        }

        if(searchName != null && searchText != ""){
            var requestPath=  contextPath+"/action/search";
            var requestParams = {};

            requestParams["searchText"]= searchText;
            requestParams["searchName"]= searchName;
            requestParams["appId"]= appId;
            requestParams["componentName"]= this.name;
            var me = this;
            Ext.Ajax.request({
                url: requestPath,
                params: requestParams,
                success: function ( result, request ) {
                    var response = Ext.JSON.decode(result.responseText);
                    me.searchResult = response.results;
                    if (response.error){
                        Ext.MessageBox.alert("Foutmelding", response.error);
                    }
                    me.showSearchResults();
                },
                failure: function(result, request) {
                    var response = Ext.JSON.decode(result.responseText);
                    Ext.MessageBox.alert("Foutmelding", response.error);
                }
            });
            this.form.getChildByElement("cancel"+ this.name).setVisible(true);
        } else {
            Ext.MessageBox.alert("Foutmelding", "Alle velden dienen ingevult te worden.");
            // search request is not complete
        }
    },
    showSearchResults : function(){
        var html = "";
        if(this.searchResult.length <= 0){
            html = "
Er zijn geen resultaten gevonden.
";
        }
        var me = this;
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        var buttonList = new Array();
        for ( var i = 0 ; i < this.searchResult.length ; i ++){
            var result = this.searchResult[i];
            buttonList.push({
                text: result.label,
                xtype: 'button',
                margin: '10px 10px 0px 10px',
                componentCls: 'mobileLarge',
                tooltip: 'Zoom naar locatie',
                id: "searchButton_"+i,
                listeners: {
                    click:{
                        scope: me,
                        fn: function(button,e,eOpts){
                            //get index
                            var loc = this.searchResult[button.id.split("_")[1]].location;
                            me.handleSearchResult(loc);
                        }
                    }
                }
            });
        }

        me.results = Ext.create('Ext.form.Panel', {
            title: 'Resultaten:',
            renderTo: this.resultPanelId,
            html: html,
            height: '100%',
            autoScroll: true,
            style: {
                padding: '0px 0px 10px 0px'
            },
            items: buttonList
        });

    },
    cancel : function(){
        this.form.getChildByElement("searchfield"+ this.name).setValue("");
        this.form.getChildByElement("searchName"+ this.name).setValue("");
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        this.results.destroy();
    },
    handleSearchResult : function(location){
        var newExtent = new Object();
        newExtent.minx=location.x-100;
        newExtent.miny=location.y-100;
        newExtent.maxx=location.x+100;
        newExtent.maxy=location.y+100;
        this.viewerController.mapComponent.getMap().zoomToExtent(newExtent);
        this.viewerController.mapComponent.getMap().removeMarker("searchmarker");
        this.viewerController.mapComponent.getMap().setMarker("searchmarker",location.x,location.y,"marker");
        this.popup.hide();
    },
    getExtComponents: function() {
        var c = [ this.mainContainer.getId(), this.form.getId() ];
        if(this.results) c.push(this.results.getId());
        return c;
    }
});

<|endoftext|>


<commit_before>"use strict";
var Email = require('email').Email,
  handlebars = require('handlebars');

var MAILING_LIST, SENDER_EMAIL;

if (process.env.NODE_ENV == 'production') {
  MAILING_LIST = "public-review-announce@w3.org";
  SENDER_EMAIL = "notifier@aries.w3.org";
} else {
  MAILING_LIST = "plh@w3.org";
  SENDER_EMAIL = "plh@w3.org";
}

var subjectTemplate = handlebars.compile("{{ status }}: {{ title }}{{cfwd}}"),
  fromTemplate = handlebars.compile("{{ name }} <{{email}}>"),
  bodyTemplate = handlebars.compile("{{ title }}\n\n{{ href }}{{ feedbackDate }}\n\nAbstract\n\n{{ abstract }}\n\nStatus of the Document\n\n{{ sotd }}");

function notifyWideReview(spec) {
  console.log("[Email] Notification: " + spec.href);
  var status = spec.status;
  if (spec.obsoletes === undefined) {
    status = "FPWD";
  }
  var context = {
    title: spec.title,
    date: spec.date,
    href: spec.href,
    status: status,
    sotd: spec.sotd,
    abstract: spec.abstract,
    feedbackDate: (spec.feedbackDate === undefined) ?
      "" : "\n\nfeedback due by: " + spec.feedbackDate,
    timestamp: Date.now()
  };
  if (spec.sotd.indexOf("wide review") !== -1) {
    context.cfwd = " (Call for Wide Review)";
  } else {
    context.cfwd = "";
  }

  var msg = new Email({
    messageId: context.href,
    to: [MAILING_LIST],
    body: bodyTemplate(context),
    subject: subjectTemplate(context),
    from: "Notifier <" + SENDER_EMAIL + ">"
  });

  msg.send(function (err) {
    if (err !== null) {
      console.log("Failure to send email for " + spec.href);
      console.log(err);
      console.log(err.stack);
    }
  });
}

exports.notifyWideReview = notifyWideReview;
<commit_msg>Add path to sendmail<commit_after>"use strict";
var Email = require('email').Email,
  handlebars = require('handlebars');

var MAILING_LIST, SENDER_EMAIL;

if (process.env.NODE_ENV == 'production') {
  MAILING_LIST = "public-review-announce@w3.org";
  SENDER_EMAIL = "notifier@aries.w3.org";
} else {
  MAILING_LIST = "plh@w3.org";
  SENDER_EMAIL = "plh@w3.org";
}

var subjectTemplate = handlebars.compile("{{ status }}: {{ title }}{{cfwd}}"),
  fromTemplate = handlebars.compile("{{ name }} <{{email}}>"),
  bodyTemplate = handlebars.compile("{{ title }}\n\n{{ href }}{{ feedbackDate }}\n\nAbstract\n\n{{ abstract }}\n\nStatus of the Document\n\n{{ sotd }}");

function notifyWideReview(spec) {
  console.log("[Email] Notification: " + spec.href);
  var status = spec.status;
  if (spec.obsoletes === undefined) {
    status = "FPWD";
  }
  var context = {
    title: spec.title,
    date: spec.date,
    href: spec.href,
    status: status,
    sotd: spec.sotd,
    abstract: spec.abstract,
    feedbackDate: (spec.feedbackDate === undefined) ?
      "" : "\n\nfeedback due by: " + spec.feedbackDate,
    timestamp: Date.now()
  };
  if (spec.sotd.indexOf("wide review") !== -1) {
    context.cfwd = " (Call for Wide Review)";
  } else {
    context.cfwd = "";
  }

  var msg = new Email({
    messageId: context.href,
    to: [MAILING_LIST],
    body: bodyTemplate(context),
    subject: subjectTemplate(context),
    from: "Notifier <" + SENDER_EMAIL + ">",
    path: "/usr/sbin/sendmail"
  });

  msg.send(function (err) {
    if (err !== null) {
      console.log("Failure to send email for " + spec.href);
      console.log(err);
      console.log(err.stack);
    }
  });
}

exports.notifyWideReview = notifyWideReview;
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return /* Your Expression */;
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Update rockpaperscissors.js<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return
    var move = ('');
    move = move || 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return /* Your Expression */;
    var move = ('');
    move = move || 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>'use babel';

import console from './console';

function match ({ name, path, tags }) {
    // TODO:
    return !!((name.slice(-1).charCodeAt(0) + tags.length) % 2)
}

/**
 * filter
 * @param  {TreeView} $treeView
 * @param  {Array} tags
 */
export default function filter ({ tags, $treeView }) {

    let hidden = [];
    let visible = [];

    /**
     * all items of files or directories
     * @type {Array} items
     */
    const items = Array.from(
        $treeView.element.querySelectorAll(
            '.list-item:not(.project-root-header)'
        )
    );

    if (tags.length) {
        // filter from back to font
        items.reverse().forEach(( item ) => {
            const {
                name,
                path,
            } = item.firstElementChild.dataset;
            if (match({ name, path, tags })) {
                visible.push(item);
            } else {
                hidden.push(item);
            }
        });
    } else {
        visible = items;
    }

    return {
        hidden,
        visible,
    };
}
<commit_msg>update filter<commit_after>'use babel';

import path from 'path';
import console from './console';

function match ({ name, path, tags }) {
    for (let expression of tags) {
        expression = expression.toLowerCase();
        // directory
        if (expression.indexOf('/') != -1 || expression.indexOf('\\') != -1) {
            const reg = /[\/|\\]/;
            let keywords = expression.split(reg);
            if (!keywords.slice(-1)[0]) {
                keywords.push('*');
            }
            keywords = keywords.filter(( keyword ) => !!keyword);
            const dir = path.split(reg);
            while (dir.length && keywords.length) {
                if (dir.shift().indexOf(keywords[0]) != -1) {
                    keywords.shift();
                }
            }
            if (keywords.length == 0) {
                return true;
            }
            if (dir.length == 0) {
                if (keywords.length == 1) {
                    expression = keywords[0];
                    path = '';
                } else {
                    continue;
                }
            }
        }
        // file
        if (expression.indexOf('.') != -1) {
            // TODO:
            // if (true) {
            //     return true;
            // }
            continue;
        }
        // wildcard
        if (expression === '*') {
            return true;
        }
        // string
        return path.indexOf(expression) != -1;
    }
    return false;
}

/**
 * filter
 * @param  {TreeView} $treeView
 * @param  {Array} tags
 */
export default function filter ({ tags, $treeView }) {

    let hidden = [];
    let visible = [];

    const projects = Array.from(
        $treeView.element.querySelectorAll(
            '.project-root'
        )
    );

    for (let project of projects) {
        const relative = path.relative.bind(path, project.directory.lowerCasePath);
        const items = Array.from(
            project.querySelectorAll(
                '.project-root .list-tree .list-item'
            )
        );
        if (tags.length) {
            items.forEach(( item ) => {
                const name = (item.file || item.parentElement.directory).name.toLowerCase();
                const path = relative((item.file || item.parentElement.directory).path.toLowerCase());
                if (match({
                    name,
                    path,
                    tags,
                })) {
                    visible.push(item);
                } else {
                    hidden.push(item);
                }
            });
        } else {
            visible = visible.concat(items);
        }
    }

    return {
        hidden,
        visible,
    };
}
<|endoftext|>


<commit_before>/* eslint-disable func-names, space-before-function-paren, prefer-arrow-callback, quotes, no-var, vars-on-top, camelcase, comma-dangle, consistent-return, max-len */
/* global ShortcutsNetwork */

import Network from './network';

(function() {
  $(function() {
    if (!$(".network-graph").length) return;

    var network_graph;
    network_graph = new Network({
      url: $(".network-graph").attr('data-url'),
      commit_url: $(".network-graph").attr('data-commit-url'),
      ref: $(".network-graph").attr('data-ref'),
      commit_id: $(".network-graph").attr('data-commit-id')
    });
    return new ShortcutsNetwork(network_graph.branch_graph);
  });
}).call(window);
<commit_msg>remove unnecessary IIFE<commit_after>/* eslint-disable func-names, space-before-function-paren, prefer-arrow-callback, quotes, no-var, vars-on-top, camelcase, comma-dangle, consistent-return, max-len */
/* global ShortcutsNetwork */

import Network from './network';

$(function() {
  if (!$(".network-graph").length) return;

  var network_graph;
  network_graph = new Network({
    url: $(".network-graph").attr('data-url'),
    commit_url: $(".network-graph").attr('data-commit-url'),
    ref: $(".network-graph").attr('data-ref'),
    commit_id: $(".network-graph").attr('data-commit-id')
  });
  return new ShortcutsNetwork(network_graph.branch_graph);
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular
        .module('point-blank')
        .controller('NavBarController', NavBarController);

  NavBarController.$inject = ['$rootScope', 'authFactory'];

  function NavBarController ($rootScope, authFactory) {
    const vm = this;

    $rootScope.loggedIn = authFactory.isLoggedIn;

    vm.logout = function () {
      $rootScope.loggedIn = false;
      authFactory.isLoggedIn = false;
      console.log(authFactory.isLoggedIn);
    };

    vm.isLoggedIn = function () {
      vm.loggedIn = authFactory.isLoggedIn;
    };
  }
})();
<commit_msg>[fix] Login button now only updates after refresh<commit_after>(function () {
  'use strict';

  angular
        .module('point-blank')
        .controller('NavBarController', NavBarController);

  NavBarController.$inject = ['$rootScope', 'authFactory'];

  function NavBarController ($rootScope, authFactory) {
    const vm = this;

    $rootScope.loggedIn = authFactory.isLoggedIn;

    vm.logout = function () {
      process.nextTick(
        function () {
          $rootScope.loggedIn = false;
          authFactory.isLoggedIn = false;
          console.log(authFactory.isLoggedIn);
        }
      );
    };

    vm.isLoggedIn = function () {
      vm.loggedIn = authFactory.isLoggedIn;
    };
  }
})();
<|endoftext|>


<commit_before>//var Rx = require('rx');
var arr = ["5", 2, 3, "hi", 7, 8, 9, "world"];
// off
var objOf = Rx.Observable.of(...arr).skip(2).take(6).takeLast(5).skipLast(2).map(x => parseInt(x))
    .filter(x => !isNaN(x)).reduce((x, y) => x + y);
// from
var objFrom = Rx.Observable.from(arr).first().last().map(x => parseInt(x * x))
    .filter(x => !isNaN(x));
// merge
var objMerge = Rx.Observable.merge(objOf, objFrom);
//
console.log("Hello Rxjs!");
objMerge.subscribe(x => console.log(x));
// just / flatMap / fromPromise
var objJustFlatMap = Rx.Observable.just("https://api.github.com/users")
    .flatMap(requestURL => Rx.Observable.fromPromise(jQuery.getJSON(requestURL)))
// buffer / delay
var countClick = document.querySelector("#countClick");
var clickResult = document.querySelector("#clickResult");
var clickStream = Rx.Observable.fromEvent(countClick, "click");
var evenTimeStampStream = clickStream.buffer(() => clickStream.delay(500))
    .map(event => event.length).do(length => console.log("Click Count : " + length)).filter(length => length === 2);
evenTimeStampStream.subscribe(event => {
    clickResult.innerHTML = "";
    objJustFlatMap.subscribe(data =>
        data.forEach(item =>
            clickResult.innerHTML += `

            ${item.login}

`))
})

var timer1 = Rx.Observable.interval(2000).take(2);
var timer2 = Rx.Observable.interval(1000).take(3);
var timer3 = Rx.Observable.interval(500).take(4);
var result = timer1.concat(timer2, timer3);
result.subscribe(x => console.log(x));

var weight = Rx.Observable.of(70, 72, 76, 79, 75);
var height = Rx.Observable.of(1.76, 1.77, 1.78);
var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => { console.log("w : " + w + " : h :" + h); return w / (h * h) });
bmi.subscribe(x => console.log('BMI is ' + x));<commit_msg>comments<commit_after>//var Rx = require('rx');
var arr = ["5", 2, 3, "hi", 7, 8, 9, "world"];
// of / skip / take / skipLast / takeLast / map / filter / reduce
var objOf = Rx.Observable.of(...arr).skip(2).take(6).takeLast(5).skipLast(2).map(x => parseInt(x))
    .filter(x => !isNaN(x)).reduce((x, y) => x + y);
// from / first / last
var objFrom = Rx.Observable.from(arr).first().last().map(x => parseInt(x * x))
    .filter(x => !isNaN(x));
// merge
var objMerge = Rx.Observable.merge(objOf, objFrom);
//
console.log("Hello Rxjs!");
objMerge.subscribe(x => console.log(x));
// just / flatMap / fromPromise
var objJustFlatMap = Rx.Observable.just("https://api.github.com/users")
    .flatMap(requestURL => Rx.Observable.fromPromise(jQuery.getJSON(requestURL)))
// fromEvent / buffer / delay / do
var countClick = document.querySelector("#countClick");
var clickResult = document.querySelector("#clickResult");
var clickStream = Rx.Observable.fromEvent(countClick, "click");
var evenTimeStampStream = clickStream.buffer(() => clickStream.delay(500))
    .map(event => event.length).do(length => console.log("Click Count : " + length)).filter(length => length === 2);
evenTimeStampStream.subscribe(event => {
    clickResult.innerHTML = "";
    objJustFlatMap.subscribe(data =>
        data.forEach(item =>
            clickResult.innerHTML += `

            ${item.login}

`))
})
// concat
var timer1 = Rx.Observable.interval(2000).take(2);
var timer2 = Rx.Observable.interval(1000).take(3);
var timer3 = Rx.Observable.interval(500).take(4);
var result = timer1.concat(timer2, timer3);
result.subscribe(x => console.log(x));
// combineLatest
var weight = Rx.Observable.of(70, 72, 76, 79, 75);
var height = Rx.Observable.of(1.76, 1.77, 1.78);
var bmi = Rx.Observable.combineLatest(weight, height, (w, h) => { console.log("w : " + w + " : h :" + h); return w / (h * h) });
bmi.subscribe(x => console.log('BMI is ' + x));

<|endoftext|>


<commit_before>/* This is part of Pterosaur.
 *
 * Copyright (c) 2014 James Kolb <jck1089@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * This file incorporates work covered under the following copyright and permission notice:
 *   Copyright © 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
 *   Copyright © 2007-2011 by Doug Kearns <dougkearns@gmail.com>
 *   Copyright © 2008-2011 by Kris Maglione <maglione.k at Gmail>
 *
 *   For a full list of authors, refer the AUTHORS file.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a
 *   copy of this software and associated documentation files (the "Software"),
 *   to deal in the Software without restriction, including without limitation
 *   the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *   and/or sell copies of the Software, and to permit persons to whom the
 *   Software is furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *   DEALINGS IN THE SOFTWARE.
 */

"use strict";
var INFO =
["plugin", { name: "fullvim",
             version: "0.5",
             href: "http://github.com/ardagnir/pterosaur",
             summary: "All text is vim",
             xmlns: "dactyl" },
    ["author", { email: "jck1089@gmail.com" },
        "James Kolb"],
    ["license", { href: "http://www.gnu.org/licenses/agpl-3.0.html" },
        "Gnu AGPL v3"],
    ["project", { name: "Pentadactyl", "min-version": "1.0" }],
    ["p", {},
        "This plugin provides full vim functionality to all input text-boxes by running a vim process in the background."]];

function update(){
    if (pterosaurCleanupCheck !== options["fullvim"])
      cleanupPterosaur();

    //This has to be up here for vimdo to work. This should probably be changed eventually.
    if (writeInsteadOfRead)
    {
      if(sendToVim !== "")
      {
        let tempSendToVim=sendToVim
        sendToVim = ""
        io.system("printf '" + tempSendToVim  + "' > /tmp/pterosaur/fifo_"+uid);
        unsent=0;
      }
      writeInsteadOfRead = 0;
      return;
    }

    if (!options["fullvim"] || (dactyl.focusedElement && dactyl.focusedElement.type === "password") || modes.main !== modes.INSERT && modes.main !== modes.AUTOCOMPLETE && modes.main !== modes.VIM_NORMAL && modes.main !== modes.VIM_COMMAND) {
      if(pterFocused) {
        cleanupForTextbox();
        pterFocused = null
      }
      return;
    }

    writeInsteadOfRead = 1; //For next time around

    if (dactyl.focusedElement !== pterFocused)
    {
      if(pterFocused)
        cleanupForTextbox();
      setupForTextbox();
    }

    let val = tmpfile.read();

    let metadata = metaTmpfile.read().split('\n');
    vimMode = metadata[0];

    if (vimMode === "c") {
      if ( modes.main !== modes.VIM_COMMAND)
      {
        modes.push(modes.VIM_COMMAND);
      }
      if (metadata[1] !=="" && metadata[1] !== lastVimCommand)
      {
        lastVimCommand = metadata[1]
        dactyl.echo("VIM COMMAND " + metadata[1], commandline.FORCE_SINGLELINE);
      }
    }
    else{
        if (modes.main === modes.VIM_COMMAND)
        {
          modes.pop();
        }
        if (lastVimCommand)
        {
          dactyl.echo("")
          lastVimCommand=""
        }
    }

    let messages = messageTmpfile.read();
    if (messages && messages!=="\n")
    {
      //window.alert(messages)
      //TODO: If another message is written right now, we could lose it.
      messageTmpfile.write("");
      //TODO: We don't neccesarily want singleline, but without it we lose focus.
      dactyl.echo(messages,commandline.FORCE_SINGLELINE);

      //We've clearing the entered command. Don't need/want to clear it later and lose our message.
      lastVimCommand=""
    }

    if (vimMode === "e")
      dactyl.echo("ERROR: "+metadata[1])
    else if (vimMode === "n" && modes.main === modes.INSERT)
    {
      //Clear --INSERT-- echoed from vim messages
      dactyl.echo("")
      modes.push(modes.VIM_NORMAL);
    }
    else if (vimMode === "i" && modes.main === modes.VIM_NORMAL)
      modes.pop();

    if (textBox) {
        if (savedCursorStart!=null && textBox.selectionStart != savedCursorStart || savedCursorEnd!=null && textBox.selectionEnd != savedCursorEnd ) {
          pterFocused = null;
          cleanupForTextbox();
          return;
        }

        if (savedText!=null && textBox.value != savedText) {
          pterFocused = null;
          cleanupForTextbox();
          return;
        }

        textBox.value = val;
        savedText = textBox.value;

        if(metadata.length>2 && vimMode !== "c" && vimMode!== "e" && !unsent)
          textBox.setSelectionRange(metadata[1], metadata[2]);

        savedCursorStart = textBox.selectionStart;
        savedCursorEnd = textBox.selectionEnd;

        if (true) {
            let elem = DOM(textBox);
            elem.attrNS(NS, "modifiable", true)
                .style.MozUserInput;
            elem.input().attrNS(NS, "modifiable", null);
        }
    }
    else {
        while (editor_.rootElement.firstChild)
            editor_.rootElement.removeChild(editor_.rootElement.firstChild);
        editor_.rootElement.innerHTML = val;
    }
}

function cleanupForTextbox() {
    io.system('vim --servername pterosaur_'+uid+' --remote-expr "LoseTextbox()"');
    unsent=1;
}

function setupForTextbox() {
    //Clear lingering command text
    if (vimMode === "c")
      io.system("printf '\\ei' > /tmp/pterosaur/fifo_"+uid);

    pterFocused = dactyl.focusedElement;
    savedText = null;
    savedCursorStart = null;
    savedCursorEnd = null;

    textBox = config.isComposeWindow ? null : dactyl.focusedElement;

    if (!DOM(textBox).isInput)
        textBox = null;
    let lineStart, columnStart, lineEnd, columnEnd;

    if (textBox) {
        var text = textBox.value;
        var preStart = text.substr(0, textBox.selectionStart);
        var preEnd = text.substr(0, textBox.selectionEnd);
        savedCursorStart = textBox.selectionStart;
        savedCursorEnd = textBox.selectionEnd;
    }
    else {
        var editor_ = window.GetCurrentEditor ? GetCurrentEditor()
                                              : Editor.getEditor(document.commandDispatcher.focusedWindow);
        dactyl.assert(editor_);
        text = Array.map(editor_.rootElement.childNodes,
                         e => DOM.stringify(e, true))
                    .join("");

        if (!editor_.selection.rangeCount)
            var sel = "";
        else {
            let range = RangeFind.nodeContents(editor_.rootElement);
            let end = editor_.selection.getRangeAt(0);
            range.setEnd(end.startContainer, end.startOffset);
            pre = DOM.stringify(range, true);
            if (range.startContainer instanceof Text)
                pre = pre.replace(/^(?:<[^>"]+>)+/, "");
            if (range.endContainer instanceof Text)
                pre = pre.replace(/(?:<\/[^>"]+>)+$/, "");
            //TODO: support selection here
            preStart = pre
            preEnd = pre
        }
    }
    lineStart = 1 + preStart.replace(/[^\n]/g, "").length;
    columnStart = 1 + preStart.replace(/[^]*\n/, "").length;
    lineEnd = 1 + preEnd.replace(/[^\n]/g, "").length;
    columnEnd = 1 + preEnd.replace(/[^]*\n/, "").length;

    let origGroup = DOM(textBox).highlight.toString();

    if (!tmpfile.write(text))
      throw Error(_("io.cantEncode"));

    var ioCommand;

    //vimCommand = 'vim --servername pterosaur_'+uid+' --remote-expr "SwitchPterosaurFile(<line>,<column>,\'<file>\',\'<metaFile>\',\'<messageFile>\')"';
    ioCommand = 'vim --servername pterosaur_'+uid+' --remote-expr "FocusTextbox(<lineStart>,<columnStart>,<lineEnd>,<columnEnd>)"';

    ioCommand = ioCommand.replace(/<columnStart>/, columnStart);
    ioCommand = ioCommand.replace(/<lineStart>/, lineStart);
    ioCommand = ioCommand.replace(/<columnEnd>/, columnEnd);
    ioCommand = ioCommand.replace(/<lineEnd>/, lineEnd);

    io.system(ioCommand);
}

modes.INSERT.params.onKeyPress = function(eventList) {
    const KILL = false, PASS = true;

    if (!options["fullvim"] || dactyl.focusedElement.type === "password")
      return PASS;

    let inputChar = DOM.Event.stringify(eventList[0])

    /*if (commandLock > COMMAND_MODE_SYNC)
    {
      commandBuffer += inputChar;
      return;
    }
    */

    if (/^<(?:.-)*(?:BS|lt|Up|Down|Left|Right|Space|Return|Del|Tab|C-h|C-w|C-u|C-k|C-r)>$/.test(inputChar)) {
      //Currently, this also refreshes. I need to disable that.
      if (inputChar==="<Space>")
        sendToVim += ' '
      else if (inputChar==="<BS>")
        sendToVim += '\\b'
      else if (inputChar==="<Return>") {
        sendToVim += '\\r'
        return PASS;
      }
      else if (inputChar==="<Tab>")
        return PASS;
      else if (inputChar==="<Up>")
        sendToVim += '\\e[A'
      else if (inputChar==="<Down>")
        sendToVim += '\\e[B'
      else if (inputChar==="<Right>")
        sendToVim += '\\e[C'
      else if (inputChar==="<Left>")
        sendToVim += '\\e[D'
      else if (inputChar==="<lt>")
        sendToVim += '<'
    }
    /*else if (/\:|\?|\//.test(inputChar) && vimMode!='i' && vimMode!='R')
    {
      CommandExMode().open("vimdo " + inputChar);
    }
    */
    else {
      if (inputChar == '%')
        sendToVim += '%%'
      else if (inputChar == '\\')
        sendToVim += '\\\\'
      else if (inputChar == '"')
        sendToVim += '\"'
      else if (inputChar == "'")
        sendToVim += "\'\\'\'"
      else
        sendToVim += inputChar
    }

    return KILL;
}

function cleanupPterosaur()
{
    if (options["fullvim"]) {
        mappings.builtin.remove(modes.INSERT, "<Space>");
        mappings.builtin.remove(modes.INSERT, "<Return>");
        mappings.builtin.add(
            [modes.INSERT],
            ["<Esc>"],
            ["Handle escape key"],
            function(){
              if (vimMode==="n") //This is more specific than VIM_NORMAL which currently includes things like visual
              {
                modes.reset()
              }
              else {
                sendToVim+="\\e"
              }
            });

        mappings.builtin.add(
            [modes.INSERT],
            ["<C-r>"],
            "Override refresh and send <C-r> to vim.",
            function(){
              sendToVim+="\x12"
            },
            {noTransaction: true});

        mappings.builtin.add(
            [modes.VIM_COMMAND],
            ["<Return>"],
            ["Override websites' carriage return behavior when in command mode"],
            function(){
              sendToVim+="\\r"
            });
    }
    else {
        mappings.builtin.add([modes.INSERT],
            ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
            function () {
                editor.expandAbbreviation(modes.INSERT);
                return Events.PASS_THROUGH;
        });

        mappings.builtin.remove( modes.INSERT, "<Esc>");
        mappings.builtin.remove( modes.INSERT, "<C-r>");
        mappings.builtin.remove( modes.VIM_COMMAND, "<Return>");
    }
    pterosaurCleanupCheck = options["fullvim"];
}

var savedText = null;
var savedCursorStart = null;
var savedCursorEnd = null;
var vimMode = 'i';
var pterFocused = null;
var textBox;
var lastVimCommand = "";
var sendToVim = "";
//To prevent collisions TODO: get sequentually, rather than randomly
var uid = Math.floor(Math.random()*0x100000000).toString(16)
var tmpfile = io.createTempFile("txt", "_pterosaur_"+uid);
var metaTmpfile = io.createTempFile("txt", "_pterosaur_"+uid+"_meta");
var messageTmpfile = io.createTempFile("txt", "_pterosaur_"+uid+"_messages");
var unsent = 0;

if (!tmpfile)
    throw Error(_("io.cantCreateTempFile"));

if (!metaTmpfile)
    throw Error(_("io.cantCreateTempFile"));

if (!messageTmpfile)
    throw Error(_("io.cantCreateTempFile"));

//We alternate reads and writes on updates. On writes, we send keypresses to vim. On reads, we read the tmpfile vim is writing to.
var writeInsteadOfRead = 0;

io.system("mkdir /tmp/pterosaur");
io.system("mkfifo /tmp/pterosaur/fifo_"+uid);

//TODO: This is an ugly hack.
io.system("(while killall -0 firefox; do sleep 1; done) > /tmp/pterosaur/fifo_"+uid+" &");

//TODO: Also an ugly hack. Also the --remote is only there because on some computers vim won't create a server outside a terminal unless it has a --remote.
//TODO: Try getting rid of loop now that thigns are stabler
io.system('sh -c \'while killall -0 firefox; do vim --servername pterosaur_'+uid+' +\'\\\'\'call SetupPterosaur("'+tmpfile.path+'","'+metaTmpfile.path+'","'+messageTmpfile.path+'")\'\\\'\'  --remote '+tmpfile.path+' </tmp/pterosaur/fifo_'+uid+' > /dev/null; done\' &');

//If this doesn't match options["fullvim"] we need to perform cleanup
var pterosaurCleanupCheck = false;

group.options.add(["fullvim"], "Edit all text inputs using vim", "boolean", false);

modes.addMode("VIM_NORMAL", {
  char: "N",
  desription: "Vim normal mode",
  bases: [modes.INSERT]
});

modes.addMode("VIM_COMMAND", {
  char: "e",
  desription: "Vim normal mode",
  bases: [modes.VIM_NORMAL]
});

commands.add(["vim[do]"],
    "Send command to vim",
    function (args) {
        dactyl.focus(pterFocused);
        let command = args.join(" ").replace(/%/g,"%%").replace(/\\/g,'\\\\');
        sendToVim += command +"\r"
    }, {
      argCount: "+",
      literal: 0
    });

let timer =  window.setInterval(update, 50);
<commit_msg>Replaced newlines with spaces on inputs<commit_after>/* This is part of Pterosaur.
 *
 * Copyright (c) 2014 James Kolb <jck1089@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * This file incorporates work covered under the following copyright and permission notice:
 *   Copyright © 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
 *   Copyright © 2007-2011 by Doug Kearns <dougkearns@gmail.com>
 *   Copyright © 2008-2011 by Kris Maglione <maglione.k at Gmail>
 *
 *   For a full list of authors, refer the AUTHORS file.
 *
 *   Permission is hereby granted, free of charge, to any person obtaining a
 *   copy of this software and associated documentation files (the "Software"),
 *   to deal in the Software without restriction, including without limitation
 *   the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *   and/or sell copies of the Software, and to permit persons to whom the
 *   Software is furnished to do so, subject to the following conditions:
 *
 *   The above copyright notice and this permission notice shall be included in
 *   all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 *   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 *   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 *   DEALINGS IN THE SOFTWARE.
 */

"use strict";
var INFO =
["plugin", { name: "fullvim",
             version: "0.5",
             href: "http://github.com/ardagnir/pterosaur",
             summary: "All text is vim",
             xmlns: "dactyl" },
    ["author", { email: "jck1089@gmail.com" },
        "James Kolb"],
    ["license", { href: "http://www.gnu.org/licenses/agpl-3.0.html" },
        "Gnu AGPL v3"],
    ["project", { name: "Pentadactyl", "min-version": "1.0" }],
    ["p", {},
        "This plugin provides full vim functionality to all input text-boxes by running a vim process in the background."]];

function update(){
    if (pterosaurCleanupCheck !== options["fullvim"])
      cleanupPterosaur();

    //This has to be up here for vimdo to work. This should probably be changed eventually.
    if (writeInsteadOfRead)
    {
      if(sendToVim !== "")
      {
        let tempSendToVim=sendToVim
        sendToVim = ""
        io.system("printf '" + tempSendToVim  + "' > /tmp/pterosaur/fifo_"+uid);
        unsent=0;
      }
      writeInsteadOfRead = 0;
      return;
    }

    if (!options["fullvim"] || (dactyl.focusedElement && dactyl.focusedElement.type === "password") || modes.main !== modes.INSERT && modes.main !== modes.AUTOCOMPLETE && modes.main !== modes.VIM_NORMAL && modes.main !== modes.VIM_COMMAND) {
      if(pterFocused) {
        cleanupForTextbox();
        pterFocused = null
      }
      return;
    }

    writeInsteadOfRead = 1; //For next time around

    if (dactyl.focusedElement !== pterFocused)
    {
      if(pterFocused)
        cleanupForTextbox();
      setupForTextbox();
    }

    let val = tmpfile.read();

    let metadata = metaTmpfile.read().split('\n');
    vimMode = metadata[0];

    if (vimMode === "c") {
      if ( modes.main !== modes.VIM_COMMAND)
      {
        modes.push(modes.VIM_COMMAND);
      }
      if (metadata[1] !=="" && metadata[1] !== lastVimCommand)
      {
        lastVimCommand = metadata[1]
        dactyl.echo("VIM COMMAND " + metadata[1], commandline.FORCE_SINGLELINE);
      }
    }
    else{
        if (modes.main === modes.VIM_COMMAND)
        {
          modes.pop();
        }
        if (lastVimCommand)
        {
          dactyl.echo("")
          lastVimCommand=""
        }
    }

    let messages = messageTmpfile.read();
    if (messages && messages!=="\n")
    {
      //window.alert(messages)
      //TODO: If another message is written right now, we could lose it.
      messageTmpfile.write("");
      //TODO: We don't neccesarily want singleline, but without it we lose focus.
      dactyl.echo(messages,commandline.FORCE_SINGLELINE);

      //We've clearing the entered command. Don't need/want to clear it later and lose our message.
      lastVimCommand=""
    }

    if (vimMode === "e")
      dactyl.echo("ERROR: "+metadata[1])
    else if (vimMode === "n" && modes.main === modes.INSERT)
    {
      //Clear --INSERT-- echoed from vim messages
      dactyl.echo("")
      modes.push(modes.VIM_NORMAL);
    }
    else if (vimMode === "i" && modes.main === modes.VIM_NORMAL)
      modes.pop();

    if (textBox) {
        if (savedCursorStart!=null && textBox.selectionStart != savedCursorStart || savedCursorEnd!=null && textBox.selectionEnd != savedCursorEnd ) {
          pterFocused = null;
          cleanupForTextbox();
          return;
        }

        if (savedText!=null && textBox.value != savedText) {
          pterFocused = null;
          cleanupForTextbox();
          return;
        }
        //We only get one line for inputs
        if(textBox.tagName == "input")
        {
          val = val.replace(/\n/g," ")
        }

        textBox.value = val;
        savedText = textBox.value;

        if(metadata.length>2 && vimMode !== "c" && vimMode!== "e" && !unsent)
          textBox.setSelectionRange(metadata[1], metadata[2]);

        savedCursorStart = textBox.selectionStart;
        savedCursorEnd = textBox.selectionEnd;

        if (true) {
            let elem = DOM(textBox);
            elem.attrNS(NS, "modifiable", true)
                .style.MozUserInput;
            elem.input().attrNS(NS, "modifiable", null);
        }
    }
    else {
        while (editor_.rootElement.firstChild)
            editor_.rootElement.removeChild(editor_.rootElement.firstChild);
        editor_.rootElement.innerHTML = val;
    }
}

function cleanupForTextbox() {
    io.system('vim --servername pterosaur_'+uid+' --remote-expr "LoseTextbox()"');
    unsent=1;
}

function setupForTextbox() {
    //Clear lingering command text
    if (vimMode === "c")
      io.system("printf '\\ei' > /tmp/pterosaur/fifo_"+uid);

    pterFocused = dactyl.focusedElement;
    savedText = null;
    savedCursorStart = null;
    savedCursorEnd = null;

    textBox = config.isComposeWindow ? null : dactyl.focusedElement;

    if (!DOM(textBox).isInput)
        textBox = null;
    let lineStart, columnStart, lineEnd, columnEnd;

    if (textBox) {
        var text = textBox.value;
        var preStart = text.substr(0, textBox.selectionStart);
        var preEnd = text.substr(0, textBox.selectionEnd);
        savedCursorStart = textBox.selectionStart;
        savedCursorEnd = textBox.selectionEnd;
    }
    else {
        var editor_ = window.GetCurrentEditor ? GetCurrentEditor()
                                              : Editor.getEditor(document.commandDispatcher.focusedWindow);
        dactyl.assert(editor_);
        text = Array.map(editor_.rootElement.childNodes,
                         e => DOM.stringify(e, true))
                    .join("");

        if (!editor_.selection.rangeCount)
            var sel = "";
        else {
            let range = RangeFind.nodeContents(editor_.rootElement);
            let end = editor_.selection.getRangeAt(0);
            range.setEnd(end.startContainer, end.startOffset);
            pre = DOM.stringify(range, true);
            if (range.startContainer instanceof Text)
                pre = pre.replace(/^(?:<[^>"]+>)+/, "");
            if (range.endContainer instanceof Text)
                pre = pre.replace(/(?:<\/[^>"]+>)+$/, "");
            //TODO: support selection here
            preStart = pre
            preEnd = pre
        }
    }
    lineStart = 1 + preStart.replace(/[^\n]/g, "").length;
    columnStart = 1 + preStart.replace(/[^]*\n/, "").length;
    lineEnd = 1 + preEnd.replace(/[^\n]/g, "").length;
    columnEnd = 1 + preEnd.replace(/[^]*\n/, "").length;

    let origGroup = DOM(textBox).highlight.toString();

    if (!tmpfile.write(text))
      throw Error(_("io.cantEncode"));

    var ioCommand;

    //vimCommand = 'vim --servername pterosaur_'+uid+' --remote-expr "SwitchPterosaurFile(<line>,<column>,\'<file>\',\'<metaFile>\',\'<messageFile>\')"';
    ioCommand = 'vim --servername pterosaur_'+uid+' --remote-expr "FocusTextbox(<lineStart>,<columnStart>,<lineEnd>,<columnEnd>)"';

    ioCommand = ioCommand.replace(/<columnStart>/, columnStart);
    ioCommand = ioCommand.replace(/<lineStart>/, lineStart);
    ioCommand = ioCommand.replace(/<columnEnd>/, columnEnd);
    ioCommand = ioCommand.replace(/<lineEnd>/, lineEnd);

    io.system(ioCommand);
}

modes.INSERT.params.onKeyPress = function(eventList) {
    const KILL = false, PASS = true;

    if (!options["fullvim"] || dactyl.focusedElement.type === "password")
      return PASS;

    let inputChar = DOM.Event.stringify(eventList[0])

    /*if (commandLock > COMMAND_MODE_SYNC)
    {
      commandBuffer += inputChar;
      return;
    }
    */

    if (/^<(?:.-)*(?:BS|lt|Up|Down|Left|Right|Space|Return|Del|Tab|C-h|C-w|C-u|C-k|C-r)>$/.test(inputChar)) {
      //Currently, this also refreshes. I need to disable that.
      if (inputChar==="<Space>")
        sendToVim += ' '
      else if (inputChar==="<BS>")
        sendToVim += '\\b'
      else if (inputChar==="<Return>") {
        sendToVim += '\\r'
        return PASS;
      }
      else if (inputChar==="<Tab>")
        return PASS;
      else if (inputChar==="<Up>")
        sendToVim += '\\e[A'
      else if (inputChar==="<Down>")
        sendToVim += '\\e[B'
      else if (inputChar==="<Right>")
        sendToVim += '\\e[C'
      else if (inputChar==="<Left>")
        sendToVim += '\\e[D'
      else if (inputChar==="<lt>")
        sendToVim += '<'
    }
    /*else if (/\:|\?|\//.test(inputChar) && vimMode!='i' && vimMode!='R')
    {
      CommandExMode().open("vimdo " + inputChar);
    }
    */
    else {
      if (inputChar == '%')
        sendToVim += '%%'
      else if (inputChar == '\\')
        sendToVim += '\\\\'
      else if (inputChar == '"')
        sendToVim += '\"'
      else if (inputChar == "'")
        sendToVim += "\'\\'\'"
      else
        sendToVim += inputChar
    }

    return KILL;
}

function cleanupPterosaur()
{
    if (options["fullvim"]) {
        mappings.builtin.remove(modes.INSERT, "<Space>");
        mappings.builtin.remove(modes.INSERT, "<Return>");
        mappings.builtin.add(
            [modes.INSERT],
            ["<Esc>"],
            ["Handle escape key"],
            function(){
              if (vimMode==="n") //This is more specific than VIM_NORMAL which currently includes things like visual
              {
                modes.reset()
              }
              else {
                sendToVim+="\\e"
              }
            });

        mappings.builtin.add(
            [modes.INSERT],
            ["<C-r>"],
            "Override refresh and send <C-r> to vim.",
            function(){
              sendToVim+="\x12"
            },
            {noTransaction: true});

        mappings.builtin.add(
            [modes.VIM_COMMAND],
            ["<Return>"],
            ["Override websites' carriage return behavior when in command mode"],
            function(){
              sendToVim+="\\r"
            });
    }
    else {
        mappings.builtin.add([modes.INSERT],
            ["<Space>", "<Return>"], "Expand Insert mode abbreviation",
            function () {
                editor.expandAbbreviation(modes.INSERT);
                return Events.PASS_THROUGH;
        });

        mappings.builtin.remove( modes.INSERT, "<Esc>");
        mappings.builtin.remove( modes.INSERT, "<C-r>");
        mappings.builtin.remove( modes.VIM_COMMAND, "<Return>");
    }
    pterosaurCleanupCheck = options["fullvim"];
}

var savedText = null;
var savedCursorStart = null;
var savedCursorEnd = null;
var vimMode = 'i';
var pterFocused = null;
var textBox;
var lastVimCommand = "";
var sendToVim = "";
//To prevent collisions TODO: get sequentually, rather than randomly
var uid = Math.floor(Math.random()*0x100000000).toString(16)
var tmpfile = io.createTempFile("txt", "_pterosaur_"+uid);
var metaTmpfile = io.createTempFile("txt", "_pterosaur_"+uid+"_meta");
var messageTmpfile = io.createTempFile("txt", "_pterosaur_"+uid+"_messages");
var unsent = 0;

if (!tmpfile)
    throw Error(_("io.cantCreateTempFile"));

if (!metaTmpfile)
    throw Error(_("io.cantCreateTempFile"));

if (!messageTmpfile)
    throw Error(_("io.cantCreateTempFile"));

//We alternate reads and writes on updates. On writes, we send keypresses to vim. On reads, we read the tmpfile vim is writing to.
var writeInsteadOfRead = 0;

io.system("mkdir /tmp/pterosaur");
io.system("mkfifo /tmp/pterosaur/fifo_"+uid);

//TODO: This is an ugly hack.
io.system("(while killall -0 firefox; do sleep 1; done) > /tmp/pterosaur/fifo_"+uid+" &");

//TODO: Also an ugly hack. Also the --remote is only there because on some computers vim won't create a server outside a terminal unless it has a --remote.
//TODO: Try getting rid of loop now that thigns are stabler
io.system('sh -c \'while killall -0 firefox; do vim --servername pterosaur_'+uid+' +\'\\\'\'call SetupPterosaur("'+tmpfile.path+'","'+metaTmpfile.path+'","'+messageTmpfile.path+'")\'\\\'\'  --remote '+tmpfile.path+' </tmp/pterosaur/fifo_'+uid+' > /dev/null; done\' &');

//If this doesn't match options["fullvim"] we need to perform cleanup
var pterosaurCleanupCheck = false;

group.options.add(["fullvim"], "Edit all text inputs using vim", "boolean", false);

modes.addMode("VIM_NORMAL", {
  char: "N",
  desription: "Vim normal mode",
  bases: [modes.INSERT]
});

modes.addMode("VIM_COMMAND", {
  char: "e",
  desription: "Vim normal mode",
  bases: [modes.VIM_NORMAL]
});

commands.add(["vim[do]"],
    "Send command to vim",
    function (args) {
        dactyl.focus(pterFocused);
        let command = args.join(" ").replace(/%/g,"%%").replace(/\\/g,'\\\\');
        sendToVim += command +"\r"
    }, {
      argCount: "+",
      literal: 0
    });

let timer =  window.setInterval(update, 50);
<|endoftext|>