<commit_before>import he from 'he';

import dbServer from '../model/db-server';
import Editor from '../utils/editor';
import exportXML from '../utils/export-xml';
import exportJSON from '../utils/export-json';
import Transformer from '../utils/transformer';
import notify from '../view/notify';

class TableBuilder {

    /**
     * Initialise.
     */
    constructor(tableElem, xsltFilename) {
        this.tableElem = tableElem;
        this.xsltFilename = xsltFilename;
    }

    /**
     * Return the dataset.
     */
    getDataset(records) {
        return records.map((el) => {
            return el[this.xsltFilename].TEI;
        });
    }

    /**
     * Return the table columns.
     */
    getColumns() {
        let columns = [{data: null}];
        $('th:not(:first-child)').each(function() {
            columns.push({data: $(this).text().replace(/\s/g, "")});
        });
        return columns;
    }

    /**
     * Build the table.
     */
    build(dataSet) {
        return new Promise((resolve, reject) => {
            const columns = this.getColumns(),
                  table   = this.tableElem.DataTable({
                "data": dataSet,
                "dom": "Bfrtip",
                "deferRender": true,
                "colReorder": {
                    "fixedColumnsLeft": 1,
                },
                "columnDefs": [
                    {
                        "targets": "_all",
                        "render": function (data, type, full, meta) {
                            return he.decode(data.toString());  // Decode HTML entities
                        }
                    },
                    {
                        "searchable": false,
                        "orderable": false,
                        "targets": 0,
                        "className": "bg-faded",
                    }
                ],
                "columns": columns,
                "buttons": [
                    {
                        "extend": "collection",
                        "text": "Export",
                        "autoClose": true,
                        "buttons": [
                            {
                                "extend": "excelHtml5",
                                "title": "teiviewer-excel-export"
                                "className": "buttons-excel-export",
                                "exportOptions": {
                                    "columns": function (idx, data, node) {
                                        return idx !== 0 && idx !== 1;
                                    }
                                }
                            },
                            {
                                "extend": "csvHtml5",
                                "title": "teiviewer-csv-export"
                                "className": "buttons-csv-export",
                                "exportOptions": {
                                    "columns": function (idx, data, node) {
                                        return idx !== 0 && idx !== 1;
                                    }
                                }
                            },
                            {
                                "text": "XML",
                                "className": "buttons-xml-export",
                                "action": function (evt, dt, node, conf) {
                                    dbServer.getAll().then(function(records) {
                                        exportXML(records);
                                    }).catch(function(err) {
                                        notify(err.message, 'error');
                                        throw err;
                                    });
                                }
                            },
                            {
                                "text": "JSON",
                                "className": "buttons-json-export",
                                "action": function (evt, dt, node, conf) {
                                    dbServer.getAll().then(function(records) {
                                        exportJSON(dataSet, false);
                                    }).catch(function(err) {
                                        notify(err.message, 'error');
                                        throw err;
                                    });
                                }
                            },
                            {
                                "text": "JSONP",
                                "className": "buttons-jsonp-export",
                                "action": function (evt, dt, node, conf) {
                                    dbServer.getAll().then(function(records) {
                                        exportJSON(dataSet, true);
                                    }).catch(function(err) {
                                        notify(err.message, 'error');
                                        throw err;
                                    });
                                }
                            }
                        ]
                    },
                    {
                        "extend": "collection",
                        "text": "Edit",
                        "autoClose": true,
                        "buttons": [
                            {
                                "text": "Select All",
                                "extend": "selectAll"
                            },
                            {
                                "text": "Deselect",
                                "extend": "selectNone"
                            },
                            {
                                "text": "Delete",
                                "className": "buttons-delete",
                                "action": function (evt, dt, node, conf) {
                                    $('tbody tr.selected').each(function() {
                                        const id = parseInt($(this).attr('id'));
                                        dbServer.remove(id).then(function() {
                                            dt.rows('#' + id).remove().draw();
                                        }).catch(function(err) {
                                            notify(err.message, 'error');
                                            throw err;
                                        });
                                    });
                                }
                            },
                            {
                                "text": "Delete All",
                                "className": "buttons-delete-all",
                                "action": function (evt, dt, node, conf) {
                                    $('tbody tr').each(function() {
                                        const id = $(this).attr('id');
                                        dbServer.clear().then(function() {
                                            dt.rows().remove().draw();
                                        }).catch(function(err) {
                                            notify(err.message, 'error');
                                            throw err;
                                        });
                                    });
                                }
                            },
                            {
                                "text": "XML Editor",
                                "className": "buttons-xml-editor",
                                "action": function (evt, dt, node, conf) {
                                    if ($('tr.selected').length !== 1) {
                                        notify('Please select a single row to edit', 'info');
                                    } else {
                                        const id = parseInt($('tr.selected').attr('id'));

                                        // Load the record into the editor modal
                                        dbServer.get(id).then((record) => {
                                            $('#editor-modal').modal('show');
                                            const container = $('#editor-modal .modal-body')[0],
                                                  editor    = new Editor(container, record, this.xsltFilename);
                                            $('#editor-modal .modal-title').html(`Editing ${record.filename}`);
                                            editor.refresh();

                                            // Handle save button click event
                                            $('#editor-modal #save-xml').on('click', function(evt){
                                                editor.save();
                                                dt.rows('#' + id).data(record[this.xsltFilename]).draw();
                                                $('#editor-modal').modal('hide');
                                                notify('Record saved!', 'success');
                                            });
                                        }).catch(function (err) {
                                            notify(err.message, 'error');
                                            throw err;
                                        });
                                    }
                                }
                            },
                        ]
                    },
                    {
                        "extend": "collection",
                        "text": "View",
                        "buttons": [
                            "pageLength",
                            {
                                "extend": "colvis",
                                "columns": ":gt(0)"
                            }
                        ]
                    }
                ],
                "order": [[ 1, 'asc' ]],
                "select": {
                    "style": "os",
                    "selector": "td:first-child"
                }
            });

            // Add index column
            table.on('order.dt search.dt', function () {
                table.column(0, {search:'applied', order:'applied'})
                     .nodes()
                     .each(function (cell, i) {
                        cell.innerHTML = i+1;
                });
            }).draw();

            // Move table elements
            $("footer #table-pagination").html($(".dataTables_paginate"));
            $("footer #table-info").append($(".dataTables_info"));
            $(".dataTables_filter").remove();
            $('.navbar-nav').append($('.dt-buttons'));

            // Fix styles
            $('.dt-buttons>.buttons-collection').removeClass('btn-secondary');
            $('.dt-buttons>.buttons-collection').addClass('nav-link');
            $('.dt-buttons.btn-group').addClass('nav-item');

            // Fix tbody position
            $('.dataTable tbody').css('height', 'calc(100% - ' + $('thead').height() + 'px)');
            $('.dataTable tbody').css('top', $('thead').height() + 'px');

            // Handle search
            $("#table-search").on("keyup search input paste cut", function() {
                table.search(this.value).draw();
             });

            // Handle select all
            $('.select-all').on('click', table.rows().select);

            resolve(table);
        });
    }

    downloadDataset(url) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                jsonp: 'callback',
                jsonpCallback: 'callback',
                dataType: 'jsonp',
            }).done((dataSet) => {
                resolve(dataSet);
            }).fail(function(jqXHR, textStatus, errorThrown) {
                reject(`Error loading dataset: ${errorThrown}`);
            });
        });
    }

    buildFromDB() {
        let transformer = new Transformer(this.xsltFilename),
            allRecords  = [];

        return new Promise((resolve, reject) => {
            dbServer.getAll().then((records) => {
                allRecords = records;
                return transformer.filterRecordsToUpdate(allRecords);
            }).then((recordsToUpdate) => {
                if(recordsToUpdate.length) {
                    notify(`Transforming ${recordsToUpdate.length} records,
                           please wait...`, 'info');
                }
                return transformer.transformMultiple(recordsToUpdate);
            }).then((transformedRecords) => {
                return dbServer.updateAll(transformedRecords);
            }).then(() => {
                return this.build(this.getDataset(allRecords));
            }).then(function(table) {
                resolve(table);
            }).catch(function(err) {
                notify(err, 'error');
                throw err;
            });
        });
    }

    /** Build the table with data loaded from a JSONP URL. */
    buildFromJSONP(url) {
        return new Promise((resolve, reject) => {
            this.downloadDataset(url).then((dataset) => {
                return this.build(dataset);
            }).then(function(table) {
                table.buttons('.buttons-xml-export').disable();
                table.buttons('.buttons-delete').disable();
                table.buttons('.buttons-delete-all').disable();
                table.buttons('.buttons-xml-editor').disable();
                resolve(table);
            }).catch(function(err) {
                throw err;
            });
        });
    }
}

export default TableBuilder;<commit_msg>Add missing commas<commit_after>import he from 'he';

import dbServer from '../model/db-server';
import Editor from '../utils/editor';
import exportXML from '../utils/export-xml';
import exportJSON from '../utils/export-json';
import Transformer from '../utils/transformer';
import notify from '../view/notify';

class TableBuilder {

    /**
     * Initialise.
     */
    constructor(tableElem, xsltFilename) {
        this.tableElem = tableElem;
        this.xsltFilename = xsltFilename;
    }

    /**
     * Return the dataset.
     */
    getDataset(records) {
        return records.map((el) => {
            return el[this.xsltFilename].TEI;
        });
    }

    /**
     * Return the table columns.
     */
    getColumns() {
        let columns = [{data: null}];
        $('th:not(:first-child)').each(function() {
            columns.push({data: $(this).text().replace(/\s/g, "")});
        });
        return columns;
    }

    /**
     * Build the table.
     */
    build(dataSet) {
        return new Promise((resolve, reject) => {
            const columns = this.getColumns(),
                  table   = this.tableElem.DataTable({
                "data": dataSet,
                "dom": "Bfrtip",
                "deferRender": true,
                "colReorder": {
                    "fixedColumnsLeft": 1,
                },
                "columnDefs": [
                    {
                        "targets": "_all",
                        "render": function (data, type, full, meta) {
                            return he.decode(data.toString());  // Decode HTML entities
                        }
                    },
                    {
                        "searchable": false,
                        "orderable": false,
                        "targets": 0,
                        "className": "bg-faded",
                    }
                ],
                "columns": columns,
                "buttons": [
                    {
                        "extend": "collection",
                        "text": "Export",
                        "autoClose": true,
                        "buttons": [
                            {
                                "extend": "excelHtml5",
                                "title": "teiviewer-excel-export",
                                "className": "buttons-excel-export",
                                "exportOptions": {
                                    "columns": function (idx, data, node) {
                                        return idx !== 0 && idx !== 1;
                                    }
                                }
                            },
                            {
                                "extend": "csvHtml5",
                                "title": "teiviewer-csv-export",
                                "className": "buttons-csv-export",
                                "exportOptions": {
                                    "columns": function (idx, data, node) {
                                        return idx !== 0 && idx !== 1;
                                    }
                                }
                            },
                            {
                                "text": "XML",
                                "className": "buttons-xml-export",
                                "action": function (evt, dt, node, conf) {
                                    dbServer.getAll().then(function(records) {
                                        exportXML(records);
                                    }).catch(function(err) {
                                        notify(err.message, 'error');
                                        throw err;
                                    });
                                }
                            },
                            {
                                "text": "JSON",
                                "className": "buttons-json-export",
                                "action": function (evt, dt, node, conf) {
                                    dbServer.getAll().then(function(records) {
                                        exportJSON(dataSet, false);
                                    }).catch(function(err) {
                                        notify(err.message, 'error');
                                        throw err;
                                    });
                                }
                            },
                            {
                                "text": "JSONP",
                                "className": "buttons-jsonp-export",
                                "action": function (evt, dt, node, conf) {
                                    dbServer.getAll().then(function(records) {
                                        exportJSON(dataSet, true);
                                    }).catch(function(err) {
                                        notify(err.message, 'error');
                                        throw err;
                                    });
                                }
                            }
                        ]
                    },
                    {
                        "extend": "collection",
                        "text": "Edit",
                        "autoClose": true,
                        "buttons": [
                            {
                                "text": "Select All",
                                "extend": "selectAll"
                            },
                            {
                                "text": "Deselect",
                                "extend": "selectNone"
                            },
                            {
                                "text": "Delete",
                                "className": "buttons-delete",
                                "action": function (evt, dt, node, conf) {
                                    $('tbody tr.selected').each(function() {
                                        const id = parseInt($(this).attr('id'));
                                        dbServer.remove(id).then(function() {
                                            dt.rows('#' + id).remove().draw();
                                        }).catch(function(err) {
                                            notify(err.message, 'error');
                                            throw err;
                                        });
                                    });
                                }
                            },
                            {
                                "text": "Delete All",
                                "className": "buttons-delete-all",
                                "action": function (evt, dt, node, conf) {
                                    $('tbody tr').each(function() {
                                        const id = $(this).attr('id');
                                        dbServer.clear().then(function() {
                                            dt.rows().remove().draw();
                                        }).catch(function(err) {
                                            notify(err.message, 'error');
                                            throw err;
                                        });
                                    });
                                }
                            },
                            {
                                "text": "XML Editor",
                                "className": "buttons-xml-editor",
                                "action": function (evt, dt, node, conf) {
                                    if ($('tr.selected').length !== 1) {
                                        notify('Please select a single row to edit', 'info');
                                    } else {
                                        const id = parseInt($('tr.selected').attr('id'));

                                        // Load the record into the editor modal
                                        dbServer.get(id).then((record) => {
                                            $('#editor-modal').modal('show');
                                            const container = $('#editor-modal .modal-body')[0],
                                                  editor    = new Editor(container, record, this.xsltFilename);
                                            $('#editor-modal .modal-title').html(`Editing ${record.filename}`);
                                            editor.refresh();

                                            // Handle save button click event
                                            $('#editor-modal #save-xml').on('click', function(evt){
                                                editor.save();
                                                dt.rows('#' + id).data(record[this.xsltFilename]).draw();
                                                $('#editor-modal').modal('hide');
                                                notify('Record saved!', 'success');
                                            });
                                        }).catch(function (err) {
                                            notify(err.message, 'error');
                                            throw err;
                                        });
                                    }
                                }
                            },
                        ]
                    },
                    {
                        "extend": "collection",
                        "text": "View",
                        "buttons": [
                            "pageLength",
                            {
                                "extend": "colvis",
                                "columns": ":gt(0)"
                            }
                        ]
                    }
                ],
                "order": [[ 1, 'asc' ]],
                "select": {
                    "style": "os",
                    "selector": "td:first-child"
                }
            });

            // Add index column
            table.on('order.dt search.dt', function () {
                table.column(0, {search:'applied', order:'applied'})
                     .nodes()
                     .each(function (cell, i) {
                        cell.innerHTML = i+1;
                });
            }).draw();

            // Move table elements
            $("footer #table-pagination").html($(".dataTables_paginate"));
            $("footer #table-info").append($(".dataTables_info"));
            $(".dataTables_filter").remove();
            $('.navbar-nav').append($('.dt-buttons'));

            // Fix styles
            $('.dt-buttons>.buttons-collection').removeClass('btn-secondary');
            $('.dt-buttons>.buttons-collection').addClass('nav-link');
            $('.dt-buttons.btn-group').addClass('nav-item');

            // Fix tbody position
            $('.dataTable tbody').css('height', 'calc(100% - ' + $('thead').height() + 'px)');
            $('.dataTable tbody').css('top', $('thead').height() + 'px');

            // Handle search
            $("#table-search").on("keyup search input paste cut", function() {
                table.search(this.value).draw();
             });

            // Handle select all
            $('.select-all').on('click', table.rows().select);

            resolve(table);
        });
    }

    downloadDataset(url) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: url,
                jsonp: 'callback',
                jsonpCallback: 'callback',
                dataType: 'jsonp',
            }).done((dataSet) => {
                resolve(dataSet);
            }).fail(function(jqXHR, textStatus, errorThrown) {
                reject(`Error loading dataset: ${errorThrown}`);
            });
        });
    }

    buildFromDB() {
        let transformer = new Transformer(this.xsltFilename),
            allRecords  = [];

        return new Promise((resolve, reject) => {
            dbServer.getAll().then((records) => {
                allRecords = records;
                return transformer.filterRecordsToUpdate(allRecords);
            }).then((recordsToUpdate) => {
                if(recordsToUpdate.length) {
                    notify(`Transforming ${recordsToUpdate.length} records,
                           please wait...`, 'info');
                }
                return transformer.transformMultiple(recordsToUpdate);
            }).then((transformedRecords) => {
                return dbServer.updateAll(transformedRecords);
            }).then(() => {
                return this.build(this.getDataset(allRecords));
            }).then(function(table) {
                resolve(table);
            }).catch(function(err) {
                notify(err, 'error');
                throw err;
            });
        });
    }

    /** Build the table with data loaded from a JSONP URL. */
    buildFromJSONP(url) {
        return new Promise((resolve, reject) => {
            this.downloadDataset(url).then((dataset) => {
                return this.build(dataset);
            }).then(function(table) {
                table.buttons('.buttons-xml-export').disable();
                table.buttons('.buttons-delete').disable();
                table.buttons('.buttons-delete-all').disable();
                table.buttons('.buttons-xml-editor').disable();
                resolve(table);
            }).catch(function(err) {
                throw err;
            });
        });
    }
}

export default TableBuilder;<|endoftext|>


<commit_before>/* global APP, $, config */
/* jshint -W101 */
import JitsiPopover from "../util/JitsiPopover";
import VideoLayout from "./VideoLayout";

/**
 * Constructs new connection indicator.
 * @param videoContainer the video container associated with the indicator.
 * @constructor
 */
function ConnectionIndicator(videoContainer, id) {
    this.videoContainer = videoContainer;
    this.bandwidth = null;
    this.packetLoss = null;
    this.bitrate = null;
    this.showMoreValue = false;
    this.resolution = null;
    this.isResolutionHD = null;
    this.transport = [];
    this.popover = null;
    this.id = id;
    this.create();
}

/**
 * Values for the connection quality
 * @type {{98: string,
 *         81: string,
 *         64: string,
 *         47: string,
 *         30: string,
 *         0: string}}
 */
ConnectionIndicator.connectionQualityValues = {
    98: "18px", //full
    81: "15px",//4 bars
    64: "11px",//3 bars
    47: "7px",//2 bars
    30: "3px",//1 bar
    0: "0px"//empty
};

ConnectionIndicator.getIP = function(value) {
    return value.substring(0, value.lastIndexOf(":"));
};

ConnectionIndicator.getPort = function(value) {
    return value.substring(value.lastIndexOf(":") + 1, value.length);
};

ConnectionIndicator.getStringFromArray = function (array) {
    var res = "";
    for(var i = 0; i < array.length; i++) {
        res += (i === 0? "" : ", ") + array[i];
    }
    return res;
};

/**
 * Generates the html content.
 * @returns {string} the html content.
 */
ConnectionIndicator.prototype.generateText = function () {
    var downloadBitrate, uploadBitrate, packetLoss, i;

    var translate = APP.translation.translateString;

    if(this.bitrate === null) {
        downloadBitrate = "N/A";
        uploadBitrate = "N/A";
    }
    else {
        downloadBitrate =
            this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
        uploadBitrate =
            this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
    }

    if(this.packetLoss === null) {
        packetLoss = "N/A";
    } else {

        packetLoss = "↓" +
            (this.packetLoss.download !== null ?
                this.packetLoss.download : "N/A") +
            "% ↑" +
            (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
            "%";
    }

    // GENERATE RESOLUTIONS STRING
    let resolutions = this.resolution || {};
    let resolutionStr = Object.keys(resolutions).map(function (ssrc) {
        let {width, height} = resolutions[ssrc];
        return `${width}x${height}`;
    }).join(', ') || 'N/A';

    var result = "
" +
        "
" +
        "" +
        translate("connectionindicator.bitrate") + "	" +
        "↓" +
        downloadBitrate + " ↑" +
        uploadBitrate + "	" +
        "

" +
        "" +
        translate("connectionindicator.packetloss") + "	" +
        "" + packetLoss  + "	" +
        "

" +
        "" +
        translate("connectionindicator.resolution") + "	" +
        "" + resolutionStr + "

";

    if(this.videoContainer.videoSpanId == "localVideoContainer") {
        result += "
" +
            translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
            "

";
    }

    if (this.showMoreValue) {
        var downloadBandwidth, uploadBandwidth, transport;
        if (this.bandwidth === null) {
            downloadBandwidth = "N/A";
            uploadBandwidth = "N/A";
        } else {
            downloadBandwidth = this.bandwidth.download?
                this.bandwidth.download + " Kbps" :
                "N/A";
            uploadBandwidth = this.bandwidth.upload?
                this.bandwidth.upload + " Kbps" :
                "N/A";
        }

        if (!this.transport || this.transport.length === 0) {
            transport = "
" +
                "" +
                translate("connectionindicator.address") + "	" +
                " N/A
";
        } else {
            var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
            for(i = 0; i < this.transport.length; i++) {
                var ip =  ConnectionIndicator.getIP(this.transport[i].ip);
                var port = ConnectionIndicator.getPort(this.transport[i].ip);
                var localIP =
                    ConnectionIndicator.getIP(this.transport[i].localip);
                var localPort =
                    ConnectionIndicator.getPort(this.transport[i].localip);
                if(data.remoteIP.indexOf(ip) == -1) {
                    data.remoteIP.push(ip);
                }

                if(data.remotePort.indexOf(port) == -1) {
                    data.remotePort.push(port);
                }

                if(data.localIP.indexOf(localIP) == -1) {
                    data.localIP.push(localIP);
                }

                if(data.localPort.indexOf(localPort) == -1) {
                    data.localPort.push(localPort);
                }
            }

            var local_address_key = "connectionindicator.localaddress";
            var remote_address_key = "connectionindicator.remoteaddress";
            var localTransport =
                "
" +
                    translate(local_address_key, {count: data.localIP.length}) +
                    "	 " +
                ConnectionIndicator.getStringFromArray(data.localIP) +
                "
";
            transport =
                "
" +
                    translate(remote_address_key,
                        {count: data.remoteIP.length}) +
                    "	 " +
                ConnectionIndicator.getStringFromArray(data.remoteIP) +
                "
";

            var key_remote = "connectionindicator.remoteport",
                key_local = "connectionindicator.localport";

            transport += "
" +
                "" +
                "" +
                translate(key_remote, {count: this.transport.length}) +
                "	";
            localTransport += "
" +
                "" +
                "" +
                translate(key_local, {count: this.transport.length}) +
                "	";

            transport +=
                ConnectionIndicator.getStringFromArray(data.remotePort);
            localTransport +=
                ConnectionIndicator.getStringFromArray(data.localPort);
            transport += "
";
            transport += localTransport + "
";
            transport +="
" +
                "" +
                translate("connectionindicator.transport") + "	" +
                "" + this.transport[0].type + "
";

        }

        result += "
" +
            "
" +
            "" +
            "" +
            translate("connectionindicator.bandwidth") + "" +
            "	" +
            "↓" +
            downloadBandwidth +
            " ↑" +
            uploadBandwidth + "
";

        result += transport + "
";
    }

    return result;
};

/**
 * Shows or hide the additional information.
 */
ConnectionIndicator.prototype.showMore = function () {
    this.showMoreValue = !this.showMoreValue;
    this.updatePopoverData();
};

function createIcon(classes, iconClass) {
    var icon = document.createElement("span");
    for(var i in classes) {
        icon.classList.add(classes[i]);
    }
    icon.appendChild(
        document.createElement("i")).classList.add(iconClass);
    return icon;
}

/**
 * Creates the indicator
 */
ConnectionIndicator.prototype.create = function () {
    this.connectionIndicatorContainer = document.createElement("div");
    this.connectionIndicatorContainer.className = "connectionindicator";
    this.connectionIndicatorContainer.style.display = "none";
    this.videoContainer.container.appendChild(
        this.connectionIndicatorContainer);
    this.popover = new JitsiPopover(
        $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
        {content: "
" +
            APP.translation.translateString("connectionindicator.na") + "
",
            skin: "black"});

    // override popover show method to make sure we will update the content
    // before showing the popover
    var origShowFunc = this.popover.show;
    this.popover.show = function () {
        // update content by forcing it, to finish even if popover
        // is not visible
        this.updatePopoverData(true);
        // call the original show, passing its actual this
        origShowFunc.call(this.popover);
    }.bind(this);

    this.emptyIcon = this.connectionIndicatorContainer.appendChild(
        createIcon(["connection", "connection_empty"], "icon-connection"));
    this.fullIcon = this.connectionIndicatorContainer.appendChild(
        createIcon(["connection", "connection_full"], "icon-connection"));
};

/**
 * Removes the indicator
 */
ConnectionIndicator.prototype.remove = function() {
    if (this.connectionIndicatorContainer.parentNode) {
        this.connectionIndicatorContainer.parentNode.removeChild(
            this.connectionIndicatorContainer);
    }
    this.popover.forceHide();
};

/**
 * Updates the data of the indicator
 * @param percent the percent of connection quality
 * @param object the statistics data.
 */
ConnectionIndicator.prototype.updateConnectionQuality =
    function (percent, object) {
    if (percent === null) {
        this.connectionIndicatorContainer.style.display = "none";
        this.popover.forceHide();
        return;
    } else {
        if(this.connectionIndicatorContainer.style.display == "none") {
            this.connectionIndicatorContainer.style.display = "block";
        }
    }
    this.bandwidth = object.bandwidth;
    this.bitrate = object.bitrate;
    this.packetLoss = object.packetLoss;
    this.transport = object.transport;
    if (object.resolution) {
        this.resolution = object.resolution;
    }
    for (var quality in ConnectionIndicator.connectionQualityValues) {
        if (percent >= quality) {
            this.fullIcon.style.width =
                ConnectionIndicator.connectionQualityValues[quality];
        }
    }
    if (object.isResolutionHD) {
        this.isResolutionHD = object.isResolutionHD;
    }
    this.updateResolutionIndicator();
    this.updatePopoverData();
};

/**
 * Updates the resolution
 * @param resolution the new resolution
 */
ConnectionIndicator.prototype.updateResolution = function (resolution) {
    this.resolution = resolution;
    this.updateResolutionIndicator();
    this.updatePopoverData();
};

/**
 * Updates the content of the popover if its visible
 * @param force to work even if popover is not visible
 */
ConnectionIndicator.prototype.updatePopoverData = function (force) {
    // generate content, translate it and add it to document only if
    // popover is visible or we force to do so.
    if(this.popover.popoverShown || force) {
        this.popover.updateContent(
            `<div class="connection_info">${this.generateText()}</div>`
        );
        APP.translation.translateElement($(".connection_info"));
    }
};

/**
 * Hides the popover
 */
ConnectionIndicator.prototype.hide = function () {
    this.popover.forceHide();
};

/**
 * Hides the indicator
 */
ConnectionIndicator.prototype.hideIndicator = function () {
    this.connectionIndicatorContainer.style.display = "none";
    if(this.popover)
        this.popover.forceHide();
};

/**
 * Updates the resolution indicator.
 */
ConnectionIndicator.prototype.updateResolutionIndicator = function () {

    if (this.id !== null
        && VideoLayout.isCurrentlyOnLarge(this.id)) {

        let showResolutionLabel = false;

        if (this.isResolutionHD !== null)
            showResolutionLabel = this.isResolutionHD;
        else if (this.resolution !== null) {
            let resolutions = this.resolution || {};
            Object.keys(resolutions).map(function (ssrc) {
                    let {width, height} = resolutions[ssrc];
                    if (height >= config.minHDHeight)
                        showResolutionLabel = true;
                });
        }

        VideoLayout.updateResolutionLabel(showResolutionLabel);
    }
};

export default ConnectionIndicator;
<commit_msg>ref(ConnectionIndicator.js): make CQ 'object' optional<commit_after>/* global APP, $, config */
/* jshint -W101 */
import JitsiPopover from "../util/JitsiPopover";
import VideoLayout from "./VideoLayout";

/**
 * Constructs new connection indicator.
 * @param videoContainer the video container associated with the indicator.
 * @constructor
 */
function ConnectionIndicator(videoContainer, id) {
    this.videoContainer = videoContainer;
    this.bandwidth = null;
    this.packetLoss = null;
    this.bitrate = null;
    this.showMoreValue = false;
    this.resolution = null;
    this.isResolutionHD = null;
    this.transport = [];
    this.popover = null;
    this.id = id;
    this.create();
}

/**
 * Values for the connection quality
 * @type {{98: string,
 *         81: string,
 *         64: string,
 *         47: string,
 *         30: string,
 *         0: string}}
 */
ConnectionIndicator.connectionQualityValues = {
    98: "18px", //full
    81: "15px",//4 bars
    64: "11px",//3 bars
    47: "7px",//2 bars
    30: "3px",//1 bar
    0: "0px"//empty
};

ConnectionIndicator.getIP = function(value) {
    return value.substring(0, value.lastIndexOf(":"));
};

ConnectionIndicator.getPort = function(value) {
    return value.substring(value.lastIndexOf(":") + 1, value.length);
};

ConnectionIndicator.getStringFromArray = function (array) {
    var res = "";
    for(var i = 0; i < array.length; i++) {
        res += (i === 0? "" : ", ") + array[i];
    }
    return res;
};

/**
 * Generates the html content.
 * @returns {string} the html content.
 */
ConnectionIndicator.prototype.generateText = function () {
    var downloadBitrate, uploadBitrate, packetLoss, i;

    var translate = APP.translation.translateString;

    if(this.bitrate === null) {
        downloadBitrate = "N/A";
        uploadBitrate = "N/A";
    }
    else {
        downloadBitrate =
            this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
        uploadBitrate =
            this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
    }

    if(this.packetLoss === null) {
        packetLoss = "N/A";
    } else {

        packetLoss = "↓" +
            (this.packetLoss.download !== null ?
                this.packetLoss.download : "N/A") +
            "% ↑" +
            (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
            "%";
    }

    // GENERATE RESOLUTIONS STRING
    let resolutions = this.resolution || {};
    let resolutionStr = Object.keys(resolutions).map(function (ssrc) {
        let {width, height} = resolutions[ssrc];
        return `${width}x${height}`;
    }).join(', ') || 'N/A';

    var result = "
" +
        "
" +
        "" +
        translate("connectionindicator.bitrate") + "	" +
        "↓" +
        downloadBitrate + " ↑" +
        uploadBitrate + "	" +
        "

" +
        "" +
        translate("connectionindicator.packetloss") + "	" +
        "" + packetLoss  + "	" +
        "

" +
        "" +
        translate("connectionindicator.resolution") + "	" +
        "" + resolutionStr + "

";

    if(this.videoContainer.videoSpanId == "localVideoContainer") {
        result += "
" +
            translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
            "

";
    }

    if (this.showMoreValue) {
        var downloadBandwidth, uploadBandwidth, transport;
        if (this.bandwidth === null) {
            downloadBandwidth = "N/A";
            uploadBandwidth = "N/A";
        } else {
            downloadBandwidth = this.bandwidth.download?
                this.bandwidth.download + " Kbps" :
                "N/A";
            uploadBandwidth = this.bandwidth.upload?
                this.bandwidth.upload + " Kbps" :
                "N/A";
        }

        if (!this.transport || this.transport.length === 0) {
            transport = "
" +
                "" +
                translate("connectionindicator.address") + "	" +
                " N/A
";
        } else {
            var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
            for(i = 0; i < this.transport.length; i++) {
                var ip =  ConnectionIndicator.getIP(this.transport[i].ip);
                var port = ConnectionIndicator.getPort(this.transport[i].ip);
                var localIP =
                    ConnectionIndicator.getIP(this.transport[i].localip);
                var localPort =
                    ConnectionIndicator.getPort(this.transport[i].localip);
                if(data.remoteIP.indexOf(ip) == -1) {
                    data.remoteIP.push(ip);
                }

                if(data.remotePort.indexOf(port) == -1) {
                    data.remotePort.push(port);
                }

                if(data.localIP.indexOf(localIP) == -1) {
                    data.localIP.push(localIP);
                }

                if(data.localPort.indexOf(localPort) == -1) {
                    data.localPort.push(localPort);
                }
            }

            var local_address_key = "connectionindicator.localaddress";
            var remote_address_key = "connectionindicator.remoteaddress";
            var localTransport =
                "
" +
                    translate(local_address_key, {count: data.localIP.length}) +
                    "	 " +
                ConnectionIndicator.getStringFromArray(data.localIP) +
                "
";
            transport =
                "
" +
                    translate(remote_address_key,
                        {count: data.remoteIP.length}) +
                    "	 " +
                ConnectionIndicator.getStringFromArray(data.remoteIP) +
                "
";

            var key_remote = "connectionindicator.remoteport",
                key_local = "connectionindicator.localport";

            transport += "
" +
                "" +
                "" +
                translate(key_remote, {count: this.transport.length}) +
                "	";
            localTransport += "
" +
                "" +
                "" +
                translate(key_local, {count: this.transport.length}) +
                "	";

            transport +=
                ConnectionIndicator.getStringFromArray(data.remotePort);
            localTransport +=
                ConnectionIndicator.getStringFromArray(data.localPort);
            transport += "
";
            transport += localTransport + "
";
            transport +="
" +
                "" +
                translate("connectionindicator.transport") + "	" +
                "" + this.transport[0].type + "
";

        }

        result += "
" +
            "
" +
            "" +
            "" +
            translate("connectionindicator.bandwidth") + "" +
            "	" +
            "↓" +
            downloadBandwidth +
            " ↑" +
            uploadBandwidth + "
";

        result += transport + "
";
    }

    return result;
};

/**
 * Shows or hide the additional information.
 */
ConnectionIndicator.prototype.showMore = function () {
    this.showMoreValue = !this.showMoreValue;
    this.updatePopoverData();
};

function createIcon(classes, iconClass) {
    var icon = document.createElement("span");
    for(var i in classes) {
        icon.classList.add(classes[i]);
    }
    icon.appendChild(
        document.createElement("i")).classList.add(iconClass);
    return icon;
}

/**
 * Creates the indicator
 */
ConnectionIndicator.prototype.create = function () {
    this.connectionIndicatorContainer = document.createElement("div");
    this.connectionIndicatorContainer.className = "connectionindicator";
    this.connectionIndicatorContainer.style.display = "none";
    this.videoContainer.container.appendChild(
        this.connectionIndicatorContainer);
    this.popover = new JitsiPopover(
        $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
        {content: "
" +
            APP.translation.translateString("connectionindicator.na") + "
",
            skin: "black"});

    // override popover show method to make sure we will update the content
    // before showing the popover
    var origShowFunc = this.popover.show;
    this.popover.show = function () {
        // update content by forcing it, to finish even if popover
        // is not visible
        this.updatePopoverData(true);
        // call the original show, passing its actual this
        origShowFunc.call(this.popover);
    }.bind(this);

    this.emptyIcon = this.connectionIndicatorContainer.appendChild(
        createIcon(["connection", "connection_empty"], "icon-connection"));
    this.fullIcon = this.connectionIndicatorContainer.appendChild(
        createIcon(["connection", "connection_full"], "icon-connection"));
};

/**
 * Removes the indicator
 */
ConnectionIndicator.prototype.remove = function() {
    if (this.connectionIndicatorContainer.parentNode) {
        this.connectionIndicatorContainer.parentNode.removeChild(
            this.connectionIndicatorContainer);
    }
    this.popover.forceHide();
};

/**
 * Updates the data of the indicator
 * @param percent the percent of connection quality
 * @param object the statistics data.
 */
ConnectionIndicator.prototype.updateConnectionQuality =
    function (percent, object) {
    if (percent === null) {
        this.connectionIndicatorContainer.style.display = "none";
        this.popover.forceHide();
        return;
    } else {
        if(this.connectionIndicatorContainer.style.display == "none") {
            this.connectionIndicatorContainer.style.display = "block";
        }
    }
    if (object) {
        this.bandwidth = object.bandwidth;
        this.bitrate = object.bitrate;
        this.packetLoss = object.packetLoss;
        this.transport = object.transport;
        if (object.resolution) {
            this.resolution = object.resolution;
        }
    }
    for (var quality in ConnectionIndicator.connectionQualityValues) {
        if (percent >= quality) {
            this.fullIcon.style.width =
                ConnectionIndicator.connectionQualityValues[quality];
        }
    }
    if (object && typeof object.isResolutionHD === 'boolean') {
        this.isResolutionHD = object.isResolutionHD;
    }
    this.updateResolutionIndicator();
    this.updatePopoverData();
};

/**
 * Updates the resolution
 * @param resolution the new resolution
 */
ConnectionIndicator.prototype.updateResolution = function (resolution) {
    this.resolution = resolution;
    this.updateResolutionIndicator();
    this.updatePopoverData();
};

/**
 * Updates the content of the popover if its visible
 * @param force to work even if popover is not visible
 */
ConnectionIndicator.prototype.updatePopoverData = function (force) {
    // generate content, translate it and add it to document only if
    // popover is visible or we force to do so.
    if(this.popover.popoverShown || force) {
        this.popover.updateContent(
            `<div class="connection_info">${this.generateText()}</div>`
        );
        APP.translation.translateElement($(".connection_info"));
    }
};

/**
 * Hides the popover
 */
ConnectionIndicator.prototype.hide = function () {
    this.popover.forceHide();
};

/**
 * Hides the indicator
 */
ConnectionIndicator.prototype.hideIndicator = function () {
    this.connectionIndicatorContainer.style.display = "none";
    if(this.popover)
        this.popover.forceHide();
};

/**
 * Updates the resolution indicator.
 */
ConnectionIndicator.prototype.updateResolutionIndicator = function () {

    if (this.id !== null
        && VideoLayout.isCurrentlyOnLarge(this.id)) {

        let showResolutionLabel = false;

        if (this.isResolutionHD !== null)
            showResolutionLabel = this.isResolutionHD;
        else if (this.resolution !== null) {
            let resolutions = this.resolution || {};
            Object.keys(resolutions).map(function (ssrc) {
                    let {width, height} = resolutions[ssrc];
                    if (height >= config.minHDHeight)
                        showResolutionLabel = true;
                });
        }

        VideoLayout.updateResolutionLabel(showResolutionLabel);
    }
};

export default ConnectionIndicator;
<|endoftext|>


<commit_before>// Copyright (c) 2020, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.ui.form.on('System Console', {
	refresh: function(frm) {
		frm.disable_save();
		frm.page.set_primary_action(__("Execute"), () => {
			frm.execute_action('Execute');
		});
	}
});
<commit_msg>Update frappe/desk/doctype/system_console/system_console.js<commit_after>// Copyright (c) 2020, Frappe Technologies and contributors
// For license information, please see license.txt

frappe.ui.form.on('System Console', {
	onload: function(frm) {
		frappe.ui.keys.add_shortcut({
			shortcut: 'shift+enter',
			action: () => frm.execute_action('Execute'),
			page: frm.page,
			description: __('Execute Console script'),
			ignore_inputs: true,
		});
	},

	refresh: function(frm) {
		frm.disable_save();
		frm.page.set_primary_action(__("Execute"), () => {
			frm.execute_action('Execute');
		});
	}
});
<|endoftext|>


<commit_before>/*jslint indent: 2, unparam: true*/
/*global $: false, document: false, togglbutton: false*/

'use strict';

togglbutton.render('#issue_view:not(.toggl)', {}, function (elem) {
  var
    projectSelect, project, link, container, spanTag,
    issue_id = $('#issue_overview', elem).getAttribute('data-issue-id'),
    description = $('#issue_overview #issue_summary', elem).textContent;

  // find the project dropdown
  // if the dropdown exists, its multiproject
  // otherwise take it from text value
  projectSelect = $('#project_chooser > form > select[name=current_project]', elem);
  project = projectSelect
    ? projectSelect.options[projectSelect.selectedIndex].text
    : $('#project_chooser').textContent.replace(/^\s+Project:\s/, '');

  link = togglbutton.createTimerLink({
    className: 'eventum',
    description: '#' + issue_id + ' ' + description,
    projectName: project
  });

  container = $('div#issue_menu', elem);

  spanTag = document.createElement("span");
  container.parentNode.appendChild(spanTag.appendChild(link));
});
<commit_msg>update eventum button selector<commit_after>/*jslint indent: 2, unparam: true*/
/*global $: false, document: false, togglbutton: false*/

'use strict';

togglbutton.render('.issue_view:not(.toggl)', {}, function (elem) {
  var
    projectSelect, project, link, container, spanTag,
    issue_id = $('#issue_overview', elem).getAttribute('data-issue-id'),
    description = $('#issue_overview #issue_summary', elem).textContent;

  // find the project dropdown
  // if the dropdown exists, its multiproject
  // otherwise take it from text value
  projectSelect = $('#project_chooser > form > select[name=current_project]', elem);
  project = projectSelect
    ? projectSelect.options[projectSelect.selectedIndex].text
    : $('#project_chooser').textContent.replace(/^\s+Project:\s/, '');

  link = togglbutton.createTimerLink({
    className: 'eventum',
    description: '#' + issue_id + ' ' + description,
    projectName: project
  });

  container = $('div#issue_menu', elem);

  spanTag = document.createElement("span");
  container.parentNode.appendChild(spanTag.appendChild(link));
});
<|endoftext|>


<commit_before>import { default as React, Component } from "react";

import { render } from "../src";

describe("special cases", () => {
  it("renders empty comments for components that return null", () => {
    const NullComponent = () => null;

    return render(<NullComponent />)
      .toPromise()
      .then(html => expect(html).to.equal(""));
  });
  it("does not render text comments for children without siblings", () => {
    const TextComponent = () => "some text";

    return render(<TextComponent />).toPromise()
      .then(html => expect(html).to.equal("some text"));
  });
  it("renders text comments for children with siblings", () => {
    const TextWithSiblingsComponent = () =>

child 1
child 2
;

    // eslint-disable-next-line max-len
    const expected = "

child 1
child 2
";

    return render(<TextWithSiblingsComponent />)
      .toPromise()
      .then(html => expect(html).to.equal(expected));
  });
  it("renders text comments for empty text with siblings", () => {
    const EmptyTextComponent = () =>
{""}
foo

;

    // eslint-disable-next-line max-len
    const expected = "

foo

";

    return render(<EmptyTextComponent />).toPromise().then(html => {
      expect(html).to.equal(expected);
    });
  });
  it("renders components that don't pass constructor arguments to super", () => {
    class C extends Component {
      constructor () {
        super();
      }
      render () {
        return
{this.props.foo}
;
      }
    }
    return render(<C foo="bar"/>).includeDataReactAttrs(false).toPromise().then(html => {
      expect(html).to.equal("
bar
");
    });
  });
});
<commit_msg>Fix: test can handle [] in __html<commit_after>import { default as React, Component } from "react";

import { render } from "../src";
import { checkParity, getRootNode } from "./_util";

describe("special cases", () => {
  it("renders empty comments for components that return null", () => {
    const NullComponent = () => null;

    return render(<NullComponent />)
      .toPromise()
      .then(html => expect(html).to.equal(""));
  });
  it("does not render text comments for children without siblings", () => {
    const TextComponent = () => "some text";

    return render(<TextComponent />).toPromise()
      .then(html => expect(html).to.equal("some text"));
  });
  it("renders text comments for children with siblings", () => {
    const TextWithSiblingsComponent = () =>

child 1
child 2
;

    // eslint-disable-next-line max-len
    const expected = "

child 1
child 2
";

    return render(<TextWithSiblingsComponent />)
      .toPromise()
      .then(html => expect(html).to.equal(expected));
  });
  it("renders text comments for empty text with siblings", () => {
    const EmptyTextComponent = () =>
{""}
foo

;

    // eslint-disable-next-line max-len
    const expected = "

foo

";

    return render(<EmptyTextComponent />).toPromise().then(html => {
      expect(html).to.equal(expected);
    });
  });
  it("renders components that don't pass constructor arguments to super", () => {
    class C extends Component {
      constructor () {
        super();
      }
      render () {
        return
{this.props.foo}
;
      }
    }
    return render(<C foo="bar"/>).includeDataReactAttrs(false).toPromise().then(html => {
      expect(html).to.equal("
bar
");
    });
  });
  it("can handle [] in __html", () => {
    checkParity(getRootNode(`
      return () =>


<commit_before>/**
 * Views for the story viewer Backbone application
 */
Namespace('storybase.viewer');

// Container view for the viewer application.
// It delegates rendering and events for the entire app to views
// rendering more specific "widgets"
storybase.viewer.views.ViewerApp = Backbone.View.extend({
  // Initialize the view
  initialize: function() {
    this.navigationView = new storybase.viewer.views.StoryNavigation();
    this.headerView = new storybase.viewer.views.StoryHeader();
    this.sections = this.options.sections;
    this.story = this.options.story;
    this.setSection(this.sections.at(0));
  },

  // Add the view's container element to the DOM and render the sub-views
  render: function() {
    this.$('footer').append(this.navigationView.el);
    this.navigationView.render();
    return this;
  },

  // Update the active story section in the sub-views
  updateSubviewSections: function() {
    this.navigationView.setSection(this.activeSection);
    this.headerView.setSection(this.activeSection);
  },

  // Set the active story section
  setSection: function(section) {
    this.activeSection = section;
    this.updateSubviewSections();
  },

  // Like setSection(), but takes a section ID as an argument instead of
  // a Section model instance object
  setSectionById: function(id) {
    this.setSection(this.sections.get(id));
  },

  // Convenience method to get the element for the active
  activeSectionEl: function() {
    return this.$('#' + this.activeSection.id);
  }
});

// View for the story viewer header.
// Updates the section heading title when the active section changes
storybase.viewer.views.StoryHeader = Backbone.View.extend({
  el: 'header',

  render: function() {
    var $titleEl = this.$el.find('.section-title').first();
    if ($titleEl.length == 0) {
      $titleEl = $('
');
      this.$el.append($titleEl);
    }
    $titleEl.text(this.section.get('title'));
    return this;
  },

  setSection: function(section) {
    this.section = section;
    this.render();
  }
});

// View to provide previous/next buttons to navigate between sections
storybase.viewer.views.StoryNavigation = Backbone.View.extend({
  tagName: 'nav',

  className: 'story-nav',

  initialize: function() {
    this.section = null;
    if (this.options.hasOwnProperty('addlLinks')) {
      this.addlLinks = this.options.addlLinks.map(function(link) {
        return {
         text: link.text,
         id: link.id,
         href: link.hasOwnProperty('href') ? link.href: '#'
       }
      });
    }
    else {
      this.addlLinks = [];
    }
  },

  render: function() {
    var context = {};
    if (this.section) {
      context.next_section = this.section.collection.get(
        this.section.get('next_section_id'));
      context.previous_section = this.section.collection.get(
        this.section.get('previous_section_id'));
    }
    context.addl_links = this.addlLinks;

    this.$el.html(ich.navigationTemplate(context));
    return this;
  },

  setSection: function(section) {
    this.section = section;
    this.render();
  }
});

// Interative visualization of a spider story structure
storybase.viewer.views.Spider = Backbone.View.extend({
  events: {
    "hover g.node": "hoverSectionNode"
  },

  initialize: function() {
    this.sections = this.options.sections;
    this.activeSection = null;
    // The id for the visualization's wrapper element
    this.visId = 'spider-vis';
  },

  // Return the visualization wrapper element
  visEl: function() {
    return this.$('#' + this.visId).first();
  },

  setSection: function(section) {
    this.activeSection = section;
    this.highlightSectionNode(this.activeSection.id);
  },

  highlightSectionNode: function(sectionId) {
    d3.selectAll('g.node').classed('active', false);
    d3.select('g.node.section-' + sectionId).classed('active', true);
  },

  render: function() {
    var elId = this.$el.attr('id');
    var width = this.$el.width();
    var height = this.$el.height();
    var vis = d3.select("#" + elId).insert("svg", "section")
        .attr("id", this.visId)
        .attr("width", width)
        .attr("height", height)
      .append("g")
      .attr("transform", "translate(40, 100)");
    var rootSection = this.sections.at(0).populateChildren();
    var tree = d3.layout.tree().size([300, 150]);
    var diagonal = d3.svg.diagonal();
    var nodes = tree.nodes(rootSection);
    var links = tree.links(nodes);

    var link = vis.selectAll("path.link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", diagonal);

    var node = vis.selectAll("g.node")
      .data(nodes)
      .enter().append("g")
      .attr('class', function(d) {
        return "node section-" + d.id;
      })
      .attr("transform",function(d) { return "translate(" + d.x + "," + d.y + ")"; });

    node.append("circle")
        .attr("r", 10);

    node.append("text")
      .attr("dx", function(d) { return d.children ? -20 : 20; })
      .attr("dy", 3)
      .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .text(function(d) { return d.get('title'); })

  },

  // Event handler for hovering over a section node
  // Changes the cursor to a "pointer" style icon to indicate that
  // the nodes are clickable.
  hoverSectionNode: function(e) {
    e.currentTarget.style.cursor = 'pointer';
  },
});

// Master view that shows the story structure visualization initially
storybase.viewer.views.SpiderViewerApp = storybase.viewer.views.ViewerApp.extend({
  events: {
    "click #topic-map": "clickTopicMapLink",
    "click g.node": "clickSectionNode"
  },

  initialize: function() {
    this.navigationView = new storybase.viewer.views.StoryNavigation({
      addlLinks: [{text: "Topic Map", id: 'topic-map'}]
    });
    this.headerView = new storybase.viewer.views.StoryHeader();
    this.initialView = new storybase.viewer.views.Spider({
      el: this.$('#body'),
      sections: this.options.sections
    });
    this.sections = this.options.sections;
    this.story = this.options.story;
  },

  render: function() {
    this.$('footer').append(this.navigationView.el);
    this.navigationView.render();
    this.initialView.render();
    // Hide all the section content initially
    this.$('section').hide();
    return this;
  },

  // Update the active story section in the sub-views
  updateSubviewSections: function() {
    storybase.viewer.views.ViewerApp.prototype.updateSubviewSections.call(this);
    this.initialView.setSection(this.activeSection);
    // Hide all sections other than the active one
    this.$('section').hide();
    this.$('#' + this.activeSection.id).show();
    this.initialView.$('svg').hide();
  },

  // Event handler for clicks on a section node
  clickSectionNode: function(e) {
    var node = d3.select(e.currentTarget);
    var sectionId = node.data()[0].id;
    this.initialView.visEl().hide();
    // TODO: I'm not sure if this is the best way to access the router
    // I don't like global variables, but passing it as an argument
    // makes for a weird circular dependency between the master view/
    // router.
    storybase.viewer.router.navigate("sections/" + sectionId,
                                     {trigger: true});
  },

  // Event handler for clicking the "Topic Map" link
  clickTopicMapLink: function(e) {
    this.activeSectionEl().toggle();
    this.initialView.visEl().show();
  }

});

// Get the appropriate master view based on the story structure type
storybase.viewer.views.getViewerApp = function(structureType, options) {
  if (structureType == 'linear') {
    return new storybase.viewer.views.ViewerApp(options);
  }
  else if (structureType == 'spider') {
    return new storybase.viewer.views.SpiderViewerApp(options);
  }
  else {
    throw "Unknown story structure type '" + structureType + "'";
  }
};
<commit_msg>Avoid call super anti-pattern<commit_after>/**
 * Views for the story viewer Backbone application
 */
Namespace('storybase.viewer');

// Container view for the viewer application.
// It delegates rendering and events for the entire app to views
// rendering more specific "widgets"
storybase.viewer.views.ViewerApp = Backbone.View.extend({
  // Initialize the view
  initialize: function() {
    this.navigationView = new storybase.viewer.views.StoryNavigation();
    this.headerView = new storybase.viewer.views.StoryHeader();
    this.sections = this.options.sections;
    this.story = this.options.story;
    this.setSection(this.sections.at(0));
  },

  // Add the view's container element to the DOM and render the sub-views
  render: function() {
    this.$('footer').append(this.navigationView.el);
    this.navigationView.render();
    return this;
  },

  // Update the active story section in the sub-views
  updateSubviewSections: function() {
    this.navigationView.setSection(this.activeSection);
    this.headerView.setSection(this.activeSection);
  },

  // Set the active story section
  setSection: function(section) {
    this.activeSection = section;
    this.updateSubviewSections();
  },

  // Like setSection(), but takes a section ID as an argument instead of
  // a Section model instance object
  setSectionById: function(id) {
    this.setSection(this.sections.get(id));
  },

  // Convenience method to get the element for the active
  activeSectionEl: function() {
    return this.$('#' + this.activeSection.id);
  }
});

// View for the story viewer header.
// Updates the section heading title when the active section changes
storybase.viewer.views.StoryHeader = Backbone.View.extend({
  el: 'header',

  render: function() {
    var $titleEl = this.$el.find('.section-title').first();
    if ($titleEl.length == 0) {
      $titleEl = $('
');
      this.$el.append($titleEl);
    }
    $titleEl.text(this.section.get('title'));
    return this;
  },

  setSection: function(section) {
    this.section = section;
    this.render();
  }
});

// View to provide previous/next buttons to navigate between sections
storybase.viewer.views.StoryNavigation = Backbone.View.extend({
  tagName: 'nav',

  className: 'story-nav',

  initialize: function() {
    this.section = null;
    if (this.options.hasOwnProperty('addlLinks')) {
      this.addlLinks = this.options.addlLinks.map(function(link) {
        return {
         text: link.text,
         id: link.id,
         href: link.hasOwnProperty('href') ? link.href: '#'
       }
      });
    }
    else {
      this.addlLinks = [];
    }
  },

  render: function() {
    var context = {};
    if (this.section) {
      context.next_section = this.section.collection.get(
        this.section.get('next_section_id'));
      context.previous_section = this.section.collection.get(
        this.section.get('previous_section_id'));
    }
    context.addl_links = this.addlLinks;

    this.$el.html(ich.navigationTemplate(context));
    return this;
  },

  setSection: function(section) {
    this.section = section;
    this.render();
  }
});

// Interative visualization of a spider story structure
storybase.viewer.views.Spider = Backbone.View.extend({
  events: {
    "hover g.node": "hoverSectionNode"
  },

  initialize: function() {
    this.sections = this.options.sections;
    this.activeSection = null;
    // The id for the visualization's wrapper element
    this.visId = 'spider-vis';
  },

  // Return the visualization wrapper element
  visEl: function() {
    return this.$('#' + this.visId).first();
  },

  setSection: function(section) {
    this.activeSection = section;
    this.highlightSectionNode(this.activeSection.id);
  },

  highlightSectionNode: function(sectionId) {
    d3.selectAll('g.node').classed('active', false);
    d3.select('g.node.section-' + sectionId).classed('active', true);
  },

  render: function() {
    var elId = this.$el.attr('id');
    var width = this.$el.width();
    var height = this.$el.height();
    var vis = d3.select("#" + elId).insert("svg", "section")
        .attr("id", this.visId)
        .attr("width", width)
        .attr("height", height)
      .append("g")
      .attr("transform", "translate(40, 100)");
    var rootSection = this.sections.at(0).populateChildren();
    var tree = d3.layout.tree().size([300, 150]);
    var diagonal = d3.svg.diagonal();
    var nodes = tree.nodes(rootSection);
    var links = tree.links(nodes);

    var link = vis.selectAll("path.link")
        .data(links)
      .enter().append("path")
        .attr("class", "link")
        .attr("d", diagonal);

    var node = vis.selectAll("g.node")
      .data(nodes)
      .enter().append("g")
      .attr('class', function(d) {
        return "node section-" + d.id;
      })
      .attr("transform",function(d) { return "translate(" + d.x + "," + d.y + ")"; });

    node.append("circle")
        .attr("r", 10);

    node.append("text")
      .attr("dx", function(d) { return d.children ? -20 : 20; })
      .attr("dy", 3)
      .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
      .text(function(d) { return d.get('title'); })

  },

  // Event handler for hovering over a section node
  // Changes the cursor to a "pointer" style icon to indicate that
  // the nodes are clickable.
  hoverSectionNode: function(e) {
    e.currentTarget.style.cursor = 'pointer';
  },
});

// Master view that shows the story structure visualization initially
storybase.viewer.views.SpiderViewerApp = storybase.viewer.views.ViewerApp.extend({
  events: {
    "click #topic-map": "clickTopicMapLink",
    "click g.node": "clickSectionNode"
  },

  initialize: function() {
    this.navigationView = new storybase.viewer.views.StoryNavigation({
      addlLinks: [{text: "Topic Map", id: 'topic-map'}]
    });
    this.headerView = new storybase.viewer.views.StoryHeader();
    this.initialView = new storybase.viewer.views.Spider({
      el: this.$('#body'),
      sections: this.options.sections
    });
    this.sections = this.options.sections;
    this.story = this.options.story;
  },

  render: function() {
    this.$('footer').append(this.navigationView.el);
    this.navigationView.render();
    this.initialView.render();
    // Hide all the section content initially
    this.$('section').hide();
    return this;
  },

  // Update the active story section in the sub-views
  updateSubviewSections: function() {
    this.navigationView.setSection(this.activeSection);
    this.headerView.setSection(this.activeSection);
    this.initialView.setSection(this.activeSection);
    // Hide all sections other than the active one
    this.$('section').hide();
    this.$('#' + this.activeSection.id).show();
    this.initialView.$('svg').hide();
  },

  // Event handler for clicks on a section node
  clickSectionNode: function(e) {
    var node = d3.select(e.currentTarget);
    var sectionId = node.data()[0].id;
    this.initialView.visEl().hide();
    // TODO: I'm not sure if this is the best way to access the router
    // I don't like global variables, but passing it as an argument
    // makes for a weird circular dependency between the master view/
    // router.
    storybase.viewer.router.navigate("sections/" + sectionId,
                                     {trigger: true});
  },

  // Event handler for clicking the "Topic Map" link
  clickTopicMapLink: function(e) {
    this.activeSectionEl().toggle();
    this.initialView.visEl().show();
  }

});

// Get the appropriate master view based on the story structure type
storybase.viewer.views.getViewerApp = function(structureType, options) {
  if (structureType == 'linear') {
    return new storybase.viewer.views.ViewerApp(options);
  }
  else if (structureType == 'spider') {
    return new storybase.viewer.views.SpiderViewerApp(options);
  }
  else {
    throw "Unknown story structure type '" + structureType + "'";
  }
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
const request = require('request');
const { ChannelProcessor } = require('./channelProcessor');
const { discordApiToken, graphqlApiBaseUrl } = require('./secrets');
const queryFactory = require('./graphql/queryFactory');

const client = new Discord.Client();

const channelProcessorMap = {};

client.on('ready', () => {
  console.log('Bot is ready');
});

client.on('message', (message) => {
  const { channel } = message;
  const channelID = channel.id;

  if (channelProcessorMap[channelID] == null) {
    const newChannelProcessor = new ChannelProcessor(channelID);
    newChannelProcessor.setOnHaikuFunction((haiku) => {
      console.log(`Haiku triggered:
        author: ${haiku.author}
        lines: ${haiku.lines}`);

      const haikuInput = {
        haiku: {
          author: haiku.author.id,
          lines: haiku.lines,
        },
      };

      const requestOptions = {
        method: 'POST',
        url: graphqlApiBaseUrl,
        json: true,
        body: queryFactory.createHaikuMutation(haiku)
      };

      request(requestOptions, (err, res, body) => {
        console.log(err);
        console.log(body);
        const responseHaiku = body.data.createHaiku;
        console.log(responseHaiku);
        channel.send(`<@${responseHaiku.author}> has created a beautiful Haiku!
          "${responseHaiku.lines[0]}
          ${responseHaiku.lines[1]}
          ${responseHaiku.lines[2]}"
           - Haiku #${responseHaiku.id}`);
      });
    });
    channelProcessorMap[channelID] = newChannelProcessor;
  }

  channelProcessorMap[channelID].processMessage(message);
});

client.login(discordApiToken);
<commit_msg>Add better error handling<commit_after>const Discord = require('discord.js');
const request = require('request');
const { ChannelProcessor } = require('./channelProcessor');
const { discordApiToken, graphqlApiBaseUrl } = require('./secrets');
const queryFactory = require('./graphql/queryFactory');

const client = new Discord.Client();

const channelProcessorMap = {};

client.on('ready', () => {
  console.log('Bot is ready');
});

client.on('message', (message) => {
  const { channel } = message;
  const channelID = channel.id;

  if (channelProcessorMap[channelID] == null) {
    const newChannelProcessor = new ChannelProcessor(channelID);
    newChannelProcessor.setOnHaikuFunction((haiku) => {
      console.log(`Haiku triggered:
        author: ${haiku.author}
        lines: ${haiku.lines}`);

      const requestBody = queryFactory.createHaikuMutation(haiku);
      const requestOptions = {
        method: 'POST',
        url: graphqlApiBaseUrl,
        json: true,
        body: requestBody,
      };

      request(requestOptions, (err, res, body) => {
        if (err != null) {
          console.log('Error saving haiku.');
          console.log(` request body: ${JSON.stringify(requestBody)}`);
          console.log(` err: ${err}`);
          console.log(` response body: ${body}`);
        } else {
          const responseHaiku = body.data.createHaiku;
          channel.send(`<@${responseHaiku.author}> has created a beautiful Haiku!
            "${responseHaiku.lines[0]}
            ${responseHaiku.lines[1]}
            ${responseHaiku.lines[2]}"
             - Haiku #${responseHaiku.id}`);
        }
      });
    });
    channelProcessorMap[channelID] = newChannelProcessor;
  }

  channelProcessorMap[channelID].processMessage(message);
});

client.login(discordApiToken);
<|endoftext|>


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

const fs = require('fs');
const optimist = require('optimist');
const delboy = require('../index');

const argv = optimist
    .usage('delBoy  publish --> Publish current module')
    .usage('delBoy  --> dry run')
    .default({ dir: process.cwd()})
    .describe('u', 'The base URL of the Reggie server (e.g. http://reggie:8080)')
    .describe('dir', 'the directory from where we want to build the package (eg. current directy)')
    .describe('package', 'the package.json (eg. package.json)')
    .alias('u', 'url')
    .alias('dir', 'directory')
    .argv;

argv.command = argv._[0];

if (argv.h) {
  optimist.showHelp();
  process.exit(0);
}

const packageInfo = JSON.parse(fs.readFileSync(`${argv.dir}/package.json`));

const registry = argv.u ? argv.u : packageInfo.publishConfig.registry;

const publishPackage = () => {
    if (!registry) {
        console.error('ups, private npm server url not found, please provide one via package.json (publishConfig: {registry: server-url} or via command line with -u option');
        process.exit(0);
    }
    delBoy.publish(argv.dir, registry, packageInfo.name, packageInfo.version);
}

if (argv.command === 'publish') {
    publishPackage();

} else {
    console.log('dry run!...');
    console.log(`packageName: ${ packageInfo.name }, version: ${packageInfo.version}, and it would be published to ${registry}`);
    delBoy.dryRun(argv.dir);
    console.log('run del-boy publish to make the actual publishing of the package');
}
<commit_msg>Fix variable name error in del-boy-cli<commit_after>#!/usr/bin/env node

const fs = require('fs');
const optimist = require('optimist');
const delboy = require('../index');

const argv = optimist
    .usage('del-boy-cli publish   --> Publish current module')
    .usage('del-boy-cli   --> dry run')
    .default({ dir: process.cwd()})
    .describe('u', 'The base URL of the Reggie server (e.g. http://reggie:8080)')
    .describe('dir', 'the directory from where we want to build the package (eg. current directy)')
    .describe('package', 'the package.json (eg. package.json)')
    .alias('u', 'url')
    .alias('dir', 'directory')
    .argv;

argv.command = argv._[0];

if (argv.h) {
  optimist.showHelp();
  process.exit(0);
}

const packageInfo = JSON.parse(fs.readFileSync(`${argv.dir}/package.json`));

const registry = argv.u ? argv.u : packageInfo.publishConfig.registry;

const publishPackage = () => {
    if (!registry) {
        console.error('ups, private npm server url not found, please provide one via package.json (publishConfig: {registry: server-url} or via command line with -u option');
        process.exit(0);
    }
    delboy.publish(argv.dir, registry, packageInfo.name, packageInfo.version);
}

if (argv.command === 'publish') {
    publishPackage();

} else {
    console.log('dry run!...');
    console.log(`packageName: ${ packageInfo.name }, version: ${packageInfo.version}, and it would be published to ${registry}`);
    delboy.dryRun(argv.dir);
    console.log('run del-boy publish to make the actual publishing of the package');
}
<|endoftext|>


<commit_before>(function() {

    'use strict';

    /* eslint-disable angular/no-service-method */
    angular.module('facetApp')

    .service('norssitService', norssitService);

    /* @ngInject */
    function norssitService($q, $location, _, FacetResultHandler, SPARQL_ENDPOINT_URL) {

        /* Public API */

        // Get the results based on facet selections.
        // Return a promise.
        this.getResults = getResults;
        // Get the facets.
        // Return a promise (because of translation).
        this.getFacets = getFacets;
        // Get the facet options.
        // Return an object.
        this.getFacetOptions = getFacetOptions;
        // Update sorting URL params.
        this.updateSortBy = updateSortBy;
        // Get the CSS class for the sort icon.
        this.getSortClass = getSortClass;

        /* Implementation */

        var facets = {
            // Text search facet for name
            entryText: {
                facetId: 'entryText',
                predicate: '<http://ldf.fi/schema/person_registry/entryText>',
                name: 'Haku',
                enabled: true
            },
            link: {
                facetId: 'link',
                choices: [
                    {
                        id: 'wikipedia',
                        pattern: '?id <http://ldf.fi/norssit/wikipedia> [] .',
                        label: 'Wikipedia'
                    },
                    {
                        id: 'kansallisbiografia',
                        pattern: '?id <http://ldf.fi/norssit/kansallisbiografia> [] .',
                        label: 'Kansallisbiografia'
                    },
                    {
                        id: 'kirjasampo',
                        pattern: '?id <http://ldf.fi/norssit/kirjasampo> [] .',
                        label: 'Kirjasampo'
                    },
                    {
                        id: 'kulttuurisampo',
                        pattern: '?id <http://ldf.fi/norssit/kulttuurisampo> [] .',
                        label: 'Kulttuurisampo'
                    },
                    {
                        id: 'sotasampo',
                        pattern: '?id <http://ldf.fi/norssit/warsa> [] .',
                        label: 'Sotasampo'
                    },
                    {
                        id: 'blf',
                        pattern: '?id <http://ldf.fi/norssit/sls_biografi> [] .',
                        label: 'BLF'
                    },
                    {
                        id: 'wikidata',
                        pattern: '?id <http://ldf.fi/norssit/wikidata> [] .',
                        label: 'Wikidata'
                    },
                    {
                        id: 'ulan',
                        pattern: '?id <http://ldf.fi/norssit/ulan> [] .',
                        label: 'ULAN'
                    },
                    {
                        id: 'viaf',
                        pattern: '?id <http://ldf.fi/norssit/viaf> [] .',
                        label: 'VIAF'
                    },
                    {
                        id: 'genicom',
                        pattern: '?id <http://ldf.fi/norssit/genicom> [] .',
                        label: 'Geni.com'
                    }
                ],
                enabled: true,
                name: 'Linkit'
            },
            familyName: {
                facetId: 'familyName',
                predicate: '<http://schema.org/familyName>',
                name: 'Sukunimi'
            },
            birthPlace: {
                facetId: 'birthPlace',
                predicate: '<http://ldf.fi/schema/person_registry/birthPlace>',
                name: 'Syntymäpaikka',
                enabled: true
            },
            enrollmentYear: {
                facetId: 'enrollmentYear',
                predicate: '<http://ldf.fi/schema/person_registry/enrollmentYear>',
                name: 'Aloittamisvuosi',
                enabled: true
            },
            matriculationYear: {
                facetId: 'matriculationYear',
                predicate: '<http://ldf.fi/schema/person_registry/matriculationYear>',
                name: 'Valmistumisvuosi',
                enabled: true
            },
            occupation: {
                facetId: 'occupation',
                predicate: '^<http://ldf.fi/schema/bioc/title_inheres_in>/a',
                name: 'Arvo tai ammatti',
                enabled: true
            },
            education: {
                facetId: 'education',
                predicate: '^<http://ldf.fi/schema/bioc/education_inheres_in>/a',
                name: 'Koulutus',
                enabled: true
            },
            organization: {
                facetId: 'organization',
                predicate: '^<http://ldf.fi/schema/bioc/title_inheres_in>/<http://ldf.fi/schema/bioc/relates_to>',
                name: 'Työpaikka tai oppilaitos',
                enabled: true
            },
            hobby: {
                facetId: 'hobby',
                predicate: '<http://schema.org/hobby>',
                name: 'Harrastus'
            },
            medal: {
                facetId: 'medal',
                predicate: '^<http://ldf.fi/schema/bioc/title_inheres_in>/<http://ldf.fi/schema/bioc/relates_to_medal>',
                name: 'Kunniamerkit ja -mitalit',
                enabled: true
            },
            rank: {
                facetId: 'rank',
                predicate: '^<http://ldf.fi/schema/bioc/title_inheres_in>/<http://ldf.fi/schema/bioc/relates_to_rank>',
                name: 'Sotilasarvo tai -toimi',
                enabled: true
            }
        };

        var prefixes =
        ' PREFIX hobbies: <http://ldf.fi/hobbies/> ' +
        ' PREFIX norssit: <http://ldf.fi/norssit/> ' +
        ' PREFIX nach: <http://ldf.fi/norssit/achievements/> ' +
        ' PREFIX owl: <http://www.w3.org/2002/07/owl#> ' +
        ' PREFIX person_registry: <http://ldf.fi/schema/person_registry/> ' +
        ' PREFIX places: <http://ldf.fi/places/> ' +
        ' PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> ' +
        ' PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ' +
        ' PREFIX relatives: <http://ldf.fi/relatives/> ' +
        ' PREFIX schema: <http://schema.org/> ' +
        ' PREFIX schemax: <http://topbraid.org/schemax/> ' +
        ' PREFIX dct: <http://purl.org/dc/terms/> ' +
        ' PREFIX skos: <http://www.w3.org/2004/02/skos/core#> ' +
        ' PREFIX xml: <http://www.w3.org/XML/1998/namespace> ' +
        ' PREFIX bioc: <http://ldf.fi/schema/bioc/> ' +
        ' PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> ';

        // The query for the results.
        // ?id is bound to the norssit URI.
        var query =
        ' SELECT DISTINCT * WHERE {' +
        '  { ' +
        '    <RESULT_SET> ' +
        '  } ' +
        '  OPTIONAL { ?id schema:givenName ?givenName . }' +
        '  OPTIONAL { ?id schema:familyName ?familyName . }' +
        '  OPTIONAL { ?id person_registry:birthPlace ?birthPlace . } ' +
        '  OPTIONAL { ?id norssit:ordinal ?ordinal . } ' +
        '  OPTIONAL { ?id norssit:register_id ?registerNumber . } ' +
        '  OPTIONAL { ?id schema:birthDate ?birthDate . }' +
        '  OPTIONAL { ?id schema:deathDate ?deathDate . }' +
        '  OPTIONAL { ' +
        '   ?id schema:hobby ?hobby_id . ' +
        '   BIND(REPLACE(STR(?hobby_id), "http://ldf.fi/hobbies/", "") AS ?hobby) ' +
        '  }' +
        '  OPTIONAL { ?id schema:image ?image . }' +
        '  OPTIONAL { ?id dct:description ?description . }' +
        '  OPTIONAL { ?id person_registry:pageNumber ?pageNumber . }' +
        '  OPTIONAL { ?id person_registry:pageImageURL ?pageImageURL . }' +
        '  OPTIONAL { ?id person_registry:relatedNorssi ?relatedNorssi . }' +
        '  OPTIONAL { ?id person_registry:enrollmentYear ?enrollmentYear . }' +
        '  OPTIONAL { ?id person_registry:matriculationYear ?matriculationYear . }' +
        '  OPTIONAL { ?id person_registry:entryText ?entryText . }' +
        '  OPTIONAL { ?id norssit:wikipedia ?wikipedia . }' +
        '  OPTIONAL { ?id norssit:viaf ?viaf . }' +
        '  OPTIONAL { ?id norssit:kansallisbiografia ?kansallisbiografia . }' +
        '  OPTIONAL { ?id norssit:wikidata ?wikidata . }' +
        '  OPTIONAL { ?id norssit:ulan ?ulan . }' +
        '  OPTIONAL { ?id norssit:warsa ?warsa . }' +
        '  OPTIONAL { ?id norssit:kirjasampo ?kirjasampo . }' +
        '  OPTIONAL { ?id norssit:kulttuurisampo ?kulttuurisampo . }' +
        '  OPTIONAL { ?id norssit:kb ?kb . }' +
        '  OPTIONAL { ?id norssit:genitree ?genitree . }' +
        '  OPTIONAL { ?id norssit:genicom ?genicom . }' +
        '  OPTIONAL { ?id norssit:sls_biografi ?blf . }' +
        '  OPTIONAL { ?id ^bioc:title_inheres_in/a/skos:prefLabel ?occupation . FILTER (str(?occupation)!="Nimike") }' +
        '  OPTIONAL { ?id ^bioc:title_inheres_in/bioc:relates_to/skos:prefLabel ?organization . }' +
        '  OPTIONAL { ' +
        '  	?id bioc:has_family_relation [' +
        '    	bioc:inheres_in ?relative__id ;' +
        '      	a/skos:prefLabel ?relative__type ] .' +
        '    	FILTER (LANG(?relative__type)="fi")' +
        '    	?relative__id schema:familyName ?relative__familyName ; schema:givenName ?relative__givenName .' +
        '		BIND (replace(concat(?relative__givenName," ",?relative__familyName),"[(][^)]+[)]\s*","") AS ?relative__name) ' +
        '  }' +
        '  OPTIONAL { ' +
        '    ?ach rdfs:subPropertyOf* nach:involved_in .' +
        '    ?id ?ach ?achievement__id . ' +
        '    ?achievement__id skos:prefLabel ?achievement__label .' +
        '    ?achievement__id norssit:wikipedia|norssit:www ?achievement__wikipedia .' +
        '  }' +
        ' }';

        // The SPARQL endpoint URL
        var endpointUrl = SPARQL_ENDPOINT_URL;

        var facetOptions = {
            endpointUrl: endpointUrl,
            rdfClass: '<http://xmlns.com/foaf/0.1/Person>',
            constraint: '?id <http://ldf.fi/norssit/ordinal> ?ordinal . ?id <http://schema.org/familyName> ?familyName .',
            preferredLang : 'fi'
        };

        var resultOptions = {
            queryTemplate: query,
            prefixes: prefixes,
            pagesPerQuery: 2 // get two pages of results per query
        };

        // The FacetResultHandler handles forming the final queries for results,
        // querying the endpoint, and mapping the results to objects.
        var resultHandler = new FacetResultHandler(endpointUrl, resultOptions);

        function getResults(facetSelections) {
            return resultHandler.getResults(facetSelections, getSortBy());
        }

        function getFacets() {
            var facetsCopy = angular.copy(facets);
            return $q.when(facetsCopy);
        }

        function getFacetOptions() {
            return facetOptions;
        }

        function updateSortBy(sortBy) {
            var sort = $location.search().sortBy || '?ordinal';
            if (sort === sortBy) {
                $location.search('desc', $location.search().desc ? null : true);
            }
            $location.search('sortBy', sortBy);
        }

        function getSortBy() {
            var sortBy = $location.search().sortBy;
            if (!_.isString(sortBy)) {
                sortBy = '?ordinal';
            }
            var sort;
            if ($location.search().desc) {
                sort = 'DESC(' + sortBy + ')';
            } else {
                sort = sortBy;
            }
            return sortBy === '?ordinal' ? sort : sort + ' ?ordinal';
        }

        function getSortClass(sortBy, numeric) {
            var sort = $location.search().sortBy || '?ordinal';
            var cls = numeric ? 'glyphicon-sort-by-order' : 'glyphicon-sort-by-alphabet';

            if (sort === sortBy) {
                if ($location.search().desc) {
                    return cls + '-alt';
                }
                return cls;
            }
        }
    }
})();
<commit_msg>Update<commit_after><|endoftext|>


<commit_before>"use strict";
exports.__esModule = true;
var getopts_1 = require("getopts");
console.log(getopts_1["default"](["-s"], {
    alias: {
        s: "super"
    },
    boolean: ["super"],
    "default": {
        "super": true
    }
}));
<commit_msg>chore: remove extraneous js file<commit_after><|endoftext|>