<commit_before>$('#detailsPage').live('pageshow', function(event) {
	var id = getUrlVars()["id"];
	$.getJSON(serviceURL + 'getemployee/'+id, displayEmployee);
});

function displayEmployee(data) {
	var employee = data.item;
	console.log(employee);
	$('#employeePic').attr('src', 'pics/' + employee.picture);
	$('#fullName').text(employee.firstName + ' ' + employee.lastName);
	$('#employeeTitle').text(employee.title);
	$('#city').text(employee.city);
	console.log(employee.officePhone);
	if (employee.managerId>0) {
		$('#actionList').append('

View Manager
' +
				'
' + employee.managerFirstName + ' ' + employee.managerLastName + '

');
	}
	if (employee.reportCount>0) {
		$('#actionList').append('

View Direct Reports
' +
				'
' + employee.reportCount + '

');
	}
	if (employee.email) {
		$('#actionList').append('

Email
' +
				'
' + employee.email + '

');
	}
	if (employee.officePhone) {
		$('#actionList').append('

Call Office
' +
				'
' + employee.officePhone + '

');
	}
	if (employee.cellPhone) {
		$('#actionList').append('

Call Cell
' +
				'
' + employee.cellPhone + '

');
		$('#actionList').append('

SMS
' +
				'
' + employee.cellPhone + '

');
	}
	$('#actionList').listview('refresh');

}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
<commit_msg>Updated employee's details Url<commit_after>$('#detailsPage').live('pageshow', function(event) {
	var id = getUrlVars()["id"];
	$.getJSON(serviceURL + 'employee/'+id, displayEmployee);
});

function displayEmployee(data) {
	var employee = data.item;
	$('#employeePic').attr('src', 'pics/' + employee.picture);
	$('#fullName').text(employee.firstName + ' ' + employee.lastName);
	$('#employeeTitle').text(employee.title);
	$('#city').text(employee.city);
	console.log(employee.officePhone);
	if (employee.managerId>0) {
		$('#actionList').append('

View Manager
' +
				'
' + employee.managerFirstName + ' ' + employee.managerLastName + '

');
	}
	if (employee.reportCount>0) {
		$('#actionList').append('

View Direct Reports
' +
				'
' + employee.reportCount + '

');
	}
	if (employee.email) {
		$('#actionList').append('

Email
' +
				'
' + employee.email + '

');
	}
	if (employee.officePhone) {
		$('#actionList').append('

Call Office
' +
				'
' + employee.officePhone + '

');
	}
	if (employee.cellPhone) {
		$('#actionList').append('

Call Cell
' +
				'
' + employee.cellPhone + '

');
		$('#actionList').append('

SMS
' +
				'
' + employee.cellPhone + '

');
	}
	$('#actionList').listview('refresh');

}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
<|endoftext|>


<commit_before>/* global OC */

/**
 * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
 *               2013, Morris Jobke <morris.jobke@gmail.com>
 *               2016, Christoph Wurst <christoph@owncloud.com>
 *               2017, Arthur Schiwon <blizzz@arthur-schiwon.de>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

OC.Settings = OC.Settings || {};

/**
 * The callback will be fired as soon as enter is pressed by the
 * user or 1 second after the last data entry
 *
 * @param callback
 * @param allowEmptyValue if this is set to true the callback is also called when the value is empty
 */
jQuery.fn.keyUpDelayedOrEnter = function (callback, allowEmptyValue) {
	var cb = callback;
	var that = this;

	this.on('input', _.debounce(function (event) {
		// enter is already handled in keypress
		if (event.keyCode === 13) {
			return;
		}
		if (allowEmptyValue || that.val() !== '') {
			cb(event);
		}
	}, 1000));

	this.keypress(function (event) {
		if (event.keyCode === 13 && (allowEmptyValue || that.val() !== '')) {
			event.preventDefault();
			cb(event);
		}
	});
};

function updateAvatar (hidedefault) {
	var $headerdiv = $('#header .avatardiv'),
		$displaydiv = $('#displayavatar .avatardiv'),
		user = OC.getCurrentUser();

	//Bump avatar avatarversion
	oc_userconfig.avatar.version = -(Math.floor(Math.random() * 1000));

	if (hidedefault) {
		$headerdiv.hide();
		$('#header .avatardiv').removeClass('avatardiv-shown');
	} else {
		$headerdiv.css({'background-color': ''});
		$headerdiv.avatar(user.uid, 32, true, false, undefined, user.displayName);
		$('#header .avatardiv').addClass('avatardiv-shown');
	}
	$displaydiv.css({'background-color': ''});
	$displaydiv.avatar(user.uid, 145, true, null, function() {
		$displaydiv.removeClass('loading');
		$('#displayavatar img').show();
		if($('#displayavatar img').length === 0 || oc_userconfig.avatar.generated) {
			$('#removeavatar').removeClass('inlineblock').addClass('hidden');
		} else {
			$('#removeavatar').removeClass('hidden').addClass('inlineblock');
		}
	}, user.displayName);
}

function showAvatarCropper () {
	var $cropper = $('#cropper');
	var $cropperImage = $('');
	$cropperImage.css('opacity', 0); // prevent showing the unresized image
	$cropper.children('.inner-container').prepend($cropperImage);

	$cropperImage.attr('src',
		OC.generateUrl('/avatar/tmp') + '?requesttoken=' + encodeURIComponent(oc_requesttoken) + '#' + Math.floor(Math.random() * 1000));

	$cropperImage.load(function () {
		var img = $cropperImage.get()[0];
		var selectSize = Math.min(img.width, img.height);
		var offsetX = (img.width - selectSize) / 2;
		var offsetY = (img.height - selectSize) / 2;
		$cropperImage.Jcrop({
			onChange: saveCoords,
			onSelect: saveCoords,
			aspectRatio: 1,
			boxHeight: Math.min(500, $('#app-content').height() -100),
			boxWidth: Math.min(500, $('#app-content').width()),
			setSelect: [offsetX, offsetY, selectSize, selectSize]
		}, function() {
			$cropper.show();
		});
	});
}

function sendCropData () {
	cleanCropper();

	var cropperData = $('#cropper').data();
	var data = {
		x: cropperData.x,
		y: cropperData.y,
		w: cropperData.w,
		h: cropperData.h
	};
	$.post(OC.generateUrl('/avatar/cropped'), {crop: data}, avatarResponseHandler);
}

function saveCoords (c) {
	$('#cropper').data(c);
}

function cleanCropper () {
	var $cropper = $('#cropper');
	$('#displayavatar').show();
	$cropper.hide();
	$('.jcrop-holder').remove();
	$('#cropper img').removeData('Jcrop').removeAttr('style').removeAttr('src');
	$('#cropper img').remove();
}

function avatarResponseHandler (data) {
	if (typeof data === 'string') {
		data = JSON.parse(data);
	}
	var $warning = $('#avatarform .warning');
	$warning.hide();
	if (data.status === "success") {
		$('#displayavatar .avatardiv').removeClass('icon-loading');
		oc_userconfig.avatar.generated = false;
		updateAvatar();
	} else if (data.data === "notsquare") {
		showAvatarCropper();
	} else {
		$warning.show();
		$warning.text(data.data.message);
	}
}

$(document).ready(function () {
	if($('#pass2').length) {
		$('#pass2').showPassword().keyup();
	}

	var removeloader = function () {
		setTimeout(function(){
			if ($('.password-state').length > 0) {
				$('.password-state').remove();
			}
		}, 5000)
	};

	$("#passwordbutton").click(function () {
		var isIE8or9 = $('html').hasClass('lte9');
		// FIXME - TODO - once support for IE8 and IE9 is dropped
		// for IE8 and IE9 this will check additionally if the typed in password
		// is different from the placeholder, because in IE8/9 the placeholder
		// is simply set as the value to look like a placeholder
		if ($('#pass1').val() !== '' && $('#pass2').val() !== ''
			&& !(isIE8or9 && $('#pass2').val() === $('#pass2').attr('placeholder'))) {
			// Serialize the data
			var post = $("#passwordform").serialize();
			$('#passwordchanged').hide();
			$('#passworderror').hide();
			$("#passwordbutton").attr('disabled', 'disabled');
			$("#passwordbutton").after("");
			$(".personal-show-label").hide();
			// Ajax foo
			$.post(OC.generateUrl('/settings/personal/changepassword'), post, function (data) {
				if (data.status === "success") {
					$("#passwordbutton").after("");
					removeloader();
					$('#pass1').val('');
					$('#pass2').val('').change();
				}
				if (typeof(data.data) !== "undefined") {
					OC.msg.finishedSaving('#password-error-msg', data);
				} else {
					OC.msg.finishedSaving('#password-error-msg',
						{
							'status' : 'error',
							'data' : {
								'message' : t('settings', 'Unable to change password')
							}
						}
					);
				}
				$(".personal-show-label").show();
				$(".password-loading").remove();
				$("#passwordbutton").removeAttr('disabled');
			});
			return false;
		} else {
			OC.msg.finishedSaving('#password-error-msg',
				{
					'status' : 'error',
					'data' : {
						'message' : t('settings', 'Unable to change password')
					}
				}
			);
			return false;
		}
	});

	var showVerifyDialog = function(dialog, howToVerify, verificationCode) {
		var dialogContent = dialog.children('.verification-dialog-content');
		dialogContent.children(".explainVerification").text(howToVerify);
		dialogContent.children(".verificationCode").text(verificationCode);
		dialog.css('display', 'block');
	};

	$(".verify").click(function (event) {

		event.stopPropagation();

		var verify = $(this);
		var indicator = $(this).children('img');
		var accountId = indicator.attr('id');
		var status = indicator.data('status');

		var onlyVerificationCode = false;
		if (parseInt(status) === 1) {
			onlyVerificationCode = true;
		}

		if (indicator.hasClass('verify-action')) {
			$.ajax(
				OC.generateUrl('/settings/users/{account}/verify', {account: accountId}),
				{
					method: 'GET',
					data: {onlyVerificationCode: onlyVerificationCode}
				}
			).done(function (data) {
				var dialog = verify.children('.verification-dialog');
				showVerifyDialog($(dialog), data.msg, data.code);
				indicator.attr('data-origin-title', t('settings', 'Verifying …'));
				indicator.attr('src', OC.imagePath('core', 'actions/verifying.svg'));
				indicator.data('status', '1');
			});
		}

	});

	// When the user clicks anywhere outside of the verification dialog we close it
	$(document).click(function(event){
		var element = event.target;
		var isDialog = $(element).hasClass('verificationCode')
			|| $(element).hasClass('explainVerification')
			|| $(element).hasClass('verification-dialog-content')
			|| $(element).hasClass('verification-dialog');
		if (!isDialog) {
			$(document).find('.verification-dialog').css('display', 'none');
		}
	});

	var userSettings = new OC.Settings.UserSettings();
	var federationSettingsView = new OC.Settings.FederationSettingsView({
		el: '#personal-settings',
		config: userSettings
	});

	userSettings.on("sync", function() {
		updateAvatar(false);
	});
	federationSettingsView.render();

	var updateLanguage = function () {
		if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
			OC.PasswordConfirmation.requirePasswordConfirmation(updateLanguage);
			return;
		}

		var selectedLang = $("#languageinput").val(),
			user = OC.getCurrentUser();

		$.ajax({
			url: OC.linkToOCS('cloud/users', 2) + user['uid'],
			method: 'PUT',
			data: {
				key: 'language',
				value: selectedLang
			},
			success: function() {
				location.reload();
			},
			fail: function() {
				OC.Notification.showTemporary(t('settings', 'An error occured while changing your language. Please reload the page and try again.'));
			}
		});
	};
	$("#languageinput").change(updateLanguage);

	var uploadparms = {
		pasteZone: null,
		done: function (e, data) {
			var response = data;
			if (typeof data.result === 'string') {
				response = JSON.parse(data.result);
			} else if (data.result && data.result.length) {
				// fetch response from iframe
				response = JSON.parse(data.result[0].body.innerText);
			} else {
				response = data.result;
			}
			avatarResponseHandler(response);
		},
		submit: function(e, data) {
			$('#displayavatar img').hide();
			$('#displayavatar .avatardiv').addClass('icon-loading');
			data.formData = _.extend(data.formData || {}, {
				requesttoken: OC.requestToken
			});
		},
		fail: function (e, data){
			var msg = data.jqXHR.statusText + ' (' + data.jqXHR.status + ')';
			if (!_.isUndefined(data.jqXHR.responseJSON) &&
				!_.isUndefined(data.jqXHR.responseJSON.data) &&
				!_.isUndefined(data.jqXHR.responseJSON.data.message)
			) {
				msg = data.jqXHR.responseJSON.data.message;
			}
			avatarResponseHandler({
				data: {
					message: msg
				}
			});
		}
	};

	$('#uploadavatar').fileupload(uploadparms);

	$('#selectavatar').click(function () {
		OC.dialogs.filepicker(
			t('settings', "Select a profile picture"),
			function (path) {
				$('#displayavatar img').hide();
				$('#displayavatar .avatardiv').addClass('loading');
				$.ajax({
					type: "POST",
					url: OC.generateUrl('/avatar/'),
					data: { path: path }
				}).done(avatarResponseHandler)
					.fail(function(jqXHR) {
						var msg = jqXHR.statusText + ' (' + jqXHR.status + ')';
						if (!_.isUndefined(jqXHR.responseJSON) &&
							!_.isUndefined(jqXHR.responseJSON.data) &&
							!_.isUndefined(jqXHR.responseJSON.data.message)
						) {
							msg = jqXHR.responseJSON.data.message;
						}
						avatarResponseHandler({
							data: {
								message: msg
							}
						});
					});
			},
			false,
			["image/png", "image/jpeg"]
		);
	});

	$('#removeavatar').click(function () {
		$.ajax({
			type: 'DELETE',
			url: OC.generateUrl('/avatar/'),
			success: function () {
				oc_userconfig.avatar.generated = true;
				updateAvatar(true);
			}
		});
	});

	$('#abortcropperbutton').click(function () {
		$('#displayavatar .avatardiv').removeClass('loading');
		$('#displayavatar img').show();
		cleanCropper();
	});

	$('#sendcropperbutton').click(function () {
		sendCropData();
	});

	$('#pass2').strengthify({
		zxcvbn: OC.linkTo('core','vendor/zxcvbn/dist/zxcvbn.js'),
		titles: [
			t('settings', 'Very weak password'),
			t('settings', 'Weak password'),
			t('settings', 'So-so password'),
			t('settings', 'Good password'),
			t('settings', 'Strong password')
		],
		drawTitles: true,
		$addAfter: $('input[name="newpassword-clone"]'),
	});

	// Load the big avatar
	var user = OC.getCurrentUser();
	$('#avatarform .avatardiv').avatar(user.uid, 145, true, null, function() {
		if($('#displayavatar img').length === 0 || oc_userconfig.avatar.generated) {
			$('#removeavatar').removeClass('inlineblock').addClass('hidden');
		} else {
			$('#removeavatar').removeClass('hidden').addClass('inlineblock');
		}
	}, user.displayName);
});

OC.Settings.updateAvatar = updateAvatar;
<commit_msg>Prevent double selection of avatar and loading fix<commit_after>/* global OC */

/**
 * Copyright (c) 2011, Robin Appelman <icewind1991@gmail.com>
 *               2013, Morris Jobke <morris.jobke@gmail.com>
 *               2016, Christoph Wurst <christoph@owncloud.com>
 *               2017, Arthur Schiwon <blizzz@arthur-schiwon.de>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 */

OC.Settings = OC.Settings || {};

/**
 * The callback will be fired as soon as enter is pressed by the
 * user or 1 second after the last data entry
 *
 * @param callback
 * @param allowEmptyValue if this is set to true the callback is also called when the value is empty
 */
jQuery.fn.keyUpDelayedOrEnter = function (callback, allowEmptyValue) {
	var cb = callback;
	var that = this;

	this.on('input', _.debounce(function (event) {
		// enter is already handled in keypress
		if (event.keyCode === 13) {
			return;
		}
		if (allowEmptyValue || that.val() !== '') {
			cb(event);
		}
	}, 1000));

	this.keypress(function (event) {
		if (event.keyCode === 13 && (allowEmptyValue || that.val() !== '')) {
			event.preventDefault();
			cb(event);
		}
	});
};

function updateAvatar (hidedefault) {
	var $headerdiv = $('#header .avatardiv'),
		$displaydiv = $('#displayavatar .avatardiv'),
		user = OC.getCurrentUser();

	//Bump avatar avatarversion
	oc_userconfig.avatar.version = -(Math.floor(Math.random() * 1000));

	if (hidedefault) {
		$headerdiv.hide();
		$('#header .avatardiv').removeClass('avatardiv-shown');
	} else {
		$headerdiv.css({'background-color': ''});
		$headerdiv.avatar(user.uid, 32, true, false, undefined, user.displayName);
		$('#header .avatardiv').addClass('avatardiv-shown');
	}
	$displaydiv.css({'background-color': ''});
	$displaydiv.avatar(user.uid, 145, true, null, function() {
		$displaydiv.removeClass('loading');
		$('#displayavatar img').show();
		if($('#displayavatar img').length === 0 || oc_userconfig.avatar.generated) {
			$('#removeavatar').removeClass('inlineblock').addClass('hidden');
		} else {
			$('#removeavatar').removeClass('hidden').addClass('inlineblock');
		}
	}, user.displayName);
}

function showAvatarCropper () {
	var $cropper = $('#cropper');
	var $cropperImage = $('');
	$cropperImage.css('opacity', 0); // prevent showing the unresized image
	$cropper.children('.inner-container').prepend($cropperImage);

	$cropperImage.attr('src',
		OC.generateUrl('/avatar/tmp') + '?requesttoken=' + encodeURIComponent(oc_requesttoken) + '#' + Math.floor(Math.random() * 1000));

	$cropperImage.load(function () {
		var img = $cropperImage.get()[0];
		var selectSize = Math.min(img.width, img.height);
		var offsetX = (img.width - selectSize) / 2;
		var offsetY = (img.height - selectSize) / 2;
		$cropperImage.Jcrop({
			onChange: saveCoords,
			onSelect: saveCoords,
			aspectRatio: 1,
			boxHeight: Math.min(500, $('#app-content').height() -100),
			boxWidth: Math.min(500, $('#app-content').width()),
			setSelect: [offsetX, offsetY, selectSize, selectSize]
		}, function() {
			$cropper.show();
		});
	});
}

function sendCropData () {
	cleanCropper();

	var cropperData = $('#cropper').data();
	var data = {
		x: cropperData.x,
		y: cropperData.y,
		w: cropperData.w,
		h: cropperData.h
	};
	$.post(OC.generateUrl('/avatar/cropped'), {crop: data}, avatarResponseHandler);
}

function saveCoords (c) {
	$('#cropper').data(c);
}

function cleanCropper () {
	var $cropper = $('#cropper');
	$('#displayavatar').show();
	$cropper.hide();
	$('.jcrop-holder').remove();
	$('#cropper img').removeData('Jcrop').removeAttr('style').removeAttr('src');
	$('#cropper img').remove();
}

function avatarResponseHandler (data) {
	if (typeof data === 'string') {
		data = JSON.parse(data);
	}
	var $warning = $('#avatarform .warning');
	$warning.hide();
	if (data.status === "success") {
		$('#displayavatar .avatardiv').removeClass('icon-loading');
		oc_userconfig.avatar.generated = false;
		updateAvatar();
	} else if (data.data === "notsquare") {
		showAvatarCropper();
	} else {
		$warning.show();
		$warning.text(data.data.message);
	}
}

$(document).ready(function () {
	if($('#pass2').length) {
		$('#pass2').showPassword().keyup();
	}

	var removeloader = function () {
		setTimeout(function(){
			if ($('.password-state').length > 0) {
				$('.password-state').remove();
			}
		}, 5000)
	};

	$("#passwordbutton").click(function () {
		var isIE8or9 = $('html').hasClass('lte9');
		// FIXME - TODO - once support for IE8 and IE9 is dropped
		// for IE8 and IE9 this will check additionally if the typed in password
		// is different from the placeholder, because in IE8/9 the placeholder
		// is simply set as the value to look like a placeholder
		if ($('#pass1').val() !== '' && $('#pass2').val() !== ''
			&& !(isIE8or9 && $('#pass2').val() === $('#pass2').attr('placeholder'))) {
			// Serialize the data
			var post = $("#passwordform").serialize();
			$('#passwordchanged').hide();
			$('#passworderror').hide();
			$("#passwordbutton").attr('disabled', 'disabled');
			$("#passwordbutton").after("");
			$(".personal-show-label").hide();
			// Ajax foo
			$.post(OC.generateUrl('/settings/personal/changepassword'), post, function (data) {
				if (data.status === "success") {
					$("#passwordbutton").after("");
					removeloader();
					$('#pass1').val('');
					$('#pass2').val('').change();
				}
				if (typeof(data.data) !== "undefined") {
					OC.msg.finishedSaving('#password-error-msg', data);
				} else {
					OC.msg.finishedSaving('#password-error-msg',
						{
							'status' : 'error',
							'data' : {
								'message' : t('settings', 'Unable to change password')
							}
						}
					);
				}
				$(".personal-show-label").show();
				$(".password-loading").remove();
				$("#passwordbutton").removeAttr('disabled');
			});
			return false;
		} else {
			OC.msg.finishedSaving('#password-error-msg',
				{
					'status' : 'error',
					'data' : {
						'message' : t('settings', 'Unable to change password')
					}
				}
			);
			return false;
		}
	});

	var showVerifyDialog = function(dialog, howToVerify, verificationCode) {
		var dialogContent = dialog.children('.verification-dialog-content');
		dialogContent.children(".explainVerification").text(howToVerify);
		dialogContent.children(".verificationCode").text(verificationCode);
		dialog.css('display', 'block');
	};

	$(".verify").click(function (event) {

		event.stopPropagation();

		var verify = $(this);
		var indicator = $(this).children('img');
		var accountId = indicator.attr('id');
		var status = indicator.data('status');

		var onlyVerificationCode = false;
		if (parseInt(status) === 1) {
			onlyVerificationCode = true;
		}

		if (indicator.hasClass('verify-action')) {
			$.ajax(
				OC.generateUrl('/settings/users/{account}/verify', {account: accountId}),
				{
					method: 'GET',
					data: {onlyVerificationCode: onlyVerificationCode}
				}
			).done(function (data) {
				var dialog = verify.children('.verification-dialog');
				showVerifyDialog($(dialog), data.msg, data.code);
				indicator.attr('data-origin-title', t('settings', 'Verifying …'));
				indicator.attr('src', OC.imagePath('core', 'actions/verifying.svg'));
				indicator.data('status', '1');
			});
		}

	});

	// When the user clicks anywhere outside of the verification dialog we close it
	$(document).click(function(event){
		var element = event.target;
		var isDialog = $(element).hasClass('verificationCode')
			|| $(element).hasClass('explainVerification')
			|| $(element).hasClass('verification-dialog-content')
			|| $(element).hasClass('verification-dialog');
		if (!isDialog) {
			$(document).find('.verification-dialog').css('display', 'none');
		}
	});

	var userSettings = new OC.Settings.UserSettings();
	var federationSettingsView = new OC.Settings.FederationSettingsView({
		el: '#personal-settings',
		config: userSettings
	});

	userSettings.on("sync", function() {
		updateAvatar(false);
	});
	federationSettingsView.render();

	var updateLanguage = function () {
		if (OC.PasswordConfirmation.requiresPasswordConfirmation()) {
			OC.PasswordConfirmation.requirePasswordConfirmation(updateLanguage);
			return;
		}

		var selectedLang = $("#languageinput").val(),
			user = OC.getCurrentUser();

		$.ajax({
			url: OC.linkToOCS('cloud/users', 2) + user['uid'],
			method: 'PUT',
			data: {
				key: 'language',
				value: selectedLang
			},
			success: function() {
				location.reload();
			},
			fail: function() {
				OC.Notification.showTemporary(t('settings', 'An error occured while changing your language. Please reload the page and try again.'));
			}
		});
	};
	$("#languageinput").change(updateLanguage);

	var uploadparms = {
		pasteZone: null,
		done: function (e, data) {
			var response = data;
			if (typeof data.result === 'string') {
				response = JSON.parse(data.result);
			} else if (data.result && data.result.length) {
				// fetch response from iframe
				response = JSON.parse(data.result[0].body.innerText);
			} else {
				response = data.result;
			}
			avatarResponseHandler(response);
		},
		submit: function(e, data) {
			$('#displayavatar img').hide();
			$('#displayavatar .avatardiv').addClass('icon-loading');
			$('#uploadavatar').prop('disabled', true)
			data.formData = _.extend(data.formData || {}, {
				requesttoken: OC.requestToken
			});
		},
		fail: function (e, data) {
			$('#displayavatar .avatardiv').removeClass('icon-loading');
			$('#uploadavatar').prop('disabled', false)
			var msg = data.jqXHR.statusText + ' (' + data.jqXHR.status + ')';
			if (!_.isUndefined(data.jqXHR.responseJSON) &&
				!_.isUndefined(data.jqXHR.responseJSON.data) &&
				!_.isUndefined(data.jqXHR.responseJSON.data.message)
			) {
				msg = data.jqXHR.responseJSON.data.message;
			}
			avatarResponseHandler({
				data: {
					message: msg
				}
			});
		}
	};

	$('#uploadavatar').fileupload(uploadparms);

	$('#selectavatar').click(function () {
		OC.dialogs.filepicker(
			t('settings', "Select a profile picture"),
			function (path) {
				$('#displayavatar img').hide();
				$('#displayavatar .avatardiv').addClass('icon-loading');
				$('#uploadavatar').prop('disabled', true)
				$.ajax({
					type: "POST",
					url: OC.generateUrl('/avatar/'),
					data: { path: path }
				}).done(avatarResponseHandler)
					.fail(function(jqXHR) {
						var msg = jqXHR.statusText + ' (' + jqXHR.status + ')';
						if (!_.isUndefined(jqXHR.responseJSON) &&
							!_.isUndefined(jqXHR.responseJSON.data) &&
							!_.isUndefined(jqXHR.responseJSON.data.message)
						) {
							msg = jqXHR.responseJSON.data.message;
						}
						avatarResponseHandler({
							data: {
								message: msg
							}
						});
					});
			},
			false,
			["image/png", "image/jpeg"]
		);
	});

	$('#removeavatar').click(function () {
		$.ajax({
			type: 'DELETE',
			url: OC.generateUrl('/avatar/'),
			success: function () {
				oc_userconfig.avatar.generated = true;
				updateAvatar(true);
			}
		});
	});

	$('#abortcropperbutton').click(function () {
		$('#displayavatar .avatardiv').removeClass('icon-loading');
		$('#displayavatar img').show();
		$('#uploadavatar').prop('disabled', false)
		cleanCropper();
	});

	$('#sendcropperbutton').click(function () {
		sendCropData();
	});

	$('#pass2').strengthify({
		zxcvbn: OC.linkTo('core','vendor/zxcvbn/dist/zxcvbn.js'),
		titles: [
			t('settings', 'Very weak password'),
			t('settings', 'Weak password'),
			t('settings', 'So-so password'),
			t('settings', 'Good password'),
			t('settings', 'Strong password')
		],
		drawTitles: true,
		$addAfter: $('input[name="newpassword-clone"]'),
	});

	// Load the big avatar
	var user = OC.getCurrentUser();
	$('#avatarform .avatardiv').avatar(user.uid, 145, true, null, function() {
		if($('#displayavatar img').length === 0 || oc_userconfig.avatar.generated) {
			$('#removeavatar').removeClass('inlineblock').addClass('hidden');
		} else {
			$('#removeavatar').removeClass('hidden').addClass('inlineblock');
		}
	}, user.displayName);
});

OC.Settings.updateAvatar = updateAvatar;
<|endoftext|>


<commit_before>var Dino = function()
{};
Dino.prototype.add = function(posX, posY)
{

	this.sfxEat = game.add.audio('smash',soundLevel,false);
	this.sfxlifeUp = game.add.audio('lifeUp',soundLevel,false);
	this.sfxTakeDamage = game.add.audio('takeDamage',soundLevel,false);
	this.sfxFoodDown = game.add.audio('foodDown',soundLevel,false);
	this.score = 0;
	this.enemysKiled = 0;
	this.killsToCallTank = 0;
	this.killsNeeded = 45;
	this.foodCount=0;
	this.safetyMode = false;
	this.lives = 3;
	this.food = 5;
	this.playerSpeed = 250;
	this.jumpForce = 520;
	this.timeToAtack = 0;
	this.atackDelay = 400;
	this.onAtackMode = false;
	this.isAlive = true;
	this.sprite = game.add.sprite(posX, posY ,'dino');
	game.physics.enable(this.sprite);
	this.sprite.body.maxVelocity.y = 800;
	this.sprite.anchor.setTo(0.4 ,0.5);
	this.sprite.smoothed = false;
	this.sprite.animations.add('stoped',[1],1);
	this.sprite.animations.add('walk',[1,2,3,4,5,6,7,0],12,true);
	this.sprite.animations.add('atack',[10,11,1],10);
	this.dieAnim = this.sprite.animations.add('die',[12,13,14,15,16,17,18],10);
	this.dieAnim.onComplete.add(function(){this.callGameOver();},this);
	this.sprite.body.collideWorldBounds = true;
	this.sprite.body.checkCollision.up = false;
	this.sprite.body.checkCollision.left = false;
	this.sprite.body.checkCollision.right = false;
	this.sprite.body.setSize(32,128,-4,-4);
	this.sprite.body.tilePadding.y = 100;
	this.sprite.body.tilePadding.x = 100;
	this.cursors = game.input.keyboard.createCursorKeys();
	this.jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
	this.atackButton = game.input.keyboard.addKey(Phaser.Keyboard.X);
	this.soundJump = game.add.audio('jump',soundLevel,false);
	this.hungryTimeDelay=10000;
	this.hungryTime = game.time.now + this.hungryTimeDelay;
	this.foods = game.add.group();
	this.foods.fixedToCamera = true;
	for(var i = 0;i< this.food;i++)
		this.foods.create(i*60,48,'food');
	this.hearts = game.add.group();
	this.hearts.fixedToCamera=true;
	for(var i =0; i<this.lives;i++)
		this.hearts.create(i*64,0, 'heart');
};

Dino.prototype.update = function()
{
	this.regulateFood();
	this.enableAtack();
	this.enableJump();
	this.enableMovement();
};
Dino.prototype.enableMovement = function ()
{
	this.sprite.body.velocity.x = 0;
	if(this.cursors.left.isDown && !this.onAtackMode)
	{
		this.sprite.body.setSize(32,128,-2,-4);
		this.sprite.scale.setTo(-1,1);
		this.sprite.animations.play('walk');
		this.sprite.body.velocity.x = -this.playerSpeed;
	}
	else if(this.cursors.right.isDown && !this.onAtackMode)
		{
		this.sprite.body.setSize(32,128,-4,-4);
		this.sprite.scale.setTo(1,1);
		this.sprite.animations.play('walk');
		this.sprite.body.velocity.x = this.playerSpeed;
		}
	else
		if(this.sprite.body.velocity.y==0 && this.sprite.body.velocity.x==0 && this.sprite.animations.currentAnim.name!= 'atack' && this.sprite.animations.currentAnim.name!= 'die')
	{
		this.sprite.animations.play('stoped');
	}
	if(this.sprite.body.velocity.y < 0)
		this.sprite.frame = 9;
		else if(this.sprite.body.velocity.y > 0)
		this.sprite.frame = 8;
};

Dino.prototype.enableJump = function()
{
	if (this.jumpButton.isDown && this.sprite.body.onFloor() && !this.onAtackMode)
	{
		this.soundJump.play();
		this.sprite.body.velocity.y = -this.jumpForce;
	}
};

Dino.prototype.enableAtack = function()
{
	if(this.atackButton.isDown && game.time.now >= this.timeToAtack && this.sprite.body.onFloor())
	{
		if(this.sprite.scale.x == -1)
			this.sprite.body.setSize(96,128,-50,-4);
		else
			this.sprite.body.setSize(96,128,30,-4);
		this.onAtackMode = true;
		this.sprite.animations.stop();
		this.sprite.animations.play('atack');
		this.timeToAtack = game.time.now + this.atackDelay;
	}
	if(game.time.now >= this.timeToAtack)
		this.onAtackMode = false;
};

Dino.prototype.smash = function(dino,target)
{
	var p;
	if(target.tag != 'human')
		dino.body.velocity.y = -this.jumpForce/1.2;
	target.body.velocity.y = -150;
	switch(target.job)
	{
		case 'normalCar':
		p = 12;
		this.score += p;
		break;
		case 'people':
			splashBlood1(target.x,target.y);
		p = 5;
		this.score += p;
		break;
		case 'shooter' :
			splashBlood1(target.x,target.y);
		p = 12;
		this.score += p;
		splashBlood1(target.x,target.y);
		break;
		case 'bomber' :
			splashBlood1(target.x,target.y);
		p = 16;
		this.score += p;
		break;
		case 'sniper' :
			splashBlood1(target.x,target.y);
		p = 20;
		this.score += p;
		default : this.score +=1;
	}
	this.displayPoint(p);
	target.takeDamage();
};

Dino.prototype.bit = function(dino,target)
{
	if(this.onAtackMode)
	{
		var p;
		switch(target.tag)
		{
			case 'human':
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 5;
				this.score += p;
			break;
			case 'shooter' :
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 10;
				this.score += p;
			break;
			case 'bomber' :
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 15;
				this.score += p;
			break;
			case 'sniper' :
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 17;
				this.score += p;
			break;
		}
		this.displayPoint(p);
		target.takeDamage();
	}
};

Dino.prototype.takeDamage = function(dino, target)
{
	if(!this.safetyMode)
	{
		this.startSafetyMode();
		if(target.isTank)
		{
			explode(dino.x,target.y);
			explode(dino.x+100,target.y);
			explode(dino.x-100,target.y);
			explode(dino.x,target.y-100);
			explode(dino.x,target.y+100);
		}
		if(target.isBomber)
			explode(dino.x,target.y);
		for(var i = 0; i < target.damage; i++)
		{
			if(this.hearts.countLiving()!==0)
				this.hearts.getTop().destroy();
		}
		if(this.hearts.countLiving()==0)
				this.sprite.animations.play('die');
	}
	target.kill();
};

Dino.prototype.hitByCar = function(dino,target)
{
	if(this.hearts.countLiving()!==0 && !target.destroyed)
	{
		this.startSafetyMode();
		this.hearts.getTop().destroy();
	}
	if(this.hearts.countLiving()==0 && this.isAlive )
	{
		this.isAlive = false;
		this.sprite.animations.play('die');
	}
	target.runOver(this);
};

Dino.prototype.callGameOver = function()
{
	var gO = game.add.sprite(game.camera.width/2-200, game.camera.height/2-50,'scoreTable');
	gO.fixedToCamera = true;
	track.stop();
	var score = game.add.text(game.camera.width/2 - 50, game.camera.height/2 -30, this.score,style6);
	score.fixedToCamera = true;
	var s = game.add.audio('lose',soundLevel,false);
	s.play();
	game.input.onDown.addOnce(function() {
	game.state.restart();
        },this);
};

Dino.prototype.startSafetyMode = function()
{
	if(this.hearts.countLiving()>1)
	{
		this.sfxTakeDamage.play();
		this.safetyMode = true;
		this.sprite.alpha= 0;
		var safetyTween = game.add.tween(this.sprite).to( { alpha: 1 }, 50, Phaser.Easing.Linear.None, true, 0, 10, true);
		safetyTween.onComplete.add(function(){this.safetyMode = false;},this);
	}
};

Dino.prototype.displayPoint = function(point)
{
	var txt = game.add.text(this.sprite.x, this.sprite.y, point, style3);
	var txt2 = game.add.text(this.sprite.x, this.sprite.y, point, style4);
	txt2.alpha = 0;
	game.add.tween(txt).to( { y:txt.y - 300 }, 4000, Phaser.Easing.Linear.None, true, 0, 0, true);
	game.add.tween(txt2).to( { y:txt.y - 300 },4000, Phaser.Easing.Linear.None, true, 0, 0, true);
	var blinkTween1 = game.add.tween(txt).to( { alpha:0 }, 50, Phaser.Easing.Linear.None, true, 0, 25, true);
	var blinkTween2 = game.add.tween(txt2).to( { alpha:1 }, 50, Phaser.Easing.Linear.None, true, 0, 25, true);
	blinkTween1.onComplete.add(function(){txt.destroy();});
	blinkTween2.onComplete.add(function(){txt.destroy();});
};

Dino.prototype.regulateFood = function()
{
	if (game.time.now > this.hungryTime)
	{
		if(this.foods.countLiving()!=0)
		{
			this.foods.getTop().destroy();
			this.sfxFoodDown.play();
		}
		else
			if(this.hearts.countLiving()!=0)
			{
				this.sfxTakeDamage.play();
				this.hearts.getTop().destroy();
			}
			if(this.hearts.countLiving()==0)
				this.sprite.animations.play('die');
		this.hungryTime = game.time.now + this.hungryTimeDelay;
	}
};
Dino.prototype.replaceFood = function()
{
	this.foodCount += 1;
	if(this.hearts.countLiving()<5 && this.foodCount >=5)
	{
		this.hearts.create(this.hearts.countLiving() * 64,0, 'heart');
		this.sfxlifeUp.play();
		this.foodCount = 0;
	}
	if(this.foods.countLiving()<5)
		this.foods.create(this.foods.countLiving() * 60,48, 'food');
	this.hungryTime = game.time.now + this.hungryTimeDelay;
};<commit_msg>[phaser][dinopixel] atualizacao(de bugs)<commit_after>var Dino = function()
{};
Dino.prototype.add = function(posX, posY)
{

	this.sfxEat = game.add.audio('smash',soundLevel,false);
	this.sfxlifeUp = game.add.audio('lifeUp',soundLevel,false);
	this.sfxTakeDamage = game.add.audio('takeDamage',soundLevel,false);
	this.sfxFoodDown = game.add.audio('foodDown',soundLevel,false);
	this.score = 0;
	this.enemysKiled = 0;
	this.killsToCallTank = 0;
	this.killsNeeded = 45;
	this.foodCount=0;
	this.safetyMode = false;
	this.lives = 3;
	this.food = 5;
	this.playerSpeed = 250;
	this.jumpForce = 520;
	this.timeToAtack = 0;
	this.atackDelay = 400;
	this.onAtackMode = false;
	this.isAlive = true;
	this.sprite = game.add.sprite(posX, posY ,'dino');
	game.physics.enable(this.sprite);
	this.sprite.body.maxVelocity.y = 800;
	this.sprite.anchor.setTo(0.4 ,0.5);
	this.sprite.smoothed = false;
	this.sprite.animations.add('stoped',[1],1);
	this.sprite.animations.add('walk',[1,2,3,4,5,6,7,0],12,true);
	this.sprite.animations.add('atack',[10,11,1],10);
	this.dieAnim = this.sprite.animations.add('die',[12,13,14,15,16,17,18],10);
	this.dieAnim.onComplete.add(function(){this.callGameOver();},this);
	this.sprite.body.collideWorldBounds = true;
	this.sprite.body.checkCollision.up = false;
	this.sprite.body.checkCollision.left = false;
	this.sprite.body.checkCollision.right = false;
	this.sprite.body.setSize(32,128,-4,-4);
	this.sprite.body.tilePadding.y = 100;
	this.sprite.body.tilePadding.x = 100;
	this.cursors = game.input.keyboard.createCursorKeys();
	this.jumpButton = game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
	this.atackButton = game.input.keyboard.addKey(Phaser.Keyboard.X);
	this.soundJump = game.add.audio('jump',soundLevel,false);
	this.hungryTimeDelay=10000;
	this.hungryTime = game.time.now + this.hungryTimeDelay;
	this.foods = game.add.group();
	this.foods.fixedToCamera = true;
	for(var i = 0;i< this.food;i++)
		this.foods.create(i*60,48,'food');
	this.hearts = game.add.group();
	this.hearts.fixedToCamera=true;
	for(var i =0; i<this.lives;i++)
		this.hearts.create(i*64,0, 'heart');
};

Dino.prototype.update = function()
{
	this.regulateFood();
	this.enableAtack();
	this.enableJump();
	this.enableMovement();
};
Dino.prototype.enableMovement = function ()
{
	this.sprite.body.velocity.x = 0;
	if(this.cursors.left.isDown && !this.onAtackMode)
	{
		this.sprite.body.setSize(32,128,-2,-4);
		this.sprite.scale.setTo(-1,1);
		this.sprite.animations.play('walk');
		this.sprite.body.velocity.x = -this.playerSpeed;
	}
	else if(this.cursors.right.isDown && !this.onAtackMode)
		{
		this.sprite.body.setSize(32,128,-4,-4);
		this.sprite.scale.setTo(1,1);
		this.sprite.animations.play('walk');
		this.sprite.body.velocity.x = this.playerSpeed;
		}
	else
		if(this.sprite.body.velocity.y==0 && this.sprite.body.velocity.x==0 && this.sprite.animations.currentAnim.name!= 'atack' && this.sprite.animations.currentAnim.name!= 'die')
	{
		this.sprite.animations.play('stoped');
	}
	if(this.sprite.body.velocity.y < 0)
		this.sprite.frame = 9;
		else if(this.sprite.body.velocity.y > 0)
		this.sprite.frame = 8;
};

Dino.prototype.enableJump = function()
{
	if (this.jumpButton.isDown && this.sprite.body.onFloor() && !this.onAtackMode)
	{
		this.soundJump.play();
		this.sprite.body.velocity.y = -this.jumpForce;
	}
};

Dino.prototype.enableAtack = function()
{
	if(this.atackButton.isDown && game.time.now >= this.timeToAtack && this.sprite.body.onFloor())
	{
		if(this.sprite.scale.x == -1)
			this.sprite.body.setSize(96,128,-50,-4);
		else
			this.sprite.body.setSize(96,128,30,-4);
		this.onAtackMode = true;
		this.sprite.animations.stop();
		this.sprite.animations.play('atack');
		this.timeToAtack = game.time.now + this.atackDelay;
	}
	if(game.time.now >= this.timeToAtack)
		this.onAtackMode = false;
};

Dino.prototype.smash = function(dino,target)
{
	var p;
	if(target.tag != 'human')
		dino.body.velocity.y = -this.jumpForce/1.2;
	target.body.velocity.y = -150;
	switch(target.job)
	{
		case 'normalCar':
		p = 12;
		this.score += p;
		break;
		case 'people':
			splashBlood1(target.x,target.y);
		p = 5;
		this.score += p;
		break;
		case 'shooter' :
			splashBlood1(target.x,target.y);
		p = 12;
		this.score += p;
		splashBlood1(target.x,target.y);
		break;
		case 'bomber' :
			splashBlood1(target.x,target.y);
		p = 16;
		this.score += p;
		break;
		case 'sniper' :
			splashBlood1(target.x,target.y);
		p = 20;
		this.score += p;
		default : this.score +=1;
	}
	this.displayPoint(p);
	target.takeDamage();
};

Dino.prototype.bit = function(dino,target)
{
	if(this.onAtackMode)
	{
		var p;
		switch(target.tag)
		{
			case 'human':
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 5;
				this.score += p;
			break;
			case 'shooter' :
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 10;
				this.score += p;
			break;
			case 'bomber' :
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 15;
				this.score += p;
			break;
			case 'sniper' :
				splashBlood2(target.x,target.y);
				this.replaceFood();
				this.sfxEat.play();
				p = 17;
				this.score += p;
			break;
		}
		this.displayPoint(p);
		target.takeDamage();
	}
};

Dino.prototype.takeDamage = function(dino, target)
{
	if(!this.safetyMode)
	{
		this.startSafetyMode();
		if(target.isTank)
		{
			explode(dino.x,target.y);
			explode(dino.x+100,target.y);
			explode(dino.x-100,target.y);
			explode(dino.x,target.y-100);
			explode(dino.x,target.y+100);
		}
		if(target.isBomber)
			explode(dino.x,target.y);
		for(var i = 0; i < target.damage; i++)
		{
			if(this.hearts.countLiving()!==0)
				this.hearts.getTop().destroy();
		}
		if(this.hearts.countLiving()==0)
				this.sprite.animations.play('die');
	}
	target.kill();
};

Dino.prototype.hitByCar = function(dino,target)
{
	if(this.hearts.countLiving()!==0 && !target.destroyed)
	{
		this.startSafetyMode();
		this.hearts.getTop().destroy();
	}
	if(this.hearts.countLiving()==0 && this.isAlive )
	{
		this.isAlive = false;
		this.sprite.animations.play('die');
	}
	target.runOver(this);
};

Dino.prototype.callGameOver = function()
{
	var gO = game.add.sprite(game.camera.width/2-200, game.camera.height/2-250,'scoreTable');
	gO.fixedToCamera = true;
	track.stop();
	var score = game.add.text(game.camera.width/2 - 50, game.camera.height/2 -30, this.score,style6);
	score.fixedToCamera = true;
	var s = game.add.audio('lose',soundLevel,false);
	s.play();
	game.input.onDown.addOnce(function() {
	game.state.restart();
        },this);
};

Dino.prototype.startSafetyMode = function()
{
	if(this.hearts.countLiving()>1)
	{
		this.sfxTakeDamage.play();
		this.safetyMode = true;
		this.sprite.alpha= 0;
		var safetyTween = game.add.tween(this.sprite).to( { alpha: 1 }, 50, Phaser.Easing.Linear.None, true, 0, 10, true);
		safetyTween.onComplete.add(function(){this.safetyMode = false;},this);
	}
};

Dino.prototype.displayPoint = function(point)
{
	var txt = game.add.text(this.sprite.x, this.sprite.y, point, style3);
	var txt2 = game.add.text(this.sprite.x, this.sprite.y, point, style4);
	txt2.alpha = 0;
	game.add.tween(txt).to( { y:txt.y - 300 }, 4000, Phaser.Easing.Linear.None, true, 0, 0, true);
	game.add.tween(txt2).to( { y:txt.y - 300 },4000, Phaser.Easing.Linear.None, true, 0, 0, true);
	var blinkTween1 = game.add.tween(txt).to( { alpha:0 }, 50, Phaser.Easing.Linear.None, true, 0, 25, true);
	var blinkTween2 = game.add.tween(txt2).to( { alpha:1 }, 50, Phaser.Easing.Linear.None, true, 0, 25, true);
	blinkTween1.onComplete.add(function(){txt.destroy();});
	blinkTween2.onComplete.add(function(){txt.destroy();});
};

Dino.prototype.regulateFood = function()
{
	if (game.time.now > this.hungryTime)
	{
		if(this.foods.countLiving()!=0)
		{
			this.foods.getTop().destroy();
			this.sfxFoodDown.play();
		}
		else
			if(this.hearts.countLiving()!=0)
			{
				this.sfxTakeDamage.play();
				this.hearts.getTop().destroy();
			}
			if(this.hearts.countLiving()==0)
				this.sprite.animations.play('die');
		this.hungryTime = game.time.now + this.hungryTimeDelay;
	}
};
Dino.prototype.replaceFood = function()
{
	this.foodCount += 1;
	if(this.hearts.countLiving()<5 && this.foodCount >=5)
	{
		this.hearts.create(this.hearts.countLiving() * 64,0, 'heart');
		this.sfxlifeUp.play();
		this.foodCount = 0;
	}
	if(this.foods.countLiving()<5)
		this.foods.create(this.foods.countLiving() * 60,48, 'food');
	this.hungryTime = game.time.now + this.hungryTimeDelay;
};<|endoftext|>


<commit_before>import Awesomplete from 'awesomplete';

frappe.ui.form.ControlMultiSelectPills = class ControlMultiSelectPills extends frappe.ui.form.ControlAutocomplete {
	make_input() {
		super.make_input();
		this.$input_area = $(this.input_area);
		this.$multiselect_wrapper = $('
')
			.addClass('form-control table-multiselect')
			.appendTo(this.$input_area);

		this.$input.removeClass('form-control');
		this.$input_area.find('.awesomplete').appendTo(this.$multiselect_wrapper);

		this.$input.on("awesomplete-selectcomplete", () => {
			this.$input.val('').focus();
		});

		// used as an internal model to store values
		this.rows = [];

		this.$input_area.on('click', '.btn-remove', (e) => {
			const $target = $(e.currentTarget);
			const $value = $target.closest('.tb-selected-value');

			const value = decodeURIComponent($value.data().value);
			this.rows = this.rows.filter(val => val !== value);

			this.parse_validate_and_set_in_model('');
		});

		this.$input.on('keydown', e => {
			// if backspace key pressed on empty input, delete last value
			if (e.keyCode == frappe.ui.keyCode.BACKSPACE && e.target.value === '') {
				this.rows = this.rows.slice(0, this.rows.length - 1);
				this.parse_validate_and_set_in_model('');
			}
		});
	}

	parse(value) {
		if (value) {
			this.rows.push(value);
		}

		return this.rows;
	}

	validate(value) {
		const rows = (value || []).slice();

		if (rows.length === 0) {
			return rows;
		}

		const all_rows_except_last = rows.slice(0, rows.length - 1);
		const last_value = rows[rows.length - 1];

		// falsy value
		if (!last_value) {
			return all_rows_except_last;
		}

		// duplicate value
		if (all_rows_except_last.includes(last_value)) {
			return all_rows_except_last;
		}

		return rows;
	}

	set_formatted_input(value) {
		this.rows = value || [];
		this.set_pill_html(this.rows);
	}

	set_pill_html(values) {
		const html = values
			.map(value => this.get_pill_html(value))
			.join('');

		this.$multiselect_wrapper.find('.tb-selected-value').remove();
		this.$multiselect_wrapper.prepend(html);
	}

	get_pill_html(value) {
		const encoded_value = encodeURIComponent(value);
		return `
			<button class="data-pill btn tb-selected-value" data-value="${encoded_value}">
				${__(value)}
				${frappe.utils.icon('close')}
			</button>
		`;
	}

	get_awesomplete_settings() {
		const settings = super.get_awesomplete_settings();

		return Object.assign(settings, {
			filter: function(text, input) {
				let d = this.get_item(text.value);
				if(!d) {
					return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
				}

				let getMatch = value => Awesomplete.FILTER_CONTAINS(value, input.match(/[^,]*$/)[0]);

				// match typed input with label or value or description
				let v = getMatch(d.label);
				if(!v && d.value) {
					v = getMatch(d.value);
				}
				if(!v && d.description) {
					v = getMatch(d.description);
				}

				return v;
			}
		});
	}

	get_value() {
		return this.rows;
	}

	get_values() {
		return this.rows;
	}

	get_data() {
		let data;
		if(this.df.get_data) {
			let txt = this.$input.val();
			data = this.df.get_data(txt);
			if (data && data.then) {
				data.then((r) => {
					this.set_data(r);
				});
				data = this.get_value();
			} else {
				this.set_data(data);
			}
		} else {
			data = super.get_data();
		}
		const values = this.get_values() || [];

		// return values which are not already selected
		if (data) data.filter(d => !values.includes(d));
		return data;
	}
};
<commit_msg>feat: show label in MultiSelectPills<commit_after>import Awesomplete from 'awesomplete';

frappe.ui.form.ControlMultiSelectPills = class ControlMultiSelectPills extends frappe.ui.form.ControlAutocomplete {
	make_input() {
		super.make_input();
		this.$input_area = $(this.input_area);
		this.$multiselect_wrapper = $('
')
			.addClass('form-control table-multiselect')
			.appendTo(this.$input_area);

		this.$input.removeClass('form-control');
		this.$input_area.find('.awesomplete').appendTo(this.$multiselect_wrapper);

		this.$input.on("awesomplete-selectcomplete", () => {
			this.$input.val('').focus();
		});

		// used as an internal model to store values
		this.rows = [];

		this.$input_area.on('click', '.btn-remove', (e) => {
			const $target = $(e.currentTarget);
			const $value = $target.closest('.tb-selected-value');

			const value = decodeURIComponent($value.data().value);
			this.rows = this.rows.filter(val => val !== value);

			this.parse_validate_and_set_in_model('');
		});

		this.$input.on('keydown', e => {
			// if backspace key pressed on empty input, delete last value
			if (e.keyCode == frappe.ui.keyCode.BACKSPACE && e.target.value === '') {
				this.rows = this.rows.slice(0, this.rows.length - 1);
				this.parse_validate_and_set_in_model('');
			}
		});
	}

	parse(value) {
		if (value) {
			this.rows.push(value);
		}

		return this.rows;
	}

	validate(value) {
		const rows = (value || []).slice();

		if (rows.length === 0) {
			return rows;
		}

		const all_rows_except_last = rows.slice(0, rows.length - 1);
		const last_value = rows[rows.length - 1];

		// falsy value
		if (!last_value) {
			return all_rows_except_last;
		}

		// duplicate value
		if (all_rows_except_last.includes(last_value)) {
			return all_rows_except_last;
		}

		return rows;
	}

	set_formatted_input(value) {
		this.rows = value || [];
		this.set_pill_html(this.rows);
	}

	set_pill_html(values) {
		const html = values
			.map(value => this.get_pill_html(value))
			.join('');

		this.$multiselect_wrapper.find('.tb-selected-value').remove();
		this.$multiselect_wrapper.prepend(html);
	}

	get_pill_html(value) {
		const label = this.get_label(value);
		const encoded_value = encodeURIComponent(value);
		return `
			<button class="data-pill btn tb-selected-value" data-value="${encoded_value}">
				${__(label || value)}
				${frappe.utils.icon('close')}
			</button>
		`;
	}

	get_label(value) {
		const item = this._data?.find(d => d.value === value);
		return item ? item.label || item.value : null;
	}

	get_awesomplete_settings() {
		const settings = super.get_awesomplete_settings();

		return Object.assign(settings, {
			filter: function(text, input) {
				let d = this.get_item(text.value);
				if(!d) {
					return Awesomplete.FILTER_CONTAINS(text, input.match(/[^,]*$/)[0]);
				}

				let getMatch = value => Awesomplete.FILTER_CONTAINS(value, input.match(/[^,]*$/)[0]);

				// match typed input with label or value or description
				let v = getMatch(d.label);
				if(!v && d.value) {
					v = getMatch(d.value);
				}
				if(!v && d.description) {
					v = getMatch(d.description);
				}

				return v;
			}
		});
	}

	get_value() {
		return this.rows;
	}

	get_values() {
		return this.rows;
	}

	get_data() {
		let data;
		if(this.df.get_data) {
			let txt = this.$input.val();
			data = this.df.get_data(txt);
			if (data && data.then) {
				data.then((r) => {
					this.set_data(r);
				});
				data = this.get_value();
			} else {
				this.set_data(data);
			}
		} else {
			data = super.get_data();
		}
		const values = this.get_values() || [];

		// return values which are not already selected
		if (data) data.filter(d => !values.includes(d));
		return data;
	}
};
<|endoftext|>


<commit_before>var __ = 'Fill me in';

describe('koan.js', function () {

  describe('Strings', function () {
    describe('literal', function () {
      it('should create Strings', function () {
        expect('a String').toBe(__);
      });

      it('should concatenate Strings', function () {
        expect('a ' + 'String').toBe(__);
      });

      it('should convert an Number to String', function () {
        expect((1).toString()).toBe(__);
      });

      it('should convert an Array to String', function () {
        expect([1, 2, 3].toString()).toBe(__);
      });

      it('should convert an Object to String', function () {
        expect({ 'abc': 1, '2': 'banana'}.toString()).toBe(__);
      });

      it('should have a type', function () {
        expect(typeof '').toBe(__);
      });

      describe('equality', function () {
        it('should equal the other literal', function () {
          expect('a' == 'a').toBe(__);
        });

        it('should equal the other literal', function () {
          expect('1' == 1).toBe(__);
        });

        it('should equal the other literal', function () {
          expect('' == false).toBe(__);
        });

        it('should be the same as other literal', function () {
          expect('a' === 'a').toBe(__);
        });

        it('should not be the same as a number', function () {
          expect('1' === 1).toBe(__);
        });

        it('should not be the same as a boolean', function () {
          expect('' === false).toBe(__);
        });
      });
    });

    describe('object', function () {
      it('should create Strings', function () {
        expect(new String('a String')).toBe(__);
      });

      it('should concatenate Strings', function () {
        expect(new String('a ') + 'String').toBe(__);
      });

      it('should convert an Number to String', function () {
        expect(new String(1)).toBe(__);
      });

      it('should convert an Array to String', function () {
        expect(new String([1, 2, 3])).toBe(__);
      });

      it('should convert an Object to String', function () {
        expect(new String({ 'abc': 1, '2': 'banana'})).toBe(__);
      });

      it('should have a type', function () {
        expect(typeof new String()).toBe(__);
      });
    });
  });
});
<commit_msg>Add comparison tests for String Objects<commit_after>var __ = 'Fill me in';

describe('koan.js', function () {

  describe('Strings', function () {
    describe('literal', function () {
      it('should create Strings', function () {
        expect('a String').toBe(__);
      });

      it('should concatenate Strings', function () {
        expect('a ' + 'String').toBe(__);
      });

      it('should convert an Number to String', function () {
        expect((1).toString()).toBe(__);
      });

      it('should convert an Array to String', function () {
        expect([1, 2, 3].toString()).toBe(__);
      });

      it('should convert an Object to String', function () {
        expect({ 'abc': 1, '2': 'banana'}.toString()).toBe(__);
      });

      it('should have a type', function () {
        expect(typeof '').toBe(__);
      });

      describe('equality', function () {
        it('should equal the other literal', function () {
          expect('a' == 'a').toBe(__);
        });

        it('should equal the number literal', function () {
          expect('1' == 1).toBe(__);
        });

        it('should equal the boolean literal', function () {
          expect('' == false).toBe(__);
        });

        it('should be the same as other literal', function () {
          expect('a' === 'a').toBe(__);
        });

        it('should not be the same as a number', function () {
          expect('1' === 1).toBe(__);
        });

        it('should not be the same as a boolean', function () {
          expect('' === false).toBe(__);
        });
      });
    });

    describe('object', function () {
      it('should create Strings', function () {
        expect(new String('a String')).toBe(__);
      });

      it('should concatenate Strings', function () {
        expect(new String('a ') + 'String').toBe(__);
      });

      it('should convert an Number to String', function () {
        expect(new String(1)).toBe(__);
      });

      it('should convert an Array to String', function () {
        expect(new String([1, 2, 3])).toBe(__);
      });

      it('should convert an Object to String', function () {
        expect(new String({ 'abc': 1, '2': 'banana'})).toBe(__);
      });

      it('should have a type', function () {
        expect(typeof new String()).toBe(__);
      });

      describe('equality', function () {
        it('should equal the other object', function () {
          expect(new String('a') == new String('a')).toBe(__);
        });

        it('should equal the other literal', function () {
          expect(new String('a') == 'a').toBe(__);
        });

        it('should equal to a number', function () {
          expect(new String('1') == 1).toBe(__);
        });

        it('should equal the boolean', function () {
          expect(new String('') == false).toBe(__);
        });

        it('should not be the same as other object', function () {
          expect(new String('a') === new String('a')).toBe(__);
        });

        it('should not be the same as other literal', function () {
          expect(new String('a') === 'a').toBe(__);
        });

        it('should not be the same as a number', function () {
          expect(new String('1') === 1).toBe(__);
        });

        it('should not be the same as a boolean', function () {
          expect(new String('') === false).toBe(__);
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>var path = require('path');
var models = require('../models/models.js');

var dirname = path.resolve(path.dirname());

// Autoload
exports.load = function (req, res, next, commentId) {
	var clause = {
		where: {
			id: Number(commentId)
		}
	};
	models.Comment.find(clause).then(function (comment) {
		if (comment) {
			req.comment = comment;
			next();
		} else {
			next(new Error('No existe commentId=' + commentId));
		}
	}).catch(function (error) {
		next(error);
	});
};

// GET /quizes/:quizId/comments/new
exports.new = function (req, res) {
	var route = path.join(dirname, 'views/comments/new.ejs');
	res.render(route, {quizId: req.params.quizId, errors: []});
};

// POST /quizes/:quizId/comments
exports.create = function (req, res) {
	var comment = models.Comment.build({
		texto: req.body.comment.texto,
		QuizId: req.params.quizId
	});
	var route = path.join(dirname, '/quizes/comments/new.ejs');
	var err = comment.validate();

	if (err) {
		var errors = [];
		for (var prop in err) {
			errors.push({message: err[prop]});
		}
		res.render(route, {comment: comment, errors: errors});
	} else {
		comment.save().then(function () {
			res.redirect('/quizes/' + req.params.quizId);
		});
	}
};

// GET /quizes/:quizId/comments/:commentId/publish
exports.publish = function (req, res, next) {
	req.comment.publicado = true;
	req.comment.save({fields: ["publicado"]}).then(function () {
		res.redirect('/quizes/' + req.params.quizId);
	}).catch(function (error) {
		next(error);
	});
};
<commit_msg>Cambios para adaptar a la ultima version de Sequelize<commit_after>var path = require('path');
var models = require('../models/models.js');

var dirname = path.resolve(path.dirname());

// Autoload
exports.load = function (req, res, next, commentId) {
	var clause = {
		where: {
			id: Number(commentId)
		}
	};
	models.Comment.find(clause).then(function (comment) {
		if (comment) {
			req.comment = comment;
			next();
		} else {
			next(new Error('No existe commentId=' + commentId));
		}
	}).catch(function (error) {
		next(error);
	});
};

// GET /quizes/:quizId/comments/new
exports.new = function (req, res) {
	var route = path.join(dirname, 'views/comments/new.ejs');
	res.render(route, {quizId: req.params.quizId, errors: []});
};

// POST /quizes/:quizId/comments
exports.create = function (req, res) {
	var comment = models.Comment.build({
		texto: req.body.comment.texto,
		QuizId: req.params.quizId
	});
	var route = path.join(dirname, '/views/comments/new.ejs');
	comment.validate().then(function () {
		comment.save().then(function () {
			res.redirect('/quizes/' + req.params.quizId);
		});
	}).catch(function (err) {
		var errors = [];
		for (var prop in err) {
			errors.push({message: err[prop]});
		}
		res.render(route, {comment: comment, errors: errors});
	});
};

// GET /quizes/:quizId/comments/:commentId/publish
exports.publish = function (req, res, next) {
	req.comment.publicado = true;
	req.comment.save({fields: ["publicado"]}).then(function () {
		res.redirect('/quizes/' + req.params.quizId);
	}).catch(function (error) {
		next(error);
	});
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Request from 'superagent';

import './News.css';

class News extends Component {

  constructor(props) {
    super(props);
    this.state = {
      news: 'News from around the world',
      currentNewsItem: 'Breaking News Headline'
    }
  }

  componentWillMount() {
    this.fetchNews();
  };

  componentDidMount() {
    // fetch News continuously after certain interval
    setInterval (() => {
      this.fetchNews();
    }, 1000 * 60 * 60);

    // change current news item continuously
    setInterval (() => {
      this.setHeadline();
    }, 1000 * 30 );
  };

  componentWillReceiveProps(newProps) {
  };

  shouldComponentUpdate(newProps, newState) {
    return true;
  };

  componentWillUpdate(nextProps, nextState) {
  };

  componentDidUpdate(prevProps, prevState) {
  };

  componentWillUnmount() {
  };

  fetchNews () {
    const serverUrl = 'http://localhost:5000/users/news';
    Request.get(serverUrl)
      .then((response) => {
        this.setState({
          news: response.body
        });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  setHeadline () {
    const length = this.state.news.length;
    const index = Math.floor(length * Math.random());
    const currentNewsItem = this.state.news[index];

    this.setState({ currentNewsItem });
  };

  render() {
    return (

{this.state.currentNewsItem.title}

    );
  }
}

export default News;
<commit_msg>Update news immediately on load<commit_after>import React, { Component } from 'react';
import Request from 'superagent';

import './News.css';

class News extends Component {

  constructor(props) {
    super(props);
    this.state = {
      news: 'News from around the world',
      currentNewsItem: 'Breaking News Headline'
    }
  }

  componentWillMount() {
    this.fetchNews();
  };

  componentDidMount() {
    // fetch News continuously after certain interval
    setInterval (() => {
      this.fetchNews();
    }, 1000 * 60 * 60);

    // change current news item continuously
    setInterval (() => {
      this.setHeadline();
    }, 1000 * 30 );
  };

  componentWillReceiveProps(newProps) {
  };

  shouldComponentUpdate(newProps, newState) {
    return true;
  };

  componentWillUpdate(nextProps, nextState) {
  };

  componentDidUpdate(prevProps, prevState) {
  };

  componentWillUnmount() {
  };

  fetchNews () {
    const serverUrl = 'http://localhost:5000/users/news';
    Request.get(serverUrl)
      .then((response) => {
        this.setState({
          news: response.body
        });
        this.setHeadline();
      })
      .catch((err) => {
        console.error(err);
      });
  };

  setHeadline () {
    const length = this.state.news.length;
    const index = Math.floor(length * Math.random());
    const currentNewsItem = this.state.news[index];

    this.setState({ currentNewsItem });
  };

  render() {
    return (

{this.state.currentNewsItem.title}

    );
  }
}

export default News;
<|endoftext|>


<commit_before>/*
 * handlebars pattern engine for patternlab-node - v0.15.1 - 2015
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

/*
 * ENGINE SUPPORT LEVEL:
 *
 * Full. Partial calls and lineage hunting are supported. Handlebars does not
 * support the mustache-specific syntax extensions, style modifiers and pattern
 * parameters, because their use cases are addressed by the core Handlebars
 * feature set. It also does not support verbose partial syntax, because it
 * seems like it can't tolerate slashes in partial names. But honestly, did you
 * really want to use the verbose syntax anyway? I don't.
 *
 */

"use strict";

var Handlebars = require('handlebars');

// regexes, stored here so they're only compiled once
const findPartialsRE = /{{#?>\s*([\w-\/.]+)(?:.|\s+)*?}}/g;
const findListItemsRE = /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g;
const findAtPartialBlockRE = /{{#?>\s*@partial-block\s*}}/g;

function escapeAtPartialBlock(partialString) {
  var partial = partialString.replace(findAtPartialBlockRE, '{{> @partial-block }}');
  return partial;
}

var engine_handlebars = {
  engine: Handlebars,
  engineName: 'handlebars',
  engineFileExtension: '.hbs',

  // partial expansion is only necessary for Mustache templates that have
  // style modifiers or pattern parameters (I think)
  expandPartials: false,

  // render it
  renderPattern: function renderPattern(pattern, data, partials) {
    if (partials) {
      Handlebars.registerPartial(partials);
    }
    pattern.extendedTemplate = escapeAtPartialBlock(pattern.extendedTemplate);
    var compiled = Handlebars.compile(pattern.extendedTemplate);
    return compiled(data);
  },

  registerPartial: function (pattern) {
    // register exact partial name
    Handlebars.registerPartial(pattern.patternPartial, pattern.template);

    // register verbose syntax? No, it seems that Handlebars can't tolerate
    // slashes in partial names.
  },

  // find and return any {{> template-name }} within pattern
  findPartials: function findPartials(pattern) {
    var matches = pattern.template.match(findPartialsRE);
    return matches;
  },
  findPartialsWithStyleModifiers: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },

  // returns any patterns that match {{> value(foo:"bar") }} or {{>
  // value:mod(foo:"bar") }} within the pattern
  findPartialsWithPatternParameters: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },
  findListItems: function (pattern) {
    var matches = pattern.template.match(findListItemsRE);
    return matches;
  },

  // given a pattern, and a partial string, tease out the "pattern key" and
  // return it.
  findPartial: function (partialString) {
    var partial = partialString.replace(findPartialsRE, '$1');
    return partial;
  }
};

module.exports = engine_handlebars;
<commit_msg>let's not muddy the waters and just leave extendedTemplate out of this.<commit_after>/*
 * handlebars pattern engine for patternlab-node - v0.15.1 - 2015
 *
 * Geoffrey Pursell, Brian Muenzenmeyer, and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

/*
 * ENGINE SUPPORT LEVEL:
 *
 * Full. Partial calls and lineage hunting are supported. Handlebars does not
 * support the mustache-specific syntax extensions, style modifiers and pattern
 * parameters, because their use cases are addressed by the core Handlebars
 * feature set. It also does not support verbose partial syntax, because it
 * seems like it can't tolerate slashes in partial names. But honestly, did you
 * really want to use the verbose syntax anyway? I don't.
 *
 */

"use strict";

var Handlebars = require('handlebars');

// regexes, stored here so they're only compiled once
const findPartialsRE = /{{#?>\s*([\w-\/.]+)(?:.|\s+)*?}}/g;
const findListItemsRE = /({{#( )?)(list(I|i)tems.)(one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)( )?}}/g;
const findAtPartialBlockRE = /{{#?>\s*@partial-block\s*}}/g;

function escapeAtPartialBlock(partialString) {
  var partial = partialString.replace(findAtPartialBlockRE, '{{> @partial-block }}');
  return partial;
}

var engine_handlebars = {
  engine: Handlebars,
  engineName: 'handlebars',
  engineFileExtension: '.hbs',

  // partial expansion is only necessary for Mustache templates that have
  // style modifiers or pattern parameters (I think)
  expandPartials: false,

  // render it
  renderPattern: function renderPattern(pattern, data, partials) {
    if (partials) {
      Handlebars.registerPartial(partials);
    }

    var compiled = Handlebars.compile(
      escapeAtPartialBlock(pattern.template)
    );

    return compiled(data);
  },

  registerPartial: function (pattern) {
    // register exact partial name
    Handlebars.registerPartial(pattern.patternPartial, pattern.template);

    // register verbose syntax? No, it seems that Handlebars can't tolerate
    // slashes in partial names.
  },

  // find and return any {{> template-name }} within pattern
  findPartials: function findPartials(pattern) {
    var matches = pattern.template.match(findPartialsRE);
    return matches;
  },
  findPartialsWithStyleModifiers: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },

  // returns any patterns that match {{> value(foo:"bar") }} or {{>
  // value:mod(foo:"bar") }} within the pattern
  findPartialsWithPatternParameters: function () {
    // TODO: make the call to this from oPattern objects conditional on their
    // being implemented here.
    return [];
  },
  findListItems: function (pattern) {
    var matches = pattern.template.match(findListItemsRE);
    return matches;
  },

  // given a pattern, and a partial string, tease out the "pattern key" and
  // return it.
  findPartial: function (partialString) {
    var partial = partialString.replace(findPartialsRE, '$1');
    return partial;
  }
};

module.exports = engine_handlebars;
<|endoftext|>


<commit_before>window.urb = {
  ship: ship,
  port: port,
  auto: auto,
  oryx: oryx,
  user: user,
  seqn_h: 0,
  seqn_u: 0,
  seqn_s: 0,
  dely: 0,
  puls: 0,
  perms: {
    pol:"gie",
    sub:"tis",
    uns:"tiu",
    mes:"tim",
    heb:"tih"
  },
  cabs: {},

  req: function(method,url,params,json,cb) {
    var xhr = new XMLHttpRequest()
    xhr.open(method.toUpperCase(), url)
    if(json)
      xhr.setRequestHeader("content-type", "text/json")

    _data = {}
    if(params.data) { _data.data = params.data; }
    if(params.ship) { _data.ship = params.ship; }
    if(params.path) { _data.path = params.path; }
    if(params.appl) { _data.appl = params.appl; }
    __data = {oryx: oryx, xyro: _data}
    xhr.send(JSON.stringify(__data))

    if(cb) {
      xhr.onload = function() {
        cb(null,{
          "status":this.status,
          "data":JSON.parse(this.responseText)
        })
      }
      xhr.onerror = function() {
        cb({
          "status":this.status,
          "data":this.responseText
        })
      }
    }
  },

  send: function(params,cb) {
    if(!params)
      throw new Error("You must supply params to urb.send.")
    if(!params.appl)
      throw new Error("You must specify an appl for urb.send.")
    if(!params.data) { params.data = {}; }

    var method, perm, url, $this

    type = params.type ? params.type : "mes"
    perm = this.perms[type]

    params.ship = params.ship ? params.ship : this.ship

    method = "put"
    url = [perm,this.user,this.port,this.seqn_s]
    url = "/"+url.join("/")

    this.seqn_s++

    $this = this
    this.req(method,url,params,true,function(err,data) {
      if(err) { $this.seqn_s--; }
      if(cb) { cb.apply(this,arguments); }
    })
  },

  subscribe: function(appl,path,ship,cb) {
    if(!cb)
      throw new Error("You must supply a callback to urb.subscribe.")

    var method, perm, url, $this

    ship = ship ? ship : this.ship

    method = "get"
    params = {
      type:"sub",
      appl:appl,
      path:path,
      ship:ship,
      incs:function() {
        window.urb.seqn_u++
      }
    }

    this.cabs[appl+","+path.replace(/[^\x00-\x7F]/g, "")+","+ship] = cb

    type = params.type ? params.type : "mes"
    perm = this.perms[type]
    method = "put"
    url = [perm,this.user,this.port]
    url = "/"+url.join("/")

    $this = this
    this.req(method,url,params,true,function(err,data) {
      if(cb) { cb.call(this,err,{status: data.status, data: data.data.data})}
      if(!err && $this.puls == 0) {
        params.type = "pol"
        $this.poll(params)
      }
    })
  },

  unsubscribe: function(appl,path,ship,cb) {
    method = "put"
    type = "uns"
    perm = this.perms[type]
    url = [perm,this.user,this.port]
    url = "/"+url.join("/")

    params = {
      appl: appl,
      path: path,
      ship: ship
    }

    var $this = this
    this.req(method,url,params,true,function(err,data) {
      console.log('ok unsubscribed')
      fn = appl+","+path.replace(/[^\x00-\x7F]/g, "")+","+ship
      $this.cabs[fn]('subscription closed')
    })
  },

  heartbeat: function() {
    this.poll({
      type:"heb",
      ship:this.ship,
      incs:function() {
        window.urb.seqn_h++
      }
    },function() {
      console.log('heartbeat.')
    })
  },

  poll: function(params,cb) {
    if(!params)
      throw new Error("You must supply params to urb.poll.")

    var method, perm, url, $this

    method = "get"
    type = params.type ? params.type : "pol"
    perm = this.perms[type]
    url = [perm,this.user,this.port,this.seqn_u]
    url = "/"+url.join("/")

    this.puls = 1

    $this = this
    this.req(method,url,params,false,function(err,data) {
      if(cb) {
        cb.call(this,err,{status: data.status, data: data.data.data})
      } else {
        fn = data.data.appl+","+data.data.path.replace(/[^\x00-\x7F]/g, "")
            +","+data.data.ship
        $this.cabs[fn].call(this,err,
          {status: data.status, data: data.data.data})
      }

      if(err)
        $this.dely += 1000
      else {
        $this.dely = 0
        params.incs()
      }

      setTimeout(function() {
        $this.poll(params,cb)
      },$this.dely)
    })
  }
}
<commit_msg>preened urb.js<commit_after>window.urb = {
  ship: ship,
  port: port,
  auto: auto,
  oryx: oryx,
  user: user,
  seqn_h: 0,
  seqn_u: 0,
  seqn_s: 0,
  dely: 0,
  puls: 0,
  perms: {
    pol:"gie",
    sub:"tis",
    uns:"tiu",
    mes:"tim",
    heb:"tih"
  },
  cabs: {},

  req: function(method,url,params,json,cb) {
    var xhr = new XMLHttpRequest()
    xhr.open(method.toUpperCase(), url)
    if(json)
      xhr.setRequestHeader("content-type", "text/json")

    _data = {}
    if(params.data) { _data.data = params.data; }
    if(params.ship) { _data.ship = params.ship; }
    if(params.path) { _data.path = params.path; }
    if(params.appl) { _data.appl = params.appl; }
    __data = {oryx: oryx, xyro: _data}
    xhr.send(JSON.stringify(__data))

    if(cb) {
      xhr.onload = function() {
        cb(null,{
          "status":this.status,
          "data":JSON.parse(this.responseText)
        })
      }
      xhr.onerror = function() {
        cb({
          "status":this.status,
          "data":this.responseText
        })
      }
    }
  },

  send: function(params,cb) {
    if(!params)
      throw new Error("You must supply params to urb.send.")
    if(!params.appl)
      throw new Error("You must specify an appl for urb.send.")
    if(!params.data) { params.data = {}; }

    var method, perm, url, $this

    type = params.type ? params.type : "mes"
    perm = this.perms[type]

    params.ship = params.ship ? params.ship : this.ship

    method = "put"
    url = [perm,this.user,this.port,this.seqn_s]
    url = "/"+url.join("/")

    this.seqn_s++

    $this = this
    this.req(method,url,params,true,function(err,data) {
      if(err) { $this.seqn_s--; }
      if(cb) { cb.apply(this,arguments); }
    })
  },

  subscribe: function(params,cb) {
    if(!cb)
      throw new Error("You must supply a callback to urb.subscribe.")
    if(!params)
      throw new Error("You must supply params to urb.subscribe.")
    if(!params.appl)
      throw new Error("You must specify an appl for urb.subscribe.")
    if(!params.path)
      throw new Error("You must specify a path for urb.subscribe.")
    params.ship = params.ship ? params.ship : this.ship

    var method, perm, url, $this

    params.type = "sub"
    params.incs = function() {
        window.urb.seqn_u++
      }

    this.cabs[params.appl+","+params.path.replace(/[^\x00-\x7F]/g, "")+","+params.ship] = cb

    url = [this.perms["sub"],this.user,this.port]
    url = "/"+url.join("/")
    method = "put"

    $this = this
    this.req(method,url,params,true,function(err,data) {
      if(cb) { cb.call(this,err,{status: data.status, data: data.data.data})}
      if(!err && $this.puls == 0) {
        params.type = "pol"
        $this.poll(params)
      }
    })
  },

  unsubscribe: function(params,cb) {
    if(!params)
      throw new Error("You must supply params to urb.unsubscribe.")
    if(!params.appl)
      throw new Error("You must specify an appl for urb.unsubscribe.")
    if(!params.path)
      throw new Error("You must specify a path for urb.unsubscribe.")
    params.ship = params.ship ? params.ship : this.ship

    method = "put"
    type = "uns"
    url = [this.perms[type],this.user,this.port]
    url = "/"+url.join("/")

    var $this = this
    this.req(method,url,params,true,function(err,data) {
      fn = params.appl+","+params.path.replace(/[^\x00-\x7F]/g, "")+","+params.ship
      $this.cabs[fn]('subscription closed')
    })
  },

  heartbeat: function() {
    this.poll({
      type:"heb",
      ship:this.ship,
      incs:function() {
        window.urb.seqn_h++
      }
    },function() {
      console.log('heartbeat.')
    })
  },

  poll: function(params,cb) {
    if(!params)
      throw new Error("You must supply params to urb.poll.")

    var method, perm, url, $this

    method = "get"
    type = params.type ? params.type : "pol"
    perm = this.perms[type]
    url = [perm,this.user,this.port,this.seqn_u]
    url = "/"+url.join("/")

    this.puls = 1

    $this = this
    this.req(method,url,params,false,function(err,data) {
      if(cb) {
        cb.call(this,err,{status: data.status, data: data.data.data})
      } else {
        fn = data.data.appl+","+data.data.path.replace(/[^\x00-\x7F]/g, "")
            +","+data.data.ship
        $this.cabs[fn].call(this,err,
          {status: data.status, data: data.data.data})
      }

      if(err)
        $this.dely += 1000
      else {
        $this.dely = 0
        params.incs()
      }

      setTimeout(function() {
        $this.poll(params,cb)
      },$this.dely)
    })
  }
}
<|endoftext|>


<commit_before>// Since we don't set a beacon_url, we'll just subscribe to the before_beacon function
// and print the results into the browser itself.
BOOMR.subscribe('before_beacon', function(o) {
	var html = "";
	if(o.t_done) { html += "This page took " + o.t_done + "ms to load
"; }
	if(o.t_head) { html += "The head section loaded in " + o.t_head + "ms
"; }
	if(o.t_body) { html += "The body section loaded in " + o.t_body + "ms
"; }
	if(o.bw) { html += "Your bandwidth to this server is " + parseInt(o.bw/1024) + "kbps (±" + parseInt(o.bw_err*100/o.bw) + "%)
"; }
	if(o.lat) { html += "Your latency to this server is " + parseInt(o.lat) + "±" + o.lat_err + "ms
"; }

	document.getElementById('results').innerHTML = html;
});

<commit_msg>t_head and t_body are not param vars<commit_after>// Since we don't set a beacon_url, we'll just subscribe to the before_beacon function
// and print the results into the browser itself.
BOOMR.subscribe('before_beacon', function(o) {
	var html = "";
	if(o.t_done) { html += "This page took " + o.t_done + "ms to load
"; }
	if(o.t_other) { html += "Other timers measured: " + o.t_other + "
"; }
	if(o.bw) { html += "Your bandwidth to this server is " + parseInt(o.bw/1024) + "kbps (±" + parseInt(o.bw_err*100/o.bw) + "%)
"; }
	if(o.lat) { html += "Your latency to this server is " + parseInt(o.lat) + "±" + o.lat_err + "ms
"; }

	document.getElementById('results').innerHTML = html;
});

<|endoftext|>


<commit_before>var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var path = require("path");

module.exports = {
    context: __dirname,

    entry: [
        './ditto/static/chat/js/base.js',
    ],

    output: {
        path: path.resolve('./ditto/static/dist'),
        publicPath: '/static/dist/', // This will override the url generated by django's staticfiles
        filename: "[name]-[hash].js",
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: ["babel-loader?optional[]=es7.comprehensions&optional[]=es7.classProperties&optional[]=es7.objectRestSpread&optional[]=es7.decorators"],
            }
        ]
    },
    plugins: [
        new BundleTracker({filename: './webpack-stats-prod.json'}),

        // removes a lot of debugging code in React
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }}),

        // keeps hashes consistent between compilations
        new webpack.optimize.OccurenceOrderPlugin(),

        // minifies your code
        // new webpack.optimize.UglifyJsPlugin({
        //     compressor: {
        //         warnings: false
        //     }
        // })
    ],
  resolve: {
    fallback: path.join(__dirname, 'node_modules'),
    extensions: ['', '.js', '.jsx']
  }
};
<commit_msg>minify production js again<commit_after>var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var path = require("path");

module.exports = {
    context: __dirname,

    entry: [
        './ditto/static/chat/js/base.js',
    ],

    output: {
        path: path.resolve('./ditto/static/dist'),
        publicPath: '/static/dist/', // This will override the url generated by django's staticfiles
        filename: "[name]-[hash].js",
    },

    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /node_modules/,
                loaders: ["babel-loader?optional[]=es7.comprehensions&optional[]=es7.classProperties&optional[]=es7.objectRestSpread&optional[]=es7.decorators"],
            }
        ]
    },
    plugins: [
        new BundleTracker({filename: './webpack-stats-prod.json'}),

        // removes a lot of debugging code in React
        new webpack.DefinePlugin({
            'process.env': {
                'NODE_ENV': JSON.stringify('production')
            }}),

        // keeps hashes consistent between compilations
        new webpack.optimize.OccurenceOrderPlugin(),

        // minifies your code
        new webpack.optimize.UglifyJsPlugin({
            compressor: {
                warnings: false
            }
        })
    ],
  resolve: {
    fallback: path.join(__dirname, 'node_modules'),
    extensions: ['', '.js', '.jsx']
  }
};
<|endoftext|>


<commit_before>/*
 Copyright 2015, 2016 OpenMarket Ltd

 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.
 */

'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClient} from 'matrix-js-sdk';
import sdk from '../../../index';
import Flair from '../elements/Flair.js';
import FlairStore from '../../../stores/FlairStore';
import { _t } from '../../../languageHandler';
import {hashCode} from '../../../utils/FormattingUtils';

export default React.createClass({
    displayName: 'SenderProfile',
    propTypes: {
        mxEvent: PropTypes.object.isRequired, // event whose sender we're showing
        text: PropTypes.string, // Text to show. Defaults to sender name
        onClick: PropTypes.func,
    },

    contextTypes: {
        matrixClient: PropTypes.instanceOf(MatrixClient),
    },

    getInitialState() {
        return {
            userGroups: null,
            relatedGroups: [],
        };
    },

    componentWillMount() {
        this.unmounted = false;
        this._updateRelatedGroups();

        FlairStore.getPublicisedGroupsCached(
            this.context.matrixClient, this.props.mxEvent.getSender(),
        ).then((userGroups) => {
            if (this.unmounted) return;
            this.setState({userGroups});
        });

        this.context.matrixClient.on('RoomState.events', this.onRoomStateEvents);
    },

    componentWillUnmount() {
        this.unmounted = true;
        this.context.matrixClient.removeListener('RoomState.events', this.onRoomStateEvents);
    },

    onRoomStateEvents(event) {
        if (event.getType() === 'm.room.related_groups' &&
            event.getRoomId() === this.props.mxEvent.getRoomId()
        ) {
            this._updateRelatedGroups();
        }
    },

    _updateRelatedGroups() {
        if (this.unmounted) return;
        const room = this.context.matrixClient.getRoom(this.props.mxEvent.getRoomId());
        if (!room) return;

        const relatedGroupsEvent = room.currentState.getStateEvents('m.room.related_groups', '');
        this.setState({
            relatedGroups: relatedGroupsEvent ? relatedGroupsEvent.getContent().groups || [] : [],
        });
    },

    _getDisplayedGroups(userGroups, relatedGroups) {
        let displayedGroups = userGroups || [];
        if (relatedGroups && relatedGroups.length > 0) {
            displayedGroups = relatedGroups.filter((groupId) => {
                return displayedGroups.includes(groupId);
            });
        } else {
            displayedGroups = [];
        }
        return displayedGroups;
    },

    render() {
        const EmojiText = sdk.getComponent('elements.EmojiText');
        const {mxEvent} = this.props;
        const colorNumber = hashCode(mxEvent.getSender()) % 8;
        const name = mxEvent.sender ? mxEvent.sender.name : mxEvent.getSender();
        const {msgtype} = mxEvent.getContent();

        if (msgtype === 'm.emote') {
            return ; // emote message must include the name so don't duplicate it
        }

        let flair =
;
        if (this.props.enableFlair) {
            const displayedGroups = this._getDisplayedGroups(
                this.state.userGroups, this.state.relatedGroups,
            );

            flair = <Flair key='flair'
                userId={mxEvent.getSender()}
                groups={displayedGroups}
            />;
        }

        const nameElem = <EmojiText key='name'>{ name || '' }</EmojiText>;

        // Name + flair
        const nameFlair =
            <span className={`mx_SenderProfile_name mx_SenderProfile_color${colorNumber}`}>
                { nameElem }

            { flair }
        ;

        const content = this.props.text ?

                { _t(this.props.text, { senderName: () => nameElem }) }
             : nameFlair;

        return (

                { content }

        );
    },
});
<commit_msg>Fix off by one error for username colors<commit_after>/*
 Copyright 2015, 2016 OpenMarket Ltd

 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.
 */

'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import {MatrixClient} from 'matrix-js-sdk';
import sdk from '../../../index';
import Flair from '../elements/Flair.js';
import FlairStore from '../../../stores/FlairStore';
import { _t } from '../../../languageHandler';
import {hashCode} from '../../../utils/FormattingUtils';

export default React.createClass({
    displayName: 'SenderProfile',
    propTypes: {
        mxEvent: PropTypes.object.isRequired, // event whose sender we're showing
        text: PropTypes.string, // Text to show. Defaults to sender name
        onClick: PropTypes.func,
    },

    contextTypes: {
        matrixClient: PropTypes.instanceOf(MatrixClient),
    },

    getInitialState() {
        return {
            userGroups: null,
            relatedGroups: [],
        };
    },

    componentWillMount() {
        this.unmounted = false;
        this._updateRelatedGroups();

        FlairStore.getPublicisedGroupsCached(
            this.context.matrixClient, this.props.mxEvent.getSender(),
        ).then((userGroups) => {
            if (this.unmounted) return;
            this.setState({userGroups});
        });

        this.context.matrixClient.on('RoomState.events', this.onRoomStateEvents);
    },

    componentWillUnmount() {
        this.unmounted = true;
        this.context.matrixClient.removeListener('RoomState.events', this.onRoomStateEvents);
    },

    onRoomStateEvents(event) {
        if (event.getType() === 'm.room.related_groups' &&
            event.getRoomId() === this.props.mxEvent.getRoomId()
        ) {
            this._updateRelatedGroups();
        }
    },

    _updateRelatedGroups() {
        if (this.unmounted) return;
        const room = this.context.matrixClient.getRoom(this.props.mxEvent.getRoomId());
        if (!room) return;

        const relatedGroupsEvent = room.currentState.getStateEvents('m.room.related_groups', '');
        this.setState({
            relatedGroups: relatedGroupsEvent ? relatedGroupsEvent.getContent().groups || [] : [],
        });
    },

    _getDisplayedGroups(userGroups, relatedGroups) {
        let displayedGroups = userGroups || [];
        if (relatedGroups && relatedGroups.length > 0) {
            displayedGroups = relatedGroups.filter((groupId) => {
                return displayedGroups.includes(groupId);
            });
        } else {
            displayedGroups = [];
        }
        return displayedGroups;
    },

    render() {
        const EmojiText = sdk.getComponent('elements.EmojiText');
        const {mxEvent} = this.props;
        const colorNumber = (hashCode(mxEvent.getSender()) % 8) + 1;
        const name = mxEvent.sender ? mxEvent.sender.name : mxEvent.getSender();
        const {msgtype} = mxEvent.getContent();

        if (msgtype === 'm.emote') {
            return ; // emote message must include the name so don't duplicate it
        }

        let flair =
;
        if (this.props.enableFlair) {
            const displayedGroups = this._getDisplayedGroups(
                this.state.userGroups, this.state.relatedGroups,
            );

            flair = <Flair key='flair'
                userId={mxEvent.getSender()}
                groups={displayedGroups}
            />;
        }

        const nameElem = <EmojiText key='name'>{ name || '' }</EmojiText>;

        // Name + flair
        const nameFlair =
            <span className={`mx_SenderProfile_name mx_SenderProfile_color${colorNumber}`}>
                { nameElem }

            { flair }
        ;

        const content = this.props.text ?

                { _t(this.props.text, { senderName: () => nameElem }) }
             : nameFlair;

        return (

                { content }

        );
    },
});
<|endoftext|>


<commit_before>const assert = require('assert')
const React = require('react')
const ReactDOM = require('react-dom')
const ReactRedux = require('react-redux')
const Redux = require('redux')
const fetchMock = require('fetch-mock')
const TestUtils = require('react-addons-test-utils')
const NewFilter = require('../../src/components/NewFilter')
const reducer = require('../../src/reducers/reducer')

function renderPage(store) {
  // NewFilter calls loadFilter and save functions from the main App onSubmit.
  return TestUtils.renderIntoDocument(
    <ReactRedux.Provider store={store}>
      <NewFilter
        loadFilter={key => key}
        save={() => 'saved'}
      />
    </ReactRedux.Provider>
  )
}

describe('NewFilter', () => {
  let renderedDOM
  let store

  before(() => {
    store = Redux.createStore(reducer)
    fetchMock.mock('*', {})
    const component = renderPage(store)
    renderedDOM = () => ReactDOM.findDOMNode(component)
  })

  after(() => {
    fetchMock.restore()
  })

  it('shows the form', () => {
    const newFilterForm = renderedDOM().querySelector('.new-filter-form')
    assert(newFilterForm)
  })

  describe('Create', () => {
    it('has a save button', () => {
      const saveButton = renderedDOM().querySelector('button[type="submit"]')
      assert(saveButton)
    })

    it('has required form fields', () => {
      const valueInput = renderedDOM().querySelector("input[name='filterValue']")
      assert(valueInput)
    })

    it('sets a created filter as LastFilter', () => {
      const filterForm = renderedDOM().querySelector('form.new-filter-form')
      const valueInput = renderedDOM().querySelector("input[name='filterValue']")
      const value = 'author:LuluPopplewell'

      valueInput.value = value
      TestUtils.Simulate.change(valueInput)
      TestUtils.Simulate.submit(filterForm)
      const activeFilter = store.filters.find(filter => filter.selected)
      assert.equal('author:LuluPopplewell', activeFilter.query)
    })
  })
})
<commit_msg>THIS TEST SHALL PASS<commit_after>const assert = require('assert')
const React = require('react')
const ReactDOM = require('react-dom')
const ReactRedux = require('react-redux')
const Redux = require('redux')
const fetchMock = require('fetch-mock')
const TestUtils = require('react-addons-test-utils')
const NewFilter = require('../../src/components/NewFilter')
const reducer = require('../../src/reducers/reducer')

function renderPage(store) {
  // NewFilter calls loadFilter and save functions from the main App onSubmit.
  return TestUtils.renderIntoDocument(
    <ReactRedux.Provider store={store}>
      <NewFilter
        loadFilter={key => key}
        save={() => 'saved'}
        cancel={() => 'cancel'}
      />
    </ReactRedux.Provider>
  )
}

describe('NewFilter', () => {
  let renderedDOM
  let store

  before(() => {
    store = Redux.createStore(reducer)
    fetchMock.mock('*', {})
    const component = renderPage(store)
    renderedDOM = () => ReactDOM.findDOMNode(component)
  })

  after(() => {
    fetchMock.restore()
  })

  it('shows the form', () => {
    const newFilterForm = renderedDOM().querySelector('.new-filter-form')
    assert(newFilterForm)
  })

  describe('Create', () => {
    it('has a save button', () => {
      const saveButton = renderedDOM().querySelector('button[type="submit"]')
      assert(saveButton)
    })

    it('has required form fields', () => {
      const valueInput = renderedDOM().querySelector("input[name='filterValue']")
      assert(valueInput)
    })

    it('the new filter becomes the active filter', () => {
      const filterForm = renderedDOM().querySelector('form.new-filter-form')
      const valueInput = renderedDOM().querySelector("input[name='filterValue']")
      const value = 'author:LuluPopplewell'

      valueInput.value = value
      TestUtils.Simulate.change(valueInput)
      TestUtils.Simulate.submit(filterForm)
      const activeFilter = store.getState().filters.find(filter => filter.selected)
      assert.equal('author:LuluPopplewell', activeFilter.query)
    })
  })
})
<|endoftext|>


<commit_before>(function (undefined) {
  var _;
  var mixins = {};
  if (typeof require === 'function') {
    _ = require('lodash');
    module.exports = mixins;
  } else {
    _ = window._;
  }

  mixins.get = function () {
    if (arguments.length === 0) {
      return void 0;
    }

    var a = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
      if (a[arguments[i]] === void 0) {
        return void 0;
      }
      a = a[arguments[i]];
    }
    return a;
  };

  _.mixin(mixins);
}).call(this);

<commit_msg>Fixed require to pass in array.<commit_after>(function (undefined) {
  var _;
  var mixins = {};
  if (typeof require === 'function') {
    _ = require(['lodash']);
    module.exports = mixins;
  } else {
    _ = window._;
  }

  mixins.get = function () {
    if (arguments.length === 0) {
      return void 0;
    }

    var a = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
      if (a[arguments[i]] === void 0) {
        return void 0;
      }
      a = a[arguments[i]];
    }
    return a;
  };

  _.mixin(mixins);
}).call(this);

<|endoftext|>