<commit_before>(function() {

var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);

function create_show_package_link(pkg) {
    return ''+pkg+'';
}

function setup_copy_to_clipboard(obj, urls) {
    var items = [];
    var len = urls.length;
    for (var i=0; i<len; i++) {
        items.push($(urls[i]).text());
    }
    obj.data('urls', items.join("\n"));

    obj.mouseover(function() {
        clip.setText($(this).data('urls'));
        if (clip.div) {
            clip.receiveEvent('mouseout', null);
            clip.reposition(this);
        }
        else {
            clip.glue(this);
        }
        clip.receiveEvent('mouseover', null);
        var self = this;
        clip.addEventListener('onComplete', function() {
            $(self).text('Copied!');
        });
    });
}

function show_loader(obj, text) {
    if (text == undefined) {
        text = 'loading..';
    }

    obj.html('

 '+text+'

');
    obj.show();
}

var ph = {
    install: {
        packages: [],

        _add: function(pkgs) {
            var items = pkgs.split(" ");
            var len = items.length;
            for (var i=0; i<len; i++) {
                var item = items[i];
                if ((item.length > 0) && (this.packages.indexOf(item) == -1)) {
                    this.packages.push(item);
                    ph.search.mark(item);
                }
            }
        },

        _remove: function(pkg) {
            var pos = this.packages.indexOf(pkg);
            if (pos >= 0) {
                this.packages.splice(pos, 1);
                ph.search.unmark(pkg);
            }
        },

        _clear: function() {
            this.packages = [];
            ph.search.update_marks();
        },

        update_list: function() {
            var obj = $('#install-package-list ul');
            var html = '';
            var len = this.packages.length;
            for (var i=0; i<len; i++) {
                var pkg = this.packages[i];
                html += '
'+create_show_package_link(pkg);
                html += 'x
 ';
            }
            obj.html(html);
            if (len > 0) {
                $('#install-package-button').show();
                $('#install-package-list').show();
            }
            else {
                $('#install-package-button').hide();
                $('#install-package-list').hide();
            }
        },

        add_form: function() {
            var pkgs = $('#install-package-add')[0].value;
            this.add(pkgs);
            $('#install-package-add').select();
        },

        add: function(pkgs) {
            this._add(pkgs);
            this.update_list();
        },

        remove: function(pkg) {
            this._remove(pkg);
            this.update_list();
        },

        clear: function() {
            this._clear();
            this.update_list();
            $('#install-package-add').select();
        },

        _create_package_list: function(items, title) {
            if (items == undefined) { return ''; }
            var len = items.length;
            if (len == 0) { return ''; }

            var html = '';
            html += '

'+title+'
';

            var list = [];
            for (var i=0; i<len; i++) {
                list.push(create_show_package_link(items[i]));
            }

            html += '
' + list.join(', ') + '
';

            html += '
';
            return html;
        },

        show: function(data, target) {
            if (target == undefined) {
                target = '#install-result';
            }

            var obj = $(target);
            var type = data.type;
            var data = data.data;
            var html = '';

            obj.html('

');
            obj = obj.find('.install-result');

            var pkgs = data.packages.join(' ');

            if (type == 'install') {
                html += '
Installation result for '+pkgs+':
';
            }
            else if (type == "upgrade") {
                html += '
Result of upgrade operation:
';
            }
            else if (type == "dist-upgrade") {
                html += '
Result of dist-upgrade operation:
';
            }

            if (data.errors.length > 0) {
                html += '

Unable to install. Error messages:

';
                var len = data.errors.length;
                for (var i=0; i<len; i++) {
                    html += '
'+data.errors[i]+'
';
                }
                html += '

';
                obj.html(html);
            }
            else {
                html += '

';
                obj.html(html);

                var head = obj.find('.head');
                var side = obj.find('.side');
                var main = obj.find('.main');

                // Already the newest version
                if (data.newest.length > 0) {
                    var items = [];
                    var len = data.newest.length;
                    for (var i=0; i<len; i++) {
                        items.push(create_show_package_link(data.newest[i]));
                    }
                    html = '
Already the newest version: ' + items.join(', ') + '
';
                    head.html(html);
                }

                // URL list
                if (data.urls.length > 0) {
                    html = '';
                    html += '
URLs
';
                    html += '
 — copy to clipboard
';
                    html += '
';

                    var len = data.urls.length;
                    for (var i=0; i<len; i++) {
                        var item = data.urls[i];
                        var url = item[0];
                        var deb = item[1];
                        var size = item[2];
                        var hash = item[3];
                        var hash_format = item[4];
                        html += '
'+url+'
';
                    }

                    html += '
';
                    main.html(html);

                    setup_copy_to_clipboard(main.find('p.copy span'), main.find('ul.urls li'));
                }

                // install

                html = '';
                html += this._create_package_list(data.install, 'To Be Installed');
                html += this._create_package_list(data.upgrade, 'To Be Upgraded');
                html += this._create_package_list(data.recommended, 'Recommended');
                html += this._create_package_list(data.suggested, 'Suggested');

                side.html(html);
            }

            obj.append('
');
            obj.show();
        },

        start: function() {
            var packages = this.packages.join(" ");
            var self = this;
            show_loader($('#install-result'));
            $.ajax({
                type: 'POST',
                url: 'install/?format=json',
                dataType: 'json',
                data: {packages: packages},
                complete: function(xhr, stat) {
                    console.log('complete.', 'stat:', stat);
                },
                success: function(data, stat) {
                    self.show(data);
                }
            });
        }
    },

    show: function(pkg) {
        var dialog = $('#dialog-package-show');
        dialog.dialog('open');
        show_loader(dialog);
        $.ajax({
            url: 'show/'+pkg+'/?format=json',
            method: 'GET',
            dataType: 'json',
            success: function(data, stat) {
                if (data.data.package == null) {
                    var html = '';
                    html += '

No package information for '+pkg+'

';
                    dialog.html(html);
                }
                else {
                    pkg = data.data.package;

                    var checked = '';
                    if (ph.install.packages.indexOf(pkg) >= 0) {
                        checked = 'checked="checked"';
                    }

                    var html = '';
                    html += '
<input type="checkbox" '+checked+' onclick="profile.search.toggle(this, \''+pkg+'\')"/> marked
';
                    html += '
'+data.data.sdesc+'
';
                    html += '
'+data.data.desc+'
';
                    html += '
';

                    var table = dialog.find('table');
                    var info = data.data.data;
                    var len = info.length;
                    for (var i=0; i<len; i++) {
                        var key = info[i][0];
                        var value = htmlentities(info[i][1]);
                        if (key != 'Description') {
                            html += '
'+key+'	'+value+'
';
                        }
                    }
                    html += '
';

                    dialog.html(html);
                }

                dialog.dialog('option', 'position', ['center', 25]);
                dialog.dialog('option', 'title', pkg);
            },

            error: function(xhr, stat, err) {
                if (xhr.status == 404) {
                    var html = '';
                    html += '

Package not found: '+pkg+'

';
                    dialog.html(html);
                }
            },
        });
    },

    search: {

        show: function(query, data) {
            var items = data.data.items;
            var len = items.length;
            var obj = $('#search-result');

            if (len == 0) {
                var html = '';
                html += '
No package found. Please try another keyword.
';
                obj.html(html);
            }
            else {
                var html = '';
                html += '
Search result for '+query+':
';
                html += '

';
                obj.html(html);
                var table = obj.find('table');
                table.append('
	Package	Description
');
                for (var i=0; i<len; i++) {
                    var pkg = items[i][0];
                    var desc = items[i][1];
                    var pkglink = create_show_package_link(pkg);
                    var addlink = '';
                    var checked = 'checked="checked"';
                    if (ph.install.packages.indexOf(pkg) == -1) {
                        checked = '';
                    }
                    var check = '<input type="checkbox" '+checked+'" onclick="profile.search.toggle(this, \''+pkg+'\')" rel="'+pkg+'"/>';
                    table.append('
'+check+'	'+pkglink+'	'+desc+'
');
                }
            }
            obj.show();
        },

        toggle: function(src, pkg) {
            if (src.checked) {
                this._skip = true;
                ph.install.add(pkg);
            }
            else {
                this._skip = true;
                ph.install.remove(pkg);
            }
        },

        mark: function(pkg, checked) {
            if (checked == undefined) {
                checked = true;
            }

            var obj = $('#search-result table.search');
            var check = obj.find('input[type="checkbox"][rel="'+pkg+'"]');
            if (check.length > 0) {
                check[0].checked = checked;
            }
        },

        unmark: function(pkg) {
            this.mark(pkg, false);
        },

        update_marks: function() {
            if (this._skip == true) { this._skip = false; return; }
            var obj = $('#search-result table.search');
            var items = obj.find('input[type="checkbox"]');
            var len = items.length;
            for (var i=0; i<len; i++) {
                items[i].checked = false;
            }

            var pkgs = ph.install.packages;
            len = pkgs.length;
            for (var i=0; i<len; i++) {
                this.mark(pkgs[i]);
            }
        },

        start: function(f) {
            var query = f.packages.value;
            var self = this;
            show_loader($('#search-result'));
            $.ajax({
                type: 'POST',
                url: 'search/?format=json',
                dataType: 'json',
                data: {packages: query},
                complete: function(xhr, stat) {
                    console.log('complete');
                    console.log('stat:', stat);
                },
                success: function(data, stat) {
                    self.show(query, data);
                }
            });
        }
    },

    dist_upgrade: {
        start: function() {
            ph.upgrade._start('dist-upgrade');
        }
    },

    upgrade: {
        start: function() {
            this._start('upgrade');
        },

        _start: function(path) {
            show_loader($('#upgrade-result'));
            $.ajax({
                type: 'POST',
                url: path + '/?format=json',
                dataType: 'json',
                complete: function(xhr, stat) {
                    console.log('complete.', 'stat:', stat);
                },
                success: function(data, stat) {
                    ph.install.show(data, '#upgrade-result');
                }
            });
        }
    },

    update: {
        start: function(sender) {
            var btn = $(sender).find('input[type="submit"]');
            btn.attr('disabled', 'disabled');
            btn.after(' updating..');

            $.ajax({
                type: 'POST',
                url: 'update/',
                dataType: 'text',
                complete: function(xhr, stat) {
                },
                success: function(data, stat) {
                    btn.attr('disabled', '');
                    console.log(window.location.href);
                    window.location.reload();
                },
            });
        }
    },

    status: {
        start: function(sender) {
            var btn = $(sender).find('input[type="submit"]');
            btn.attr('disabled', 'disabled');
            btn.after(' uploading..');
            $('#dialog-status-upload').bind('dialogbeforeclose', function() {
                return false;
            });
        }
    },

    init: function() {
        this._init_dialogs();
        this._init_tabs();
    },

    _init_dialogs: function() {
        $('.dialog').dialog({autoOpen: false, modal: true});
        $('#dialog-status-upload').dialog('option', 'width', 500);
        $('#dialog-sources').dialog('option', 'width', 500);
        $('#dialog-package-show').dialog('option', 'width', 700);
        $('#dialog-package-show').dialog('option', 'maxHeight', 500);
    },

    _init_tabs: function() {
        $('.tabs').tabs();
    }
}

this.profile = ph;
})();

function show_dialog(s) {
    $(s).dialog('open');
}
function htmlentities(txt) {
    txt = txt.replace(/</g, '<');
    txt = txt.replace(/>/g, '>');
    return txt;
}
<commit_msg>Restore copy-to-clipboard label<commit_after>(function() {

var clip = new ZeroClipboard.Client();
clip.setHandCursor(true);

function create_show_package_link(pkg) {
    return ''+pkg+'';
}

function setup_copy_to_clipboard(obj, urls) {
    var items = [];
    var len = urls.length;
    for (var i=0; i<len; i++) {
        items.push($(urls[i]).text());
    }
    obj.data('urls', items.join("\n"));

    obj.mouseover(function() {
        clip.setText($(this).data('urls'));
        if (clip.div) {
            clip.receiveEvent('mouseout', null);
            clip.reposition(this);
        }
        else {
            clip.glue(this);
        }
        clip.receiveEvent('mouseover', null);
        var self = this;
        clip.addEventListener('onComplete', function() {
            $(self).text('copied!');
        });
        clip.addEventListener('onMouseOut', function() {
            $(self).text('copy to clipboard');
        });
    });
}

function show_loader(obj, text) {
    if (text == undefined) {
        text = 'loading..';
    }

    obj.html('

 '+text+'

');
    obj.show();
}

var ph = {
    install: {
        packages: [],

        _add: function(pkgs) {
            var items = pkgs.split(" ");
            var len = items.length;
            for (var i=0; i<len; i++) {
                var item = items[i];
                if ((item.length > 0) && (this.packages.indexOf(item) == -1)) {
                    this.packages.push(item);
                    ph.search.mark(item);
                }
            }
        },

        _remove: function(pkg) {
            var pos = this.packages.indexOf(pkg);
            if (pos >= 0) {
                this.packages.splice(pos, 1);
                ph.search.unmark(pkg);
            }
        },

        _clear: function() {
            this.packages = [];
            ph.search.update_marks();
        },

        update_list: function() {
            var obj = $('#install-package-list ul');
            var html = '';
            var len = this.packages.length;
            for (var i=0; i<len; i++) {
                var pkg = this.packages[i];
                html += '
'+create_show_package_link(pkg);
                html += 'x
 ';
            }
            obj.html(html);
            if (len > 0) {
                $('#install-package-button').show();
                $('#install-package-list').show();
            }
            else {
                $('#install-package-button').hide();
                $('#install-package-list').hide();
            }
        },

        add_form: function() {
            var pkgs = $('#install-package-add')[0].value;
            this.add(pkgs);
            $('#install-package-add').select();
        },

        add: function(pkgs) {
            this._add(pkgs);
            this.update_list();
        },

        remove: function(pkg) {
            this._remove(pkg);
            this.update_list();
        },

        clear: function() {
            this._clear();
            this.update_list();
            $('#install-package-add').select();
        },

        _create_package_list: function(items, title) {
            if (items == undefined) { return ''; }
            var len = items.length;
            if (len == 0) { return ''; }

            var html = '';
            html += '

'+title+'
';

            var list = [];
            for (var i=0; i<len; i++) {
                list.push(create_show_package_link(items[i]));
            }

            html += '
' + list.join(', ') + '
';

            html += '
';
            return html;
        },

        show: function(data, target) {
            if (target == undefined) {
                target = '#install-result';
            }

            var obj = $(target);
            var type = data.type;
            var data = data.data;
            var html = '';

            obj.html('

');
            obj = obj.find('.install-result');

            var pkgs = data.packages.join(' ');

            if (type == 'install') {
                html += '
Installation result for '+pkgs+':
';
            }
            else if (type == "upgrade") {
                html += '
Result of upgrade operation:
';
            }
            else if (type == "dist-upgrade") {
                html += '
Result of dist-upgrade operation:
';
            }

            if (data.errors.length > 0) {
                html += '

Unable to install. Error messages:

';
                var len = data.errors.length;
                for (var i=0; i<len; i++) {
                    html += '
'+data.errors[i]+'
';
                }
                html += '

';
                obj.html(html);
            }
            else {
                html += '

';
                obj.html(html);

                var head = obj.find('.head');
                var side = obj.find('.side');
                var main = obj.find('.main');

                // Already the newest version
                if (data.newest.length > 0) {
                    var items = [];
                    var len = data.newest.length;
                    for (var i=0; i<len; i++) {
                        items.push(create_show_package_link(data.newest[i]));
                    }
                    html = '
Already the newest version: ' + items.join(', ') + '
';
                    head.html(html);
                }

                // URL list
                if (data.urls.length > 0) {
                    html = '';
                    html += '
URLs
';
                    html += '
 — copy to clipboard
';
                    html += '
';

                    var len = data.urls.length;
                    for (var i=0; i<len; i++) {
                        var item = data.urls[i];
                        var url = item[0];
                        var deb = item[1];
                        var size = item[2];
                        var hash = item[3];
                        var hash_format = item[4];
                        html += '
'+url+'
';
                    }

                    html += '
';
                    main.html(html);

                    setup_copy_to_clipboard(main.find('p.copy span'), main.find('ul.urls li'));
                }

                // install

                html = '';
                html += this._create_package_list(data.install, 'To Be Installed');
                html += this._create_package_list(data.upgrade, 'To Be Upgraded');
                html += this._create_package_list(data.recommended, 'Recommended');
                html += this._create_package_list(data.suggested, 'Suggested');

                side.html(html);
            }

            obj.append('
');
            obj.show();
        },

        start: function() {
            var packages = this.packages.join(" ");
            var self = this;
            show_loader($('#install-result'));
            $.ajax({
                type: 'POST',
                url: 'install/?format=json',
                dataType: 'json',
                data: {packages: packages},
                complete: function(xhr, stat) {
                    console.log('complete.', 'stat:', stat);
                },
                success: function(data, stat) {
                    self.show(data);
                }
            });
        }
    },

    show: function(pkg) {
        var dialog = $('#dialog-package-show');
        dialog.dialog('open');
        show_loader(dialog);
        $.ajax({
            url: 'show/'+pkg+'/?format=json',
            method: 'GET',
            dataType: 'json',
            success: function(data, stat) {
                if (data.data.package == null) {
                    var html = '';
                    html += '

No package information for '+pkg+'

';
                    dialog.html(html);
                }
                else {
                    pkg = data.data.package;

                    var checked = '';
                    if (ph.install.packages.indexOf(pkg) >= 0) {
                        checked = 'checked="checked"';
                    }

                    var html = '';
                    html += '
<input type="checkbox" '+checked+' onclick="profile.search.toggle(this, \''+pkg+'\')"/> marked
';
                    html += '
'+data.data.sdesc+'
';
                    html += '
'+data.data.desc+'
';
                    html += '
';

                    var table = dialog.find('table');
                    var info = data.data.data;
                    var len = info.length;
                    for (var i=0; i<len; i++) {
                        var key = info[i][0];
                        var value = htmlentities(info[i][1]);
                        if (key != 'Description') {
                            html += '
'+key+'	'+value+'
';
                        }
                    }
                    html += '
';

                    dialog.html(html);
                }

                dialog.dialog('option', 'position', ['center', 25]);
                dialog.dialog('option', 'title', pkg);
            },

            error: function(xhr, stat, err) {
                if (xhr.status == 404) {
                    var html = '';
                    html += '

Package not found: '+pkg+'

';
                    dialog.html(html);
                }
            },
        });
    },

    search: {

        show: function(query, data) {
            var items = data.data.items;
            var len = items.length;
            var obj = $('#search-result');

            if (len == 0) {
                var html = '';
                html += '
No package found. Please try another keyword.
';
                obj.html(html);
            }
            else {
                var html = '';
                html += '
Search result for '+query+':
';
                html += '

';
                obj.html(html);
                var table = obj.find('table');
                table.append('
	Package	Description
');
                for (var i=0; i<len; i++) {
                    var pkg = items[i][0];
                    var desc = items[i][1];
                    var pkglink = create_show_package_link(pkg);
                    var addlink = '';
                    var checked = 'checked="checked"';
                    if (ph.install.packages.indexOf(pkg) == -1) {
                        checked = '';
                    }
                    var check = '<input type="checkbox" '+checked+'" onclick="profile.search.toggle(this, \''+pkg+'\')" rel="'+pkg+'"/>';
                    table.append('
'+check+'	'+pkglink+'	'+desc+'
');
                }
            }
            obj.show();
        },

        toggle: function(src, pkg) {
            if (src.checked) {
                this._skip = true;
                ph.install.add(pkg);
            }
            else {
                this._skip = true;
                ph.install.remove(pkg);
            }
        },

        mark: function(pkg, checked) {
            if (checked == undefined) {
                checked = true;
            }

            var obj = $('#search-result table.search');
            var check = obj.find('input[type="checkbox"][rel="'+pkg+'"]');
            if (check.length > 0) {
                check[0].checked = checked;
            }
        },

        unmark: function(pkg) {
            this.mark(pkg, false);
        },

        update_marks: function() {
            if (this._skip == true) { this._skip = false; return; }
            var obj = $('#search-result table.search');
            var items = obj.find('input[type="checkbox"]');
            var len = items.length;
            for (var i=0; i<len; i++) {
                items[i].checked = false;
            }

            var pkgs = ph.install.packages;
            len = pkgs.length;
            for (var i=0; i<len; i++) {
                this.mark(pkgs[i]);
            }
        },

        start: function(f) {
            var query = f.packages.value;
            var self = this;
            show_loader($('#search-result'));
            $.ajax({
                type: 'POST',
                url: 'search/?format=json',
                dataType: 'json',
                data: {packages: query},
                complete: function(xhr, stat) {
                    console.log('complete');
                    console.log('stat:', stat);
                },
                success: function(data, stat) {
                    self.show(query, data);
                }
            });
        }
    },

    dist_upgrade: {
        start: function() {
            ph.upgrade._start('dist-upgrade');
        }
    },

    upgrade: {
        start: function() {
            this._start('upgrade');
        },

        _start: function(path) {
            show_loader($('#upgrade-result'));
            $.ajax({
                type: 'POST',
                url: path + '/?format=json',
                dataType: 'json',
                complete: function(xhr, stat) {
                    console.log('complete.', 'stat:', stat);
                },
                success: function(data, stat) {
                    ph.install.show(data, '#upgrade-result');
                }
            });
        }
    },

    update: {
        start: function(sender) {
            var btn = $(sender).find('input[type="submit"]');
            btn.attr('disabled', 'disabled');
            btn.after(' updating..');

            $.ajax({
                type: 'POST',
                url: 'update/',
                dataType: 'text',
                complete: function(xhr, stat) {
                },
                success: function(data, stat) {
                    btn.attr('disabled', '');
                    console.log(window.location.href);
                    window.location.reload();
                },
            });
        }
    },

    status: {
        start: function(sender) {
            var btn = $(sender).find('input[type="submit"]');
            btn.attr('disabled', 'disabled');
            btn.after(' uploading..');
            $('#dialog-status-upload').bind('dialogbeforeclose', function() {
                return false;
            });
        }
    },

    init: function() {
        this._init_dialogs();
        this._init_tabs();
    },

    _init_dialogs: function() {
        $('.dialog').dialog({autoOpen: false, modal: true});
        $('#dialog-status-upload').dialog('option', 'width', 500);
        $('#dialog-sources').dialog('option', 'width', 500);
        $('#dialog-package-show').dialog('option', 'width', 700);
        $('#dialog-package-show').dialog('option', 'maxHeight', 500);
    },

    _init_tabs: function() {
        $('.tabs').tabs();
    }
}

this.profile = ph;
})();

function show_dialog(s) {
    $(s).dialog('open');
}
function htmlentities(txt) {
    txt = txt.replace(/</g, '<');
    txt = txt.replace(/>/g, '>');
    return txt;
}
<|endoftext|>


<commit_before>'use strict';

module.exports = function (stamp) {
  return {
    allow: (!(/^arm/).test(stamp.a)) // TODO fabricator failed with SIGKILL. maybe 500 mb mem droplet is too weak?
  };
};
<commit_msg>seems geoip-lite is ok in travis and in droplets. now arm is the aim<commit_after>'use strict';

module.exports = function (stamp) {
  return {
    allow: (!(/^arm/).test(stamp.a)) // TODO memory consumption aim is to compile geoip-lite on arm
  };
};
<|endoftext|>


<commit_before>/* global browser, window, document, localStorage */
const CONTAINER_HIDE_SRC = '/img/container-hide.svg';
const CONTAINER_UNHIDE_SRC = '/img/container-unhide.svg';

function showOrHideContainerTabs(userContextId, hasHiddenTabs) {
  return new Promise((resolve, reject) => {
    const hideorshowIcon = document.querySelector(`#uci-${userContextId}-hideorshow-icon`);

    browser.runtime.sendMessage({
      method: hasHiddenTabs ? 'showTabs' : 'hideTabs',
      userContextId: userContextId
    }).then(() => {
      return browser.runtime.sendMessage({
        method: 'getIdentity',
        userContextId: userContextId
      });
    }).then((identity) => {
      if (!identity.hasHiddenTabs && !identity.hasOpenTabs) {
        hideorshowIcon.style.display = "none";
      } else {
        hideorshowIcon.style.display = "";
      }

      hideorshowIcon.src = hasHiddenTabs ? CONTAINER_HIDE_SRC : CONTAINER_UNHIDE_SRC;
    }).then(resolve);
  });
}

if (localStorage.getItem('onboarded2')) {
  for (const element of document.querySelectorAll('.onboarding')) {
    element.classList.add('hide');
  }
  document.querySelector('#container-panel').classList.remove('hide');
} else if (localStorage.getItem('onboarded1')) {
  document.querySelector('.onboarding-panel-1').classList.add('hide');
  document.querySelector('#container-panel').classList.add('hide');
} else {
  document.querySelector('.onboarding-panel-2').classList.add('hide');
  document.querySelector('#container-panel').classList.add('hide');
}

document.querySelector('#onboarding-next-button').addEventListener('click', ()=> {
  localStorage.setItem('onboarded1', true);
  document.querySelector('.onboarding-panel-2').classList.remove('hide');
  document.querySelector('.onboarding-panel-1').classList.add('hide');
  document.querySelector('#container-panel').classList.add('hide');
});

document.querySelector('#onboarding-done-button').addEventListener('click', ()=> {
  localStorage.setItem('onboarded2', true);
  document.querySelector('.onboarding-panel-1').classList.add('hide');
  document.querySelector('.onboarding-panel-2').classList.add('hide');
  document.querySelector('#container-panel').classList.remove('hide');
});

browser.runtime.sendMessage({method: 'queryIdentities'}).then(identities=> {
  const identitiesListElement = document.querySelector('.identities-list');

  identities.forEach(identity=> {
    let hideOrShowIconSrc = CONTAINER_HIDE_SRC;

    if (identity.hasHiddenTabs) {
      hideOrShowIconSrc = CONTAINER_UNHIDE_SRC;
    }

    const identityRow = `

      ${identity.name}

      >

`;

    identitiesListElement.innerHTML += identityRow;

    // No tabs, no icon.
    if (!identity.hasHiddenTabs && !identity.hasOpenTabs) {
      const hideorshowIcon = document.querySelector(`#uci-${identity.userContextId}-hideorshow-icon`);
      hideorshowIcon.style.display = "none";
    }
  });

  const rows = identitiesListElement.querySelectorAll('tr');

  rows.forEach(row=> {
    row.addEventListener('click', e=> {
      const userContextId = e.target.parentElement.parentElement.dataset.identityCookieStoreId;

      if (e.target.matches('.hideorshow-icon')) {
        browser.runtime.sendMessage({
          method: 'getIdentity',
          userContextId
        }).then(identity=> {
          showOrHideContainerTabs(userContextId, identity.hasHiddenTabs);
        });
      } else if (e.target.matches('.newtab-icon')) {
        showOrHideContainerTabs(userContextId, true).then(() => {
          browser.runtime.sendMessage({
            method: 'openTab',
            userContextId: userContextId})
          .then(() => {
            window.close();
          });
        });
      }
    });
  });
});

document.querySelector('#edit-containers-link').addEventListener('click', ()=> {
  browser.runtime.sendMessage({
    method: 'openTab',
    url: "about:preferences#containers"
  }).then(()=> {
    window.close();
  });
});

document.querySelector('#sort-containers-link').addEventListener('click', ()=> {
  browser.runtime.sendMessage({
    method: 'sortTabs'
  }).then(()=> {
    window.close();
  });
});
<commit_msg>Let's use a DocumentFragment instead innerHTML<commit_after>/* global browser, window, document, localStorage */
const CONTAINER_HIDE_SRC = '/img/container-hide.svg';
const CONTAINER_UNHIDE_SRC = '/img/container-unhide.svg';

function showOrHideContainerTabs(userContextId, hasHiddenTabs) {
  // Let's show/hide the tabs
  return browser.runtime.sendMessage({
    method: hasHiddenTabs ? 'showTabs' : 'hideTabs',
    userContextId: userContextId
  })
  // We need to retrieve the new identity configuration in order to choose the
  // correct icon.
  .then(() => {
    return browser.runtime.sendMessage({
      method: 'getIdentity',
      userContextId: userContextId
    });
  })
  // Let's update the icon.
  .then((identity) => {
    let hideorshowIcon = document.querySelector(`#uci-${identity.userContextId}-hideorshow-icon`);
    if (!identity.hasHiddenTabs && !identity.hasOpenTabs) {
      hideorshowIcon.style.display = "none";
    } else {
      hideorshowIcon.style.display = "";
    }

    hideorshowIcon.src = hasHiddenTabs ? CONTAINER_HIDE_SRC : CONTAINER_UNHIDE_SRC;

    // The new identity is returned.
    return identity;
  });
}

if (localStorage.getItem('onboarded2')) {
  for (let element of document.querySelectorAll('.onboarding')) {
    element.classList.add('hide');
  }
  document.querySelector('#container-panel').classList.remove('hide');
} else if (localStorage.getItem('onboarded1')) {
  document.querySelector('.onboarding-panel-1').classList.add('hide');
  document.querySelector('#container-panel').classList.add('hide');
} else {
  document.querySelector('.onboarding-panel-2').classList.add('hide');
  document.querySelector('#container-panel').classList.add('hide');
}

document.querySelector('#onboarding-next-button').addEventListener('click', () => {
  localStorage.setItem('onboarded1', true);
  document.querySelector('.onboarding-panel-2').classList.remove('hide');
  document.querySelector('.onboarding-panel-1').classList.add('hide');
  document.querySelector('#container-panel').classList.add('hide');
});

document.querySelector('#onboarding-done-button').addEventListener('click', () => {
  localStorage.setItem('onboarded2', true);
  document.querySelector('.onboarding-panel-1').classList.add('hide');
  document.querySelector('.onboarding-panel-2').classList.add('hide');
  document.querySelector('#container-panel').classList.remove('hide');
});

browser.runtime.sendMessage({method: 'queryIdentities'}).then(identities => {
  let fragment = document.createDocumentFragment();

  identities.forEach(identity => {
    let hideOrShowIconSrc = CONTAINER_HIDE_SRC;

    if (identity.hasHiddenTabs) {
      hideOrShowIconSrc = CONTAINER_UNHIDE_SRC;
    }

    let tr = document.createElement('tr');
    fragment.appendChild(tr);
    tr.setAttribute('data-identity-cookie-store-id', identity.userContextId);
    tr.innerHTML = `

      ${identity.name}

      >	`;

    // No tabs, no icon.
    if (!identity.hasHiddenTabs && !identity.hasOpenTabs) {
      let hideorshowIcon = fragment.querySelector(`#uci-${identity.userContextId}-hideorshow-icon`);
      hideorshowIcon.style.display = "none";
    }

    tr.addEventListener('click', e => {
      if (e.target.matches('.hideorshow-icon')) {
        showOrHideContainerTabs(identity.userContextId,
                                identity.hasHiddenTabs).then(i => {
          identity = i
        });
      } else if (e.target.matches('.newtab-icon')) {
        showOrHideContainerTabs(identity.userContextId, true).then(() => {
          browser.runtime.sendMessage({
            method: 'openTab',
            userContextId: identity.userContextId,
          }).then(() => {
            window.close();
          });
        });
      }
    });
  });

  document.querySelector('.identities-list').appendChild(fragment);
});

document.querySelector('#edit-containers-link').addEventListener('click', () => {
  browser.runtime.sendMessage({
    method: 'openTab',
    url: "about:preferences#containers"
  }).then(() => {
    window.close();
  });
});

document.querySelector('#sort-containers-link').addEventListener('click', () => {
  browser.runtime.sendMessage({
    method: 'sortTabs'
  }).then(() => {
    window.close();
  });
});
<|endoftext|>


<commit_before>'use strict'

const Path = require('path')
const Webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ExtractSASS = new ExtractTextPlugin('styles/bundle.css')

module.exports = options => {

  const webpackConfig = {
    devtool: options.devtool,
    entry: [
      `webpack-dev-server/client?http://localhost:${options.port}`,
      'webpack/hot/dev-server',
      './src/main.js'
    ],
    output: {
      path: Path.join(__dirname, 'dist'),
      filename: 'd3-playbooks.base.min.js'
    },
    plugins: [
      new Webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development')
        }
      }),
      new HtmlWebpackPlugin({
        template: './src/index.html'
      })
    ],
    module: {
      loaders: [{
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
      }]
    }
  }

  if (options.isProduction) {
    webpackConfig.entry = ['./src/main.js']

    // external dependencies
    webpackConfig.externals = {
      d3: 'd3',
      Papa: 'papaparse'
    }

    webpackConfig.plugins.push(
      new Webpack.optimize.OccurenceOrderPlugin(),
      new Webpack.optimize.UglifyJsPlugin({
        compressor: {
          warnings: false
        }
      }),
      ExtractSASS
    )

    webpackConfig.module.loaders.push({
      test: /\.scss$/i,
      loader: ExtractSASS.extract(['css', 'sass'])
    })

  } else {
    webpackConfig.plugins.push(
      new Webpack.HotModuleReplacementPlugin(),
      new Webpack.ProvidePlugin({d3: 'd3'})
    )

    webpackConfig.module.loaders.push({
      test: /\.scss$/i,
      loaders: ['style', 'css', 'sass']
    }, {
      test: /\.js$/,
      loader: 'eslint',
      exclude: /node_modules/
    })

    webpackConfig.devServer = {
      contentBase: './dist',
      hot: true,
      port: options.port,
      inline: true,
      progress: true
    }
  }

  return webpackConfig

}
<commit_msg>refactor: include css into main js build<commit_after>'use strict'

const Path = require('path')
const Webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = options => {

  const webpackConfig = {
    devtool: options.devtool,
    entry: [
      `webpack-dev-server/client?http://localhost:${options.port}`,
      'webpack/hot/dev-server',
      './src/main.js'
    ],
    output: {
      path: Path.join(__dirname, 'dist'),
      filename: 'd3-playbooks.base.min.js'
    },
    plugins: [
      new Webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development')
        }
      }),
      new HtmlWebpackPlugin({
        template: './src/index.html'
      })
    ],
    module: {
      loaders: [{
        test: /\.scss$/i,
        loaders: ['style', 'css', 'sass']
      }, {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel',
        query: {
          presets: ['es2015']
        }
      }]
    }
  }

  if (options.isProduction) {
    webpackConfig.entry = ['./src/main.js']

    // external dependencies
    webpackConfig.externals = {
      d3: 'd3',
      Papa: 'papaparse'
    }

    webpackConfig.plugins.push(
      new Webpack.optimize.OccurenceOrderPlugin(),
      new Webpack.optimize.UglifyJsPlugin({
        compressor: {
          warnings: false
        }
      })
    )

  } else {
    webpackConfig.plugins.push(
      new Webpack.HotModuleReplacementPlugin(),
      new Webpack.ProvidePlugin({d3: 'd3'})
    )

    webpackConfig.module.loaders.push({
      test: /\.js$/,
      loader: 'eslint',
      exclude: /node_modules/
    })

    webpackConfig.devServer = {
      contentBase: './dist',
      hot: true,
      port: options.port,
      inline: true,
      progress: true
    }
  }

  return webpackConfig

}
<|endoftext|>


<commit_before>/* eslint-disable max-lines */

// In this version increase:
// 1. set schema version to 12
// 2. Remove orphan event i.e. entry events whose entry has been deleted.
//    Do this to simplify entry event refactor.
// 3. Drop possible 'attachments' collections from earlier failed migration.
// 4. refactor entries and entry events
// 5. refactor locations by adding published prop
// 6. refactor locations by adding createdAt prop
// 7. select thumbnails for each location and add thumbnail prop
// 8. remove visits-related user properties
// 9. add activeAt property to entries
//
// Also, new indices were made and thus 'npm run migrate' is needed.

const db = require('georap-db');
const asyn = require('async');
const clone = require('clone');
const schema = require('../../lib/schema');
const iter = require('../../lib/iter');
const removeOrphanEvents = require('./removeOrphanEvents');
const migrateEntry = require('./migrateEntry');
const getThumbnail = require('./getThumbnail');
const addActiveAt = require('./addActiveAt');
const removeVisitStatistics = require('./removeVisitStatistics');

const FROM_VERSION = 11;
const TO_VERSION = FROM_VERSION + 1;

// Steps to be executed with asyn.eachSeries in the given order.
// The parameter 'nextStep' is function (err) that must be called in the end of
// each step.
const substeps = [

  function updateSchema(nextStep) {
    console.log('1. Updating schema version tag...');

    schema.setVersion(TO_VERSION, (err) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  Schema version tag created:', TO_VERSION);
      return nextStep(null);
    });
  },

  function removeOrphan(nextStep) {
    console.log('2. Remove orphan events...');

    removeOrphanEvents((err, numRemoved) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + numRemoved + ' orphan entry events were removed.');
      return nextStep();
    });
  },

  function dropFailed(nextStep) {
    console.log('3. Drop possible attachments collection...');

    db.get().dropCollection('attachments', (err, wasDropped) => {
      if (err) {
        return nextStep(err);
      }
      if (wasDropped) {
        console.log('  The attachments collection was dropped successfully.');
      } else {
        console.log('  No need to drop collections.');
      }
      return nextStep();
    });
  },

  function refactorEntries(nextStep) {
    console.log('4. Refactor entries and create attachments...');

    db.collection('entries')
      .find()
      .project({
        _id: 1,
      })
      .toArray((err, entryIds) => {
        if (err) {
          return nextStep(err);
        }

        asyn.eachSeries(entryIds, (wrappedEntryId, eachNext) => {
          migrateEntry(wrappedEntryId._id, eachNext);
        }, (eachErr) => {
          if (eachErr) {
            return nextStep(eachErr);
          }
          console.log('  ' + entryIds.length + ' entries were migrated.');
          return nextStep();
        });
      });
  },

  function migrateLocations(nextStep) {
    console.log('5. Add published prop and ensure visits prop in locations...');

    const coll = db.collection('locations');

    iter.updateEach(coll, (origLoc, iterNext) => {
      const loc = clone(origLoc);
      loc.visits = [];
      loc.published = false;
      return iterNext(null, loc);
    }, (err, iterResults) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + iterResults.numDocuments + ' locations processed ' +
        'successfully.');
      console.log('  ' + iterResults.numUpdated + ' locations updated, ' +
        (iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
        'need an update');

      return nextStep();
    });
  },

  function addCreatedAt(nextStep) {
    console.log('6. Add createdAt prop to each location...');

    const coll = db.collection('locations');

    iter.updateEach(coll, (origLoc, iterNext) => {
      db.collection('events').findOne({
        locationId: origLoc._id,
        type: 'location_created',
      }, (err, locEv) => {
        if (err) {
          return iterNext(err);
        }

        if (!locEv) {
          const msg = 'Missing location_created event for ' + origLoc._id;
          return iterNext(new Error(msg));
        }

        const loc = clone(origLoc);
        loc.createdAt = locEv.time;
        return iterNext(null, loc);
      });
    }, (err, iterResults) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + iterResults.numDocuments + ' locations processed ' +
        'successfully.');
      console.log('  ' + iterResults.numUpdated + ' locations updated, ' +
        (iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
        'need an update');

      return nextStep();
    });
  },

  function addThumbnail(nextStep) {
    console.log('7. Add thumbnail to each location...');

    const coll = db.collection('locations');

    iter.updateEach(coll, (origLoc, iterNext) => {
      getThumbnail(origLoc._id, (err, attachment) => {
        if (err) {
          return iterNext(err);
        }

        const loc = clone(origLoc);

        if (attachment) {
          loc.thumbnail = attachment.key;
        } else {
          // No image attachment. Default path.
          loc.thumbnail = null;
        }

        return iterNext(null, loc);
      });
    }, (err, iterResults) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + iterResults.numDocuments + ' locations processed ' +
        'successfully.');
      console.log('  ' + iterResults.numUpdated + ' locations updated, ' +
        (iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
        'need an update');

      return nextStep();
    });
  },

  // Remove outdated statistics from users
  removeVisitStatistics,

  // Add activeAt property to entries
  addActiveAt,

];

exports.run = (callback) => {
  // Parameters
  //   callback
  //     function (err)

  console.log();
  console.log('### Step v' + FROM_VERSION + ' to v' + TO_VERSION + ' ###');

  asyn.series(substeps, (err) => {
    if (err) {
      console.error(err);
      return callback(err);
    }

    return callback();
  });
};
<commit_msg>Remove visits from locs during migration<commit_after>/* eslint-disable max-lines */

// In this version increase:
// 1. set schema version to 12
// 2. Remove orphan event i.e. entry events whose entry has been deleted.
//    Do this to simplify entry event refactor.
// 3. Drop possible 'attachments' collections from earlier failed migration.
// 4. refactor entries and entry events
// 5. refactor locations by adding published prop
// 6. refactor locations by adding createdAt prop
// 7. select thumbnails for each location and add thumbnail prop
// 8. remove visits-related user properties
// 9. add activeAt property to entries
//
// Also, new indices were made and thus 'npm run migrate' is needed.

const db = require('georap-db');
const asyn = require('async');
const clone = require('clone');
const schema = require('../../lib/schema');
const iter = require('../../lib/iter');
const removeOrphanEvents = require('./removeOrphanEvents');
const migrateEntry = require('./migrateEntry');
const getThumbnail = require('./getThumbnail');
const addActiveAt = require('./addActiveAt');
const removeVisitStatistics = require('./removeVisitStatistics');

const FROM_VERSION = 11;
const TO_VERSION = FROM_VERSION + 1;

// Steps to be executed with asyn.eachSeries in the given order.
// The parameter 'nextStep' is function (err) that must be called in the end of
// each step.
const substeps = [

  function updateSchema(nextStep) {
    console.log('1. Updating schema version tag...');

    schema.setVersion(TO_VERSION, (err) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  Schema version tag created:', TO_VERSION);
      return nextStep(null);
    });
  },

  function removeOrphan(nextStep) {
    console.log('2. Remove orphan events...');

    removeOrphanEvents((err, numRemoved) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + numRemoved + ' orphan entry events were removed.');
      return nextStep();
    });
  },

  function dropFailed(nextStep) {
    console.log('3. Drop possible attachments collection...');

    db.get().dropCollection('attachments', (err, wasDropped) => {
      if (err) {
        return nextStep(err);
      }
      if (wasDropped) {
        console.log('  The attachments collection was dropped successfully.');
      } else {
        console.log('  No need to drop collections.');
      }
      return nextStep();
    });
  },

  function refactorEntries(nextStep) {
    console.log('4. Refactor entries and create attachments...');

    db.collection('entries')
      .find()
      .project({
        _id: 1,
      })
      .toArray((err, entryIds) => {
        if (err) {
          return nextStep(err);
        }

        asyn.eachSeries(entryIds, (wrappedEntryId, eachNext) => {
          migrateEntry(wrappedEntryId._id, eachNext);
        }, (eachErr) => {
          if (eachErr) {
            return nextStep(eachErr);
          }
          console.log('  ' + entryIds.length + ' entries were migrated.');
          return nextStep();
        });
      });
  },

  function migrateLocations(nextStep) {
    console.log('5. Add published prop and remove visits prop in locations...');

    const coll = db.collection('locations');

    iter.updateEach(coll, (origLoc, iterNext) => {
      const loc = clone(origLoc);
      delete loc.visits;
      loc.published = false;
      return iterNext(null, loc);
    }, (err, iterResults) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + iterResults.numDocuments + ' locations processed ' +
        'successfully.');
      console.log('  ' + iterResults.numUpdated + ' locations updated, ' +
        (iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
        'need an update');

      return nextStep();
    });
  },

  function addCreatedAt(nextStep) {
    console.log('6. Add createdAt prop to each location...');

    const coll = db.collection('locations');

    iter.updateEach(coll, (origLoc, iterNext) => {
      db.collection('events').findOne({
        locationId: origLoc._id,
        type: 'location_created',
      }, (err, locEv) => {
        if (err) {
          return iterNext(err);
        }

        if (!locEv) {
          const msg = 'Missing location_created event for ' + origLoc._id;
          return iterNext(new Error(msg));
        }

        const loc = clone(origLoc);
        loc.createdAt = locEv.time;
        return iterNext(null, loc);
      });
    }, (err, iterResults) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + iterResults.numDocuments + ' locations processed ' +
        'successfully.');
      console.log('  ' + iterResults.numUpdated + ' locations updated, ' +
        (iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
        'need an update');

      return nextStep();
    });
  },

  function addThumbnail(nextStep) {
    console.log('7. Add thumbnail to each location...');

    const coll = db.collection('locations');

    iter.updateEach(coll, (origLoc, iterNext) => {
      getThumbnail(origLoc._id, (err, attachment) => {
        if (err) {
          return iterNext(err);
        }

        const loc = clone(origLoc);

        if (attachment) {
          loc.thumbnail = attachment.key;
        } else {
          // No image attachment. Default path.
          loc.thumbnail = null;
        }

        return iterNext(null, loc);
      });
    }, (err, iterResults) => {
      if (err) {
        return nextStep(err);
      }

      console.log('  ' + iterResults.numDocuments + ' locations processed ' +
        'successfully.');
      console.log('  ' + iterResults.numUpdated + ' locations updated, ' +
        (iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
        'need an update');

      return nextStep();
    });
  },

  // Remove outdated statistics from users
  removeVisitStatistics,

  // Add activeAt property to entries
  addActiveAt,

];

exports.run = (callback) => {
  // Parameters
  //   callback
  //     function (err)

  console.log();
  console.log('### Step v' + FROM_VERSION + ' to v' + TO_VERSION + ' ###');

  asyn.series(substeps, (err) => {
    if (err) {
      console.error(err);
      return callback(err);
    }

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


<commit_before>'use strict';

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const NpmImportPlugin = require('less-plugin-npm-import');

const banner = require('./dev/banner');

const config = {

  context: __dirname,

  devtool: 'source-map',

  output: {
    // if path is not set to '/build' => Error invalid argument in MemoryFileSystem.js
    path: '/build',
    filename: 'js/[name].js'
  },

  resolve: {
    root: path.resolve('./src'),
    extensions: ['', '.js']
  },

  debug: false,
  cache: false,
  watch: false,

  module: {

    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /(bower_components|node_modules)/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css')
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract(
          'style',
          'css?limit=32768?name=images/[name].[ext]!postcss!less',
          {
            publicPath: '../'
          }
        )
      },
      {
        // test should match the following:
        //
        //  '../fonts/availity-font.eot?18704236'
        //  '../fonts/availity-font.eot'
        //
        test: /\.(ttf|woff|eot|svg).*/,
        loader: 'file?name=fonts/[name].[ext]'
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        loader: 'url?limit=32768?name=images/[name].[ext]'
      },
      {
        test: /tests.*\.html$/,
        loader: 'html'
      },
      {
        // Files ending in *.html will be loaded into Angular $templaceCache relative to 'lib' folder.
        test: /\.html$/,
        exclude: /tests/,
        loader: `ngtemplate?relativeTo=${process.cwd()}/!html`
      }
    ]
  },

  postcss() {
    return [autoprefixer({browsers: ['last 2 versions', 'ie 9-11']})];
  },

  lessLoader: {
    lessPlugins: [
      new NpmImportPlugin({
        prefix: '~'
      })
    ]
  },

  plugins: [

    new webpack.BannerPlugin(banner(), {
      exclude: ['vendor']
    }),

    new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),

    new webpack.DefinePlugin({
      APP_VERSION: JSON.stringify('Unknown')
    }),

    new ExtractTextPlugin('css/[name].css', {
      disable: false,
      allChunks: true
    }),

    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery'
    })

  ]
};

module.exports = config;

<commit_msg>force the same jquery in all amd plugins<commit_after>'use strict';

const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const NpmImportPlugin = require('less-plugin-npm-import');

const banner = require('./dev/banner');

const config = {

  context: __dirname,

  devtool: 'source-map',

  output: {
    // if path is not set to '/build' => Error invalid argument in MemoryFileSystem.js
    path: '/build',
    filename: 'js/[name].js'
  },

  resolve: {
    root: path.resolve('./src'),
    extensions: ['', '.js'],
    alias: {
      // without this $.fn.datepicker will be undefined.  Datepicker plugin
      // tried to load it's own version of jQuery
      jquery: require.resolve('jquery')
    }
  },

  debug: false,
  cache: false,
  watch: false,

  module: {

    loaders: [
      {
        test: /\.js$/,
        loader: 'babel',
        exclude: /(bower_components|node_modules)/
      },
      {
        test: /\.json$/,
        loader: 'json'
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('style', 'css')
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract(
          'style',
          'css?limit=32768?name=images/[name].[ext]!postcss!less',
          {
            publicPath: '../'
          }
        )
      },
      {
        // test should match the following:
        //
        //  '../fonts/availity-font.eot?18704236'
        //  '../fonts/availity-font.eot'
        //
        test: /\.(ttf|woff|eot|svg).*/,
        loader: 'file?name=fonts/[name].[ext]'
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        loader: 'url?limit=32768?name=images/[name].[ext]'
      },
      {
        test: /tests.*\.html$/,
        loader: 'html'
      },
      {
        // Files ending in *.html will be loaded into Angular $templaceCache relative to 'lib' folder.
        test: /\.html$/,
        exclude: /tests/,
        loader: `ngtemplate?relativeTo=${process.cwd()}/!html`
      }
    ]
  },

  postcss() {
    return [autoprefixer({browsers: ['last 2 versions', 'ie 9-11']})];
  },

  lessLoader: {
    lessPlugins: [
      new NpmImportPlugin({
        prefix: '~'
      })
    ]
  },

  plugins: [

    new webpack.BannerPlugin(banner(), {
      exclude: ['vendor']
    }),

    new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]),

    new webpack.DefinePlugin({
      APP_VERSION: JSON.stringify('Unknown')
    }),

    new ExtractTextPlugin('css/[name].css', {
      disable: false,
      allChunks: true
    }),

    new webpack.ProvidePlugin({
      'jQuery': 'jquery',
      'window.jQuery': 'jquery',
      'jquery': 'jquery',
      'window.jquery': 'jquery',
      '$': 'jquery',
      'window.$': 'jquery'
    })

  ]
};

module.exports = config;

<|endoftext|>


<commit_before>const _ = require('lodash');
// const marked = require('marked');
// this file is in the front end part of the code. This We should create a place for code that is required by both the front end and the back end, to avoid me inadvertently breaking this module when working on the frontend
// const { getCreatedBy, getContent } = require( './client/src/shared/requestUtils');
const { newCommentEmailBody, newIssueEmailBody, closedIssueEmailBody, reopenedIssueEmailBody } = require( './emailBodies');

const processIssues = (action, issue, projectName, requestLink) => {
  switch (action) {
    case 'opened':
      return {
        subject: `Re: ${issue.title}`,
        content: newIssueEmailBody(issue, requestLink)
      };
      break;
    case 'closed':
      return {
        subject: `Re: ${issue.title}`,
        content: closedIssueEmailBody(issue, requestLink)
      };
      break;
    case 'reopened':
      return {
        subject: `Re: ${issue.title}`,
        content: reopenedIssueEmailBody(issue, requestLink)
//         (
//           `
//
Your request for ${projectName}:

//
${issue.title}

//
has been reopened.
`
//         )
      };
      break;
    default:
      console.log(`RequestApp: unsupported action: ${action}`);
      return { }
      break;
  }
};

const processComment = (action, issue, comment, projectName, requestLink) => {
  switch (action) {
    case 'created':
      return {
        subject: `Re: ${issue.title}`,
        content: newCommentEmailBody(issue, comment, requestLink)
      };
      break;
    default:
      console.log(`RequestApp: unsupported action: ${action}`);
      return { }
      break;
  }
};

const getNotificationText = (eventType, payload, projectName, requestLink) => {
  if (eventType === 'issues') {
    return processIssues(payload.action, payload.issue, projectName, requestLink);
  } else if (eventType === 'issue_comment') {
    return processComment(payload.action, payload.issue, payload.comment, projectName, requestLink);
  } else {
    throw new Error(`invalid eventType:${eventType} only "issues" and "issue_comment" are currently supported.`);
  }
};

const getRequestUrl = (issueNumber, project, appRootUrl) => {
  return `${appRootUrl}/requests/${project.organisation}/${project.repository}/${encodeURIComponent(project.label)}/${issueNumber}`;
};

const getAppUrl = (project, appRootUrl) => {
  return `${appRootUrl}/requests/${project.organisation}/${project.repository}/${encodeURIComponent(project.label)}`;
};

const findProject = (payload, projects) => {
  const organisation = payload.organization.login;
  const repo = payload.repository.name;
  const labels = payload.issue.labels.map(issue => issue.name);
  const project = _.find(projects, p => p.organisation === organisation && p.repository === repo);
  if (!project) {
    throw new Error(`Unable to find a matching project for issue: ${payload.issue.html_url}, organisation ${organisation}, repo, ${repo}, labels ${JSON.stringify(labels)}. Available projects: ${JSON.stringify(projects)}`);
  }
  return project;
};

module.exports = {
  findProject,
  getRequestUrl,
  getNotificationText
};
<commit_msg>Remove dead wood<commit_after>const _ = require('lodash');
const { newCommentEmailBody, newIssueEmailBody, closedIssueEmailBody, reopenedIssueEmailBody } = require( './emailBodies');

const processIssues = (action, issue, projectName, requestLink) => {
  switch (action) {
    case 'opened':
      return {
        subject: `Re: ${issue.title}`,
        content: newIssueEmailBody(issue, requestLink)
      };
      break;
    case 'closed':
      return {
        subject: `Re: ${issue.title}`,
        content: closedIssueEmailBody(issue, requestLink)
      };
      break;
    case 'reopened':
      return {
        subject: `Re: ${issue.title}`,
        content: reopenedIssueEmailBody(issue, requestLink)
      };
      break;
    default:
      console.log(`RequestApp: unsupported action: ${action}`);
      return { }
      break;
  }
};

const processComment = (action, issue, comment, projectName, requestLink) => {
  switch (action) {
    case 'created':
      return {
        subject: `Re: ${issue.title}`,
        content: newCommentEmailBody(issue, comment, requestLink)
      };
      break;
    default:
      console.log(`RequestApp: unsupported action: ${action}`);
      return { }
      break;
  }
};

const getNotificationText = (eventType, payload, projectName, requestLink) => {
  if (eventType === 'issues') {
    return processIssues(payload.action, payload.issue, projectName, requestLink);
  } else if (eventType === 'issue_comment') {
    return processComment(payload.action, payload.issue, payload.comment, projectName, requestLink);
  } else {
    throw new Error(`invalid eventType:${eventType} only "issues" and "issue_comment" are currently supported.`);
  }
};

const getRequestUrl = (issueNumber, project, appRootUrl) => {
  return `${appRootUrl}/requests/${project.organisation}/${project.repository}/${encodeURIComponent(project.label)}/${issueNumber}`;
};

const getAppUrl = (project, appRootUrl) => {
  return `${appRootUrl}/requests/${project.organisation}/${project.repository}/${encodeURIComponent(project.label)}`;
};

const findProject = (payload, projects) => {
  const organisation = payload.organization.login;
  const repo = payload.repository.name;
  const labels = payload.issue.labels.map(issue => issue.name);
  const project = _.find(projects, p => p.organisation === organisation && p.repository === repo);
  if (!project) {
    throw new Error(`Unable to find a matching project for issue: ${payload.issue.html_url}, organisation ${organisation}, repo, ${repo}, labels ${JSON.stringify(labels)}. Available projects: ${JSON.stringify(projects)}`);
  }
  return project;
};

module.exports = {
  findProject,
  getRequestUrl,
  getNotificationText
};
<|endoftext|>


<commit_before>const { ProvidePlugin } = require('webpack')

module.exports = {
  plugins: [
    new ProvidePlugin({
      PouchDB: 'pouchdb',
      pouchdbFind: 'pouchdb-find',
      pouchdbAdapterCordovaSqlite: 'pouchdb-adapter-cordova-sqlite'
    })
  ]
}
<commit_msg>fix: We copy fonts to the right folder. Waiting for a cozy-script fix<commit_after>const { ProvidePlugin } = require('webpack')
const CopyPlugin = require('copy-webpack-plugin')

module.exports = {
  plugins: [
    new ProvidePlugin({
      PouchDB: 'pouchdb',
      pouchdbFind: 'pouchdb-find',
      pouchdbAdapterCordovaSqlite: 'pouchdb-adapter-cordova-sqlite'
    }),
    new CopyPlugin([
      {
        from: 'src/drive/mobile/assets/fonts/',
        to: 'app/'
      }
    ])
  ]
}
<|endoftext|>


<commit_before>var WEBSOCKET_ADDRESS = 'ws://localhost:8887';
var HISTOGRAM_T = 10;

/**
 * Attempt to establish new websockets connection
 * @param {Function} messageCB onmessage function callback.
 */
function connectWS(messageCB) {
  // Init websockets with globally defined address.
  ws = new WebSocket(WEBSOCKET_ADDRESS);
  ws.onopen = function() {
    // Print a message when connection opens.
    console.log('open on ' + WEBSOCKET_ADDRESS);
  };
  ws.onclose = function() {
    initDone = false;
    // Print a message when connection closes.
    console.log('Websocket closed. Trying to reconnect.');
    // Call this function again (try to reconnect).
    setTimeout(function() {
      connectWS(messageCB);
    }, 1000);
  };
  // Set passed function as onmessage callback.
  ws.onmessage = messageCB;
}

/**
 * Websocket onmessage callback function.
 * @param {Object} e Event (with `data`) passed from server.
 */
function messageRecieved(e) {
  var data = JSON.parse(e.data);
  if (data.message && data.message === 'init' && !initDone) {
    saveChartToImg();
    saveWon();
    colors = data.colors;
    probabilities = data.p;
    displayProbabilites(probabilities, colors);
    initChart(colors);
    ws.send('init-ok');
    initDone = true;
  } else if (data.message && data.message === 'chart') {
    // drawWonChart(data.value);
  } else if (chart && !data.message) {
    updateChart(data);
  }
}

function initDatapoints() {
  if (datapoints) {
    for (var i = 0; i < datapoints.length; i++) {
      datapoints[i].splice(0);
    }
  }
}

function initChart(colors) {
  datapoints = [];
  var chartData = [];
  for (var i = 0; i < 10; i++) {
    datapoints.push([]);
    chartData.push({
      type: "line",
      dataPoints: datapoints[i],
      markerType: "none"
    });
  }
  initDatapoints();

  CanvasJS.addColorSet("graphColors", colors);

  chart = new CanvasJS.Chart("chartContainer", {
    title: {
      text: "Delež barv"
    },
    colorSet: "graphColors",
    height: 500,
    axisX: {
      title: "čas [iteracije]",
      minimum: 0
    },
    axisY: {
      title: "verjetnost",
      minimum: 0,
      maximum: 1.0
    },
    data: chartData
  });

  return chart;
}

function saveWon() {
  try {
    if (datapoints) {
      var i;
      for (i = 0; i < datapoints.length; i++) {
        var y = datapoints[i][datapoints[i].length - 1];
        if (y === 1) {
          break;
        }
      }
      wonIndices.push(i);
    }
  } catch (e) {}
}

function drawWonChart(newData) {
  // if (wonIndices.length === HISTOGRAM_T) {
  //   var numWon = wonIndices.splice(0)
  //     .filter(function(e) {
  //       // if color at index 0 won
  //       return e === 0;
  //     })
  //     .length / HISTOGRAM_T;
  // wonChartData.push({
  //   x: wonChartData.length + 1,
  //   y: Math.log(numWon / (1 - numWon))
  // });
  // wonChartData.push(newData);
  //
  // if(!histogram) {
  //   histogram = new CanvasJS.Chart('wonChartContainer', {
  //     title: {
  //       text: 'Razmerje zmag'
  //     },
  //     data: [{
  //       type: 'column',
  //       dataPoints: wonChartData
  //     }]
  //   });
  // }
  // histogram.render();
}

function saveChartToImg() {
  try {
    if (datapoints) {
      var canvas = document.querySelector("#chartContainer canvas");
      var img = canvas.toDataURL("image/png");
      var imageContainer = document.getElementById("slike");
      var newImage = new Image();
      newImage.src = img;
      imageContainer.appendChild(newImage);
    }
  } catch (e) {}
}

function updateChart(data) {
  var d = data[0],
    lastD = datapoints[0][datapoints[0].length - 1];
  if (d && lastD && d.x < lastD.x) {

    initDatapoints();
  }
  data.map(function(e, i) {
    datapoints[i].push(e);
  });
  chart.render();
}

function displayProbabilites(data, colors) {
  valuesEl.empty();
  for (var i = 0; i < data.length; i++) {
    var p = data[i];
    var c = colors[i];
    valuesEl.append($('<span>')
      .addClass('value')
      .text(p)
      .css('border', '8px solid ' + c));
  }
}

$(function() {
  chart = null;
  histogram = null;
  wonIndices = [];
  wonChartData = [];
  valuesEl = $('#values');
  initDone = false;
  connectWS(messageRecieved);
});
<commit_msg>fix updateChart condition for lower values of x<commit_after>var WEBSOCKET_ADDRESS = 'ws://localhost:8887';
var HISTOGRAM_T = 10;

/**
 * Attempt to establish new websockets connection
 * @param {Function} messageCB onmessage function callback.
 */
function connectWS(messageCB) {
  // Init websockets with globally defined address.
  ws = new WebSocket(WEBSOCKET_ADDRESS);
  ws.onopen = function() {
    // Print a message when connection opens.
    console.log('open on ' + WEBSOCKET_ADDRESS);
  };
  ws.onclose = function() {
    initDone = false;
    // Print a message when connection closes.
    console.log('Websocket closed. Trying to reconnect.');
    // Call this function again (try to reconnect).
    setTimeout(function() {
      connectWS(messageCB);
    }, 1000);
  };
  // Set passed function as onmessage callback.
  ws.onmessage = messageCB;
}

/**
 * Websocket onmessage callback function.
 * @param {Object} e Event (with `data`) passed from server.
 */
function messageRecieved(e) {
  var data = JSON.parse(e.data);
  if (data.message && data.message === 'init' && !initDone) {
    saveChartToImg();
    saveWon();
    colors = data.colors;
    probabilities = data.p;
    displayProbabilites(probabilities, colors);
    initChart(colors);
    ws.send('init-ok');
    initDone = true;
  } else if (data.message && data.message === 'chart') {
    // drawWonChart(data.value);
  } else if (chart && !data.message) {
    updateChart(data);
  }
}

function initDatapoints() {
  if (datapoints) {
    for (var i = 0; i < datapoints.length; i++) {
      datapoints[i].splice(0);
    }
  }
}

function initChart(colors) {
  datapoints = [];
  var chartData = [];
  for (var i = 0; i < 10; i++) {
    datapoints.push([]);
    chartData.push({
      type: "line",
      dataPoints: datapoints[i],
      markerType: "none"
    });
  }
  initDatapoints();

  CanvasJS.addColorSet("graphColors", colors);

  chart = new CanvasJS.Chart("chartContainer", {
    title: {
      text: "Delež barv"
    },
    colorSet: "graphColors",
    height: 500,
    axisX: {
      title: "čas [iteracije]",
      minimum: 0
    },
    axisY: {
      title: "verjetnost",
      minimum: 0,
      maximum: 1.0
    },
    data: chartData
  });

  return chart;
}

function saveWon() {
  try {
    if (datapoints) {
      var i;
      for (i = 0; i < datapoints.length; i++) {
        var y = datapoints[i][datapoints[i].length - 1];
        if (y === 1) {
          break;
        }
      }
      wonIndices.push(i);
    }
  } catch (e) {}
}

function drawWonChart(newData) {
  // if (wonIndices.length === HISTOGRAM_T) {
  //   var numWon = wonIndices.splice(0)
  //     .filter(function(e) {
  //       // if color at index 0 won
  //       return e === 0;
  //     })
  //     .length / HISTOGRAM_T;
  // wonChartData.push({
  //   x: wonChartData.length + 1,
  //   y: Math.log(numWon / (1 - numWon))
  // });
  // wonChartData.push(newData);
  //
  // if(!histogram) {
  //   histogram = new CanvasJS.Chart('wonChartContainer', {
  //     title: {
  //       text: 'Razmerje zmag'
  //     },
  //     data: [{
  //       type: 'column',
  //       dataPoints: wonChartData
  //     }]
  //   });
  // }
  // histogram.render();
}

function saveChartToImg() {
  try {
    if (datapoints) {
      var canvas = document.querySelector("#chartContainer canvas");
      var img = canvas.toDataURL("image/png");
      var imageContainer = document.getElementById("slike");
      var newImage = new Image();
      newImage.src = img;
      imageContainer.appendChild(newImage);
    }
  } catch (e) {}
}

function updateChart(data) {
  var color = data[0],
    lastColor = datapoints[0][datapoints[0].length - 1];
  if (color && lastColor && color.x <= lastColor.x) {
    initDatapoints();
  }
  data.map(function(e, i) {
    datapoints[i].push(e);
  });
  chart.render();
}

function displayProbabilites(data, colors) {
  valuesEl.empty();
  for (var i = 0; i < data.length; i++) {
    var p = data[i];
    var c = colors[i];
    valuesEl.append($('<span>')
      .addClass('value')
      .text(p)
      .css('border', '8px solid ' + c));
  }
}

$(function() {
  chart = null;
  histogram = null;
  wonIndices = [];
  wonChartData = [];
  valuesEl = $('#values');
  initDone = false;
  connectWS(messageRecieved);
});
<|endoftext|>


<commit_before>cracked.microsynth = function (params) {

    var methods = {
        init: function (options) {
            //set up a basic synth: lfo, sine, lowpass, envelope
            __().begin("microsynth", params).

                lfo({gain: 0, type:"square"}).

                sine().

                lowpass({q: 0}).

                adsr().

                gain().

                end("microsynth");
        },
        noteOn: function (params) {
            //process incoming arguments for this note
            var args = params || {};
            var freq = __.isNum(params) ? __.pitch2freq(params) : __.pitch2freq(args.pitch);
            var env = args.envelope || [0.01,0.1,0.5];

            //loop thru selected nodes
            cracked.each("microsynth", function (el, index, arr) {
                //kill anything that's running
                cracked.exec("adsr", ["release",0.01], el.search("adsr"));
                //select any internal sine nodes the monosynth contains (using "el.search(sine)")
                //and then call frequency() passing in the pitch argument we got w noteOn.
                cracked.exec("frequency", [freq], el.search("sine"));
                //wait til the previous note is over
                setTimeout(function(){
                    //grab internal adsr and call trigger, pass the envelope parameter we received
                    cracked.exec("adsr", ["trigger", env], el.search("adsr"));
                },10);
            });
        },
        noteOff: function (params) {
            cracked.each("microsynth", function (el, index, arr) {
                params = __.ifUndef(params,0.1);
                var p = __.isNum(params) ? params : __.ifUndef(params.envelope,0.1);
                //call the adsr release
                cracked.exec("adsr", ["release",p], el.search("adsr"));
            });
        }
    };

    if (methods[params]) {
        methods[params].apply(this, Array.prototype.slice.call(arguments, 1));
    } else {
        methods.init(params);
    }

    return cracked;
};<commit_msg>minisynth configuration<commit_after>cracked.microsynth = function (params) {

    var methods = {
        init: function (options) {

            var opts = options || {};

            /*
                expected format
                {
                    lfo:{
                        type:"sawtooth",
                        intensity:0,
                        speed:5
                    },
                    osc: {
                         type:"sine",
                         frequency:440,
                         detune:0
                    },
                    lp: {
                        q:0,
                        frequency:440
                    },
                    adsr: {
                        envelope:0.5
                    },
                    gain: {
                        volume:1
                    }
                }
             */

            //set up a basic synth: lfo, sine, lowpass, envelope
            //options:
            //lfo- type, intensity, speed
            //osc- type, frequency, detune
            //lowpass- q, frequency
            //adsr- envelope
            //gain- volume

            var lfo_type        = opts.lfo.type         || "sawtooth",
                lfo_intensity   = opts.lfo.intensity    || 0,
                lfo_speed       = opts.lfo.speed        || 5,
                osc_type        = opts.osc.type         || "sine",
                osc_frequency   = opts.osc.frequency    || 440,
                osc_detune      = opts.osc.detune       || 0,
                lp_q            = opts.lp.q             || 0,
                lp_frequency    = opts.lp.frequency     || 440,
                adsr_envelope   = opts.adsr.envelope    || 0.5,
                gain_volume     = opts.gain.volume      || 1;

            __().begin("microsynth", params).

                lfo({
                    gain:lfo_intensity,
                    frequency:lfo_speed,
                    type:lfo_type
                }).

                osc({
                    detune:osc_detune,
                    frequency:osc_frequency,
                    type:osc_type
                }).

                lowpass({
                    q: lp_q,
                    frequency:lp_frequency
                }).

                adsr({
                    envelope:adsr_envelope
                }).

                gain({
                    gain:gain_volume
                }).

                end("microsynth");
        },
        noteOn: function (params) {
            //process incoming arguments for this note
            var args = params || {};
            var freq = __.isNum(params) ? __.pitch2freq(params) : __.pitch2freq(args.pitch);
            var env = args.envelope || [0.01,0.1,0.5];

            //loop thru selected nodes
            cracked.each("microsynth", function (el, index, arr) {
                //kill anything that's running
                cracked.exec("adsr", ["release",0.01], el.search("adsr"));
                //select any internal sine nodes the monosynth contains (using "el.search(sine)")
                //and then call frequency() passing in the pitch argument we got w noteOn.
                cracked.exec("frequency", [freq], el.search("sine"));
                //wait til the previous note is over
                setTimeout(function(){
                    //grab internal adsr and call trigger, pass the envelope parameter we received
                    cracked.exec("adsr", ["trigger", env], el.search("adsr"));
                },10);
            });
        },
        noteOff: function (params) {
            cracked.each("microsynth", function (el, index, arr) {
                params = __.ifUndef(params,0.1);
                var p = __.isNum(params) ? params : __.ifUndef(params.envelope,0.1);
                //call the adsr release
                cracked.exec("adsr", ["release",p], el.search("adsr"));
            });
        }
    };

    if (methods[params]) {
        methods[params].apply(this, Array.prototype.slice.call(arguments, 1));
    } else {
        methods.init(params);
    }

    return cracked;
};<|endoftext|>


<commit_before>function isImage(mime) {
    switch (mime) {
    case "image/gif":
    case "image/jpeg":
    case "image/png":
    case "image/tiff":
    case "image/x-ms-bmp":
    case "image/bmp":
        return true;
    default:
        return false;
    }
}

function numberWithCommas(n) {
    n = n.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(n)) {
        n = n.replace(pattern, "$1,$2");
    }
    return n;
}

function bytesToSizeStr(bytes) {
    if(bytes === 0) return '0 Byte';
    var k = 1000;
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];

}

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function _add_json_callback(url) {
    return url + "&callback=JSON_CALLBACK";
}

function _add_json_callback2(url) {
    var qIndex = url.indexOf("?");
    var argSeparator = "&";
    if (qIndex == -1) {
        argSeparator = "?";
    }

    return url + argSeparator + "callback=JSON_CALLBACK";
}

function differenceById(from, others) {
    var idsFrom = from.map(function(entry) {
        return entry.id;
    });
    var idsOthers = others.map(function(entry) {
        return entry.id;
    });

    var diff = _.difference(idsFrom, idsOthers);
    return from.filter(function(entry) {
        return _.indexOf(diff, function(e) {
            return e == entry.id;
        }) !== -1;
    });
}

function removeById(from, what) {
    var i = _.indexOf(from, function(item) {
        return item.id === what.id;
    });

    if (i !== -1) {
        from.splice(i, 1);
    }
}

String.prototype.capitalize = function () {
    return this.replace(/(?:^|\s)\S/g, function (a) {
        return a.toUpperCase();
    });
};

// save a reference to the core implementation
var indexOfValue = _.indexOf;

// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({

    // return the index of the first array element passing a test
    indexOf: function (array, test) {
        // delegate to standard indexOf if the test isn't a function
        if (!_.isFunction(test)) return indexOfValue(array, test);
        // otherwise, look for the index
        for (var x = 0; x < array.length; x++) {
            if (test(array[x])) return x;
        }
        // not found, return fail value
        return -1;
    }

    //contains: function(list, value, fromIndex) {
    //    return _.includes(list, value, fromIndex);
    //}
});
<commit_msg>Return index for the found item.<commit_after>function isImage(mime) {
    switch (mime) {
    case "image/gif":
    case "image/jpeg":
    case "image/png":
    case "image/tiff":
    case "image/x-ms-bmp":
    case "image/bmp":
        return true;
    default:
        return false;
    }
}

function numberWithCommas(n) {
    n = n.toString();
    var pattern = /(-?\d+)(\d{3})/;
    while (pattern.test(n)) {
        n = n.replace(pattern, "$1,$2");
    }
    return n;
}

function bytesToSizeStr(bytes) {
    if(bytes === 0) return '0 Byte';
    var k = 1000;
    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];

}

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function _add_json_callback(url) {
    return url + "&callback=JSON_CALLBACK";
}

function _add_json_callback2(url) {
    var qIndex = url.indexOf("?");
    var argSeparator = "&";
    if (qIndex == -1) {
        argSeparator = "?";
    }

    return url + argSeparator + "callback=JSON_CALLBACK";
}

function differenceById(from, others) {
    var idsFrom = from.map(function(entry) {
        return entry.id;
    });
    var idsOthers = others.map(function(entry) {
        return entry.id;
    });

    var diff = _.difference(idsFrom, idsOthers);
    return from.filter(function(entry) {
        return _.indexOf(diff, function(e) {
            return e == entry.id;
        }) !== -1;
    });
}

function removeById(from, what) {
    var i = _.indexOf(from, function(item) {
        return item.id === what.id;
    });

    if (i !== -1) {
        from.splice(i, 1);
    }

    return i;
}

String.prototype.capitalize = function () {
    return this.replace(/(?:^|\s)\S/g, function (a) {
        return a.toUpperCase();
    });
};

// save a reference to the core implementation
var indexOfValue = _.indexOf;

// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({

    // return the index of the first array element passing a test
    indexOf: function (array, test) {
        // delegate to standard indexOf if the test isn't a function
        if (!_.isFunction(test)) return indexOfValue(array, test);
        // otherwise, look for the index
        for (var x = 0; x < array.length; x++) {
            if (test(array[x])) return x;
        }
        // not found, return fail value
        return -1;
    }

    //contains: function(list, value, fromIndex) {
    //    return _.includes(list, value, fromIndex);
    //}
});
<|endoftext|>


<commit_before>exports.handlers = {
  beforeParse(e) {
    e.source = e.source.replace(/@typedef.*/, "");
    return e;
  }
};
<commit_msg>feat: remove unused plugins (#262)<commit_after><|endoftext|>


<commit_before>(function($) {
    var DynamicInput = function(element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.dynamic_input.defaults, options);
        this.nextid = 1;
        this.baseid = this.$element.attr("id");
        this.basename = this.$element.attr("name").split("_")[0];

        this.$element.keyup($.proxy(this.checknotempty, this));
        for (var cpt = 1; true; cpt++) {
            var $input = $("#" + this.baseid + "_" + cpt);

            if (!$input.length) {
                break;
            }
            $input.after(this.addrmlink($input));
            $input.focusout(this.checkempty);
            this.nextid++;
        }
    };

    DynamicInput.prototype = {
        constructor: DynamicInput,

        addrmlink: function(input) {
            var $rmlink = $('');

            $rmlink.click($.proxy(this.removeinput, $rmlink));
            return $rmlink;
        },

        addinput: function() {
            var id = this.baseid + '_' + this.nextid;
            var name = this.basename + '_' + this.nextid;
            var $ninput = $('<input type="text"'
                + 'id="' + id + '" '
                + 'name="' + name + '"'
                + '/>');
            var $rmlink = this.addrmlink($ninput);

            $ninput.focusout(this.checkempty);
            $ninput.val(this.$element.val());
            this.$element.val(this.options.emptylabel);
            this.$element.after($ninput, $rmlink);
            this.nextid++;
        },

        removeinput: function(evt, force) {
            evt.preventDefault();
            var id = "#" + this.attr("id").replace("_rmbtn", "");
            var $input = $(id);

            if ($input.val() == "" && (force == undefined || !force)) {
                return;
            }
            $input.remove();
            this.remove();
        },

        checknotempty: function(evt) {
            if (evt.keyCode != 13) {
                return;
            }
            if (this.$element.val() == "") {
                return;
            }
            this.addinput();
        },

        checkempty: function(evt) {
            var $input = $(evt.target);

            if ($input.val() == "") {
                $("#" + $input.attr("id") + "_rmbtn").trigger("click", true);
            }
        }
    };

    $.fn.dynamic_input = function(method) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('dynamic_input'),
                options = typeof method === "object" && method;

            if (!data) {
                $this.data('dynamic_input', new DynamicInput(this, options));
            }
            if (typeof method === "string") {
                data[method]();
            }
        });
    };

    /*
     * Allow an external access to the constructor (for inheritance)
     */
    $.fn.dynamic_input.Constructor = DynamicInput;

    $.fn.dynamic_input.defaults = {
        emptylabel: ""
    };

})(jQuery);<commit_msg>Substitute icon with glyphicon<commit_after>(function($) {
    var DynamicInput = function(element, options) {
        this.$element = $(element);
        this.options = $.extend({}, $.fn.dynamic_input.defaults, options);
        this.nextid = 1;
        this.baseid = this.$element.attr("id");
        this.basename = this.$element.attr("name").split("_")[0];

        this.$element.keyup($.proxy(this.checknotempty, this));
        for (var cpt = 1; true; cpt++) {
            var $input = $("#" + this.baseid + "_" + cpt);

            if (!$input.length) {
                break;
            }
            $input.after(this.addrmlink($input));
            $input.focusout(this.checkempty);
            this.nextid++;
        }
    };

    DynamicInput.prototype = {
        constructor: DynamicInput,

        addrmlink: function(input) {
            var $rmlink = $('');

            $rmlink.click($.proxy(this.removeinput, $rmlink));
            return $rmlink;
        },

        addinput: function() {
            var id = this.baseid + '_' + this.nextid;
            var name = this.basename + '_' + this.nextid;
            var $ninput = $('<input type="text"'
                + 'id="' + id + '" '
                + 'name="' + name + '"'
                + '/>');
            var $rmlink = this.addrmlink($ninput);

            $ninput.focusout(this.checkempty);
            $ninput.val(this.$element.val());
            this.$element.val(this.options.emptylabel);
            this.$element.after($ninput, $rmlink);
            this.nextid++;
        },

        removeinput: function(evt, force) {
            evt.preventDefault();
            var id = "#" + this.attr("id").replace("_rmbtn", "");
            var $input = $(id);

            if ($input.val() == "" && (force == undefined || !force)) {
                return;
            }
            $input.remove();
            this.remove();
        },

        checknotempty: function(evt) {
            if (evt.keyCode != 13) {
                return;
            }
            if (this.$element.val() == "") {
                return;
            }
            this.addinput();
        },

        checkempty: function(evt) {
            var $input = $(evt.target);

            if ($input.val() == "") {
                $("#" + $input.attr("id") + "_rmbtn").trigger("click", true);
            }
        }
    };

    $.fn.dynamic_input = function(method) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('dynamic_input'),
                options = typeof method === "object" && method;

            if (!data) {
                $this.data('dynamic_input', new DynamicInput(this, options));
            }
            if (typeof method === "string") {
                data[method]();
            }
        });
    };

    /*
     * Allow an external access to the constructor (for inheritance)
     */
    $.fn.dynamic_input.Constructor = DynamicInput;

    $.fn.dynamic_input.defaults = {
        emptylabel: ""
    };

})(jQuery);<|endoftext|>


<commit_before>// @flow

import React from 'react'

type Props = {
  title: string,
  user: string,
  repo: string,
  type: 'star' | 'watch' | 'fork' | 'follow',
  width: number,
  height: number,
  count?: boolean,
  large?: boolean
}

const GithubButton = (props: Props) => {
  const { title, user, repo, type, width, height, count, large } = props
  let options = `?user=${user}&repo=${repo}&type=${type}`
  if (count) options += '&count=true'
  if (large) options += '&size=large'

  return (
    <iframe
      title={title}
      src={`https://ghbtns.com/github-btn.html${options}`}
      frameBorder="0"
      allowTransparency="true"
      scrolling="0"
      width={width}
      height={height}
      style={{ border: 'none', width, height }}
    />
  )
}

GithubButton.defaultProps = {
  count: false,
  large: false
}

export default GithubButton
<commit_msg>temp solution<commit_after>// @flow

import React from 'react'

type Props = {
  title: string,
  user: string,
  repo: string,
  type: 'star' | 'watch' | 'fork' | 'follow',
  width: number,
  height: number,
  count?: boolean,
  large?: boolean
}

const GithubButton = (props: Props) => {
  const { title, user, repo, type, width, height, count, large } = props
  let options = `?user=${user}&repo=${repo}&type=${type}`
  if (count) options += '&count=true'
  if (large) options += '&size=large'

  return (
    <iframe
      title={title}
      src={`https://ghbtns.com/github-btn.html${options}`}
      frameBorder="0"
      allowtransparency="true" // eslint-disable-line react/no-unknown-property
      scrolling="0"
      width={width}
      height={height}
      style={{ border: 'none', width, height }}
    />
  )
}

GithubButton.defaultProps = {
  count: false,
  large: false
}

export default GithubButton
<|endoftext|>


<commit_before>import React from 'react';

export default function GithubButton({user, repo, type, width, height, count, large}) {

  let src = `https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=${type}`;
  if (count) src += '&count=true';
  if (large) src += '&size=large';

  return (

  );
}
<commit_msg>Add proptypes to GithubButton<commit_after>import React from 'react';

const GithubButton = (props) => {
  const {user, repo, type, width, height, count, large} = props;
  let src = `https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=${type}`;
  if (count) src += '&count=true';
  if (large) src += '&size=large';

  return (

  );
};

GithubButton.propTypes = {
  user: React.PropTypes.string.isRequired,
  repo: React.PropTypes.string.isRequired,
  type: React.PropTypes.oneOf(['star', 'watch', 'fork', 'follow']).isRequired,
  width: React.PropTypes.number.isRequired,
  height: React.PropTypes.number.isRequired,
  count: React.PropTypes.bool,
  large: React.PropTypes.bool
};

export default GithubButton;
<|endoftext|>