<commit_before> // U3.W7: Design your own Code Combat Mission

// This is a solo challenge

// Your mission description:
// Overall mission: hit kanye with the mic
// Goals: grab the mic, hit kanye with it
// Characters: player, kanye
// Objects: player, kanye, mic
// Functions: draw, playerMove, aiMove, houseKeeping

// Pseudocode
// create objects for player, kanye and microphone
// add properties to object for x/y location
// add kanye alive property
// add player moving and micEquip property
// create event listener and map to wasd
// use housekeeping method to contain misc logic

// Refactored code

//if this comment is gone then i broke git plz send help
//initializes canvas1 & canvas2
var a = document.getElementById('canvas');
var b = document.getElementById('canvas2');
var ctx = a.getContext('2d');
var ctx2 = b.getContext('2d');
b.height = 500;
b.width = 1000;
a.height = 500;
a.width = 500;
var dy = 50;
var dx = 50;

//draws to canvas 100 times a second
setInterval(draw, 10)

var kanye = {
	x: 400,
	y: 0,
	alive: true,
}

var mic = {

	x: 250,
	y: 250,
}

var player = {
    x: 0,
    y: 0,
    micEquip: false,
    moving: false,
}

//draws the images onto the html canvas
function draw(){
	ctx.clearRect(0, 0, a.width, a.height)

	ctx.beginPath();
	ctx.drawImage(jay, player.x, player.y, 50, 50)
	ctx.closePath();
	ctx.fill();

	ctx.beginPath();
	ctx.drawImage(img, kanye.x, kanye.y, 50, 50)
	ctx.closePath();
	ctx.fill();

	ctx.beginPath();
	ctx.drawImage(microphone, mic.x, mic.y, 50, 50);
	ctx.closePath();
	ctx.fill();
}

//event listener for wasd input
 window.addEventListener('keydown', playerMove, true);

//moves the player
function playerMove(evt){
	switch (evt.keyCode) {
		case 87:  /* w was pressed */
			if (player.y - dy >= 0){
			    player.y -= dy;
			    player.moving = true;
			    houseKeeping()
		}
		break;
		case 83:  /* s was pressed */
			if (player.y + dy < a.height){
			    player.y += dy;
			    player.moving = true;
			    houseKeeping()
		}
		break;
		case 65:  /* a was pressed */
			if (player.x - dx >= 0){
			    player.x -= dx;
			    player.moving = true;
			    houseKeeping()
		}
		break;
		case 68:  /* d was pressed */
			if (player.x + dx < a.width){
			    player.x += dx;
			    player.moving = true;
			    houseKeeping()
		}
		break;
	}
}

//ai movement
function aiMove() {
	var ranNum = Math.floor((Math.random() * 4) + 1)
	if (ranNum == 1){
		if (kanye.y - dy >= 0){
			kanye.y -= dy;
		} else {
			kanye.y = kanye.y
		}
	} else if (ranNum == 2) {
		if (kanye.y + dy < a.height) {
			kanye.y += dy;
		} else {
			kanye.y = kanye.y
		}
	} else if (ranNum == 3) {
		if (kanye.x - dx >= 0) {
			kanye.x -= dx;
		} else {
			kanye.x = kanye.x
		}
	} else {
		if (kanye.x + dx < a.width){
			kanye.x += dx;
		} else {
			kanye.x = kanye.x
		}
	}
}

//regulates micEquip property on player, mic coords when equipped, whether kanye is alive
function houseKeeping() {
	aiMove()

	if (player.moving = true) {
		console.log("player is moving x:" + player.x + " y:" + player.y)
	}

	if (player.x == mic.x-50 && player.y == mic.y){
		setTimeout(function(){
		alert("you got the mic, now hit kanye with it");
		}, 15);
		player.micEquip = true;
	}

	if (player.micEquip == true) {
		mic.x = player.x + 50
		mic.y = player.y
		console.log("you got the mic")
	}

	if((mic.x == kanye.x) && (mic.y == kanye.y)) {
		setTimeout(function(){
		alert("you hit kanye with the mic, you win")
		}, 15);
		kanye.alive = false
	}

	if (kanye.alive == false){
		shoulder.play()
		ctx2.drawImage(t, 500, 0, 500, 500);
		console.log("you win!")
		kanye.x = 100000
		kanye.y = 100000
	}
}

//loading images and sound file

var shoulder = new Audio("shoulder.mp3")

img = new Image()
img.src = "kanye.jpg"

jay = new Image()
jay.src = "jay.png"

microphone = new Image()
microphone.src = "mic.jpg"

t = new Image()
t.src = "trophy.gif"

// Reflection
// This challenge was definitely a huge learning experience for me. I feel way more comfortable with JS than I did before
// and I feel that I understand the relation between HTML and JS better than I did before. This challenge took me
// a few days to complete, and I refactored as I went because I was never satisfied with my original code in the state
// that it was in.
//
//
//
//<commit_msg>add gameover<commit_after> // U3.W7: Design your own Code Combat Mission

// This is a solo challenge

// Your mission description:
// Overall mission: hit kanye with the mic
// Goals: grab the mic, hit kanye with it
// Characters: player, kanye
// Objects: player, kanye, mic
// Functions: draw, playerMove, aiMove, houseKeeping

// Pseudocode
// create objects for player, kanye and microphone
// add properties to object for x/y location
// add kanye alive property
// add player moving and micEquip property
// create event listener and map to wasd
// use housekeeping method to contain misc logic

// Refactored code

//if this comment is gone then i broke git plz send help
//initializes canvas1 & canvas2
var a = document.getElementById('canvas');
var b = document.getElementById('canvas2');
var ctx = a.getContext('2d');
var ctx2 = b.getContext('2d');
b.height = 500;
b.width = 1000;
a.height = 500;
a.width = 500;
var dy = 50;
var dx = 50;

//draws to canvas 100 times a second
setInterval(draw, 10)

var kanye = {
	x: 400,
	y: 0,
	alive: true,
}

var mic = {

	x: 250,
	y: 250,
}

var player = {
    x: 0,
    y: 0,
    micEquip: false,
    moving: false,
}

//draws the images onto the html canvas
function draw(){
	ctx.clearRect(0, 0, a.width, a.height)

	ctx.beginPath();
	ctx.drawImage(jay, player.x, player.y, 50, 50)
	ctx.closePath();
	ctx.fill();

	ctx.beginPath();
	ctx.drawImage(img, kanye.x, kanye.y, 50, 50)
	ctx.closePath();
	ctx.fill();

	ctx.beginPath();
	ctx.drawImage(microphone, mic.x, mic.y, 50, 50);
	ctx.closePath();
	ctx.fill();
}

//event listener for wasd input
 window.addEventListener('keydown', playerMove, true);

//moves the player
function playerMove(evt){
	switch (evt.keyCode) {
		case 87:  /* w was pressed */
			if (player.y - dy >= 0){
			    player.y -= dy;
			    player.moving = true;
			    houseKeeping()
		}
		break;
		case 83:  /* s was pressed */
			if (player.y + dy < a.height){
			    player.y += dy;
			    player.moving = true;
			    houseKeeping()
		}
		break;
		case 65:  /* a was pressed */
			if (player.x - dx >= 0){
			    player.x -= dx;
			    player.moving = true;
			    houseKeeping()
		}
		break;
		case 68:  /* d was pressed */
			if (player.x + dx < a.width){
			    player.x += dx;
			    player.moving = true;
			    houseKeeping()
		}
		break;
	}
}

//ai movement
function aiMove() {
	var ranNum = Math.floor((Math.random() * 4) + 1)
	if (ranNum == 1){
		if (kanye.y - dy >= 0){
			kanye.y -= dy;
		} else {
			kanye.y = kanye.y
		}
	} else if (ranNum == 2) {
		if (kanye.y + dy < a.height) {
			kanye.y += dy;
		} else {
			kanye.y = kanye.y
		}
	} else if (ranNum == 3) {
		if (kanye.x - dx >= 0) {
			kanye.x -= dx;
		} else {
			kanye.x = kanye.x
		}
	} else {
		if (kanye.x + dx < a.width){
			kanye.x += dx;
		} else {
			kanye.x = kanye.x
		}
	}
}

//regulates micEquip property on player, mic coords when equipped, whether kanye is alive
function houseKeeping() {
	aiMove()

	if (player.moving = true) {
		console.log("player is moving x:" + player.x + " y:" + player.y)
	}

	if (player.x == mic.x-50 && player.y == mic.y){
		setTimeout(function(){
		alert("you got the mic, now hit kanye with it");
		}, 15);
		player.micEquip = true;
	}

	if (player.micEquip == true) {
		mic.x = player.x + 50
		mic.y = player.y
		console.log("you got the mic")
	}

	if((mic.x == kanye.x) && (mic.y == kanye.y)) {
		setTimeout(function(){
		alert("you hit kanye with the mic, you win")
		}, 15);
		kanye.alive = false
	}

	if (kanye.alive == false){
		shoulder.play()
		ctx2.drawImage(t, 500, 0, 500, 500);
		console.log("you win!")
		kanye.x = 100000
		kanye.y = 100000
		setTimeout(function(){
		clearInterval(refresh)
		}, 15);
	}
}

//loading images and sound file

var shoulder = new Audio("shoulder.mp3")

img = new Image()
img.src = "kanye.jpg"

jay = new Image()
jay.src = "jay.png"

microphone = new Image()
microphone.src = "mic.jpg"

t = new Image()
t.src = "trophy.gif"

// Reflection
// This challenge was definitely a huge learning experience for me. I feel way more comfortable with JS than I did before
// and I feel that I understand the relation between HTML and JS better than I did before. This challenge took me
// a few days to complete, and I refactored as I went because I was never satisfied with my original code in the state
// that it was in.
//
//
//
//<|endoftext|>


<commit_before>/* Magic Mirror Test config custom calendar
 *
 * MIT Licensed.
 */
let config = {
	port: 8080,
	ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"],

	language: "en",
	timeFormat: 12,
	units: "metric",
	electronOptions: {
		webPreferences: {
			nodeIntegration: true
		}
	},

	modules: [
		{
			module: "calendar",
			position: "bottom_bar",
			config: {
				calendars: [
					{
						maximumEntries: 4,
						maximumNumberOfDays: 10000,
						symbol: "birthday-cake",
						fullDaySymbol: "calendar-day",
						recurringSymbol: "undo",
						url: "http://localhost:8080/tests/configs/data/calendar_test_icons.ics"
					}
				]
			}
		}
	]
};

/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
	module.exports = config;
}
<commit_msg>Change custom calendar test to not include past events<commit_after>/* Magic Mirror Test config custom calendar
 *
 * MIT Licensed.
 */
let config = {
	port: 8080,
	ipWhitelist: ["127.0.0.1", "::ffff:127.0.0.1", "::1"],

	language: "en",
	timeFormat: 12,
	units: "metric",
	electronOptions: {
		webPreferences: {
			nodeIntegration: true
		}
	},

	modules: [
		{
			module: "calendar",
			position: "bottom_bar",
			broadcastPastEvents: false,
			config: {
				calendars: [
					{
						maximumEntries: 4,
						maximumNumberOfDays: 10000,
						symbol: "birthday-cake",
						fullDaySymbol: "calendar-day",
						recurringSymbol: "undo",
						url: "http://localhost:8080/tests/configs/data/calendar_test_icons.ics"
					}
				]
			}
		}
	]
};

/*************** DO NOT EDIT THE LINE BELOW ***************/
if (typeof module !== "undefined") {
	module.exports = config;
}
<|endoftext|>


<commit_before>angular.module('proximate', ['ionic',
  'proximate.controllers',
  'proximate.services'])

.run(function($ionicPlatform, $localStorage, $state, PubNub, Settings) {

  // Similarly, add fake region array to localStorage to simulate previous info
  var testRegions = [{
    uuid : 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    identifier : 'Estimote Icy One',
    minor : 10907,
    major : 23516
  }, {
    uuid : 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    identifier : 'Estimote Blue One',
    minor : 50306,
    major : 54690
  }, {
    uuid : 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    identifier : 'Estimote Mint One',
    minor : 3704,
    major : 57868
  }];

  $localStorage.set('beaconList', JSON.stringify(testRegions));

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }

    Settings.updateDeviceId();

    // Resets initialized value (testing)
    // $localStorage.set('initialized', 'false');

    if ($localStorage.get('initialized') !== 'true') {
      $state.go('splash', {}, {reload: true});
    }

  });
})

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider

    .state('tab', {
      url: '/tab',
      abstract: true,
      templateUrl: 'views/tabs.html'
    })

    .state('tab.status', {
      url: '/status',
      views: {
        'status': {
          templateUrl: 'views/status.html',
          controller: 'StatusCtrl'
        }
      }
    })

    .state('tab.upcoming', {
      url: '/upcoming',
      views: {
        'upcoming': {
          templateUrl: 'views/upcoming.html',
          controller: 'UpcomingCtrl'
        }
      }
    })

    .state('tab.settings', {
      url: '/settings',
      views: {
        'settings': {
          templateUrl: 'views/settings.html',
          controller: 'SettingsCtrl'
        }
      }
    })

    .state('splash', {
      url: '/splash',
      templateUrl: 'views/splash.html',
      controller: 'SplashCtrl'
    });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/status');

});
<commit_msg>Rebase<commit_after>angular.module('proximate', ['ionic',
  'proximate.controllers',
  'proximate.services'])

.run(function($ionicPlatform, $localStorage, $state, PubNub, Settings) {

  // Similarly, add fake region array to localStorage to simulate previous info
  var testRegions = [{
    uuid : 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    identifier : 'Estimote Icy One',
    minor : 10907,
    major : 23516
  }, {
    uuid : 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    identifier : 'Estimote Blue One',
    minor : 50306,
    major : 54690
  }, {
    uuid : 'B9407F30-F5F8-466E-AFF9-25556B57FE6D',
    identifier : 'Estimote Mint One',
    minor : 3704,
    major : 57868
  }];

  $localStorage.set('beaconList', JSON.stringify(testRegions));

  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }

    Settings.updateDeviceId();

    // Resets initialized value (testing)
    $localStorage.set('initialized', 'false');

    if ($localStorage.get('initialized') !== 'true') {
      $state.go('splash', {}, {reload: true});
    }

  });
})

.config(function($stateProvider, $urlRouterProvider) {

  $stateProvider

    .state('tab', {
      url: '/tab',
      abstract: true,
      templateUrl: 'views/tabs.html'
    })

    .state('tab.status', {
      url: '/status',
      views: {
        'status': {
          templateUrl: 'views/status.html',
          controller: 'StatusCtrl'
        }
      }
    })

    .state('tab.upcoming', {
      url: '/upcoming',
      views: {
        'upcoming': {
          templateUrl: 'views/upcoming.html',
          controller: 'UpcomingCtrl'
        }
      }
    })

    .state('tab.settings', {
      url: '/settings',
      views: {
        'settings': {
          templateUrl: 'views/settings.html',
          controller: 'SettingsCtrl'
        }
      }
    })

    .state('splash', {
      url: '/splash',
      templateUrl: 'views/splash.html',
      controller: 'SplashCtrl'
    });

  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/status');

});
<|endoftext|>


<commit_before>if( ( $('#ca-addsection').length > 0 || ( $.inArray('Non-talk pages that are automatically signed', mw.config.get( 'wgCategories' ))  >= 0 && mw.config.get( 'wgAction' ) == 'view' ) ) && $.inArray('Pages that should not be manually archived', mw.config.get( 'wgCategories' )) === -1){
	var request0 = {
		action:"query",
		titles: mw.config.get( 'wgPageName' ),
		rvsection: 0,
		prop: "revisions|info",
		intoken: "edit",
		rvprop: "content",
		indexpageids: 1,
		dataType: "xml",
		format: "xml"
	};
	$.get(mw.config.get( 'wgScriptPath' )+"/api.php", request0, function(response0){
		var content0 = $(response0).find('rev').text();
		var headerLevelRegEx = new RegExp('\\| *headerlevel *= *(\\d+)');
		var headerLevel = headerLevelRegEx.exec(content0);
		if ((headerLevel === null) || (typeof(headerLevel) === 'undefined')){
			headerLevel = 2;
		} else {
			headerLevel = parseInt(headerLevel[1]);
		}
		$('h' + headerLevel + ' span.mw-headline').each(function(index, value){
			var editSectionUrl = $(this).parent().find('.mw-editsection a:first').attr('href');
			var sectionReg = /&section=(.*)/;
			var sectionRaw = sectionReg.exec(editSectionUrl);
			if ((sectionRaw != null) && (sectionRaw[1].indexOf('T') < 0)){
				var section = parseInt(sectionRaw[1]);
				if ($(this).parent().prop("tagName") == 'H' + headerLevel){

					$(this).parent('h' + headerLevel).append('
 | ' + 'Archive' + '
');

					$(this).parent('h' + headerLevel).find('a.archiverLink').click(function(){

						var mHeaders = 'Retrieving headers...';
						var mSection = 'retrieving section content...';
						var mPosting = 'Content retrieved, performing edits...';
						var mPosted = 'Archive appended...';
						var mCleared = 'Section cleared...';
						var mReloading = 'All done! Reloading...';

						$('body').append('

');

						$('body').prepend('

');

						$('.arcProg').append('
' + mHeaders + '
');

						var regexObject3 = new RegExp('\\| *counter *= *(\\d+)');
						var counter = regexObject3.exec(content0);
						if ((counter === null) || (typeof(counter) === 'undefined')){
							$('.arcProg').remove();
							$('.overlay').remove();
							alert("No archive counter was detected on this page, so archiving was aborted.\n\n\tSee User:Equazcion/OneClickArchiver for details.");
						} else {
							var archiveNum = counter[1];

							var archiveNameReg = /\| *archive *= *(.*\%\(counter\)d.*?) *(-->)?/;
							var archiveNameRegMatch = archiveNameReg.exec(content0);
							if ((archiveNameRegMatch === null) || (typeof(archiveNameRegMatch) === 'undefined')){
								$('.arcProg').remove();
								$('.overlay').remove();
								alert("No archive name was detected on this page, so archiving was aborted.\n\n\tSee User:Equazcion/OneClickArchiver for details.");
							} else {

								var monthNames = ["january", "february", "march", "april", "may", "june",
									"july", "august", "september", "october", "november", "december"];

								var shortMonthNames = ["jan", "feb", "mar", "apr", "may", "jun",
									"jul", "aug", "sep", "oct", "nov", "dec"];

								var year = new Date().getFullYear();
								var month = new Date().getMonth();

								var rootBase = mw.config.get('wgPageName')
									.replace(/\/.*/g, '')
									.replace(/_/g, ' ');
 								var archiveName = archiveNameRegMatch[1]
									.replace(/\| *archive *= */, '')
									.replace(/\%\(year\)d/g, year)
									.replace(/\%\(month\)d/g, month)
									.replace(/\%\(monthname\)s/g, monthNames[month])
									.replace(/\%\(monthnameshort\)s/g, shortMonthNames[month])
									.replace(/\%\(counter\)d/g, archiveNum);
								var archiveBase = archiveName
									.replace(/\/.*/, '')
									.replace(/_/g, ' ');
								var archiveSub = archiveName
									.replace(/_/g, ' ')
									.replace(archiveBase, '');
								if(archiveBase != rootBase){
									$('.arcProg').remove();
									$('.overlay').remove();
									alert("Archiving was aborted due to archive page name mismatch:\n\n\tFound:\t\t" + archiveName + "\n\tExpected:\t" + mw.config.get('wgPageName').replace("_", " ") + archiveSub + "\n\n\n\tSee User:Equazcion/OneClickArchiver for details.");
								} else {
									$('.arcProg').append('
' + 'Archive name ' + archiveName + ' found, ' + mSection + '
');

									var request5 = {
										action:"query",
										titles: mw.config.get( 'wgPageName' ),
										rvsection: section,
										prop: "revisions|info",
										intoken: "edit",
										rvprop: "content",
										indexpageids: 1,
										dataType: "xml",
										format: "xml"
									};

									$.get(mw.config.get( 'wgScriptPath' )+"/api.php", request5, function(response5){

										$('.arcProg').append('
' + mPosting + '
');

										var dnau = $(response5).find('rev').text().match(//);
										if (dnau === null || typeof(dnau) === 'undefined'){
											var dnauDate = Date.now();
											dnau = null;
										} else {
											dnau = dnau[1] + ':' + dnau[2] + ' ' + dnau[3] + ' ' + dnau[4] + ' ' + dnau[5];
											var dnauDate = new Date(dnau);
											dnauDate = dnauDate.valueOf();
										}

										if(dnauDate > Date.now()){
											$('.arcProg').remove();
											$('.overlay').remove();
											alert("This section has been marked \"Do Not Archive Until\" " + dnau + ", so archiving was aborted.\n\n\tSee User:Equazcion/OneClickArchiver for details.");
										} else {
											var contentSection = '\n\n{{Clear}}\n' + $(response5).find('rev').text();

											if(dnau != null){
												contentSection = contentSection.replace(//g, '');
											}

											var request1 = {
												action:"edit",
												title: archiveName,
												appendtext: contentSection,
												summary: '[[User:Equazcion/OneClickArchiver|OneClickArchiver]] adding 1 discussion',
												token: mw.user.tokens.get( 'editToken' )
											};

											var request2 = {
												action:"edit",
												section: section,
												title: mw.config.get( 'wgPageName' ),
												text: "",
												summary: '[[User:Equazcion/OneClickArchiver|OneClickArchiver]] archived 1 discussion to [[' + archiveName + ']]',
												token: mw.user.tokens.get( 'editToken' )
											};

											$.when(
												$.post(mw.config.get( 'wgScriptPath' )+"/api.php", request1, function(response1){
													$('.arcProg').append('
' + mPosted + '
'); }),
												$.post(mw.config.get( 'wgScriptPath' )+"/api.php", request2, function(response2){
													$('.arcProg').append('
' + mCleared + '
'); })
											 ).done(function() {
												$('.arcProg').append('
' + mReloading + '
');
												location.reload();
											});
										}
									});
								}
							}
						}
					});
				}
			}
		});
		var linkTextD = "OCA - on", linkDescD = "Disable OneClickArchiver on this page";
		var linkTextE = "OCA - off", linkDescE = "Enable OneClickArchiver on this page";
		var linkText = linkTextD, linkDesc = linkDescD;
		var OCAstate = mw.user.options.get('userjs-OCA-enabled', 'true');
		if(OCAstate === 'false'){
			linkText = linkTextE, linkDesc = linkDescE;
			$( 'div.archiverDiv' ).css( 'display', 'none');
		}
		var archiverToggle = mw.util.addPortletLink(
			'p-cactions',
			'#archiverLink',
			linkText,
			'pt-OCA',
			linkDesc,
			'o',
			null
		);
		$( archiverToggle ).click( function ( e ) {
			e.preventDefault();
			/* Toggle the archiveLinks */
			$( 'div.archiverDiv' ).css( 'display', function (i, val) {
				return val === "none" ? "" : "none";
			});
			/* Toggle the toggle link */
			$( 'li#pt-OCA a' ).html( function (i, val) {
				return val === linkTextD ? linkTextE : linkTextD;
			});
			/* Toggle the toggle description */
			$( 'li#pt-OCA a' ).attr( 'title', function (i, val) {
				return val === linkDescD ? linkDescE : linkDescD;
			});
			/* Toggle default state */
			new mw.Api().postWithToken( 'options', {
				action: 'options',
				optionname: 'userjs-OCA-enabled',
				optionvalue: OCAstate === 'true' ? 'false' : 'true'
			} ).done(function() {
				var resultMsg = 'OneClickArchiver is now ' + ((OCAstate === 'true') ? 'disabled' : 'enabled') + ' by default.';
				mw.notify(resultMsg);
			});
		});
	});
}
<commit_msg>Update from Sandbox version.<commit_after>$(document).ready( function () {
	if ( ( $( '#ca-addsection' ).length > 0 ||
		( $.inArray( 'Non-talk pages that are automatically signed', mw.config.get( 'wgCategories' ) )  >= 0 &&
		mw.config.get( 'wgAction' ) == 'view' ) ) &&
		$.inArray( 'Pages that should not be manually archived', mw.config.get( 'wgCategories'  ) ) === -1 ) {
		var request0 = {
			action: 'query',
			titles: mw.config.get( 'wgPageName' ),
			rvsection: 0,
			prop: 'revisions|info',
			rvprop: "content",
			indexpageids: 1,
			format: 'json'
		};
		$.get( mw.config.get( 'wgScriptPath' ) + '/api.php', request0, function( response0 ) {
			var content0 = response0.query.pages.revisions[0]['*'];
			var headerLevelRegEx = new RegExp( '\\| *headerlevel *= *(\\d+)' );
			var headerLevel = headerLevelRegEx.exec( content0 );
			if ( headerLevel === null || headerLevel === undefined ) {
				headerLevel = 2;
			} else {
				headerLevel = parseInt( headerLevel[1] );
			}
			$( 'h' + headerLevel + ' span.mw-headline' ).each( function( i, v ) {
				var editSectionUrl = $( this ).parent().find( '.mw-editsection a:first' ).attr( 'href' );
				var sectionReg = /&section=(.*)/;
				var sectionRaw = sectionReg.exec( editSectionUrl );
				if ( sectionRaw != null && sectionRaw[1].indexOf( 'T' ) < 0 ) {
					var section = parseInt( sectionRaw[1] );
					if ( $( this ).parent().prop( 'tagName' ) == 'H' + headerLevel ) {

						$( this ).parent( 'h' + headerLevel ).append( '
 | ' + 'Archive' + '
' );

						$( this ).parent( 'h' + headerLevel ).find( 'a.archiverLink' ).click( function() {

							var mHeaders = 'Retrieving headers...';
							var mSection = 'retrieving section content...';
							var mPosting = 'Content retrieved, performing edits...';
							var mPosted = 'Archive appended...';
							var mCleared = 'Section cleared...';
							var mReloading = 'All done! Reloading...';

							$( 'body' ).append( '

' );

							$( 'body' ).prepend( '

' );

							$( '.arcProg' ).append( '
' + mHeaders + '
' );

							var regexObject3 = new RegExp( '\\| *counter *= *(\\d+)' );
							var counter = regexObject3.exec( content0 );
							if ( counter === null || counter === undefined ) {
								$( '.arcProg' ).remove();
								$( '.overlay' ).remove();
								alert( 'No archive counter was detected on this page, so archiving was aborted.\n\n\tSee User:Equazcion/OneClickArchiver for details.' );
							} else {
								var archiveNum = counter[1];

								var archiveNameReg = /\| *archive *= *(.*\%\(counter\)d.*?) *(-->)?/;
								var archiveNameRegMatch = archiveNameReg.exec( content0 );
								if ( archiveNameRegMatch === null || archiveNameRegMatch === undefined ) {
									$( '.arcProg' ).remove();
									$( '.overlay' ).remove();
									alert( 'No archive name was detected on this page, so archiving was aborted.\n\n\tSee User:Equazcion/OneClickArchiver for details.' );
								} else {
									var year = new Date().getFullYear();
									var month = new Date().getMonth();

									var rootBase = mw.config.get( 'wgPageName' )
										.replace( /\/.*/g, '' )
										.replace( /_/g, ' ' );
									var archiveName = archiveNameRegMatch[1]
										.replace( /\| *archive *= */, '' )
										.replace( /\%\(year\)d/g, year)
										.replace( /\%\(month\)d/g, month)
										.replace( /\%\(monthname\)s/g, mw.config.get( 'wgMonthNames' )[month+1] )
										.replace( /\%\(monthnameshort\)s/g, mw.config.get( 'wgMonthNamesShort' )[month+1] )
										.replace( /\%\(counter\)d/g, archiveNum);
									var archiveBase = archiveName
										.replace( /\/.*/, '' )
										.replace( /_/g, ' ' );
									var archiveSub = archiveName
										.replace( /_/g, ' ' )
										.replace( archiveBase, '' );
									if( archiveBase != rootBase ) {
										$( '.arcProg' ).remove();
										$( '.overlay' ).remove();
										alert( 'Archiving was aborted due to archive page name mismatch:\n\n\tFound:\t\t' + archiveName + '\n\tExpected:\t' + mw.config.get( 'wgPageName' ).replace( '_', ' ' ) + archiveSub + '\n\n\n\tSee User:Equazcion/OneClickArchiver for details.' );
									} else {
										$( '.arcProg' ).append( '
' + 'Archive name ' + archiveName + ' found, ' + mSection + '
' );

										var request5 = {
											action: 'query',
											titles: mw.config.get( 'wgPageName' ),
											rvsection: section,
											prop: 'revisions|info',
											intoken: 'edit',
											rvprop: 'content',
											indexpageids: 1,
											dataType: 'xml',
											format: 'xml'
										};

										$.get( mw.config.get( 'wgScriptPath' ) + '/api.php', request5, function( response5 ) {

											$( '.arcProg' ).append( '
' + mPosting + '
' );

											var dnau = $( response5 ).find( 'rev' ).text().match( // );
											if ( dnau === null || dnau === undefined ) {
												var dnauDate = Date.now();
												dnau = null;
											} else {
												dnau = dnau[1] + ':' + dnau[2] + ' ' + dnau[3] + ' ' + dnau[4] + ' ' + dnau[5];
												var dnauDate = new Date( dnau );
												dnauDate = dnauDate.valueOf();
											}

											if ( dnauDate > Date.now() ) {
												$( '.arcProg' ).remove();
												$( '.overlay' ).remove();
												alert( 'This section has been marked \"Do Not Archive Until\" " + dnau + ", so archiving was aborted.\n\n\tSee User:Equazcion/OneClickArchiver for details.' );
											} else {
												var contentSection = '\n\n{{Clear}}\n' + $( response5 ).find( 'rev' ).text();

												if ( dnau != null ) {
													contentSection = contentSection.replace( //g, '' );
												}
												new mw.Api().postWithToken( 'edit', {
													action: 'edit',
													title: archiveName,
													appendtext: contentSection,
													summary: '[[User:Equazcion/OneClickArchiver|OneClickArchiver]] ([[User:Technical_13/SandBox/OneClickArchiver.js|β]]) adding 1 discussion'
												} ).done( function() {
													$( '.arcProg' ).append( '
' + mPosted + '
' );
													new mw.Api().postWithToken( 'edit', {
														action: 'edit',
														section: section,
														title: mw.config.get( 'wgPageName' ),
														text: '',
														summary: '[[User:Equazcion/OneClickArchiver|OneClickArchiver]] ([[User:Technical_13/SandBox/OneClickArchiver.js|β]]) archived 1 discussion to [[' + archiveName + ']]',
													} ).done( function() {
														$( '.arcProg' ).append( '
' + mCleared + '
' );
														$( '.arcProg' ).append( '
' + mReloading + '
' );
														location.reload();
													} );
												} );
											}
										} );
									}
								}
							}
						} );
					}
				}
			} );
			var linkTextD = 'OCA - on', linkDescD = 'Disable OneClickArchiver on this page';
			var linkTextE = 'OCA - off', linkDescE = 'Enable OneClickArchiver on this page';
			var linkText = linkTextD, linkDesc = linkDescD;
			var OCAstate = mw.user.options.get( 'userjs-OCA-enabled', 'true' );
			if ( OCAstate === 'false' ) {
				linkText = linkTextE, linkDesc = linkDescE;
				$( 'div.archiverDiv' ).css( 'display', 'none' );
			}
			var archiverToggle = mw.util.addPortletLink(
				'p-cactions',
				'#archiverLink',
				linkText,
				'pt-OCA',
				linkDesc,
				'o',
				null
			);
			$( archiverToggle ).click( function ( e ) {
				e.preventDefault();
				/* Toggle the archiveLinks */
				$( 'div.archiverDiv' ).css( 'display', function (i, val) {
					return val === 'none' ? '' : 'none';
				});
				/* Toggle the toggle link */
				$( 'li#pt-OCA a' ).html( function ( i, val ) {
					return val === linkTextD ? linkTextE : linkTextD;
				});
				/* Toggle the toggle description */
				$( 'li#pt-OCA a' ).attr( 'title', function (i, val) {
					return val === linkDescD ? linkDescE : linkDescD;
				});
				/* Toggle default state */
				new mw.Api().postWithToken( 'options', {
					action: 'options',
					optionname: 'userjs-OCA-enabled',
					optionvalue: OCAstate === 'true' ? 'false' : 'true'
				} ).done( function() {
					var resultMsg = 'OneClickArchiver is now ' + ( OCAstate === 'true' ? 'disabled' : 'enabled' ) + ' by default.';
					mw.notify(resultMsg);
					OCAstate = OCAstate === 'true' ? 'false' : 'true';
				} );
			} );
		} );
	}
} );
<|endoftext|>


<commit_before>module.exports = function(app, router, cron) {
    console.log('module cron');

    new cron('* * * * * *', function() {
        console.log('You will see this message every second');
    }, null, true, 'America/Los_Angeles');

    router.post('/:job', function(req, res) {
        res.json({
            message: 'update ok'
        });

    });

    router.delete('/:job', function(req, res) {
        res.json({
            message: 'update ok'
        });
    });

    app.use('/cron', router);

}<commit_msg>use debug info in cron<commit_after>module.exports = function(app, router, cron, logger) {
    logger.info('module cron');

    new cron('* * * * * *', function() {
        logger.debug('You will see this message every second');
    }, null, true, 'America/Los_Angeles');

    router.post('/:job', function(req, res) {
        res.json({
            message: 'update ok'
        });

    });

    router.delete('/:job', function(req, res) {
        res.json({
            message: 'update ok'
        });
    });

    app.use('/cron', router);

}<|endoftext|>


<commit_before>import React from 'react';
import $ from 'jquery';
import Dropzone from 'react-dropzone';

import Button from 'react-bootstrap/lib/Button';
import Input from 'react-bootstrap/lib/Input';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';

class AboutComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      files: []
    };

    this.onDrop = this.onDrop.bind(this);
    this.upload = this.upload.bind(this);
  }

  onDrop(files) {
    let oldFiles = this.state.files.slice();
    oldFiles.push(files);
    this.setState({
      files
    });
  }

  upload() {
    console.log(this.state.files);
  }

  render() {
    let preview;
    if (this.state.files.length > 0) {
      preview = (

{this.state.files.length} to upload...

          <Button primary onClick={this.upload}>Start upload!</Button>

            {this.state.files.map((file) => )}

      );
    }
    return (
      <Row>
        <Col xs={12} md={6} lg={6}>

A little bit about me:

            <Input
              type='text'
              placeholder='Short Name'
            />
            <Input
              type='text'
              placeholder='Default Value'
            />
            <Input
              type='textarea'
              placeholder='Address comes here'
              rows={2}
              rowsMax={4}
            />

        </Col>
        <Col xs={12} md={6} lg={6}>
          <form className='uploadZone' onSubmit={this.upload}>
            <Dropzone onDrop={this.onDrop}>

Try dropping some files here, or click to select files to upload.

            </Dropzone>
            {preview}
          </form>
        </Col>
      </Row>
    );
  }
}

export default AboutComponent;
<commit_msg>client side for profile picture upload<commit_after>import React from 'react';
import $ from 'jquery';
import Dropzone from 'react-dropzone';

import Button from 'react-bootstrap/lib/Button';
import Input from 'react-bootstrap/lib/Input';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';

class AboutComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      files: []
    };

    this.onDrop = this.onDrop.bind(this);
    this.upload = this.upload.bind(this);
  }

  onDrop(files) {
    let oldFiles = this.state.files.slice();
    oldFiles.push(files);
    this.setState({
      files
    });
  }

  upload() {
    let submitForm = function (event, data) {
      // Create a jQuery object from the form
      let $form = $(event.target);

      // Serialize the form data
      let formData = $form.serialize();

      // You should sterilise the file names
      $.each(data.files, function (key, value) {
        formData = formData + '&filenames[]=' + value;
      });

      $.ajax({
        url: '/api/profile/img',
        type: 'POST',
        data: formData,
        cache: false,
        dataType: 'json',
        success(data, textStatus, jqXHR) {
          if (typeof data.error === 'undefined') {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
          } else {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
          }
        },
        error(jqXHR, textStatus, errorThrown) {
          // Handle errors here
          console.log('ERRORS: ' + textStatus);
        },
        complete() {
          // STOP LOADING SPINNER
        }
      });
    };

    let data = new FormData();
    let files = this.state.files;
    if (files && files.length > 0) {
      this.state.files.forEach(function (value, i) {
        data.append(i, value);
      });
      $.ajax({
        url: '/api/profile/img',
        type: 'POST',
        data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false,
        success(data, textStatus, jqXHR) {
          if (typeof data.error === 'undefined') {
            // Success so call function to process the form
            submitForm(event, data);
          } else {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
          }
        },
        error(jqXHR, textStatus, errorThrown) {
          // Handle errors here
          console.log('ERRORS: ' + textStatus);
          // STOP LOADING SPINNER
        }
      });
    } else {
      alert('nothing to upload!');
    }
  }

  render() {
    let preview;
    if (this.state.files.length > 0) {
      preview = (

{this.state.files.length} to upload...

          <Button primary onClick={this.upload}>Start upload!</Button>

            {this.state.files.map((file) => )}

      );
    }
    return (
      <Row>
        <Col xs={12} md={6} lg={6}>

A little bit about me:

            <Input
              type='text'
              placeholder='Short Name'
            />
            <Input
              type='text'
              placeholder='Default Value'
            />
            <Input
              type='textarea'
              placeholder='Address comes here'
              rows={2}
              rowsMax={4}
            />

        </Col>
        <Col xs={12} md={6} lg={6}>
          <form className='uploadZone' onSubmit={this.upload}>
            <Dropzone onDrop={this.onDrop}>

Try dropping some files here, or click to select files to upload.

            </Dropzone>
            {preview}
          </form>
        </Col>
      </Row>
    );
  }
}

export default AboutComponent;
<|endoftext|>


<commit_before>/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */

export SLDSSettings from './settings';
export Settings from './settings';

export SLDSIconSettings from './icon-settings';
export IconSettings from './icon-settings';

export SLDSAccordion from './accordion';
export Accordion from './accordion';

export SLDSAccordionPanel from './accordion/panel';
export AccordionPanel from './accordion/panel';

export SLDSAlert from './alert';
export Alert from './alert';

export SLDSAlertContainer from './alert/container';
export AlertContainer from './alert/container';

export SLDSAvatar from './avatar';
export Avatar from './avatar';

export SLDSButton from './button';
export Button from './button';

export SLDSButtonGroup from './button-group';
export ButtonGroup from './button-group';

export SLDSButtonStateful from './button-stateful';
export ButtonStateful from './button-stateful';

/* Remove at next breaking change */
export SLDSBreadCrumb from './breadcrumb';
export BreadCrumb from './breadcrumb';

export SLDSBreadcrumb from './breadcrumb';
export Breadcrumb from './breadcrumb';

export SLDSCard from './card';
export Card from './card';

export SLDSCardEmpty from './card/empty';
export CardEmpty from './card/empty';

export SLDSCardFilter from './card/filter';
export CardFilter from './card/filter';

export SLDSCheckbox from './forms/checkbox';
export Checkbox from './forms/checkbox';

export SLDSCombobox from './combobox';
export Combobox from './combobox';

export SLDSComboboxFilterAndLimit from './combobox/filter';
export comboboxFilterAndLimit from './combobox/filter';
export comboboxAddSubheadings from './combobox/add-subheadings';

export SLDSGlobalHeader from './global-header';
export GlobalHeader from './global-header';

export SLDSGlobalHeaderButton from './global-header/button';
export GlobalHeaderButton from './global-header/button';

export SLDSGlobalHeaderDropdown from './global-header/dropdown';
export GlobalHeaderDropdown from './global-header/dropdown';

export SLDSGlobalHeaderProfile from './global-header/profile';
export GlobalHeaderProfile from './global-header/profile';

export SLDSGlobalHeaderSearch from './global-header/search';
export GlobalHeaderSearch from './global-header/search';

export SLDSGlobalNavigationBar from './global-navigation-bar';
export GlobalNavigationBar from './global-navigation-bar';

export SLDSGlobalNavigationBarRegion from './global-navigation-bar/region';
export GlobalNavigationBarRegion from './global-navigation-bar/region';

export SLDSGlobalNavigationBarLink from './global-navigation-bar/link';
export GlobalNavigationBarLink from './global-navigation-bar/link';

export SLDSGlobalNavigationBarDropdown from './global-navigation-bar/dropdown';
export GlobalNavigationBarDropdown from './global-navigation-bar/dropdown';

export SLDSDataTable from './data-table';
export DataTable from './data-table';

export SLDSDataTableCell from './data-table/cell';
export DataTableCell from './data-table/cell';

export SLDSDataTableColumn from './data-table/column';
export DataTableColumn from './data-table/column';

export SLDSDataTableRowActions from './data-table/row-actions';
export DataTableRowActions from './data-table/row-actions';

export SLDSDatepicker from './date-picker';
export Datepicker from './date-picker';

export SLDSIcon from './icon';
export Icon from './icon';

export SLDSIllustration from './illustration';
export Illustration from './illustration';

// TODO: Should probably be removed from export and only used internally. This component does not implement Button Icons per SLDS, but only the icons in buttons
export SLDSButtonIcon from './icon/button-icon';
export ButtonIcon from './icon/button-icon';

export SLDSFilter from './filter';
export Filter from './filter';

export SLDSInlineEdit from './forms/input/inline';
export InlineEdit from './forms/input/inline';

export SLDSInput from './input';
export Input from './input';

export SLDSSearch from './input/search';
export Search from './input/search';

export SLDSInputIcon from './icon/input-icon';
export InputIcon from './icon/input-icon';

export SLDSLookup from './lookup';
export Lookup from './lookup';
export SLDSLookupDefaultFooter from './lookup/menu/default-footer';
export LookupDefaultFooter from './lookup/menu/default-footer';
export SLDSLookupDefaultHeader from './lookup/menu/default-header';
export LookupDefaultHeader from './lookup/menu/default-header';
export SLDSLookupDefaultSectionDivider from './lookup/menu/default-section-divider';
export LookupDefaultSectionDivider from './lookup/menu/default-section-divider';

export SLDSMediaObject from './media-object';
export MediaObject from './media-object';

export SLDSMenuDropdown from './menu-dropdown';
export Dropdown from './menu-dropdown';
export SLDSDropdownTrigger from './menu-dropdown/button-trigger';
export DropdownTrigger from './menu-dropdown/button-trigger';

export SLDSMenuPicklist from './menu-picklist';
export Picklist from './menu-picklist';

export SLDSModal from './modal';
export Modal from './modal';

export SLDSModalTrigger from './modal/trigger';
export ModalTrigger from './modal/trigger';

export SLDSNavigation from './navigation';
export Navigation from './navigation';

export SLDSNotification from './notification';
export Notification from './notification';

export SLDSPanel from './panel';
export Panel from './panel';
export SLDSPanelFilterGroup from './panel/filtering/group';
export PanelFilterGroup from './panel/filtering/group';
export SLDSPanelFilterList from './panel/filtering/list';
export PanelFilterList from './panel/filtering/list';
export SLDSPanelFilterListHeading from './panel/filtering/list-heading';
export PanelFilterListHeading from './panel/filtering/list-heading';

export SLDSPageHeader from './page-header';
export PageHeader from './page-header';

export SLDSPill from './pill';
export Pill from './pill';

export SLDSPopover from './popover';
export Popover from './popover';

export SLDSPopoverTooltip from './tooltip';
export PopoverTooltip from './tooltip';
export SLDSTooltip from './tooltip';
export Tooltip from './tooltip';

export SLDSProgressIndicator from './progress-indicator';
export ProgressIndicator from './progress-indicator';

export SLDSProgressRing from './progress-ring';
export ProgressRing from './progress-ring';

export SLDSRadio from './radio';
export Radio from './radio';

export SLDSRadioButtonGroup from './radio-button-group';
export RadioButtonGroup from './radio-button-group';

export SLDSRadioGroup from './radio-group';
export RadioGroup from './radio-group';

export SLDSSlider from './slider';
export Slider from './slider';

export SLDSSpinner from './spinner';
export Spinner from './spinner';

// Remove at next breaking change
export SLDSSplitview from './split-view';
export Splitview from './split-view';

export SLDSSplitView from './split-view';
export SplitView from './split-view';

export SLDSSplitViewHeader from './split-view/header';
export SplitViewHeader from './split-view/header';

export SLDSSplitViewListbox from './split-view/listbox';
export SplitViewListbox from './split-view/listbox';

export SLDSTextarea from './textarea';
export Textarea from './textarea';

export SLDSTimepicker from './time-picker';
export Timepicker from './time-picker';

export SLDSTabs from './tabs';
export Tabs from './tabs';
export SLDSTabsPanel from './tabs/panel';
export TabsPanel from './tabs/panel';

export SLDSToast from './toast';
export Toast from './toast';
export SLDSToastContainer from './toast/container';
export ToastContainer from './toast/container';

export SLDSUtilityIcon from './utilities/utility-icon';
export UtilityIcon from './utilities/utility-icon';

export SLDSTree from './tree';
export Tree from './tree';

// Library utilities
export log from '../utilities/log';
<commit_msg>Add AppLauncher to requireds<commit_after>/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */

export SLDSSettings from './settings';
export Settings from './settings';

export SLDSIconSettings from './icon-settings';
export IconSettings from './icon-settings';

export SLDSAccordion from './accordion';
export Accordion from './accordion';

export SLDSAccordionPanel from './accordion/panel';
export AccordionPanel from './accordion/panel';

export SLDSAlert from './alert';
export Alert from './alert';

export SLDSAlertContainer from './alert/container';
export AlertContainer from './alert/container';

export SLDSAppLauncher from './app-launcher';
export AppLauncher from './app-launcher';

export SLDSAvatar from './avatar';
export Avatar from './avatar';

export SLDSButton from './button';
export Button from './button';

export SLDSButtonGroup from './button-group';
export ButtonGroup from './button-group';

export SLDSButtonStateful from './button-stateful';
export ButtonStateful from './button-stateful';

/* Remove at next breaking change */
export SLDSBreadCrumb from './breadcrumb';
export BreadCrumb from './breadcrumb';

export SLDSBreadcrumb from './breadcrumb';
export Breadcrumb from './breadcrumb';

export SLDSCard from './card';
export Card from './card';

export SLDSCardEmpty from './card/empty';
export CardEmpty from './card/empty';

export SLDSCardFilter from './card/filter';
export CardFilter from './card/filter';

export SLDSCheckbox from './forms/checkbox';
export Checkbox from './forms/checkbox';

export SLDSCombobox from './combobox';
export Combobox from './combobox';

export SLDSComboboxFilterAndLimit from './combobox/filter';
export comboboxFilterAndLimit from './combobox/filter';
export comboboxAddSubheadings from './combobox/add-subheadings';

export SLDSGlobalHeader from './global-header';
export GlobalHeader from './global-header';

export SLDSGlobalHeaderButton from './global-header/button';
export GlobalHeaderButton from './global-header/button';

export SLDSGlobalHeaderDropdown from './global-header/dropdown';
export GlobalHeaderDropdown from './global-header/dropdown';

export SLDSGlobalHeaderProfile from './global-header/profile';
export GlobalHeaderProfile from './global-header/profile';

export SLDSGlobalHeaderSearch from './global-header/search';
export GlobalHeaderSearch from './global-header/search';

export SLDSGlobalNavigationBar from './global-navigation-bar';
export GlobalNavigationBar from './global-navigation-bar';

export SLDSGlobalNavigationBarRegion from './global-navigation-bar/region';
export GlobalNavigationBarRegion from './global-navigation-bar/region';

export SLDSGlobalNavigationBarLink from './global-navigation-bar/link';
export GlobalNavigationBarLink from './global-navigation-bar/link';

export SLDSGlobalNavigationBarDropdown from './global-navigation-bar/dropdown';
export GlobalNavigationBarDropdown from './global-navigation-bar/dropdown';

export SLDSDataTable from './data-table';
export DataTable from './data-table';

export SLDSDataTableCell from './data-table/cell';
export DataTableCell from './data-table/cell';

export SLDSDataTableColumn from './data-table/column';
export DataTableColumn from './data-table/column';

export SLDSDataTableRowActions from './data-table/row-actions';
export DataTableRowActions from './data-table/row-actions';

export SLDSDatepicker from './date-picker';
export Datepicker from './date-picker';

export SLDSIcon from './icon';
export Icon from './icon';

export SLDSIllustration from './illustration';
export Illustration from './illustration';

// TODO: Should probably be removed from export and only used internally. This component does not implement Button Icons per SLDS, but only the icons in buttons
export SLDSButtonIcon from './icon/button-icon';
export ButtonIcon from './icon/button-icon';

export SLDSFilter from './filter';
export Filter from './filter';

export SLDSInlineEdit from './forms/input/inline';
export InlineEdit from './forms/input/inline';

export SLDSInput from './input';
export Input from './input';

export SLDSSearch from './input/search';
export Search from './input/search';

export SLDSInputIcon from './icon/input-icon';
export InputIcon from './icon/input-icon';

export SLDSLookup from './lookup';
export Lookup from './lookup';
export SLDSLookupDefaultFooter from './lookup/menu/default-footer';
export LookupDefaultFooter from './lookup/menu/default-footer';
export SLDSLookupDefaultHeader from './lookup/menu/default-header';
export LookupDefaultHeader from './lookup/menu/default-header';
export SLDSLookupDefaultSectionDivider from './lookup/menu/default-section-divider';
export LookupDefaultSectionDivider from './lookup/menu/default-section-divider';

export SLDSMediaObject from './media-object';
export MediaObject from './media-object';

export SLDSMenuDropdown from './menu-dropdown';
export Dropdown from './menu-dropdown';
export SLDSDropdownTrigger from './menu-dropdown/button-trigger';
export DropdownTrigger from './menu-dropdown/button-trigger';

export SLDSMenuPicklist from './menu-picklist';
export Picklist from './menu-picklist';

export SLDSModal from './modal';
export Modal from './modal';

export SLDSModalTrigger from './modal/trigger';
export ModalTrigger from './modal/trigger';

export SLDSNavigation from './navigation';
export Navigation from './navigation';

export SLDSNotification from './notification';
export Notification from './notification';

export SLDSPanel from './panel';
export Panel from './panel';
export SLDSPanelFilterGroup from './panel/filtering/group';
export PanelFilterGroup from './panel/filtering/group';
export SLDSPanelFilterList from './panel/filtering/list';
export PanelFilterList from './panel/filtering/list';
export SLDSPanelFilterListHeading from './panel/filtering/list-heading';
export PanelFilterListHeading from './panel/filtering/list-heading';

export SLDSPageHeader from './page-header';
export PageHeader from './page-header';

export SLDSPill from './pill';
export Pill from './pill';

export SLDSPopover from './popover';
export Popover from './popover';

export SLDSPopoverTooltip from './tooltip';
export PopoverTooltip from './tooltip';
export SLDSTooltip from './tooltip';
export Tooltip from './tooltip';

export SLDSProgressIndicator from './progress-indicator';
export ProgressIndicator from './progress-indicator';

export SLDSProgressRing from './progress-ring';
export ProgressRing from './progress-ring';

export SLDSRadio from './radio';
export Radio from './radio';

export SLDSRadioButtonGroup from './radio-button-group';
export RadioButtonGroup from './radio-button-group';

export SLDSRadioGroup from './radio-group';
export RadioGroup from './radio-group';

export SLDSSlider from './slider';
export Slider from './slider';

export SLDSSpinner from './spinner';
export Spinner from './spinner';

// Remove at next breaking change
export SLDSSplitview from './split-view';
export Splitview from './split-view';

export SLDSSplitView from './split-view';
export SplitView from './split-view';

export SLDSSplitViewHeader from './split-view/header';
export SplitViewHeader from './split-view/header';

export SLDSSplitViewListbox from './split-view/listbox';
export SplitViewListbox from './split-view/listbox';

export SLDSTextarea from './textarea';
export Textarea from './textarea';

export SLDSTimepicker from './time-picker';
export Timepicker from './time-picker';

export SLDSTabs from './tabs';
export Tabs from './tabs';
export SLDSTabsPanel from './tabs/panel';
export TabsPanel from './tabs/panel';

export SLDSToast from './toast';
export Toast from './toast';
export SLDSToastContainer from './toast/container';
export ToastContainer from './toast/container';

export SLDSUtilityIcon from './utilities/utility-icon';
export UtilityIcon from './utilities/utility-icon';

export SLDSTree from './tree';
export Tree from './tree';

// Library utilities
export log from '../utilities/log';
<|endoftext|>


<commit_before>var toCloneTarget = function (target) {
    var clone = cloneVisible(target);
    var position = getScreenPosition(target);
    css(clone, `position:absolute;left:${position.left}px;top:${position.top}px;user-select:none;`);
    setOpacity(target, 0);
    return clone;
};
var appendChild = function (a, b) {
    a.appendChild(b);
};
var remove = function (a) {
    a.parentNode && a.parentNode.removeChild(a);
};
function drag(target, initialEvent, overflow) {

    !/^(?:select|input|textarea)$/i.test(initialEvent.target.tagName) && initialEvent.preventDefault();
    if (isArray(target)) {
        var extraTargets = target.slice(1);
        target = target[0];
    } else {
        var extraTargets = target.with ? [].concat(target.with) : [];
    }
    var saved_delta = { x: target.offsetLeft - initialEvent.clientX, y: target.offsetTop - initialEvent.clientY };
    var clone;
    var saved_opacity = target.style.opacity;
    var saved_filter = target.style.filter;
    var extraStyles = extraTargets.map(e => ({ opacity: e.style.opacity, filter: e.style.filter }));
    var extraClones;
    var mousemove = function (event) {
        if (event.moveLocked) return;
        if (!saved_delta.ing) {
            var abs = Math.abs;
            if (abs(target.offsetLeft - event.clientX - saved_delta.x < MOVELOCK_DELTA) && abs(target.offsetTop - event.clientY - saved_delta.y) < MOVELOCK_DELTA) return;
            saved_delta.ing = true;
            if (!/absolute|fixed/.test(getComputedStyle(target).position)) {
                clone = toCloneTarget(target);
                appendChild(document.body, clone);
            } else {
                clone = target;
            }
            extraClones = extraTargets.map(toCloneTarget);
            extraClones.map(c => document.body.appendChild(c));
            saved_delta.x += clone.offsetLeft - target.offsetLeft;
            saved_delta.y += clone.offsetTop - target.offsetTop;
            clone.style.zIndex = zIndex();
            extraClones.map(e => e.style.zIndex = clone.style.zIndex);
            dispatch("dragstart", target);
        }
        drag.target = clone;
        event.moveLocked = true;
        var offsetLeft = saved_delta.x + event.clientX;
        var offsetTop = saved_delta.y + event.clientY;
        var cloneDeltaLeft = - clone.offsetLeft;
        var cloneDeltaTop = - clone.offsetTop;
        move.call(clone, offsetLeft, offsetTop, overflow);
        cloneDeltaLeft += clone.offsetLeft;
        cloneDeltaTop += clone.offsetTop;
        extraClones.map(clone => css(clone, `left:${fromPixel(clone.offsetLeft + cloneDeltaLeft)};top:${fromPixel(clone.offsetTop + cloneDeltaTop)};`));
        dispatch("dragmove", target);
    };
    var clear = function () {
        if (clone !== target) remove(clone), css(target, { opacity: saved_opacity, filter: saved_filter });
        remove(extraClones);
        extraTargets.map((target, cx) => css(target, extraStyles[cx]));
        if (saved_delta.ing) dispatch("dragend", target);
        drag.target = null;
        saved_delta = null;
    };
    moveupon(target, {
        move: mousemove,
        end: clear
    }, initialEvent);
}
var mousedrag = function (event) {
    drag(this, event);
};
var touchdrag = function (event) {
    extendTouchEvent(event);
    drag(this, event);
};
drag.on = function (target) {
    onmousedown(target, mousedrag);
    ontouchstart(target, touchdrag);
};<commit_msg>未拖动时不再报错<commit_after>var toCloneTarget = function (target) {
    var clone = cloneVisible(target);
    var position = getScreenPosition(target);
    css(clone, `position:absolute;left:${position.left}px;top:${position.top}px;user-select:none;`);
    setOpacity(target, 0);
    return clone;
};
var appendChild = function (a, b) {
    a.appendChild(b);
};
var remove = function (a) {
    a && a.parentNode && a.parentNode.removeChild(a);
};
function drag(target, initialEvent, overflow) {

    !/^(?:select|input|textarea)$/i.test(initialEvent.target.tagName) && initialEvent.preventDefault();
    if (isArray(target)) {
        var extraTargets = target.slice(1);
        target = target[0];
    } else {
        var extraTargets = target.with ? [].concat(target.with) : [];
    }
    var saved_delta = { x: target.offsetLeft - initialEvent.clientX, y: target.offsetTop - initialEvent.clientY };
    var clone;
    var saved_opacity = target.style.opacity;
    var saved_filter = target.style.filter;
    var extraStyles = extraTargets.map(e => ({ opacity: e.style.opacity, filter: e.style.filter }));
    var extraClones;
    var mousemove = function (event) {
        if (event.moveLocked) return;
        if (!saved_delta.ing) {
            var abs = Math.abs;
            if (abs(target.offsetLeft - event.clientX - saved_delta.x < MOVELOCK_DELTA) && abs(target.offsetTop - event.clientY - saved_delta.y) < MOVELOCK_DELTA) return;
            saved_delta.ing = true;
            if (!/absolute|fixed/.test(getComputedStyle(target).position)) {
                clone = toCloneTarget(target);
                appendChild(document.body, clone);
            } else {
                clone = target;
            }
            extraClones = extraTargets.map(toCloneTarget);
            extraClones.map(c => document.body.appendChild(c));
            saved_delta.x += clone.offsetLeft - target.offsetLeft;
            saved_delta.y += clone.offsetTop - target.offsetTop;
            clone.style.zIndex = zIndex();
            extraClones.map(e => e.style.zIndex = clone.style.zIndex);
            dispatch("dragstart", target);
        }
        drag.target = clone;
        event.moveLocked = true;
        var offsetLeft = saved_delta.x + event.clientX;
        var offsetTop = saved_delta.y + event.clientY;
        var cloneDeltaLeft = - clone.offsetLeft;
        var cloneDeltaTop = - clone.offsetTop;
        move.call(clone, offsetLeft, offsetTop, overflow);
        cloneDeltaLeft += clone.offsetLeft;
        cloneDeltaTop += clone.offsetTop;
        extraClones.map(clone => css(clone, `left:${fromPixel(clone.offsetLeft + cloneDeltaLeft)};top:${fromPixel(clone.offsetTop + cloneDeltaTop)};`));
        dispatch("dragmove", target);
    };
    var clear = function () {
        if (clone !== target) remove(clone), css(target, { opacity: saved_opacity, filter: saved_filter });
        remove(extraClones);
        extraTargets.map((target, cx) => css(target, extraStyles[cx]));
        if (saved_delta.ing) dispatch("dragend", target);
        drag.target = null;
        saved_delta = null;
    };
    moveupon(target, {
        move: mousemove,
        end: clear
    }, initialEvent);
}
var mousedrag = function (event) {
    drag(this, event);
};
var touchdrag = function (event) {
    extendTouchEvent(event);
    drag(this, event);
};
drag.on = function (target) {
    onmousedown(target, mousedrag);
    ontouchstart(target, touchdrag);
};<|endoftext|>


<commit_before>var cip = require('./cip-methods.js');
var Q = require('q');

var result_mapping = [
    {'key': 'id',
     'short': 'id'},
    {'key': '{af4b2e00-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'filename'
    },
    {'key': '{f5d1dcd8-c553-4346-8d4d-672c85bb59be}',
     'short': 'license',
    },
    {'key': '{9b071045-118c-4f42-afa1-c3121783ac66}',
     'short': 'creator',
    },
    {'key': '{af4b2e2c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'copyright',
    },
    {'key': '{2ce9c8eb-b83d-4a91-9d09-2141cac7de12}',
     'short': 'description',
    },
    {'key': '{af4b2e12-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_height'
    },
    {'key': '{af4b2e11-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_width'
    },
    {'key': '{af4b2e0f-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'dpi',
    },
    {'key': '{418a4c92-fe63-11d3-9030-0080ad80c556}',
     'short': 'longitude',
    },
    {'key': '{418a4c91-fe63-11d3-9030-0080ad80c556}',
     'short': 'latitude',
    },
    {'key': '{ca6903b8-c3c4-47fa-9592-2d486d766ce0}',
     'short': 'actorname',
    },
    {'key': '{38664623-b081-4251-8c1c-383ef57ac54d}',
     'short': 'locationnote'
    },
    {'key': '{a02dd229-5aa8-4bb4-825a-038cf21f92bd}',
     'short': 'year'
    },
    {'key': '{76f2cca6-3652-40ee-b198-5d0afe931caa}',
     'short': 'assetno'
    },
    {'key': '{59ac5106-a3b4-4152-8647-66cebcb6af48}',
     'short': 'creation_time_from'
    },
    {'key': '{eaf2f030-2bfb-4d75-98ab-fb9bd33affcc}',
     'short': 'creation_time_to'
    },
    {'key': '{65f668d1-b070-494f-a9a3-7b6c3d370e65}',
     'short': 'acceptance_time_from'
    },
    {'key': '{0db7de9e-37fa-47a5-b087-0b1e6066ee86}',
     'short': 'acceptance_time_to'
    },
    {'key': '{1cb94319-9e1f-428e-993f-a78c78947f60}',
     'short': 'timenote'
    },
    {'key': '{8e820869-e338-4761-aa88-3dcd89f8cbae}',
     'short': 'archiveno'
    },
    {'key': '{d6025301-ef5e-4722-b101-78fd28262a98}',
     'short': 'topno'
    },
    {'key': '{8ac71e5d-5ca9-42cf-8c21-02c41e1af5cd}',
     'short': 'archivename'
    },
    {'key': '{9aef60d3-38b4-4e47-8104-d018b83ea6c6}',
     'short': 'unitno'
    },
    {'key': '{51b661a3-585e-4dbd-9e98-85e12ad91190}',
     'short': 'place'
    },
    {'key': '{24252838-de09-46e4-8f7d-f3fb85cde78f}',
     'short': 'city'
    },
    {'key': '{6fb1f61b-14a3-4851-bba0-cf7e71ef59cb}',
     'short': 'short_title'
    },
    {'key': '{af4b2e0c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'categories'
    },
    {'key': '{659ca0c6-92d8-4f7a-af58-8a3c69df2ede}',
     'short': 'street'
    },
    {'key': '{ed64a9f8-8d19-4f60-a615-5bd3b188e98a}',
     'short': 'address'
    },
    {'key': '{5bbe594f-d029-4bb5-9c42-8f1ac8c94b7f}',
     'short': 'zipcode'
    },
    {'key': '{af4b2e02-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'modification_time'
    },
    {'key': '{a493be21-0f70-4cae-9394-703eca848bad}',
     'short': 'review_state'
    },
    {'key': '{bf7a30ac-e53b-4147-95e0-aea8c71340ca}',
     'short': 'cropping_status'
    },
    {'key': '{af4b2e71-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_sub_assets'
    },
    {'key': '{af4b2e72-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_master_assets'
    }
];

exports.result_mapping = result_mapping;

function format_result(fields) {
    var result = {};

    for(var i=0; i < result_mapping.length; ++i) {
        if(result_mapping[i].key in fields) {
            result[result_mapping[i].short] = fields[result_mapping[i].key];
        }
    }

    return result;
}

exports.format_result = format_result;

// This expects that the related_master_assets has been parsed using the
// cip-methods.js's parse_binary_relations
function extend_from_master(nm, metadata) {
    console.log(metadata);
    // We expect the formatted metadata to contain a binary field with related
    // master asset ids.
    if(!metadata.related_master_assets || metadata.related_master_assets.length === 0) {
        return metadata;
    }
    // We expect only one master asset.
    if(metadata.related_master_assets.length !== 1) {
        // Compile a textual representation of the master asset id's.
        var master_asset_summary = JSON.stringify(metadata.related_master_assets);
        throw new Error( 'Expected exactly one master asset, received ' +
            metadata.related_master_assets.length+ ': ' +master_asset_summary );
    }
    // Deriving the single master asset id.
    var master_asset_id = metadata.related_master_assets[0].id;

    return cip.get_asset(nm, metadata.catalog, master_asset_id)
    .then(function(master_assets) {
        // We assume only one is returned.
        if(master_assets.length !== 1) {
            throw new Error( 'Expected exactly one master asset, received ' +
                master_assets.length );
        }
        var master_asset = master_assets[0];
        var master_asset_metadata = format_result(master_asset.fields);
        // Overwrite where the original asset has no value.
        for(var f in metadata) {
            var original_value = metadata[f];
            var master_value = master_asset_metadata[f];
            if(!original_value && master_value) {
                // Overwrite with the master assets value.
                metadata[f] = master_value;
            }
        }
        console.log(metadata);
        return metadata;
    });
}

exports.extend_from_master = extend_from_master;
<commit_msg>Update asset-mapping.js<commit_after>var cip = require('./cip-methods.js');
var Q = require('q');

var result_mapping = [
    {'key': 'id',
     'short': 'id'},
    {'key': '{af4b2e00-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'filename'
    },
    {'key': '{f5d1dcd8-c553-4346-8d4d-672c85bb59be}',
     'short': 'license',
    },
    {'key': '{9b071045-118c-4f42-afa1-c3121783ac66}',
     'short': 'creator',
    },
    {'key': '{af4b2e2c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'copyright',
    },
    {'key': '{2ce9c8eb-b83d-4a91-9d09-2141cac7de12}',
     'short': 'description',
    },
    {'key': '{af4b2e12-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_height'
    },
    {'key': '{af4b2e11-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'img_width'
    },
    {'key': '{af4b2e0f-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'dpi',
    },
    {'key': '{418a4c92-fe63-11d3-9030-0080ad80c556}',
     'short': 'longitude',
    },
    {'key': '{418a4c91-fe63-11d3-9030-0080ad80c556}',
     'short': 'latitude',
    },
    {'key': '{ca6903b8-c3c4-47fa-9592-2d486d766ce0}',
     'short': 'actorname',
    },
    {'key': '{38664623-b081-4251-8c1c-383ef57ac54d}',
     'short': 'locationnote'
    },
    {'key': '{a02dd229-5aa8-4bb4-825a-038cf21f92bd}',
     'short': 'year'
    },
    {'key': '{76f2cca6-3652-40ee-b198-5d0afe931caa}',
     'short': 'assetno'
    },
    {'key': '{59ac5106-a3b4-4152-8647-66cebcb6af48}',
     'short': 'creation_time_from'
    },
    {'key': '{eaf2f030-2bfb-4d75-98ab-fb9bd33affcc}',
     'short': 'creation_time_to'
    },
    {'key': '{65f668d1-b070-494f-a9a3-7b6c3d370e65}',
     'short': 'acceptance_time_from'
    },
    {'key': '{0db7de9e-37fa-47a5-b087-0b1e6066ee86}',
     'short': 'acceptance_time_to'
    },
    {'key': '{1cb94319-9e1f-428e-993f-a78c78947f60}',
     'short': 'timenote'
    },
    {'key': '{8e820869-e338-4761-aa88-3dcd89f8cbae}',
     'short': 'archiveno'
    },
    {'key': '{d6025301-ef5e-4722-b101-78fd28262a98}',
     'short': 'topno'
    },
    {'key': '{8ac71e5d-5ca9-42cf-8c21-02c41e1af5cd}',
     'short': 'archivename'
    },
    {'key': '{9aef60d3-38b4-4e47-8104-d018b83ea6c6}',
     'short': 'unitno'
    },
    {'key': '{51b661a3-585e-4dbd-9e98-85e12ad91190}',
     'short': 'place'
    },
    {'key': '{24252838-de09-46e4-8f7d-f3fb85cde78f}',
     'short': 'city'
    },
    {'key': '{6fb1f61b-14a3-4851-bba0-cf7e71ef59cb}',
     'short': 'short_title'
    },
    {'key': '{af4b2e0c-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'categories'
    },
    {'key': '{659ca0c6-92d8-4f7a-af58-8a3c69df2ede}',
     'short': 'street'
    },
    {'key': '{ed64a9f8-8d19-4f60-a615-5bd3b188e98a}',
     'short': 'address'
    },
    {'key': '{5bbe594f-d029-4bb5-9c42-8f1ac8c94b7f}',
     'short': 'zipcode'
    },
    {'key': '{af4b2e02-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'modification_time'
    },
    {'key': '{a493be21-0f70-4cae-9394-703eca848bad}',
     'short': 'review_state'
    },
    {'key': '{bf7a30ac-e53b-4147-95e0-aea8c71340ca}',
     'short': 'cropping_status'
    },
    {'key': '{af4b2e71-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_sub_assets'
    },
    {'key': '{af4b2e72-5f6a-11d2-8f20-0000c0e166dc}',
     'short': 'related_master_assets'
    }
];

exports.result_mapping = result_mapping;

function format_result(fields) {
    var result = {};

    for(var i=0; i < result_mapping.length; ++i) {
        if(result_mapping[i].key in fields) {
            result[result_mapping[i].short] = fields[result_mapping[i].key];
        }
    }

    return result;
}

exports.format_result = format_result;

// This expects that the related_master_assets has been parsed using the
// cip-methods.js's parse_binary_relations
function extend_from_master(nm, metadata) {
    console.log(metadata);
    // We expect the formatted metadata to contain a binary field with related
    // master asset ids.
    if(!metadata.related_master_assets || metadata.related_master_assets.length === 0) {
        return metadata;
    }
    // We expect only one master asset.
    if(metadata.related_master_assets.length !== 1) {
        // Compile a textual representation of the master asset id's.
        var master_asset_summary = JSON.stringify(metadata.related_master_assets);
        throw new Error( 'Expected exactly one master asset, received ' +
            metadata.related_master_assets.length+ ': ' +master_asset_summary );
    }
    // Deriving the single master asset id.
    var master_asset_id = metadata.related_master_assets[0].id;

    return cip.get_asset(nm, metadata.catalog, master_asset_id)
    .then(function(master_assets) {
        // We assume only one is returned.
        if(master_assets.length !== 1) {
            throw new Error( 'Expected exactly one master asset, received ' +
                master_assets.length );
        }
        var master_asset = master_assets[0];
        var master_asset_metadata = format_result(master_asset.fields);
        // Overwrite where the original asset has no value.
        for(var f in metadata) {
            var original_value = metadata[f];
            var master_value = master_asset_metadata[f];
            if(!original_value && master_value) {
                // Overwrite with the master assets value.
                metadata[f] = master_value;
            }
        }
        return metadata;
    });
}

exports.extend_from_master = extend_from_master;
<|endoftext|>


<commit_before>"use strict";
var errh = require('ncbt').errh;
var ops = require('ops');
var AuthProblem = require('./auth_problem');

var AuthProvider = function (opt_options) {
	this.options = this.createOptions(opt_options);

	this.tokener = null;
	this.adapter = null;
	this.revoker = null;
};

AuthProvider.prototype.createOptions = function (opt_options) {
	return ops.cloneWithDefaults(opt_options, this.getDefaultOptions());
};

AuthProvider.prototype.getDefaultOptions = function () {
	var authMaxAge = 60 * 60 * 24 * 7 * 2 * 1000; // 2 weeks in ms
	return {
		maxAge: authMaxAge,
		useLimitedToken: true, // use limited token cookie CSRF protection (see README for details)
		renewalInterval: Math.round(authMaxAge / 2),

		allowedIssuedClockDeviation: 5 * 60 * 1000, // 5 minites in ms
	};
};

AuthProvider.prototype.setTokener = function (tokener) {
	this.tokener = tokener;
};

AuthProvider.prototype.setAdapter = function (adapter) {
	this.adapter = adapter;
};

AuthProvider.prototype.setRevoker = function (revoker) {
	this.revoker = revoker;
};

AuthProvider.prototype.login = function (res, identityStr, options, cb) {
	options = options || {};
	var useCookies = !!options.useCookies;
	var isSessionLifetime = !!options.isSessionLifetime;

	var self = this;
	this.tokener.createToken(identityStr, {
		useLimitedToken: this.options.useLimitedToken,
		useCookies: useCookies,
		isSessionLifetime: isSessionLifetime
	}, errh(function (tokenInfo) {
		if (res != null) {
			self.adapter.applyAuthData(res, tokenInfo, self.getMaxAge(isSessionLifetime), useCookies);
		}
		cb(null, {
			tokenInfo: tokenInfo,
			result: self.prepareTokenResult(tokenInfo)
		});
	}, cb));
};

AuthProvider.prototype.auth = function (req, res, options, cb) {
	var authData = this.adapter.extractAuthData(req);
	this.auth(authData, res, options, cb);
};

AuthProvider.prototype.authByData = function (authData, res, options, cb) {
	options = options || {};
	var allowUnprotected = !!options.allowUnprotected;
	// allowed values: null (auto), 'skip', 'force'
	var renewalMode = options.renewalMode || null;

	var self = this;
	var result = {
		authData: authData,
	};
	if (authData == null) {
		this.authProblem('NoAuthData', null, cb);
	}
	else if (!allowUnprotected && !authData.isCsrfProtected) {
		this.authProblem('CSRF', result, cb);
	}
	else {
		this.tokener.parseToken(authData.token, authData.additionalToken, errh(function (tokenData) {
			result.tokenData = tokenData;
			if (tokenData == null) {
				self.authProblem('InvalidToken', result, cb);
			}
			else if (!self.isValidIssued(tokenData)) {
				self.authProblem('InvalidIssued', result, cb);
			}
			else if (self.isExpired(tokenData)) {
				self.authProblem('Expired', result, cb);
			}
			else if (!self.isExpectedIdentity(tokenData, authData)) {
				self.authProblem('UnexpectedIdentity', result, cb);
			}
			else {
				self.checkRevoked(tokenData, errh(function (isRevoked) {
					if (isRevoked) {
						self.authProblem('Revoked', result, cb);
					}
					else if (renewalMode == 'force' || renewalMode != 'skip' && self.needRenew(tokenData)) {
						self.renew(res, tokenData, errh(function (renewalInfo) {
							result.renewalTokenInfo = renewalInfo.renewalTokenInfo;
							result.renewal = renewalInfo.renewal;
							cb(null, result);
						}, cb));
					}
					else {
						cb(null, result);
					}
				}, cb));
			}
		}, cb));
	}
};

AuthProvider.prototype.renew = function (res, tokenData, cb) {
	var self = this;
	this.tokener.renewToken(tokenData, self.options.useLimitedToken, errh(function (renewalTokenInfo) {
		if (res != null) {
			self.adapter.applyRenewal(res, renewalTokenInfo, self.getMaxAge(tokenData.isSessionLifetime), tokenData.useCookies);
		}
		cb(null, {
			renewalTokenInfo: renewalTokenInfo,
			renewal: self.prepareTokenResult(renewalTokenInfo, tokenData.isSessionLifetime)
		});
	}, cb));
};

AuthProvider.prototype.needRenew = function (tokenData) {
	// tokenData: as encoded to token by tokener
	return tokenData.issued + this.options.renewalInterval < Date.now();
};

AuthProvider.prototype.clearCookies = function (res) {
	this.adapter.clearCookies(res);
};

AuthProvider.prototype.isAuthProblem = function (err) {
	return err instanceof AuthProblem;
};

// internal

AuthProvider.prototype.authProblem = function (code, data, cb) {
	cb(new AuthProblem(code, data));
};

AuthProvider.prototype.prepareTokenResult = function (tokenInfo, opt_isSessionLifetime) {
	// tokenInfo: token, limitedToken, issued
	var isLimited = (tokenInfo.limitedToken != null);
	var result = {
		issued: tokenInfo.issued,
		token: isLimited ? tokenInfo.limitedToken : tokenInfo.token,
	};
	result.maxAge = this.getMaxAge();
	if (isLimited) {
		result.isLimited = true;
	}
	return result;
};

AuthProvider.prototype.getMaxAge = function (opt_isSessionLifetime) {
	return opt_isSessionLifetime ? null : this.options.maxAge;
};

AuthProvider.prototype.isValidIssued = function (tokenData) {
	return this.tokener.isValidIssued(tokenData.issued, this.options.allowedIssuedClockDeviation);
};

AuthProvider.prototype.isExpired = function (tokenData) {
	return this.tokener.isExpired(tokenData.issued, this.options.maxAge);
};

AuthProvider.prototype.isExpectedIdentity = function (tokenData, authData) {
	var result;
	if (authData.expectedIdentityStr == null) {
		result = true;
	}
	else {
		result = (tokenData.identityStr == authData.expectedIdentityStr);
	}
	return result;
};

AuthProvider.prototype.checkRevoked = function (tokenData, cb) {
	if (this.revoker != null) {
		this.revoker.checkRevoked(tokenData, cb);
	}
	else {
		cb(null, false);
	}
};

module.exports = AuthProvider;
<commit_msg>AuthProvider.prototype.prepareAuthResult introduced<commit_after>"use strict";
var errh = require('ncbt').errh;
var ops = require('ops');
var AuthProblem = require('./auth_problem');

var AuthProvider = function (opt_options) {
	this.options = this.createOptions(opt_options);

	this.tokener = null;
	this.adapter = null;
	this.revoker = null;
};

AuthProvider.prototype.createOptions = function (opt_options) {
	return ops.cloneWithDefaults(opt_options, this.getDefaultOptions());
};

AuthProvider.prototype.getDefaultOptions = function () {
	var authMaxAge = 60 * 60 * 24 * 7 * 2 * 1000; // 2 weeks in ms
	return {
		maxAge: authMaxAge,
		useLimitedToken: true, // use limited token cookie CSRF protection (see README for details)
		renewalInterval: Math.round(authMaxAge / 2),

		allowedIssuedClockDeviation: 5 * 60 * 1000, // 5 minites in ms
	};
};

AuthProvider.prototype.setTokener = function (tokener) {
	this.tokener = tokener;
};

AuthProvider.prototype.setAdapter = function (adapter) {
	this.adapter = adapter;
};

AuthProvider.prototype.setRevoker = function (revoker) {
	this.revoker = revoker;
};

AuthProvider.prototype.login = function (res, identityStr, options, cb) {
	options = options || {};
	var useCookies = !!options.useCookies;
	var isSessionLifetime = !!options.isSessionLifetime;

	var self = this;
	this.tokener.createToken(identityStr, {
		useLimitedToken: this.options.useLimitedToken,
		useCookies: useCookies,
		isSessionLifetime: isSessionLifetime
	}, errh(function (tokenInfo) {
		if (res != null) {
			self.adapter.applyAuthData(res, tokenInfo, self.getMaxAge(isSessionLifetime), useCookies);
		}
		cb(null, {
			tokenInfo: tokenInfo,
			result: self.prepareTokenResult(tokenInfo)
		});
	}, cb));
};

AuthProvider.prototype.auth = function (req, res, options, cb) {
	var authData = this.adapter.extractAuthData(req);
	this.auth(authData, res, options, cb);
};

AuthProvider.prototype.authByData = function (authData, res, options, cb) {
	options = options || {};
	var allowUnprotected = !!options.allowUnprotected;
	// allowed values: null (auto), 'skip', 'force'
	var renewalMode = options.renewalMode || null;

	var self = this;
	var result = {
		authData: authData,
	};
	if (authData == null) {
		this.authProblem('NoAuthData', null, cb);
	}
	else if (!allowUnprotected && !authData.isCsrfProtected) {
		this.authProblem('CSRF', result, cb);
	}
	else {
		this.tokener.parseToken(authData.token, authData.additionalToken, errh(function (tokenData) {
			result.tokenData = tokenData;
			if (tokenData == null) {
				self.authProblem('InvalidToken', result, cb);
			}
			else if (!self.isValidIssued(tokenData)) {
				self.authProblem('InvalidIssued', result, cb);
			}
			else if (self.isExpired(tokenData)) {
				self.authProblem('Expired', result, cb);
			}
			else if (!self.isExpectedIdentity(tokenData, authData)) {
				self.authProblem('UnexpectedIdentity', result, cb);
			}
			else {
				self.checkRevoked(tokenData, errh(function (isRevoked) {
					if (isRevoked) {
						self.authProblem('Revoked', result, cb);
					}
					else if (renewalMode == 'force' || renewalMode != 'skip' && self.needRenew(tokenData)) {
						self.renew(res, tokenData, errh(function (renewalInfo) {
							result.renewalTokenInfo = renewalInfo.renewalTokenInfo;
							result.renewal = renewalInfo.renewal;
							self.prepareAuthResult(res, options, result, cb);
						}, cb));
					}
					else {
						self.prepareAuthResult(res, options, result, cb);
					}
				}, cb));
			}
		}, cb));
	}
};

AuthProvider.prototype.renew = function (res, tokenData, cb) {
	var self = this;
	this.tokener.renewToken(tokenData, self.options.useLimitedToken, errh(function (renewalTokenInfo) {
		if (res != null) {
			self.adapter.applyRenewal(res, renewalTokenInfo, self.getMaxAge(tokenData.isSessionLifetime), tokenData.useCookies);
		}
		cb(null, {
			renewalTokenInfo: renewalTokenInfo,
			renewal: self.prepareTokenResult(renewalTokenInfo, tokenData.isSessionLifetime)
		});
	}, cb));
};

AuthProvider.prototype.needRenew = function (tokenData) {
	// tokenData: as encoded to token by tokener
	return tokenData.issued + this.options.renewalInterval < Date.now();
};

AuthProvider.prototype.clearCookies = function (res) {
	this.adapter.clearCookies(res);
};

AuthProvider.prototype.isAuthProblem = function (err) {
	return err instanceof AuthProblem;
};

AuthProvider.prototype.prepareAuthResult = function (res, options, result, cb) {
	cb(null, result);
};

// internal

AuthProvider.prototype.authProblem = function (code, result, cb) {
	cb(new AuthProblem(code, result));
};

AuthProvider.prototype.prepareTokenResult = function (tokenInfo, opt_isSessionLifetime) {
	// tokenInfo: token, limitedToken, issued
	var isLimited = (tokenInfo.limitedToken != null);
	var result = {
		issued: tokenInfo.issued,
		token: isLimited ? tokenInfo.limitedToken : tokenInfo.token,
	};
	result.maxAge = this.getMaxAge();
	if (isLimited) {
		result.isLimited = true;
	}
	return result;
};

AuthProvider.prototype.getMaxAge = function (opt_isSessionLifetime) {
	return opt_isSessionLifetime ? null : this.options.maxAge;
};

AuthProvider.prototype.isValidIssued = function (tokenData) {
	return this.tokener.isValidIssued(tokenData.issued, this.options.allowedIssuedClockDeviation);
};

AuthProvider.prototype.isExpired = function (tokenData) {
	return this.tokener.isExpired(tokenData.issued, this.options.maxAge);
};

AuthProvider.prototype.isExpectedIdentity = function (tokenData, authData) {
	var result;
	if (authData.expectedIdentityStr == null) {
		result = true;
	}
	else {
		result = (tokenData.identityStr == authData.expectedIdentityStr);
	}
	return result;
};

AuthProvider.prototype.checkRevoked = function (tokenData, cb) {
	if (this.revoker != null) {
		this.revoker.checkRevoked(tokenData, cb);
	}
	else {
		cb(null, false);
	}
};

module.exports = AuthProvider;
<|endoftext|>


<commit_before>var babel = require("babel-core");
var assign = require('object.assign');

var mapPlugin = {
	'commonjs': 'babel-plugin-transform-es2015-modules-commonjs',
	'amd': 'babel-plugin-transform-es2015-modules-amd'
};

module.exports = function(source, compileOptions, options){
	var opts = assign({}, options.babelOptions, {
		sourceMap: compileOptions.sourceMaps || false
	});

	opts.presets = opts.presets || [
		require("babel-preset-es2015-no-commonjs"),
		require("babel-preset-react"),
		require("babel-preset-stage-0")
	];
	opts.plugins = opts.plugins || [];
	opts.plugins.push(mapPlugin[compileOptions.modules]);

	if(opts.sourceMap) {
		opts.sourceMapTarget = options.sourceMapFileName;
		opts.sourceFileName = options.sourceMapFileName;
	}

	var result = babel.transform(source, opts);
	return result;
};
<commit_msg>Directly require babel plugin<commit_after>var babel = require("babel-core");
var assign = require('object.assign');

var mapPlugin = {
	'commonjs': 'babel-plugin-transform-es2015-modules-commonjs',
	'amd': 'babel-plugin-transform-es2015-modules-amd'
};

module.exports = function(source, compileOptions, options){
	var opts = assign({}, options.babelOptions, {
		sourceMap: compileOptions.sourceMaps || false
	});

	opts.presets = opts.presets || [
		require("babel-preset-es2015-no-commonjs"),
		require("babel-preset-react"),
		require("babel-preset-stage-0")
	];
	opts.plugins = opts.plugins || [];
	opts.plugins.push(require(mapPlugin[compileOptions.modules]));

	if(opts.sourceMap) {
		opts.sourceMapTarget = options.sourceMapFileName;
		opts.sourceFileName = options.sourceMapFileName;
	}

	var result = babel.transform(source, opts);
	return result;
};
<|endoftext|>


<commit_before>// Batch Request

var _ = require('lodash'),
    check = require('validator').check,
    methods = require('methods'),
    Promise = require('bluebird'),
    request = require('request'),
    url = require('url');

var batchRequest = function(params) {

    // Set default option values
    params = params || {};
    params.localOnly = (typeof params.localOnly === 'undefined') ? true : params.localOnly;
    params.httpsAlways = (typeof params.localOnly === 'undefined') ? false : params.localOnly;
    params.max = (typeof params.max === 'undefined') ? 20 : params.max;
    params.validateRespond = (typeof params.validateRespond === 'undefined') ? true : params.validateRespond;

    var batch = function(req, res, next) {
        // Here we assume it the request has already been validated, either by
        // our included middleware or otherwise by the app developer.

        // We also assume it has been run through some middleware like
        // express.bodyParser() or express.json() to parse the request.

        var requests = req.body;
        var requestPromises = [];

        // First suss out dependencies

        // Temporarily ignoring dependencies
        _.each(requests, function(r, key) {
            // push a Promise for each request
            requestPromises.push(new Promise(function(resolve, reject) {
                request(r, function(error, response, body) {
                    var resp = {};
                    resp.key = key;
                    resp.data = response;
                    resolve(resp);
                });
            }));
        });

        // Wait for all to complete before responding
        Promise.all(requestPromises).then(function(results) {
            var result = {};
            results.forEach(function(item) {
                result[item.key] = item.data;
            });
            res.json(result);
            next();
        });
    };

    batch.validate = function(req, res, next) {
        var err = null;
        var requests = req.body;

        // Validation on Request object as a whole
        try {
            check(_.size(requests), 'Cannot make a batch request with an empty request object').min(1);
            check(_.size(requests), 'Over the max request limit. Please limit batches to ' + params.max + ' requests').max(params.max);
            if (req.method === 'POST' && !req.is('json')) {
                throw new Error('Batch Request will only accept body as json');
            }
        } catch (e) {
            err = {
                error: {
                    'message': e.message,
                    'type': 'ValidationError'
                }
            };
        }

        // Validation on each request object
        _.each(requests, function(r, key) {

            // If no method provided, default to GET
            r.method = (typeof r.method === 'string') ? r.method.toLowerCase() : 'get';

            // Accept either uri or url (this is what request does, we just mirror)
            r.url = r.url || r.uri;

            try {
                check(r.url, 'Invalid URL').isUrl();
                check(r.method, 'Invalid method').isIn(methods);
            } catch (e) {
                err = {
                    error: {
                        'message': e.message,
                        'request': key,
                        'type': 'ValidationError'
                    }
                };
            }

            // TODO: Convert relative paths to full paths
            // var fullURL = req.protocol + "://" + req.get('host') + req.url;

        });

        if (err !== null) {
            res.send(400, err);
            next(err);
        } else {
            next();
        }
    };

    return batch;
};

module.exports = batchRequest;
<commit_msg>Start refactor which will include dependencies<commit_after>// Batch Request

var _ = require('lodash'),
    check = require('validator').check,
    methods = require('methods'),
    Promise = require('bluebird'),
    request = require('request'),
    url = require('url');

var batchRequest = function(params) {

    // Set default option values
    params = params || {};
    params.localOnly = (typeof params.localOnly === 'undefined') ? true : params.localOnly;
    params.httpsAlways = (typeof params.localOnly === 'undefined') ? false : params.localOnly;
    params.max = (typeof params.max === 'undefined') ? 20 : params.max;
    params.validateRespond = (typeof params.validateRespond === 'undefined') ? true : params.validateRespond;

    var batch = function(req, res, next) {
        // Here we assume it the request has already been validated, either by
        // our included middleware or otherwise by the app developer.

        // We also assume it has been run through some middleware like
        // express.bodyParser() or express.json() to parse the request.

        // We want a deep clone here as we're going to destroy this object.
        var requests = _.cloneDeep(req.body);

        // First, let's fire off all calls without any dependencies, accumulate their promises
        var requestPromises = _.reduce(requests, function(promises, r, key) {
            if (!r.dependency || r.dependency === 'none') {
                promises[key] = new Promise(function(resolve, reject) {
                    request(r, function(error, response, body) {
                        var resp = {};
                        resp.key = key;
                        resp.data = response;
                        resolve(resp);
                    });
                });
            }
            return promises;
        }, {});

        // And while we do that, build the dependency object with those items as keys
        // { key: Promise }

        // Then recursively iterate over all items with dependencies, resolving some at each pass

        // Then flatten out the chain with Promise.all(_.values(promises)).then( ... );

        // Temporarily ignoring dependencies

        // Wait for all to complete before responding
        Promise.all(_.values(requestPromises)).then(function(results) {
            var result = {};
            results.forEach(function(item) {
                result[item.key] = item.data;
            });
            res.json(result);
            next();
        });
    };

    batch.validate = function(req, res, next) {
        var err = null;
        var requests = req.body;

        // Validation on Request object as a whole
        try {
            check(_.size(requests), 'Cannot make a batch request with an empty request object').min(1);
            check(_.size(requests), 'Over the max request limit. Please limit batches to ' + params.max + ' requests').max(params.max);
            if (req.method === 'POST' && !req.is('json')) {
                throw new Error('Batch Request will only accept body as json');
            }
        } catch (e) {
            err = {
                error: {
                    'message': e.message,
                    'type': 'ValidationError'
                }
            };
        }

        // Validation on each request object
        _.each(requests, function(r, key) {

            // If no method provided, default to GET
            r.method = (typeof r.method === 'string') ? r.method.toLowerCase() : 'get';

            // Accept either uri or url (this is what request does, we just mirror)
            r.url = r.url || r.uri;

            try {
                check(r.url, 'Invalid URL').isUrl();
                check(r.method, 'Invalid method').isIn(methods);
            } catch (e) {
                err = {
                    error: {
                        'message': e.message,
                        'request': key,
                        'type': 'ValidationError'
                    }
                };
            }

            // TODO: Convert relative paths to full paths
            // var fullURL = req.protocol + "://" + req.get('host') + req.url;

        });

        if (err !== null) {
            res.send(400, err);
            next(err);
        } else {
            next();
        }
    };

    return batch;
};

module.exports = batchRequest;
<|endoftext|>