<commit_before>function createBoxPlot(data, element, plottype) {
    var mode = get_current_mode();
    var layout = {};
    switch (mode) {
        case "single-crystal-group":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "single-crystal":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "two-crystal-groups":

            switch (plottype) {

                case "angles":
                    var rows = getDateFromTable(1, [1, 7, 9, 11, 13, 15, 17, 8, 10, 12, 14, 16, 18]);

                    var pos_titles = [];
                    var values = [];
                    for (var i = 0; i < rows.length; i++) {
                        title = rows[i][0].split("-");
                        if (!pos_titles.includes(title[0])) {
                            values.push(rows[i].slice(1,7));
                            pos_titles.push(title[0]);
                        }
                        if (!pos_titles.includes(title[1])) {
                            values.push(rows[i].slice(7));
                            pos_titles.push(title[1]);
                        }
                    }

                    var y = Array(values.length).fill('Angles')

                    var trace1 = {
                        y: getColumn(values, 0),
                        name: 'Distance to 7TM axis',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace2 = {
                        y: getColumn(values, 1),
                        name: 'Rotation (Ca angle)',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace3 = {
                        y: getColumn(values, 2),
                        name: 'Rotamer',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace4 = {
                        y: getColumn(values, 3),
                        name: 'SASA',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace5 = {
                        y: getColumn(values, 4),
                        name: 'RSA',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace6 = {
                        y: getColumn(values, 5),
                        name: 'Presence',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var data = [trace1, trace2, trace3, trace4, trace5, trace6];

                    var layout = {
                        title: 'Grouped Horizontal Box Plot',
                        xaxis: {
                            // title: 'Angles',
                            zeroline: false
                        },
                        // grid: {rows: 1, columns: 6, pattern: 'independent'},
                        boxmode: 'group'
                    };

                    break;
                default:
                    var rows = getDateFromTable(1, [1, 2, 3, 4]);

                    var text_array = getColumn(rows, 0);
                    var y0 = getColumn(rows, 1);
                    var y1 = getColumn(rows, 2);
                    var y2 = getColumn(rows, 3);

                    var trace1 = {
                        y: y0,
                        type: 'box',
                        text: text_array,
                        name: 'Set 1',
                        boxpoints: 'all',
                        jitter: 0.3,
                        pointpos: -1.8
                    };

                    var trace2 = {
                        y: y1,
                        type: 'box',
                        text: text_array,
                        name: 'Set 2',
                        boxpoints: 'all',
                        jitter: 0.3,
                        pointpos: -1.8
                    };

                    var trace3 = {
                        y: y2,
                        type: 'box',
                        text: text_array,
                        name: 'Diff',
                        boxpoints: 'all',
                        jitter: 0.3,
                        pointpos: -1.8
                    };

                    var data = [trace1, trace2, trace3];
            }

            break;
    }

    Plotly.newPlot(element, data, layout);

}

function createBoxPlotResidue(data, element, plottype, cell_index, limit_pdbs = false, aa = false) {
    var mode = get_current_mode();
    var layout = {};
    switch (mode) {
        case "single-crystal-group":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "single-crystal":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "two-crystal-groups":

            switch (plottype) {

                case "angles":

                    x = [];
                    ys = {};
                    pdbs = [];
                    pos = '';
                    pdbs = two_sets_pdbs1.concat(two_sets_pdbs2);
                    // If only use a subset of pdbs.
                    if (limit_pdbs) pdbs = limit_pdbs;
                    pdbs_shown = []
                    pdbs.forEach(function(pdb){
                        pdb = pdb.toUpperCase();
                        let d = data[pdb];
                        if (d.length > 0) {
                            pos = d[0];
                            pdbs_shown.push(pdb)
                            if (two_sets_pdbs1.includes(pdb)) {
                                x.push('Set 1');
                            } else if (two_sets_pdbs2.includes(pdb)) {
                                x.push('Set 2');
                            }
                            for (var i = 2; i < d.length; i++) {
                                if (!ys[i - 2]) ys[i - 2] = [];
                                ys[i - 2].push(d[i]);
                            }
                        }
                    });

                    if (aa) pos = pos+" "+aa;

                    names = ['core_distance','a_angle','outer_angle','tau','phi','psi', 'sasa', 'rsa','theta','hse']

                    name_index = Math.floor((cell_index-6)/2);
                    name_index = { 7: 'core_distance', 8:'core_distance',
                                   9: 'a_angle', 10:'a_angle',
                                   11: 'outer_angle', 12:'outer_angle',
                                   13: 'sasa', 14:'sasa',
                                   15: 'rsa', 16:'rsa' };

                    // console.log(cell_index,name_index,name_index[cell_index]);

                    var traces = [];
                    for (const key in ys) {
                        new_x = []
                        for (var i = 0; i < x.length; i++) {
                            new_x.push(names[key]+"<br>"+x[i]);
                        }
                        visible_trace = 'legendonly';
                        if (name_index[cell_index]==names[key]) visible_trace = true;
                        trace = {
                            y: ys[key],
                            x: new_x,
                            name: names[key],
                            type: 'box',
                            boxmean: true,
                            // boxpoints: 'all',
                            text: pdbs_shown,
                            jitter: 0.5,
                            whiskerwidth: 0.2,
                            fillcolor: 'cls',
                            marker: {
                                size: 2
                            },
                            line: {
                                width: 1
                            },
                            visible: visible_trace
                        };
                        traces.push(trace);
                    }

                    var data = traces;

                    var layout = {
                        title: 'Angles data for position '+pos,
                        // xaxis: {
                        //     zeroline: false
                        // },
                          xaxis: {
                            showgrid: false,
                            zeroline: false,
                          },
                        yaxis: {
                            zeroline: false
                        },
                        // boxmode: 'group'
                    };

                    break;
                default:
            }

            break;
    }

    Plotly.newPlot(element, data, layout, {showLink: true}); //editable: true,
}

function getDateFromTable(browser_tab, columns) {
    var mode = get_current_mode();
    var mode_tab = mode + "-tab";
    var tab_id = "#" + mode_tab + " .browser-table-" + browser_tab;
    console.log(tab_id);
    var rows = [];
    if ($.fn.DataTable.isDataTable(tab_id)) {
        var table = $(tab_id).DataTable();
        table.rows({
            filter: 'applied'
        }).data().each(function(i) {
            var temp = [];
            columns.forEach(function(c, ii) {
                temp.push(i[c]);
            });
            rows.push(temp);
        })
    }
    return rows;

}

function getColumn(anArray, columnNumber) {
    return anArray.map(function(row) {
        return row[columnNumber];
    });
}
<commit_msg>Show circular representation diagrams for angle data<commit_after>function sum(a) {
    var s = 0;
    for (var i = 0; i < a.length; i++) s += a[i];
    return s;
}

function degToRad(a) {
    return Math.PI / 180 * a;
}

function meanAngleDeg(a) {
    return 180 / Math.PI * Math.atan2(
        sum(a.map(degToRad).map(Math.sin)) / a.length,
        sum(a.map(degToRad).map(Math.cos)) / a.length
    );
}

function createBoxPlot(data, element, plottype) {
    var mode = get_current_mode();
    var layout = {};
    switch (mode) {
        case "single-crystal-group":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "single-crystal":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "two-crystal-groups":

            switch (plottype) {

                case "angles":
                    var rows = getDateFromTable(1, [1, 7, 9, 11, 13, 15, 17, 8, 10, 12, 14, 16, 18]);

                    var pos_titles = [];
                    var values = [];
                    for (var i = 0; i < rows.length; i++) {
                        title = rows[i][0].split("-");
                        if (!pos_titles.includes(title[0])) {
                            values.push(rows[i].slice(1, 7));
                            pos_titles.push(title[0]);
                        }
                        if (!pos_titles.includes(title[1])) {
                            values.push(rows[i].slice(7));
                            pos_titles.push(title[1]);
                        }
                    }

                    var y = Array(values.length).fill('Angles')

                    var trace1 = {
                        y: getColumn(values, 0),
                        name: 'Distance to 7TM axis',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace2 = {
                        y: getColumn(values, 1),
                        name: 'Rotation (Ca angle)',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace3 = {
                        y: getColumn(values, 2),
                        name: 'Rotamer',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace4 = {
                        y: getColumn(values, 3),
                        name: 'SASA',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace5 = {
                        y: getColumn(values, 4),
                        name: 'RSA',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var trace6 = {
                        y: getColumn(values, 5),
                        name: 'Presence',
                        type: 'box',
                        boxmean: false,
                        text: pos_titles
                    };

                    var data = [trace1, trace2, trace3, trace4, trace5, trace6];

                    var layout = {
                        title: 'Grouped Horizontal Box Plot',
                        xaxis: {
                            // title: 'Angles',
                            zeroline: false
                        },
                        // grid: {rows: 1, columns: 6, pattern: 'independent'},
                        boxmode: 'group'
                    };

                    break;
                default:
                    var rows = getDateFromTable(1, [1, 2, 3, 4]);

                    var text_array = getColumn(rows, 0);
                    var y0 = getColumn(rows, 1);
                    var y1 = getColumn(rows, 2);
                    var y2 = getColumn(rows, 3);

                    var trace1 = {
                        y: y0,
                        type: 'box',
                        text: text_array,
                        name: 'Set 1',
                        boxpoints: 'all',
                        jitter: 0.3,
                        pointpos: -1.8
                    };

                    var trace2 = {
                        y: y1,
                        type: 'box',
                        text: text_array,
                        name: 'Set 2',
                        boxpoints: 'all',
                        jitter: 0.3,
                        pointpos: -1.8
                    };

                    var trace3 = {
                        y: y2,
                        type: 'box',
                        text: text_array,
                        name: 'Diff',
                        boxpoints: 'all',
                        jitter: 0.3,
                        pointpos: -1.8
                    };

                    var data = [trace1, trace2, trace3];
            }

            break;
    }

    Plotly.newPlot(element, data, layout);

}

function createBoxPlotResidue(data, element, plottype, cell_index, limit_pdbs = false, aa = false) {
    var mode = get_current_mode();
    var layout = {};
    switch (mode) {
        case "single-crystal-group":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "single-crystal":

            var data = [{
                y: [0, 1, 1, 2, 3, 5, 8, 13, 21],
                boxpoints: 'all',
                jitter: 0.3,
                pointpos: -1.8,
                type: 'box',
                text: ['Text A', 'Text B', 'Text C', 'Text D', 'Text E'],
            }];

            break;
        case "two-crystal-groups":

            switch (plottype) {

                case "angles":

                    x = [];
                    ys = {};
                    ys1 = {};
                    ys2 = {};
                    pdbs = [];
                    pos = '';
                    pdbs = two_sets_pdbs1.concat(two_sets_pdbs2);
                    // If only use a subset of pdbs.
                    if (limit_pdbs) pdbs = limit_pdbs;
                    pdbs_shown = []
                    pdbs.forEach(function(pdb) {
                        pdb = pdb.toUpperCase();
                        let d = data[pdb];
                        if (d.length > 0) {
                            pos = d[0];
                            pdbs_shown.push(pdb)
                            if (two_sets_pdbs1.includes(pdb)) {
                                x.push('Set 1');
                            } else if (two_sets_pdbs2.includes(pdb)) {
                                x.push('Set 2');
                            }
                            for (var i = 2; i < d.length; i++) {
                                if (!ys[i - 2]) {
                                    ys[i - 2] = [];
                                    ys1[i - 2] = [];
                                    ys2[i - 2] = [];
                                }
                                ys[i - 2].push(d[i]);

                                if (two_sets_pdbs1.includes(pdb))
                                    ys1[i - 2].push(d[i]);

                                if (two_sets_pdbs2.includes(pdb))
                                    ys2[i - 2].push(d[i]);
                            }
                        }
                    });

                    if (aa) pos = pos + " " + aa;

                    names = [['core_distance',false], ['a_angle',true], ['outer_angle',true], ['tau',true], ['phi',true], ['psi',true], ['sasa',false], ['rsa',false], ['theta',true], ['hse',false], ['dssp',false]]

                    name_index = Math.floor((cell_index - 6) / 2);
                    name_index = {
                        7: 'core_distance',
                        8: 'core_distance',
                        9: 'a_angle',
                        10: 'a_angle',
                        11: 'outer_angle',
                        12: 'outer_angle',
                        13: 'sasa',
                        14: 'sasa',
                        15: 'rsa',
                        16: 'rsa'
                    };

                    // console.log(cell_index,name_index,name_index[cell_index]);

                    var traces = [];
                    is_angle = true;
                    for (const key in ys) {
                        if (name_index[cell_index] != names[key][0]) continue;
                        is_angle = names[key][1]
                        new_x = []
                        for (var i = 0; i < x.length; i++) {
                            new_x.push(names[key][0] + "<br>" + x[i]);
                        }
                        visible_trace = 'legendonly';
                        if (name_index[cell_index] == names[key][0]) visible_trace = true;
                        if (names[key][1] == true) {
                            mean1 = meanAngleDeg(ys1[key]);
                            mean2 = meanAngleDeg(ys2[key]);
                            traces = [{
                                    type: "scatterpolar",
                                    mode: "markers",
                                    r: Array(ys1[key].length).fill(1),
                                    theta: ys1[key],
                                    name: "Set 1",
                                    marker: {
                                        color: "#8090c7",
                                        symbol: "circle",
                                        size: 15
                                    },
                                    opacity: 0.8,
                                },
                                {
                                    type: "scatterpolar",
                                    mode: "lines",
                                    r: [0, 0.9],
                                    theta: [0, mean1],
                                    name: "Set 1 mean",
                                    line: {
                                        color: "#8090c7",
                                        width: 5,
                                    },
                                },
                                {
                                    type: "scatterpolar",
                                    mode: "markers",
                                    r: Array(ys2[key].length).fill(1),
                                    theta: ys2[key],
                                    name: "Set 2",
                                    marker: {
                                        color: "red",
                                        symbol: "circle",
                                        size: 15
                                    },
                                    opacity: 0.8,
                                    subplot: "polar2"
                                },
                                {
                                    type: "scatterpolar",
                                    mode: "lines",
                                    r: [0, 0.9],
                                    theta: [0, mean2],
                                    name: "Set 2 mean",
                                    line: {
                                        color: "red",
                                        width: 5,
                                    },
                                    subplot: "polar2"
                                }];

                        } else {
                            trace = {
                                y: ys[key],
                                x: new_x,
                                name: names[key][0],
                                type: 'box',
                                boxmean: true,
                                // boxpoints: 'all',
                                text: pdbs_shown,
                                jitter: 0.5,
                                whiskerwidth: 0.2,
                                fillcolor: 'cls',
                                marker: {
                                    size: 2
                                },
                                line: {
                                    width: 1
                                },
                                visible: visible_trace
                            };
                            // Only show one data type on a chart.
                            traces.push(trace);

                        }
                    }

                    var data = traces;
                    if (is_angle == true) {

                        var layout = {
                            title: 'Angles data for position ' + pos,
                            polar: {
                                radialaxis: {
                                    //autorange: true,
                                    showgrid: true,
                                    zeroline: false,
                                    showline: false,
                                    autotick: true,
                                    ticks: '',
                                    showticklabels: false,
                                    range: [0, 1.1]

                                },
                                angularaxis: {
                                    tickfont: {
                                        size: 8
                                    }
                                }
                                },
                            polar2: {
                                radialaxis: {
                                    //autorange: true,
                                    showgrid: true,
                                    zeroline: false,
                                    showline: false,
                                    autotick: true,
                                    ticks: '',
                                    showticklabels: false,
                                    range: [0, 1.1]

                                },
                                angularaxis: {
                                    tickfont: {
                                        size: 8
                                    }
                                }
                                }
                        }
                    } else {
                        var layout = {
                            title: 'Angles data for position ' + pos,
                            // xaxis: {
                            //     zeroline: false
                            // },
                            xaxis: {
                                showgrid: false,
                                zeroline: false,
                            },
                            yaxis: {
                                zeroline: false
                            },
                            // boxmode: 'group'
                        };
                    }
                    break;
                default:
            }

            break;
    }
    Plotly.newPlot(element, data, layout, { showLink: true }); //editable: true,
}

function getDateFromTable(browser_tab, columns) {
    var mode = get_current_mode();
    var mode_tab = mode + "-tab";
    var tab_id = "#" + mode_tab + " .browser-table-" + browser_tab;
    console.log(tab_id);
    var rows = [];
    if ($.fn.DataTable.isDataTable(tab_id)) {
        var table = $(tab_id).DataTable();
        table.rows({
            filter: 'applied'
        }).data().each(function(i) {
            var temp = [];
            columns.forEach(function(c, ii) {
                temp.push(i[c]);
            });
            rows.push(temp);
        })
    }
    return rows;

}

function getColumn(anArray, columnNumber) {
    return anArray.map(function(row) {
        return row[columnNumber];
    });
}<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var getHomePath = require('home-path');

/**
 *  Write the config to the . file
 *
 *  @param {String} file - name of the file to write
 *  @param {String|Buffer} contents - file contents to write
 *  @return {Boolean}
 *  @api public
 */

exports.write = function(file, contents) {
  var rcPath = _getRcPath(file);
  var err = null;

  try {
    fs.writeFileSync(rcPath, contents);
  } catch(e) {
    err = e;
  };

  return err;
};

/**
 *  read the contents of the config file
 *
 *  @return {String} file
 *  @api public
 */

exports.read = function(file) {
  var rcPath = _getRcPath(file);
  return fs.readFileSync(rcPath);
};

/**
 *  remove the dot file from disk
 *
 *  @param {String} file
 *  @return {Boolean}
 *  @api public
 */

exports.unlink = function(file) {
  var rcPath = _getRcPath(file);
  var err = null;

  try {
    fs.unlinkSync(rcPath);
  } catch(e) {
    err = e;
  };

  return err;
};

/**
 *  Get the . file path
 *
 *  @param {String} file
 *  @return {String}
 *  @api private
 */

function _getRcPath(file) {
  var home = getHomePath();
  return path.join(home, '.'+file);
};
<commit_msg>updates to try/catch reads<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var getHomePath = require('home-path');

/**
 *  Write the config to the . file
 *
 *  @param {String} file - name of the file to write
 *  @param {String|Buffer} contents - file contents to write
 *  @return {Boolean}
 *  @api public
 */

exports.write = function(file, contents) {
  var rcPath = _getRcPath(file);
  var err = null;

  try {
    fs.writeFileSync(rcPath, contents);
  } catch(e) {
    err = e;
  };

  return err;
};

/**
 *  read the contents of the config file
 *
 *  @return {String} file
 *  @api public
 */

exports.read = function(file) {
  var rcPath = _getRcPath(file);
  var contents;

  try {
    contents = fs.readFileSync(rcPath);
  } catch (e) {
    contents = e;
  };

  return contents;
};

/**
 *  remove the dot file from disk
 *
 *  @param {String} file
 *  @return {Boolean}
 *  @api public
 */

exports.unlink = function(file) {
  var rcPath = _getRcPath(file);
  var err = null;

  try {
    fs.unlinkSync(rcPath);
  } catch(e) {
    err = e;
  };

  return err;
};

/**
 *  Get the . file path
 *
 *  @param {String} file
 *  @return {String}
 *  @api private
 */

function _getRcPath(file) {
  var home = getHomePath();
  return path.join(home, '.'+file);
};
<|endoftext|>


<commit_before><commit_msg>Update app/index.js<commit_after>var koa = require('koa');
var app = koa();

app.use(function *(next) {
  var start = new Date;
  yield next;
  var ms = new Date - start;
  console.log('%s %s - %s', this.method, this.url, ms);
});

app.use(function *() {
  this.body = 'Hello, Koa!';
});

app.listen(3000);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

$(document).ready(function(){
	$("#passwordbutton").click( function(){
		if ($('#pass1').val() != '' && $('#pass2').val() != '') {
			// Serialize the data
			var post = $( "#passwordform" ).serialize();
			$('#passwordchanged').hide();
			$('#passworderror').hide();
			// Ajax foo
			$.post( 'ajax/changepassword.php', post, function(data){
				if( data.status == "success" ){
					$('#pass1').val('');
					$('#pass2').val('');
					$('#passwordchanged').show();
				}
				else{
					$('#passworderror').html( data.data.message );
					$('#passworderror').show();
				}
			});
			return false;
		} else {
			$('#passwordchanged').hide();
			$('#passworderror').show();
			return false;
		}

	});

	$('#lostpassword #email').blur(function(event){
		event.preventDefault();
		OC.msg.startSaving('#lostpassword .msg');
		var post = $( "#lostpassword" ).serialize();
		$.post( 'ajax/lostpassword.php', post, function(data){
			OC.msg.finishedSaving('#lostpassword .msg', data);
		});
	});

	$("#languageinput").chosen();

	$("#languageinput").change( function(){
		// Serialize the data
		var post = $( "#languageinput" ).serialize();
		// Ajax foo
		$.post( 'ajax/setlanguage.php', post, function(data){
			if( data.status == "success" ){
				location.reload();
			}
			else{
				$('#passworderror').html( data.data.message );
			}
		});
		return false;
	});
} );

OC.msg={
	startSaving:function(selector){
		$(selector)
			.html( t('settings', 'Saving...') )
			.removeClass('success')
			.removeClass('error')
			.stop(true, true)
			.show();
	},
	finishedSaving:function(selector, data){
		if( data.status == "success" ){
			 $(selector).html( data.data.message )
				.addClass('success')
				.stop(true, true)
				.delay(3000)
				.fadeOut(600);
		}else{
			$(selector).html( data.data.message ).addClass('error');
		}
	}
}
<commit_msg>Fix password is being saved even if not changed<commit_after>/**
 * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

$(document).ready(function(){
	$("#passwordbutton").click( function(){
		if ($('#pass1').val() != '' && $('#pass2').val() != '') {
			// Serialize the data
			var post = $( "#passwordform" ).serialize();
			$('#passwordchanged').hide();
			$('#passworderror').hide();
			// Ajax foo
			$.post( 'ajax/changepassword.php', post, function(data){
				if( data.status == "success" ){
					$('#pass1').val('');
					$('#pass2').val('');
					$('#passwordchanged').show();
				}
				else{
					$('#passworderror').html( data.data.message );
					$('#passworderror').show();
				}
			});
			return false;
		} else {
			$('#passwordchanged').hide();
			$('#passworderror').show();
			return false;
		}

	});

	$('#lostpassword #email').blur(function(event){
		if ($(this).val() == this.defaultValue){
			return;
		}
		event.preventDefault();
		this.defaultValue = $(this).val();
		OC.msg.startSaving('#lostpassword .msg');
		var post = $( "#lostpassword" ).serialize();
		$.post( 'ajax/lostpassword.php', post, function(data){
			OC.msg.finishedSaving('#lostpassword .msg', data);
		});
	});

	$("#languageinput").chosen();

	$("#languageinput").change( function(){
		// Serialize the data
		var post = $( "#languageinput" ).serialize();
		// Ajax foo
		$.post( 'ajax/setlanguage.php', post, function(data){
			if( data.status == "success" ){
				location.reload();
			}
			else{
				$('#passworderror').html( data.data.message );
			}
		});
		return false;
	});
} );

OC.msg={
	startSaving:function(selector){
		$(selector)
			.html( t('settings', 'Saving...') )
			.removeClass('success')
			.removeClass('error')
			.stop(true, true)
			.show();
	},
	finishedSaving:function(selector, data){
		if( data.status == "success" ){
			 $(selector).html( data.data.message )
				.addClass('success')
				.stop(true, true)
				.delay(3000)
				.fadeOut(600);
		}else{
			$(selector).html( data.data.message ).addClass('error');
		}
	}
}
<|endoftext|>


<commit_before>(function () {
  var pg = document.querySelector("#playground code")
  if (pg) {
    var hash = window.location.hash.slice(1)
    function updateTitle(text) {
      document.title =
        document.title.replace(/(:.*)?$/, ": " + text.replace(/\s+/g, " ").trim())
    }
    if (hash) {
      var text = window.LZString.decompressFromEncodedURIComponent(hash)
      pg.innerHTML = text.replace(/[\u00A0-\u9999<>&]/gim, function (i) {
        return '&#' + i.charCodeAt(0) + ';'
      })
      updateTitle(text)
    }
    var to = null
    document.onkeyup = function () {
      clearTimeout(to)
      to = setTimeout(function () {
        var elem = document.querySelector(".CodeMirror-lines")
        if (elem) {
          history.replaceState(
            null,
            '',
            window.location.protocol +
            window.location.host +
            window.location.pathname +
            window.location.search +
            '#' +
            window.LZString.compressToEncodedURIComponent(
              elem.innerText.replace(/\u200B|^\s*|\s*$/gm, "")))
          updateTitle(elem.innerText)
        }
      }, 250)
    }
  }
})()
<commit_msg>Should not include protocol and host<commit_after>(function () {
  var pg = document.querySelector("#playground code")
  if (pg) {
    var hash = window.location.hash.slice(1)
    function updateTitle(text) {
      document.title =
        document.title.replace(/(:.*)?$/, ": " + text.replace(/\s+/g, " ").trim())
    }
    if (hash) {
      var text = window.LZString.decompressFromEncodedURIComponent(hash)
      pg.innerHTML = text.replace(/[\u00A0-\u9999<>&]/gim, function (i) {
        return '&#' + i.charCodeAt(0) + ';'
      })
      updateTitle(text)
    }
    var to = null
    document.onkeyup = function () {
      clearTimeout(to)
      to = setTimeout(function () {
        var elem = document.querySelector(".CodeMirror-lines")
        if (elem) {
          history.replaceState(
            null,
            '',
            window.location.pathname +
            window.location.search +
            '#' +
            window.LZString.compressToEncodedURIComponent(
              elem.innerText.replace(/\u200B|^\s*|\s*$/gm, "")))
          updateTitle(elem.innerText)
        }
      }, 250)
    }
  }
})()
<|endoftext|>


<commit_before>/* eslint-disable import/prefer-default-export */
/* eslint-disable import/no-extraneous-dependencies */

import 'vtk.js/Sources/favicon';

import HttpDataAccessHelper from 'vtk.js/Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkColorMaps from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkColorTransferFunction from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkURLExtract from 'vtk.js/Sources/Common/Core/URLExtract';
import vtkXMLPolyDataReader from 'vtk.js/Sources/IO/XML/XMLPolyDataReader';
import vtkFPSMonitor from 'vtk.js/Sources/Interaction/UI/FPSMonitor';

import {
  ColorMode,
  ScalarMode,
} from 'vtk.js/Sources/Rendering/Core/Mapper/Constants';

import style from './GeometryViewer.mcss';
import icon from '../../../Documentation/content/icon/favicon-96x96.png';

let autoInit = true;
let background = [0, 0, 0];
let renderWindow;
let renderer;

global.pipeline = {};

// Process arguments from URL
const userParams = vtkURLExtract.extractURLParameters();

// Background handling
if (userParams.background) {
  background = userParams.background.split(',').map((s) => Number(s));
}
const selectorClass =
  background.length === 3 && background.reduce((a, b) => a + b, 0) < 1.5
    ? style.dark
    : style.light;

// name
const defaultName = userParams.name || '';

// lut
const lutName = userParams.lut || 'erdc_rainbow_bright';

// field
const field = userParams.field || '';

// camera
function updateCamera(camera) {
  ['zoom', 'pitch', 'elevation', 'yaw', 'azimuth', 'roll', 'dolly'].forEach(
    (key) => {
      if (userParams[key]) {
        camera[key](userParams[key]);
      }
      renderWindow.render();
    }
  );
}

function preventDefaults(e) {
  e.preventDefault();
  e.stopPropagation();
}

// ----------------------------------------------------------------------------
// DOM containers for UI control
// ----------------------------------------------------------------------------

const rootControllerContainer = document.createElement('div');
rootControllerContainer.setAttribute('class', style.rootController);

const addDataSetButton = document.createElement('img');
addDataSetButton.setAttribute('class', style.button);
addDataSetButton.setAttribute('src', icon);
addDataSetButton.addEventListener('click', () => {
  const isVisible = rootControllerContainer.style.display !== 'none';
  rootControllerContainer.style.display = isVisible ? 'none' : 'flex';
});

const fpsMonitor = vtkFPSMonitor.newInstance();
const fpsElm = fpsMonitor.getFpsMonitorContainer();
fpsElm.classList.add(style.fpsMonitor);

// ----------------------------------------------------------------------------
// Add class to body if iOS device
// ----------------------------------------------------------------------------

const iOS = /iPad|iPhone|iPod/.test(window.navigator.platform);

if (iOS) {
  document.querySelector('body').classList.add('is-ios-device');
}

// ----------------------------------------------------------------------------

function emptyContainer(container) {
  fpsMonitor.setContainer(null);
  while (container.firstChild) {
    container.removeChild(container.firstChild);
  }
}

// ----------------------------------------------------------------------------

function createViewer(container) {
  const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
    background,
    rootContainer: container,
    containerStyle: { height: '100%', width: '100%', position: 'absolute' },
  });
  renderer = fullScreenRenderer.getRenderer();
  renderWindow = fullScreenRenderer.getRenderWindow();
  renderWindow.getInteractor().setDesiredUpdateRate(15);

  container.appendChild(rootControllerContainer);
  container.appendChild(addDataSetButton);

  if (userParams.fps) {
    if (Array.isArray(userParams.fps)) {
      fpsMonitor.setMonitorVisibility(...userParams.fps);
      if (userParams.fps.length === 4) {
        fpsMonitor.setOrientation(userParams.fps[3]);
      }
    }
    fpsMonitor.setRenderWindow(renderWindow);
    fpsMonitor.setContainer(container);
    fullScreenRenderer.setResizeCallback(fpsMonitor.update);
  }
}

// ----------------------------------------------------------------------------

function createPipeline(fileName, fileContents) {
  // Create UI
  const presetSelector = document.createElement('select');
  presetSelector.setAttribute('class', selectorClass);
  presetSelector.innerHTML = vtkColorMaps.rgbPresetNames
    .map(
      (name) =>
        `<option value="${name}" ${
          lutName === name ? 'selected="selected"' : ''
        }>${name}</option>`
    )
    .join('');

  const representationSelector = document.createElement('select');
  representationSelector.setAttribute('class', selectorClass);
  representationSelector.innerHTML = [
    'Hidden',
    'Points',
    'Wireframe',
    'Surface',
    'Surface with Edge',
  ]
    .map(
      (name, idx) =>
        `<option value="${idx === 0 ? 0 : 1}:${idx < 4 ? idx - 1 : 2}:${
          idx === 4 ? 1 : 0
        }">${name}</option>`
    )
    .join('');
  representationSelector.value = '1:2:0';

  const colorBySelector = document.createElement('select');
  colorBySelector.setAttribute('class', selectorClass);

  const componentSelector = document.createElement('select');
  componentSelector.setAttribute('class', selectorClass);
  componentSelector.style.display = 'none';

  const opacitySelector = document.createElement('input');
  opacitySelector.setAttribute('class', selectorClass);
  opacitySelector.setAttribute('type', 'range');
  opacitySelector.setAttribute('value', '100');
  opacitySelector.setAttribute('max', '100');
  opacitySelector.setAttribute('min', '1');

  const labelSelector = document.createElement('label');
  labelSelector.setAttribute('class', selectorClass);
  labelSelector.innerHTML = fileName;

  const controlContainer = document.createElement('div');
  controlContainer.setAttribute('class', style.control);
  controlContainer.appendChild(labelSelector);
  controlContainer.appendChild(representationSelector);
  controlContainer.appendChild(presetSelector);
  controlContainer.appendChild(colorBySelector);
  controlContainer.appendChild(componentSelector);
  controlContainer.appendChild(opacitySelector);
  rootControllerContainer.appendChild(controlContainer);

  // VTK pipeline
  const vtpReader = vtkXMLPolyDataReader.newInstance();
  vtpReader.parseAsArrayBuffer(fileContents);

  const lookupTable = vtkColorTransferFunction.newInstance();
  const source = vtpReader.getOutputData(0);
  const mapper = vtkMapper.newInstance({
    interpolateScalarsBeforeMapping: false,
    useLookupTableScalarRange: true,
    lookupTable,
    scalarVisibility: false,
  });
  const actor = vtkActor.newInstance();
  const scalars = source.getPointData().getScalars();
  const dataRange = [].concat(scalars ? scalars.getRange() : [0, 1]);

  // --------------------------------------------------------------------
  // Color handling
  // --------------------------------------------------------------------

  function applyPreset() {
    const preset = vtkColorMaps.getPresetByName(presetSelector.value);
    lookupTable.applyColorMap(preset);
    lookupTable.setMappingRange(dataRange[0], dataRange[1]);
    lookupTable.updateRange();
  }
  applyPreset();
  presetSelector.addEventListener('change', applyPreset);

  // --------------------------------------------------------------------
  // Representation handling
  // --------------------------------------------------------------------

  function updateRepresentation(event) {
    const [
      visibility,
      representation,
      edgeVisibility,
    ] = event.target.value.split(':').map(Number);
    actor.getProperty().set({ representation, edgeVisibility });
    actor.setVisibility(!!visibility);
    renderWindow.render();
  }
  representationSelector.addEventListener('change', updateRepresentation);

  // --------------------------------------------------------------------
  // Opacity handling
  // --------------------------------------------------------------------

  function updateOpacity(event) {
    const opacity = Number(event.target.value) / 100;
    actor.getProperty().setOpacity(opacity);
    renderWindow.render();
  }

  opacitySelector.addEventListener('input', updateOpacity);

  // --------------------------------------------------------------------
  // ColorBy handling
  // --------------------------------------------------------------------

  const colorByOptions = [{ value: ':', label: 'Solid color' }].concat(
    source
      .getPointData()
      .getArrays()
      .map((a) => ({
        label: `(p) ${a.getName()}`,
        value: `PointData:${a.getName()}`,
      })),
    source
      .getCellData()
      .getArrays()
      .map((a) => ({
        label: `(c) ${a.getName()}`,
        value: `CellData:${a.getName()}`,
      }))
  );
  colorBySelector.innerHTML = colorByOptions
    .map(
      ({ label, value }) =>
        `<option value="${value}" ${
          field === value ? 'selected="selected"' : ''
        }>${label}</option>`
    )
    .join('');

  function updateColorBy(event) {
    const [location, colorByArrayName] = event.target.value.split(':');
    const interpolateScalarsBeforeMapping = location === 'PointData';
    let colorMode = ColorMode.DEFAULT;
    let scalarMode = ScalarMode.DEFAULT;
    const scalarVisibility = location.length > 0;
    if (scalarVisibility) {
      const activeArray = source[`get${location}`]().getArrayByName(
        colorByArrayName
      );
      const newDataRange = activeArray.getRange();
      dataRange[0] = newDataRange[0];
      dataRange[1] = newDataRange[1];
      colorMode = ColorMode.MAP_SCALARS;
      scalarMode =
        location === 'PointData'
          ? ScalarMode.USE_POINT_FIELD_DATA
          : ScalarMode.USE_CELL_FIELD_DATA;

      const numberOfComponents = activeArray.getNumberOfComponents();
      if (numberOfComponents > 1) {
        // always start on magnitude setting
        if (mapper.getLookupTable()) {
          const lut = mapper.getLookupTable();
          lut.setVectorModeToMagnitude();
        }
        componentSelector.style.display = 'block';
        const compOpts = ['Magnitude'];
        while (compOpts.length <= numberOfComponents) {
          compOpts.push(`Component ${compOpts.length}`);
        }
        componentSelector.innerHTML = compOpts
          .map((t, index) => `<option value="${index - 1}">${t}</option>`)
          .join('');
      } else {
        componentSelector.style.display = 'none';
      }
    } else {
      componentSelector.style.display = 'none';
    }
    mapper.set({
      colorByArrayName,
      colorMode,
      interpolateScalarsBeforeMapping,
      scalarMode,
      scalarVisibility,
    });
    applyPreset();
  }
  colorBySelector.addEventListener('change', updateColorBy);
  updateColorBy({ target: colorBySelector });

  function updateColorByComponent(event) {
    if (mapper.getLookupTable()) {
      const lut = mapper.getLookupTable();
      if (event.target.value === -1) {
        lut.setVectorModeToMagnitude();
      } else {
        lut.setVectorModeToComponent();
        lut.setVectorComponent(Number(event.target.value));
      }
      renderWindow.render();
    }
  }
  componentSelector.addEventListener('change', updateColorByComponent);

  // --------------------------------------------------------------------
  // Pipeline handling
  // --------------------------------------------------------------------

  actor.setMapper(mapper);
  mapper.setInputData(source);
  renderer.addActor(actor);

  // Manage update when lookupTable change
  lookupTable.onModified(() => {
    renderWindow.render();
  });

  // First render
  renderer.resetCamera();
  renderWindow.render();

  global.pipeline[fileName] = {
    actor,
    mapper,
    source,
    lookupTable,
    renderer,
    renderWindow,
  };

  // Update stats
  fpsMonitor.update();
}

// ----------------------------------------------------------------------------

function loadFile(file) {
  const reader = new FileReader();
  reader.onload = function onLoad(e) {
    createPipeline(file.name, reader.result);
  };
  reader.readAsArrayBuffer(file);
}

// ----------------------------------------------------------------------------

export function load(container, options) {
  autoInit = false;
  emptyContainer(container);

  if (options.files) {
    createViewer(container);
    let count = options.files.length;
    while (count--) {
      loadFile(options.files[count]);
    }
    updateCamera(renderer.getActiveCamera());
  } else if (options.fileURL) {
    const progressContainer = document.createElement('div');
    progressContainer.setAttribute('class', style.progress);
    container.appendChild(progressContainer);

    const progressCallback = (progressEvent) => {
      const percent = Math.floor(
        100 * progressEvent.loaded / progressEvent.total
      );
      progressContainer.innerHTML = `Loading ${percent}%`;
    };

    HttpDataAccessHelper.fetchBinary(options.fileURL, {
      progressCallback,
    }).then((binary) => {
      container.removeChild(progressContainer);
      createViewer(container);
      createPipeline(defaultName, binary);
      updateCamera(renderer.getActiveCamera());
    });
  }
}

export function initLocalFileLoader(container) {
  const exampleContainer = document.querySelector('.content');
  const rootBody = document.querySelector('body');
  const myContainer = container || exampleContainer || rootBody;

  if (myContainer !== container) {
    myContainer.classList.add(style.fullScreen);
    rootBody.style.margin = '0';
    rootBody.style.padding = '0';
  } else {
    rootBody.style.margin = '0';
    rootBody.style.padding = '0';
  }

  const fileContainer = document.createElement('div');
  fileContainer.innerHTML = `<div class="${
    style.bigFileDrop
  }"/><input type="file" multiple accept=".vtp" style="display: none;"/>`;
  myContainer.appendChild(fileContainer);

  const fileInput = fileContainer.querySelector('input');

  function handleFile(e) {
    preventDefaults(e);
    const dataTransfer = e.dataTransfer;
    const files = e.target.files || dataTransfer.files;
    if (files.length > 0) {
      myContainer.removeChild(fileContainer);
      load(myContainer, { files });
    }
  }

  fileInput.addEventListener('change', handleFile);
  fileContainer.addEventListener('drop', handleFile);
  fileContainer.addEventListener('click', (e) => fileInput.click());
  fileContainer.addEventListener('dragover', preventDefaults);
}

// Look at URL an see if we should load a file
// ?fileURL=https://data.kitware.com/api/v1/item/59cdbb588d777f31ac63de08/download
if (userParams.url || userParams.fileURL) {
  const exampleContainer = document.querySelector('.content');
  const rootBody = document.querySelector('body');
  const myContainer = exampleContainer || rootBody;

  if (myContainer) {
    myContainer.classList.add(style.fullScreen);
    rootBody.style.margin = '0';
    rootBody.style.padding = '0';
  }

  load(myContainer, userParams);
}

// Auto setup if no method get called within 100ms
setTimeout(() => {
  if (autoInit) {
    initLocalFileLoader();
  }
}, 100);
<commit_msg>doc(GeometryViewer): Support array for loading remote data<commit_after>/* eslint-disable import/prefer-default-export */
/* eslint-disable import/no-extraneous-dependencies */

import 'vtk.js/Sources/favicon';

import HttpDataAccessHelper from 'vtk.js/Sources/IO/Core/DataAccessHelper/HttpDataAccessHelper';
import vtkActor from 'vtk.js/Sources/Rendering/Core/Actor';
import vtkColorMaps from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction/ColorMaps';
import vtkColorTransferFunction from 'vtk.js/Sources/Rendering/Core/ColorTransferFunction';
import vtkFullScreenRenderWindow from 'vtk.js/Sources/Rendering/Misc/FullScreenRenderWindow';
import vtkMapper from 'vtk.js/Sources/Rendering/Core/Mapper';
import vtkURLExtract from 'vtk.js/Sources/Common/Core/URLExtract';
import vtkXMLPolyDataReader from 'vtk.js/Sources/IO/XML/XMLPolyDataReader';
import vtkFPSMonitor from 'vtk.js/Sources/Interaction/UI/FPSMonitor';

import {
  ColorMode,
  ScalarMode,
} from 'vtk.js/Sources/Rendering/Core/Mapper/Constants';

import style from './GeometryViewer.mcss';
import icon from '../../../Documentation/content/icon/favicon-96x96.png';

let autoInit = true;
let background = [0, 0, 0];
let renderWindow;
let renderer;

global.pipeline = {};

// Process arguments from URL
const userParams = vtkURLExtract.extractURLParameters();

// Background handling
if (userParams.background) {
  background = userParams.background.split(',').map((s) => Number(s));
}
const selectorClass =
  background.length === 3 && background.reduce((a, b) => a + b, 0) < 1.5
    ? style.dark
    : style.light;

// lut
const lutName = userParams.lut || 'erdc_rainbow_bright';

// field
const field = userParams.field || '';

// camera
function updateCamera(camera) {
  ['zoom', 'pitch', 'elevation', 'yaw', 'azimuth', 'roll', 'dolly'].forEach(
    (key) => {
      if (userParams[key]) {
        camera[key](userParams[key]);
      }
      renderWindow.render();
    }
  );
}

function preventDefaults(e) {
  e.preventDefault();
  e.stopPropagation();
}

// ----------------------------------------------------------------------------
// DOM containers for UI control
// ----------------------------------------------------------------------------

const rootControllerContainer = document.createElement('div');
rootControllerContainer.setAttribute('class', style.rootController);

const addDataSetButton = document.createElement('img');
addDataSetButton.setAttribute('class', style.button);
addDataSetButton.setAttribute('src', icon);
addDataSetButton.addEventListener('click', () => {
  const isVisible = rootControllerContainer.style.display !== 'none';
  rootControllerContainer.style.display = isVisible ? 'none' : 'flex';
});

const fpsMonitor = vtkFPSMonitor.newInstance();
const fpsElm = fpsMonitor.getFpsMonitorContainer();
fpsElm.classList.add(style.fpsMonitor);

// ----------------------------------------------------------------------------
// Add class to body if iOS device
// ----------------------------------------------------------------------------

const iOS = /iPad|iPhone|iPod/.test(window.navigator.platform);

if (iOS) {
  document.querySelector('body').classList.add('is-ios-device');
}

// ----------------------------------------------------------------------------

function emptyContainer(container) {
  fpsMonitor.setContainer(null);
  while (container.firstChild) {
    container.removeChild(container.firstChild);
  }
}

// ----------------------------------------------------------------------------

function createViewer(container) {
  const fullScreenRenderer = vtkFullScreenRenderWindow.newInstance({
    background,
    rootContainer: container,
    containerStyle: { height: '100%', width: '100%', position: 'absolute' },
  });
  renderer = fullScreenRenderer.getRenderer();
  renderWindow = fullScreenRenderer.getRenderWindow();
  renderWindow.getInteractor().setDesiredUpdateRate(15);

  container.appendChild(rootControllerContainer);
  container.appendChild(addDataSetButton);

  if (userParams.fps) {
    if (Array.isArray(userParams.fps)) {
      fpsMonitor.setMonitorVisibility(...userParams.fps);
      if (userParams.fps.length === 4) {
        fpsMonitor.setOrientation(userParams.fps[3]);
      }
    }
    fpsMonitor.setRenderWindow(renderWindow);
    fpsMonitor.setContainer(container);
    fullScreenRenderer.setResizeCallback(fpsMonitor.update);
  }
}

// ----------------------------------------------------------------------------

function createPipeline(fileName, fileContents) {
  // Create UI
  const presetSelector = document.createElement('select');
  presetSelector.setAttribute('class', selectorClass);
  presetSelector.innerHTML = vtkColorMaps.rgbPresetNames
    .map(
      (name) =>
        `<option value="${name}" ${
          lutName === name ? 'selected="selected"' : ''
        }>${name}</option>`
    )
    .join('');

  const representationSelector = document.createElement('select');
  representationSelector.setAttribute('class', selectorClass);
  representationSelector.innerHTML = [
    'Hidden',
    'Points',
    'Wireframe',
    'Surface',
    'Surface with Edge',
  ]
    .map(
      (name, idx) =>
        `<option value="${idx === 0 ? 0 : 1}:${idx < 4 ? idx - 1 : 2}:${
          idx === 4 ? 1 : 0
        }">${name}</option>`
    )
    .join('');
  representationSelector.value = '1:2:0';

  const colorBySelector = document.createElement('select');
  colorBySelector.setAttribute('class', selectorClass);

  const componentSelector = document.createElement('select');
  componentSelector.setAttribute('class', selectorClass);
  componentSelector.style.display = 'none';

  const opacitySelector = document.createElement('input');
  opacitySelector.setAttribute('class', selectorClass);
  opacitySelector.setAttribute('type', 'range');
  opacitySelector.setAttribute('value', '100');
  opacitySelector.setAttribute('max', '100');
  opacitySelector.setAttribute('min', '1');

  const labelSelector = document.createElement('label');
  labelSelector.setAttribute('class', selectorClass);
  labelSelector.innerHTML = fileName;

  const controlContainer = document.createElement('div');
  controlContainer.setAttribute('class', style.control);
  controlContainer.appendChild(labelSelector);
  controlContainer.appendChild(representationSelector);
  controlContainer.appendChild(presetSelector);
  controlContainer.appendChild(colorBySelector);
  controlContainer.appendChild(componentSelector);
  controlContainer.appendChild(opacitySelector);
  rootControllerContainer.appendChild(controlContainer);

  // VTK pipeline
  const vtpReader = vtkXMLPolyDataReader.newInstance();
  vtpReader.parseAsArrayBuffer(fileContents);

  const lookupTable = vtkColorTransferFunction.newInstance();
  const source = vtpReader.getOutputData(0);
  const mapper = vtkMapper.newInstance({
    interpolateScalarsBeforeMapping: false,
    useLookupTableScalarRange: true,
    lookupTable,
    scalarVisibility: false,
  });
  const actor = vtkActor.newInstance();
  const scalars = source.getPointData().getScalars();
  const dataRange = [].concat(scalars ? scalars.getRange() : [0, 1]);

  // --------------------------------------------------------------------
  // Color handling
  // --------------------------------------------------------------------

  function applyPreset() {
    const preset = vtkColorMaps.getPresetByName(presetSelector.value);
    lookupTable.applyColorMap(preset);
    lookupTable.setMappingRange(dataRange[0], dataRange[1]);
    lookupTable.updateRange();
  }
  applyPreset();
  presetSelector.addEventListener('change', applyPreset);

  // --------------------------------------------------------------------
  // Representation handling
  // --------------------------------------------------------------------

  function updateRepresentation(event) {
    const [
      visibility,
      representation,
      edgeVisibility,
    ] = event.target.value.split(':').map(Number);
    actor.getProperty().set({ representation, edgeVisibility });
    actor.setVisibility(!!visibility);
    renderWindow.render();
  }
  representationSelector.addEventListener('change', updateRepresentation);

  // --------------------------------------------------------------------
  // Opacity handling
  // --------------------------------------------------------------------

  function updateOpacity(event) {
    const opacity = Number(event.target.value) / 100;
    actor.getProperty().setOpacity(opacity);
    renderWindow.render();
  }

  opacitySelector.addEventListener('input', updateOpacity);

  // --------------------------------------------------------------------
  // ColorBy handling
  // --------------------------------------------------------------------

  const colorByOptions = [{ value: ':', label: 'Solid color' }].concat(
    source
      .getPointData()
      .getArrays()
      .map((a) => ({
        label: `(p) ${a.getName()}`,
        value: `PointData:${a.getName()}`,
      })),
    source
      .getCellData()
      .getArrays()
      .map((a) => ({
        label: `(c) ${a.getName()}`,
        value: `CellData:${a.getName()}`,
      }))
  );
  colorBySelector.innerHTML = colorByOptions
    .map(
      ({ label, value }) =>
        `<option value="${value}" ${
          field === value ? 'selected="selected"' : ''
        }>${label}</option>`
    )
    .join('');

  function updateColorBy(event) {
    const [location, colorByArrayName] = event.target.value.split(':');
    const interpolateScalarsBeforeMapping = location === 'PointData';
    let colorMode = ColorMode.DEFAULT;
    let scalarMode = ScalarMode.DEFAULT;
    const scalarVisibility = location.length > 0;
    if (scalarVisibility) {
      const activeArray = source[`get${location}`]().getArrayByName(
        colorByArrayName
      );
      const newDataRange = activeArray.getRange();
      dataRange[0] = newDataRange[0];
      dataRange[1] = newDataRange[1];
      colorMode = ColorMode.MAP_SCALARS;
      scalarMode =
        location === 'PointData'
          ? ScalarMode.USE_POINT_FIELD_DATA
          : ScalarMode.USE_CELL_FIELD_DATA;

      const numberOfComponents = activeArray.getNumberOfComponents();
      if (numberOfComponents > 1) {
        // always start on magnitude setting
        if (mapper.getLookupTable()) {
          const lut = mapper.getLookupTable();
          lut.setVectorModeToMagnitude();
        }
        componentSelector.style.display = 'block';
        const compOpts = ['Magnitude'];
        while (compOpts.length <= numberOfComponents) {
          compOpts.push(`Component ${compOpts.length}`);
        }
        componentSelector.innerHTML = compOpts
          .map((t, index) => `<option value="${index - 1}">${t}</option>`)
          .join('');
      } else {
        componentSelector.style.display = 'none';
      }
    } else {
      componentSelector.style.display = 'none';
    }
    mapper.set({
      colorByArrayName,
      colorMode,
      interpolateScalarsBeforeMapping,
      scalarMode,
      scalarVisibility,
    });
    applyPreset();
  }
  colorBySelector.addEventListener('change', updateColorBy);
  updateColorBy({ target: colorBySelector });

  function updateColorByComponent(event) {
    if (mapper.getLookupTable()) {
      const lut = mapper.getLookupTable();
      if (event.target.value === -1) {
        lut.setVectorModeToMagnitude();
      } else {
        lut.setVectorModeToComponent();
        lut.setVectorComponent(Number(event.target.value));
      }
      renderWindow.render();
    }
  }
  componentSelector.addEventListener('change', updateColorByComponent);

  // --------------------------------------------------------------------
  // Pipeline handling
  // --------------------------------------------------------------------

  actor.setMapper(mapper);
  mapper.setInputData(source);
  renderer.addActor(actor);

  // Manage update when lookupTable change
  lookupTable.onModified(() => {
    renderWindow.render();
  });

  // First render
  renderer.resetCamera();
  renderWindow.render();

  global.pipeline[fileName] = {
    actor,
    mapper,
    source,
    lookupTable,
    renderer,
    renderWindow,
  };

  // Update stats
  fpsMonitor.update();
}

// ----------------------------------------------------------------------------

function loadFile(file) {
  const reader = new FileReader();
  reader.onload = function onLoad(e) {
    createPipeline(file.name, reader.result);
  };
  reader.readAsArrayBuffer(file);
}

// ----------------------------------------------------------------------------

export function load(container, options) {
  autoInit = false;
  emptyContainer(container);

  if (options.files) {
    createViewer(container);
    let count = options.files.length;
    while (count--) {
      loadFile(options.files[count]);
    }
    updateCamera(renderer.getActiveCamera());
  } else if (options.fileURL) {
    const urls = [].concat(options.fileURL);
    const progressContainer = document.createElement('div');
    progressContainer.setAttribute('class', style.progress);
    container.appendChild(progressContainer);

    const progressCallback = (progressEvent) => {
      const percent = Math.floor(
        100 * progressEvent.loaded / progressEvent.total / urls.length
      );
      progressContainer.innerHTML = `Loading ${percent}%`;
    };

    createViewer(container);
    const nbURLs = urls.length;
    let nbLoadedData = 0;

    /* eslint-disable no-loop-func */
    while (urls.length) {
      const url = urls.pop();
      const name = Array.isArray(userParams.name)
        ? userParams.name[urls.length]
        : `Data ${urls.length + 1}`;
      HttpDataAccessHelper.fetchBinary(url, {
        progressCallback,
      }).then((binary) => {
        nbLoadedData++;
        if (nbLoadedData === nbURLs) {
          container.removeChild(progressContainer);
        }
        createPipeline(name, binary);
        updateCamera(renderer.getActiveCamera());
      });
    }
  }
}

export function initLocalFileLoader(container) {
  const exampleContainer = document.querySelector('.content');
  const rootBody = document.querySelector('body');
  const myContainer = container || exampleContainer || rootBody;

  if (myContainer !== container) {
    myContainer.classList.add(style.fullScreen);
    rootBody.style.margin = '0';
    rootBody.style.padding = '0';
  } else {
    rootBody.style.margin = '0';
    rootBody.style.padding = '0';
  }

  const fileContainer = document.createElement('div');
  fileContainer.innerHTML = `<div class="${
    style.bigFileDrop
  }"/><input type="file" multiple accept=".vtp" style="display: none;"/>`;
  myContainer.appendChild(fileContainer);

  const fileInput = fileContainer.querySelector('input');

  function handleFile(e) {
    preventDefaults(e);
    const dataTransfer = e.dataTransfer;
    const files = e.target.files || dataTransfer.files;
    if (files.length > 0) {
      myContainer.removeChild(fileContainer);
      load(myContainer, { files });
    }
  }

  fileInput.addEventListener('change', handleFile);
  fileContainer.addEventListener('drop', handleFile);
  fileContainer.addEventListener('click', (e) => fileInput.click());
  fileContainer.addEventListener('dragover', preventDefaults);
}

// Look at URL an see if we should load a file
// ?fileURL=https://data.kitware.com/api/v1/item/59cdbb588d777f31ac63de08/download
if (userParams.url || userParams.fileURL) {
  const exampleContainer = document.querySelector('.content');
  const rootBody = document.querySelector('body');
  const myContainer = exampleContainer || rootBody;

  if (myContainer) {
    myContainer.classList.add(style.fullScreen);
    rootBody.style.margin = '0';
    rootBody.style.padding = '0';
  }

  load(myContainer, userParams);
}

// Auto setup if no method get called within 100ms
setTimeout(() => {
  if (autoInit) {
    initLocalFileLoader();
  }
}, 100);
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   xTuple PostBooks - xTuple Business Management Framework
// Copyright: ©2011 OpenMFG LLC, d/b/a xTuple
// ==========================================================================
/*globals XT */

sc_require('ext/store');
sc_require('ext/dispatch');
sc_require('ext/data_source');

/** @instance

  An object that contains user login information for quick access at run time.

  @extends SC.Object
*/

XT.session = SC.Object.create({

  SETTINGS:             0x0100,
  PRIVILEGES:           0x0200,
  LOCALE:               0x0400,
  ALL:                  0x0100 | 0x0200 | 0x0400,

  privileges: null,

  store: function() {
    return XT.store;
  }.property().cacheable(),

  /**
    Loads session objects for settings, preferences and privileges into local
    memory. Types `XT.session.SETTINGS`, `XT.session.LOCALE` or types
    `XT.session.PRIVILEGES` can be passed as bitwise operators. If no
    arguments are passed the default is `XT.session.ALL` which will load all
    session objects.
  */
  load: function(types) {
    var self = this,
        store = this.get('store'),
        dispatch, callback;

    if (types === undefined) types = this.ALL;

    if (types & this.PRIVILEGES) {
      dispatch = XT.Dispatch.create({
        className: 'XT.Session',
        functionName: 'privileges',
        target: self,
        action: self.didFetchPrivileges
      });

      store.dispatch(dispatch);
    }

    if (types & this.SETTINGS) {
      dispatch = XT.Dispatch.create({
        className: 'XT.Session',
        functionName: 'settings',
        target: self,
        action: self.didFetchSettings
      });

      store.dispatch(dispatch);
    }

    if (types & this.LOCALE) {
      dispatch = XT.Dispatch.create({
        className: 'XT.Session',
        functionName: 'locale',
        target: self,
        action: self.didFetchLocale
      });

      store.dispatch(dispatch);
    }

    return true;
  },

  didFetchSettings: function(error, response) {
    // Create an object for settings.
    var that = this,
        settings = SC.Object.create({
          // Return false if property not found
          get: function(key) {
            for (var prop in this) {
              if (prop === key) return this[prop];
            }

            return false;
          },

          set: function(key, value) {
            this.get('changed').push(key);

            arguments.callee.base.apply(this, arguments);
          },

          changed: []
        });

    // Loop through the response and set a setting for each found
    response.forEach(function(item) {
      settings.set(item.setting, item.value);
    });

    settings.set('changed', []);

    // Attach the settings to the session object
    this.set('settings', settings);

    return true;
  },

  didFetchPrivileges: function(error, response) {
    // Create a special object for privileges where the get function returns
    // `false` if it can't find the key.
    var privileges = SC.Object.create({
      get: function(key) {
        if (typeof key === 'boolean') return key;

        for (var prop in this) {
          if (prop === key) return this[prop];
        }

        return false;
      }
    });

    // Loop through the response and set a privilege for each found.
    response.forEach(function(item) {
      privileges.set(item.privilege, item.isGranted);
    });

    // Attach the privileges to the session object.
    this.set('privileges', privileges);

    return true;
  },

  didFetchLocale: function(error, response) {
    // Attach the locale to the session object.
    this.set('locale', response);

    return true;
  },

  init: function() {
    arguments.callee.base.apply(this, arguments);
    XT.ready(function() { XT.session.load(); });
  }

});
<commit_msg>data_source was moved<commit_after>// ==========================================================================
// Project:   xTuple PostBooks - xTuple Business Management Framework
// Copyright: ©2011 OpenMFG LLC, d/b/a xTuple
// ==========================================================================
/*globals XT */

sc_require('ext/store');
sc_require('ext/dispatch');

/** @instance

  An object that contains user login information for quick access at run time.

  @extends SC.Object
*/

XT.session = SC.Object.create({

  SETTINGS:             0x0100,
  PRIVILEGES:           0x0200,
  LOCALE:               0x0400,
  ALL:                  0x0100 | 0x0200 | 0x0400,

  privileges: null,

  store: function() {
    return XT.store;
  }.property().cacheable(),

  /**
    Loads session objects for settings, preferences and privileges into local
    memory. Types `XT.session.SETTINGS`, `XT.session.LOCALE` or types
    `XT.session.PRIVILEGES` can be passed as bitwise operators. If no
    arguments are passed the default is `XT.session.ALL` which will load all
    session objects.
  */
  load: function(types) {
    var self = this,
        store = this.get('store'),
        dispatch, callback;

    if (types === undefined) types = this.ALL;

    if (types & this.PRIVILEGES) {
      dispatch = XT.Dispatch.create({
        className: 'XT.Session',
        functionName: 'privileges',
        target: self,
        action: self.didFetchPrivileges
      });

      store.dispatch(dispatch);
    }

    if (types & this.SETTINGS) {
      dispatch = XT.Dispatch.create({
        className: 'XT.Session',
        functionName: 'settings',
        target: self,
        action: self.didFetchSettings
      });

      store.dispatch(dispatch);
    }

    if (types & this.LOCALE) {
      dispatch = XT.Dispatch.create({
        className: 'XT.Session',
        functionName: 'locale',
        target: self,
        action: self.didFetchLocale
      });

      store.dispatch(dispatch);
    }

    return true;
  },

  didFetchSettings: function(error, response) {
    // Create an object for settings.
    var that = this,
        settings = SC.Object.create({
          // Return false if property not found
          get: function(key) {
            for (var prop in this) {
              if (prop === key) return this[prop];
            }

            return false;
          },

          set: function(key, value) {
            this.get('changed').push(key);

            arguments.callee.base.apply(this, arguments);
          },

          changed: []
        });

    // Loop through the response and set a setting for each found
    response.forEach(function(item) {
      settings.set(item.setting, item.value);
    });

    settings.set('changed', []);

    // Attach the settings to the session object
    this.set('settings', settings);

    return true;
  },

  didFetchPrivileges: function(error, response) {
    // Create a special object for privileges where the get function returns
    // `false` if it can't find the key.
    var privileges = SC.Object.create({
      get: function(key) {
        if (typeof key === 'boolean') return key;

        for (var prop in this) {
          if (prop === key) return this[prop];
        }

        return false;
      }
    });

    // Loop through the response and set a privilege for each found.
    response.forEach(function(item) {
      privileges.set(item.privilege, item.isGranted);
    });

    // Attach the privileges to the session object.
    this.set('privileges', privileges);

    return true;
  },

  didFetchLocale: function(error, response) {
    // Attach the locale to the session object.
    this.set('locale', response);

    return true;
  },

  init: function() {
    arguments.callee.base.apply(this, arguments);
    XT.ready(function() { XT.session.load(); });
  }

});
<|endoftext|>