text:
/**
 * Version 1.0.0
 *
 * Created by Niels Klazenga on 10/04/2015.
 *
 * $.fn.keybase([action], options);
 *
 * var options = {
 *   baseUrl: "http://keybase.rbg.vic.gov.au/ws/keyJSON",
 *   ajaxDataType: "json",
 *   key: 2672,
 *   title: true,
 *   titleDiv: ".keybase-key-title",
 *   source: true,
 *   sourceDiv: ".keybase-key-source",
 *   cssClass: {
 *     currentNode: "keybase-player-currentnode",
 *     path: "keybase-player-path",
 *     remainingItems: "keybase-player-remainingitems",
 *     discardedItems: "keybase-player-discardeditems",
 *     stepBack: "keybase-player-stepback",
 *     startOver: "keybase-player-startover"
 *   },
 *   playerDiv: "#keybase-player",
 *   currentNodeDisplay: function(node, currentNodeDiv),
 *   discardedItemsDisplay: function(items, itemsDiv),
 *   pathDisplay: function(path, pathDiv),
 *   playerEvents: function(),
 *   playerWindow: function(),
 *   remainingItemsDisplay: function(items, itemsDiv),
 *   resultDisplay: function(result, resultDiv),
 *   renderItemLink: function(item),
 *   filterItems: []|undefined,     // array of item IDs
 *   filterItemNames: []|undefined  // array of item names
 *
 * };
 *
 * Possible actions are 'player', 'indentedKey' and 'bracketedKey'. Action is optional: if no action is given, 'player'
 * is assumed.
 *
 * There are default values for all options except 'key'. 'key' may also be replaced with a 'data' object, when another
 * web service or file is being used. When a file is used 'data' should be an empty object or not defined at all and
 * 'baseURL' should contain the entire path to the file. 'ajaxDataType' can be either 'json' (default) or 'jsonp'.
 */

;(function( $ ) {
    var json;
    var settings;
    var nested_sets;

    var rootNodeID;
    var next_id;
    var keyNodes;
    var current_node;

    var currentNodeElem;
    var pathElem;
    var remainingItemsElem;
    var discardedItemsElem;

    var filter_items;
    var filter_leads = [];
    var filter_parents = [];
    var filter_nodes = [];
    var activeFilter;

    var bracketed_key;
    var indented_key;
    var indentedKeyHtml;

    var i;

    $.fn.keybase = function() {

        $.fn.keybase.getters = {
            jsonKey: function() { return json; },
            settings: function() { return settings; },
            nestedSets: function() { return nested_sets; },
            currentNode: function() { return current_node; },
            bracketedKey: function() { return bracketed_key; },
            indentedKey: function() { return indented_key; },
            filterItems: function() { return filter_items; },
            filterLeads: function() { return filter_leads; },
            filterParents: function() { return filter_parents; },
            filterNodes: function() { return filter_nodes; },
            keyNodes: function() { return keyNodes; }
        };

        var options;
        if (arguments.length === 1) {
            options = arguments[0];
        }

        var action;
        if (arguments.length === 2) {
            action = arguments[0];
            options = arguments[1];
        }

        settings = $.extend(true, {}, $.fn.keybase.defaults, settings, options);

        if (settings.filterItems.length > 0) {
            filter_items = settings.filterItems;
        }
        else {
            if (settings.filterItemNames.length > 0) {
                filter_items = JSPath.apply('.items{.item_name===$item_name}.item_id', $.fn.keybase.getters.jsonKey(), {item_name: settings.filterItemNames});
            }
            else {
                if (!(filter_items !== undefined && filter_items.length > 0 && settings.reset !== true)) {
                    filter_items = [];
                }
            }
        }
        $.fn.keybase.setActiveFilter = function(filter) {
            activeFilter = filter;
        }
        $.fn.keybase.getters.activeFilter = function() {
            return activeFilter;
        }
        $.fn.keybase.setFilterItems = function(items) {
            filter_items = items;
        }

        var data;
        if (settings.data) {
            data = settings.data;
        }
        else {
            if (settings.key) {
                data = {key_id: settings.key};
            }
            else {
                data = false;
            }
        }

        if (!json || settings.reset === true) {
            var contentType ="application/x-www-form-urlencoded; charset=utf-8";

            if(window.XDomainRequest) //for IE8,IE9
                contentType = "text/plain";

            $.ajax({
                url: settings.baseUrl,
                data: {key_id: settings.key},
                dataType: settings.ajaxDataType,
                contentType: contentType,
                beforeSend: function() {
                    settings.beforeSend();
                },
                success: function(data){
                    json = data;
                    settings.onJson();

                    if (settings.title) {
                        settings.keyTitle(json);
                    }

                    if (settings.source) {
                        settings.keySource(json.source);
                    }

                    if ((!action || action === 'player') && !$('.keybase-player-window').length) {
                        settings.playerWindow();
                    }

                    // root node
                    rootNodeID = json.first_step.root_node_id;
                    next_id = rootNodeID;

                    linkItems();
                    sortItems();

                    nestedSets();
                    getNodes();
                    if (filter_items.length > 0) {
                        setFilter();
                    }
                    else {
                        nextCouplet();
                    }
                    settings.playerEvents();

                    if (action === "indentedKey") {
                        indentedKey();
                        settings.indentedKeyDisplay(json);
                    }

                    if (action === "bracketedKey") {
                        bracketedKey();
                        settings.bracketedKeyDisplay(json);
                    }

                    settings.onLoad(json);
                },
                complete: function() {
                    settings.onComplete();
                },
                error:function(jqXHR,textStatus,errorThrown) {
                    alert("You can not send Cross Domain AJAX requests: " + errorThrown);
                }
            });

        }
        else {
            if (settings.title) {
                settings.keyTitle(json);
            }

            if (settings.source) {
                settings.keySource(json.source);
            }

            if ((!action || action === 'player') && !$('.keybase-player-window').length) {
                settings.playerWindow();
            }

            // root node
            rootNodeID = json.first_step.root_node_id;
            next_id = rootNodeID;

            nestedSets();
            getNodes();
            if (filter_items.length > 0) {
                filterLeads();
            }
            else {
                nextCouplet();
            }
            settings.playerEvents();

            if (action === "indentedKey") {
                indentedKey();
                settings.indentedKeyDisplay(json);
            }

            if (action === "bracketedKey") {
                bracketedKey();
                settings.bracketedKeyDisplay(json);
            }
        }
    };

    $.fn.keybase.defaults = {
        baseUrl: "http://keybase.rbg.vic.gov.au/ws/keyJSON",
        ajaxDataType: 'json',
        title: true,
        titleDiv: '.keybase-key-title',
        source: true,
        sourceDiv: '.keybase-key-source',
        playerDiv: '#keybase-player',
        bracketedKeyDiv: '#keybase-bracketed',
        indentedKeyDiv: '#keybase-indented',
        cssClass: {
            currentNode: 'keybase-player-currentnode',
            path: 'keybase-player-path',
            remainingItems: 'keybase-player-remainingitems',
            discardedItems: 'keybase-player-discardeditems',
            stepBack: 'keybase-player-stepback',
            startOver: 'keybase-player-startover'
        },
        reset: false,
        beforeSend: function() {},
        onJson: function() {},
        onLoad: function() {},
        onComplete: function() {},
        onFilterWindowOpen: function() {},
        filterItems: [],
        filterItemNames: [],
        onBracketedKeyComplete: function() {},
        onIndentedKeyComplete: function() {}
    };

    /*
     * KeyBase Player display functions
     * Can be overridden by user.
     */

    /**
     * playerEvents function
     *
     * Sets up the events that make the KeyBase Player work. Note: events need to be removed first,
     * so you can run consecutive keys in the same page.
     */
    $.fn.keybase.defaults.playerEvents = function() {
        $('.' + settings.cssClass.currentNode).off('click', 'a.keybase-lead', currentNodeHandler);
        $('.' + settings.cssClass.currentNode).on('click', 'a.keybase-lead', currentNodeHandler);

        $('.' + settings.cssClass.path).off('click', 'a', stepBackHandler);
        $('.' + settings.cssClass.path).on('click', 'a', stepBackHandler);

        $('.' + settings.cssClass.stepBack).off('click', 'a', stepBackHandler);
        $('.' + settings.cssClass.stepBack).on('click', 'a', stepBackHandler);

        $('.' + settings.cssClass.startOver).off('click', 'a', startOverHandler);
        $('.' + settings.cssClass.startOver).on('click', 'a', startOverHandler);

        $('body').off('click', '.keybase-player-filter a', filterHandler);
        $('body').on('click', '.keybase-player-filter a', filterHandler);

    };

    /*
     * currentNodeHandler
     *
     * Finds the next couplet when a lead of the current node is clicked.
     *
     * @param {type} event
     * @returns {undefined}
     */
    var currentNodeHandler = function( event ) {
        event.preventDefault();
        if ($(event.target).attr('href')) {
            next_id = $(event.target).attr('href').replace("#l_", "");
        }
        else {
            next_id = $(event.target).parents('[href]').eq(0).attr('href').replace("#l_", "");
        }
        nextCouplet();
    };

    /**
     * stepBackHandler
     *
     * Finds the previous couplet when the 'step back' button is clicked, or, when a
     * lead in the path is clicked, finds the couplet the lead is in.
     *
     * @param {type} event
     * @returns {undefined}
     */
    var stepBackHandler = function( event ) {
            event.preventDefault();
            if ($(event.target).attr('href')) {
                var lead_id = $(event.target).attr('href').replace("#l_", "");
            }
            else {
                var lead_id = $(event.target).parents('[href]').eq(0).attr('href').replace("#l_", "");
            }
            next_id = getParent(lead_id);
            nextCouplet();
    };

    /**
     * startOverHandler
     *
     * Restarts the key player at the first couplet.
     *
     * @param {type} event
     * @returns {undefined}
     */
    var startOverHandler = function( event ) {
        event.preventDefault();
        next_id = $(event.target).parents('a').eq(0).attr('href').replace("#l_", "");
        nextCouplet();
    };

    /**
     * filterHandler
     *
     * @description Runs the localFilter function when the local filter button is clicked
     * @param {type} event
     */
    var filterHandler = function(event) {
        event.preventDefault();
        localFilter();
    };

    /**
     * playerWindow function
     *
     * Sets up the window the KeyBase Player runs in. Can be overridden by the user. Any user-defined playerWindow
     * function either must set up containers (divs) for the current node, path, remaining items and discarded items,
     * or they must be already defined in the HTML.
     */
    $.fn.keybase.defaults.playerWindow = function() {
        $('
', {class: 'keybase-player-window'}).appendTo(settings.playerDiv);

        if (!$('.keybase-player-window').height()) {
            var panelHeight = $('.keybase-player-window').width() * 0.67;
            $('.keybase-player-window').css('height', panelHeight + 'px');
        }

        var css = {
            'position': 'absolute',
            'height': (($('.keybase-player-window').height()*0.5) - 3) + 'px',
            'width': '100%'
        };

        $('
', {class: 'keybase-player-leftpane'}).appendTo('.keybase-player-window');
        currentNodeElem = $('
', {class: settings.cssClass.currentNode}).css(css).appendTo('.keybase-player-leftpane');
        $('
', {class: 'keybase-player-drag-updown'}).appendTo('.keybase-player-leftpane');
        pathElem = $('
', {class: settings.cssClass.path}).css(css).appendTo('.keybase-player-leftpane');
        $('
', {class: 'keybase-player-drag-leftright'}).appendTo('.keybase-player-window');
        $('
', {class: 'keybase-player-rightpane'}).appendTo('.keybase-player-window');
        remainingItemsElem = $('
', {class: settings.cssClass.remainingItems}).css(css).appendTo('.keybase-player-rightpane');
        $('
', {class: 'keybase-player-drag-updown'}).appendTo('.keybase-player-rightpane');
        discardedItemsElem = $('
', {class: settings.cssClass.discardedItems}).css(css).appendTo('.keybase-player-rightpane');

        settings.resizePlayerWindow();

        $('
', {html: 'Current node'}).appendTo(currentNodeElem);
        $('
', {html: 'Path'}).appendTo(pathElem);
        $('
', {html: 'Remaining items ()'}).appendTo(remainingItemsElem);
        $('
', {html: 'Discarded items ()'}).appendTo(discardedItemsElem);

        $('
').appendTo(currentNodeElem);
        $('
').appendTo(pathElem);
        $('
').appendTo(remainingItemsElem);
        $('
').appendTo(discardedItemsElem);

        currentNodeElem.children('div').css('height', (currentNodeElem.height() -
            currentNodeElem.children('h3').height() -
            (parseInt(currentNodeElem.children('h3').css('padding-top'))*2)) + 'px');
        pathElem.children('div').css('height', (pathElem.height() -
            pathElem.children('h3').height() -
            (parseInt(pathElem.children('h3').css('padding-top'))*2)) + 'px');
        remainingItemsElem.children('div').css('height', (remainingItemsElem.height() -
            remainingItemsElem.children('h3').height() -
            (parseInt(remainingItemsElem.children('h3').css('padding-top'))*2)) + 'px');
        discardedItemsElem.children('div').css('height', (discardedItemsElem.height() -
            discardedItemsElem.children('h3').height() -
            (parseInt(discardedItemsElem.children('h3').css('padding-top'))*2)) + 'px');

        // KeyBase Player menu
        $('', {class: 'keybase-player-menu'}).appendTo('.' + settings.cssClass.currentNode + ' h3');
        $('', {class: settings.cssClass.stepBack}).appendTo('.keybase-player-menu');
        $('', {href: '#', title: 'Step back'}).appendTo('.' + settings.cssClass.stepBack);
        $('', {class: settings.cssClass.startOver}).appendTo('.keybase-player-menu');
        $('', {href: '#', title: 'Start over'}).appendTo('.' + settings.cssClass.startOver);

        // Local filter button
        $('', {class: 'keybase-player-menu'}).appendTo('.' + settings.cssClass.remainingItems + ' h3');
        $('', {class: 'keybase-player-filter'}).appendTo('.' + settings.cssClass.remainingItems + ' .keybase-player-menu');
        $('', {href: '#', title: 'Filter'}).appendTo('.' + settings.cssClass.remainingItems + ' .keybase-player-filter');

        if ($('link[rel=stylesheet][href*=font-awesome]').length > 0) {
            $('.keybase-player-filter a').html('');
            $('.' + settings.cssClass.stepBack + ' a').html('');
            $('.' + settings.cssClass.startOver + ' a').html('');
        }

        // Resize Player panes
        var position;
        $('.keybase-player-window').on('mousedown', '.keybase-player-drag-leftright', $.fn.keybase.dragLeftRight);
        $('.keybase-player-leftpane').on('mousedown', '.keybase-player-drag-updown', $.fn.keybase.dragUpDownLeftPane);
        $('.keybase-player-rightpane').on('mousedown', '.keybase-player-drag-updown', $.fn.keybase.dragUpDownRightPane);

        $(document).mouseup(function(e){
            $(document).unbind('mousemove');
        });
    };

    $.fn.keybase.defaults.resizePlayerWindow = function() {
        $('.keybase-player-window').css({
            'position': 'relative'
        });
        $('.keybase-player-drag-leftright').css({
            'width': '6px',
            'height': '100%'
        });
        $('.keybase-player-drag-updown').css({
            'height': '6px',
            'width': '100%'
        });
        $('.keybase-player-leftpane, .keybase-player-rightpane').css({
            'height': '100%',
            'position': 'absolute',
            'top': '0px'
        });

        $('.keybase-player-leftpane').css({
            'width': (($('.keybase-player-window').width()*0.67) - 3) + 'px',
            'left': '0px'
        });
        $('.keybase-player-drag-leftright').css({
            'position': 'absolute',
            'top': '0px',
            'left': $('.keybase-player-leftpane').width() + 'px'
        });
        $('.keybase-player-rightpane').css({
            'width': (($('.keybase-player-window').width() * 0.33) - 3) + 'px',
            'left': ($('.keybase-player-leftpane').width() + 6) + 'px'
        });

        $('.keybase-player-drag-updown').css({
            'position': 'absolute',
            'top': (($('.keybase-player-window').height() * 0.5) - 3) + 'px'
        });
        $('.' + settings.cssClass.path + ', .' + settings.cssClass.discardedItems).css({
            'top': (($('.keybase-player-window').height() * 0.5) + 3) + 'px'
        });
    };

    $.fn.keybase.dragLeftRight = function(event) {
        event.preventDefault();
        position = $('.keybase-player-window').offset();
        $(document).mousemove(function(e){
            if (e.pageX > position.left+190 &&
                e.pageX < position.left+$('.keybase-player-window').width()-190) {
                $('.keybase-player-leftpane').css("width",e.pageX-position.left);
                $('.keybase-player-drag-leftright').css('left', e.pageX-position.left);
                $('.keybase-player-rightpane').css({"left": e.pageX-position.left+6,
                    "width": ($('.keybase-player-window').width()-$('.keybase-player-leftpane').width()-6) + 'px'});
            }
        });
    };

    $.fn.keybase.dragUpDownLeftPane = function(event) {
        event.preventDefault();
        position = $('.keybase-player-leftpane').offset();
        $(document).mousemove(function(e) {
            if (e.pageY > position.top+29
                && e.pageY < position.top+$('.keybase-player-window').height()-32) {
                $('.keybase-player-leftpane .keybase-player-drag-updown').css('top', e.pageY-position.top+2);
                currentNodeElem.css("height", e.pageY-position.top);
                pathElem.css({'top': e.pageY-position.top+5,
                    'height': ($('.keybase-player-window').height()-currentNodeElem.height()-6) + 'px'});
                currentNodeElem.children('div').css('height', (currentNodeElem.height() -
                    currentNodeElem.children('h3').height() -
                    (parseInt(currentNodeElem.children('h3').css('padding-top'))*2)) + 'px');
                pathElem.children('div').css('height', (pathElem.height() -
                    pathElem.children('h3').height() -
                    (parseInt(pathElem.children('h3').css('padding-top'))*2)) + 'px');
                if (pathElem.children('div').height() < 5) {
                    pathElem.children('div').css('overflow', 'hidden').children().hide();
                }
                else {
                    pathElem.children('div').css('overflow', 'auto').children().show();
                }
            }
        });
    }

    $.fn.keybase.dragUpDownRightPane = function(event) {
        event.preventDefault();
        position = $('.keybase-player-rightpane').offset();
        $(document).mousemove(function(e) {
            if (e.pageY > position.top+29
                && e.pageY < position.top+$('.keybase-player-window').height()-32) {
                $('.keybase-player-rightpane .keybase-player-drag-updown').css('top', e.pageY-position.top+2);
                remainingItemsElem.css("height", e.pageY-position.top);
                discardedItemsElem.css({'top': e.pageY-position.top+5,
                    'height': ($('.keybase-player-window').height() -
                        remainingItemsElem.height()-6) + 'px'});
                remainingItemsElem.children('div').css('height', (remainingItemsElem.height() -
                    remainingItemsElem.children('h3').height() -
                    (parseInt(remainingItemsElem.children('h3').css('padding-top'))*2)) + 'px');
                discardedItemsElem.children('div').css('height', (discardedItemsElem.height() -
                    discardedItemsElem.children('h3').height() -
                    (parseInt(discardedItemsElem.children('h3').css('padding-top'))*2)) + 'px');
                if (discardedItemsElem.children('div').height() < 5) {
                    discardedItemsElem.children('div').css('overflow', 'hidden').children().hide();
                }
                else {
                    discardedItemsElem.children('div').css('overflow', 'auto').children().show();
                }
            }
        });
    }

    /**
     * currentNodeDisplay function
     *
     * Displays the current node.
     *
     * @param node
     * @param currentNodeDiv
     */
    $.fn.keybase.defaults.currentNodeDisplay = function(node, currentNodeDiv) {
        var leads = [];
        $.each(node, function(index, item) {
            var lead = '
' + item.lead_text + '
';
            leads.push(lead);
        });
        $(currentNodeDiv).eq(0).children('div').eq(0).html('
' + leads.join('') + '
');
    };

    /**
     * resultDisplay function
     *
     * Displays the determination result.
     *
     * @param result
     * @param resultDiv
     */
    $.fn.keybase.defaults.resultDisplay = function(result, resultDiv) {
        if (result[0].url) {
            var text = '' + result[0].item_name + '';
        }
        else {
            var text = result[0].item_name;
        }
        $(resultDiv).eq(0).children('div').eq(0).html('
Result: ' + text + '
');
    };

    /**
     * pathDisplay function
     *
     * Displays the path followed to get to the current couplet (or result).
     *
     * @param path
     * @param pathDiv
     */
    $.fn.keybase.defaults.pathDisplay = function(path, pathDiv) {
        var leads = [];
        $.each(path, function(index, item) {
            var lead;
            if (filter_leads.length === 0 || filter_parents[item.parent_id] > 1) {
                lead = '
' + item.lead_text + '
';
            }
            leads.push(lead);
         });
        $(pathDiv).eq(0).children('div').eq(0).html('
' + leads.join('') + '
');
    };

    /**
     *
     */
    $.fn.keybase.defaults.renderItemLink = function(item) {
        var link = '';
        if (item.url) {
            link += '' + item.item_name + '';
        }
        else {
            link += item.item_name;
        }
        if (item.to_key) {
            link += '';
        }

        if (item.link_to_item_id) {
            link += ': ';
            if (item.link_to_url) {
                link += '' + item.link_to_item_name + '';
            }
            else {
                link += item.link_to_item_name;
            }
            if (item.link_to_key) {
                link += '';
            }
        }
        return link;
    }

    /**
     * remainingItemsDisplay functions
     *
     * Displays the remaining items.
     *
     * @param items
     * @param itemsDiv
     */
    $.fn.keybase.defaults.remainingItemsDisplay = function(items, itemsDiv) {
        var list = itemsDisplay(items);
        $(itemsDiv).eq(0).children('h3').eq(0).children('.keybase-num-remaining').eq(0).html(items.length);
        $(itemsDiv).eq(0).children('div').eq(0).html('
' + list.join('') + '
');
        displayChildItems(itemsDiv);
    };

    /**
     * discardedItemsDisplay function
     *
     * Displays the discarded items.
     *
     * @param array items
     * @param itemsDiv
     */
    $.fn.keybase.defaults.discardedItemsDisplay = function(items, itemsDiv) {
        var list = itemsDisplay(items);
        $(itemsDiv).eq(0).children('h3').eq(0).html('Discarded items (' + items.length + ')');
        $(itemsDiv).eq(0).children('div').eq(0).html('
' + list.join('') + '
');
        displayChildItems(itemsDiv);
    };

    /**
     * itemsDisplay function
     *
     * @param array items
     * @returns {undefined}
     */
    var itemsDisplay = function(items) {
        var list = [];
        $.each(items, function(index, item) {
            var entity;
            entity = '
';
            entity += settings.renderItemLink(item);
            entity += '
';
            list.push(entity);
        });
        return list;
    };

    var displayChildItems = function(itemsDiv) {
        var childItems = $(itemsDiv + ' [data-parent-id]');
        if (childItems.length) {
            childItems.each(function() {
                var selector = itemsDiv + ' [data-item-id="' + $(this).data('parent-id') + '"]';
                var parent = $(selector);
                if (parent.length) {
                    $('
').append($(this)).appendTo(parent.eq(0));
                }
            });
        }
    };

    /**
     * function keyTitle
     *
     * Displays the title of the key.
     */
    $.fn.keybase.defaults.keyTitle = function(json) {
        if (!$(settings.titleDiv).length) {
            if (settings.titleDiv.substr(0, 1) === '#') {
                $('
', {id: settings.titleDiv.substr(1)}).appendTo(settings.playerDiv);
            }
            else {
                $('
', {class: settings.titleDiv.substr(1)}).appendTo(settings.playerDiv);
            }
        }

        $('
', {class: 'keybase-project-icon'})
            .append('')
            .appendTo(settings.titleDiv);

        $('
', {
            style: "float:left;",
            html: '<a href="/keybase/project/show/' + json.project.project_id + '"' + json.project.project_name + ': ' + json.key_title + ''
        }).appendTo(settings.titleDiv);

    };

    /**
     * function keySource
     *
     * Displays the source publication of the key.
     *
     * @param source
     */
    $.fn.keybase.defaults.keySource = function(source) {
        var str;
        if (source.author && source.publication_year && source.title) {
            if (source.is_modified) {
                str = 'Modified from: ';
            }
            else {
                str = 'From: ';
            }

            str += '' + source.author + ' (' + source.publication_year + '). ';
            if (source.journal) {
                str += source.title + '. ' + source.journal + '';
                if (source.series) {
                    str += ', ser. ' + source.series;
                }
                str += ' ' + source.volume + '';
                if (source.part) {
                    str += '(' + source.part + ')';
                }
                str += ': ' + source.page + '.';
            }
            else {
                if (source.in_title) {
                    str += source.title + '. In: ';
                    if (source.in_author) {
                        str += source.in_author + ', ';
                    }
                    str += '' + source.in_title + '';
                    if (source.volume) {
                        str += ' ' + source.volume + '';
                    }
                    if (source.page) {
                        str += ', pp. ' + source.page;
                    }
                    str += '.';
                    if (source.publisher) {
                        str += ' ' + source.publisher;
                        if (source.place_of_publication) {
                            str += ',';
                        }
                        else {
                            str += '.';
                        }
                    }
                    if (source.place_of_publication) {
                        str += ' ' + source.place_of_publication + '.';
                    }
                }
            }
        }

        if (!$(settings.sourceDiv).length) {
            if (settings.sourceDiv.substr(0, 1) === '#') {
                $('
', {id: settings.sourceDiv.substr(1)}).appendTo(settings.playerDiv);
            }
            else {
                $('
', {class: settings.sourceDiv.substr(1)}).appendTo(settings.playerDiv);
            }
        }
        $(settings.sourceDiv).html(str);
    };

    /*
     * KeyBase processing functions
     */

    /**
     * function nestedSets
     *
     * Creates the nested sets that are necessary to run or reproduce the key. Initiates the getNode function, which
     * will do the heavy lifting and when the getNode function has traversed all the nodes creates the nested set for
     * the root node.
     */
    var nestedSets = function() {
        nested_sets = [];

        i = 1;
        getNode(rootNodeID);

        nested_sets.sort(function(a, b) {
            return a.left - b.left;
        });

        json.first_step.left = 1;
        json.first_step.right = Math.max.apply(Math, JSPath.apply('.right', nested_sets));
    };

    /**
     * function getNode
     *
     * Work horse for the nestedSets function: traverses the key by finding the leads for which the parent ID is the
     * ID for the current lead at each step.
     *
     * @param parentID
     */
    var getNode = function(parentID) {
        var leads = JSPath.apply('.leads{.parent_id==' + parentID + '}', json);
        $.each(leads, function( index, lead ) {
            i++;
            lead.left = i;
            //if (!lead.item) {
                getNode(lead.lead_id);
            //}
            lead.right = i;
            nested_sets.push(lead);
        });
    };

    var getNodes = function() {
        var parent_ids = JSPath.apply('.parent_id', nested_sets);
        var ids = [];
        keyNodes = [];
        var i = 1;

        $.each(parent_ids, function(index, item) {
            if (ids.indexOf(item) === -1) {
                ids.push(item);
                var node = {
                    "parent_id": item,
                    "node_number": i
                };
                keyNodes.push(node);
                i++;
            }
        });
    };

    /**
     * function nextCouplet
     *
     * Main function for the KeyBase Player. Calls the processing functions that return the current node, path followed
     * to get to the current node, and remaining and discarded items as Javascript Objects and then the display
     * functions that will turn the Javascript into human readable HTML. Display functions can be overridden by the user
     * when the KeyBase function is called.
     */
    var nextCouplet = function() {
        if (next_id === rootNodeID) {
            left = json.first_step.left;
            right = json.first_step.right;
        }
        else {
            var curnode = JSPath.apply('.leads{.lead_id=="'+  next_id + '"}', json);
            left = curnode[0].left;
            right = curnode[0].right;
        }

        // Current node
        currentNode(next_id);
        if (current_node.length > 1) {
            settings.currentNodeDisplay(current_node, '.' + settings.cssClass.currentNode);
        }
        else {
            var result = getResult();
            settings.resultDisplay(result, '.' + settings.cssClass.currentNode);
        }
        $('.keybase-player-startover:eq(0)>a:eq(0)').attr('href', '#l_' + rootNodeID);
        $('.keybase-player-stepback:eq(0)>a:eq(0)').attr('href', '#l_' + next_id);

        // Path
        var path = getPath();
        settings.pathDisplay(path, '.' + settings.cssClass.path);

        // Remaining and discarded items
        var items = remainingItems();
        settings.remainingItemsDisplay(items.remaining, '.' + settings.cssClass.remainingItems);
        settings.discardedItemsDisplay(items.discarded, '.' + settings.cssClass.discardedItems);

        $.fn.keybase.getters.remainingItems = function() { return items.remaining; };
        $.fn.keybase.getters.discardedItems = function() { return items.discarded; };
    };

    /**
     * function currentNode
     *
     * @param parentID
     * @returns {*}
     */
    var currentNode = function(parentID) {
        if (filter_leads.length === 0) {
            current_node = JSPath.apply('.leads{.parent_id=="' + parentID + '"}', json);
        }
        else {
            var path = '.leads{.parent_id=="' + parentID + '"}{.lead_id==$lead_id}';
            var node = JSPath.apply(path, json, {lead_id: filter_leads});
            if (node.length === 1) {
                next_id = node[0].lead_id;
                currentNode(next_id);
            }
            else {
                current_node = node;
            }
        }
    };

    /**
     * function getResult
     *
     * Gets the determination result when the currentNode is not a couplet, but a taxon.
     *
     * @returns {*}
     */
    var getResult = function() {
        var item_id = JSPath.apply('.leads{.lead_id=="'+  next_id + '"}.item', json)[0];
        return JSPath.apply('.items{.item_id == "'+  item_id + '"}', json);
    };

    /**
     * function getPath
     *
     * Gets the path followed to get to the current node.
     *
     * @returns {*}
     */
    var getPath = function() {
        var path = JSPath.apply('.leads{.left <= ' + left + ' && .right >= ' + right + '}', json);
        $.fn.keybase.getters.path = function() {return path;};
        return path;
    };

    /**
     * function remainingItems
     *
     * Splits the items into remaining and discarded items
     *
     * @param aux_remaining
     * @returns {{remaining: Array, discarded: Array}}
     */
    var remainingItems = function() {
        var remaining = JSPath.apply('.leads{.item && .left >= ' + left + ' && .right <= ' + right + '}.item', json);
        var remaining_items = [];
        var discarded_items = [];

        var items;
        if (filter_items.length === 0) {
            items = json.items;
        }
        else {
            var path = '.items{.item_id==$item_id}';
            items = JSPath.apply(path, json, {item_id: filter_items});
        }

        $.each(items, function(index, item) {
            if (remaining.indexOf(item.item_id) > -1) {
                remaining_items.push(item);
            }
            else {
                discarded_items.push(item);
            }
        });

        var items = {
            remaining: remaining_items,
            discarded: discarded_items
        };
        return items;
    };

    /**
     * function getParent
     *
     * Gets the parent ID for the lead (based on the lead ID). Used to get the lead ID to initiate the trace back
     * functions.
     *
     * @param leadID
     * @returns {*}
     */
    var getParent = function(leadID) {
        return JSPath.apply('.leads{.lead_id=="'+  leadID + '"}.parent_id[0]', json);
    };

    /**
     * function indentedKey
     *
     * Initiates the indentedKeyNode function that creates the indented key. At the moment there is no display function
     * for the indented key yet and the display depends on the Dynatree widget.
     */
    var indentedKey = function() {
        indented_key = [];
        var root = {};
        root.title = json.key_title;
        root.isFolder = true;
        root.expand = true;
        root.children = [];
        if (filter_leads.length === 0) {
            indentedKeyNode(rootNodeID, root);
        }
        else {
            filter_nodes = [];
            $.each(Object.keys(filter_parents), function(index, item) {
                if (filter_parents[item] > 1) {
                    filter_nodes.push(item);
                }
            });
            indentedKeyNode(filter_nodes[0], root);
        }
        indented_key.push(root);
    };

    /**
     * function indentedKeyNode
     *
     * Creates the indented key nodes.
     *
     * @param parent_id
     * @param parent
     */
    var indentedKeyNode = function(parent_id, parent) {
        var children = [];
        if (filter_leads.length === 0) {
            children = JSPath('.{.parent_id==' + parent_id + '}', nested_sets);
        }
        else {
            children = JSPath('.{.parent_id==' + parent_id + ' && .lead_id==$filter_leads}', nested_sets, {filter_leads: filter_leads});
        }
        parent.children = [];
        if (children.length > 0) {
            if (children.length > 1) {
                var couplet = {};
                couplet.title = "Couplet";
                couplet.isFolder = true;
                couplet.expand = true;
                couplet.children = [];
                parent.children[0] = couplet;

                //parent.children = children;
                $.each(children, function(index, lead) {
                    var child = $.extend({}, lead);

                    if (filter_leads.length === 0) {
                        child.fromNode = JSPath.apply('.{.parent_id=="' +  child.parent_id+ '"}', keyNodes)[0].node_number;
                    }
                    else {
                        child.fromNode = filter_nodes.indexOf(child.parent_id)+1;
                    }

                    var toNode = JSPath.apply('.{.parent_id=="' +  child.lead_id+ '"}', keyNodes);
                    if (toNode.length > 0) {
                        child.toNode = toNode[0].node_number;
                    }

                    child.title = lead.lead_text;
                    child.href = "#" + lead.lead_id;
                    child.expand = true;
                    delete child.left;
                    delete child.right;
                    if (child.item == null) {
                        delete child.item;
                    }

                    if (filter_leads.length === 0) {
                        var toNode = JSPath.apply('.{.parent_id=="' +  child.lead_id+ '"}', keyNodes);
                        if (toNode.length > 0) {
                            child.toNode = toNode[0].node_number;
                        }
                    }
                    else {
                        if (filter_nodes.indexOf(child.lead_id) > -1) {
                            child.toNode = filter_nodes.indexOf(child.lead_id)+1;
                        }
                    }
                    //if (children.length > 1) {
                        couplet.children[index] = child;
                    //}
                    indentedKeyNode(lead.lead_id, child);
                });
            }
            else {
                lead = children[0];
                if (lead.item !== null) {
                    parent.item = lead.item;
                }
                indentedKeyNode(lead.lead_id, parent);
            }
        }
        else {
            parent.children[0] = indentedKeyItem(parent.item);
            delete parent.item;
        }
    };

    var indentedKeyItem = function(item) {
            var taxa = {};
            taxa.title = "Item";
            taxa.isFolder = true;
            taxa.children = [];

            var taxon = {};
            taxon.item_id = item;
            taxon.title = JSPath.apply('.items{.item_id==="' + item + '"}.item_name', json)[0];
            taxa.children[0] = taxon;
            //alert (taxon.title);
            taxa.expand = true;
            return taxa;
    };

    /**
     * function indentedKeyDisplay
     *
     * Displays the indented key. The function is accessible from outside the plugin, so
     * users can overwrite it with their own function.
     */
    $.fn.keybase.defaults.indentedKeyDisplay = function(json) {
        indentedKeyHtml = '
';
        displayIndentedKeyCouplet(indented_key[0].children[0]);

        indentedKeyHtml += '
 ';

        $(settings.indentedKeyDiv).html(indentedKeyHtml);
        $(settings.indentedKeyDiv).prepend('

')

        settings.onIndentedKeyComplete();
    };

    /**
     * function displayIndentedKeyCouplet
     */
    var displayIndentedKeyCouplet = function(couplet) {
        var leads = couplet.children;
        indentedKeyHtml += '
';
        for (var i = 0; i < leads.length; i++) {
            var lead = leads[i];
            indentedKeyHtml += '
';
            indentedKeyHtml += '
';
            indentedKeyHtml += '' + lead.fromNode + '';
            indentedKeyHtml += '' + lead.title + '';
            var child = lead.children[0];
            if (child.title === "Couplet") {
                indentedKeyHtml += '
 ';
                displayIndentedKeyCouplet(child);
            }
            else {
                var item = JSPath.apply('.items{.item_id==="' + child.children[0].item_id + '"}', json)[0];
                indentedKeyHtml += '';
                if (typeof item.parent_id !== 'undefined') {
                    var parent = JSPath.apply('.items{.item_id==' + item.parent_id + '}', json)[0];
                    indentedKeyHtml += settings.renderItemLink(parent);
                    indentedKeyHtml += ': ';
                }
                indentedKeyHtml += settings.renderItemLink(item);
                indentedKeyHtml += ' ';
                indentedKeyHtml += '
 ';
            }
            indentedKeyHtml += '
';
        }

        indentedKeyHtml += '
 ';
    };

    /**
     * function bracketedKey
     *
     * Creates the bracketed key. At the moment there is no display function for the bracketed key yet and the display
     * depends on the Dynatree widget, which is not very suitable for the purpose.
     */
    var bracketedKey = function() {
        bracketed_key = [];
        var parent_ids = JSPath.apply('.{.lead_text && .lead_text!=="[link through]"}.parent_id', nested_sets);
        var link_through_parents = JSPath.apply('.{!.lead_text || .lead_text==="[link through]"}.parent_id', nested_sets);
        var nodes = [];

        var root = {};
        root.title = json.key_title;
        root.isFolder = true;
        root.expand = true;
        root.children = [];

        if (filter_leads.length > 0) {
            var filterNodes = function() {
                var nodes = [];
                $.each(Object.keys(filter_parents), function(index, item) {
                    if (filter_parents[item] > 1) {
                        nodes.push(item);
                    }
                });
                return nodes;
            }
            filter_nodes = filterNodes();
        }

        $.each(parent_ids, function (index, parent) {
            if (filter_leads.length === 0 || (Object.keys(filter_parents).indexOf(parent) > -1 && filter_parents[parent] > 1)) {
                if (nodes.indexOf(parent) == -1) {
                    nodes.push(parent);

                    var couplet = {};
                    couplet.title = "Couplet";
                    couplet.isFolder = true;
                    couplet.expand = true;
                    couplet.children = [];

                    var leads = JSPath.apply('.{.parent_id==' + parent + '}', nested_sets);

                    $.each(leads, function(index, lead) {
                        var l = {};
                        if (filter_leads.length === 0) {
                            l.fromNode = JSPath.apply('.{.parent_id=="' +  lead.parent_id + '"}', keyNodes)[0].node_number;
                        }
                        else {
                            l.fromNode = filter_nodes.indexOf(lead.parent_id)+1;
                        }

                        l.parent_id = lead.parent_id;
                        l.lead_id = lead.lead_id;

                        l.title = lead.lead_text;
                        l.href = '#' + lead.lead_id;
                        l.expand = true;
                        l.children = [];
                        if (lead.item != null) {
                            var items = {};
                            items.title = "Item";
                            items.isFolder = true;
                            items.expand = true;
                            items.children = [];
                            var item = {};
                            item.item_id = lead.item;
                            item.title = JSPath.apply('.items{.item_id==="' + lead.item + '"}.item_name', json)[0];
                            item.expand = true;
                            items.children.push(item);
                            l.children.push(items);
                        }
                        else {
                            if (filter_leads.length === 0) {
                                var toNode = JSPath.apply('.{.parent_id=="' +  lead.lead_id+ '"}', keyNodes);
                                if (toNode.length > 0) {
                                    l.toNode = toNode[0].node_number;
                                }
                            }
                            else {
                                var to = filteredBracketedKeyToNode(lead);
                                if (to.toNode !== undefined) {
                                    l.toNode = to.toNode;
                                }
                                else {
                                    if (to.items !== undefined) {
                                        l.children.push(to.items);
                                    }
                                }
                            }
                        }
                        if (link_through_parents.indexOf(lead.lead_id) > -1) {
                            var linkItems = JSPath.apply('.{.parent_id==' + lead.lead_id + '}.item', nested_sets);
                            l.linkItems = JSPath.apply('.items{.item_id==$item}', json, {item: linkItems});
                        }

                        couplet.children.push(l);
                    });
                    root.children.push(couplet);

                }
            }
        });
        bracketed_key.push(root);
    };

    /*
     * function filteredBracketedKeyToNode
     */
    var filteredBracketedKeyToNode = function(lead) {
        var toNode = JSPath.apply('.{.parent_id=="' + lead.lead_id + '" && .lead_id===$filterLeads}', nested_sets, {filterLeads: filter_leads});
        if (toNode.length > 0) {
            if (toNode.length > 1) {
                //var nodeNumber = JSPath.apply('.{.parent_id=="' + toNode[0].parent_id + '"}', keyNodes)[0].node_number;
                //return {toNode: nodeNumber};
                return {toNode: filter_nodes.indexOf(toNode[0].parent_id)+1};
            }
            else {
                if (toNode[0].item !== null && toNode[0].item.length > 0) {
                    var items = {};
                    items.title = "Item";
                    items.isFolder = true;
                    items.expand = true;
                    items.children = [];
                    var item = {};
                    item.item_id = toNode[0].item;
                    item.title = JSPath.apply('.items{.item_id==="' + toNode[0].item + '"}.item_name', json)[0];
                    item.expand = true;
                    items.children.push(item);
                    return {items: items};
                }
                else {
                    return filteredBracketedKeyToNode(toNode[0]);
                }
            }
        }
    };

    /**
     * function bracketedKeyDisplay
     *
     * Displays the bracketed key. This function is accessible from outside the plugin, so
     * users can use their own function to display the bracketed keys. If the KeyBase plugin
     * is used to manage keys in a project, you might not want to directly link to the next
     * key, for example, but make the user go via the web page for the keyed-out item.
     */
    $.fn.keybase.defaults.bracketedKeyDisplay = function(json) {
        var html = '
';
        var couplets = bracketed_key[0].children;
        for (var i = 0; i < couplets.length; i++)  {
            var couplet = couplets[i];
            var leads = couplet.children;
            html += '
';
            //html += '' + JSON.stringify(couplet.children) + '';
            for (var j = 0; j < leads.length; j++) {
                var lead = leads[j];
                var items = lead.children;
                html += '
';
                html += '' + lead.fromNode + '';
                html += '' + lead.title;
                if (lead.toNode !== undefined) {
                    html += '' + lead.toNode + '';
                }
                else {
                    var toItem = items[0].children[0];
                    var item = JSPath.apply('.items{.item_id=="' + toItem.item_id + '"}', json)[0];
                    html += '';
                    html += settings.renderItemLink(item);
                    if (typeof lead.linkItems !== 'undefined') {
                        html += ': ';
                        $.each(lead.linkItems, function(index, item) {
                            html += settings.renderItemLink(item);
                        });
                    }
                    html += ' ';
                }
                html += ' ';
                html += '
 ';
            }
            html += '
 ';

        }
        html += '
 ';
        $(settings.bracketedKeyDiv).html(html);
        $(settings.bracketedKeyDiv).prepend('

');

        settings.onBracketedKeyComplete();
    };

    /*
     * Filter functions
     */

    /**
     * function localFilter
     *
     * Sets up the window for the local filter, as well as the functionality.
     */
    var localFilter = function() {

        var localFilter = $('
', {class: 'keybase-local-filter'});
        var divIncluded = $('
');
        var divExcluded = $('
');
        var labelIncluded = $('', {for: 'initems', html: 'Included items'});
        var labelExcluded = $('', {for: 'outitems', html: 'Excluded items'});
        var selectIncluded = $('<select>', {name:"includedItems", id: 'initems', multiple:"multiple"});
        var selectExcluded = $('<select>', {name:"excludedItems", id: 'outitems', multiple:"multiple"});

        var incl = [];
        var excl = [];
        $.each(json.items, function(index, item) {
            var name = item.item_name;
            name += (item.link_to_item_name) ? ': ' + item.link_to_item_name : '';
            var opt = '<option value="' + item.item_id + '">' + name + '</option>';
            if (filter_items.length === 0 || filter_items.indexOf(item.item_id) > -1 || filter_items.indexOf(Number(item.item_id)) > -1) {
                incl.push(opt);
            }
            else {
                excl.push(opt);
            }
        });

        selectIncluded.append(incl.join(''));
        sortOptions('includedItems');
        if (excl) {
            selectExcluded.append(excl.join(''));
            sortOptions('excludedItems');
        }

        var buttonDiv = $('
', {class: 'keybase-filter-buttons'});
        buttonDiv.append('<button class="keybase-filter-button-excl"></button>').
            append('<button class="keybase-filter-button-excl-all"></button>').
            append('<button class="keybase-filter-button-incl"></button>').
            append('<button class="keybase-filter-button-incl-all"></button>');

        var footerDiv = $('
', {class: 'keybase-local-filter-footer'});
        footerDiv.append('<button class="keybase-local-filter-cancel">Cancel</button>').
            append('<button class="keybase-local-filter-ok">OK</button>');

        divIncluded.append(labelIncluded).append(selectIncluded);
        divExcluded.append(labelExcluded).append(selectExcluded);

        localFilter.append(divIncluded).append(buttonDiv).append(divExcluded).append(footerDiv);

        keybaseLightBox(localFilter);

        boxHeaders();

        $('.keybase-filter-button-excl').click(function(e) {
            $('[name=includedItems]>option:selected').each(function() {
                $(this).remove();
                $(this).removeAttr('selected')
                $('[name=excludedItems]').append($(this));
            });
            sortOptions('excludedItems');
            $.fn.keybase.filterItems();
            boxHeaders();
        });

        $('.keybase-filter-button-excl-all').click(function(e) {
            $('[name=includedItems]>option').each(function() {
                $(this).remove();
                $(this).removeAttr('selected')
                $('[name=excludedItems]').append($(this));
            });
            sortOptions('excludedItems');
            $.fn.keybase.filterItems();
            boxHeaders();
        });

        $('.keybase-filter-button-incl').click(function(e) {
            $('[name=excludedItems]>option:selected').each(function() {
                $(this).remove();
                $(this).removeAttr('selected')
                $('[name=includedItems]').append($(this));
            });
            sortOptions('includedItems');
            $.fn.keybase.filterItems();
            boxHeaders();
        });

        $('.keybase-filter-button-incl-all').click(function(e) {
            $('[name=excludedItems]>option').each(function() {
                $(this).remove();
                $(this).removeAttr('selected')
                $('[name=includedItems]').append($(this));
            });
            sortOptions('includedItems');
            $.fn.keybase.filterItems();
            boxHeaders();
        });

        $('.keybase-local-filter-cancel').click(function() {
            closeKeybaseLightbox();
        });

        $('.keybase-local-filter-ok').click(function() {
            closeKeybaseLightbox();

            if (filter_items.length) {
                setFilter();
                bracketedKey();
                settings.bracketedKeyDisplay(json);
                indentedKey();
                settings.indentedKeyDisplay();
            }
            else {
                removeFilter();
                bracketedKey();
                settings.bracketedKeyDisplay(json);
                indentedKey();
                settings.indentedKeyDisplay();
            }
        });

        settings.onFilterWindowOpen();
    };

    /**
     * function keybaseLightBox
     *
     * LightBox for the local filter.
     *
     * @param content
     */
    var keybaseLightBox = function(content) {
        // add lightbox/shadow
's if not previously added
        if($('#keybase-lightbox').length === 0){
            var theLightbox = $('
');
            theLightbox.append(
                '
' +
                    '' +
                    '
').
                append('

').
                append('

');

            var theShadow = $('
');
            theShadow.css('height', $(document).height() + 'px');
            $(theShadow).click(function(e){
                closeKeybaseLightbox();
            });

            $('body').append(theShadow);
            $('body').append(theLightbox);
            $(document).keydown(function (e) {
                if (e.keyCode == 27) {
                    closeKeybaseLightbox();
                }
            });
            $('.keybase-lightbox-close').click(function() {
                closeKeybaseLightbox();
            });
        }

        // remove any previously added content
        $('.keybase-lightbox-content').empty();

        // insert HTML content
        if(content != null){
            $('.keybase-lightbox-content').append(content);
        }

        // move the lightbox to the current window top + 100px
        $('#keybase-lightbox').css('top', $(window).scrollTop() + 100 + 'px');

        // display the lightbox
        $('#keybase-lightbox').show();
        $('#keybase-lightbox-shadow').show();

    };

    /**
     * function closeKeybaseLightbox
     *
     * Closes the light box.
     */
    var closeKeybaseLightbox = function() {
        $('#keybase-lightbox').hide();
        $('#keybase-lightbox-shadow').hide();
    };

    /**
     * function sortOptions
     *
     * Orders the options for the included and excluded items in the local filter.
     *
     * @param select
     */
    var sortOptions = function(select) {
        var options = $('[name=' + select + ']>option');
        options.sort(function(a,b) {
            if (a.text > b.text) return 1;
            else if (a.text option').length + ')');
        $('label[for="outitems"]').text('Excluded taxa ('
                + $('#outitems>option').length + ')');
    };

    /**
     * function $.fn.keybase.filterItems
     *
     * Creates an array of item IDs for items to filter on, based on the options
     * in the Included items select.
     */
    $.fn.keybase.filterItems = function() {
        filter_items = [];
        var initems = $('[name=includedItems]>option');
        var outitems = $('[name=excludedItems]>option');
        if (initems.length && outitems.length) {
            $('[name=includedItems]>option').each(function () {
                filter_items.push($(this).val());
            });
        }
    };

    /**
     * function setFilter
     *
     * Calls the function that creates the filtered key and restarts the key.
     */
    var setFilter = function() {
        filterLeads();
        next_id = rootNodeID;
        if ($('.keybase-player-window').length === 0) {
            settings.playerWindow();
            settings.playerEvents();
        }
        nextCouplet();

        if ($('.keybase-player-filter-remove').length === 0) {
            $('.keybase-player-filter')
                    .after(''
                            + '');
            if ($('link[rel=stylesheet][href*=font-awesome]').length > 0) {
                $('.keybase-player-filter-remove a')
                        .html('');
            }

            $('.keybase-player-filter-remove').click(function(e) {
                e.preventDefault();
                removeFilter();
            });
        }
    };

    /**
     * function filterLeads
     *
     * Creates the array with leads that need to be followed to key out all
     * items in the filter.
     */
    var filterLeads = function() {
        var path = '.{.item==$item}.left';
        var filter_nodes = JSPath.apply(path, nested_sets, {item: filter_items});

        filter_leads = [];
        var parents = [];
        $.each(filter_nodes, function(index, node) {
            var leads = JSPath.apply('.{.left <= '+ node + '}{.right >= '
                    + node + '}', nested_sets);
            $.each(leads, function(ind, lead) {
                if (filter_leads.indexOf(lead.lead_id) === -1) {
                    filter_leads.push(lead.lead_id);
                    parents.push(lead.parent_id);
                }
            });
        });

        // get object with parent_ids and their number of occurrences
        // in the filtered set
        filter_parents = parents.reduce(function (acc, curr) {
            if (typeof acc[curr] == 'undefined') {
                acc[curr] = 1;
            } else {
                acc[curr] += 1;
            }
            return acc;
        }, {});

    };

    /**
     * function removeFilter
     *
     * Destroys the filter.
     */
    var removeFilter = function() {
        filter_items = [];
        filter_leads = [];
        filter_parents = [];
        next_id = rootNodeID;
        nextCouplet();
        $('.keybase-player-filter').css('background-color', '#ddd');
        $('.keybase-player-filter-remove').remove();
    };

    /**
     *
     */
    var linkItems = function() {

        var linkThroughLeads =
                JSPath.apply('.leads{.lead_text==="[link through]"}', json);
        if (linkThroughLeads.length > 0) {
            $.each(linkThroughLeads, function(index, lead) {
                var item = JSPath('.items{.item_id==' + lead.item + '}', json)[0];
                var parentLead = JSPath('.leads{.lead_id==' + lead.parent_id + '}', json)[0];
                if (typeof parentLead.item !== 'undefined' && parentLead.item) {
                    item.parent_id = parentLead.item;
                }
            });
        }

/*      var link_through_leads =
                JSPath.apply('.leads{.lead_text==="[link through]"}.parent_id',
                        json);
        if (link_through_leads.length > 0) {
            var link_item_ids = [];
            var link_items = [];
            var removeLeads = [];
            $.each(json.leads, function(index, lead) {
                if (lead.lead_text === "[link through]") {
                    var parent_lead = JSPath.apply('.leads{.lead_id=="'
                            + lead.parent_id + '"}', json)[0];
                    if (link_item_ids.indexOf(lead.item) === -1) {
                        link_item_ids.push(lead.item);
                        var link_item = {
                            item_id: lead.item,
                            parent_id: parent_lead.item
                        };
                        link_items.push(link_item);
                    }
                    parent_lead.item += '_' + lead.item;
                    removeLeads.push(index);
                }
            });

            json.leads = $.grep(json.leads, function(n, i) {
                return $.inArray(i, removeLeads) === -1;
            });

            $.each(json.items, function(index, item) {
                var i = link_item_ids.indexOf(item.item_id);
                if (i > -1) {
                    var parent_item = JSPath.apply('.items{.item_id==="'
                            + link_items[i].parent_id + '"}', json)[0];
                    item.link_to_item_id = item.item_id;
                    item.item_id = parent_item.item_id + '_' + item.item_id;
                    item.link_to_item_name = item.item_name;
                    item.link_to_url = item.url;
                    item.link_to_key = item.to_key;
                    item.item_name = parent_item.item_name;
                    item.url = parent_item.url;
                    item.to_key = parent_item.to_key;
                }
            });

            var keyed_out_items = JSPath.apply('.leads{.item}.item', json);
            var removeItems = [];
            $.each(json.items, function(index, item) {
                if (keyed_out_items.indexOf(item.item_id) === -1) {
                    removeItems.push(index);
                }
            });

            json.items = $.grep(json.items, function(n, i) {
                return $.inArray(i, removeItems) === -1;
            });
        }
*/
    };

    var sortItems = function() {
        json.items.sort(function(a, b) {
            var sort_a = a.item_name +
                    (a.link_to_item_name ? a.link_to_item_name : '');
            var sort_b = b.item_name +
                    (b.link_to_item_name ? b.link_to_item_name : '');
            if (sort_a > sort_b) {
                return 1;
            }
            if (sort_a < sort_b) {
                return -1;
            }
            return 0;
        });
    };

    var unique = function(list) {
        var result = [];
        $.each(list, function(i, e) {
            if ($.inArray(e, result) == -1) result.push(e);
        });
        return result;
    }

}( jQuery ));


text:
package com.erep.elucs.cmd;

import com.erep.elucs.extractor.ErepublikDataExtractor;
import com.erep.elucs.extractor.ErpkErepublikDataExtractor;
import com.erep.elucs.model.json.exchange.ExchangeInfo;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.pircbotx.PircBotX;
import org.pircbotx.hooks.events.MessageEvent;

import java.util.List;

/**
 * @author dragos
 */
public class ExchangeCmd extends AbstractCmd {

    private final ErepublikDataExtractor erepublikDataExtractor;

    public ExchangeCmd(PircBotX botX) {
        super(botX, "mm", "<gold|cc> Displays first 10 offers af selling <gold|cc>.");
        erepublikDataExtractor = new ErpkErepublikDataExtractor();
    }

    @Override
    public void doLogic(CommandLine commandLine, MessageEvent event) {
        List argList = commandLine.getArgList();
        if (argList != null && argList.size() == 2) {
            Object arg = argList.get(1);
            if (arg instanceof String) {
                String param = (String) arg;
                int type = "gold".equals(param) ? 1 : ("cc".equals(param) ? 0 : -1);
                if (type >= 0) {
                    List<ExchangeInfo> exchangeInfos = erepublikDataExtractor.getExchangeInfo(type);
                    if (exchangeInfos != null && exchangeInfos.size() != 0) {
                        StringBuilder builder = new StringBuilder();
                        builder.append("Buy 1 ").append(param).append(" for : ");
                        for (ExchangeInfo info : exchangeInfos) {
                            builder.append(info.getRate()).append(" CC, ");
                        }
                        builder.delete(builder.length() - 1, builder.length());
                        sendMessage(event, builder.toString());
                    } else {
                        sendMessage(event, "No exchange offer received.");
                    }
                } else {
                    sendError(event, "Please use  gold or cc as parameter");
                }
            } else {
                sendError(event, "Please use  gold or cc as parameter");
            }
        } else {
            sendError(event, "Please use  gold or cc as parameter");
        }

    }

    @Override
    protected Options getCmdOptions() {
        return new Options();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package validatecode.xiaolian;

import android.support.v7.app.ActionBarActivity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

	public static final int MSG_RECEIVED_CODE = 1;
	private EditText et_validateCode= null;

	private SmsObserver mObserver;
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == MSG_RECEIVED_CODE) {
				String code =(String) msg.obj;
				//更新UI
				et_validateCode.setText(code);
			}
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		et_validateCode = 	(EditText) findViewById(R.id.et_validateCode);

		mObserver = new SmsObserver(MainActivity.this , mHandler);
		Uri uri = 	Uri.parse("content://sms");
		getContentResolver().registerContentObserver(uri, true, mObserver);
	}

	@Override
	protected void onPause() {
		super.onPause();
		getContentResolver().unregisterContentObserver(mObserver);
	}
}


text: package dupefinder


text:
<?php

class EarlyMedievalCoins_DenominationsController extends Pas_Controller_Action_Admin {

    /** The denominations model
     * @access protected
     * @var \Denominations
     */
    protected $_denominations;

    /** Initialise the ACL and contexts
     * @access public
     * @return void
     */
    public function init() {
        $this->_helper->_acl->allow(null);
        $this->_helper->contextSwitch()->setAutoJsonSerialization(false);
        $this->_helper->contextSwitch()
                ->setAutoDisableLayout(true)
                ->addActionContext('index', array('xml','json'))
                ->addActionContext('denomination', array('xml','json'))
                ->initContext();
    }

    /** Internal period number for querying the database
     * @access protected
     * @var integer
     */
    protected $_period = 47;

    /** Set up index page for denominations
     * @access public
     * @return void
     */
    public function indexAction() {
        $this->view->denominations = $this->_denominations
                ->getDenominations($this->_period, null);
    }

    /** Get details of each individual denomination
     * @access public
     * @return void
     * @throws Pas_Exception_Param
     */
    public function denominationAction() {
        if($this->_getParam('id',false)) {
        $this->view->id = $this->_getParam('id');
        $this->view->denoms = $this->_denominations->getDenom($this->_getParam('id'),(int)$this->_period);
        $this->view->rulers = $this->_denominations->getRulerDenomination($this->_getParam('id'));
        } else {
            throw new Pas_Exception_Param($this->_missingParameter, 500);
        }
    }
 }


text:
package org.apache.mxnet.spark.example

import org.apache.mxnet.spark.MXNet
import org.apache.mxnet.{Symbol, NDArray, Context, Shape}
import org.apache.spark.mllib.linalg.Vectors
import org.apache.spark.mllib.regression.LabeledPoint
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkContext, SparkConf}
import org.kohsuke.args4j.{Option, CmdLineParser}
import org.slf4j.{LoggerFactory, Logger}

import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConverters._

class ClassificationExample
object ClassificationExample {
  private val logger: Logger = LoggerFactory.getLogger(classOf[ClassificationExample])
  def main(args: Array[String]): Unit = {
    val cmdLine = new CommandLine
    val parser: CmdLineParser = new CmdLineParser(cmdLine)
    try {
      parser.parseArgument(args.toList.asJava)
      cmdLine.checkArguments()

      val conf = new SparkConf().setAppName("MXNet")
      val sc = new SparkContext(conf)

      val network = if (cmdLine.model == "mlp") getMlp else getLenet
      val dimension = if (cmdLine.model == "mlp") Shape(784) else Shape(1, 28, 28)
      val devs =
        if (cmdLine.gpus != null) cmdLine.gpus.split(',').map(id => Context.gpu(id.trim.toInt))
        else if (cmdLine.cpus != null) cmdLine.cpus.split(',').map(id => Context.cpu(id.trim.toInt))
        else Array(Context.cpu(0))

      val mxnet = new MXNet()
        .setBatchSize(128)
        .setLabelName("softmax_label")
        .setContext(devs)
        .setDimension(dimension)
        .setNetwork(network)
        .setNumEpoch(cmdLine.numEpoch)
        .setNumServer(cmdLine.numServer)
        .setNumWorker(cmdLine.numWorker)
        .setExecutorJars(cmdLine.jars)
        .setJava(cmdLine.java)

      val trainData = parseRawData(sc, cmdLine.input)
      val start = System.currentTimeMillis
      val model = mxnet.fit(trainData)
      val timeCost = System.currentTimeMillis - start
      logger.info("Training cost {} milli seconds", timeCost)
      model.save(sc, cmdLine.output + "/model")

      logger.info("Now do validation")
      val valData = parseRawData(sc, cmdLine.inputVal)

      val brModel = sc.broadcast(model)
      val res = valData.mapPartitions { data =>
        // get real labels
        import org.apache.spark.mllib.linalg.Vector
        val points = ArrayBuffer.empty[Vector]
        val y = ArrayBuffer.empty[Float]
        while (data.hasNext) {
          val evalData = data.next()
          y += evalData.label.toFloat
          points += evalData.features
        }

        // get predicted labels
        val probArrays = brModel.value.predict(points.toIterator)
        require(probArrays.length == 1)
        val prob = probArrays(0)
        val py = NDArray.argmax_channel(prob.get)
        require(y.length == py.size, s"${y.length} mismatch ${py.size}")

        // I'm too lazy to calculate the accuracy
        val res = Iterator((y.toArray zip py.toArray).map {
          case (y1, py1) => y1 + "," + py1 }.mkString("\n"))

        py.dispose()
        prob.get.dispose()
        res
      }
      res.saveAsTextFile(cmdLine.output + "/data")

      sc.stop()
    } catch {
      case e: Throwable =>
        e.printStackTrace()
        logger.error(e.getMessage, e)
        sys.exit(-1)
    }
  }

  private def parseRawData(sc: SparkContext, path: String): RDD[LabeledPoint] = {
    val raw = sc.textFile(path)
    raw.map { s =>
      val parts = s.split(' ')
      val label = java.lang.Double.parseDouble(parts(0))
      val features = Vectors.dense(parts(1).trim().split(',').map(java.lang.Double.parseDouble))
      LabeledPoint(label, features)
    }
  }

  private class CommandLine {
    @Option(name = "--input", usage = "Input training file.")
    val input: String = null
    @Option(name = "--input-val", usage = "Input validation file.")
    val inputVal: String = null
    @Option(name = "--output", usage = "Output inferred result.")
    val output: String = null
    @Option(name = "--jars", usage = "Jars for running MXNet on other nodes.")
    val jars: String = null
    @Option(name = "--num-server", usage = "PS server number")
    val numServer: Int = 1
    @Option(name = "--num-worker", usage = "PS worker number")
    val numWorker: Int = 1
    @Option(name = "--num-epoch", usage = "Number of epochs")
    val numEpoch: Int = 10
    @Option(name = "--java", usage = "Java bin")
    val java: String = "java"
    @Option(name = "--model", usage = "Model definition")
    val model: String = "mlp"
    @Option(name = "--gpus", usage = "the gpus will be used, e.g. '0,1,2,3'")
    val gpus: String = null
    @Option(name = "--cpus", usage = "the cpus will be used, e.g. '0,1,2,3'")
    val cpus: String = null

    def checkArguments(): Unit = {
      require(input != null, "Undefined input path")
      require(numServer > 0, s"Invalid number of servers: $numServer")
      require(numWorker > 0, s"Invalid number of workers: $numWorker")
    }
  }

  def getMlp: Symbol = {
    val data = Symbol.Variable("data")
    val fc1 = Symbol.FullyConnected(name = "fc1")()(Map("data" -> data, "num_hidden" -> 128))
    val act1 = Symbol.Activation(name = "relu1")()(Map("data" -> fc1, "act_type" -> "relu"))
    val fc2 = Symbol.FullyConnected(name = "fc2")()(Map("data" -> act1, "num_hidden" -> 64))
    val act2 = Symbol.Activation(name = "relu2")()(Map("data" -> fc2, "act_type" -> "relu"))
    val fc3 = Symbol.FullyConnected(name = "fc3")()(Map("data" -> act2, "num_hidden" -> 10))
    val mlp = Symbol.SoftmaxOutput(name = "softmax")()(Map("data" -> fc3))
    mlp
  }

  // LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick
  // Haffner. "Gradient-based learning applied to document recognition."
  // Proceedings of the IEEE (1998)
  def getLenet: Symbol = {
    val data = Symbol.Variable("data")
    // first conv
    val conv1 = Symbol.Convolution()()(
      Map("data" -> data, "kernel" -> "(5, 5)", "num_filter" -> 20))
    val tanh1 = Symbol.Activation()()(Map("data" -> conv1, "act_type" -> "tanh"))
    val pool1 = Symbol.Pooling()()(Map("data" -> tanh1, "pool_type" -> "max",
      "kernel" -> "(2, 2)", "stride" -> "(2, 2)"))
    // second conv
    val conv2 = Symbol.Convolution()()(
      Map("data" -> pool1, "kernel" -> "(5, 5)", "num_filter" -> 50))
    val tanh2 = Symbol.Activation()()(Map("data" -> conv2, "act_type" -> "tanh"))
    val pool2 = Symbol.Pooling()()(Map("data" -> tanh2, "pool_type" -> "max",
      "kernel" -> "(2, 2)", "stride" -> "(2, 2)"))
    // first fullc
    val flatten = Symbol.Flatten()()(Map("data" -> pool2))
    val fc1 = Symbol.FullyConnected()()(Map("data" -> flatten, "num_hidden" -> 500))
    val tanh3 = Symbol.Activation()()(Map("data" -> fc1, "act_type" -> "tanh"))
    // second fullc
    val fc2 = Symbol.FullyConnected()()(Map("data" -> tanh3, "num_hidden" -> 10))
    // loss
    val lenet = Symbol.SoftmaxOutput(name = "softmax")()(Map("data" -> fc2))
    lenet
  }
}


text:
describe ToyRobotSimulator::Robot do
  let(:robot) { ToyRobotSimulator::Robot.new(0, 0) }

  before { robot.place(1, 1, 'north') }

  describe '#place' do
    it { expect(robot.position).to eq({x: 1, y: 1}) }
    it { expect(robot.facing).to eq('north') }
  end

  describe '#move' do
    context 'when new coordinates are valid' do
      before { robot.move }

      it { expect(robot.position).to eq({x: 1, y: 2}) }
    end

    context 'when new coordinates are not valid' do
      before do
        robot.place(4, 4, 'north')
        robot.move
      end

      it { expect(robot.position).to eq({x: 4, y: 4}) }
    end
  end

  describe '#left' do
    before { robot.left }

    it { expect(robot.facing).to eq('west') }
  end

  describe '#right' do
    before { robot.right }

    it { expect(robot.facing).to eq('east') }
  end
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">

    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=0,minimum-scale=1.0,maximum-scale=1.0,minimal-ui" />
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <link rel="stylesheet" href="css/animate.min.css"/>
    <link rel="stylesheet" href="css/csshake.min.css"/>
    <link rel="stylesheet" href="css/main.css"/>
    <link rel="stylesheet" href="css/my_animate.css"/>

    <title>《一生所爱》520火热拍摄中!</title>

<audio preload id="bgm" class="bgm">
    <source src="img/media/sound/black.mp3" type="audio/mpeg">
</audio>

            loading

        <video class="ab" poster="" id="video_1" preload playsinline webkit-playsinline >
            <source src="img/media/video/1.mp4" />
        </video>


text:
Chat Bot

			<form role="form" ng-submit="submit()">

						<input type="text" class="form-control input-underline input-lg" id="" placeholder="UserId" ng-model = "loggeduser">

						<input type="password" class="form-control input-underline input-lg" id="" placeholder="Password">

				<button type="submit" class="btn btn-white btn-outline btn-lg btn-rounded">Login</button>

			</form>


text:
namespace space_invaders
{

class render_engine;

class bullet : public game_object
{
public:
	bullet(int x, int y, int8_t direction);
	void update();
	void on_collide(game_object* collider) override ;

protected:

private:
	static float speed;

};

}

#endif


text:
<plugin>
  <name>pbtypes</name>
  <description>gst-plugins-base dynamic types</description>
  <filename>../../gst/pbtypes/.libs/libgstpbtypes.so</filename>
  <basename>libgstpbtypes.so</basename>
  <version>1.16.2</version>
  <license>LGPL</license>
  <source>gst-plugins-base</source>
  <package>GStreamer Base Plug-ins source release</package>
  <origin>Unknown package origin</origin>
  <elements>
  </elements>
</plugin>


text:
package com.rozdoum.socialcomponents.managers;

import android.content.Context;

import com.google.firebase.database.ValueEventListener;
import com.rozdoum.socialcomponents.main.interactors.CommentInteractor;
import com.rozdoum.socialcomponents.managers.listeners.OnDataChangedListener;
import com.rozdoum.socialcomponents.managers.listeners.OnTaskCompleteListener;
import com.rozdoum.socialcomponents.model.Comment;

public class CommentManager extends FirebaseListenersManager {

    private static final String TAG = CommentManager.class.getSimpleName();
    private static CommentManager instance;

    private Context context;
    CommentInteractor commentInteractor;

    public static CommentManager getInstance(Context context) {
        if (instance == null) {
            instance = new CommentManager(context);
        }

        return instance;
    }

    private CommentManager(Context context) {
        this.context = context;
        commentInteractor = CommentInteractor.getInstance(context);
    }

    public void createOrUpdateComment(String commentText, String postId, OnTaskCompleteListener onTaskCompleteListener) {
        commentInteractor.createComment(commentText, postId, onTaskCompleteListener);
    }

    public void decrementCommentsCount(String postId, OnTaskCompleteListener onTaskCompleteListener) {
        commentInteractor.decrementCommentsCount(postId, onTaskCompleteListener);
    }

    public void getCommentsList(Context activityContext, String postId, OnDataChangedListener<Comment> onDataChangedListener) {
        ValueEventListener valueEventListener = commentInteractor.getCommentsList(postId, onDataChangedListener);
        addListenerToMap(activityContext, valueEventListener);
    }

    public void removeComment(String commentId, final String postId, final OnTaskCompleteListener onTaskCompleteListener) {
        commentInteractor.removeComment(commentId, postId, onTaskCompleteListener);
    }

    public void updateComment(String commentId, String commentText, String postId, OnTaskCompleteListener onTaskCompleteListener) {
        commentInteractor.updateComment(commentId, commentText, postId, onTaskCompleteListener);
    }
}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Main extends CI_Controller {

	public function __construct()
	{
		parent::__construct();

		$this->load->database();
		$this->load->helper('url');

		$this->load->library('grocery_CRUD');

        //$this->load->model('Grocery_crud_model'); // =================== AGREGADO =================== //
	}

	public function _example_output($output = null)
	{
		$this->load->view('example.php',$output);
	}

	public function offices()
	{
		$output = $this->grocery_crud->render();

		$this->_example_output($output);
	}

	public function index()
	{
		$this->_example_output((object)array('output' => '' , 'js_files' => array() , 'css_files' => array()));
	}

	public function offices_management()
	{
		try{
			$crud = new grocery_CRUD();

			$crud->set_theme('datatables');
			$crud->set_table('offices');
			$crud->set_subject('Office');
			$crud->required_fields('city');
			$crud->columns('city','country','phone','addressLine1','postalCode');

			$output = $crud->render();

			$this->_example_output($output);

		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}

	public function employees_management()
	{
			$crud = new grocery_CRUD();

			$crud->set_theme('datatables');
			$crud->set_table('employees');
			$crud->set_relation('officeCode','offices','city');
			$crud->display_as('officeCode','Office City');
			$crud->set_subject('Employee');

			$crud->required_fields('lastName');

			$crud->set_field_upload('file_url','assets/uploads/files');

			$output = $crud->render();

			$this->_example_output($output);
	}

	public function customers_management()
	{
			$crud = new grocery_CRUD();

			$crud->set_table('customers');
			$crud->columns('customerName','contactLastName','phone','city','country','salesRepEmployeeNumber','creditLimit');
			$crud->display_as('salesRepEmployeeNumber','from Employeer')
				 ->display_as('customerName','Name')
				 ->display_as('contactLastName','Last Name');
			$crud->set_subject('Customer');
			$crud->set_relation('salesRepEmployeeNumber','employees','lastName');

			$output = $crud->render();

			$this->_example_output($output);
	}

    public function miembros()
    {
        $crud = new grocery_CRUD();

        $crud->set_table('miembros');
        $crud->columns('nmiembro','nombre','apellido','movil','dojo','grado','estado','fechaingreso');
        //$crud->columns('customerName','contactLastName','phone','city','country','salesRepEmployeeNumber','creditLimit');
        $crud->display_as('nmiembro',    'Miembro #')
            ->display_as('nombre',      'Nombre')
            ->display_as('apellido',    'Apellido')
            ->display_as('movil',       'Móvil')
            ->display_as('dojo',        'Dojo')
            ->display_as('grado',       'Grado')
            ->display_as('estado',      'Estado')
            ->display_as('fechaingreso','Fecha de Ingreso');
        $crud->set_subject('Miembro');
        //$crud->set_relation('salesRepEmployeeNumber','employees','lastName');

        $output = $crud->render();

        $this->_example_output($output);
    }

	public function orders_management()
	{
			$crud = new grocery_CRUD();

			$crud->set_relation('customerNumber','customers','{contactLastName} {contactFirstName}');
			$crud->display_as('customerNumber','Customer');
			$crud->set_table('orders');
			$crud->set_subject('Order');
			$crud->unset_add();
			$crud->unset_delete();

			$output = $crud->render();

			$this->_example_output($output);
	}

	public function products_management()
	{
			$crud = new grocery_CRUD();

			$crud->set_table('products');
			$crud->set_subject('Product');
			$crud->unset_columns('productDescription');
			$crud->callback_column('buyPrice',array($this,'valueToEuro'));

			$output = $crud->render();

			$this->_example_output($output);
	}

	public function valueToEuro($value, $row)
	{
		return $value.' €';
	}

	public function film_management()
	{
		$crud = new grocery_CRUD();

		$crud->set_table('film');
		$crud->set_relation_n_n('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname','priority');
		$crud->set_relation_n_n('category', 'film_category', 'category', 'film_id', 'category_id', 'name');
		$crud->unset_columns('special_features','description','actors');

		$crud->fields('title', 'description', 'actors' ,  'category' ,'release_year', 'rental_duration', 'rental_rate', 'length', 'replacement_cost', 'rating', 'special_features');

		$output = $crud->render();

		$this->_example_output($output);
	}

	public function film_management_twitter_bootstrap()
	{
		try{
			$crud = new grocery_CRUD();

			$crud->set_theme('twitter-bootstrap');
			$crud->set_table('film');
			$crud->set_relation_n_n('actors', 'film_actor', 'actor', 'film_id', 'actor_id', 'fullname','priority');
			$crud->set_relation_n_n('category', 'film_category', 'category', 'film_id', 'category_id', 'name');
			$crud->unset_columns('special_features','description','actors');

			$crud->fields('title', 'description', 'actors' ,  'category' ,'release_year', 'rental_duration', 'rental_rate', 'length', 'replacement_cost', 'rating', 'special_features');

			$output = $crud->render();
			$this->_example_output($output);

		}catch(Exception $e){
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}

	function multigrids()
	{
		$this->config->load('grocery_crud');
		$this->config->set_item('grocery_crud_dialog_forms',true);
		$this->config->set_item('grocery_crud_default_per_page',10);

		$output1 = $this->offices_management2();

		$output2 = $this->employees_management2();

		$output3 = $this->customers_management2();

		$js_files = $output1->js_files + $output2->js_files + $output3->js_files;
		$css_files = $output1->css_files + $output2->css_files + $output3->css_files;
		$output = "
List 1
".$output1->output."
List 2
".$output2->output."
List 3
".$output3->output;

		$this->_example_output((object)array(
				'js_files' => $js_files,
				'css_files' => $css_files,
				'output'	=> $output
		));
	}

	public function offices_management2()
	{
		$crud = new grocery_CRUD();
		$crud->set_table('offices');
		$crud->set_subject('Office');

		$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)),site_url(strtolower(__CLASS__."/multigrids")));

		$output = $crud->render();

		if($crud->getState() != 'list') {
			$this->_example_output($output);
		} else {
			return $output;
		}
	}

	public function employees_management2()
	{
		$crud = new grocery_CRUD();

		$crud->set_theme('datatables');
		$crud->set_table('employees');
		$crud->set_relation('officeCode','offices','city');
		$crud->display_as('officeCode','Office City');
		$crud->set_subject('Employee');

		$crud->required_fields('lastName');

		$crud->set_field_upload('file_url','assets/uploads/files');

		$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)),site_url(strtolower(__CLASS__."/multigrids")));

		$output = $crud->render();

		if($crud->getState() != 'list') {
			$this->_example_output($output);
		} else {
			return $output;
		}
	}

	public function customers_management2()
	{
		$crud = new grocery_CRUD();

		$crud->set_table('customers');
		$crud->columns('customerName','contactLastName','phone','city','country','salesRepEmployeeNumber','creditLimit');
		$crud->display_as('salesRepEmployeeNumber','from Employeer')
			 ->display_as('customerName','Name')
			 ->display_as('contactLastName','Last Name');
		$crud->set_subject('Customer');
		$crud->set_relation('salesRepEmployeeNumber','employees','lastName');

		$crud->set_crud_url_path(site_url(strtolower(__CLASS__."/".__FUNCTION__)),site_url(strtolower(__CLASS__."/multigrids")));

		$output = $crud->render();

		if($crud->getState() != 'list') {
			$this->_example_output($output);
		} else {
			return $output;
		}
	}

}


text:
"""
    aboutwindow.py

    Python programming for the about window.
"""

try:
    import pygtk
    pygtk.require("2.0")
except:
    pass

from gi.repository import Gtk

class AboutWindow(object):
    """
        Class representing the about window.
    """

    window = None

    def __init__(self, application):
        builder = Gtk.Builder()
        builder.add_from_file("ui/About.glade")

        self.window = builder.get_object("AboutWindow")

        builder.connect_signals(self)
        self.window.set_visible(True)
        response = self.window.run()

    def user_response(self, element, event):
        """
            Signal that's called when the user submits a response to the about dialog.
        """

        self.window.destroy()


text:
package com.waynezhang.mcommon.support;

import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.view.ContextThemeWrapper;

import com.waynezhang.mcommon.util.ContextUtil;

/**
 * Created by jc0mm0n on 10/26/14.
 */
public class Safeguard {
    /**
     * <pre>
     * 判断是否需要忽略回调
     * 在对服务器发送请求后,页面已经关闭,但是回调没有及时销毁
     * 而这时候产生的回调如果对页面进行了某些操作都会导致应用异常
     *
     * 处理方法:
     * 在产生回调时先用此方法检查相关状态
     * </pre>
     * @param objects 可以是Activity, Fragment, View元素
     * @return true表示不需要再执行回调动作, false表示可以接着执行回调动作
     */
    public static boolean ignorable(Object... objects) {
        if (objects == null)
            return true;

        for (Object obj : objects) {
            if (obj instanceof Activity && !isValid((Activity) obj)) {
                return true;
            } else if (obj instanceof Fragment && !isValid((Fragment) obj)) {
                return true;
            } else if (obj instanceof ContextThemeWrapper && !isValid(ContextUtil.scanForActivity((Context) obj))) {
                return true;
            } else if (!isValid(obj)) {
                return true;
            }
        }
        return false;
    }

    private static boolean isValid(Activity activity) {
        if (activity == null)
            return false;

        return !activity.isFinishing();
    }

    private static boolean isValid(Fragment fragment) {
        if (fragment == null)
            return false;

        if (fragment.isDetached()) {
            return true;
        }

        return isValid(fragment.getActivity());
    }

    private static boolean isValid(Object obj) {
        return obj != null;
    }
}


text:
"""
The script shows how to train Augmented SBERT (In-Domain) strategy for STSb dataset with nlp textual augmentation.
We utilise nlpaug (https://github.com/makcedward/nlpaug) for data augmentation strategies over a single sentence.

We chose synonym replacement for our example with (can be extended to other techniques) -
    1. Word-embeddings (word2vec)
    2. WordNet
    3. Contextual word-embeddings (BERT)

Methodology:
Take a gold STSb pair, like (A, B, 0.6) Then replace synonyms in A and B, which gives you (A', B', 0.6)
These are the silver data and SBERT is finally trained on (gold + silver) STSb data.

Additional requirements:
pip install nlpaug

Information:
We went over the nlpaug package and found from our experience, the commonly used and effective technique
is synonym replacement with words. However feel free to use any textual data augmentation mentioned
in the example - (https://github.com/makcedward/nlpaug/blob/master/example/textual_augmenter.ipynb)

You could also extend the easy data augmentation methods for other languages too, a good example can be
found here - (https://github.com/makcedward/nlpaug/blob/master/example/textual_language_augmenter.ipynb)

Citation: https://arxiv.org/abs/2010.08240

Usage:
python train_sts_indomain_nlpaug.py
"""
from torch.utils.data import DataLoader
import torch
import math
from sentence_transformers import SentenceTransformer, LoggingHandler, losses, models, util
from sentence_transformers.evaluation import EmbeddingSimilarityEvaluator
from sentence_transformers.readers import STSBenchmarkDataReader, InputExample
import nlpaug.augmenter.word as naw
import logging
from datetime import datetime
import sys
import os
import gzip
import csv
import tqdm

#### Just some code to print debug information to stdout
logging.basicConfig(format='%(asctime)s - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S',
                    level=logging.INFO,
                    handlers=[LoggingHandler()])
#### /print debug information to stdout

#You can specify any huggingface/transformers pre-trained model here, for example, bert-base-uncased, roberta-base, xlm-roberta-base
model_name = sys.argv[1] if len(sys.argv) > 1 else 'bert-base-uncased'
device = "cuda" if torch.cuda.is_available() else "cpu"
batch_size = 16
num_epochs = 1

###### Read Datasets ######

#Check if dataset exsist. If not, download and extract  it
sts_dataset_path = 'datasets/stsbenchmark.tsv.gz'

if not os.path.exists(sts_dataset_path):
    util.http_get('https://sbert.net/datasets/stsbenchmark.tsv.gz', sts_dataset_path)

model_save_path = 'output/bi-encoder/stsb_indomain_eda_'+model_name.replace("/", "-")+'-'+datetime.now().strftime("%Y-%m-%d_%H-%M-%S")

###### Bi-encoder (sentence-transformers) ######
logging.info("Loading SBERT model: {}".format(model_name))
# Use Huggingface/transformers model (like BERT, RoBERTa, XLNet, XLM-R) for mapping tokens to embeddings
word_embedding_model = models.Transformer(model_name)

# Apply mean pooling to get one fixed sized sentence vector
pooling_model = models.Pooling(word_embedding_model.get_word_embedding_dimension(),
                               pooling_mode_mean_tokens=True,
                               pooling_mode_cls_token=False,
                               pooling_mode_max_tokens=False)

model = SentenceTransformer(modules=[word_embedding_model, pooling_model])

# Convert the dataset to a DataLoader ready for training
gold_samples = []
dev_samples = []
test_samples = []

with gzip.open(sts_dataset_path, 'rt', encoding='utf8') as fIn:
    reader = csv.DictReader(fIn, delimiter='\t', quoting=csv.QUOTE_NONE)
    for row in reader:
        score = float(row['score']) / 5.0  # Normalize score to range 0 ... 1
        inp_example = InputExample(texts=[row['sentence1'], row['sentence2']], label=score)

        if row['split'] == 'dev':
            dev_samples.append(inp_example)
        elif row['split'] == 'test':
            test_samples.append(inp_example)
        else:
            gold_samples.append(inp_example)

##################################################################################
#
# Data Augmentation: Synonym Replacement with word2vec, BERT, WordNet using nlpaug
#
##################################################################################

logging.info("Starting with synonym replacement...")

#### Synonym replacement using Word2Vec ####
# Download the word2vec pre-trained Google News corpus (GoogleNews-vectors-negative300.bin)
# link: https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sharing

# aug = naw.WordEmbsAug(
#     model_type='word2vec', model_path=model_dir+'GoogleNews-vectors-negative300.bin',
#     action="substitute")

#### Synonym replacement using WordNet ####
# aug = naw.SynonymAug(aug_src='wordnet')

#### Synonym replacement using BERT ####
aug = naw.ContextualWordEmbsAug(
    model_path=model_name, action="insert", device=device)

silver_samples = []
progress = tqdm.tqdm(unit="docs", total=len(gold_samples))

for sample in gold_samples:
    augmented_texts = aug.augment(sample.texts)
    inp_example = InputExample(texts=augmented_texts, label=sample.label)
    silver_samples.append(inp_example)
    progress.update(1)

progress.reset()
progress.close()
logging.info("Textual augmentation completed....")
logging.info("Number of silver pairs generated: {}".format(len(silver_samples)))

###################################################################
#
# Train SBERT model with both (gold + silver) STS benchmark dataset
#
###################################################################

logging.info("Read STSbenchmark (gold + silver) training dataset")
train_dataloader = DataLoader(gold_samples + silver_samples, shuffle=True, batch_size=batch_size)
train_loss = losses.CosineSimilarityLoss(model=model)

logging.info("Read STSbenchmark dev dataset")
evaluator = EmbeddingSimilarityEvaluator.from_input_examples(dev_samples, name='sts-dev')

# Configure the training.
warmup_steps = math.ceil(len(train_dataloader) * num_epochs * 0.1) #10% of train data for warm-up
logging.info("Warmup-steps: {}".format(warmup_steps))

# Train the SBERT model
model.fit(train_objectives=[(train_dataloader, train_loss)],
          evaluator=evaluator,
          epochs=num_epochs,
          evaluation_steps=1000,
          warmup_steps=warmup_steps,
          output_path=model_save_path
          )

##########################################################
#
# Evaluate SBERT performance on STS benchmark test dataset
#
##########################################################

model = SentenceTransformer(model_save_path)
test_evaluator = EmbeddingSimilarityEvaluator.from_input_examples(test_samples, name='sts-test')
test_evaluator(model, output_path=model_save_path)


text:
package net.chromarenderer.renderer.scene.acc;

import net.chromarenderer.AccStructType;
import net.chromarenderer.math.geometry.Geometry;

/**
 * @author bensteinert
 */
public class NoAccelerationImpl implements AccelerationStructure {

    private Iterable<? extends Geometry> geometryList;

    public NoAccelerationImpl(Iterable<? extends Geometry> geometryList) {
        this.geometryList = geometryList;
    }

    @Override
    public void intersect(IntersectionContext ctx) {
        for (Geometry geometry : geometryList) {
            ctx.checkGeometry(geometry);
        }
    }

    @Override
    public AccStructType getType() {
        return AccStructType.LIST;
    }
}


text:
.bottom-space{
    margin-bottom: 10px;
}