<commit_before>Highcharts.setOptions({
    lang: {
        thousandsSep: ','
    }
});

function initializeTable(table_id, column_names, data){
    // column_names is an array of names to be used as the header row of the table
    // data is a 2D array of values for the table
    var names = [];
    $.each(column_names, function(i, name){
        names.push({'title': name});
    })
    $(table_id).DataTable({
        searching: false,
        lengthMenu: [ [20, 100, -1], [20, 100, "All"] ],
        destroy: true,
        data: data,
        columns: names,
        info: false,
        paging: false
    });
}

function makeDemandChart(element_id, place_data){

    var sorted_data = _.sortBy(place_data, 'demand_sum').reverse()

    var n_cols = 36
    var prepped_data = [
        {
            name: 'Higher education',
            color: '#154779',
            data: _.pluck(sorted_data, "demand_entry_he").slice(0,n_cols)
        }, {
            name: 'Further education',
            color: '#2b74a6',
            data: _.pluck(sorted_data, "demand_entry_fe").slice(0,n_cols)
        }
        , {
            name: 'School leavers',
            color: '#60aadb',
            data: _.pluck(sorted_data, "demand_entry_sl").slice(0,n_cols)
        }
    ]

    occupations = _.pluck(sorted_data, "occupation").slice(0,n_cols)

    stackedBarHelper(element_id, prepped_data, occupations, 'Demand', 'Demand (# jobs)', place_data)
}

function makeCompScatterPlot(element_id, place_data, education){

    if (education=='he'){
        var place_data_edu = _.where(place_data, {include_he: "1"})
        var point_color = '#154779'

        $("#he-select").attr('class', 'btn selected');
        $("#fe-select").attr('class', 'btn');
    }
    else{
        var place_data_edu = _.where(place_data, {include_fe: "1"})
        var point_color = "#2b74a6"

        $("#fe-select").attr('class', 'btn selected');
        $("#he-select").attr('class', 'btn');
    }

    var prepped_data = []
    $(place_data_edu).each(function(i, row){
        point = {
            x: row['advertised_avg_salary_entry_degree'],
            y: row['fe_ds_ratio_log'],
            name: shortenName(row['occupation']),
            full_name: row['occupation']
        }
        if (!isNaN(point.x) && !isNaN(point.y)) prepped_data.push(point)
    })

    scatterHelper(element_id, prepped_data, 'Opportunity', 'Opportunity', point_color, place_data)
}

function scatterHelper(element_id, prepped_data, y_label_full, y_label_short, point_color, place_data){
    var chart_height = $(element_id).height()

    $(element_id).highcharts({

        chart: {
            type: 'scatter',
            zoomType: 'xy'
        },

        credits: {
            enabled: false
        },

        legend: {
            enabled: false
        },

        title: {
            text: ''
        },

        xAxis: {
            title: {
                text: 'Average salary',
                style: {
                    color: '#aaa',
                }
            },
            labels: {
                formatter: function () {
                   return '£'+(this.value / 1000) + 'k';
                },
                style: {
                    color: '#aaa',
                    fontSize: '9px',
                }
            },
            min: 18000,
            tickColor: '#eee',
            tickLength: 5,
            lineColor: '#eee'
        },

        yAxis: {
            gridLineWidth: 0,
            startOnTick: true,
            endOnTick: true,
            max: 2.4,
            min: -2.4,
            title: {
                text: y_label_full,
                style: {
                    color: '#aaa',
                }
            },
            labels: {
                enabled: false
            },
            lineColor: '#eee',
            lineWidth: 1
        },

        tooltip: {
            useHTML: true,
            headerFormat: '
',
            pointFormat: '
{point.full_name}
' +
                '
Average salary:	£{point.x:,.0f}
' +
                '
'+y_label_short+':	{point.y}
',
            footerFormat: '
',
            followPointer: true,
            shadow: false,
            borderColor: '#eee'
        },

        labels: {
            items: [
                {
                    html: "↑ Less competition",
                    style: {
                        color: '#FBAB18',
                        left: '10px',
                        top: '10px',
                    }
                },
                {
                    html: "↓ More competition",
                    style: {
                        color: '#FBAB18',
                        left: '10px',
                        top: chart_height - 90
                    }
                }
            ]
        },

        plotOptions: {
            series: {
                cursor: 'pointer',
                color: point_color,
                point: {
                    events: {
                        click: function () {
                            selectOccupation(this.full_name, place_data);
                        },
                        mouseOver: function () {
                            triggerHoverBar(this.full_name);
                        },
                    }
                },
                marker: {
                    states: {
                        select: {
                            fillColor: point_color,
                            lineWidth: 6,
                            lineColor: "#f47730",
                            radius: 8
                        }
                    }
                },
                states: {
                    hover: {
                        halo: {
                            size: 12,
                        }
                    }

                }
            },
        },

        series: [{
            data: prepped_data,
        }]

    });
};

function stackedBarHelper(element_id, prepped_data, categories, y_label_full, y_label_short, place_data){
    $(element_id).highcharts({
        chart: {
            type: 'bar',
            zoomType: 'y'
        },
        credits: {
            enabled: false
        },
        title: {
            text: ''
        },
        xAxis: {
            categories: categories,
            tickWidth: 0,
            labels: {
                formatter: function () {
                    return shortenName(this.value);
                },
                style: {
                    fontSize: '9px',
                    color: '#aaa'
                }
            },
            lineColor: '#eee'
        },
        yAxis: {
            min: 0,
            gridLineWidth: 0,
            endOnTick: false,
            title: {
                text: y_label_short,
                style: {
                    color: '#aaa'
                }
            },
            labels: {
                style: {
                    color: '#aaa',
                    fontSize: '9px',
                }
            }
        },
        legend: {
            align: 'right',
            layout: 'vertical',
            x: -30,
            verticalAlign: 'top',
            y: 50,
            floating: true,
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
            borderColor: '#CCC',
            borderWidth: 1,
            shadow: false
        },
        tooltip: {
            useHTML: true,
            headerFormat: '

{point.x}
',
            pointFormat:  '
{series.name}:	{point.y:,.0f}
',
            footerFormat: '
',
            shared: true,
            positioner: function () {
                return { x: 200, y: 350 };
            },
            shadow: false,
            borderColor: '#eee'
        },
        plotOptions: {
            bar: {
                stacking: 'normal'
            },
            series: {
                cursor: 'pointer',
                pointPadding: 0,
                groupPadding: .1,
                point: {
                    events: {
                        click: function () {
                            selectOccupation(categories[this.x], place_data);
                        },
                        mouseOver: function () {
                            triggerHoverScatter(categories[this.x]);
                        }
                    }
                },
                states: {
                    select: {
                        borderColor: "#f47730",
                        color: "#f47730"
                    },
                    hover: {
                        brightness: .2
                    }
                }
            }
        },
        series: prepped_data

    });
};

function highlightOcc(occupation){

    $.each(Highcharts.charts, function(index, chart){
        if (chart && chart.options.chart.type == 'scatter'){
            // looping thru stuff in scatterplot
            $.each(chart.series[0].points, function(index, point){
                if(point.full_name == occupation){
                    point.select(true, true);
                }
                else{
                    point.select(false, true);
                }
            });
        }
        else if (chart && chart.options.chart.type == 'bar'){
            // looping thru stuff in bar chart
            $.each(chart.series, function(index, series){
                $.each(series.data, function(index, point){
                    if(point.category == occupation){
                        point.select(true, true);
                    }
                    else{
                        point.select(false, true);
                    }
                });
            });
        };
    });

}

function triggerHoverScatter(occupation){

    $.each(Highcharts.charts, function(index, chart){
        if (chart && chart.options.chart.type == 'scatter'){
            $.each(chart.series[0].points, function(index, point){
                if(point.full_name == occupation){
                    point.setState('hover');
                    chart.tooltip.refresh(point);
                }
                else{
                    point.setState();
                }
            });
        };
    });

}
function triggerHoverBar(occupation){

    // looping thru stuff in bar chart
    $.each(Highcharts.charts, function(index, chart){
        if (chart && chart.options.chart.type == 'bar'){
            $.each(chart.series, function(index, series){
                $.each(series.data, function(index, point){
                    if(point.category == occupation){
                        point.setState('hover');
                        chart.tooltip.refresh([chart.series[0].data[index], chart.series[1].data[index], chart.series[2].data[index]]);
                    }
                    else{
                        point.setState();
                    }
                });
            });
        };
    });

}

function shortenName(long_name) {
    return occupation_mapping[long_name]['short_name'];
};<commit_msg>tweak scatterplot axis, closes #54<commit_after>Highcharts.setOptions({
    lang: {
        thousandsSep: ','
    }
});

function initializeTable(table_id, column_names, data){
    // column_names is an array of names to be used as the header row of the table
    // data is a 2D array of values for the table
    var names = [];
    $.each(column_names, function(i, name){
        names.push({'title': name});
    })
    $(table_id).DataTable({
        searching: false,
        lengthMenu: [ [20, 100, -1], [20, 100, "All"] ],
        destroy: true,
        data: data,
        columns: names,
        info: false,
        paging: false
    });
}

function makeDemandChart(element_id, place_data){

    var sorted_data = _.sortBy(place_data, 'demand_sum').reverse()

    var n_cols = 36
    var prepped_data = [
        {
            name: 'Higher education',
            color: '#154779',
            data: _.pluck(sorted_data, "demand_entry_he").slice(0,n_cols)
        }, {
            name: 'Further education',
            color: '#2b74a6',
            data: _.pluck(sorted_data, "demand_entry_fe").slice(0,n_cols)
        }
        , {
            name: 'School leavers',
            color: '#60aadb',
            data: _.pluck(sorted_data, "demand_entry_sl").slice(0,n_cols)
        }
    ]

    occupations = _.pluck(sorted_data, "occupation").slice(0,n_cols)

    stackedBarHelper(element_id, prepped_data, occupations, 'Demand', 'Demand (# jobs)', place_data)
}

function makeCompScatterPlot(element_id, place_data, education){

    if (education=='he'){
        var place_data_edu = _.where(place_data, {include_he: "1"})
        var point_color = '#154779'

        $("#he-select").attr('class', 'btn selected');
        $("#fe-select").attr('class', 'btn');
    }
    else{
        var place_data_edu = _.where(place_data, {include_fe: "1"})
        var point_color = "#2b74a6"

        $("#fe-select").attr('class', 'btn selected');
        $("#he-select").attr('class', 'btn');
    }

    var prepped_data = []
    $(place_data_edu).each(function(i, row){
        point = {
            x: row['advertised_avg_salary_entry_degree'],
            y: row['fe_ds_ratio_log'],
            name: shortenName(row['occupation']),
            full_name: row['occupation']
        }
        if (!isNaN(point.x) && !isNaN(point.y)) prepped_data.push(point)
    })

    scatterHelper(element_id, prepped_data, 'Opportunity', 'Opportunity', point_color, place_data)
}

function scatterHelper(element_id, prepped_data, y_label_full, y_label_short, point_color, place_data){
    var chart_height = $(element_id).height()

    $(element_id).highcharts({

        chart: {
            type: 'scatter',
            zoomType: 'xy'
        },

        credits: {
            enabled: false
        },

        legend: {
            enabled: false
        },

        title: {
            text: ''
        },

        xAxis: {
            title: {
                text: 'Average salary',
                style: {
                    color: '#aaa',
                }
            },
            labels: {
                formatter: function () {
                   return '£'+(this.value / 1000) + 'k';
                },
                style: {
                    color: '#aaa',
                    fontSize: '9px',
                }
            },
            min: 18000,
            tickColor: '#eee',
            tickLength: 5,
            lineColor: '#eee'
        },

        yAxis: {
            gridLineWidth: 0,
            startOnTick: false,
            endOnTick: false,
            max: 2.4,
            min: -2.4,
            title: {
                text: y_label_full,
                style: {
                    color: '#aaa',
                }
            },
            labels: {
                enabled: false
            },
            lineColor: '#eee',
            lineWidth: 1
        },

        tooltip: {
            useHTML: true,
            headerFormat: '
',
            pointFormat: '
{point.full_name}
' +
                '
Average salary:	£{point.x:,.0f}
' +
                '
'+y_label_short+':	{point.y}
',
            footerFormat: '
',
            followPointer: true,
            shadow: false,
            borderColor: '#eee'
        },

        labels: {
            items: [
                {
                    html: "↑ Less competition",
                    style: {
                        color: '#FBAB18',
                        left: '10px',
                        top: '10px',
                    }
                },
                {
                    html: "↓ More competition",
                    style: {
                        color: '#FBAB18',
                        left: '10px',
                        top: chart_height - 90
                    }
                }
            ]
        },

        plotOptions: {
            series: {
                cursor: 'pointer',
                color: point_color,
                point: {
                    events: {
                        click: function () {
                            selectOccupation(this.full_name, place_data);
                        },
                        mouseOver: function () {
                            triggerHoverBar(this.full_name);
                        },
                    }
                },
                marker: {
                    states: {
                        select: {
                            fillColor: point_color,
                            lineWidth: 6,
                            lineColor: "#f47730",
                            radius: 8
                        }
                    }
                },
                states: {
                    hover: {
                        halo: {
                            size: 12,
                        }
                    }

                }
            },
        },

        series: [{
            data: prepped_data,
        }]

    });
};

function stackedBarHelper(element_id, prepped_data, categories, y_label_full, y_label_short, place_data){
    $(element_id).highcharts({
        chart: {
            type: 'bar',
            zoomType: 'y'
        },
        credits: {
            enabled: false
        },
        title: {
            text: ''
        },
        xAxis: {
            categories: categories,
            tickWidth: 0,
            labels: {
                formatter: function () {
                    return shortenName(this.value);
                },
                style: {
                    fontSize: '9px',
                    color: '#aaa'
                }
            },
            lineColor: '#eee'
        },
        yAxis: {
            min: 0,
            gridLineWidth: 0,
            endOnTick: false,
            title: {
                text: y_label_short,
                style: {
                    color: '#aaa'
                }
            },
            labels: {
                style: {
                    color: '#aaa',
                    fontSize: '9px',
                }
            }
        },
        legend: {
            align: 'right',
            layout: 'vertical',
            x: -30,
            verticalAlign: 'top',
            y: 50,
            floating: true,
            backgroundColor: (Highcharts.theme && Highcharts.theme.background2) || 'white',
            borderColor: '#CCC',
            borderWidth: 1,
            shadow: false
        },
        tooltip: {
            useHTML: true,
            headerFormat: '

{point.x}
',
            pointFormat:  '
{series.name}:	{point.y:,.0f}
',
            footerFormat: '
',
            shared: true,
            positioner: function () {
                return { x: 200, y: 350 };
            },
            shadow: false,
            borderColor: '#eee'
        },
        plotOptions: {
            bar: {
                stacking: 'normal'
            },
            series: {
                cursor: 'pointer',
                pointPadding: 0,
                groupPadding: .1,
                point: {
                    events: {
                        click: function () {
                            selectOccupation(categories[this.x], place_data);
                        },
                        mouseOver: function () {
                            triggerHoverScatter(categories[this.x]);
                        }
                    }
                },
                states: {
                    select: {
                        borderColor: "#f47730",
                        color: "#f47730"
                    },
                    hover: {
                        brightness: .2
                    }
                }
            }
        },
        series: prepped_data

    });
};

function highlightOcc(occupation){

    $.each(Highcharts.charts, function(index, chart){
        if (chart && chart.options.chart.type == 'scatter'){
            // looping thru stuff in scatterplot
            $.each(chart.series[0].points, function(index, point){
                if(point.full_name == occupation){
                    point.select(true, true);
                }
                else{
                    point.select(false, true);
                }
            });
        }
        else if (chart && chart.options.chart.type == 'bar'){
            // looping thru stuff in bar chart
            $.each(chart.series, function(index, series){
                $.each(series.data, function(index, point){
                    if(point.category == occupation){
                        point.select(true, true);
                    }
                    else{
                        point.select(false, true);
                    }
                });
            });
        };
    });

}

function triggerHoverScatter(occupation){

    $.each(Highcharts.charts, function(index, chart){
        if (chart && chart.options.chart.type == 'scatter'){
            $.each(chart.series[0].points, function(index, point){
                if(point.full_name == occupation){
                    point.setState('hover');
                    chart.tooltip.refresh(point);
                }
                else{
                    point.setState();
                }
            });
        };
    });

}
function triggerHoverBar(occupation){

    // looping thru stuff in bar chart
    $.each(Highcharts.charts, function(index, chart){
        if (chart && chart.options.chart.type == 'bar'){
            $.each(chart.series, function(index, series){
                $.each(series.data, function(index, point){
                    if(point.category == occupation){
                        point.setState('hover');
                        chart.tooltip.refresh([chart.series[0].data[index], chart.series[1].data[index], chart.series[2].data[index]]);
                    }
                    else{
                        point.setState();
                    }
                });
            });
        };
    });

}

function shortenName(long_name) {
    return occupation_mapping[long_name]['short_name'];
};<|endoftext|>


<commit_before>(function($){

 $.fn.time = function(options) {

            var defaults = {};
            var options = $.extend(defaults, options);

            return this.each(function() {
            var obj = $(this);
            obj.html('

');
            var $secondi = $('#secondi');
            var $ora = $('#ore');
            var $minuti = $('#minuti');

            /* function ora esatta per ora esatta*/
            function oraesatta (a,b,c){
            var dataintera = new Date();
            var HH = dataintera.getHours();
            var MM = dataintera.getMinutes();
            var SS = dataintera.getSeconds();
            var degsec = SS*6;
            var degora = (HH*30)+((1/2)*MM);
            var degmin = MM*6;

            a.css({'transform':'rotate('+degsec+'deg)',
                   '-o-transform':'rotate('+degsec+'deg)',
                   '-ms-transform':'rotate('+degsec+'deg)',
                   '-moz-transform':'rotate('+degsec+'deg)',
                   '-webkit-transform': 'rotate('+degsec+'deg)'});

            b.css({'transform':'rotate('+degora+'deg)',
                       '-o-transform':'rotate('+degora+'deg)',
                       '-ms-transform':'rotate('+degora+'deg)',
                       '-moz-transform':'rotate('+degora+'deg)',
                       '-webkit-transform': 'rotate('+degora+'deg)'});

           c.css({'transform':'rotate('+degmin+'deg)',
                      '-o-transform':'rotate('+degmin+'deg)',
                      '-ms-transform':'rotate('+degmin+'deg)',
                      '-moz-transform':'rotate('+degmin+'deg)',
                      '-webkit-transform': 'rotate('+degmin+'deg)'});

                     };
             /* function oraesatta per ora esatta*/

      oraesatta($secondi , $ora , $minuti);

      setInterval(function(){oraesatta($secondi,$ora,$minuti)},1000);

    });

 };
})(jQuery);
<commit_msg>Update jquery.time.js<commit_after>(function($){

 $.fn.time = function(options) {

            var dataintera = new Date();
            var HH = dataintera.getHours();
            var MM = dataintera.getMinutes();
            var SS = dataintera.getSeconds();

            var defaults = {font_size:22 , color:'red'};
            var options = $.extend(defaults, options);

           return this.each(function() {

           var str = ' :  : ';
           $(this).html(str).css({'font-size': options.font_size+'px', 'color': options.color});

           if(SS<=9){
           $(' span.ss').html('0'+SS);
           }
           else{
            $(' span.ss').html(SS);
           };

           if(MM<=9){
            $(' span.mm').html('0'+MM);

           }else{
            $(' span.mm').html(MM);
            };

           if(HH<=9){
            $(' span.hh').html('0'+HH);

           }else{
            $(' span.hh').html(HH);
            };

           setInterval(function(){
           var dataintera = new Date();
           var HH = dataintera.getHours();
           var MM = dataintera.getMinutes();
           var SS = dataintera.getSeconds();

           if(SS<=9){$('span.ss').html('0'+SS);
            } else{$('span.ss').html(SS);
           };

          if(MM<=9){$('span.mm').html('0'+MM);
            }else{$('span.mm').html(MM);
            };

           if(HH<=9){$('span.hh').html('0'+HH);
            }else{$('span.hh').html(HH);
            };

           },1000);

    });

 };
})(jQuery);
<|endoftext|>


<commit_before>//Karyoviewer object
jviz.modules.karyoviewer = function(opt)
{
  //Check the options
  if(typeof opt !== 'object'){ var opt = {}; }

  //Save the ideogram ID
  this._id = (typeof opt.id === 'undefined') ? jviz.misc.getID({ prefix: 'karyoviewer', length: 5 }) : opt.id;

  //Save the ideogram class
  this._class = (typeof opt.class === 'undefined') ? 'jviz-modules-karyoviewer' : opt.class;

  //Parent element
  this._parent = opt.parent;

  //Default size
  this._width = 0; //Default width
  this._height = 0; //Default height

  //Margins
  //this._margin = { top: 30, bottom: 30, left: 40, right: 40 };

  //Orientation
  this._orientation = {};
  this._orientation.actual = ''; //Actual orientation name
  this._orientation.default = 'portrait'; //Default orientation
  this._orientation.values = [ 'portrait', 'landscape' ]; //Orientation values

  //Block configuration
  this._block = {};
  this._block.width = 0; //Block width
  this._block.height = 0; //Block height
  this._block.draw = { width: 0, height: 0 }; //Block draw zone
  this._block.margin = { top: 30, bottom: 30, left: 0, right: 0 }; //Block margins
  this._block.resized = false; //Block is resized

  //Block default values
  this._block.default = {};

  //Default values for protrait
  this._block.default.portrait = {};
  this._block.default.portrait.draw_width = 15; //Default portrait draw width
  this._block.default.portrait.draw_height = 70; //Default portrait draw height
  this._block.default.portrait.margin_top = 30; //Default portrait margin top
  this._block.default.portrait.margin_bottom = 30; //Default portrait margin bottom

  //Default values for landscape
  this._block.default.landscape = {};
  this._block.default.landscape.draw_width = 0; //Default landscape draw width
  this._block.default.landscape.draw_height = 20; //Default landscape draw height
  this._block.default.landscape.margin_top = 30; //Default landscape margin top
  this._block.default.landscape.margin_bottom = 30; //Default landscape margin bottom
  this._block.default.landscape.margin_left = 40; //Default landscape margin left
  this._block.default.landscape.margin_right = 40; //Default landscape margin right

  //Panel object
  this._panel = {};
  this._panel.el = null; //Panel element
  this._panel.id = this._id + '-panel'; //Panel id
  this._panel.parent = this._id; //Panel parent
  this._panel.title = (typeof opt.title === 'string') ? opt.title : 'Karyotype viewer'; //Panel title
  this._panel.detail = (typeof opt.detail === 'string') ? opt.detail : ''; //Panel detail
  this._panel.detail = ''; //Panel detail
  this._panel.visible = (typeof opt.panel === 'boolean') ? opt.panel : true; //Panel is visible
  this._panel.foot = false; //Disable foot

  //Canvas object
  this._canvas = {};
  this._canvas.id = this._id + '-canvas'; //Canvas ID
  this._canvas.parent = this._id; //Parent canvas ID
  this._canvas.width = '100%'; //Canvas width
  this._canvas.height = 0; //Canvas height
  this._canvas.layers = 3; //Number of layers
  this._canvas.el = null; //Canvas element

  //Check the chromosomes object
  if(typeof opt.chromosomes !== 'object'){ opt.chromosomes = {}; }

  //Chromosomes info
  this._chromosomes = {};
  this._chromosomes.width = 15; //Chromosome default width
  this._chromosomes.height = 20; //Chromosome default height
  this._chromosomes.layer = 1; //Chromosome layer
  this._chromosomes.list = []; //Chromosomes list
  this._chromosomes.index = {}; //Chromosomes index
  this._chromosomes.names = {}; //Chromosome names
  this._chromosomes.max = 0; //Chromosome max length
  this._chromosomes.num = 0; //Number of chromosomes
  this._chromosomes.color = jviz.colors.blue2.hex; //Chromosome color
  this._chromosomes.opacity = 0.6; //Chromosome opacity
  this._chromosomes.resized = false; //Chromosome data is resized

  //Chromosome radius
  this._chromosomes.radius = {};
  this._chromosomes.radius.portrait = 6; //Chromosome radius for portrait
  this._chromosomes.radius.landscape = 10; //Chromosome radius for landscape

  //Chromosome name
  this._chromosomes.name = {};
  this._chromosomes.name.list = []; //List of chromosomes names
  this._chromosomes.name.visible = true; //Chromosome name is visible
  this._chromosomes.name.margin = 7; //Chromosome name margin

  //Chromosome name text
  this._chromosomes.name.text = {};
  this._chromosomes.name.text.font = jviz.font.default; //Chromosome name text font
  this._chromosomes.name.text.size = '12px'; //Chromosome name text size
  this._chromosomes.name.text.align = 'center'; //Chromosome name text align

  //Centromere
  this._chromosomes.centromere = {};
  this._chromosomes.centromere.list = []; //List of centromere positions
  this._chromosomes.centromere.opacity = 0.9; //Centromere opacity

  //Check the features object
  if(typeof opt.features === 'undefined'){ opt.features = {}; }

  //Features object
  this._features = {};
  this._features.list = []; //List of features
  this._features.layer = 2; //Features layer
  this._features.color = (typeof opt.features.color === 'string') ? opt.features.color : jviz.colors.red.hex; //Features default color
  this._features.opacity = 0.8; //Features opacity
  this._features.resized = false; //Features data is resized

  //Features counter
  this._features.counter = {};
  this._features.counter.visible = (typeof opt.features.count === 'boolean') ? opt.features.count : true; //Features counter is visible

  //Features triangle
  this._features.triangle = {};
  this._features.triangle.width = 6; //Features triangle width
  this._features.triangle.height = 4; //Features triangle height
  this._features.triangle.margin = 1; //Features triangle mrgin
  this._features.triangle.opacity = 0.6; //Features triangle opacity
  this._features.triangle.visible = (typeof opt.features.triangle === 'boolean') ? opt.features.triangle : true; //Triangle visible

  //Features label
  this._features.label = {};
  this._features.label.opacity = 1.0; //Features label opacity
  this._features.label.visible = (typeof opt.features.label === 'boolean') ? opt.features.label : true; //Label visible

  //Features label rectangle
  this._features.label.rectangle = {};
  this._features.label.rectangle.width = 0; //Features label rectangle width
  this._features.label.rectangle.height = 0; //Features label rectangle height
  this._features.label.rectangle.radius = 5; //Features label rectangle radius

  //Chromosomes hover
  this._hover = {};
  this._hover.index = -1; //Hover chromosome index
  this._hover.margin = { top: 10, bottom: 20, left: 10, right: 10 }; //Hover margin
  this._hover.color = jviz.colors.white.hex; //Hover background color
  this._hover.opacity = 1.0; //Hover background color opacity
  this._hover.radius = 10; //Hover radius
  this._hover.layer = 0; //Hover layer

  //Check for undefined orientation
  if(typeof opt.orientation !== 'string'){ opt.orientation = 'portrait'; }

  //Build the karyotype element
  this.build();

  //Register the events
  this.events();

  //Parse the orientation
  this.orientation(opt.orientation);

  //Return this
  return this;
};
<commit_msg>js/karyoviewer.js: save features for each chromosome<commit_after>//Karyoviewer object
jviz.modules.karyoviewer = function(opt)
{
  //Check the options
  if(typeof opt !== 'object'){ var opt = {}; }

  //Save the ideogram ID
  this._id = (typeof opt.id === 'undefined') ? jviz.misc.getID({ prefix: 'karyoviewer', length: 5 }) : opt.id;

  //Save the ideogram class
  this._class = (typeof opt.class === 'undefined') ? 'jviz-modules-karyoviewer' : opt.class;

  //Parent element
  this._parent = opt.parent;

  //Default size
  this._width = 0; //Default width
  this._height = 0; //Default height

  //Margins
  //this._margin = { top: 30, bottom: 30, left: 40, right: 40 };

  //Orientation
  this._orientation = {};
  this._orientation.actual = ''; //Actual orientation name
  this._orientation.default = 'portrait'; //Default orientation
  this._orientation.values = [ 'portrait', 'landscape' ]; //Orientation values

  //Block configuration
  this._block = {};
  this._block.width = 0; //Block width
  this._block.height = 0; //Block height
  this._block.draw = { width: 0, height: 0 }; //Block draw zone
  this._block.margin = { top: 30, bottom: 30, left: 0, right: 0 }; //Block margins
  this._block.resized = false; //Block is resized

  //Block default values
  this._block.default = {};

  //Default values for protrait
  this._block.default.portrait = {};
  this._block.default.portrait.draw_width = 15; //Default portrait draw width
  this._block.default.portrait.draw_height = 70; //Default portrait draw height
  this._block.default.portrait.margin_top = 30; //Default portrait margin top
  this._block.default.portrait.margin_bottom = 30; //Default portrait margin bottom

  //Default values for landscape
  this._block.default.landscape = {};
  this._block.default.landscape.draw_width = 0; //Default landscape draw width
  this._block.default.landscape.draw_height = 20; //Default landscape draw height
  this._block.default.landscape.margin_top = 30; //Default landscape margin top
  this._block.default.landscape.margin_bottom = 30; //Default landscape margin bottom
  this._block.default.landscape.margin_left = 40; //Default landscape margin left
  this._block.default.landscape.margin_right = 40; //Default landscape margin right

  //Panel object
  this._panel = {};
  this._panel.el = null; //Panel element
  this._panel.id = this._id + '-panel'; //Panel id
  this._panel.parent = this._id; //Panel parent
  this._panel.title = (typeof opt.title === 'string') ? opt.title : 'Karyotype viewer'; //Panel title
  this._panel.detail = (typeof opt.detail === 'string') ? opt.detail : ''; //Panel detail
  this._panel.detail = ''; //Panel detail
  this._panel.visible = (typeof opt.panel === 'boolean') ? opt.panel : true; //Panel is visible
  this._panel.foot = false; //Disable foot

  //Canvas object
  this._canvas = {};
  this._canvas.id = this._id + '-canvas'; //Canvas ID
  this._canvas.parent = this._id; //Parent canvas ID
  this._canvas.width = '100%'; //Canvas width
  this._canvas.height = 0; //Canvas height
  this._canvas.layers = 3; //Number of layers
  this._canvas.el = null; //Canvas element

  //Check the chromosomes object
  if(typeof opt.chromosomes !== 'object'){ opt.chromosomes = {}; }

  //Chromosomes info
  this._chromosomes = {};
  this._chromosomes.width = 15; //Chromosome default width
  this._chromosomes.height = 20; //Chromosome default height
  this._chromosomes.layer = 1; //Chromosome layer
  this._chromosomes.list = []; //Chromosomes list
  this._chromosomes.index = {}; //Chromosomes index
  this._chromosomes.names = {}; //Chromosome names
  this._chromosomes.max = 0; //Chromosome max length
  this._chromosomes.num = 0; //Number of chromosomes
  this._chromosomes.color = jviz.colors.blue2.hex; //Chromosome color
  this._chromosomes.opacity = 0.6; //Chromosome opacity
  this._chromosomes.resized = false; //Chromosome data is resized

  //Chromosome radius
  this._chromosomes.radius = {};
  this._chromosomes.radius.portrait = 6; //Chromosome radius for portrait
  this._chromosomes.radius.landscape = 10; //Chromosome radius for landscape

  //Chromosome name
  this._chromosomes.name = {};
  this._chromosomes.name.list = []; //List of chromosomes names
  this._chromosomes.name.visible = true; //Chromosome name is visible
  this._chromosomes.name.margin = 7; //Chromosome name margin

  //Chromosome name text
  this._chromosomes.name.text = {};
  this._chromosomes.name.text.font = jviz.font.default; //Chromosome name text font
  this._chromosomes.name.text.size = '12px'; //Chromosome name text size
  this._chromosomes.name.text.align = 'center'; //Chromosome name text align

  //Centromere
  this._chromosomes.centromere = {};
  this._chromosomes.centromere.list = []; //List of centromere positions
  this._chromosomes.centromere.opacity = 0.9; //Centromere opacity

  //Check the features object
  if(typeof opt.features === 'undefined'){ opt.features = {}; }

  //Features object
  this._features = {};
  this._features.list = []; //List of features
  this._features.chromosomes = {}; //List of features by chromosomes
  this._features.layer = 2; //Features layer
  this._features.color = (typeof opt.features.color === 'string') ? opt.features.color : jviz.colors.red.hex; //Features default color
  this._features.opacity = 0.8; //Features opacity
  this._features.resized = false; //Features data is resized

  //Features counter
  this._features.counter = {};
  this._features.counter.visible = (typeof opt.features.count === 'boolean') ? opt.features.count : true; //Features counter is visible

  //Features triangle
  this._features.triangle = {};
  this._features.triangle.width = 6; //Features triangle width
  this._features.triangle.height = 4; //Features triangle height
  this._features.triangle.margin = 1; //Features triangle mrgin
  this._features.triangle.opacity = 0.6; //Features triangle opacity
  this._features.triangle.visible = (typeof opt.features.triangle === 'boolean') ? opt.features.triangle : true; //Triangle visible

  //Features label
  this._features.label = {};
  this._features.label.opacity = 1.0; //Features label opacity
  this._features.label.visible = (typeof opt.features.label === 'boolean') ? opt.features.label : true; //Label visible

  //Features label rectangle
  this._features.label.rectangle = {};
  this._features.label.rectangle.width = 0; //Features label rectangle width
  this._features.label.rectangle.height = 0; //Features label rectangle height
  this._features.label.rectangle.radius = 5; //Features label rectangle radius

  //Chromosomes hover
  this._hover = {};
  this._hover.index = -1; //Hover chromosome index
  this._hover.margin = { top: 10, bottom: 20, left: 10, right: 10 }; //Hover margin
  this._hover.color = jviz.colors.white.hex; //Hover background color
  this._hover.opacity = 1.0; //Hover background color opacity
  this._hover.radius = 10; //Hover radius
  this._hover.layer = 0; //Hover layer

  //Check for undefined orientation
  if(typeof opt.orientation !== 'string'){ opt.orientation = 'portrait'; }

  //Build the karyotype element
  this.build();

  //Register the events
  this.events();

  //Parse the orientation
  this.orientation(opt.orientation);

  //Return this
  return this;
};
<|endoftext|>


<commit_before>import { getIsFetchingBuildConfigs } from '../reducers/build_config';
import { isFetchingOneArticle } from '../reducers/articles';
import axios from 'axios';

const requestBuildConfigs = (filter) => ({
	type: 'ALL_BUILD_CONFIG_REQUEST',
	filter,
});

const receiveBuildConfigs = (filter, response) => ({
	type: 'ALL_BUILD_CONFIG_RESPONSE',
	filter,
	response,
});

const apiFail = (type, error) => {
	let errorDescription = 'Network Connection Failure.';
	if (error.response) {
		errorDescription = error.response.status;
	}
	console.log('API ERROR OCCURS: ' + type);
	console.log(errorDescription);
	return ({
		type: type,
		error: errorDescription
	})
};

export const fetchBuildConfigsAction = (filter) => (dispatch, getState) => {
	if (getIsFetchingBuildConfigs(getState(), filter)) {
		return Promise.resolve();
	}

	dispatch(requestBuildConfigs(filter));
	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs').then(response => {
		dispatch(receiveBuildConfigs(filter, response.data));
	}).catch(error => {
		dispatch(apiFail('ALL_BUILD_CONFIG_FAILURE', error));
	});
};

export const saveBuildConfigAction = (buildConfig, redirectTo) => (dispatch, getState) => {
	return axios.post(getState().apiConfig.apiUrl + '/buildconfigs', buildConfig)
		.then(() => {
			redirectTo();
		}).catch((error) => {
			dispatch(apiFail('SAVE_BUILD_CONFIG_FAILURE', error));
		});
};

export const updateBuildConfigAction = (env, buildConfig, redirectTo) => (dispatch, getState) => {
	return axios.post(getState().apiConfig.apiUrl + '/buildconfigs/' + env, buildConfig)
		.then(() => {
			redirectTo();
		}).catch((error) => {
			dispatch(apiFail('UPDATE_BUILD_CONFIG_FAILURE', error));
		});
};

const getBuildConfigRequest = (env) => ({
	type: 'ONE_BUILD_CONFIG_REQUEST',
	env
});

const getBuildConfigResponse = (env, response) => ({
	type: 'ONE_BUILD_CONFIG_RESPONSE',
	env,
	response,
});

export const getBuildConfigAction = (env) => (dispatch, getState) => {
	dispatch(getBuildConfigRequest(env));

	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		dispatch(getBuildConfigResponse(env, response.data));
	}).catch(error => {
		dispatch(apiFail('ONE_BUILD_CONFIG_FAILURE', error));
	});
};

const loadBuildConfigForCloneResponse = (response) => ({
	type: 'LOAD_BUILD_CONFIG_FOR_CLONE_RESPONSE',
	response
});

export const loadBuildConfigForCloneAction = (env) => (dispatch, getState) => {
	dispatch(getBuildConfigRequest(env));

	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		dispatch(loadBuildConfigForCloneResponse(response.data));
	}).catch(error => {
		dispatch(apiFail('LOAD_BUILD_CONFIG_FOR_CLONE_FAILURE', error));
	});
};

const loadBuildConfigForEditResponse = (response) => ({
	type: 'LOAD_BUILD_CONFIG_FOR_EDIT_RESPONSE',
	response
});

export const loadBuildConfigForEditAction = (env) => (dispatch, getState) => {
	dispatch(getBuildConfigRequest(env));

	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		dispatch(loadBuildConfigForEditResponse(response.data));
	}).catch(error => {
		dispatch(apiFail('LOAD_BUILD_CONFIG_FOR_EDIT_FAILURE', error));
	});
};

const deleteBuildConfigResponse = (env) => ({
	type: 'DELETE_BUILD_CONFIG_RESPONSE',
	env
});

export const deleteBuildConfigAction = (env, postAction) => (dispatch, getState) => {
	return axios.delete(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		console.log(response);
		dispatch(deleteBuildConfigResponse(env));
		postAction('all');
	}).catch(error => {
		dispatch(apiFail('DELETE_BUILD_CONFIG_FAILURE', error));
	});
};

const attributeAdded = (result, type) => ({
	type,
	attributes: result
});

export const addAttributeAction = (name, value) => (dispatch) => {
	dispatch(attributeAdded({attributes: {[name]: value}}, 'ADD_CUSTOM_ATTRIBUTE_RESPONSE'))
};

export const addDefaultAttributeAction = (name, value) => (dispatch) => {
	dispatch(attributeAdded({[name]: value}, 'ADD_DEFAULT_ATTRIBUTE_RESPONSE'))
};

const attributeRemoved = (name) => ({
	type: 'REMOVE_ATTRIBUTE_RESPONSE',
	name
});

export const removeAttributeAction = (name) => (dispatch) => {
	dispatch(attributeRemoved(name));
};

const attributeEmpty = () => ({
	type: 'EMPTY_BUILD_CONFIG'
});

export const clearBuildConfigNewAction = () => (dispatch) => {
	dispatch(attributeEmpty());
};

const setErrorMessage = (errorMessage) => ({
	type: 'NEW_VALIDATION_ERROR',
	errorMessage
});

export const setErrorMessageAction = (errorMessage) => (dispatch) => {
	dispatch(setErrorMessage(errorMessage));
};

const emptyErrorMessage = () => ({
	type: 'EMPTY_ERROR_MESSAGES'
});

export const emptyErrorMessagesAction = () => (dispatch) => {
	dispatch(emptyErrorMessage())
};

const setGeneralErrorMessage = (errorMessage) => ({
	type: 'GENERAL_ERROR_MESSAGE',
	errorMessage
});

export const setGeneralErrorMessageAction = (errorMessage) => (dispatch) => {
	dispatch(setGeneralErrorMessage(errorMessage));
};

const emptyGeneralErrorMessage = () => ({
	type: 'EMPTY_GENERAL_ERROR_MESSAGES'
});

export const emptyGeneralErrorMessagesAction = () => (dispatch) => {
	dispatch(emptyGeneralErrorMessage())
};

export const emptyApiErrors = () => ({
	type: 'EMPTY_API_ERRORS'
});

export const emptyApiErrorsAction = () => (dispatch) => {
	dispatch(emptyApiErrors())
};

const pageTitle = (title) => ({
	type: 'SET_CURRENT_PAGE_TITLE',
	title
});

export const setCurrentPageTitle = (title) => (dispatch) => {
	dispatch(pageTitle(title))
};

const requestOneArticle = () => ({
	type: 'IS_FETCHING_ARTICLE',
	status: true
});

const receiveOneArticle = (oneArticle) => ({
	type: 'ONE_ARTICLE',
	title: oneArticle.title,
	content: oneArticle.content
});

export const fetchArticlesAction = (filter) => (dispatch, getState) => {
	if (isFetchingOneArticle(getState(), filter)) {
		return Promise.resolve();
	}

	dispatch(requestOneArticle());
	return axios.get('https://martinhelp-developer-edition.eu11.force.com/services/apexrest/api/article/test-art3').then(response => {
		dispatch(receiveOneArticle(response.data));
	}).catch(error => {
		dispatch(apiFail('ONE_ARTICLE_FAILURE', error));
	});
};
<commit_msg>article rest endpoint update<commit_after>import { getIsFetchingBuildConfigs } from '../reducers/build_config';
import { isFetchingOneArticle } from '../reducers/articles';
import axios from 'axios';

const requestBuildConfigs = (filter) => ({
	type: 'ALL_BUILD_CONFIG_REQUEST',
	filter,
});

const receiveBuildConfigs = (filter, response) => ({
	type: 'ALL_BUILD_CONFIG_RESPONSE',
	filter,
	response,
});

const apiFail = (type, error) => {
	let errorDescription = 'Network Connection Failure.';
	if (error.response) {
		errorDescription = error.response.status;
	}
	console.log('API ERROR OCCURS: ' + type);
	console.log(errorDescription);
	return ({
		type: type,
		error: errorDescription
	})
};

export const fetchBuildConfigsAction = (filter) => (dispatch, getState) => {
	if (getIsFetchingBuildConfigs(getState(), filter)) {
		return Promise.resolve();
	}

	dispatch(requestBuildConfigs(filter));
	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs').then(response => {
		dispatch(receiveBuildConfigs(filter, response.data));
	}).catch(error => {
		dispatch(apiFail('ALL_BUILD_CONFIG_FAILURE', error));
	});
};

export const saveBuildConfigAction = (buildConfig, redirectTo) => (dispatch, getState) => {
	return axios.post(getState().apiConfig.apiUrl + '/buildconfigs', buildConfig)
		.then(() => {
			redirectTo();
		}).catch((error) => {
			dispatch(apiFail('SAVE_BUILD_CONFIG_FAILURE', error));
		});
};

export const updateBuildConfigAction = (env, buildConfig, redirectTo) => (dispatch, getState) => {
	return axios.post(getState().apiConfig.apiUrl + '/buildconfigs/' + env, buildConfig)
		.then(() => {
			redirectTo();
		}).catch((error) => {
			dispatch(apiFail('UPDATE_BUILD_CONFIG_FAILURE', error));
		});
};

const getBuildConfigRequest = (env) => ({
	type: 'ONE_BUILD_CONFIG_REQUEST',
	env
});

const getBuildConfigResponse = (env, response) => ({
	type: 'ONE_BUILD_CONFIG_RESPONSE',
	env,
	response,
});

export const getBuildConfigAction = (env) => (dispatch, getState) => {
	dispatch(getBuildConfigRequest(env));

	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		dispatch(getBuildConfigResponse(env, response.data));
	}).catch(error => {
		dispatch(apiFail('ONE_BUILD_CONFIG_FAILURE', error));
	});
};

const loadBuildConfigForCloneResponse = (response) => ({
	type: 'LOAD_BUILD_CONFIG_FOR_CLONE_RESPONSE',
	response
});

export const loadBuildConfigForCloneAction = (env) => (dispatch, getState) => {
	dispatch(getBuildConfigRequest(env));

	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		dispatch(loadBuildConfigForCloneResponse(response.data));
	}).catch(error => {
		dispatch(apiFail('LOAD_BUILD_CONFIG_FOR_CLONE_FAILURE', error));
	});
};

const loadBuildConfigForEditResponse = (response) => ({
	type: 'LOAD_BUILD_CONFIG_FOR_EDIT_RESPONSE',
	response
});

export const loadBuildConfigForEditAction = (env) => (dispatch, getState) => {
	dispatch(getBuildConfigRequest(env));

	return axios.get(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		dispatch(loadBuildConfigForEditResponse(response.data));
	}).catch(error => {
		dispatch(apiFail('LOAD_BUILD_CONFIG_FOR_EDIT_FAILURE', error));
	});
};

const deleteBuildConfigResponse = (env) => ({
	type: 'DELETE_BUILD_CONFIG_RESPONSE',
	env
});

export const deleteBuildConfigAction = (env, postAction) => (dispatch, getState) => {
	return axios.delete(getState().apiConfig.apiUrl + '/buildconfigs/' + env).then(response => {
		console.log(response);
		dispatch(deleteBuildConfigResponse(env));
		postAction('all');
	}).catch(error => {
		dispatch(apiFail('DELETE_BUILD_CONFIG_FAILURE', error));
	});
};

const attributeAdded = (result, type) => ({
	type,
	attributes: result
});

export const addAttributeAction = (name, value) => (dispatch) => {
	dispatch(attributeAdded({attributes: {[name]: value}}, 'ADD_CUSTOM_ATTRIBUTE_RESPONSE'))
};

export const addDefaultAttributeAction = (name, value) => (dispatch) => {
	dispatch(attributeAdded({[name]: value}, 'ADD_DEFAULT_ATTRIBUTE_RESPONSE'))
};

const attributeRemoved = (name) => ({
	type: 'REMOVE_ATTRIBUTE_RESPONSE',
	name
});

export const removeAttributeAction = (name) => (dispatch) => {
	dispatch(attributeRemoved(name));
};

const attributeEmpty = () => ({
	type: 'EMPTY_BUILD_CONFIG'
});

export const clearBuildConfigNewAction = () => (dispatch) => {
	dispatch(attributeEmpty());
};

const setErrorMessage = (errorMessage) => ({
	type: 'NEW_VALIDATION_ERROR',
	errorMessage
});

export const setErrorMessageAction = (errorMessage) => (dispatch) => {
	dispatch(setErrorMessage(errorMessage));
};

const emptyErrorMessage = () => ({
	type: 'EMPTY_ERROR_MESSAGES'
});

export const emptyErrorMessagesAction = () => (dispatch) => {
	dispatch(emptyErrorMessage())
};

const setGeneralErrorMessage = (errorMessage) => ({
	type: 'GENERAL_ERROR_MESSAGE',
	errorMessage
});

export const setGeneralErrorMessageAction = (errorMessage) => (dispatch) => {
	dispatch(setGeneralErrorMessage(errorMessage));
};

const emptyGeneralErrorMessage = () => ({
	type: 'EMPTY_GENERAL_ERROR_MESSAGES'
});

export const emptyGeneralErrorMessagesAction = () => (dispatch) => {
	dispatch(emptyGeneralErrorMessage())
};

export const emptyApiErrors = () => ({
	type: 'EMPTY_API_ERRORS'
});

export const emptyApiErrorsAction = () => (dispatch) => {
	dispatch(emptyApiErrors())
};

const pageTitle = (title) => ({
	type: 'SET_CURRENT_PAGE_TITLE',
	title
});

export const setCurrentPageTitle = (title) => (dispatch) => {
	dispatch(pageTitle(title))
};

const requestOneArticle = () => ({
	type: 'IS_FETCHING_ARTICLE',
	status: true
});

const receiveOneArticle = (oneArticle) => ({
	type: 'ONE_ARTICLE',
	title: oneArticle.title,
	content: oneArticle.content
});

export const fetchArticlesAction = (filter) => (dispatch, getState) => {
	if (isFetchingOneArticle(getState(), filter)) {
		return Promise.resolve();
	}

	dispatch(requestOneArticle());
	return axios.get('https://martinhelp-developer-edition.eu11.force.com/services/apexrest/api/article/one/test-art3').then(response => {
		dispatch(receiveOneArticle(response.data));
	}).catch(error => {
		dispatch(apiFail('ONE_ARTICLE_FAILURE', error));
	});
};
<|endoftext|>


<commit_before>/* global Backbone, OCA */

/**
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function(OCA, Backbone) {
	'use strict';

	OCA.SpreedMe = OCA.SpreedMe || {};
	OCA.SpreedMe.Models = OCA.SpreedMe.Models || {};

	/**
	 * Model for rooms.
	 *
	 * Room can be used as the model of a RoomCollection or as a standalone
	 * model. When used as a standalone model the token must be provided in the
	 * constructor options.
	 *
	 * Besides fetching the data from the server it supports renaming the room
	 * by calling "save('displayName', nameToSet, options)"; in this case the
	 * options must contain, at least, "patch: true" (it may contain other
	 * options like a success callback too if needed).
	 */
	var Room = Backbone.Model.extend({
		defaults: {
			name: '',
			token: '',
			count: 0,
			active: false,
			lastPing: 0
		},
		url: function() {
			return OC.linkToOCS('apps/spreed/api/v1/room', 2) + this.get('token');
		},
		parse: function(result) {
			// When the model is created by a RoomCollection "Room.parse" will
			// be called with the result already parsed by
			// "RoomCollection.parse", so the given result is already the
			// attributes hash to be set on the model.
			return (result.ocs === undefined)? result : result.ocs.data;
		},
		sync: function(method, model, options) {
			// When saving a model "Backbone.Model.save" calls "sync" with an
			// "update" method, which by default sends a "PUT" request that
			// contains all the attributes of the model. In order to send only
			// the attributes to be saved "patch: true" must be set in the
			// options. However, this causes a "PATCH" request instead of a
			// "PUT" request to be sent, so the "method" must be changed from
			// "patch" to "update", as the backend expects a "PUT" request.
			// Moreover, the endpoint to rename a room expects the name to be
			// provided in a "roomName" attribute instead of a "displayName"
			// attribute, so that has to be changed too.
			if (method === 'patch' && options.attrs.displayName) {
				method = 'update';

				options.attrs.roomName = options.attrs.displayName;
				delete options.attrs.displayName;
			}

			return Backbone.Model.prototype.sync.call(this, method, model, options);
		}
	});

	OCA.SpreedMe.Models.Room = Room;

})(OCA, Backbone);
<commit_msg>Fix room rename.<commit_after>/* global Backbone, OCA */

/**
 * @author Christoph Wurst <christoph@winzerhof-wurst.at>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function(OCA, Backbone) {
	'use strict';

	OCA.SpreedMe = OCA.SpreedMe || {};
	OCA.SpreedMe.Models = OCA.SpreedMe.Models || {};

	/**
	 * Model for rooms.
	 *
	 * Room can be used as the model of a RoomCollection or as a standalone
	 * model. When used as a standalone model the token must be provided in the
	 * constructor options.
	 *
	 * Besides fetching the data from the server it supports renaming the room
	 * by calling "save('displayName', nameToSet, options)"; in this case the
	 * options must contain, at least, "patch: true" (it may contain other
	 * options like a success callback too if needed).
	 */
	var Room = Backbone.Model.extend({
		defaults: {
			name: '',
			token: '',
			count: 0,
			active: false,
			lastPing: 0
		},
		url: function() {
			return OC.linkToOCS('apps/spreed/api/v1/room', 2) + this.get('token');
		},
		parse: function(result) {
			// When the model is created by a RoomCollection "Room.parse" will
			// be called with the result already parsed by
			// "RoomCollection.parse", so the given result is already the
			// attributes hash to be set on the model.
			return (result.ocs === undefined)? result : result.ocs.data;
		},
		sync: function(method, model, options) {
			// When saving a model "Backbone.Model.save" calls "sync" with an
			// "update" method, which by default sends a "PUT" request that
			// contains all the attributes of the model. In order to send only
			// the attributes to be saved "patch: true" must be set in the
			// options. However, this causes a "PATCH" request instead of a
			// "PUT" request to be sent, so the "method" must be changed from
			// "patch" to "update", as the backend expects a "PUT" request.
			// Moreover, the endpoint to rename a room expects the name to be
			// provided in a "roomName" attribute instead of a "name"
			// attribute, so that has to be changed too.
			if (method === 'patch' && options.attrs.name) {
				method = 'update';

				options.attrs.roomName = options.attrs.name;
				delete options.attrs.name;
			}

			return Backbone.Model.prototype.sync.call(this, method, model, options);
		}
	});

	OCA.SpreedMe.Models.Room = Room;

})(OCA, Backbone);
<|endoftext|>


<commit_before>ol.control.Sidebar = function (settings) {

    var defaults = {
        element: null,
        position: 'left'
    }, i, child;

    this._options = Object.assign({}, defaults, settings);

    ol.control.Control.call(this, {
        element: document.getElementById(this._options.element),
        target: this._options.target
    });
}

ol.inherits(ol.control.Sidebar, ol.control.Control);

ol.control.Sidebar.prototype.setMap = function(map) {
    var _this = this;

    // Wire up listeners etc. and store reference to new map
    //ol.control.Control.prototype.setMap.call(this, map);

    // Attach .sidebar-left/right class
    this.element.classList.add('sidebar-' + this._options.position);

    // Find sidebar > div.sidebar-content
    for (i = this.element.children.length - 1; i >= 0; i--) {
        child = this.element.children[i];
        if (child.tagName === 'DIV' &&
            child.classList.contains('sidebar-content')) {
            this._container = child;
        }
    }

    // Find sidebar ul.sidebar-tabs > li, sidebar .sidebar-tabs > ul > li
    this._tabitems = this.element.querySelectorAll('ul.sidebar-tabs > li, .sidebar-tabs > ul > li');
    for (i = this._tabitems.length - 1; i >= 0; i--) {
        this._tabitems[i]._sidebar = this;
        child = this._tabitems[i];
        var sub = child.querySelector('a');
        if (sub.hasAttribute('href') && sub.getAttribute('href').slice(0,1) == '#') {
            sub.onclick = function(e) {
                e = e || window.event;
                e.preventDefault();
                if (this.parentNode.classList.contains('active')) {
                    _this.close();
                } else if (!this.parentNode.classList.contains('disabled')) {
                    _this.open(this.hash.slice(1));
                }
            };
        }
    }

    // Find sidebar > div.sidebar-content > div.sidebar-pane
    this._panes = [];
    this._closeButtons = [];
    for (i = this._container.children.length - 1; i >= 0; i--) {
        child = this._container.children[i];
        if (child.tagName == 'DIV' &&
            child.classList.contains('sidebar-pane')) {
            this._panes.push(child);
            var closeButtons = child.querySelectorAll('.sidebar-close');
            for (var j = 0, len = closeButtons.length; j < len; j++) {
                this._closeButtons.push(closeButtons[j]);
                closeButtons[j].onclick = function(e) {
                    e = e || window.event;
                    e.preventDefault();
                    _this.close();
                };
            }
        }
    }
};

ol.control.Sidebar.prototype.open = function(id) {
    var i, child;

    // hide old active contents and show new content
    for (i = this._panes.length - 1; i >= 0; i--) {
        child = this._panes[i];
        if (child.id == id) {
            child.classList.add('active');
        } else if (child.classList.contains('active')) {
            child.classList.remove('active');
        }
    }
    // remove old active highlights and set new highlight
    for (i = this._tabitems.length - 1; i >= 0; i--) {
        child = this._tabitems[i];
        if (child.querySelector('a').hash == '#' + id) {
            child.classList.add('active');
        } else if (child.classList.contains('active')) {
            child.classList.remove('active');
        }
    }
    // open sidebar (if necessary)
    if (this.element.classList.contains('collapsed')) {
        this.element.classList.remove('collapsed');
    }
    return this;
};

ol.control.Sidebar.prototype.close = function() {
    // remove old active highlights
    for (var i = this._tabitems.length - 1; i >= 0; i--) {
        var child = this._tabitems[i];
        if (child.classList.contains('active')) {
            child.classList.remove('active');
        }
    }
    // close sidebar
    if (!this.element.classList.contains('collapsed')) {
        this.element.classList.add('collapsed');
    }
    return this;
};<commit_msg>Fix lint issues<commit_after>ol.control.Sidebar = function (settings) {

    var defaults = {
        element: null,
        position: 'left'
    }, i, child;

    this._options = Object.assign({}, defaults, settings);

    ol.control.Control.call(this, {
        element: document.getElementById(this._options.element),
        target: this._options.target
    });
};

ol.inherits(ol.control.Sidebar, ol.control.Control);

ol.control.Sidebar.prototype.setMap = function(map) {
    var _this = this;

    // Wire up listeners etc. and store reference to new map
    //ol.control.Control.prototype.setMap.call(this, map);

    // Attach .sidebar-left/right class
    this.element.classList.add('sidebar-' + this._options.position);

    // Find sidebar > div.sidebar-content
    for (i = this.element.children.length - 1; i >= 0; i--) {
        child = this.element.children[i];
        if (child.tagName === 'DIV' &&
            child.classList.contains('sidebar-content')) {
            this._container = child;
        }
    }

    function tabClick(e) {
        e = e || window.event;
        e.preventDefault();
        if (this.parentNode.classList.contains('active')) {
            _this.close();
        } else if (!this.parentNode.classList.contains('disabled')) {
            _this.open(this.hash.slice(1));
        }
    }

    function closeClick(e) {
        e = e || window.event;
        e.preventDefault();
        _this.close();
    }

    // Find sidebar ul.sidebar-tabs > li, sidebar .sidebar-tabs > ul > li
    this._tabitems = this.element.querySelectorAll('ul.sidebar-tabs > li, .sidebar-tabs > ul > li');
    for (i = this._tabitems.length - 1; i >= 0; i--) {
        this._tabitems[i]._sidebar = this;
        child = this._tabitems[i];
        var sub = child.querySelector('a');
        if (sub.hasAttribute('href') && sub.getAttribute('href').slice(0,1) == '#') {
            sub.onclick = tabClick;
        }
    }

    // Find sidebar > div.sidebar-content > div.sidebar-pane
    this._panes = [];
    this._closeButtons = [];
    for (i = this._container.children.length - 1; i >= 0; i--) {
        child = this._container.children[i];
        if (child.tagName == 'DIV' &&
            child.classList.contains('sidebar-pane')) {
            this._panes.push(child);
            var closeButtons = child.querySelectorAll('.sidebar-close');
            for (var j = 0, len = closeButtons.length; j < len; j++) {
                this._closeButtons.push(closeButtons[j]);
                closeButtons[j].onclick = closeClick;
            }
        }
    }
};

ol.control.Sidebar.prototype.open = function(id) {
    var i, child;

    // hide old active contents and show new content
    for (i = this._panes.length - 1; i >= 0; i--) {
        child = this._panes[i];
        if (child.id == id) {
            child.classList.add('active');
        } else if (child.classList.contains('active')) {
            child.classList.remove('active');
        }
    }
    // remove old active highlights and set new highlight
    for (i = this._tabitems.length - 1; i >= 0; i--) {
        child = this._tabitems[i];
        if (child.querySelector('a').hash == '#' + id) {
            child.classList.add('active');
        } else if (child.classList.contains('active')) {
            child.classList.remove('active');
        }
    }
    // open sidebar (if necessary)
    if (this.element.classList.contains('collapsed')) {
        this.element.classList.remove('collapsed');
    }
    return this;
};

ol.control.Sidebar.prototype.close = function() {
    // remove old active highlights
    for (var i = this._tabitems.length - 1; i >= 0; i--) {
        var child = this._tabitems[i];
        if (child.classList.contains('active')) {
            child.classList.remove('active');
        }
    }
    // close sidebar
    if (!this.element.classList.contains('collapsed')) {
        this.element.classList.add('collapsed');
    }
    return this;
};<|endoftext|>


<commit_before>const $$ = function(aObj) {
	const _r = {
		/**
		 * <odoc>
		 * <key>$$(aObject).get(aPath) : Object</key>
		 * Given aObject it will try to parse the aPath a retrive the corresponding object under that path. Example:\
		 * \
		 * var a = { a : 1, b : { c: 2, d: [0, 1] } };\
		 * \
		 * print($$(a).get("b.c")); // 2\
		 * sprint($$(a).get("b.d")); // [0, 1]\
		 * print($$(a).get("b.d[0]")); // 0\
		 * \
		 * </odoc>
		 */
		get: (aPath) => {
            if (!$$(aObj).isObject()) return void 0;

			aPath = aPath.replace(/\[(\w+)\]/g, '.$1');
			aPath = aPath.replace(/^\./, '');

			var a = aPath.split('.');
			for (var i = 0, n = a.length; i < n; ++i) {
				var k = a[i];
				if (k in aObj) {
					aObj = aObj[k];
				} else {
					return;
				}
			}
            return aObj;
		},
		/**
		 * <odoc>
		 * <key>$$(aObject).set(aPath, aNewValue) : Object</key>
		 * Given aObject it will try to parse the aPath a set the corresponding object under that path to aNewValue. Example:\
		 * \
		 * var a = { a : 1, b : { c: 2, d: [0, 1] } };\
		 * \
		 * sprint($$(a).set("b.c", 123); // { a : 1, b : { c: 123, d: [0, 1] } }\
		 * \
		 * </odoc>
		 */
		set: (aPath, aValue) => {
			if (!$$(aObj).isObject()) return void 0;
			var orig = aObj;

			aPath = aPath.replace(/\[(\w+)\]/g, '.$1');
			aPath = aPath.replace(/^\./, '');

			var a = aPath.split('.');
			var prev, prevK;
			for (var i = 0, n = a.length; i < n; ++i) {
				var k = a[i];
				prev = aObj;
				prevK = k;
				if (k in aObj) {
					aObj = aObj[k];
				} else {
					aObj[k] = {};
					aObj = aObj[k];
				}
			}
			prev[prevK] = aValue;
			return orig;
        },
        isDef: () => { return (!(typeof aObj == 'undefined')) ? true : false; },
        isUnDef: () => { return (typeof aObj == 'undefined') ? true : false; },
        isArray: () => { return Array.isArray(aObj); },
        isMap: () => { return (Object.prototype.toString.call(aObj) == "[object Object]"); },
        isObject: () => { var type = typeof aObj; return type === 'function' || type === 'object' && !!aObj; },
        isFunction: () => { return typeof aObj == 'function' || false; },
        isString: () => { return typeof aObj == 'string' || false; },
        isNumber: () => { return !isNaN(parseFloat(aObj)) && isFinite(aObj); },
        isDate: () => { return (null != aObj) && !isNaN(aObj) && ("undefined" !== typeof aObj.getDate); }
	};
	return _r;
};

const _$ = function(aValue, aPrefixMessage) {
    var defined;
    if ($$(aPrefixMessage).isDef()) aPrefixMessage += " "; else aPrefixMessage = "";
    if ($$(aValue).isDef()) defined = true; else defined = false;

    const __r = {
		// Defaults
        default : (aVal) => {
            if (!defined) return aVal; else return aValue;
        },
        $_ : (aMessage) => {
			if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "not available";
			if (!defined) throw aMessage;
			return aValue;
		},

		// Type check
        isNumber: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a number";
            if (defined && !$$(aValue).isNumber()) throw aMessage;
            return __r;
        },
        isString: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a string";
            if (defined && !$$(aValue).isString()) throw aMessage;
            return __r;
        },
        isBoolean: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not boolean";
            if (defined && (typeof aValue !== "boolean")) throw aMessage;
            return __r;
        },
        isArray: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an array";
            if (defined && !$$(aValue).isArray()) throw aMessage;
            return __r;
        },
        isMap: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a map";
            if (defined && !$$(aValue).isMap()) throw aMessage;
            return __r;
        },
        isObject: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an object";
            if (defined && !$$(aValue).isObject()) throw aMessage;
            return __r;
        },
		isJavaObject: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a java object";
            if (defined && !isJavaObject(aValue)) throw aMessage;
            return __r;
		},
		isInstanceOf: (aClass, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an instance of " + aClass;
            if (defined && !(aValue instanceof aClass)) throw aMessage;
            return __r;
		},

		// Generic validations
        check: (aFunction, aMessage) => {
			if (!$$(aFunction).isFunction() && !$$(aFunction).isString()) throw "please provide a function to check";
            var res = ($$(aValue).isFunction() ? aFunction(aValue) : (new Function('v', 'return ' + aFunction))(aValue));
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not ok";
            if (defined && !res) throw aMessage;
            return __r;
        },
        expr: (aEval, aMessage) => {
			if (!$$(aEval).isString()) throw "please provide an expression";
            var res = af.eval(templify(aEval, { v: aValue }));
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not ok";
            if (defined && !res) throw aMessage;
            return __r;
		},
		equals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is equals to " + aVal;
            if (defined && aValue == aVal) throw aMessage;
            return __r;
        }        ,
        notEquals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not equals to " + aVal;
            if (defined && aValue != aVal) throw aMessage;
            return __r;
		},
		anyOf: (aVals, aMessage) => {
			if (!$$(aVals).isArray()) throw "please provide an array of values";
			if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "has a value not in " + JSON.stringify(aVals);
			if (defined && $$(aValue).isArray()) {
				aValue.forEach((v) => {
					if (aVals.indexOf(v) < 0) throw aMessage;
				});
            }
            return __r;
		},
		oneOf: (aVals, aMessage) => {
			if (!$$(aVals).isArray()) throw "please provide an array of values";
			if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not one of " + JSON.stringify(aVals);
            if (defined && !$$(aValue).isArray() && aVals.indexOf(aValue) < 0) throw aMessage;
            return __r;
		},

		// Numeric validations
        between: (aValA, aValB, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not between " + aValA + " and " + aValB;
            if (defined && (aValue < aValB && aValue > aValA)) throw aMessage;
        },
        betweenEquals: (aValA, aValB, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not between " + aValA + " and " + aValB;
            if (defined && (aValue <= aValB && aValue >= aValA)) throw aMessage;
        },
        less: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is less than " + aVal;
            if (defined && aValue > aVal) throw aMessage;
            return __r;
        },
        lessEquals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is less or equals than " + aVal;
            if (defined && aValue >= aVal) throw aMessage;
            return __r;
        },
        greater: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is greater than " + aVal;
            if (defined && aValue < aVal) throw aMessage;
            return __r;
        },
        greaterEquals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is greater or equals than " + aVal;
            if (defined && aValue <= aVal) throw aMessage;
            return __r;
        },

		// String validations
        notEmpty: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is empty";
            if (defined && String(aValue) == "") throw aMessage;
            return __r;
        },
        empty: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not empty";
            if (defined && String(aValue) != "") throw aMessage;
            return __r;
        },
        contains: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if contains";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't contain " + aVal;
            if (defined && String(aValue).indexOf(aVal) < 0) throw aMessage;
            return __r;
        },
        notContains: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if not contains";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "contains " + aVal;
            if (defined && String(aValue).indexOf(aVal) >= 0) throw aMessage;
            return __r;
        },
        starts: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it starts with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't start with '" + aVal + "'";
            if (defined && !(aValue.startsWith(aValu))) throw aMessage;
            return __r;
        },
        ends: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it ends with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't end with '" + aVal + "'";
            if (defined && !(aValue.endsWith(aVal))) throw aMessage;
            return __r;
        },
        notStarts: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it not starts with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "starts with '" + aVal + "'";
            if (defined && (aValue.startsWith(aValu))) throw aMessage;
            return __r;
        },
        notEnds: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it not ends with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "ends with '" + aVal + "'";
            if (defined && (aValue.endsWith(aVal))) throw aMessage;
            return __r;
        },
        regexp: (aRegExp, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't match '" + aRegExp + "'";
            if (!(aRegExp instanceof RegExp)) throw "is not a regular expression (" + aRegExp + ")";
            if (defined && !aRegExp.test(aValue)) throw aMessage;
            return __r;
        },
        javaRegexp: (aRegExp, aMods, aMessage) => {
			if ($$(aRegExp).isUnDef() || !$$(aRegExp).isString()) throw "please provide a regular expression string";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't match '" + aRegExp + "'";
            if (defined && !javaRegExp(aValue).test(aRegExp, aMods)) throw aMessage;
            return __r;
        }
    };
    return __r;
};
<commit_msg>improvements on openafsigil<commit_after>const $$ = function(aObj) {
	const _r = {
		/**
		 * <odoc>
		 * <key>$$(aObject).get(aPath) : Object</key>
		 * Given aObject it will try to parse the aPath a retrive the corresponding object under that path. Example:\
		 * \
		 * var a = { a : 1, b : { c: 2, d: [0, 1] } };\
		 * \
		 * print($$(a).get("b.c")); // 2\
		 * sprint($$(a).get("b.d")); // [0, 1]\
		 * print($$(a).get("b.d[0]")); // 0\
		 * \
		 * </odoc>
		 */
		get: (aPath) => {
            if (!$$(aObj).isObject()) return void 0;

			aPath = aPath.replace(/\[(\w+)\]/g, '.$1');
			aPath = aPath.replace(/^\./, '');

			var a = aPath.split('.');
			for (var i = 0, n = a.length; i < n; ++i) {
				var k = a[i];
				if (k in aObj) {
					aObj = aObj[k];
				} else {
					return;
				}
			}
            return aObj;
		},
		/**
		 * <odoc>
		 * <key>$$(aObject).set(aPath, aNewValue) : Object</key>
		 * Given aObject it will try to parse the aPath a set the corresponding object under that path to aNewValue. Example:\
		 * \
		 * var a = { a : 1, b : { c: 2, d: [0, 1] } };\
		 * \
		 * sprint($$(a).set("b.c", 123); // { a : 1, b : { c: 123, d: [0, 1] } }\
		 * \
		 * </odoc>
		 */
		set: (aPath, aValue) => {
			if (!$$(aObj).isObject()) return void 0;
			var orig = aObj;

			aPath = aPath.replace(/\[(\w+)\]/g, '.$1');
			aPath = aPath.replace(/^\./, '');

			var a = aPath.split('.');
			var prev, prevK;
			for (var i = 0, n = a.length; i < n; ++i) {
				var k = a[i];
				prev = aObj;
				prevK = k;
				if (k in aObj) {
					aObj = aObj[k];
				} else {
					aObj[k] = {};
					aObj = aObj[k];
				}
			}
			prev[prevK] = aValue;
			return orig;
        },
        isDef: () => { return (!(typeof aObj == 'undefined')) ? true : false; },
        isUnDef: () => { return (typeof aObj == 'undefined') ? true : false; },
        isArray: () => { return Array.isArray(aObj); },
        isMap: () => { return (Object.prototype.toString.call(aObj) == "[object Object]"); },
        isObject: () => { var type = typeof aObj; return type === 'function' || type === 'object' && !!aObj; },
        isFunction: () => { return typeof aObj == 'function' || false; },
        isString: () => { return typeof aObj == 'string' || false; },
        isNumber: () => { return !isNaN(parseFloat(aObj)) && isFinite(aObj); },
        isDate: () => { return (null != aObj) && !isNaN(aObj) && ("undefined" !== typeof aObj.getDate); },
        isRegExp: () => { return (aObj instanceof RegExp); }
	};
	return _r;
};

const _$ = function(aValue, aPrefixMessage) {
    var defined;
    if ($$(aPrefixMessage).isDef()) aPrefixMessage += " "; else aPrefixMessage = "";
    if ($$(aValue).isDef()) defined = true; else defined = false;

    const __r = {
		// Defaults
        default : (aVal) => {
            if (!defined) return aVal; else return aValue;
        },
        $_ : (aMessage) => {
			if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "not available";
			if (!defined) throw aMessage;
			return aValue;
		},

		// Type check
        isNumber: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a number";
            if (defined && !$$(aValue).isNumber()) throw aMessage;
            return __r;
        },
        isString: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a string";
            if (defined && !$$(aValue).isString()) throw aMessage;
            return __r;
        },
        isBoolean: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not boolean";
            if (defined && (typeof aValue !== "boolean")) throw aMessage;
            return __r;
        },
        isArray: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an array";
            if (defined && !$$(aValue).isArray()) throw aMessage;
            return __r;
        },
        isMap: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a map";
            if (defined && !$$(aValue).isMap()) throw aMessage;
            return __r;
        },
        isObject: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an object";
            if (defined && !$$(aValue).isObject()) throw aMessage;
            return __r;
        },
        isDate: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a date";
            if (defined && !$$(aValue).isDate()) throw aMessage;
            return __r;
        },
        isRegExp: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a RegExp";
            if (defined && !$$(aValue).isRegExp()) throw aMessage;
            return __r;
        },
        isFunction: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a function";
            if (defined && !$$(aValue).isFunction()) throw aMessage;
            return __r;
        },
		isJavaObject: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not a java object";
            if (defined && !isJavaObject(aValue)) throw aMessage;
            return __r;
		},
		isInstanceOf: (aClass, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not an instance of " + aClass;
            if (defined && !(aValue instanceof aClass)) throw aMessage;
            return __r;
		},

		// Generic validations
        check: (aFunction, aMessage) => {
			if (!$$(aFunction).isFunction() && !$$(aFunction).isString()) throw "please provide a function to check";
            var res = ($$(aValue).isFunction() ? aFunction(aValue) : (new Function('v', 'return ' + aFunction))(aValue));
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not ok";
            if (defined && !res) throw aMessage;
            return __r;
        },
        expr: (aEval, aMessage) => {
			if (!$$(aEval).isString()) throw "please provide an expression";
            var res = af.eval(templify(aEval, { v: aValue }));
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not ok";
            if (defined && !res) throw aMessage;
            return __r;
		},
		equals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is equals to " + aVal;
            if (defined && aValue == aVal) throw aMessage;
            return __r;
        }        ,
        notEquals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not equals to " + aVal;
            if (defined && aValue != aVal) throw aMessage;
            return __r;
		},
		anyOf: (aVals, aMessage) => {
			if (!$$(aVals).isArray()) throw "please provide an array of values";
			if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "has a value not in " + JSON.stringify(aVals);
			if (defined && $$(aValue).isArray()) {
				aValue.forEach((v) => {
					if (aVals.indexOf(v) < 0) throw aMessage;
				});
            }
            return __r;
		},
		oneOf: (aVals, aMessage) => {
			if (!$$(aVals).isArray()) throw "please provide an array of values";
			if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not one of " + JSON.stringify(aVals);
            if (defined && !$$(aValue).isArray() && aVals.indexOf(aValue) < 0) throw aMessage;
            return __r;
		},

		// Numeric validations
        between: (aValA, aValB, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not between " + aValA + " and " + aValB;
            if (defined && (aValue < aValB && aValue > aValA)) throw aMessage;
        },
        betweenEquals: (aValA, aValB, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not between " + aValA + " and " + aValB;
            if (defined && (aValue <= aValB && aValue >= aValA)) throw aMessage;
        },
        less: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is less than " + aVal;
            if (defined && aValue > aVal) throw aMessage;
            return __r;
        },
        lessEquals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is less or equals than " + aVal;
            if (defined && aValue >= aVal) throw aMessage;
            return __r;
        },
        greater: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is greater than " + aVal;
            if (defined && aValue < aVal) throw aMessage;
            return __r;
        },
        greaterEquals: (aVal, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is greater or equals than " + aVal;
            if (defined && aValue <= aVal) throw aMessage;
            return __r;
        },

		// String validations
        notEmpty: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is empty";
            if (defined && String(aValue) == "") throw aMessage;
            return __r;
        },
        empty: (aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "is not empty";
            if (defined && String(aValue) != "") throw aMessage;
            return __r;
        },
        contains: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if contains";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't contain " + aVal;
            if (defined && String(aValue).indexOf(aVal) < 0) throw aMessage;
            return __r;
        },
        notContains: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if not contains";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "contains " + aVal;
            if (defined && String(aValue).indexOf(aVal) >= 0) throw aMessage;
            return __r;
        },
        starts: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it starts with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't start with '" + aVal + "'";
            if (defined && !(aValue.startsWith(aValu))) throw aMessage;
            return __r;
        },
        ends: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it ends with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't end with '" + aVal + "'";
            if (defined && !(aValue.endsWith(aVal))) throw aMessage;
            return __r;
        },
        notStarts: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it not starts with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "starts with '" + aVal + "'";
            if (defined && (aValue.startsWith(aValu))) throw aMessage;
            return __r;
        },
        notEnds: (aVal, aMessage) => {
			if (!$$(aVal).isString()) throw "please provide a string to check if it not ends with";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "ends with '" + aVal + "'";
            if (defined && (aValue.endsWith(aVal))) throw aMessage;
            return __r;
        },
        regexp: (aRegExp, aMessage) => {
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't match '" + aRegExp + "'";
            if (!(aRegExp instanceof RegExp)) throw "is not a regular expression (" + aRegExp + ")";
            if (defined && !aRegExp.test(aValue)) throw aMessage;
            return __r;
        },
        javaRegexp: (aRegExp, aMods, aMessage) => {
			if ($$(aRegExp).isUnDef() || !$$(aRegExp).isString()) throw "please provide a regular expression string";
            if ($$(aMessage).isUnDef()) aMessage = aPrefixMessage + "doesn't match '" + aRegExp + "'";
            if (defined && !javaRegExp(aValue).test(aRegExp, aMods)) throw aMessage;
            return __r;
        }
    };
    return __r;
};
<|endoftext|>