<commit_before>var XML_EXPENSE_ADD_URL = null;
var ADD_EXPENSES_TABLE = null;
var LAST_EXPENSE_ID = 0;

function readExpenseDate(expense) {
	var date_input = expense.find("input.date-input");
	if (date_input.length != 1) {
		return undefined;
	}
	if (date_input[0].type == "date") {
		if (date_input.val().match('^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$')) {
			return date_input.val();
		}
	} else { //text
		var m = date_input.val().match('^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$');
		if (m) {
			return m[3] + '-' + m[2] + '-' + m[1];
		}
	}
	return undefined;
}

function readExpenseTitle(expense) {
	var title_input = expense.find("input.title-input");
	if (title_input.length != 1 || title_input.val().length == 0) {
		return undefined;
	}
	return title_input.val();
}

function readExpensePrice(expense) {
	var price_input = expense.find("input.price-input");
	if (price_input.length != 1
				|| ! price_input.val().match('^[-+]?(([0-9]{1,3}([, ][0-9]{3})*|[0-9]+)(.[0-9]?[0-9]?)?)$')
				|| parseFloat(price_input.val().replace(/ /g, '').replace(/,/g, '')) == 0) {
		return undefined;
	}
	return parseFloat(price_input.val().replace(/ /g, '').replace(/,/g, ''));
}

function isFilledExpense(expense) {
	// Given an expense, return true is it is fully and correctly filled

	var expense_date = readExpenseDate(expense);
	if (! expense_date) {
		return undefined;
	}

	var expense_title = readExpenseTitle(expense);
	if (! expense_title) {
		return undefined;
	}

	var expense_price = readExpensePrice(expense);
	if (! expense_price) {
		return undefined;
	}
	return {date: expense_date, title: expense_title, price: expense_price};
}

function reactOnExpenseChange() {
	// Automaticcaly append expenses when the last line is fully filled
	// Only the last line is checked

	var expense = $(this).parent().parent();
	// expense is the last expense of the table is not equivalent to
	// data-expense-identifier == LAST_EXPENSE_ID as the expense could have been deleted..
	if (expense[0] == ADD_EXPENSES_TABLE.children().last()[0] && isFilledExpense(expense)) {
		appendExpense();
	}
}

function reactOnPriceFocusOut() {
	// Automatically format the price on focus out action

	var price_value = readExpensePrice($(this).parent().parent());
	if (! price_value) {
		return false;
	}

	var price_value_str = $(this).val();
	var price_value_new_str = price_value.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});

	var language = window.navigator.userLanguage || window.navigator.language;
	if (language.toLowerCase() == 'fr' || language.toLowerCase() == 'fr-fr') {
		price_value_new_str = price_value_new_str.replace(/,/g, ' ');
	}
	if (price_value_str != price_value_new_str) {
		$(this).val(price_value_new_str);
	}
}

function reactOnPriceFocus() {
	// Automatically format the price on focus in order to ease the modification

	var price_value = readExpensePrice($(this).parent().parent());
	if (! price_value) {
		return false;
	}

	var price_value_str = $(this).val();
	var price_value_new_str = price_value.toFixed(2);
	if (price_value_str != price_value_new_str) {
		$(this).val(price_value_new_str);
	}
}

function appendExpense() {
	// Append an empty expense in the form

	LAST_EXPENSE_ID++;
	var expense = $("<tr/>");
	expense.addClass('expense-edit');
	expense.attr("data-expense-identifier", LAST_EXPENSE_ID);

	var date_td = $("<td/>");
	var date_input_desc = $("<span/>");
	date_input_desc.addClass("glyphicon glyphicon-calendar");
	var date_input = $("<input/>");
	date_input.addClass("date-input");
	date_input.attr("required", "");
	date_input.attr("type", "date");
	if (date_input[0].type == "text") //date type not supported (HTML5)
	{
		date_input.attr("placeholder", "dd/mm/yyyy");
		date_input.datepicker({dateFormat: "dd/mm/yy"});
	}
	date_input.keyup(reactOnExpenseChange);
	date_td.append(date_input_desc);
	date_td.append(date_input);
	expense.append(date_td);

	var title_td = $("<td/>");
	var title_input = $("<input/>");
	title_input.addClass("title-input");
	title_input.attr("required", "");
	title_input.attr("size", "50");
	title_input.attr("type", "text");
	title_input.attr("placeholder", "Short description of the expense");
	title_input.keyup(reactOnExpenseChange);
	title_td.append(title_input);
	expense.append(title_td);

	var price_td = $("<td/>");
	var price_input = $("<input/>");
	price_input.addClass("price-input");
	price_input.attr("required", "");
	price_input.attr("size", "10");
	price_input.attr("type", "text");
	price_input.attr("pattern", "[-+]?(\\d{1,3}([\\s,]\\d{3})*|\\d+)(\\.\\d{0,2})?"); // 1000.00, 1 000.00, 1000 are valids
	price_input.attr("placeholder", "0.00");
	price_input.keyup(reactOnExpenseChange);
	price_input.focus(reactOnPriceFocus);
	price_input.focusout(reactOnPriceFocusOut);
	price_td.append(price_input);
	expense.append(price_td);

	var categories_td = $("<td/>");
	expense.append(categories_td);

	var actions_td = $("<td/>");
	var delete_img = $("<span/>");
	delete_img.addClass("glyphicon glyphicon-trash");
	delete_img.attr("style", "cursor:pointer;");
	delete_img.attr("title", "Delete this expense");
	delete_img.click(function() {
		$(this).parent().parent().remove();
		if (ADD_EXPENSES_TABLE.children().length == 0) {
			appendExpense();
		}
	});
	actions_td.append(delete_img);
	var send_img = $("<span/>");
	send_img.addClass("glyphicon glyphicon-ok");
	send_img.attr("style", "cursor:pointer;");
	send_img.attr("title", "Save this expense");
	send_img.click(ajaxSaveNewExpense);
	actions_td.append(send_img);
	expense.append(actions_td);

	ADD_EXPENSES_TABLE.append(expense);
}

function initAddExpensesTable(addExpenseUrl) {
	// Initialize expenses table

	XML_EXPENSE_ADD_URL = addExpenseUrl;
	ADD_EXPENSES_TABLE = $('table#add_expenses_table tbody');
	ADD_EXPENSES_TABLE.html("");
	appendExpense();
	$("button#submit-expenses").click(ajaxSaveAllExpenses);
}

/**
 * AJAX query to save all expenses
 */
function ajaxSaveAllExpenses()
{
	if (! XML_EXPENSE_ADD_URL)
	{
		alert("Unable to find the url");
		return;
	}

	var expenses = ADD_EXPENSES_TABLE.find("tr");
	for (var i = 0 ; i != expenses.length ; i++) {
		var expense = $(expenses[i]);
		var expense_details = isFilledExpense(expense);
		if (expense_details && (expense.hasClass('expense-edit') || expense.hasClass('expense-fail'))) {
			expense.find("span.glyphicon-ok").click();
		}
	}
}

/**
 * AJAX query to save new expense
 */
function ajaxSaveNewExpense()
{
	if (! XML_EXPENSE_ADD_URL)
	{
		alert("Unable to find the url");
		return;
	}

	var expense = $(this).parent().parent();
	if (! expense.hasClass('expense-edit') && ! expense.hasClass('expense-fail'))
	{
		alert("The operation cannot be run on this expense");
		return;
	}
	var expense_details = isFilledExpense(expense);
	if (! expense_details) {
		alert("Please fill the expense before saving it");
		return;
	}

	expense.removeClass('expense-edit');
	expense.addClass('expense-wait');
	$.ajax({
		type: "post",
		url: XML_EXPENSE_ADD_URL,
		data:
		{
			_xsrf: getCookie("_xsrf"),
			client_id: expense.attr('data-expense-identifier'),
			title: expense_details['title'],
			date: expense_details['date'],
			price: expense_details['price'],
		},
		dataType: "xml",
		success: function(xml)
		{
			expense.removeClass('expense-wait');
			expense.addClass('expense-success');
		},
		error: function(xhr)
		{
			expense.removeClass("expense-wait");
			expense.addClass('expense-fail');
			alert($(xhr.responseText).text());
		}
	});
}

<commit_msg>[bug][expenses] Changing the date is not triggering the creation of a new line<commit_after>var XML_EXPENSE_ADD_URL = null;
var ADD_EXPENSES_TABLE = null;
var LAST_EXPENSE_ID = 0;

function readExpenseDate(expense) {
	var date_input = expense.find("input.date-input");
	if (date_input.length != 1) {
		return undefined;
	}
	if (date_input[0].type == "date") {
		if (date_input.val().match('^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$')) {
			return date_input.val();
		}
	} else { //text
		var m = date_input.val().match('^([0-9]{1,2})/([0-9]{1,2})/([0-9]{4})$');
		if (m) {
			return m[3] + '-' + m[2] + '-' + m[1];
		}
	}
	return undefined;
}

function readExpenseTitle(expense) {
	var title_input = expense.find("input.title-input");
	if (title_input.length != 1 || title_input.val().length == 0) {
		return undefined;
	}
	return title_input.val();
}

function readExpensePrice(expense) {
	var price_input = expense.find("input.price-input");
	if (price_input.length != 1
				|| ! price_input.val().match('^[-+]?(([0-9]{1,3}([, ][0-9]{3})*|[0-9]+)(.[0-9]?[0-9]?)?)$')
				|| parseFloat(price_input.val().replace(/ /g, '').replace(/,/g, '')) == 0) {
		return undefined;
	}
	return parseFloat(price_input.val().replace(/ /g, '').replace(/,/g, ''));
}

function isFilledExpense(expense) {
	// Given an expense, return true is it is fully and correctly filled

	var expense_date = readExpenseDate(expense);
	if (! expense_date) {
		return undefined;
	}

	var expense_title = readExpenseTitle(expense);
	if (! expense_title) {
		return undefined;
	}

	var expense_price = readExpensePrice(expense);
	if (! expense_price) {
		return undefined;
	}
	return {date: expense_date, title: expense_title, price: expense_price};
}

function reactOnExpenseChange() {
	// Automaticcaly append expenses when the last line is fully filled
	// Only the last line is checked

	var expense = $(this).parent().parent();
	// expense is the last expense of the table is not equivalent to
	// data-expense-identifier == LAST_EXPENSE_ID as the expense could have been deleted..
	if (expense[0] == ADD_EXPENSES_TABLE.children().last()[0] && isFilledExpense(expense)) {
		appendExpense();
	}
}

function reactOnPriceFocusOut() {
	// Automatically format the price on focus out action

	var price_value = readExpensePrice($(this).parent().parent());
	if (! price_value) {
		return false;
	}

	var price_value_str = $(this).val();
	var price_value_new_str = price_value.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});

	var language = window.navigator.userLanguage || window.navigator.language;
	if (language.toLowerCase() == 'fr' || language.toLowerCase() == 'fr-fr') {
		price_value_new_str = price_value_new_str.replace(/,/g, ' ');
	}
	if (price_value_str != price_value_new_str) {
		$(this).val(price_value_new_str);
	}
}

function reactOnPriceFocus() {
	// Automatically format the price on focus in order to ease the modification

	var price_value = readExpensePrice($(this).parent().parent());
	if (! price_value) {
		return false;
	}

	var price_value_str = $(this).val();
	var price_value_new_str = price_value.toFixed(2);
	if (price_value_str != price_value_new_str) {
		$(this).val(price_value_new_str);
	}
}

function appendExpense() {
	// Append an empty expense in the form

	LAST_EXPENSE_ID++;
	var expense = $("<tr/>");
	expense.addClass('expense-edit');
	expense.attr("data-expense-identifier", LAST_EXPENSE_ID);

	var date_td = $("<td/>");
	var date_input_desc = $("<span/>");
	date_input_desc.addClass("glyphicon glyphicon-calendar");
	var date_input = $("<input/>");
	date_input.addClass("date-input");
	date_input.attr("required", "");
	date_input.attr("type", "date");
	if (date_input[0].type == "text") //date type not supported (HTML5)
	{
		date_input.attr("placeholder", "dd/mm/yyyy");
		date_input.datepicker({dateFormat: "dd/mm/yy"});
	}
	date_input.change(reactOnExpenseChange);
	date_input.keyup(reactOnExpenseChange);
	date_td.append(date_input_desc);
	date_td.append(date_input);
	expense.append(date_td);

	var title_td = $("<td/>");
	var title_input = $("<input/>");
	title_input.addClass("title-input");
	title_input.attr("required", "");
	title_input.attr("size", "50");
	title_input.attr("type", "text");
	title_input.attr("placeholder", "Short description of the expense");
	title_input.keyup(reactOnExpenseChange);
	title_td.append(title_input);
	expense.append(title_td);

	var price_td = $("<td/>");
	var price_input = $("<input/>");
	price_input.addClass("price-input");
	price_input.attr("required", "");
	price_input.attr("size", "10");
	price_input.attr("type", "text");
	price_input.attr("pattern", "[-+]?(\\d{1,3}([\\s,]\\d{3})*|\\d+)(\\.\\d{0,2})?"); // 1000.00, 1 000.00, 1000 are valids
	price_input.attr("placeholder", "0.00");
	price_input.keyup(reactOnExpenseChange);
	price_input.focus(reactOnPriceFocus);
	price_input.focusout(reactOnPriceFocusOut);
	price_td.append(price_input);
	expense.append(price_td);

	var categories_td = $("<td/>");
	expense.append(categories_td);

	var actions_td = $("<td/>");
	var delete_img = $("<span/>");
	delete_img.addClass("glyphicon glyphicon-trash");
	delete_img.attr("style", "cursor:pointer;");
	delete_img.attr("title", "Delete this expense");
	delete_img.click(function() {
		$(this).parent().parent().remove();
		if (ADD_EXPENSES_TABLE.children().length == 0) {
			appendExpense();
		}
	});
	actions_td.append(delete_img);
	var send_img = $("<span/>");
	send_img.addClass("glyphicon glyphicon-ok");
	send_img.attr("style", "cursor:pointer;");
	send_img.attr("title", "Save this expense");
	send_img.click(ajaxSaveNewExpense);
	actions_td.append(send_img);
	expense.append(actions_td);

	ADD_EXPENSES_TABLE.append(expense);
}

function initAddExpensesTable(addExpenseUrl) {
	// Initialize expenses table

	XML_EXPENSE_ADD_URL = addExpenseUrl;
	ADD_EXPENSES_TABLE = $('table#add_expenses_table tbody');
	ADD_EXPENSES_TABLE.html("");
	appendExpense();
	$("button#submit-expenses").click(ajaxSaveAllExpenses);
}

/**
 * AJAX query to save all expenses
 */
function ajaxSaveAllExpenses()
{
	if (! XML_EXPENSE_ADD_URL)
	{
		alert("Unable to find the url");
		return;
	}

	var expenses = ADD_EXPENSES_TABLE.find("tr");
	for (var i = 0 ; i != expenses.length ; i++) {
		var expense = $(expenses[i]);
		var expense_details = isFilledExpense(expense);
		if (expense_details && (expense.hasClass('expense-edit') || expense.hasClass('expense-fail'))) {
			expense.find("span.glyphicon-ok").click();
		}
	}
}

/**
 * AJAX query to save new expense
 */
function ajaxSaveNewExpense()
{
	if (! XML_EXPENSE_ADD_URL)
	{
		alert("Unable to find the url");
		return;
	}

	var expense = $(this).parent().parent();
	if (! expense.hasClass('expense-edit') && ! expense.hasClass('expense-fail'))
	{
		alert("The operation cannot be run on this expense");
		return;
	}
	var expense_details = isFilledExpense(expense);
	if (! expense_details) {
		alert("Please fill the expense before saving it");
		return;
	}

	expense.removeClass('expense-edit');
	expense.addClass('expense-wait');
	$.ajax({
		type: "post",
		url: XML_EXPENSE_ADD_URL,
		data:
		{
			_xsrf: getCookie("_xsrf"),
			client_id: expense.attr('data-expense-identifier'),
			title: expense_details['title'],
			date: expense_details['date'],
			price: expense_details['price'],
		},
		dataType: "xml",
		success: function(xml)
		{
			expense.removeClass('expense-wait');
			expense.addClass('expense-success');
		},
		error: function(xhr)
		{
			expense.removeClass("expense-wait");
			expense.addClass('expense-fail');
			alert($(xhr.responseText).text());
		}
	});
}

<|endoftext|>


<commit_before>var _privateObject;

export default {
  expose(privateObject) {
    _privateObject = privateObject;
  },

  via(publicObject, transform = x => x) {
    return Object.defineProperties(publicObject, Object.keys(_privateObject)
                                                       .reduce((m, n) => {
                                                         m[n] = {
                                                           configurable: true,
                                                           enumerable: true,
                                                           get: () => _privateObject[n],
                                                           set: x => _privateObject[n] = transform(x)
                                                         };

                                                         return m;
                                                       }, {}));
  }
};
<commit_msg>[breaking] Adopt new API<commit_after>var _privateObject;

export default {
  expose(privateObject) {
    _privateObject = privateObject;
  },

  via(publicObject) {
    return (transform = x => x) => {
      return Object.defineProperties(publicObject, Object.keys(_privateObject)
                                                         .reduce((m, n) => {
                                                           m[n] = {
                                                             configurable: true,
                                                             enumerable: true,
                                                             get: () => _privateObject[n],
                                                             set: x => _privateObject[n] = transform(x)
                                                           };

                                                           return m;
                                                         }, {}));
    };
  }
};
<|endoftext|>


<commit_before>/**
 *
 *  -----------------------------------
 *  SocialDig.js - v0.1.0
 *  -----------------------------------
 *
 *  Query data from your social profiles with ease.
 *
 *  https://github.com/kjbrum/SocialDig.js
 *  @license Copyright (c) Kyle Brumm <http://kylebrumm.com>
 *
 */

;
(function(global) {
    var SocialDig = function(settings, cb) {
        return new SocialDig.init(settings, cb);
    }

    SocialDig.prototype = {
        /*********************************************
         * Query the data from the necessary service *
         *********************************************/
        queryData: function() {
            var self = this;
            var container = self.selector;

            // Check the type of selector that was supplied
            if (typeof self.selector === 'string') {
                container = document.querySelector(self.selector);
            }

            // Build the request URL
            switch (self.service) {
                case '500px':
                    self.url = 'https://api.500px.com/v1/photos?consumer_key=' + self.auth + '&feature=user&username=' + self.user + '&image_size=440';
                    break;
                case 'behance':
                    self.url = 'http://www.behance.net/v2/users/' + self.user + '/projects?client_id=' + self.auth;
                    break;
                case 'codepen':
                    self.url = 'http://cpv2api.com/pens/public/' + self.user;
                    break;
                case 'dribbble':
                    self.url = 'https://api.dribbble.com/v1/users/' + self.user + '/shots';
                    break;
                case 'flickr':
                    self.url = 'https://api.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + self.auth + '&user_id=' + self.user + '&format=json&nojsoncallback=1';
                    break;
                case 'github':
                    self.url = 'https://api.github.com/users/' + self.user + '/repos?sort=updated';
                    break;
                case 'google-plus':
                    self.url = 'https://www.googleapis.com/plus/v1/people/' + self.user + '/activities/public?key=' + self.auth;
                    break;
                case 'instagram':
                    self.url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + self.auth;
                    break;
                case 'pinterest':
                    self.url = 'https://api.pinterest.com/v1/me/boards/?access_token=' + self.auth + '&fields=id,name,url,created_at,counts,description,creator,image,privacy,reason';
                    break;
                case 'spotify':
                    self.url = 'https://api.spotify.com/v1/users/' + self.user + '/playlists';
                    break;
                case 'trello':
                    self.url = 'https://api.trello.com/1/members/' + self.user  + '/boards';
                    break;
                // case 'twitter':
                //     self.url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' + self.user;
                //     break;
            }

            // Make the API request
            var special = ['instagram', 'behance'];
            if (special.indexOf(self.service) > -1) {
                SocialDig.jsonp(self.url).then(function(data){
                    self.data = data;
                    self.cb(self.data);
                });
            } else {
                var request = new XMLHttpRequest();
                request.open('GET', self.url, true);

                // Enable additional headers
                var headers = ['dribbble', 'spotify'];
                if (headers.indexOf(self.service) > -1) {
                    request.setRequestHeader('Authorization', 'Bearer ' + self.auth);
                }

                // Check for a successful response
                request.onload = function() {
                    // Parse the response
                    var data = JSON.parse(request.responseText);
                    self.data = data;

                    // Check the status of the request
                    if (request.status >= 200 && request.status < 400) {
                        // Return the found data
                        self.cb(self.data);
                    } else {
                        // Error from the server
                        throw self.data.message;
                    }
                };

                // Handle any errors
                request.onerror = function() {
                    // Connection error
                    throw 'connection error';
                };

                // Send the request
                request.send();
            }
        }
    };

    /******************************
     *  Initializing our function *
     ******************************/
    SocialDig.init = function(settings, cb) {
        var self = this;

        // Setup settings
        self.selector = settings.selector || '.social-dig'; // Selector for the container
        self.service = settings.service || ''; // Service
        self.user = settings.user || ''; // Service user (username/id/etc...)
        self.auth = settings.auth || ''; // Service authorization token/key
        self.url = ''; // Service API URL
        self.data = ''; // Service data from server
        self.cb = cb; // Service callback

        // Query the data
        self.queryData();
    }

    /**********************
     *  Handle JSONP APIs *
     **********************/
    SocialDig.jsonp = function(url) {
        return new Promise(function(resolve, reject){
            var id = '_' + Math.round(10000 * Math.random());
            var callbackName = 'jsonp_callback_' + id;
            window[callbackName] = function(data){
                delete window[callbackName];
                var ele = document.getElementById(id);
                ele.parentNode.removeChild(ele);
                resolve(data);
            }

            var src = url + '&callback=' + callbackName;
            var script = document.createElement('script');
            script.src = src;
            script.id = id;
            script.addEventListener('error', reject);
            (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script);
        })
    }

    SocialDig.init.prototype = SocialDig.prototype;
    global.SocialDig = global.SD = SocialDig;
}(window));
<commit_msg>Move the JSONP into the SocialDig prototype<commit_after>/**
 *
 *  -----------------------------------
 *  SocialDig.js - v0.1.0
 *  -----------------------------------
 *
 *  Query data from your social profiles with ease.
 *
 *  https://github.com/kjbrum/SocialDig.js
 *  @license Copyright (c) Kyle Brumm <http://kylebrumm.com>
 *
 */

;
(function(global) {
    var SocialDig = function(settings, cb) {
        return new SocialDig.init(settings, cb);
    }

    SocialDig.prototype = {
        /*********************************************
         * Query the data from the necessary service *
         *********************************************/
        queryData: function() {
            var self = this;
            var container = self.selector;

            // Check the type of selector that was supplied
            if (typeof self.selector === 'string') {
                container = document.querySelector(self.selector);
            }

            // Build the request URL
            switch (self.service) {
                case '500px':
                    self.url = 'https://api.500px.com/v1/photos?consumer_key=' + self.auth + '&feature=user&username=' + self.user + '&image_size=440';
                    break;
                case 'behance':
                    self.url = 'http://www.behance.net/v2/users/' + self.user + '/projects?client_id=' + self.auth;
                    break;
                case 'codepen':
                    self.url = 'http://cpv2api.com/pens/public/' + self.user;
                    break;
                case 'dribbble':
                    self.url = 'https://api.dribbble.com/v1/users/' + self.user + '/shots';
                    break;
                case 'flickr':
                    self.url = 'https://api.flickr.com/services/rest/?method=flickr.people.getPhotos&api_key=' + self.auth + '&user_id=' + self.user + '&format=json&nojsoncallback=1';
                    break;
                case 'github':
                    self.url = 'https://api.github.com/users/' + self.user + '/repos?sort=updated';
                    break;
                case 'google-plus':
                    self.url = 'https://www.googleapis.com/plus/v1/people/' + self.user + '/activities/public?key=' + self.auth;
                    break;
                case 'instagram':
                    self.url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + self.auth;
                    break;
                case 'pinterest':
                    self.url = 'https://api.pinterest.com/v1/me/boards/?access_token=' + self.auth + '&fields=id,name,url,created_at,counts,description,creator,image,privacy,reason';
                    break;
                case 'spotify':
                    self.url = 'https://api.spotify.com/v1/users/' + self.user + '/playlists';
                    break;
                case 'trello':
                    self.url = 'https://api.trello.com/1/members/' + self.user  + '/boards';
                    break;
                // case 'twitter':
                //     self.url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=' + self.user;
                //     break;
            }

            // Make the API request
            var special = ['instagram', 'behance'];
            if (special.indexOf(self.service) > -1) {
                self.JSONP(self.url).then(function(data){
                    self.data = data;
                    self.cb(self.data);
                });
            } else {
                var request = new XMLHttpRequest();
                request.open('GET', self.url, true);

                // Enable additional headers
                var headers = ['dribbble', 'spotify'];
                if (headers.indexOf(self.service) > -1) {
                    request.setRequestHeader('Authorization', 'Bearer ' + self.auth);
                }

                // Check for a successful response
                request.onload = function() {
                    // Parse the response
                    var data = JSON.parse(request.responseText);
                    self.data = data;

                    // Check the status of the request
                    if (request.status >= 200 && request.status < 400) {
                        // Return the found data
                        self.cb(self.data);
                    } else {
                        // Error from the server
                        throw self.data.message;
                    }
                };

                // Handle any errors
                request.onerror = function() {
                    // Connection error
                    throw 'connection error';
                };

                // Send the request
                request.send();
            }
        },

        /**********************
         *  Handle JSONP APIs *
         **********************/
        JSONP: function(url) {
            return new Promise(function(resolve, reject){
                var id = '_' + Math.round(10000 * Math.random());
                var callbackName = 'jsonp_callback_' + id;
                window[callbackName] = function(data){
                    delete window[callbackName];
                    var ele = document.getElementById(id);
                    ele.parentNode.removeChild(ele);
                    resolve(data);
                }

                var src = url + '&callback=' + callbackName;
                var script = document.createElement('script');
                script.src = src;
                script.id = id;
                script.addEventListener('error', reject);
                (document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script);
            })
        }
    };

    /******************************
     *  Initializing our function *
     ******************************/
    SocialDig.init = function(settings, cb) {
        var self = this;

        // Setup settings
        self.selector = settings.selector || '.social-dig'; // Selector for the container
        self.service = settings.service || ''; // Service
        self.user = settings.user || ''; // Service user (username/id/etc...)
        self.auth = settings.auth || ''; // Service authorization token/key
        self.url = ''; // Service API URL
        self.data = ''; // Service data from server
        self.cb = cb; // Service callback

        // Query the data
        self.queryData();
    };

    SocialDig.init.prototype = SocialDig.prototype;
    global.SocialDig = global.SD = SocialDig;
}(window));
<|endoftext|>


<commit_before>define(["sugar-web/activity/activity","webL10n","sugar-web/graphics/palette","sugar-web/graphics/presencepalette"], function (activity,wl10n, palette,presencepalette) {
    var activity = requirejs("sugar-web/activity/activity");

    // Manipulate the DOM only when it is ready.
    requirejs(['domReady!'], function (doc) {

        // Initialize the activity.
		activity.setup();

		var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
		//sanitize html messages
		var tagOrComment = new RegExp(
			'<(?:'
			// Comment body.
			+ '!--(?:(?:-*[^->])*--+|-?)'
			// Special "raw text" elements whose content should be elided.
			+ '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*'
			+ '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
			// Regular name
			+ '|/?[a-z]'
			+ tagBody
			+ ')>',
			'gi');
		function removeTags(html) {
			var oldHtml;
			do {
				oldHtml = html;
				html = html.replace(tagOrComment, '');
			} while (html !== oldHtml);
		return html.replace(/</g, '<');
		}

        var form = document.getElementById('message-form');
        var messageField = document.getElementById('message');
        var messagesList = document.getElementById('messages');
        var socketStatus = document.getElementById('status');
        var messageContent = document.getElementById('content');

	document.getElementById("status").innerHTML = l10n_s.get("status");
	messageField.placeholder = l10n_s.get("WriteYourMessage");

	    var userSettings = null;

		// Connect to network
        var presenceObject;
		function shareActivity() {
			presenceObject = activity.getPresenceObject(function (error, presence) {
				// Unable to join
				if (error)  {
					socketStatus.innerHTML = l10n_s.get('Error');
					socketStatus.className = 'error';
					return;
				}

				// Store settings
				userSettings = presence.getUserInfo();
				socketStatus.innerHTML = l10n_s.get('Connected');
				socketStatus.className = 'open';
				messageField.readOnly = false;

				// Not found, create a new shared activity
				if (!window.top.sugar.environment.sharedId) {
					presence.createSharedActivity('org.sugarlabs.ChatPrototype', function (groupId) {
					});
				}

				// Show a disconnected message when the WebSocket is closed.
				presence.onConnectionClosed(function (event) {
					console.log(l10n_s.get("ConnectionClosed"));
					socketStatus.innerHTML = l10n_s.get('DisconnectedFromWebSocket');
					socketStatus.className = 'closed';
				});

				// Display connection changed
				presence.onSharedActivityUserChanged(function (msg) {
					var userName = msg.user.name.replace('<','<').replace('>','>');
					messagesList.innerHTML += '
' + userName + ' ' + (msg.move>0?l10n_s.get('Join'):l10n_s.get('Leave')) + ' '+l10n_s.get('Chat')+'
';
				});

				// Handle messages received
				presence.onDataReceived(function (msg) {
					var text = msg.content;
					var author = msg.user.name.replace('<','<').replace('>','>');
					var colour = msg.user.colorvalue;

					var authorElem = '' + author + '';

					myElem = document.createElement('li');
					myElem.class = 'received';
					myElem.style.background = colour.fill;
					myElem.innerHTML = authorElem + text;
					myElem.style.color = colour.stroke;

					messagesList.appendChild(myElem);
					messageContent.scrollTop = messageContent.scrollHeight;
				});
			});
		}

		// Create network palette
        var networkButton = document.getElementById("network-button");
		presencepalette = new presencepalette.PresencePalette(networkButton, undefined);
		presencepalette.addEventListener('shared', shareActivity);

		// Launched with a shared id, activity is already shared
		if (window.top.sugar.environment.sharedId) {
			shareActivity();
			presencepalette.setShared(true);
		}

		// Handle message text update
        messageField.onkeydown = function (e) {
            if (e.keyCode === 13) {
				var message = removeTags(messageField.value);

				// Send the message through the WebSocket.
				var toSend = {user: userSettings, content: message};
				presenceObject.sendMessage(presenceObject.getSharedInfo().id, toSend);

                // Clear out the message field
				messageField.placeholder = l10n_s.get("WriteYourMessage");
                messageField.value = "";
				messageField.setSelectionRange(0,0);
				return false;
            }
        };
	    //Emoji messages
        var selectEmoji = document.getElementById('emoji-button')
        var emojiOption;
        var emojRange = [128513, 128591]; //Array of emojis

        for (var x = emojRange[0]; x < emojRange[1]; x++) {
          emojiOption = document.createElement('option');
          emojiOption.value = x;
          emojiOption.innerHTML = "&#" + x + ";";
          selectEmoji.appendChild(emojiOption);
        }
    });

});
<commit_msg>Added options for sad and others select tag.<commit_after>define(["sugar-web/activity/activity","webL10n","sugar-web/graphics/palette","sugar-web/graphics/presencepalette"], function (activity,wl10n, palette,presencepalette) {
    var activity = requirejs("sugar-web/activity/activity");

    // Manipulate the DOM only when it is ready.
    requirejs(['domReady!'], function (doc) {

        // Initialize the activity.
		activity.setup();

		var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
		//sanitize html messages
		var tagOrComment = new RegExp(
			'<(?:'
			// Comment body.
			+ '!--(?:(?:-*[^->])*--+|-?)'
			// Special "raw text" elements whose content should be elided.
			+ '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*'
			+ '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
			// Regular name
			+ '|/?[a-z]'
			+ tagBody
			+ ')>',
			'gi');
		function removeTags(html) {
			var oldHtml;
			do {
				oldHtml = html;
				html = html.replace(tagOrComment, '');
			} while (html !== oldHtml);
		return html.replace(/</g, '<');
		}

        var form = document.getElementById('message-form');
        var messageField = document.getElementById('message');
        var messagesList = document.getElementById('messages');
        var socketStatus = document.getElementById('status');
        var messageContent = document.getElementById('content');

	document.getElementById("status").innerHTML = l10n_s.get("status");
	messageField.placeholder = l10n_s.get("WriteYourMessage");

	    var userSettings = null;

		// Connect to network
        var presenceObject;
		function shareActivity() {
			presenceObject = activity.getPresenceObject(function (error, presence) {
				// Unable to join
				if (error)  {
					socketStatus.innerHTML = l10n_s.get('Error');
					socketStatus.className = 'error';
					return;
				}

				// Store settings
				userSettings = presence.getUserInfo();
				socketStatus.innerHTML = l10n_s.get('Connected');
				socketStatus.className = 'open';
				messageField.readOnly = false;

				// Not found, create a new shared activity
				if (!window.top.sugar.environment.sharedId) {
					presence.createSharedActivity('org.sugarlabs.ChatPrototype', function (groupId) {
					});
				}

				// Show a disconnected message when the WebSocket is closed.
				presence.onConnectionClosed(function (event) {
					console.log(l10n_s.get("ConnectionClosed"));
					socketStatus.innerHTML = l10n_s.get('DisconnectedFromWebSocket');
					socketStatus.className = 'closed';
				});

				// Display connection changed
				presence.onSharedActivityUserChanged(function (msg) {
					var userName = msg.user.name.replace('<','<').replace('>','>');
					messagesList.innerHTML += '
' + userName + ' ' + (msg.move>0?l10n_s.get('Join'):l10n_s.get('Leave')) + ' '+l10n_s.get('Chat')+'
';
				});

				// Handle messages received
				presence.onDataReceived(function (msg) {
					var text = msg.content;
					var author = msg.user.name.replace('<','<').replace('>','>');
					var colour = msg.user.colorvalue;

					var authorElem = '' + author + '';

					myElem = document.createElement('li');
					myElem.class = 'received';
					myElem.style.background = colour.fill;
					myElem.innerHTML = authorElem + text;
					myElem.style.color = colour.stroke;

					messagesList.appendChild(myElem);
					messageContent.scrollTop = messageContent.scrollHeight;
				});
			});
		}

		// Create network palette
        var networkButton = document.getElementById("network-button");
		presencepalette = new presencepalette.PresencePalette(networkButton, undefined);
		presencepalette.addEventListener('shared', shareActivity);

		// Launched with a shared id, activity is already shared
		if (window.top.sugar.environment.sharedId) {
			shareActivity();
			presencepalette.setShared(true);
		}

		// Handle message text update
        messageField.onkeydown = function (e) {
            if (e.keyCode === 13) {
				var message = removeTags(messageField.value);

				// Send the message through the WebSocket.
				var toSend = {user: userSettings, content: message};
				presenceObject.sendMessage(presenceObject.getSharedInfo().id, toSend);

                // Clear out the message field
				messageField.placeholder = l10n_s.get("WriteYourMessage");
                messageField.value = "";
				messageField.setSelectionRange(0,0);
				return false;
            }
        };
	    //Smiley Emoji options
        var selectSmiley = document.getElementById('smiley-button')
        var smileyOption;
        var smileyRange = [
          [128513, 128515], [128517, 128519], [128521, 128528] //Array of happy emojis
        ];

        for (var i = 0; i < smileyRange.length; i++) {
          var range = smileyRange[i];
          for (var x = range[0]; x < range[1]; x++) {

            smileyOption = document.createElement('option');
            smileyOption.value = x;
            smileyOption.innerHTML = "&#" + x + ";";
            selectSmiley.appendChild(smileyOption);
          }

        }

        //Sad Emoji options
          var selectSad = document.getElementById('sad-button')
          var sadOption;
          var sadRange = [
            [128531, 128533], [128545, 128551], [128555, 128558] //Array of sad or upset emojis
          ];

          for (var i = 0; i < sadRange.length; i++) {
            var range = sadRange[i];
            for (var x = range[0]; x < range[1]; x++) {

              sadOption = document.createElement('option');
              sadOption.value = x;
              sadOption.innerHTML = "&#" + x + ";";
              selectSad.appendChild(sadOption);
            }

          }

          //Others Emoji options
            var selectOthers = document.getElementById('others-button')
            var otherOption;
            var otherRange = [
              [128568, 128573], [128582, 128588] //Array of other emojis
            ];

            for (var i = 0; i < otherRange.length; i++) {
              var range = otherRange[i];
              for (var x = range[0]; x < range[1]; x++) {

                otherOption = document.createElement('option');
                otherOption.value = x;
                otherOption.innerHTML = "&#" + x + ";";
                selectOthers.appendChild(otherOption);
              }

            }
    });

});
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * 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.
 *
 */

var ws = new WebSocket('wss://' + location.host + '/groupcall');
var participants = {};
var name;
var state = true;

window.onbeforeunload = function() {
	//ws.close();
};

ws.onmessage = function(message) {
	var parsedMessage = JSON.parse(message.data);
	console.info('Received message: ' + message.data);

	switch (parsedMessage.id) {
	case 'existingParticipants':
		onExistingParticipants(parsedMessage);
		break;
	case 'newParticipantArrived':
		onNewParticipant(parsedMessage);
		break;
	case 'participantLeft':
		onParticipantLeft(parsedMessage);
		break;
	case 'receiveVideoAnswer':
		receiveVideoResponse(parsedMessage);
		break;
	case 'iceCandidate':
		participants[parsedMessage.name].rtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
	        if (error) {
		      console.error("Error adding candidate: " + error);
		      return;
	        }
	    });
	    break;
	default:
		console.error('Unrecognized message', parsedMessage);
	}
}

function register() {
	/*if (!state) {
		if (state == true) {
			ws.close();
		}
		ws = new WebSocket('wss://' + location.host + '/groupcall');
		state = true;
	}*/
	name = document.getElementById('name').value;
	var room = document.getElementById('roomName').value;

	document.getElementById('room-header').innerText = 'ROOM ' + room;
	document.getElementById('join').style.display = 'none';
	document.getElementById('room').style.display = 'block';

	var message = {
		id : 'joinRoom',
		name : name,
		room : room,
	}
	sendMessage(message);
}

function onNewParticipant(request) {
	receiveVideo(request);
}

function receiveVideoResponse(result) {
	participants[result.name].rtcPeer.processAnswer (result.sdpAnswer, function (error) {
		if (error) return console.error (error);
	});
}

function callResponse(message) {
	if (message.response != 'accepted') {
		console.info('Call not accepted by peer. Closing call');
		stop();
	} else {
		webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
			if (error) return console.error (error);
		});
	}
}

function onExistingParticipants(msg) {
	var constraints = {
		audio : true,
		video : {
			mandatory : {
				maxWidth : 1280,
				maxFrameRate : 15,
				minFrameRate : 15
			}
		}
	};
	console.log(name + " registered in room " + room);
	var participant = new Participant(name, msg.selfIsTeacher != null ? msg.selfIsTeacher : false);
	participants[name] = participant;
	var video = participant.getVideoElement();

	var options = {
	      localVideo: video,
	      mediaConstraints: constraints,
	      onicecandidate: participant.onIceCandidate.bind(participant)
	    }
	participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,
		function (error) {
		  if(error) {
			  return console.error(error);
		  }
		  this.generateOffer (participant.offerToReceiveVideo.bind(participant));
	});

	msg.data.forEach(receiveVideo);
}

function leaveRoom() {
	sendMessage({
		id : 'leaveRoom'
	});

	for ( var key in participants) {
		participants[key].dispose();
	}

	document.getElementById('join').style.display = 'block';
	document.getElementById('room').style.display = 'none';

	//ws.close();
	state = false;
}

function receiveVideo(senderObj) {
	var sender = senderObj.name;
	var participant = new Participant(sender, senderObj.isTeacher);
	participants[sender] = participant;
	var video = participant.getVideoElement();

	var options = {
      remoteVideo: video,
      onicecandidate: participant.onIceCandidate.bind(participant)
    }

	participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
			function (error) {
			  if(error) {
				  return console.error(error);
			  }
			  this.generateOffer (participant.offerToReceiveVideo.bind(participant));
	});;
}

function onParticipantLeft(request) {
	console.log('Participant ' + request.name + ' left');
	var participant = participants[request.name];
	if (participant != null) {
		participant.dispose();
		delete participants[request.name];
	}
}

function sendMessage(message) {
	var jsonMessage = JSON.stringify(message);
	console.log('Senging message: ' + jsonMessage);
	ws.send(jsonMessage);
}
<commit_msg>increase pixels<commit_after>/*
 * (C) Copyright 2014 Kurento (http://kurento.org/)
 *
 * 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.
 *
 */

var ws = new WebSocket('wss://' + location.host + '/groupcall');
var participants = {};
var name;
var state = true;

window.onbeforeunload = function() {
	//ws.close();
};

ws.onmessage = function(message) {
	var parsedMessage = JSON.parse(message.data);
	console.info('Received message: ' + message.data);

	switch (parsedMessage.id) {
	case 'existingParticipants':
		onExistingParticipants(parsedMessage);
		break;
	case 'newParticipantArrived':
		onNewParticipant(parsedMessage);
		break;
	case 'participantLeft':
		onParticipantLeft(parsedMessage);
		break;
	case 'receiveVideoAnswer':
		receiveVideoResponse(parsedMessage);
		break;
	case 'iceCandidate':
		participants[parsedMessage.name].rtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
	        if (error) {
		      console.error("Error adding candidate: " + error);
		      return;
	        }
	    });
	    break;
	default:
		console.error('Unrecognized message', parsedMessage);
	}
}

function register() {
	/*if (!state) {
		if (state == true) {
			ws.close();
		}
		ws = new WebSocket('wss://' + location.host + '/groupcall');
		state = true;
	}*/
	name = document.getElementById('name').value;
	var room = document.getElementById('roomName').value;

	document.getElementById('room-header').innerText = 'ROOM ' + room;
	document.getElementById('join').style.display = 'none';
	document.getElementById('room').style.display = 'block';

	var message = {
		id : 'joinRoom',
		name : name,
		room : room,
	}
	sendMessage(message);
}

function onNewParticipant(request) {
	receiveVideo(request);
}

function receiveVideoResponse(result) {
	participants[result.name].rtcPeer.processAnswer (result.sdpAnswer, function (error) {
		if (error) return console.error (error);
	});
}

function callResponse(message) {
	if (message.response != 'accepted') {
		console.info('Call not accepted by peer. Closing call');
		stop();
	} else {
		webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
			if (error) return console.error (error);
		});
	}
}

function onExistingParticipants(msg) {
	var constraints = {
		audio : true,
		video : {
			mandatory : {
				width: 1280,
				height: 1280,
				maxFrameRate : 15,
				minFrameRate : 15
			}
		}
	};
	console.log(name + " registered in room " + room);
	var participant = new Participant(name, msg.selfIsTeacher != null ? msg.selfIsTeacher : false);
	participants[name] = participant;
	var video = participant.getVideoElement();

	var options = {
	      localVideo: video,
	      mediaConstraints: constraints,
	      onicecandidate: participant.onIceCandidate.bind(participant)
	    }
	participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(options,
		function (error) {
		  if(error) {
			  return console.error(error);
		  }
		  this.generateOffer (participant.offerToReceiveVideo.bind(participant));
	});

	msg.data.forEach(receiveVideo);
}

function leaveRoom() {
	sendMessage({
		id : 'leaveRoom'
	});

	for ( var key in participants) {
		participants[key].dispose();
	}

	document.getElementById('join').style.display = 'block';
	document.getElementById('room').style.display = 'none';

	//ws.close();
	state = false;
}

function receiveVideo(senderObj) {
	var sender = senderObj.name;
	var participant = new Participant(sender, senderObj.isTeacher);
	participants[sender] = participant;
	var video = participant.getVideoElement();

	var options = {
      remoteVideo: video,
      onicecandidate: participant.onIceCandidate.bind(participant)
    }

	participant.rtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(options,
			function (error) {
			  if(error) {
				  return console.error(error);
			  }
			  this.generateOffer (participant.offerToReceiveVideo.bind(participant));
	});;
}

function onParticipantLeft(request) {
	console.log('Participant ' + request.name + ' left');
	var participant = participants[request.name];
	if (participant != null) {
		participant.dispose();
		delete participants[request.name];
	}
}

function sendMessage(message) {
	var jsonMessage = JSON.stringify(message);
	console.log('Senging message: ' + jsonMessage);
	ws.send(jsonMessage);
}
<|endoftext|>


<commit_before>/* eslint-disable no-console */
const axios = require('axios');
const crypto = require('crypto');
const cheerio = require('cheerio');
const {execSync} = require('child_process');
const URL = require('url');
const axiosRetry = require('axios-retry');

axiosRetry(axios, {retries: 3});

const requestGET = ({url, reporter}) => {
    const activity = reporter.activityTimer(`Fetching '${url}'`);
    activity.start();

    return axios
        .get(url)
        .then((results) => {
            activity.end();

            if (results.status !== 200) {
                throw results.data;
            }
            return results.data;
        });
};

function getContentFromConfluencePage(url, content) {
    const $ = cheerio.load(cheerio.load(content)('.wiki-content').html());

    $('.conf-macro.output-inline th:contains("Plugin Information")').parents('table').remove();

    // Remove any table of contents
    $('.toc').remove();

    // Replace href/src with the wiki url
    $('[href]').each((idx, elm) => {
        $(elm).attr('href', URL.resolve(url, $(elm).attr('href')));
    });
    $('[src]').each((idx, elm) => {
        $(elm).attr('src', URL.resolve(url, $(elm).attr('src')));
    });
    return ($('body') || $).html();
}

const pluginWikiUrlRe = /^https?:\/\/wiki.jenkins(?:-ci.org|.io)\/display\/(?:jenkins|hudson)\/([^/]*)\/?$/i;
const getPluginContent = async ({plugin, reporter}) => {
    plugin.id = plugin.id || plugin.name;
    plugin.wiki = plugin.wiki || {};
    // absolutely required fields
    plugin.wiki.content = plugin.wiki.content || '';
    plugin.wiki.url = plugin.wiki.url || '';

    if (!process.env.GET_CONTENT) {
        return plugin;
    }
    let matches;
    if ((matches = pluginWikiUrlRe.exec(plugin.wiki.url)) != null) {
        try {
            return await requestGET({
                reporter,
                url: `https://wiki.jenkins.io/rest/api/content?expand=body.view&title=${matches[1]}`
            }).then(async data => {
                plugin.wiki.content = await getContentFromConfluencePage(
                    'https://wiki.jenkins.io/',
                    `<body class="wiki-content">${data.results[0].body.view.value}</body>`
                );
                return plugin;
            });
        } catch (e) {
            console.error(`Error fetching wiki content for ${plugin.name}`, e);
        }
    }

    return requestGET({reporter, url: `https://plugins.jenkins.io/api/plugin/${plugin.name}`}).then(data => {
        plugin.wiki.content = data.wiki.content || '';
        return plugin;
    });
};

const fetchPluginData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch plugins info');
    sectionActivity.start();
    const promises = [];
    let page = 1;
    let pluginsContainer;
    do {
        const url = `https://plugins.jenkins.io/api/plugins/?limit=100&page=${page}`;
        pluginsContainer = await requestGET({url, reporter});

        for (const plugin of pluginsContainer.plugins) {
            promises.push(getPluginContent({plugin, reporter}).then(pluginData => {
                return createNode({
                    ...pluginData,
                    id: pluginData.name.trim(),
                    parent: null,
                    children: [],
                    internal: {
                        type: 'JenkinsPlugin',
                        contentDigest: crypto.createHash('md5').update(`plugin${pluginData.name.trim()}`).digest('hex')
                    }
                });
            }));
        }
        await Promise.all(promises);
        page = pluginsContainer.page + 1;
    } while (!page || pluginsContainer.page < pluginsContainer.pages);
    await Promise.all(promises);
    sectionActivity.end();
};

const fetchCategoryData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch categories info');
    sectionActivity.start();
    const url = 'https://plugins.jenkins.io/api/categories/?limit=100';
    const categoriesContainer = await requestGET({url, reporter});

    for (const category of categoriesContainer.categories) {
        createNode({
            ...category,
            id: category.id.trim(),
            parent: null,
            children: [],
            internal: {
                type: 'JenkinsPluginCategory',
                contentDigest: crypto
                    .createHash('md5')
                    .update(`category${category.name}`)
                    .digest('hex')
            }
        });
    }
    sectionActivity.end();
};

const fetchLabelData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch labels info');
    sectionActivity.start();
    const url = 'https://plugins.jenkins.io/api/labels/?limit=100';
    const labelsContainer = await requestGET({url, reporter});

    for (const label of labelsContainer.labels) {
        createNode({
            ...label,
            id: label.id.trim(),
            parent: null,
            children: [],
            internal: {
                type: 'JenkinsPluginLabel',
                contentDigest: crypto
                    .createHash('md5')
                    .update(`label${label.name}`)
                    .digest('hex')
            }
        });
    }
    sectionActivity.end();
};

const fetchSiteInfo = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch plugin api info');
    sectionActivity.start();
    const url = 'https://plugins.jenkins.io/api/info';
    const info = await requestGET({url, reporter});

    createNode({
        api: {
            ...info
        },
        website: {
            commit: execSync('git rev-parse HEAD').toString().trim(),
            version: require('find-package-json')().next().value.version,
        },
        id: 'pluginSiteInfo',
        parent: null,
        children: [],
        internal: {
            type: 'JenkinsPluginSiteInfo',
            contentDigest: crypto.createHash('md5').update('pluginSiteInfo').digest('hex')
        }
    });
    sectionActivity.end();
};

module.exports = {
    fetchSiteInfo,
    fetchLabelData,
    fetchCategoryData,
    fetchPluginData,
    getPluginContent,
    requestGET
}
;
<commit_msg>Pull the actual english version / pom url from wiki, not just the first one returned. Fixes #105<commit_after>/* eslint-disable no-console */
const axios = require('axios');
const crypto = require('crypto');
const cheerio = require('cheerio');
const {execSync} = require('child_process');
const URL = require('url');
const axiosRetry = require('axios-retry');

axiosRetry(axios, {retries: 3});

const requestGET = ({url, reporter}) => {
    const activity = reporter.activityTimer(`Fetching '${url}'`);
    activity.start();

    return axios
        .get(url)
        .then((results) => {
            activity.end();

            if (results.status !== 200) {
                throw results.data;
            }
            return results.data;
        });
};

function getContentFromConfluencePage(url, content) {
    const $ = cheerio.load(cheerio.load(content)('.wiki-content').html());

    $('.conf-macro.output-inline th:contains("Plugin Information")').parents('table').remove();

    // Remove any table of contents
    $('.toc').remove();

    // Replace href/src with the wiki url
    $('[href]').each((idx, elm) => {
        $(elm).attr('href', URL.resolve(url, $(elm).attr('href')));
    });
    $('[src]').each((idx, elm) => {
        $(elm).attr('src', URL.resolve(url, $(elm).attr('src')));
    });
    return ($('body') || $).html();
}

const pluginWikiUrlRe = /^https?:\/\/wiki.jenkins(?:-ci.org|.io)\/display\/(?:jenkins|hudson)\/([^/]*)\/?$/i;
const getPluginContent = async ({plugin, reporter}) => {
    plugin.id = plugin.id || plugin.name;
    plugin.wiki = plugin.wiki || {};
    // absolutely required fields
    plugin.wiki.content = plugin.wiki.content || '';
    plugin.wiki.url = plugin.wiki.url || '';

    if (!process.env.GET_CONTENT) {
        return plugin;
    }
    let matches;
    if ((matches = pluginWikiUrlRe.exec(plugin.wiki.url)) != null) {
        try {
            return await requestGET({
                reporter,
                url: `https://wiki.jenkins.io/rest/api/content?expand=body.view&title=${matches[1]}`
            }).then(async data => {
                const result = data.results.find(result => plugin.wiki.url.includes(result._links.webui)) || data.results[0];
                plugin.wiki.content = await getContentFromConfluencePage(
                    'https://wiki.jenkins.io/',
                    `<body class="wiki-content">${result.body.view.value}</body>`);
                return plugin;
            });
        } catch (e) {
            console.error(`Error fetching wiki content for ${plugin.name}`, e);
        }
    }

    return requestGET({reporter, url: `https://plugins.jenkins.io/api/plugin/${plugin.name}`}).then(data => {
        plugin.wiki.content = data.wiki.content || '';
        return plugin;
    });
};

const fetchPluginData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch plugins info');
    sectionActivity.start();
    const promises = [];
    let page = 1;
    let pluginsContainer;
    do {
        const url = `https://plugins.jenkins.io/api/plugins/?limit=100&page=${page}`;
        pluginsContainer = await requestGET({url, reporter});

        for (const plugin of pluginsContainer.plugins) {
            promises.push(getPluginContent({plugin, reporter}).then(pluginData => {
                return createNode({
                    ...pluginData,
                    id: pluginData.name.trim(),
                    parent: null,
                    children: [],
                    internal: {
                        type: 'JenkinsPlugin',
                        contentDigest: crypto.createHash('md5').update(`plugin${pluginData.name.trim()}`).digest('hex')
                    }
                });
            }));
        }
        await Promise.all(promises);
        page = pluginsContainer.page + 1;
    } while (!page || pluginsContainer.page < pluginsContainer.pages);
    await Promise.all(promises);
    sectionActivity.end();
};

const fetchCategoryData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch categories info');
    sectionActivity.start();
    const url = 'https://plugins.jenkins.io/api/categories/?limit=100';
    const categoriesContainer = await requestGET({url, reporter});

    for (const category of categoriesContainer.categories) {
        createNode({
            ...category,
            id: category.id.trim(),
            parent: null,
            children: [],
            internal: {
                type: 'JenkinsPluginCategory',
                contentDigest: crypto
                    .createHash('md5')
                    .update(`category${category.name}`)
                    .digest('hex')
            }
        });
    }
    sectionActivity.end();
};

const fetchLabelData = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch labels info');
    sectionActivity.start();
    const url = 'https://plugins.jenkins.io/api/labels/?limit=100';
    const labelsContainer = await requestGET({url, reporter});

    for (const label of labelsContainer.labels) {
        createNode({
            ...label,
            id: label.id.trim(),
            parent: null,
            children: [],
            internal: {
                type: 'JenkinsPluginLabel',
                contentDigest: crypto
                    .createHash('md5')
                    .update(`label${label.name}`)
                    .digest('hex')
            }
        });
    }
    sectionActivity.end();
};

const fetchSiteInfo = async ({createNode, reporter}) => {
    const sectionActivity = reporter.activityTimer('fetch plugin api info');
    sectionActivity.start();
    const url = 'https://plugins.jenkins.io/api/info';
    const info = await requestGET({url, reporter});

    createNode({
        api: {
            ...info
        },
        website: {
            commit: execSync('git rev-parse HEAD').toString().trim(),
            version: require('find-package-json')().next().value.version,
        },
        id: 'pluginSiteInfo',
        parent: null,
        children: [],
        internal: {
            type: 'JenkinsPluginSiteInfo',
            contentDigest: crypto.createHash('md5').update('pluginSiteInfo').digest('hex')
        }
    });
    sectionActivity.end();
};

module.exports = {
    fetchSiteInfo,
    fetchLabelData,
    fetchCategoryData,
    fetchPluginData,
    getPluginContent,
    requestGET
}
;
<|endoftext|>


<commit_before>const LinkToken = artifacts.require('./chainlink/src/lib/LinkToken.sol');
const ChainLinkOracle = artifacts.require('./chainlink/src/Oracle.sol');
const MarketContractFactory = artifacts.require('./chainlink/MarketContractFactoryChainLink.sol');
const OracleHub = artifacts.require('./chainlink/OracleHubChainLink.sol');
const CollateralToken = artifacts.require('./tokens/CollateralToken.sol');

const MarketContractRegistry = artifacts.require('./MarketContractRegistry.sol');
const MarketToken = artifacts.require('./tokens/MarketToken.sol');

module.exports = function (deployer, network) {
  const gasLimit = web3.eth.getBlock('latest').gasLimit;
  const marketContractExpiration = Math.floor(Date.now() / 1000) + 60 * 15; // expires in 15 minutes.

  if (network !== 'live') {
    return deployer.deploy(LinkToken).then(function (linkToken) {
      return deployer.deploy(ChainLinkOracle, LinkToken.address).then(function () {
        return MarketContractRegistry.deployed().then(function (registry) {
          return deployer.deploy(
            MarketContractFactory,
            registry.address,
            MarketToken.address,
            {gas: gasLimit, from: web3.eth.accounts[0]}
          ).then(function (factory) {
            return registry.addFactoryAddress(factory.address).then(function () {
              return deployer.deploy(
                OracleHub,
                factory.address,
                LinkToken.address,
                ChainLinkOracle.address,
                {gas: gasLimit, from: web3.eth.accounts[0]}
              ).then(function (oracleHub) {
                // set the oracle hub address in the factory to allow to request queries.
                return factory.setOracleHubAddress(
                  oracleHub.address,
                  {from: web3.eth.accounts[0]}
                ).then(function () {
                  // transfer link token to hub to pay for queries.
                  return linkToken.transfer(oracleHub.address, 10e22).then(function () {
                    return factory.deployMarketContractChainLink(
                      'ETHXBT',
                      CollateralToken.address,
                      [20155, 60465, 2, 10, marketContractExpiration],
                      'https://api.kraken.com/0/public/Ticker?pair=ETHUSD',
                      'result.XETHZUSD.c.0',
                      'fakeSleepJobId',
                      'fakeOnDemandJobId',
                      {gas: gasLimit, from: web3.eth.accounts[0]}
                    )
                  });
                });
              });
            });
          });
        });
      });
    });
  }
};
<commit_msg>Link MathLib with MMarketContractFactoryChainLink<commit_after>const MathLib = artifacts.require('./libraries/MathLib.sol');
const LinkToken = artifacts.require('./chainlink/src/lib/LinkToken.sol');
const ChainLinkOracle = artifacts.require('./chainlink/src/Oracle.sol');
const MarketContractFactory = artifacts.require('./chainlink/MarketContractFactoryChainLink.sol');
const OracleHub = artifacts.require('./chainlink/OracleHubChainLink.sol');
const CollateralToken = artifacts.require('./tokens/CollateralToken.sol');

const MarketContractRegistry = artifacts.require('./MarketContractRegistry.sol');
const MarketToken = artifacts.require('./tokens/MarketToken.sol');

module.exports = function (deployer, network) {
  const gasLimit = web3.eth.getBlock('latest').gasLimit;
  const marketContractExpiration = Math.floor(Date.now() / 1000) + 60 * 15; // expires in 15 minutes.

  if (network !== 'live') {
    return deployer.deploy(LinkToken).then(function (linkToken) {
      return deployer.deploy(ChainLinkOracle, LinkToken.address).then(function () {
        return MarketContractRegistry.deployed().then(function (registry) {
          deployer.link(MathLib, [MarketContractFactory]).then(function () {
            return deployer.deploy(
              MarketContractFactory,
              registry.address,
              MarketToken.address,
              {gas: gasLimit, from: web3.eth.accounts[0]}
            ).then(function (factory) {
              return registry.addFactoryAddress(factory.address).then(function () {
                return deployer.deploy(
                  OracleHub,
                  factory.address,
                  LinkToken.address,
                  ChainLinkOracle.address,
                  {gas: gasLimit, from: web3.eth.accounts[0]}
                ).then(function (oracleHub) {
                  // set the oracle hub address in the factory to allow to request queries.
                  return factory.setOracleHubAddress(
                    oracleHub.address,
                    {from: web3.eth.accounts[0]}
                  ).then(function () {
                    // transfer link token to hub to pay for queries.
                    return linkToken.transfer(oracleHub.address, 10e22).then(function () {
                      return factory.deployMarketContractChainLink(
                        'ETHXBT',
                        CollateralToken.address,
                        [20155, 60465, 2, 10, marketContractExpiration],
                        'https://api.kraken.com/0/public/Ticker?pair=ETHUSD',
                        'result.XETHZUSD.c.0',
                        'fakeSleepJobId',
                        'fakeOnDemandJobId',
                        {gas: gasLimit, from: web3.eth.accounts[0]}
                      );
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  }
};
<|endoftext|>


<commit_before>Pipi = { /*!
 *
 *  # Pipi: BiB/i Putter
 *
 *  - "Putting EPUBs in Web Page with BiB/i."
 *  - (c) Satoru MATSUSHIMA - http://sarasa.la/bib/i
 *  - Licensed under the MIT license. - http://www.opensource.org/licenses/mit-license.php
 *
 *  - Tue August 19 15:00:00 2014 +0900
 */    Version: "0.997.0", Build: 20140819.0
};

(function(embedBibi) {
	if(window["bibi-pipi"]) return;
	window["bibi-pipi"] = { Status: "waiting" };
	document.addEventListener("DOMContentLoaded", embedBibi, false);
	  window.addEventListener("load",             embedBibi, false);
})(function() {
	if(window["bibi-pipi"].Status != "waiting") return;
	window["bibi-pipi"].Status = "processing";
	var As = document.querySelectorAll ? document.querySelectorAll('a[data-bibi]') : (function(_As, As) {
		for(var L = _As.length, i = 0; i < L; i++) if(_As[i].getAttribute("data-bibi")) As.push(_As[i]);
		return As;
	})(document.body.getElementsByTagName("a"), []);
	if(As.length) {
		var create = function(TagName, Properties) {
			var Element = document.createElement(TagName);
			for(var Attribute in Properties) Element[Attribute] = Properties[Attribute];
			return Element;
		};
		var BibiPath = As[0].href.replace(/^(.+?bib\/i)\/.+$/, "$1");
		var FullScreenEnabled = (function(B) {
			if(B.requestFullscreen       || B.requestFullScreen)       return true;
			if(B.webkitRequestFullscreen || B.webkitRequestFullScreen) return true;
			if(B.mozRequestFullscreen    || B.mozRequestFullScreen)    return true;
			if(B.msRequestFullscreen)                                  return true;
			return false;
		})(document.body);
		if(FullScreenEnabled) {
			window["bibi-pipi"].requestFullscreen = function(E) {
				if(E.requestFullscreen)       return E.requestFullscreen();
				if(E.requestFullScreen)       return E.requestFullScreen();
				if(E.webkitRequestFullscreen) return E.webkitRequestFullscreen();
				if(E.webkitRequestFullScreen) return E.webkitRequestFullScreen();
				if(E.mozRequestFullscreen)    return E.mozRequestFullscreen();
				if(E.mozRequestFullScreen)    return E.mozRequestFullScreen();
				if(E.msRequestFullscreen)     return E.msRequestFullscreen();
			};
			window["bibi-pipi"].exitFullscreen = function(D) {
				if(D.exitFullscreen)          return D.exitFullscreen();
				if(D.cencelFullScreen)        return D.cancelFullScreen();
				if(D.webkitExitFullscreen)    return D.webkitExitFullscreen();
				if(D.webkitCancelFullScreen)  return D.webkitCancelFullScreen();
				if(D.mozExitFullscreen)       return D.mozExitFullscreen();
				if(D.mozCancelFullScreen)     return D.mozCancelFullScreen();
				if(D.msExitFullscreen)        return D.msExitFullscreen();
			};
			window["bibi-pipi"].getFullscreenElement = function(D) {
				if(D.fullscreenElement)       return D.fullscreenElement;
				if(D.fullScreenElement)       return D.fullScreenElement;
				if(D.webkitFullscreenElement) return D.webkitFullscreenElement;
				if(D.webkitFullScreenElement) return D.webkitFullScreenElement;
				if(D.mozFullscreenElement)    return D.mozFullscreenElement;
				if(D.mozFullScreenElement)    return D.mozFullScreenElement;
				if(D.msFullscreenElement)     return D.msFullscreenElement;
				return null;
			};
		}
		document.getElementsByTagName("head")[0].appendChild(
			create("link", { rel: "stylesheet", id: "bibi-css", href: BibiPath + "/res/styles/pipi.css" })
		);
		window["bibi-pipi"].Holders = [];
		for(var L = As.length, i = 0; i < L; i++) {
			if(!As[i].getAttribute("href")) continue;
			var Holder = create("span", {
				className: "bibi-holder " + (FullScreenEnabled ? "bibi-fullscreen-enabled" : "bibi-fullscreen-not-enabled"),
				title: (As[i].innerText ? As[i].innerText + " " : "") + "(powered by BiB/i)"
			});
			var Href      = As[i].getAttribute("href");
			var Src       = Href;
			var Class     = As[i].getAttribute("data-bibi-class");
			var ID        = As[i].getAttribute("data-bibi-id");
			var Style     = As[i].getAttribute("data-bibi-style");
			var Poster    = As[i].getAttribute("data-bibi-poster");
			var Autostart = As[i].getAttribute("data-bibi-autostart");
			if(Class) Holder.className += " " + Class;
			if(ID)    Holder.id = ID;
			if(Style) Holder.setAttribute("style", Style);
			if(Autostart) {
				Src += (/#/.test(Src) ? "," : "#") + "pipi(autostart:true)";
			} else if(Poster) {
				var PosterLink = create("link", { href: Poster });
				Poster = PosterLink.href;
				delete PosterLink;
				Src += (/#/.test(Src) ? "," : "#") + "pipi(poster:" + encodeURIComponent(Poster).replace("(", "_BibiKakkoOpen_").replace(")", "_BibiKakkoClose_") + ")";
			}
			As[i].style.display = "none";
			As[i].parentNode.insertBefore(Holder, As[i]);
			Holder.appendChild(
				create("iframe", {
					className: "bibi-frame",
					frameborder: "0",
					scrolling: "auto",
					allowfullscreen: "true",
					webkitallowfullscreen: "true",
					mozallowfullscreen: "true",
					src: Src
				})
			);
			Holder.SwitchNewWindow = Holder.appendChild(
				create("a", {
					className: "bibi-switch-newwindow",
					title: "Open in New Window",
					target: "_blank",
					href: Href
				})
			);
			if(FullScreenEnabled) {
				Holder.className += " bibi-fullscreen-enabled";
				Holder.SwitchFullscreen = Holder.appendChild(
					create("span", {
						className: "bibi-switch-fullscreen",
						title: "Enter Fullscreen",
						Holder: Holder,
						onclick: function() {
							if(!window["bibi-pipi"].getFullscreenElement(document)) {
								window["bibi-pipi"].requestFullscreen(this.Holder);
								this.title = "Exit Fullscreen";
							} else {
								window["bibi-pipi"].exitFullscreen(document);
								this.title = "Enter Fullscreen";
							}
						}
					})
				);
			}
			window["bibi-pipi"].Holders.push(Holder);
		}
	}
	window["bibi-pipi"].Status = "processed";
});
<commit_msg>Do autostart only when data-bibi-autostart is true<commit_after>Pipi = { /*!
 *
 *  # Pipi: BiB/i Putter
 *
 *  - "Putting EPUBs in Web Page with BiB/i."
 *  - (c) Satoru MATSUSHIMA - http://sarasa.la/bib/i
 *  - Licensed under the MIT license. - http://www.opensource.org/licenses/mit-license.php
 *
 *  - Tue August 19 15:00:00 2014 +0900
 */    Version: "0.997.0", Build: 20140819.0
};

(function(embedBibi) {
	if(window["bibi-pipi"]) return;
	window["bibi-pipi"] = { Status: "waiting" };
	document.addEventListener("DOMContentLoaded", embedBibi, false);
	  window.addEventListener("load",             embedBibi, false);
})(function() {
	if(window["bibi-pipi"].Status != "waiting") return;
	window["bibi-pipi"].Status = "processing";
	var As = document.querySelectorAll ? document.querySelectorAll('a[data-bibi]') : (function(_As, As) {
		for(var L = _As.length, i = 0; i < L; i++) if(_As[i].getAttribute("data-bibi")) As.push(_As[i]);
		return As;
	})(document.body.getElementsByTagName("a"), []);
	if(As.length) {
		var create = function(TagName, Properties) {
			var Element = document.createElement(TagName);
			for(var Attribute in Properties) Element[Attribute] = Properties[Attribute];
			return Element;
		};
		var BibiPath = As[0].href.replace(/^(.+?bib\/i)\/.+$/, "$1");
		var FullScreenEnabled = (function(B) {
			if(B.requestFullscreen       || B.requestFullScreen)       return true;
			if(B.webkitRequestFullscreen || B.webkitRequestFullScreen) return true;
			if(B.mozRequestFullscreen    || B.mozRequestFullScreen)    return true;
			if(B.msRequestFullscreen)                                  return true;
			return false;
		})(document.body);
		if(FullScreenEnabled) {
			window["bibi-pipi"].requestFullscreen = function(E) {
				if(E.requestFullscreen)       return E.requestFullscreen();
				if(E.requestFullScreen)       return E.requestFullScreen();
				if(E.webkitRequestFullscreen) return E.webkitRequestFullscreen();
				if(E.webkitRequestFullScreen) return E.webkitRequestFullScreen();
				if(E.mozRequestFullscreen)    return E.mozRequestFullscreen();
				if(E.mozRequestFullScreen)    return E.mozRequestFullScreen();
				if(E.msRequestFullscreen)     return E.msRequestFullscreen();
			};
			window["bibi-pipi"].exitFullscreen = function(D) {
				if(D.exitFullscreen)          return D.exitFullscreen();
				if(D.cencelFullScreen)        return D.cancelFullScreen();
				if(D.webkitExitFullscreen)    return D.webkitExitFullscreen();
				if(D.webkitCancelFullScreen)  return D.webkitCancelFullScreen();
				if(D.mozExitFullscreen)       return D.mozExitFullscreen();
				if(D.mozCancelFullScreen)     return D.mozCancelFullScreen();
				if(D.msExitFullscreen)        return D.msExitFullscreen();
			};
			window["bibi-pipi"].getFullscreenElement = function(D) {
				if(D.fullscreenElement)       return D.fullscreenElement;
				if(D.fullScreenElement)       return D.fullScreenElement;
				if(D.webkitFullscreenElement) return D.webkitFullscreenElement;
				if(D.webkitFullScreenElement) return D.webkitFullScreenElement;
				if(D.mozFullscreenElement)    return D.mozFullscreenElement;
				if(D.mozFullScreenElement)    return D.mozFullScreenElement;
				if(D.msFullscreenElement)     return D.msFullscreenElement;
				return null;
			};
		}
		document.getElementsByTagName("head")[0].appendChild(
			create("link", { rel: "stylesheet", id: "bibi-css", href: BibiPath + "/res/styles/pipi.css" })
		);
		window["bibi-pipi"].Holders = [];
		for(var L = As.length, i = 0; i < L; i++) {
			if(!As[i].getAttribute("href")) continue;
			var Holder = create("span", {
				className: "bibi-holder " + (FullScreenEnabled ? "bibi-fullscreen-enabled" : "bibi-fullscreen-not-enabled"),
				title: (As[i].innerText ? As[i].innerText + " " : "") + "(powered by BiB/i)"
			});
			var Href      = As[i].getAttribute("href");
			var Src       = Href;
			var Class     = As[i].getAttribute("data-bibi-class");
			var ID        = As[i].getAttribute("data-bibi-id");
			var Style     = As[i].getAttribute("data-bibi-style");
			var Poster    = As[i].getAttribute("data-bibi-poster");
			var Autostart = As[i].getAttribute("data-bibi-autostart") === "true";
			if(Class) Holder.className += " " + Class;
			if(ID)    Holder.id = ID;
			if(Style) Holder.setAttribute("style", Style);
			if(Autostart) {
				Src += (/#/.test(Src) ? "," : "#") + "pipi(autostart:true)";
			} else if(Poster) {
				var PosterLink = create("link", { href: Poster });
				Poster = PosterLink.href;
				delete PosterLink;
				Src += (/#/.test(Src) ? "," : "#") + "pipi(poster:" + encodeURIComponent(Poster).replace("(", "_BibiKakkoOpen_").replace(")", "_BibiKakkoClose_") + ")";
			}
			As[i].style.display = "none";
			As[i].parentNode.insertBefore(Holder, As[i]);
			Holder.appendChild(
				create("iframe", {
					className: "bibi-frame",
					frameborder: "0",
					scrolling: "auto",
					allowfullscreen: "true",
					webkitallowfullscreen: "true",
					mozallowfullscreen: "true",
					src: Src
				})
			);
			Holder.SwitchNewWindow = Holder.appendChild(
				create("a", {
					className: "bibi-switch-newwindow",
					title: "Open in New Window",
					target: "_blank",
					href: Href
				})
			);
			if(FullScreenEnabled) {
				Holder.className += " bibi-fullscreen-enabled";
				Holder.SwitchFullscreen = Holder.appendChild(
					create("span", {
						className: "bibi-switch-fullscreen",
						title: "Enter Fullscreen",
						Holder: Holder,
						onclick: function() {
							if(!window["bibi-pipi"].getFullscreenElement(document)) {
								window["bibi-pipi"].requestFullscreen(this.Holder);
								this.title = "Exit Fullscreen";
							} else {
								window["bibi-pipi"].exitFullscreen(document);
								this.title = "Enter Fullscreen";
							}
						}
					})
				);
			}
			window["bibi-pipi"].Holders.push(Holder);
		}
	}
	window["bibi-pipi"].Status = "processed";
});
<|endoftext|>


<commit_before>const extend = require('deep-extend')

function addBaseDependencies (files = {}, context) {
  extend(files.pkg, {
    scripts: {
      'subtask:buildgulp': 'gulp build --env=production',
      'assets': 'gulp copy:assets --env=init',
      'build': 'cross-env NODE_ENV=production npm run subtask:buildgulp && cross-env NODE_ENV=production npm run subtask:bundlewebpack',
      'deploy': 'npm run build',
      'dev': 'cross-env NODE_ENV=development gulp',
      'favicon': 'gulp build:favicon --env=init',
      'htmlassets': 'gulp copy:contentimages --env=init',
      'init': 'cross-env NODE_ENV=production gulp init --env=init && cross-env NODE_ENV=production  npm run subtask:bundlewebpack',
      'template': 'gulp compiler:html --env=init',
      'uiimages': 'gulp rebuild:images --env=init',
      'fonts': 'gulp copy:fonts --env=init'
    },
    devDependencies: {
      'ansi-html': '^0.0.7',
      'babel-cli': '^6.24.1',
      'babel-core': '^6.24.1',
      'babel-preset-es2015': '^6.24.1',
      'browser-sync': '^2.18.7',
      'cross-env': '^5.0.0',
      'gulp-bump': '^2.7.0',
      'gulp-changed': '^3.1.0',
      'gulp-cheerio': '^0.6.2',
      'gulp-concat': '^2.6.1',
      'gulp-favicons': '^2.2.7',
      'gulp-html-prettify': '^0.0.1',
      'gulp-if': '^2.0.2',
      'gulp-imagemin': '^3.3.0',
      'gulp-modernizr': '^1.0.0-alpha',
      'gulp-notify': '^3.0.0',
      'gulp-plumber': '^1.1.0',
      'gulp.spritesmith': '^6.3.0',
      'gulp-svg-sprite': '^1.3.7',
      'gulp-twig': '^0.7.0',
      'gulp-uglify': '^3.0.0',
      'gulp-watch': '^4.3.11',
      'gulp-favicons': '2.1.5',
      'imagemin-jpeg-recompress': '^5.1.0',
      'imagemin-pngquant': '^5.0.1',
      'imagemin-svgo': '^5.2.2',
      'require-dir': '^0.3.2',
      'run-sequence': '^1.2.2'
    }
  })
}

module.exports = addBaseDependencies
<commit_msg>Update base.js<commit_after>const extend = require('deep-extend')

function addBaseDependencies (files = {}, context) {
  extend(files.pkg, {
    scripts: {
      'subtask:buildgulp': 'gulp build --env=production',
      'assets': 'gulp copy:assets --env=init',
      'build': 'cross-env NODE_ENV=production npm run subtask:buildgulp && cross-env NODE_ENV=production npm run subtask:bundlewebpack',
      'deploy': 'npm run build',
      'dev': 'cross-env NODE_ENV=development gulp',
      'favicon': 'gulp build:favicon --env=init',
      'htmlassets': 'gulp copy:contentimages --env=init',
      'init': 'cross-env NODE_ENV=production gulp init --env=init && cross-env NODE_ENV=production  npm run subtask:bundlewebpack',
      'template': 'gulp compiler:html --env=init',
      'uiimages': 'gulp rebuild:images --env=init',
      'fonts': 'gulp copy:fonts --env=init'
    },
    devDependencies: {
      'ansi-html': '^0.0.7',
      'babel-cli': '^6.24.1',
      'babel-core': '^6.24.1',
      'babel-preset-es2015': '^6.24.1',
      'browser-sync': '^2.18.7',
      'cross-env': '^5.0.0',
      'gulp-bump': '^2.7.0',
      'gulp-changed': '^3.1.0',
      'gulp-cheerio': '^0.6.2',
      'gulp-concat': '^2.6.1',
      'gulp-html-prettify': '^0.0.1',
      'gulp-if': '^2.0.2',
      'gulp-imagemin': '^3.3.0',
      'gulp-modernizr': '^1.0.0-alpha',
      'gulp-notify': '^3.0.0',
      'gulp-plumber': '^1.1.0',
      'gulp.spritesmith': '^6.3.0',
      'gulp-svg-sprite': '^1.3.7',
      'gulp-twig': '^0.7.0',
      'gulp-uglify': '^3.0.0',
      'gulp-watch': '^4.3.11',
      'gulp-favicons': '2.1.5',
      'imagemin-jpeg-recompress': '^5.1.0',
      'imagemin-pngquant': '^5.0.1',
      'imagemin-svgo': '^5.2.2',
      'require-dir': '^0.3.2',
      'run-sequence': '^1.2.2'
    }
  })
}

module.exports = addBaseDependencies
<|endoftext|>


<commit_before>import {bisect} from "d3-array";
import {round} from "d3-interpolate";
import {map, slice} from "./array";
import constant from "./constant";
import number from "./number";

export function deinterpolateLinear(a, b) {
  return (b -= (a = +a))
      ? function(x) { return (x - a) / b; }
      : constant(isNaN(b) ? NaN : 0);
};

function deinterpolateClamp(deinterpolate) {
  return function(a, b) {
    var d = deinterpolate(a, b);
    return function(x) {
      return Math.max(0, Math.min(1, d(x)));
    };
  };
}

function bimap(domain, range, deinterpolate, reinterpolate) {
  var d = deinterpolate(domain[0], domain[1]),
      r = reinterpolate(range[0], range[1]);
  return function(x) {
    return r(d(x));
  };
}

function polymap(domain, range, deinterpolate, reinterpolate) {
  var j = Math.min(domain.length, range.length) - 1,
      d = new Array(j),
      r = new Array(j),
      i = -1;

  // Handle descending domains.
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range = range.slice().reverse();
  }

  while (++i < j) {
    d[i] = deinterpolate(domain[i], domain[i + 1]);
    r[i] = reinterpolate(range[i], range[i + 1]);
  }

  return function(x) {
    var i = bisect(domain, x, 1, j) - 1;
    return r[i](d[i](x));
  };
}

// deinterpolate takes a domain value and returns a parameter t in [0,1]
// reinterpolate takes a parameter t in [0,1] and returns a domain value; the inverse of deinterpolate
// interpolate takes a parameter t in [0,1] and returns a range value
export default function quantitative(domain, range, deinterpolate, reinterpolate, interpolate, clamp) {
  var output,
      input;

  function remap() {
    var map = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
    output = map(domain, range, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate);
    input = map(range, domain, clamp ? deinterpolateClamp(deinterpolateLinear) : deinterpolateLinear, reinterpolate);
    return scale;
  }

  function scale(x) {
    return output(x);
  }

  scale.invert = function(y) {
    return input(y);
  };

  scale.domain = function(_) {
    return arguments.length ? (domain = map.call(_, number), remap()) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice.call(_), remap()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return scale.range(_).interpolate(round);
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, remap()) : clamp;
  };

  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, remap()) : interpolate;
  };

  scale.copy = function() {
    return quantitative(domain, range, deinterpolate, reinterpolate, interpolate, clamp);
  };

  return remap();
};
<commit_msg>Comments.<commit_after>import {bisect} from "d3-array";
import {round} from "d3-interpolate";
import {map, slice} from "./array";
import constant from "./constant";
import number from "./number";

export function deinterpolateLinear(a, b) {
  return (b -= (a = +a))
      ? function(x) { return (x - a) / b; }
      : constant(isNaN(b) ? NaN : 0);
};

function deinterpolateClamp(deinterpolate) {
  return function(a, b) {
    var d = deinterpolate(a, b);
    return function(x) { return Math.max(0, Math.min(1, d(x))); };
  };
}

function bimap(domain, range, deinterpolate, reinterpolate) {
  var d = deinterpolate(domain[0], domain[1]),
      r = reinterpolate(range[0], range[1]);
  return function(x) { return r(d(x)); };
}

function polymap(domain, range, deinterpolate, reinterpolate) {
  var j = Math.min(domain.length, range.length) - 1,
      d = new Array(j),
      r = new Array(j),
      i = -1;

  // Reverse descending domains.
  if (domain[j] < domain[0]) {
    domain = domain.slice().reverse();
    range = range.slice().reverse();
  }

  while (++i < j) {
    d[i] = deinterpolate(domain[i], domain[i + 1]);
    r[i] = reinterpolate(range[i], range[i + 1]);
  }

  return function(x) {
    var i = bisect(domain, x, 1, j) - 1;
    return r[i](d[i](x));
  };
}

// deinterpolate(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// reinterpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding domain value x in [a,b].
// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value in [a,b].
// interpolate should always be a linear mapping, but deinterpolate and reinterpolate need not be.
export default function quantitative(domain, range, deinterpolate, reinterpolate, interpolate, clamp) {
  var output,
      input;

  function remap() {
    var map = Math.min(domain.length, range.length) > 2 ? polymap : bimap;
    output = map(domain, range, clamp ? deinterpolateClamp(deinterpolate) : deinterpolate, interpolate);
    input = map(range, domain, clamp ? deinterpolateClamp(deinterpolateLinear) : deinterpolateLinear, reinterpolate);
    return scale;
  }

  function scale(x) {
    return output(x);
  }

  scale.invert = function(y) {
    return input(y);
  };

  scale.domain = function(_) {
    return arguments.length ? (domain = map.call(_, number), remap()) : domain.slice();
  };

  scale.range = function(_) {
    return arguments.length ? (range = slice.call(_), remap()) : range.slice();
  };

  scale.rangeRound = function(_) {
    return scale.range(_).interpolate(round);
  };

  scale.clamp = function(_) {
    return arguments.length ? (clamp = !!_, remap()) : clamp;
  };

  scale.interpolate = function(_) {
    return arguments.length ? (interpolate = _, remap()) : interpolate;
  };

  scale.copy = function() {
    return quantitative(domain, range, deinterpolate, reinterpolate, interpolate, clamp);
  };

  return remap();
};
<|endoftext|>