<commit_before>enyo.kind({
	name: "App",
	layoutKind: "FittableRowsLayout",
	components: [
		{kind: "Signals",
		ondeviceready: "deviceready",
		onbackbutton: "handleBackGesture",
		onCoreNaviDragStart: "handleCoreNaviDragStart",
		onCoreNaviDrag: "handleCoreNaviDrag",
		onCoreNaviDragFinish: "handleCoreNaviDragFinish"},
		{kind: "FittableRows",
		style: "border: 5px solid #333; background-color: #777; padding: 10px; color: white; margin: 10px; border-radius: 16px; text-align: right;",
		fit: true,
		components:[
			{kind: "onyx.Toolbar", style: "margin-bottom: 5px;", components:[
				{name: "Result", style: "font-size: 16pt; font-weight: bold;"}
			]},
			{kind: "FittableColumns", style: "margin-bottom: 5px;", components:[
				{kind: "onyx.Toolbar",
					style: "width: 75%; height: 48px; margin-left: 12.5%; margin-right: 5px; text-align: right;",
				fit: true,
				components:[
					{name: "Formula", style: "font-size: 12pt;"}
				]},
				{kind: "onyx.Button", style: "width: 48px; height: 48px; border-radius: 24px;", classes: "onyx-toolbar", content: "<", ontap: "backspaceTapped"}
			]},
			{kind: "FittableRows",
			fit: true,
			defaultKind: enyo.kind({
				kind: "FittableColumns",
				style: "height: 15.5%; margin: 0.5%;",
				defaultKind: enyo.kind({
					kind: "onyx.Button",
					classes: "onyx-toolbar",
					style: "width: 24%; margin: 0.5%; border-radius: 8px; font-size: 24pt; font-weight: bold;",
					ontap: "keyTapped"
				}),
			}),
			components:[
				{components:[
					/**{style: "visibility: hidden;"},*/
    					{content: "Square Root", ontap: "sqrtTapped"},
					{content: "("},
					{content: ")"},
					{content: "C", style: "margin-right: 0;", ontap: "cancelTapped"},
				]},
 {components:[
                                        {content: "ln", ontap: "lnTapped"},
                                        {content: "log", ontap: "logTapped"},
                                        {content: "^2"},
                                        {content: ""},
                                ]},

				{components:[
					{content: "7", classes: "number-button"},
					{content: "8", classes: "number-button"},
					{content: "9", classes: "number-button"},
					{content: "+", style: "margin-right: 0;"},
				]},
				{components:[
					{content: "4", classes: "number-button"},
					{content: "5", classes: "number-button"},
					{content: "6", classes: "number-button"},
					{content: "-", style: "margin-right: 0;"},
				]},
				{components:[
					{content: "1", classes: "number-button"},
					{content: "2", classes: "number-button"},
					{content: "3", classes: "number-button"},
					{content: "*", style: "margin-right: 0;"},
				]},
				{components:[
					{content: "."},
					{content: "0", classes: "number-button"},
					{content: "=", ontap: "equalsTapped"},
					{content: "/", style: "margin-right: 0;"},
				]},
			]},
		]},
		{kind: "CoreNavi", fingerTracking: true}
	],
	//Action Handlers
	keyTapped: function(inSender, inEvent) {
		var formula = this.$.Formula;
		formula.setContent(formula.getContent() + inSender.getContent());

	},
	equalsTapped: function() {
		try {
			var formula = this.$.Formula;
			formula2.setContent(formula.replace('sqrt', 'Math.sqrt'));
			var result = eval(formula2.getContent());
		}
		catch(err) {
			result = "Invalid Input";
		}
		this.$.Result.setContent(result);
	},
	cancelTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("");
	},
	sqrtTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("sqrt(");
	},
	lnTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("ln(");
	},
	logTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("log(");
	},
	backspaceTapped: function() {
		var formula = this.$.Formula;
		formula.setContent(formula.getContent().substr(0, formula.getContent().length - 1));
	},
	//Helper Functions
	handleBackGesture: function(inSender, inEvent) {
		//this.$.AppPanels.setIndex(0);
	},
	handleCoreNaviDragStart: function(inSender, inEvent) {
		/*
		if(enyo.Panels.isScreenNarrow()) {
			this.$.AppPanels.dragstartTransition(inEvent);
		}
		*/
	},
	handleCoreNaviDrag: function(inSender, inEvent) {
		/*
		if(enyo.Panels.isScreenNarrow()) {
			this.$.AppPanels.dragTransition(inEvent);
		}
		*/
	},
	handleCoreNaviDragFinish: function(inSender, inEvent) {
		/*
		if(enyo.Panels.isScreenNarrow()) {
			this.$.AppPanels.dragfinishTransition(inEvent);
		}
		*/
	},
});
<commit_msg>Calculator: Fix sqrt parsing, move calculation into it's own function<commit_after>enyo.kind({
	name: "App",
	layoutKind: "FittableRowsLayout",
	components: [
		{kind: "Signals",
		ondeviceready: "deviceready",
		onbackbutton: "handleBackGesture",
		onCoreNaviDragStart: "handleCoreNaviDragStart",
		onCoreNaviDrag: "handleCoreNaviDrag",
		onCoreNaviDragFinish: "handleCoreNaviDragFinish"},
		{kind: "FittableRows",
		style: "border: 5px solid #333; background-color: #777; padding: 10px; color: white; margin: 10px; border-radius: 16px; text-align: right;",
		fit: true,
		components:[
			{kind: "onyx.Toolbar", style: "margin-bottom: 5px;", components:[
				{name: "Result", style: "font-size: 16pt; font-weight: bold;"}
			]},
			{kind: "FittableColumns", style: "margin-bottom: 5px;", components:[
				{kind: "onyx.Toolbar",
					style: "width: 75%; height: 48px; margin-left: 12.5%; margin-right: 5px; text-align: right;",
				fit: true,
				components:[
					{name: "Formula", style: "font-size: 12pt;"}
				]},
				{kind: "onyx.Button", style: "width: 48px; height: 48px; border-radius: 24px;", classes: "onyx-toolbar", content: "<", ontap: "backspaceTapped"}
			]},
			{kind: "FittableRows",
			fit: true,
			defaultKind: enyo.kind({
				kind: "FittableColumns",
				style: "height: 15.5%; margin: 0.5%;",
				defaultKind: enyo.kind({
					kind: "onyx.Button",
					classes: "onyx-toolbar",
					style: "width: 24%; margin: 0.5%; border-radius: 8px; font-size: 24pt; font-weight: bold;",
					ontap: "keyTapped"
				}),
			}),
			components:[
				{components:[
					/**{style: "visibility: hidden;"},*/
    					{content: "Square Root", ontap: "sqrtTapped"},
					{content: "("},
					{content: ")"},
					{content: "C", style: "margin-right: 0;", ontap: "cancelTapped"},
				]},
 {components:[
                                        {content: "ln", ontap: "lnTapped"},
                                        {content: "log", ontap: "logTapped"},
                                        {content: "^2"},
                                        {content: ""},
                                ]},

				{components:[
					{content: "7", classes: "number-button"},
					{content: "8", classes: "number-button"},
					{content: "9", classes: "number-button"},
					{content: "+", style: "margin-right: 0;"},
				]},
				{components:[
					{content: "4", classes: "number-button"},
					{content: "5", classes: "number-button"},
					{content: "6", classes: "number-button"},
					{content: "-", style: "margin-right: 0;"},
				]},
				{components:[
					{content: "1", classes: "number-button"},
					{content: "2", classes: "number-button"},
					{content: "3", classes: "number-button"},
					{content: "*", style: "margin-right: 0;"},
				]},
				{components:[
					{content: "."},
					{content: "0", classes: "number-button"},
					{content: "=", ontap: "equalsTapped"},
					{content: "/", style: "margin-right: 0;"},
				]},
			]},
		]},
		{kind: "CoreNavi", fingerTracking: true}
	],
	//Action Handlers
	keyTapped: function(inSender, inEvent) {
		var formula = this.$.Formula;
		formula.setContent(formula.getContent() + inSender.getContent());

	},
	equalsTapped: function() {
		this.$.Result.setContent(this.calculate(this.$.Formula.getContent()));
	},
	calculate: function(formula) {
		try {
			// Replace mathematical notation with JS here
			var parsed;
			parsed = formula.replace('sqrt', 'Math.sqrt');

			return eval(parsed);
		}
		catch(err) {
			enyo.log(err);
			return "Invalid Input";
		}
	},
	cancelTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("");
	},
	sqrtTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("sqrt(");
	},
	lnTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("ln(");
	},
	logTapped: function() {
		this.$.Result.setContent("");
		this.$.Formula.setContent("log(");
	},
	backspaceTapped: function() {
		var formula = this.$.Formula;
		formula.setContent(formula.getContent().substr(0, formula.getContent().length - 1));
	},
	//Helper Functions
	handleBackGesture: function(inSender, inEvent) {
		//this.$.AppPanels.setIndex(0);
	},
	handleCoreNaviDragStart: function(inSender, inEvent) {
		/*
		if(enyo.Panels.isScreenNarrow()) {
			this.$.AppPanels.dragstartTransition(inEvent);
		}
		*/
	},
	handleCoreNaviDrag: function(inSender, inEvent) {
		/*
		if(enyo.Panels.isScreenNarrow()) {
			this.$.AppPanels.dragTransition(inEvent);
		}
		*/
	},
	handleCoreNaviDragFinish: function(inSender, inEvent) {
		/*
		if(enyo.Panels.isScreenNarrow()) {
			this.$.AppPanels.dragfinishTransition(inEvent);
		}
		*/
	},
});
<|endoftext|>


<commit_before><commit_msg>luid-user-picker [enh] myId is not in the scope and update query in getMeAsync() (only ask for the id)<commit_after><|endoftext|>


<commit_before>const d3Tip = require('d3-tip')
const d3 = require('d3')

const d3tip = d3Tip(d3)

const marginY = 80
const marginX = 20
const height = 300 - marginY * 2
const width = 700 - marginX * 2

const data = [
  pt('website', 'year-of-code', 'yoshuawuyts.github.io/year-of-code', '2015-05-04'),
  pt('module', 'from2-string','https://github.com/yoshuawuyts/from2-string', '2015-04-29'),
  pt('post', 'Party tricks with ES6 symbols', 'https://medium.com/code-ops/party-tricks-with-es6-symbols-ee328fdb6c4b', '2015-04-30'),
]

const xScale = d3.scale.linear()
  .domain([0, 52])
  .range([0, width])

const yScale = d3.scale.linear()
  .domain([0, 2])
  .range([0, height])

const x = d3.time.scale()
  .domain([new Date(2015, 4, 1), new Date(2016, 3, 1)])
  .range([0, width])

const xAxis = d3.svg.axis()
  .scale(x)
  .orient('bottom')
  .ticks(d3.time.months)
  .tickSize(16, 0)
  .tickFormat(d3.time.format('%b'))

const tip = d3tip()
  .attr('class', 'plot-tip')
  .html(d => '' + d.name + '')

const svg = d3.select('[role="plot"]')
  .append('svg')
  .attr('height', height + marginY * 2)
  .attr('width', width + marginX * 2)
  .append('g')
  .attr('transform', 'translate(' + marginX + ',' + marginY + ')')
  .attr('class', 'plot')

svg.call(tip)

// create x axis
svg.append('g')
  .attr('transform', 'translate(0,' + (height + 20) + ')')
  .attr('class', 'plot-x-axis')
  .call(xAxis)

// create dots
svg.selectAll('circle')
   .data(data)
   .enter()
   .append('circle')
   .attr('cx', d => xScale(d.cx))
   .attr('cy', d => yScale(d.cy))
   .attr('r', 7)
   .on('mouseover', tip.show)
   .on('mouseout', tip.hide)

// add labels to dots
svg.selectAll('text')
  .data(data)
  .enter()
  .append('text')
  .text(d => d.name)
  .attr('x', d => xScale(d.cx))
  .attr('y', d => yScale(d.cy))

// create a data point
// str, str, str -> obj
function pt (type, name, uri, date) {
  return {
    type: type,
    name: name,
    date: date,
    uri: uri,
    cx: parseWeek(date),
    cy: typeIndex(type)
  }
}

// get the relative week from a date
// example: 2015-07-19 => 02
// str -> num
function parseWeek (date) {
  return Number(date.split('-')[1]) - 5
}

// return a y index for a type
// str -> num
function typeIndex (str) {
  if (str === 'website') return 0
  if (str === 'module') return 1
  if (str === 'post') return 2
}
<commit_msg>plot: open in new window<commit_after>const d3Tip = require('d3-tip')
const d3 = require('d3')

const d3tip = d3Tip(d3)

const marginY = 80
const marginX = 20
const height = 300 - marginY * 2
const width = 700 - marginX * 2

const data = [
  pt('website', 'year-of-code', 'https://yoshuawuyts.github.io/year-of-code', '2015-05-04'),
  pt('module', 'from2-string','https://github.com/yoshuawuyts/from2-string', '2015-04-29'),
  pt('post', 'Party tricks with ES6 symbols', 'https://medium.com/code-ops/party-tricks-with-es6-symbols-ee328fdb6c4b', '2015-04-30'),
]

const xScale = d3.scale.linear()
  .domain([0, 52])
  .range([0, width])

const yScale = d3.scale.linear()
  .domain([0, 2])
  .range([0, height])

const x = d3.time.scale()
  .domain([new Date(2015, 4, 1), new Date(2016, 3, 1)])
  .range([0, width])

const xAxis = d3.svg.axis()
  .scale(x)
  .orient('bottom')
  .ticks(d3.time.months)
  .tickSize(16, 0)
  .tickFormat(d3.time.format('%b'))

const tip = d3tip()
  .attr('class', 'plot-tip')
  .html(d => '' + d.name + '')

const svg = d3.select('[role="plot"]')
  .append('svg')
  .attr('height', height + marginY * 2)
  .attr('width', width + marginX * 2)
  .append('g')
  .attr('transform', 'translate(' + marginX + ',' + marginY + ')')
  .attr('class', 'plot')

svg.call(tip)

// create x axis
svg.append('g')
  .attr('transform', 'translate(0,' + (height + 20) + ')')
  .attr('class', 'plot-x-axis')
  .call(xAxis)

// create dots
svg.selectAll('circle')
   .data(data)
   .enter()
   .append('circle')
   .attr('cx', d => xScale(d.cx))
   .attr('cy', d => yScale(d.cy))
   .attr('r', 7)
   .on('mouseover', tip.show)
   .on('mouseout', tip.hide)
   .on('click', d => window.open(d.uri))

// add labels to dots
svg.selectAll('text')
  .data(data)
  .enter()
  .append('text')
  .text(d => d.name)
  .attr('x', d => xScale(d.cx))
  .attr('y', d => yScale(d.cy))

// create a data point
// str, str, str -> obj
function pt (type, name, uri, date) {
  return {
    type: type,
    name: name,
    date: date,
    uri: uri,
    cx: parseWeek(date),
    cy: typeIndex(type)
  }
}

// get the relative week from a date
// example: 2015-07-19 => 02
// str -> num
function parseWeek (date) {
  return Number(date.split('-')[1]) - 5
}

// return a y index for a type
// str -> num
function typeIndex (str) {
  if (str === 'website') return 0
  if (str === 'module') return 1
  if (str === 'post') return 2
}
<|endoftext|>


<commit_before>var csrftoken = $('meta[name=csrf-token]').attr('content');

$(document).ready(function () {
    "use strict";

    $('#li-boot').addClass('active');

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto'
    });

    $('.clickable-table tbody').on("click", "tr", function () {
        var url = $(this).data('url');
        if (url) {
            window.location = url;
        }
    });
});

$(document).ready(function () {
    "use strict";

    $.ajax({
        'url': '/_ajax/count/boot',
        'traditional': true,
        'cache': true,
        'context': $('#boot-reports-count'),
        'dataType': 'json',
        'data': {
            'job': $('#job-id').val(),
            'date_range': $('#date-range').val()
        },
        'dataFilter': function (data, type) {
            if (type === 'json') {
                return JSON.parse(data).result;
            }
            return data;
        },
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'statusCode': {
            404: function () {
                $(this).empty().append('∞');
            },
            500: function () {
                $(this).empty().append('∞');
            }
        }
    }).done(function (data) {
        $(this).empty().append(data.count);
    });
});

$(document).ready(function () {
    "use strict";

    $.ajax({
        'url': '/_ajax/boot',
        'traditional': true,
        'cache': true,
        'context': $('#boot-boards-count'),
        'dataType': 'json',
        'data': {
            'job': $('#job-id').val(),
            'date_range': $('#date-range').val(),
            'aggregate': 'board',
            'field': 'board'
        },
        'dataFilter': function (data, type) {
            if (type === 'json') {
                return JSON.parse(data).result;
            }
            return data;
        },
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'statusCode': {
            404: function () {
                $(this).empty().append('∞');
            },
            500: function () {
                $(this).empty().append('∞');
            }
        }
    }).done(function (data) {
        $(this).empty().append(data.length);
    });
});

$(document).ready(function () {
    "use strict";

    function countFailedBootReports (data) {
        var i = 0,
            len = data.length,
            deferredCalls = new Array(len);

        if (len > 0) {
            for (i; i < len; i++) {
                deferredCalls[i] = $.ajax({
                    'url': '/_ajax/count/boot',
                    'traditional': true,
                    'cache': true,
                    'dataType': 'json',
                    'data': {
                        'status': 'FAIL',
                        'job': $('#job-id').val(),
                        'kernel': data[i].kernel
                    },
                    'dataFilter': function (data, type) {
                        if (type === 'json') {
                            return JSON.parse(data).result;
                        }
                        return data;
                    },
                    'beforeSend': function (xhr) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                });
            }

            $.when.apply($, deferredCalls).then(function () {
                var count = '∞',
                    first = null;
                len = arguments.length;

                if (len > 0) {
                    // This is the case when we have only one build and the
                    // deferred call returns just the plain object not in an
                    // Array like way.
                    first = arguments[0];
                    if (! Array.isArray(first)) {
                        count = first.count;
                        $('#fail-count0').empty().append(count);
                    } else {
                        for (i = 0; i < len; i++) {
                            if (arguments[i] !== null) {
                                count = arguments[i][0].count;
                                $('#fail-count' + i).empty().append(count);
                            }
                        }
                    }
                }
            });
        }
    }

    function countFailCallback () {
        $('.fail-badge').each(function () {
            $(this).empty().append('∞');
        });
    }

    $.when(
        $.ajax({
            'url': '/_ajax/boot',
            'traditional': true,
            'cache': true,
            'dataType': 'json',
            'context': $('#boot-reports-body'),
            'data': {
                'aggregate': 'kernel',
                'job': $('#job-id').val(),
                'sort': 'created_on',
                'sort_order': -1,
                'date_range': $('#date-range').val(),
                'field': ['job', 'kernel', 'created_on']
            },
            'dataFilter': function (data, type) {
                if (type === 'json') {
                    return JSON.parse(data).result;
                }
                return data;
            },
            'beforeSend': function (xhr) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            'statusCode': {
                404: function () {
                    $('#failed-builds-body').empty().append(
                        '
' +
                        '
Error loading data.

'
                    );
                    var text = '
' +
                        '<button type="button" class="close" ' +
                        'data-dismiss="alert" aria-hidden="true">×</button>' +
                        '404 error while loading defconfigs from the server.\n' +
                        'Please contact the website administrators.' +
                        '
';
                    $('#errors-container').append(text);
                    $('#boots-404-error').alert();
                },
                500: function () {
                    $('#failed-builds-body').empty().append(
                        '
' +
                        '
Error loading data.

'
                    );
                    var text = '
' +
                        '<button type="button" class="close" ' +
                        'data-dismiss="alert" aria-hidden="true">×</button>' +
                        '500 error while loading defconfigs from the server.\n' +
                        'Please contact the website administrators.' +
                        '
';
                    $('#errors-container').append(text);
                    $('#boots-500-error').alert();
                }
            }
        }).done(function (data) {
            console.log(data);
            var row = '',
                job = $('#job-id').val(),
                created, col1, col2, col3, col4, href,
                kernel,
                i = 0,
                len = data.length;

            if (len === 0) {
                row = '

' +
                    'No boot reports available.

';
                $(this).empty().append(row);
            } else {
                for (i; i < len; i++) {
                    kernel = data[i].kernel;
                    created = new Date(data[i].created_on['$date']);
                    href = '/boot/all/job/' + job + '/kernel/' + kernel + '/';

                    col1 = '' + kernel + '	';
                    col2 = '' +
                        '' +
                        '' +
                        '	';
                    col3 = '' + created.getCustomISODate() + '	';
                    col4 = '' +
                        '' +
                        '' +
                        '' +
                        '	';
                    row += '
' +
                        col1 + col2 + col3 + col4 + '
';
                }

                $(this).empty().append(row);
            }
        })
    ).then(countFailedBootReports, countFailCallback);
});<commit_msg>Fix JSON parsing.<commit_after>var csrftoken = $('meta[name=csrf-token]').attr('content');

$(document).ready(function () {
    "use strict";

    $('#li-boot').addClass('active');

    $('body').tooltip({
        'selector': '[rel=tooltip]',
        'placement': 'auto'
    });

    $('.clickable-table tbody').on("click", "tr", function () {
        var url = $(this).data('url');
        if (url) {
            window.location = url;
        }
    });
});

$(document).ready(function () {
    "use strict";

    $.ajax({
        'url': '/_ajax/count/boot',
        'traditional': true,
        'cache': true,
        'context': $('#boot-reports-count'),
        'dataType': 'json',
        'data': {
            'job': $('#job-id').val(),
            'date_range': $('#date-range').val()
        },
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'statusCode': {
            404: function () {
                $(this).empty().append('∞');
            },
            500: function () {
                $(this).empty().append('∞');
            }
        }
    }).done(function (data) {
        data = data.result[0];
        $(this).empty().append(data.count);
    });
});

$(document).ready(function () {
    "use strict";

    $.ajax({
        'url': '/_ajax/boot',
        'traditional': true,
        'cache': true,
        'context': $('#boot-boards-count'),
        'dataType': 'json',
        'data': {
            'job': $('#job-id').val(),
            'date_range': $('#date-range').val(),
            'aggregate': 'board',
            'field': 'board'
        },
        'beforeSend': function (xhr) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        'statusCode': {
            404: function () {
                $(this).empty().append('∞');
            },
            500: function () {
                $(this).empty().append('∞');
            }
        }
    }).done(function (data) {
        data = data.result;
        $(this).empty().append(data.length);
    });
});

$(document).ready(function () {
    "use strict";

    function countFailedBootReports (data) {
        data = data.result;

        var i = 0,
            len = data.length,
            deferredCalls = new Array(len);

        if (len > 0) {
            for (i; i < len; i++) {
                deferredCalls[i] = $.ajax({
                    'url': '/_ajax/count/boot',
                    'traditional': true,
                    'cache': true,
                    'dataType': 'json',
                    'data': {
                        'status': 'FAIL',
                        'job': $('#job-id').val(),
                        'kernel': data[i].kernel
                    },
                    'beforeSend': function (xhr) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                });
            }

            $.when.apply($, deferredCalls).then(function () {
                var count = '∞',
                    first = null;
                len = arguments.length;

                if (len > 0) {
                    // This is the case when we have only one build and the
                    // deferred call returns just the plain object not in an
                    // Array like way.
                    first = arguments[0];
                    if (! Array.isArray(first)) {
                        count = first.count;
                        $('#fail-count0').empty().append(count);
                    } else {
                        for (i = 0; i < len; i++) {
                            if (arguments[i] !== null) {
                                count = arguments[i][0].result[0].count;
                                $('#fail-count' + i).empty().append(count);
                            }
                        }
                    }
                }
            });
        }
    }

    function countFailCallback () {
        $('.fail-badge').each(function () {
            $(this).empty().append('∞');
        });
    }

    $.when(
        $.ajax({
            'url': '/_ajax/boot',
            'traditional': true,
            'cache': true,
            'dataType': 'json',
            'context': $('#boot-reports-body'),
            'data': {
                'aggregate': 'kernel',
                'job': $('#job-id').val(),
                'sort': 'created_on',
                'sort_order': -1,
                'date_range': $('#date-range').val(),
                'field': ['job', 'kernel', 'created_on']
            },
            'beforeSend': function (xhr) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            },
            'statusCode': {
                404: function () {
                    $('#failed-builds-body').empty().append(
                        '
' +
                        '
Error loading data.

'
                    );
                    var text = '
' +
                        '<button type="button" class="close" ' +
                        'data-dismiss="alert" aria-hidden="true">×</button>' +
                        '404 error while loading defconfigs from the server.\n' +
                        'Please contact the website administrators.' +
                        '
';
                    $('#errors-container').append(text);
                    $('#boots-404-error').alert();
                },
                500: function () {
                    $('#failed-builds-body').empty().append(
                        '
' +
                        '
Error loading data.

'
                    );
                    var text = '
' +
                        '<button type="button" class="close" ' +
                        'data-dismiss="alert" aria-hidden="true">×</button>' +
                        '500 error while loading defconfigs from the server.\n' +
                        'Please contact the website administrators.' +
                        '
';
                    $('#errors-container').append(text);
                    $('#boots-500-error').alert();
                }
            }
        }).done(function (data) {
            data = data.result;

            var row = '',
                job = $('#job-id').val(),
                created, col1, col2, col3, col4, href,
                kernel,
                i = 0,
                len = data.length;

            if (len === 0) {
                row = '

' +
                    'No boot reports available.

';
                $(this).empty().append(row);
            } else {
                for (i; i < len; i++) {
                    kernel = data[i].kernel;
                    created = new Date(data[i].created_on['$date']);
                    href = '/boot/all/job/' + job + '/kernel/' + kernel + '/';

                    col1 = '' + kernel + '	';
                    col2 = '' +
                        '' +
                        '' +
                        '	';
                    col3 = '' + created.getCustomISODate() + '	';
                    col4 = '' +
                        '' +
                        '' +
                        '' +
                        '	';
                    row += '
' +
                        col1 + col2 + col3 + col4 + '
';
                }

                $(this).empty().append(row);
            }
        })
    ).then(countFailedBootReports, countFailCallback);
});<|endoftext|>


<commit_before>module.exports = {
	name: "frappe-html",
	setup(build) {
		let path = require("path");
		let fs = require("fs/promises");

		build.onResolve({ filter: /\.html$/ }, (args) => {
			return {
				path: path.join(args.resolveDir, args.path),
				namespace: "frappe-html",
			};
		});

		build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => {
			let filepath = args.path;
			let filename = path.basename(filepath).split(".")[0];

			return fs
				.readFile(filepath, "utf-8")
				.then((content) => {
					content = JSON.stringify(scrub_html_template(content));
					return {
						contents: `\n\tfrappe.templates['${filename}'] = ${content};\n`,
						watchFiles: [filepath],
					};
				})
				.catch(() => {
					return {
						contents: "",
						warnings: [
							{
								text: `There was an error importing ${filepath}`,
							},
						],
					};
				});
		});
	},
};

function scrub_html_template(content) {
	content = content.replace(/`/g, "\\`");
	return content;
}
<commit_msg>Revert "fix: allow backtick in HTML templates as well"<commit_after>module.exports = {
	name: "frappe-html",
	setup(build) {
		let path = require("path");
		let fs = require("fs/promises");

		build.onResolve({ filter: /\.html$/ }, (args) => {
			return {
				path: path.join(args.resolveDir, args.path),
				namespace: "frappe-html",
			};
		});

		build.onLoad({ filter: /.*/, namespace: "frappe-html" }, (args) => {
			let filepath = args.path;
			let filename = path.basename(filepath).split(".")[0];

			return fs
				.readFile(filepath, "utf-8")
				.then((content) => {
					content = scrub_html_template(content);
					return {
						contents: `\n\tfrappe.templates['${filename}'] = \`${content}\`;\n`,
						watchFiles: [filepath],
					};
				})
				.catch(() => {
					return {
						contents: "",
						warnings: [
							{
								text: `There was an error importing ${filepath}`,
							},
						],
					};
				});
		});
	},
};

function scrub_html_template(content) {
	content = content.replace(/`/g, "\\`");
	return content;
}
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var CMApiClient = require('../../lib/cm-api-client');
var Promise = require('bluebird');
var sinon = require('sinon');

describe('cm-api-client', function() {

  this.timeout(100);

  it('is created properly', function() {
    var baseUrl = 'http://cm.dev/';
    var apiKey = 'foo';
    var cmHttpClient = new CMApiClient(baseUrl, apiKey);

    assert.instanceOf(cmHttpClient, CMApiClient, 'has proper type');
    assert.strictEqual(cmHttpClient.baseUrl, baseUrl, 'has proper baseUrl');
    assert.strictEqual(cmHttpClient.apiKey, apiKey, 'has proper apiKey');
  });

  describe('_request()', function() {
    var baseUri = 'http://cm.dev/';
    var apiKey = 'fooKey';
    var cmHttpClient = new CMApiClient(baseUri, apiKey);
    var serviceLocator = require('../../lib/service-locator.js');

    var logger = {
      info: function() {
      }
    };

    var loggerSpy = sinon.spy(logger, 'info');
    serviceLocator.register('logger', function() {
      return logger;
    });

    var action = 'foo';
    var sentData = ['bar', 'baz'];

    it('works with successful response', function(done) {
      var requestPromiseMock = sinon.stub(cmHttpClient, '_httpClient').returns(
        function(options) {
          assert.deepEqual(options, {
            method: 'POST',
            uri: baseUri,
            body: {
              method: 'CM_Janus_RpcEndpoints.' + action,
              params: [apiKey].concat(sentData)
            },
            json: true
          }, 'invoked with proper params');
          return Promise.resolve({body: 'body', success: {result: 'quux'}});
        }
      );

      cmHttpClient._request(action, sentData).then(function(res) {
        assert.strictEqual(res, 'quux');
        assert.isTrue(loggerSpy.calledTwice);
        assert.isTrue(loggerSpy.getCall(0).calledWith('cm-api', 'request', baseUri));
        assert.isTrue(loggerSpy.getCall(1).calledWith('cm-api', 'response', 'body'));
        assert.isTrue(requestPromiseMock.calledOnce);
        requestPromiseMock.restore();
        done();
      });
    });

    it('works with response with error', function(done) {
      var requestPromiseMock = sinon.stub(cmHttpClient, '_httpClient').returns(
        function() {
          return Promise.resolve({body: 'bodyErr', error: {msg: 'disaster'}});
        }
      );

      cmHttpClient._request(action, sentData).catch(function(err) {
        assert.instanceOf(err, Error);
        assert.strictEqual(err.message, 'cm-api error: disaster');
        assert.strictEqual(loggerSpy.callCount, 4);
        assert.isTrue(loggerSpy.getCall(2).calledWith('cm-api', 'request', baseUri));
        assert.isTrue(loggerSpy.getCall(3).calledWith('cm-api', 'response', 'bodyErr'));
        assert.isTrue(requestPromiseMock.calledOnce);
        requestPromiseMock.restore();
        done();
      });
    });

    it('works with completely failed request', function(done) {
      var requestPromiseMock = sinon.stub(cmHttpClient, '_httpClient').returns(
        function() {
          return Promise.reject(new Error('request failed'));
        }
      );

      cmHttpClient._request(action, sentData).catch(function(err) {
        assert.instanceOf(err, Error);
        assert.strictEqual(err.message, 'cm-api error: request failed');
        assert.strictEqual(loggerSpy.callCount, 5);
        assert.isTrue(loggerSpy.getCall(4).calledWith('cm-api', 'request', baseUri));
        assert.isTrue(requestPromiseMock.calledOnce);
        requestPromiseMock.restore();
        done();
      });
    });
  });

  describe('isValidUser()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'foo');
    var userData = {foo: 'bar'};

    it('works when returns true', function() {
      var successStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.isValidUser(userData);
      assert.isTrue(successStub.withArgs('isValidUser', [userData]).calledOnce);
      successStub.restore();
    });

    it('works when returns false', function(done) {
      var failStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(false));
      cmHttpClient.isValidUser(userData).catch(function(err) {
        assert.instanceOf(err, Error);
        assert.strictEqual(err.message, 'Not valid user');
        assert.isTrue(failStub.withArgs('isValidUser', [userData]).calledOnce);
        done();
      });
    });
  });

  describe('publish()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'apiKey');
    var streamChannelKey = 'scKey';
    var streamKey = 'stKey';
    var start = 123;
    var userData = {foo: 'bar'};

    it('passes params to request correctly', function() {
      var requestStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.publish(streamChannelKey, streamKey, start, userData);
      assert.isTrue(requestStub.withArgs('publish', [streamChannelKey, streamKey, start, userData]).calledOnce);
      requestStub.restore();
    });
  });

  describe('subscribe()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'apiKey');
    var streamChannelKey = 'scKey';
    var streamKey = 'stKey';
    var start = 123;
    var userData = {foo: 'bar'};

    it('passes params to request correctly', function() {
      var requestStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.subscribe(streamChannelKey, streamKey, start, userData);
      assert.isTrue(requestStub.withArgs('subscribe', [streamChannelKey, streamKey, start, userData]).calledOnce);
      requestStub.restore();
    });
  });

  describe('removeStream()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'apiKey');
    var streamChannelKey = 'scKey';
    var streamKey = 'stKey';

    it('passes params to request correctly', function() {
      var requestStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.removeStream(streamChannelKey, streamKey);
      assert.isTrue(requestStub.withArgs('removeStream', [streamChannelKey, streamKey]).calledOnce);
      requestStub.restore();
    });
  });
});
<commit_msg>increase timeout<commit_after>var assert = require('chai').assert;
var CMApiClient = require('../../lib/cm-api-client');
var Promise = require('bluebird');
var sinon = require('sinon');

describe('cm-api-client', function() {

  this.timeout(1000);

  it('is created properly', function() {
    var baseUrl = 'http://cm.dev/';
    var apiKey = 'foo';
    var cmHttpClient = new CMApiClient(baseUrl, apiKey);

    assert.instanceOf(cmHttpClient, CMApiClient, 'has proper type');
    assert.strictEqual(cmHttpClient.baseUrl, baseUrl, 'has proper baseUrl');
    assert.strictEqual(cmHttpClient.apiKey, apiKey, 'has proper apiKey');
  });

  describe('_request()', function() {
    var baseUri = 'http://cm.dev/';
    var apiKey = 'fooKey';
    var cmHttpClient = new CMApiClient(baseUri, apiKey);
    var serviceLocator = require('../../lib/service-locator.js');

    var logger = {
      info: function() {
      }
    };

    var loggerSpy = sinon.spy(logger, 'info');
    serviceLocator.register('logger', function() {
      return logger;
    });

    var action = 'foo';
    var sentData = ['bar', 'baz'];

    it('works with successful response', function(done) {
      var requestPromiseMock = sinon.stub(cmHttpClient, '_httpClient').returns(
        function(options) {
          assert.deepEqual(options, {
            method: 'POST',
            uri: baseUri,
            body: {
              method: 'CM_Janus_RpcEndpoints.' + action,
              params: [apiKey].concat(sentData)
            },
            json: true
          }, 'invoked with proper params');
          return Promise.resolve({body: 'body', success: {result: 'quux'}});
        }
      );

      cmHttpClient._request(action, sentData).then(function(res) {
        assert.strictEqual(res, 'quux');
        assert.isTrue(loggerSpy.calledTwice);
        assert.isTrue(loggerSpy.getCall(0).calledWith('cm-api', 'request', baseUri));
        assert.isTrue(loggerSpy.getCall(1).calledWith('cm-api', 'response', 'body'));
        assert.isTrue(requestPromiseMock.calledOnce);
        requestPromiseMock.restore();
        done();
      });
    });

    it('works with response with error', function(done) {
      var requestPromiseMock = sinon.stub(cmHttpClient, '_httpClient').returns(
        function() {
          return Promise.resolve({body: 'bodyErr', error: {msg: 'disaster'}});
        }
      );

      cmHttpClient._request(action, sentData).catch(function(err) {
        assert.instanceOf(err, Error);
        assert.strictEqual(err.message, 'cm-api error: disaster');
        assert.strictEqual(loggerSpy.callCount, 4);
        assert.isTrue(loggerSpy.getCall(2).calledWith('cm-api', 'request', baseUri));
        assert.isTrue(loggerSpy.getCall(3).calledWith('cm-api', 'response', 'bodyErr'));
        assert.isTrue(requestPromiseMock.calledOnce);
        requestPromiseMock.restore();
        done();
      });
    });

    it('works with completely failed request', function(done) {
      var requestPromiseMock = sinon.stub(cmHttpClient, '_httpClient').returns(
        function() {
          return Promise.reject(new Error('request failed'));
        }
      );

      cmHttpClient._request(action, sentData).catch(function(err) {
        assert.instanceOf(err, Error);
        assert.strictEqual(err.message, 'cm-api error: request failed');
        assert.strictEqual(loggerSpy.callCount, 5);
        assert.isTrue(loggerSpy.getCall(4).calledWith('cm-api', 'request', baseUri));
        assert.isTrue(requestPromiseMock.calledOnce);
        requestPromiseMock.restore();
        done();
      });
    });
  });

  describe('isValidUser()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'foo');
    var userData = {foo: 'bar'};

    it('works when returns true', function() {
      var successStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.isValidUser(userData);
      assert.isTrue(successStub.withArgs('isValidUser', [userData]).calledOnce);
      successStub.restore();
    });

    it('works when returns false', function(done) {
      var failStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(false));
      cmHttpClient.isValidUser(userData).catch(function(err) {
        assert.instanceOf(err, Error);
        assert.strictEqual(err.message, 'Not valid user');
        assert.isTrue(failStub.withArgs('isValidUser', [userData]).calledOnce);
        done();
      });
    });
  });

  describe('publish()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'apiKey');
    var streamChannelKey = 'scKey';
    var streamKey = 'stKey';
    var start = 123;
    var userData = {foo: 'bar'};

    it('passes params to request correctly', function() {
      var requestStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.publish(streamChannelKey, streamKey, start, userData);
      assert.isTrue(requestStub.withArgs('publish', [streamChannelKey, streamKey, start, userData]).calledOnce);
      requestStub.restore();
    });
  });

  describe('subscribe()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'apiKey');
    var streamChannelKey = 'scKey';
    var streamKey = 'stKey';
    var start = 123;
    var userData = {foo: 'bar'};

    it('passes params to request correctly', function() {
      var requestStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.subscribe(streamChannelKey, streamKey, start, userData);
      assert.isTrue(requestStub.withArgs('subscribe', [streamChannelKey, streamKey, start, userData]).calledOnce);
      requestStub.restore();
    });
  });

  describe('removeStream()', function() {
    var cmHttpClient = new CMApiClient('http://cm.dev/', 'apiKey');
    var streamChannelKey = 'scKey';
    var streamKey = 'stKey';

    it('passes params to request correctly', function() {
      var requestStub = sinon.stub(cmHttpClient, '_request').returns(Promise.resolve(true));
      cmHttpClient.removeStream(streamChannelKey, streamKey);
      assert.isTrue(requestStub.withArgs('removeStream', [streamChannelKey, streamKey]).calledOnce);
      requestStub.restore();
    });
  });
});
<|endoftext|>


<commit_before>/* global ares */
/**
 * This kind provide a widget to tune global properties
 */

enyo.kind({
	name: "AresProperties",
	classes: "enyo-unselectable ares-classic-popup",
	kind:"onyx.Popup",
	fit: true,
	modal: true, centered: true, floating: true, autoDismiss: false,
	events: {
		onModifiedConfig: "",
		onSaveGeneratedXml: "",
		onDone: ""
	},

	components: [
		{classes:"title left-align", components:[
			{kind: "onyx.RadioGroup", onActivate: "switchDrawers", name: "thumbnail", classes:"ares-radio-group", components: []}
		]},
		{kind: "onyx.Toolbar", name: "toolbarId", classes:"bottom-toolbar", components: [
			{name: "ok", classes:"right", kind: "onyx.Button", content: "OK", ontap: "confirmTap"}
		]},
		{kind: "Signals", onPluginRegist: "handlePluginRegist"}
	],

	debug: false,

	/**
	 * @protected
	 */
	create: function() {
		ares.setupTraceLogger(this);
		this.inherited(arguments);
		this.createAresAboutDrawer();
	},

	/**
	 * @private
	 */
	createAresAboutDrawer: function() {
		var aresAboutTabEntry = {
			id: "aresAbout",
			name: "Ares",
			kind: "AboutAresPanel",
			components:[{content:"Ares", classes:"large-fixed"},{tag:"span", classes:"ares-bottom-check"}]
		};
		this.createComponentTab(aresAboutTabEntry);
	},

	/**
	 * Create a tab to display basic informations about Ares or embeeded plugins
	 *
	 * @param  {Object} inTabEntry object that define the name of the tab thumbnail & drawer
	 *                             and the kind of the tab panel.
	 * @private
	 */
	createComponentTab: function(inTabEntry) {
		var drawer = this.createComponent({
			name: inTabEntry.id + 'Drawer',
			kind: "onyx.Drawer",
			open: false
		},{addBefore: this.$.toolbarId});

		inTabEntry.panel = drawer.createComponent({
			name: inTabEntry.id,
			kind: inTabEntry.kind
		});

		inTabEntry.tab = this.$.thumbnail.createComponent({
			name: inTabEntry.id + 'Tab',
			content: inTabEntry.name,
			componentId: inTabEntry.id,
			showing: true,
			active: true,
			components:inTabEntry.components
		});
	},

	/**
	 * Receive the {onPluginRegist} broadcast notification
	 * @param {Object} inEvent.pluginService
	 */
	handlePluginRegist: function(inSender, inEvent) {
		this.trace("");

		if (typeof inEvent.pluginService.getAresPropertiesKind !== 'function') {
			return true;
		}

		var pluginService = {
			id: inEvent.pluginService.id,
			name: inEvent.pluginService.getName() || inEvent.pluginService.id,
			kind: inEvent.pluginService.getAresPropertiesKind()
		};
		this.createComponentTab(pluginService);
	},

	// /**
	//  * close one drawer and open the other depending on which radio button was tapped
	//  */
	switchDrawers: function(inSender, inEvent) {
		if (inEvent.originator.active === true ) {
			enyo.forEach(inEvent.originator.parent.children, function(tab) {
				var activate = (tab.componentId === inEvent.originator.componentId);
				this.$[tab.componentId + 'Drawer'].setOpen(activate);
			}, this);
		}
	},

	confirmTap: function(inSender, inEvent) {
		this.hide();
	}

});

enyo.kind({
	name: "AboutAresPanel",
	kind: "enyo.Scroller",
	fit: "true",
	classes: "ares-about-drawer",
	published: {
		config: {},
		aboutAresData: undefined
	},
	events: {
		onError: ""
	},
	components: [
		{name: "errorMessage", content: "Error: Unable to load Ares About data from Ares IDE Server", showing: false},
		{
			kind: "FittableRows",
			name: "aboutDescription",
				components: [
					{
						kind:"FittableColumns",
						components: [
							{content: "Ares version: ", classes: "ares-about-description"},
							{name: "versionValue"}
						]
					},
					{
						kind:"FittableColumns",
						components: [
							{content: "If you encounter any bug please report it in the following link ", classes: "ares-about-description"},
							{name: "brValue", kind: "enyo.Control", tag: "a", content: "Report a bug", attributes: {"target": "_blank"}}
						]
					},
					{
						kind:"FittableColumns",
						components: [
							{content: "We would welcome any contribution you can come with ", classes: "ares-about-description"},
							{name: "homeValue", kind: "enyo.Control", tag: "a", content: "Project Homepage", attributes: {"target": "_blank"}}
						]
					},
					{
						kind:"FittableColumns",
						components: [
							{content: "Copyright: ", classes: "ares-about-description"},
							{name: "license", classes: "ares-about-description"},
							{ content: " all rights reserved"}
						]
					}
				]
		}
	],

	/**
	 * private
	 */
	create: function(){
		this.inherited(arguments);
		this.reqAboutAresData();

	},

	/**
	 * Send an AJAX request to the  Backend in order to get the needed data for the Ares description.
	 * @rprivate
	 */
	reqAboutAresData: function(){
		var origin = window.location.origin || window.location.protocol + "//" + window.location.host; // Webkit/FF vs IE

		var req = new enyo.Ajax({
			url: origin + '/res/aboutares'
		});

		req.response(this, function(inSender, inData) {
			this.setAboutAresData(inData.aboutAres);
		});

		//Show the error in a Pop-up.
		req.error(this, function(inSender, inError){

			this.doError({msg: "("+inError +") Unable to load Ares About data", err: inError});
			this.$.errorMessage.show();
			this.$.aboutDescription.hide();
		});

		req.go();
	},

	/**
	 * @private
	 */
	aboutAresDataChanged: function(){
		this.$.versionValue.content = this.aboutAresData.version;
		this.$.brValue.setAttribute("href", this.aboutAresData.bugReportURL);
		this.$.homeValue.setAttribute("href", this.aboutAresData.projectHomePage);
		this.$.license.content = this.aboutAresData.license;
	}
});
<commit_msg>ENYO-2795: reduce verbosity of AresProperties window.<commit_after>/* global ares */
/**
 * This kind provide a widget to tune global properties
 */

enyo.kind({
	name: "AresProperties",
	classes: "enyo-unselectable ares-classic-popup",
	kind:"onyx.Popup",
	fit: true,
	modal: true, centered: true, floating: true, autoDismiss: false,
	events: {
		onModifiedConfig: "",
		onSaveGeneratedXml: "",
		onDone: ""
	},

	components: [
		{classes:"title left-align", components:[
			{kind: "onyx.RadioGroup", onActivate: "switchDrawers", name: "thumbnail", classes:"ares-radio-group", components: []}
		]},
		{kind: "onyx.Toolbar", name: "toolbarId", classes:"bottom-toolbar", components: [
			{name: "ok", classes:"right", kind: "onyx.Button", content: "OK", ontap: "confirmTap"}
		]},
		{kind: "Signals", onPluginRegist: "handlePluginRegist"}
	],

	debug: false,

	/**
	 * @protected
	 */
	create: function() {
		ares.setupTraceLogger(this);
		this.inherited(arguments);
		this.createAresAboutDrawer();
	},

	/**
	 * @private
	 */
	createAresAboutDrawer: function() {
		var aresAboutTabEntry = {
			id: "aresAbout",
			name: "Ares",
			kind: "AboutAresPanel",
			components:[{content:"Ares", classes:"large-fixed"},{tag:"span", classes:"ares-bottom-check"}]
		};
		this.createComponentTab(aresAboutTabEntry);
	},

	/**
	 * Create a tab to display basic informations about Ares or embeeded plugins
	 *
	 * @param  {Object} inTabEntry object that define the name of the tab thumbnail & drawer
	 *                             and the kind of the tab panel.
	 * @private
	 */
	createComponentTab: function(inTabEntry) {
		var drawer = this.createComponent({
			name: inTabEntry.id + 'Drawer',
			kind: "onyx.Drawer",
			open: false
		},{addBefore: this.$.toolbarId});

		inTabEntry.panel = drawer.createComponent({
			name: inTabEntry.id,
			kind: inTabEntry.kind
		});

		inTabEntry.tab = this.$.thumbnail.createComponent({
			name: inTabEntry.id + 'Tab',
			content: inTabEntry.name,
			componentId: inTabEntry.id,
			showing: true,
			active: true,
			components:inTabEntry.components
		});
	},

	/**
	 * Receive the {onPluginRegist} broadcast notification
	 * @param {Object} inEvent.pluginService
	 */
	handlePluginRegist: function(inSender, inEvent) {
		this.trace("");

		if (typeof inEvent.pluginService.getAresPropertiesKind !== 'function') {
			return true;
		}

		var pluginService = {
			id: inEvent.pluginService.id,
			name: inEvent.pluginService.getName() || inEvent.pluginService.id,
			kind: inEvent.pluginService.getAresPropertiesKind()
		};
		this.createComponentTab(pluginService);
	},

	// /**
	//  * close one drawer and open the other depending on which radio button was tapped
	//  */
	switchDrawers: function(inSender, inEvent) {
		if (inEvent.originator.active === true ) {
			enyo.forEach(inEvent.originator.parent.children, function(tab) {
				var activate = (tab.componentId === inEvent.originator.componentId);
				this.$[tab.componentId + 'Drawer'].setOpen(activate);
			}, this);
		}
	},

	confirmTap: function(inSender, inEvent) {
		this.hide();
	}

});

enyo.kind({
	name: "AboutAresPanel",
	kind: "enyo.Scroller",
	fit: "true",
	classes: "ares-about-drawer",
	published: {
		config: {},
		aboutAresData: undefined
	},
	events: {
		onError: ""
	},
	components: [
		{name: "errorMessage", content: "Error: Unable to load Ares About data from Ares IDE Server", showing: false},
		{
			kind: "FittableRows",
			name: "aboutDescription",
				components: [
					{
						kind:"FittableColumns",
						components: [
							{content: "Ares version: ", classes: "ares-about-description"},
							{name: "versionValue"}
						]
					},
					{
						kind:"FittableColumns",
						components: [
							{content: "In case of issue, please consider ", classes: "ares-about-description"},
							{name: "brValue", kind: "enyo.Control", tag: "a", content: "Reporting a bug", attributes: {"target": "_blank"}}
						]
					},
					{
						kind:"FittableColumns",
						components: [
							{content: "See ", classes: "ares-about-description"},
							{name: "homeValue", kind: "enyo.Control", tag: "a", content: "Project Homepage", attributes: {"target": "_blank"}}
						]
					},
					{
						kind:"FittableColumns",
						components: [
							{content: "License: ", classes: "ares-about-description"},
							{name: "license", classes: "ares-about-description"}
						]
					}
				]
		}
	],

	/**
	 * private
	 */
	create: function(){
		this.inherited(arguments);
		this.reqAboutAresData();

	},

	/**
	 * Send an AJAX request to the  Backend in order to get the needed data for the Ares description.
	 * @rprivate
	 */
	reqAboutAresData: function(){
		var origin = window.location.origin || window.location.protocol + "//" + window.location.host; // Webkit/FF vs IE

		var req = new enyo.Ajax({
			url: origin + '/res/aboutares'
		});

		req.response(this, function(inSender, inData) {
			this.setAboutAresData(inData.aboutAres);
		});

		//Show the error in a Pop-up.
		req.error(this, function(inSender, inError){

			this.doError({msg: "("+inError +") Unable to load Ares About data", err: inError});
			this.$.errorMessage.show();
			this.$.aboutDescription.hide();
		});

		req.go();
	},

	/**
	 * @private
	 */
	aboutAresDataChanged: function(){
		this.$.versionValue.content = this.aboutAresData.version;
		this.$.brValue.setAttribute("href", this.aboutAresData.bugReportURL);
		this.$.homeValue.setAttribute("href", this.aboutAresData.projectHomePage);
		this.$.license.content = this.aboutAresData.license;
	}
});
<|endoftext|>


<commit_before>define(["feeds", "jquery", "views/feeds.jade", "sinon"], function(feeds, $, feedsView) {

    describe("when the feeds page is shown", function() {

        beforeEach(function() {

            function subscription(name) {
                return {
                    name: name,
                    htmlUrl: "http://server.com/" + name,
                    rssUrl: "http://server.com/" + name + "/rss"
                };
            }

            var templateResult = feedsView({
                    rows: [
                        subscription("first"),
                        subscription("second"),
                        subscription("third")
                    ]
                });

            this.fixture.append(templateResult);

            feeds.initialize(this.fixture);
        });

        describe("when the unsubscribe button is clicked", function() {

            var secondRow;
            var secondRowRssUrl;

            beforeEach(function() {

                this.fakeServer = this.sinon.useFakeXMLHttpRequest();

                secondRow = $(".js-subscription:eq(1)", this.fixture);
                secondRowRssUrl = secondRow.data("rssurl");

                expect(secondRow.length).to.be(1);

                this.fixtureContainsSecondRow = function() {
                    return jQuery.contains(this.fixture[0], secondRow[0]);
                };

                expect(this.fixtureContainsSecondRow()).to.be(true);
                expect(secondRowRssUrl).to.be("http://server.com/second/rss");

                secondRow.find("a.js-unsubscribe").click();
            });

            it("will hide the row ", function() {
                expect(this.fixtureContainsSecondRow()).to.be(false);
            });

            it("will notify the server", function() {

                expect(this.fakeServer.requests.length).to.be(1);

                var request = this.fakeServer.requests[0];

                expect(request.url).to.be("/feeds/unsubscribe");
                expect(request.method).to.be("POST");
                expect(request.requestBody).to.be(JSON.stringify({
                            rssUrl: secondRowRssUrl
                        }));
            });
        });
    });
});<commit_msg>oops, fix client-side test<commit_after>define(["feeds", "jquery", "views/feeds.jade", "sinon"], function(feeds, $, feedsView) {

    describe("when the feeds page is shown", function() {

        beforeEach(function() {

            function subscription(name) {
                return {
                    name: name,
                    htmlUrl: "http://server.com/" + name,
                    rssUrl: "http://server.com/" + name + "/rss"
                };
            }

            var templateResult = feedsView({
                    rows: [
                        subscription("first"),
                        subscription("second"),
                        subscription("third")
                    ]
                });

            this.fixture.append(templateResult);

            feeds.initialize(this.fixture);
        });

        describe("when the unsubscribe button is clicked", function() {

            var secondRow;
            var secondRowRssUrl;

            beforeEach(function() {

                this.fakeServer = this.sinon.useFakeXMLHttpRequest();

                secondRow = $(".js-subscription:eq(1)", this.fixture);
                secondRowRssUrl = secondRow.data("rssurl");

                expect(secondRow.length).to.be(1);

                this.fixtureContainsSecondRow = function() {
                    return jQuery.contains(this.fixture[0], secondRow[0]);
                };

                expect(this.fixtureContainsSecondRow()).to.be(true);
                expect(secondRowRssUrl).to.be("http://server.com/second/rss");

                secondRow.find("a.js-unsubscribe").click();
            });

            it("when the request is complete, it will hide the row ", function() {

                this.fakeServer.requests[0].respond(200);

                expect(this.fixtureContainsSecondRow()).to.be(false);
            });

            it("will notify the server", function() {

                expect(this.fakeServer.requests.length).to.be(1);

                var request = this.fakeServer.requests[0];

                expect(request.url).to.be("/feeds/unsubscribe");
                expect(request.method).to.be("POST");
                expect(request.requestBody).to.be(JSON.stringify({
                            rssUrl: secondRowRssUrl
                        }));
            });
        });
    });
});<|endoftext|>


<commit_before>// second post
var car = new Object();
car.type = "sedan";
car.brand = "BMW";
car.topVelocity = 261;

// this is perfectly possible with objects.. but you will run into problems when you do that with primitive types

var array = new Array(23,34); // array anti pattern output [23,34]
var array = new Array(23); // output [ , , , , , , , , , , , , , , , , , , , , , , ]

// go on with what is supposed to be a best practice for pattern with object literals
// JSON notation style
var car = {
    "type":"sedan",
    "brand":"BMW",
    "topVelocity":261
}

var array = [23,24] // output [23,24]
var array = [23] // output [23]

var myObj={
    'varOne':'One',
    'methodOne':function(){ alert('methodOne has been called!')}
}
myObj.methodOne();<commit_msg>Bug fix<commit_after><|endoftext|>


<commit_before> /* ===========================================================
 * bootstrap-modalmanager.js
 * ===========================================================
 * Copyright 2012 Jordan Schroter.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function($){

	"use strict"; // jshint ;_;

	var baseModalzIndex, baseModalAbszIndex, baseBackdropzIndex, baseBackdropAbszIndex,	zIndexFactor;

	$(function(){
		var $baseModal = $('
').appendTo('body'),
			$baseBackdrop = $('
').appendTo('body'),
			$baseModalAbs = $('
').appendTo('body'),
			$baseBackdropAbs = $('
').appendTo('body');

		baseModalzIndex = +$baseModal.css('z-index'),
		baseModalAbszIndex = +$baseModalAbs.css('z-index'),
		baseBackdropzIndex = +$baseBackdrop.css('z-index'),
		baseBackdropAbszIndex = +$baseBackdropAbs.css('z-index'),
		zIndexFactor = baseModalzIndex - baseBackdropzIndex;

		$baseModal.remove();
		$baseBackdrop.remove();
		$baseModalAbs.remove();
		$baseBackdropAbs.remove();
		$baseBackdrop = $baseModal = $baseModalAbs = $baseBackdrop = null;
	});

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	}

	window.ModalManager = ModalManager;

	ModalManager.prototype = {

		constructor: ModalManager,

		init: function(element, options){
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.isBody = this.$element[0] === $('body')[0];

			this.$container = this.$element.find('.modal-container');
			this.$parent = this.$container.length ? this.$container : this.$element;

			this.$element.toggleClass('has-modal-container', !!this.$container.length);
		},

		createModal: function(element, options){
			$(element).modal($.extend({ manager: this }, options));
		},

		appendModal: function(modal){
			this.stack.push(modal);

			var that = this;

			modal.$element.on('show.modalmanager', function(e){
				modal.isShown = true;

				that.$element
					.toggleClass('modal-open', that.hasOpenModal())
					.toggleClass('page-overflow', $(window).height() < that.$element.height());

				var $scrollElement = (that.$container.length ? that.$container :
					(that.isBody ? $(window) : that.$element));

				var modalOverflow = $(window).height() < modal.$element.height() || modal.options.modalOverflow;

				modal.$element
					.toggleClass('modal-overflow', modalOverflow)
					.css('margin-top', $scrollElement.scrollTop() - (modalOverflow ? 0 : modal.$element.height()/2))
					.css('z-index', (!that.isBody ? baseModalAbszIndex : baseModalzIndex)
						+ (zIndexFactor * that.getIndexOfModal(modal)));

				that.backdrop(modal, function () {
					var transition = $.support.transition && modal.$element.hasClass('fade')

					modal.$parent =  modal.$element.parent();
					if (!modal.$parent.length || modal.$parent[0] !== that.$parent[0]) {
						modal.$element.detach().appendTo(that.$parent);
					}

					modal.$element.show();

					if (transition) {
						modal.$element[0].style.display = 'run-in';
						modal.$element[0].offsetWidth;
						modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
					}

					modal.$element
						.addClass('in')
						.attr('aria-hidden', false)
						.toggleClass('modal-absolute', !that.isBody);

					var complete = function(){
						that.setFocus();
						modal.$element.triggerHandler('shown');
					}

					transition ?
						modal.$element.one($.support.transition.end, complete) :
						complete();
				});
			});

			modal.$element.on('hidden.modalmanager', function(e){
				that.backdrop(modal);

				if (modal.$backdrop){
					$.support.transition && modal.$element.hasClass('fade')?
						modal.$backdrop.one($.support.transition.end, function(){ that.destroyModal(modal) }) :
						that.destroyModal(modal);
				} else {
					that.destroyModal(modal);
				}

			});

			modal.$element.on('destroy.modalmanager', function(e){
				that.removeModal(modal);
			});
		},

		destroyModal: function(modal){
			modal.destroy();
			var hasOpenModal = this.hasOpenModal();
			this.$element.toggleClass('modal-open', hasOpenModal);
			if (!hasOpenModal){
				this.$element.removeClass('page-overflow');
			}
			this.setFocus();
		},

		hasOpenModal: function(){
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) return true;
			}
			return false;
		},

		setFocus: function () {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			topModal && topModal.$element.focus();
		},

		removeModal: function(modal){
			modal.$element.off('.modalmanager');
			if (modal.$backdrop) this.removeBackdrop.call(modal);
			this.stack.splice(this.getIndexOfModal(modal), 1);
		},

		getModalAt: function(index){
			return this.stack[index];
		},

		getIndexOfModal: function(modal){
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},

		removeBackdrop: function (modal) {
			modal.$backdrop.remove();
			modal.$backdrop = null;
		},

		createBackdrop: function(animate){
			var $backdrop;

			if (!this.isLoading) {
				$backdrop =  $('
')
					.appendTo(this.$parent)
					.toggleClass('modal-absolute', !this.isBody);
			} else {
				$backdrop = this.$loading;
				$backdrop.off('.modalmanager');
				this.$spinner.remove();
				this.isLoading = false;
				this.$loading = this.$spinner = null;
			}

			return $backdrop
		},

		backdrop: function (modal, callback) {
			var animate = modal.$element.hasClass('fade') ? 'fade' : '',
				showBackdrop = $.extend({}, this.options, modal.options).backdrop;

			if (modal.isShown && showBackdrop) {
				var doAnimate = $.support.transition && animate && !this.isLoading;

				modal.$backdrop = this.createBackdrop(animate);

				modal.$backdrop.css('z-index',
						(!this.isBody ? baseBackdropAbszIndex : baseBackdropzIndex)
						+ (zIndexFactor * this.getIndexOfModal(modal)));

				if (modal.options.backdrop != 'static') {
					modal.$backdrop.on('click.modal', $.proxy(modal.hide, modal));
				}

				if (doAnimate) modal.$backdrop[0].offsetWidth // force reflow

				modal.$backdrop.addClass('in')

				doAnimate ?
				modal.$backdrop.one($.support.transition.end, callback) :
				callback();

			} else if (!modal.isShown && modal.$backdrop) {
				modal.$backdrop.removeClass('in');

				var that = this;
				$.support.transition && modal.$element.hasClass('fade')?
					modal.$backdrop.one($.support.transition.end, function(){ that.removeBackdrop(modal) }) :
					that.removeBackdrop(modal);

			} else if (callback) {
				callback();
			}
		},

		removeLoading: function(){
			this.$loading && this.$loading.remove();
			this.$loading = null;
			this.isLoading = false;
		},

		loading: function(callback){
			callback = callback || function(){ };

			this.$element.toggleClass('modal-open', !this.isLoading || this.hasOpenModal());

			if (!this.isLoading) {

				this.$loading = this.createBackdrop('fade');

				this.$loading[0].offsetWidth // force reflow

				this.$loading
					.css('z-index',
						(!this.isBody ? baseBackdropAbszIndex : baseBackdropzIndex)
						+ (zIndexFactor * this.stack.length))
					.on('click.modalmanager', $.proxy(this.loading, this))
					.addClass('in');

				var $scrollElement = (this.$container.length ? this.$container :
						(this.isBody ? $(window) : this.$element));

				this.$spinner = $('
')
					.append(this.options.spinner)
					.css('z-index', this.$loading.css('z-index'))
					.css('margin-top', $scrollElement.scrollTop())
					.appendTo(this.$parent)
					.addClass('in');

				this.isLoading = true;

				$.support.transition ?
				this.$loading.one($.support.transition.end, callback) :
				callback();

			} else if (this.isLoading && this.$loading) {
				this.$loading.removeClass('in');

				if (this.$spinner) this.$spinner.remove();

				var that = this;
				$.support.transition ?
					this.$loading.one($.support.transition.end, function(){ that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		},

		toggleLoading: function(callback){ this.loading(callback); }
	}

	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option) {
		return this.each(function () {
			var $this = $(this)
			, data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, options)))
			if (typeof option == 'string') data[option]()
		})
	}

	$.fn.modalmanager.defaults = {
		backdrop: true,
		spinner: '

'
	}

	$.fn.modalmanager.Constructor = ModalManager

	// Create a default global modal manager
	$(function(){
		window.GlobalModalManager = new ModalManager('body');
	})

}(jQuery);<commit_msg>hack to prevent other components from triggering the modalmanager<commit_after> /* ===========================================================
 * bootstrap-modalmanager.js
 * ===========================================================
 * Copyright 2012 Jordan Schroter.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ========================================================== */

!function($){

	"use strict"; // jshint ;_;

	var baseModalzIndex, baseModalAbszIndex, baseBackdropzIndex, baseBackdropAbszIndex,	zIndexFactor;

	$(function(){
		var $baseModal = $('
').appendTo('body'),
			$baseBackdrop = $('
').appendTo('body'),
			$baseModalAbs = $('
').appendTo('body'),
			$baseBackdropAbs = $('
').appendTo('body');

		baseModalzIndex = +$baseModal.css('z-index'),
		baseModalAbszIndex = +$baseModalAbs.css('z-index'),
		baseBackdropzIndex = +$baseBackdrop.css('z-index'),
		baseBackdropAbszIndex = +$baseBackdropAbs.css('z-index'),
		zIndexFactor = baseModalzIndex - baseBackdropzIndex;

		$baseModal.remove();
		$baseBackdrop.remove();
		$baseModalAbs.remove();
		$baseBackdropAbs.remove();
		$baseBackdrop = $baseModal = $baseModalAbs = $baseBackdrop = null;
	});

	/* MODAL MANAGER CLASS DEFINITION
	* ====================== */

	var ModalManager = function (element, options) {
		this.init(element, options);
	}

	window.ModalManager = ModalManager;

	ModalManager.prototype = {

		constructor: ModalManager,

		init: function(element, options){
			this.$element = $(element);
			this.options = $.extend({}, $.fn.modalmanager.defaults, this.$element.data(), typeof options == 'object' && options);
			this.stack = [];
			this.isBody = this.$element[0] === $('body')[0];

			this.$container = this.$element.find('.modal-container');
			this.$parent = this.$container.length ? this.$container : this.$element;

			this.$element.toggleClass('has-modal-container', !!this.$container.length);
		},

		createModal: function(element, options){
			$(element).modal($.extend({ manager: this }, options));
		},

		appendModal: function(modal){
			this.stack.push(modal);

			var that = this;

			modal.$element.on('show.modalmanager', targetIsModal(function(e){
				modal.isShown = true;

				that.$element
					.toggleClass('modal-open', that.hasOpenModal())
					.toggleClass('page-overflow', $(window).height() < that.$element.height());

				var $scrollElement = (that.$container.length ? that.$container :
					(that.isBody ? $(window) : that.$element));

				var modalOverflow = $(window).height() < modal.$element.height() || modal.options.modalOverflow;

				modal.$element
					.toggleClass('modal-overflow', modalOverflow)
					.css('margin-top', $scrollElement.scrollTop() - (modalOverflow ? 0 : modal.$element.height()/2))
					.css('z-index', (!that.isBody ? baseModalAbszIndex : baseModalzIndex)
						+ (zIndexFactor * that.getIndexOfModal(modal)));

				that.backdrop(modal, function () {
					var transition = $.support.transition && modal.$element.hasClass('fade')

					modal.$parent =  modal.$element.parent();
					if (!modal.$parent.length || modal.$parent[0] !== that.$parent[0]) {
						modal.$element.detach().appendTo(that.$parent);
					}

					modal.$element.show();

					if (transition) {
						modal.$element[0].style.display = 'run-in';
						modal.$element[0].offsetWidth;
						modal.$element.one($.support.transition.end, function () { modal.$element[0].style.display = 'block' });
					}

					modal.$element
						.addClass('in')
						.attr('aria-hidden', false)
						.toggleClass('modal-absolute', !that.isBody);

					var complete = function(){
						that.setFocus();
						modal.$element.triggerHandler('shown');
					}

					transition ?
						modal.$element.one($.support.transition.end, complete) :
						complete();
				});
			}));

			modal.$element.on('hidden.modalmanager', targetIsModal(function(e){
				that.backdrop(modal);

				if (modal.$backdrop){
					$.support.transition && modal.$element.hasClass('fade')?
						modal.$backdrop.one($.support.transition.end, function(){ that.destroyModal(modal) }) :
						that.destroyModal(modal);
				} else {
					that.destroyModal(modal);
				}

			}));

			modal.$element.on('destroy.modalmanager', targetIsModal(function(e){
				that.removeModal(modal);
			}));
		},

		destroyModal: function(modal){
			modal.destroy();
			var hasOpenModal = this.hasOpenModal();
			this.$element.toggleClass('modal-open', hasOpenModal);
			if (!hasOpenModal){
				this.$element.removeClass('page-overflow');
			}
			this.setFocus();
		},

		hasOpenModal: function(){
			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) return true;
			}
			return false;
		},

		setFocus: function () {
			var topModal;

			for (var i = 0; i < this.stack.length; i++){
				if (this.stack[i].isShown) topModal = this.stack[i];
			}

			topModal && topModal.$element.focus();
		},

		removeModal: function(modal){
			modal.$element.off('.modalmanager');
			if (modal.$backdrop) this.removeBackdrop.call(modal);
			this.stack.splice(this.getIndexOfModal(modal), 1);
		},

		getModalAt: function(index){
			return this.stack[index];
		},

		getIndexOfModal: function(modal){
			for (var i = 0; i < this.stack.length; i++){
				if (modal === this.stack[i]) return i;
			}
		},

		removeBackdrop: function (modal) {
			modal.$backdrop.remove();
			modal.$backdrop = null;
		},

		createBackdrop: function(animate){
			var $backdrop;

			if (!this.isLoading) {
				$backdrop =  $('
')
					.appendTo(this.$parent)
					.toggleClass('modal-absolute', !this.isBody);
			} else {
				$backdrop = this.$loading;
				$backdrop.off('.modalmanager');
				this.$spinner.remove();
				this.isLoading = false;
				this.$loading = this.$spinner = null;
			}

			return $backdrop
		},

		backdrop: function (modal, callback) {
			var animate = modal.$element.hasClass('fade') ? 'fade' : '',
				showBackdrop = $.extend({}, this.options, modal.options).backdrop;

			if (modal.isShown && showBackdrop) {
				var doAnimate = $.support.transition && animate && !this.isLoading;

				modal.$backdrop = this.createBackdrop(animate);

				modal.$backdrop.css('z-index',
						(!this.isBody ? baseBackdropAbszIndex : baseBackdropzIndex)
						+ (zIndexFactor * this.getIndexOfModal(modal)));

				if (modal.options.backdrop != 'static') {
					modal.$backdrop.on('click.modal', $.proxy(modal.hide, modal));
				}

				if (doAnimate) modal.$backdrop[0].offsetWidth // force reflow

				modal.$backdrop.addClass('in')

				doAnimate ?
				modal.$backdrop.one($.support.transition.end, callback) :
				callback();

			} else if (!modal.isShown && modal.$backdrop) {
				modal.$backdrop.removeClass('in');

				var that = this;
				$.support.transition && modal.$element.hasClass('fade')?
					modal.$backdrop.one($.support.transition.end, function(){ that.removeBackdrop(modal) }) :
					that.removeBackdrop(modal);

			} else if (callback) {
				callback();
			}
		},

		removeLoading: function(){
			this.$loading && this.$loading.remove();
			this.$loading = null;
			this.isLoading = false;
		},

		loading: function(callback){
			callback = callback || function(){ };

			this.$element.toggleClass('modal-open', !this.isLoading || this.hasOpenModal());

			if (!this.isLoading) {

				this.$loading = this.createBackdrop('fade');

				this.$loading[0].offsetWidth // force reflow

				this.$loading
					.css('z-index',
						(!this.isBody ? baseBackdropAbszIndex : baseBackdropzIndex)
						+ (zIndexFactor * this.stack.length))
					.on('click.modalmanager', $.proxy(this.loading, this))
					.addClass('in');

				var $scrollElement = (this.$container.length ? this.$container :
						(this.isBody ? $(window) : this.$element));

				this.$spinner = $('
')
					.append(this.options.spinner)
					.css('z-index', this.$loading.css('z-index'))
					.css('margin-top', $scrollElement.scrollTop())
					.appendTo(this.$parent)
					.addClass('in');

				this.isLoading = true;

				$.support.transition ?
				this.$loading.one($.support.transition.end, callback) :
				callback();

			} else if (this.isLoading && this.$loading) {
				this.$loading.removeClass('in');

				if (this.$spinner) this.$spinner.remove();

				var that = this;
				$.support.transition ?
					this.$loading.one($.support.transition.end, function(){ that.removeLoading() }) :
					that.removeLoading();

			} else if (callback) {
				callback(this.isLoading);
			}
		},

		toggleLoading: function(callback){ this.loading(callback); }
	}

	/* PRIVATE METHODS
	* ======================= */

	// make sure the event target is the modal itself in order to prevent
	// other components such as tabsfrom triggering the modal manager.
	// if Boostsrap namespaced events, this would not be needed.
	function targetIsModal(callback){
		return function(e){
			if (this === e.target){
				callback.apply(this, arguments);
			}
		}
	}

	/* MODAL MANAGER PLUGIN DEFINITION
	* ======================= */

	$.fn.modalmanager = function (option) {
		return this.each(function () {
			var $this = $(this)
			, data = $this.data('modalmanager');

			if (!data) $this.data('modalmanager', (data = new ModalManager(this, options)))
			if (typeof option == 'string') data[option]()
		})
	}

	$.fn.modalmanager.defaults = {
		backdrop: true,
		spinner: '

'
	}

	$.fn.modalmanager.Constructor = ModalManager

	// Create a default global modal manager
	$(function(){
		window.GlobalModalManager = new ModalManager('body');
	})

}(jQuery);<|endoftext|>


<commit_before>if (typeof define !== 'function') { var define = require('amdefine')(module) }

define([
  './keyboard-util'
], function(
  keyboardUtil
) {

  function ShortcutManager() {
    keyboardUtil.addKeyDownListener(this._keyDown.bind(this));
    keyboardUtil.addKeyUpListener(this._keyUp.bind(this));
  }
  ShortcutManager.prototype = {

    _pressedKeys: [],
    _registeredShortcuts: [],

    registerShortcut: function(shortcut, callback) {
      this._registeredShortcuts.push([shortcut, callback]);
    },

    _keyDown: function(key) {
      this._pressedKeys.push(key);
    },

    _keyUp: function(keyName) {
      if (keyName != 'Meta') {
        return;
      }
      var callback = this._getCallbackForPressedKeys(this._pressedKeys);
      callback && callback();
      this._pressedKeys = [];
    },

    _getCallbackForPressedKeys: function(pressedKeys) {
      var found = this._registeredShortcuts.filter(function(shortcut) {
        return shortcut[0].join('+') == pressedKeys.join('+');
      });
      if (found.length) {
        // Use the first shortcut map found.
        var firstShortcut = found[0];
        return firstShortcut[1];
      }
      return null;
    }
  };

  return ShortcutManager;
});
<commit_msg>Init complex types in constructor.<commit_after>if (typeof define !== 'function') { var define = require('amdefine')(module) }

define([
  './keyboard-util'
], function(
  keyboardUtil
) {

  function ShortcutManager() {
    this._pressedKeys = [];
    this._registeredShortcuts = [];
    keyboardUtil.addKeyDownListener(this._keyDown.bind(this));
    keyboardUtil.addKeyUpListener(this._keyUp.bind(this));
  }
  ShortcutManager.prototype = {

    _pressedKeys: null,
    _registeredShortcuts: null,

    registerShortcut: function(shortcut, callback) {
      this._registeredShortcuts.push([shortcut, callback]);
    },

    _keyDown: function(key) {
      this._pressedKeys.push(key);
    },

    _keyUp: function(keyName) {
      if (keyName != 'Meta') {
        return;
      }
      var callback = this._getCallbackForPressedKeys(this._pressedKeys);
      callback && callback();
      this._pressedKeys = [];
    },

    _getCallbackForPressedKeys: function(pressedKeys) {
      var found = this._registeredShortcuts.filter(function(shortcut) {
        return shortcut[0].join('+') == pressedKeys.join('+');
      });
      if (found.length) {
        // Use the first shortcut map found.
        var firstShortcut = found[0];
        return firstShortcut[1];
      }
      return null;
    }
  };

  return ShortcutManager;
});
<|endoftext|>


<commit_before>/* eslint-env node, es6 */

'use strict';

const
  DOC_ROOT = __dirname,
  PORT = 8080,

  MODULE_PACKAGES = [
    'jasmine-core',
    'test-page-loader',
    'anim-event',
    'plain-draggable'
  ],

  http = require('http'),
  staticAlias = require('node-static-alias'),
  logger = (() => {
    const log4js = require('log4js');
    log4js.configure({
      appenders: {
        out: {
          type: 'console',
          layout: {
            type: 'pattern',
            pattern: '%[[%r]%] %m' // Super simple format
          }
        }
      },
      categories: {default: {appenders: ['out'], level: 'info'}}
    });
    return log4js.getLogger('node-static-alias');
  })();

http.createServer((request, response) => {
  request.addListener('end', () => {
    (new staticAlias.Server(DOC_ROOT, {
      cache: false,
      headers: {'Cache-Control': 'no-cache, must-revalidate'},
      alias:
        MODULE_PACKAGES.map(packageName =>
          ({ // node_modules
            match: new RegExp(`^/${packageName}/.+`),
            serve: `${require.resolve(packageName).replace(
              // Include `packageName` for nested `node_modules`
              new RegExp(`^(.*[/\\\\]node_modules)[/\\\\]${packageName}[/\\\\].*$`), '$1')}<% reqPath %>`,
            allowOutside: true
          })
        ).concat([
          {
            match: /^\/src/,
            serve: '..<% reqPath %>',
            allowOutside: true
          }
        ]),
      logger
    }))
      .serve(request, response, e => {
        if (e) {
          response.writeHead(e.status, e.headers);
          logger.error('(%s) %s', request.url, response.statusCode);
          if (e.status === 404) {
            response.end('Not Found');
          }
        } else {
          logger.info('(%s) %s', request.url, response.statusCode);
        }
      });
  }).resume();
}).listen(PORT);

console.log(`START: http://localhost:${PORT}/\nROOT: ${DOC_ROOT}`);
console.log('(^C to stop)');
<commit_msg>Fix: It is constructed again.<commit_after>/* eslint-env node, es6 */

'use strict';

const
  DOC_ROOT = __dirname,
  PORT = 8080,

  MODULE_PACKAGES = [
    'jasmine-core',
    'test-page-loader',
    'anim-event',
    'plain-draggable'
  ],

  logger = (() => {
    const log4js = require('log4js');
    log4js.configure({
      appenders: {
        out: {
          type: 'console',
          layout: {
            type: 'pattern',
            pattern: '%[[%r]%] %m' // Super simple format
          }
        }
      },
      categories: {default: {appenders: ['out'], level: 'info'}}
    });
    return log4js.getLogger('node-static-alias');
  })(),

  staticAlias = new (require('node-static-alias')).Server(DOC_ROOT, {
    cache: false,
    headers: {'Cache-Control': 'no-cache, must-revalidate'},
    alias:
      MODULE_PACKAGES.map(packageName =>
        ({ // node_modules
          match: new RegExp(`^/${packageName}/.+`),
          serve: `${require.resolve(packageName).replace(
            // Include `packageName` for nested `node_modules`
            new RegExp(`^(.*[/\\\\]node_modules)[/\\\\]${packageName}[/\\\\].*$`), '$1')}<% reqPath %>`,
          allowOutside: true
        })
      ).concat([
        {
          match: /^\/src/,
          serve: '..<% reqPath %>',
          allowOutside: true
        }
      ]),
    logger
  });

require('http').createServer((request, response) => {
  request.addListener('end', () => {
    staticAlias.serve(request, response, error => {
      if (error) {
        response.writeHead(error.status, error.headers);
        logger.error('(%s) %s', request.url, response.statusCode);
        if (error.status === 404) {
          response.end('Not Found');
        }
      } else {
        logger.info('(%s) %s', request.url, response.statusCode);
      }
    });
  }).resume();
}).listen(PORT);

console.log(`START: http://localhost:${PORT}/\nROOT: ${DOC_ROOT}`);
console.log('(^C to stop)');
<|endoftext|>


<commit_before><commit_msg>Remove non-common properties from hardcoded hierarchy<commit_after><|endoftext|>