<commit_before>/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
  var maxLen = 0, numArr = [], index;
  for (var i = 0; i < s.length; i++) {
    index = numArr.indexOf(s[i]);
    if (index !== -1) {
      numArr = numArr.slice(index + 1, numArr.length);
    }
    numArr.push(s[i]);
    maxLen = numArr.length > maxLen ? numArr.length : maxLen;
  }
  return maxLen;
};
module.exports = lengthOfLongestSubstring;
<commit_msg>update typo<commit_after>/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
  var maxLen = 0, subArr = [], index;
  for (var i = 0; i < s.length; i++) {
    index = subArr.indexOf(s[i]);
    if (index !== -1) {
      subArr = subArr.slice(index + 1, subArr.length);
    }
    subArr.push(s[i]);
    maxLen = subArr.length > maxLen ? subArr.length : maxLen;
  }
  return maxLen;
};
module.exports = lengthOfLongestSubstring;
<|endoftext|>


<commit_before>var JSProblemState = {
  currently_open: [],
  last_open: [],
  ever_opened: []
};
var disableStateUpdates = false;

console.log('inner ready');

// hx-js handles all the hide/show stuff for us.
// Copying a few things from it below.

// Takes in an array of classes, as from a className function.
// Returns the number or name attached to the important class.
function getClassNumber(className, importantClass) {
  let allClasses = className.split(/\s+/);
  for (let i = 0; i < allClasses.length; i++) {
    if (allClasses[i].indexOf(importantClass) === 0) {
      return allClasses[i].slice(importantClass.length);
    }
  }
  return -1;
}

// Make sure all the boxes that were open last time are open now.
function putEmBack() {
  console.log('putting them back');
  // Make sure hx-js has assigned listeners. We need those.
  let waitForToggles = setInterval(function() {
    console.log('checking for listeners');
    if (window.parent.hxGlobalOptions) {
      clearInterval(waitForToggles);
      console.log('found them');
      // Just click their buttons. Only click the first one we find.
      JSProblemState.currently_open.forEach(function(n) {
        if (
          window.parent.window.$('.hx-toggletarget' + n).css('display') ===
          'none'
        ) {
          console.log('element ' + n + ' is hidden. Clicking.');
          disableStateUpdates = true;
          window.parent.window.$('.hx-togglebutton' + n)[0].click();
          disableStateUpdates = false;
        }
      });
    }
  }, 250);
}

// Keep the Problem State up to date.
window.parent.window.$('[class^="hx-togglebutton"').on('click tap', function() {
  if (disableStateUpdates) {
    console.log('state updates temporarily disabled');
  } else {
    console.log('state updates aok');
    JSProblemState.last_open = Array.from(JSProblemState.currently_open);

    let myNumber = getClassNumber(this.className, 'hx-togglebutton');

    // Every time we open a box, add it to ever_opened and currently_open.
    if (JSProblemState.currently_open.indexOf(myNumber) === -1) {
      JSProblemState.currently_open.push(myNumber);
    } else {
      JSProblemState.currently_open.splice(
        JSProblemState.currently_open.indexOf(myNumber),
        1
      );
    }

    // Every time we close a box, remove it from currently_open.
    if (JSProblemState.ever_opened.indexOf(myNumber) === -1) {
      JSProblemState.ever_opened.push(myNumber);
    }

    console.log(JSProblemState);
  }
});

// This wrapper function is necessary.
var pathway_problem = (function() {
  // REQUIRED --- DO NOT REMOVE/CHANGE!!
  var channel;

  // REQUIRED --- DO NOT REMOVE/CHANGE!!
  if (window.parent !== window) {
    channel = Channel.build({
      window: window.parent,
      origin: '*',
      scope: 'JSInput'
    });
    channel.bind('getGrade', getGrade);
    channel.bind('getState', getState);
    channel.bind('setState', setState);
  }

  // getState() and setState() are required by the problem type.
  function getState() {
    console.log('getting state');
    return JSON.stringify(JSProblemState);
  }

  function setState() {
    console.log('setting state');
    stateStr = arguments.length === 1 ? arguments[0] : arguments[1];
    JSProblemState = JSON.parse(stateStr);
    console.log(JSProblemState);
    putEmBack();
  }

  function getGrade() {
    console.log('getting grade');
    // Log the problem state.
    // This is called from the parent window's Javascript so that we can write to the official edX logs.
    parent.logThatThing(JSProblemState);
    // Return the whole problem state.
    return JSON.stringify(JSProblemState);
  }

  // REQUIRED --- DO NOT REMOVE/CHANGE!!
  return {
    getState: getState,
    setState: setState,
    getGrade: getGrade
  };
})();
<commit_msg>Collapse orphans<commit_after>var JSProblemState = {
  currently_open: [],
  last_open: [],
  ever_opened: []
};
var disableStateUpdates = false;

console.log('inner ready');

// hx-js handles all the hide/show stuff for us.
// Copying a few things from it below.

// Takes in an array of classes, as from a className function.
// Returns the number or name attached to the important class.
function getClassLabel(className, importantClass) {
  let allClasses = className.split(/\s+/);
  for (let i = 0; i < allClasses.length; i++) {
    if (allClasses[i].indexOf(importantClass) === 0) {
      return allClasses[i].slice(importantClass.length);
    }
  }
  return -1;
}

// Make sure all the boxes that were open last time are open now.
function putEmBack() {
  console.log('putting them back');
  // Make sure hx-js has assigned listeners. We need those.
  let waitForToggles = setInterval(function() {
    console.log('checking for listeners');
    if (window.parent.hxGlobalOptions) {
      clearInterval(waitForToggles);
      console.log('found them');
      // Just click their buttons. Only click the first one we find.
      JSProblemState.currently_open.forEach(function(n) {
        if (
          window.parent.window.$('.hx-toggletarget' + n).css('display') ===
          'none'
        ) {
          console.log('element ' + n + ' is hidden. Clicking.');
          disableStateUpdates = true;
          window.parent.window.$('.hx-togglebutton' + n)[0].click();
          disableStateUpdates = false;
        }
      });
    }
  }, 250);
}

// Keep the Problem State up to date.
window.parent.window.$('[class^="hx-togglebutton"').on('click tap', function() {
  if (disableStateUpdates) {
    console.log('state updates temporarily disabled');
  } else {
    console.log('state updates aok');
    JSProblemState.last_open = Array.from(JSProblemState.currently_open);

    let myLabel = getClassLabel(this.className, 'hx-togglebutton');

    // Every time we open a box, add it to currently_open.
    if (JSProblemState.currently_open.indexOf(myLabel) === -1) {
      JSProblemState.currently_open.push(myLabel);
    } else {
      // Every time we close a box, remove it from currently_open.
      JSProblemState.currently_open.splice(
        JSProblemState.currently_open.indexOf(myLabel),
        1
      );
      // If we close a box that would leave orphan boxes, close those too.
      window.parent.window
        .$('.hx-toggletarget' + myLabel)
        .find('button')
        .each(function(i, b) {
          if (b.attributes['aria-expanded'].value === 'true') {
            b.click();
          }
        });
    }

    // Every time we open a box, add it to ever_opened.
    if (JSProblemState.ever_opened.indexOf(myLabel) === -1) {
      JSProblemState.ever_opened.push(myLabel);
    }

    console.log(JSProblemState);
  }
});

// This wrapper function is necessary.
var pathway_problem = (function() {
  // REQUIRED --- DO NOT REMOVE/CHANGE!!
  var channel;

  // REQUIRED --- DO NOT REMOVE/CHANGE!!
  if (window.parent !== window) {
    channel = Channel.build({
      window: window.parent,
      origin: '*',
      scope: 'JSInput'
    });
    channel.bind('getGrade', getGrade);
    channel.bind('getState', getState);
    channel.bind('setState', setState);
  }

  // getState() and setState() are required by the problem type.
  function getState() {
    console.log('getting state');
    return JSON.stringify(JSProblemState);
  }

  function setState() {
    console.log('setting state');
    stateStr = arguments.length === 1 ? arguments[0] : arguments[1];
    JSProblemState = JSON.parse(stateStr);
    console.log(JSProblemState);
    putEmBack();
  }

  function getGrade() {
    console.log('getting grade');
    // Log the problem state.
    // This is called from the parent window's Javascript so that we can write to the official edX logs.
    parent.logThatThing(JSProblemState);
    // Return the whole problem state.
    return JSON.stringify(JSProblemState);
  }

  // REQUIRED --- DO NOT REMOVE/CHANGE!!
  return {
    getState: getState,
    setState: setState,
    getGrade: getGrade
  };
})();
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

<include src="util.js"/>
<include src="view.js"/>
<include src="tab_switcher_view.js"/>
<include src="data_view.js"/>
<include src="http_cache_view.js"/>
<include src="test_view.js"/>
<include src="hsts_view.js"/>
<include src="browser_bridge.js"/>
<include src="source_tracker.js"/>
<include src="main.js"/>
<include src="dns_view.js"/>
<include src="source_row.js"/>
<include src="events_view.js"/>
<include src="details_view.js"/>
<include src="source_entry.js"/>
<include src="resizable_vertical_split_view.js"/>
<include src="top_mid_bottom_view.js"/>
<include src="timeline_view_painter.js"/>
<include src="log_view_painter.js"/>
<include src="log_grouper.js"/>
<include src="proxy_view.js"/>
<include src="socket_pool_wrapper.js"/>
<include src="sockets_view.js"/>
<include src="spdy_view.js"/>
<include src="service_providers_view.js"/>
<include src="http_throttling_view.js"/>
<include src="logs_view.js"/>
<include src="prerender_view.js"/>

document.addEventListener('DOMContentLoaded', function () {
  $('reloaded-link').addEventListener('click', function () {
    history.go(0);
  });
  onLoaded();  // from main.js
});
<commit_msg>Fix the "reloaded" link on about:net-internals.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

<include src="util.js"/>
<include src="view.js"/>
<include src="tab_switcher_view.js"/>
<include src="data_view.js"/>
<include src="http_cache_view.js"/>
<include src="test_view.js"/>
<include src="hsts_view.js"/>
<include src="browser_bridge.js"/>
<include src="source_tracker.js"/>
<include src="main.js"/>
<include src="dns_view.js"/>
<include src="source_row.js"/>
<include src="events_view.js"/>
<include src="details_view.js"/>
<include src="source_entry.js"/>
<include src="resizable_vertical_split_view.js"/>
<include src="top_mid_bottom_view.js"/>
<include src="timeline_view_painter.js"/>
<include src="log_view_painter.js"/>
<include src="log_grouper.js"/>
<include src="proxy_view.js"/>
<include src="socket_pool_wrapper.js"/>
<include src="sockets_view.js"/>
<include src="spdy_view.js"/>
<include src="service_providers_view.js"/>
<include src="http_throttling_view.js"/>
<include src="logs_view.js"/>
<include src="prerender_view.js"/>

document.addEventListener('DOMContentLoaded', function () {
  $('reloaded-link').addEventListener('click', function (event) {
    history.go(0);
    event.preventDefault();
  });
  onLoaded();  // from main.js
});
<|endoftext|>


<commit_before>'use strict';

// Committees controller
angular.module('committees').controller('CommitteeCtrl', ['$scope', '$stateParams', '$location', 'Authentication', 'Users', 'Committees', '$q', '$log',
	function($scope, $stateParams, $location, Authentication, Users, Committees, $q, $log) {

		/* Committee Link Permissions */
		if($scope.role.admin)
			$scope.committeeTemplates.edit = true;

		$scope.committeeTemplates.attendance = true;
		$scope.committeeTemplates.schedule = true;
		$scope.committeeTemplates.resources = true;

		/* Committee Data to be Loaded on Page Load */
		$scope.findCommittee().then(function() {
			$scope.getChair();
			$scope.getMembers();
		});

		/* Committee Functions */
		// Create new Committee
		$scope.create = function($scope) {
			// Create new Committee object
			var committee = new Committees.Committees ({
				name: this.committee.name,
				chair: this.chair.id
			});

			// Redirect after save
			committee.$save(function(response) {
				$location.path('committees/' + response._id);

				// Clear form fields
				this.committee.name = '';
				this.chair.id = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			//Clear form fields
			this.committee.name = '';
			this.chair.id = '';

		};

		// Remove existing Committee
		$scope.remove = function( committee ) {
			if ( committee ) { committee.$remove();

				for (var i in $scope.committees ) {
					if ($scope.committees [i] === committee ) {
						$scope.committees.splice(i, 1);
					}
				}
			} else {
				$scope.committee.$remove(function() {
					$location.path('committees');
				});
			}
		};

		// Update existing Committee
		$scope.update = function() {
			var committee = $scope.committee ;

			committee.$update(function() {
				$location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		//Add member to committee
		$scope.addMember = function(user){
			var committee = $scope.committee;
			var passed = 1;
			angular.forEach(committee.members, function(members){
				if(members === user._id) passed = 0;
			});
			if(passed){
				Committees.Member.update({userId: user._id,committeeId: committee._id},function(){
					$location.path('committees/' + committee._id+'/edit');
				});
			}
		};

		$scope.removeMember = function(member){
			var committee = $scope.committee;
			var passed = 0;
			angular.forEach(committee.members, function(members){
				if(members === member._id) passed = 1;
			});
			if(passed) Committees.Member.remove({userId: member._id,committeeId: committee._id},function(){
					$location.path('committees/' + committee._id+'/edit');
			});
		};

		$scope.getMembers = function(){
			var committee = $scope.committee;
			var Members = Committees.Members.query({committeeId: committee._id}).$promise.then(function(data) {
				// $log.debug(data);
				$scope.members = data;
			});
		};

		$scope.getMeetings = function(){
			var committee = $scope.committee;
			var Meetings = Committees.Meetings.query({committeeId: committee._id}).$promise.then(function(data) {
				console.log(data);
				$scope.meetings = data;
			});
		};

		$scope.addSchedule = function(schedule){
			var committee = $scope.committee;
			var scheduleById = schedule._id;
			console.log('committee: '+committee._id);
			console.log('committee: '+scheduleById);
			$scope.committee.schedules.push(schedule._id);
			$scope.committee.$update(function() {
				// $location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.addMeeting = function(meeting){
			var committee = $scope.committee;
			var meetingById = meeting._id;
			var Meetings = Committees.Meetings.put({committeeId: committee._id, meetingId: meetingById}).$promise.then(function(data) {
				console.log(data);
				$scope.meetings = data;
			});
		};
		$scope.removeMeeting = function(meeting){
			var committee = $scope.committee;
			var meetingById = meeting._id;
			var Meetings = Committees.Meetings.delete({committeeId: committee._id, meetingId: meetingById}).$promise.then(function(data) {
				console.log(data);
				$scope.meetings = data;
			});
		};

		$scope.setChair = function(userId){
			var committee = $scope.committee;
			Committees.Chair.update({committeeId: committee._id, chairId: userId}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;
			});
		};

		$scope.removeChair = function(){
			var committee = $scope.committee;
			Committees.Chair.delete({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				console.log(data.displayName);
				$scope.committee = data;

			});
		};

		$scope.getChair = function(){
			var committee = $scope.committee;
			Committees.Chair.get({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				$log.debug($scope.committee.name + ' Chair: ' + data.displayName);
				$scope.chair = data;
			});
		};

		/* Attendance Checking */
		$scope.membersPresent = 0;

		$scope.checkMembersPresent = function(isChecked){
			// $log.debug('Committee Members:');
			// $log.debug($scope.members);

			// $log.debug('isChecked:');
			// $log.debug(isChecked);

			if(isChecked === true){
				$scope.membersPresent++;
			}

			if(isChecked === false){
				$scope.membersPresent--;
			}
		};

		/* Committee Function Calls */

		/* Clean Up on Exit */
		$scope.$on("$destroy", function() {
			$scope.committeeTemplates.edit = false;
			$scope.committeeTemplates.attendance = false;
			$scope.committeeTemplates.schedule = false;
			$scope.committeeTemplates.resources = false;
		});

	}
]);<commit_msg>Fixed destroy line in committee.controller from double quotes to singlue quotes.<commit_after>'use strict';

// Committees controller
angular.module('committees').controller('CommitteeCtrl', ['$scope', '$stateParams', '$location', 'Authentication', 'Users', 'Committees', '$q', '$log',
	function($scope, $stateParams, $location, Authentication, Users, Committees, $q, $log) {

		/* Committee Link Permissions */
		if($scope.role.admin)
			$scope.committeeTemplates.edit = true;

		$scope.committeeTemplates.attendance = true;
		$scope.committeeTemplates.schedule = true;
		$scope.committeeTemplates.resources = true;

		/* Committee Data to be Loaded on Page Load */
		$scope.findCommittee().then(function() {
			$scope.getChair();
			$scope.getMembers();
		});

		/* Committee Functions */
		// Create new Committee
		$scope.create = function($scope) {
			// Create new Committee object
			var committee = new Committees.Committees ({
				name: this.committee.name,
				chair: this.chair.id
			});

			// Redirect after save
			committee.$save(function(response) {
				$location.path('committees/' + response._id);

				// Clear form fields
				this.committee.name = '';
				this.chair.id = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

			//Clear form fields
			this.committee.name = '';
			this.chair.id = '';

		};

		// Remove existing Committee
		$scope.remove = function( committee ) {
			if ( committee ) { committee.$remove();

				for (var i in $scope.committees ) {
					if ($scope.committees [i] === committee ) {
						$scope.committees.splice(i, 1);
					}
				}
			} else {
				$scope.committee.$remove(function() {
					$location.path('committees');
				});
			}
		};

		// Update existing Committee
		$scope.update = function() {
			var committee = $scope.committee ;

			committee.$update(function() {
				$location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		//Add member to committee
		$scope.addMember = function(user){
			var committee = $scope.committee;
			var passed = 1;
			angular.forEach(committee.members, function(members){
				if(members === user._id) passed = 0;
			});
			if(passed){
				Committees.Member.update({userId: user._id,committeeId: committee._id},function(){
					$location.path('committees/' + committee._id+'/edit');
				});
			}
		};

		$scope.removeMember = function(member){
			var committee = $scope.committee;
			var passed = 0;
			angular.forEach(committee.members, function(members){
				if(members === member._id) passed = 1;
			});
			if(passed) Committees.Member.remove({userId: member._id,committeeId: committee._id},function(){
					$location.path('committees/' + committee._id+'/edit');
			});
		};

		$scope.getMembers = function(){
			var committee = $scope.committee;
			var Members = Committees.Members.query({committeeId: committee._id}).$promise.then(function(data) {
				// $log.debug(data);
				$scope.members = data;
			});
		};

		$scope.getMeetings = function(){
			var committee = $scope.committee;
			var Meetings = Committees.Meetings.query({committeeId: committee._id}).$promise.then(function(data) {
				console.log(data);
				$scope.meetings = data;
			});
		};

		$scope.addSchedule = function(schedule){
			var committee = $scope.committee;
			var scheduleById = schedule._id;
			console.log('committee: '+committee._id);
			console.log('committee: '+scheduleById);
			$scope.committee.schedules.push(schedule._id);
			$scope.committee.$update(function() {
				// $location.path('committees/' + committee._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		$scope.addMeeting = function(meeting){
			var committee = $scope.committee;
			var meetingById = meeting._id;
			var Meetings = Committees.Meetings.put({committeeId: committee._id, meetingId: meetingById}).$promise.then(function(data) {
				console.log(data);
				$scope.meetings = data;
			});
		};
		$scope.removeMeeting = function(meeting){
			var committee = $scope.committee;
			var meetingById = meeting._id;
			var Meetings = Committees.Meetings.delete({committeeId: committee._id, meetingId: meetingById}).$promise.then(function(data) {
				console.log(data);
				$scope.meetings = data;
			});
		};

		$scope.setChair = function(userId){
			var committee = $scope.committee;
			Committees.Chair.update({committeeId: committee._id, chairId: userId}).$promise.then(function(data) {
				console.log(data);
				$scope.committee = data;
			});
		};

		$scope.removeChair = function(){
			var committee = $scope.committee;
			Committees.Chair.delete({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				console.log(data.displayName);
				$scope.committee = data;

			});
		};

		$scope.getChair = function(){
			var committee = $scope.committee;
			Committees.Chair.get({committeeId: committee._id, chairId: committee.chair}).$promise.then(function(data) {
				$log.debug($scope.committee.name + ' Chair: ' + data.displayName);
				$scope.chair = data;
			});
		};

		/* Attendance Checking */
		$scope.membersPresent = 0;

		$scope.checkMembersPresent = function(isChecked){
			// $log.debug('Committee Members:');
			// $log.debug($scope.members);

			// $log.debug('isChecked:');
			// $log.debug(isChecked);

			if(isChecked === true){
				$scope.membersPresent++;
			}

			if(isChecked === false){
				$scope.membersPresent--;
			}
		};

		/* Committee Function Calls */

		/* Clean Up on Exit */
		$scope.$on('$destroy', function() {
			$scope.committeeTemplates.edit = false;
			$scope.committeeTemplates.attendance = false;
			$scope.committeeTemplates.schedule = false;
			$scope.committeeTemplates.resources = false;
		});

	}
]);<|endoftext|>


<commit_before>'use strict';

angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
	function($scope, $http, $location, Authentication) {
  $scope.authentication = Authentication;

  // If user is signed in then redirect back home
  if ($scope.authentication.user) $location.path('/');

  $scope.signup = function() {
    $http.post('/auth/signup', $scope.credentials).success(function(response) {
      // If successful we assign the response to the global user model
      $scope.authentication.user = response;

      // And redirect to the index page
      $location.path('/');
    }).error(function(response) {
      $scope.error = response.message;
    });
  };

  $scope.signin = function() {
    $http.post('/auth/signin', $scope.credentials).success(function(response) {
      // If successful we assign the response to the global user model
      $scope.authentication.user = response;

      // And redirect to the index page
      $location.path('/');
    }).error(function(response) {
      $scope.error = response.message;
    });
  };
	}
]);
<commit_msg>untabifies<commit_after>'use strict';

angular.module('users').controller('AuthenticationController', ['$scope', '$http', '$location', 'Authentication',
  function($scope, $http, $location, Authentication) {
  $scope.authentication = Authentication;

  // If user is signed in then redirect back home
  if ($scope.authentication.user) $location.path('/');

  $scope.signup = function() {
    $http.post('/auth/signup', $scope.credentials).success(function(response) {
      // If successful we assign the response to the global user model
      $scope.authentication.user = response;

      // And redirect to the index page
      $location.path('/');
    }).error(function(response) {
      $scope.error = response.message;
    });
  };

  $scope.signin = function() {
    $http.post('/auth/signin', $scope.credentials).success(function(response) {
      // If successful we assign the response to the global user model
      $scope.authentication.user = response;

      // And redirect to the index page
      $location.path('/');
    }).error(function(response) {
      $scope.error = response.message;
    });
  };
  }
]);
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('app.states')
    .run(appRun);

  /** @ngInject */
  function appRun(routerHelper) {
    routerHelper.configureStates(getStates());
  }

  function getStates() {
    return {
      'blueprints.list': {
        url: '', // No url, this state is the index of projects
        templateUrl: 'app/states/blueprints/list/list.html',
        controller: StateController,
        controllerAs: 'vm',
        title: N_('Blueprint List'),
        resolve: {
          blueprints: resolveBlueprints,
          serviceCatalogs: resolveServiceCatalogs
        }
      }
    };
  }

  /** @ngInject */
  function resolveBlueprints(CollectionsApi) {
    var options = {
      mock: true,
      expand: 'resources'
    };

    return CollectionsApi.query('blueprints', options);
  }

  function resolveServiceCatalogs(CollectionsApi) {
    var options = {
      expand: 'resources',
      sort_by: 'name',
      sort_options: 'ignore_case'};

    return CollectionsApi.query('service_catalogs', options);
  }

  /** @ngInject */
  function StateController($state, blueprints, BlueprintsState, serviceCatalogs, BlueprintDetailsModal, BlueprintDeleteModal, Notifications,
                           $rootScope, Language) {
    /* jshint validthis: true */
    var vm = this;
    var categoryNames = [];
    var visibilityNames = ['Private', 'Public'];

    vm.title = __('Blueprint List');

    // For mock RESTFul api operations
    if (!BlueprintsState.getBlueprints()) {
      BlueprintsState.setBlueprints(blueprints.resources);
    }

    vm.blueprints = BlueprintsState.getBlueprints();
    vm.serviceCatalogs = serviceCatalogs.resources;

    angular.forEach(vm.blueprints, addMockFilters);
    angular.forEach(vm.serviceCatalogs, addCategoryFilter);

    function addMockFilters(blueprint) {
      if (!blueprint.catalog) {
        if (!categoryNames.includes(__('Unassigned'))) {
          categoryNames.push(__('Unassigned'));
        }
      } else {
        categoryNames.push(blueprint.catalog.name);
      }

      if (!visibilityNames.includes(blueprint.visibility.name)) {
        visibilityNames.push(blueprint.visibility.name);
      }
    }

    function addCategoryFilter(item) {
      categoryNames.push(item.name);
    }

    /* This notification 'splice' code doesn't work.  Splice needs a third argument, the items to splice in
     * Not sure what this code is trying to accomplish, but it exists in login, request list, & services list
    if (angular.isDefined($rootScope.notifications) && $rootScope.notifications.data.length > 0) {
      $rootScope.notifications.data.splice(0, $rootScope.notifications.data.length);
    }
    */

    vm.blueprintsList = angular.copy(vm.blueprints);

    vm.listConfig = {
      selectItems: false,
      showSelectBox: true,
      onClick: handleClick,
      onCheckBoxChange: handleCheckBoxChange
    };

    vm.actionButtons = [
      {
        name: __('Publish'),
        title: __('Publish Blueprint'),
        actionFn: publishBlueprint
      }
    ];

    vm.enableButtonForItemFn = function(action, item) {
      if (action.name === __('Publish')) {
        if (item.num_nodes > 0 && !item.published) {
          return true;
        } else {
          return false;
        }
      }
    };

    vm.menuActions = [
      {
        name: __('Edit'),
        title: __('Edit Blueprint'),
        actionFn: editBlueprint
      },
      {
        name: __('Duplicate'),
        title: __('Duplicate Blueprint'),
        actionFn: duplicateBlueprint
      },
      {
        name: __('Delete'),
        title: __('Delete Blueprint'),
        actionFn: deleteBlueprint
      }
    ];

    vm.toolbarConfig = {
      filterConfig: {
        fields: [
          {
            id: 'name',
            title: __('Name'),
            placeholder: __('Filter by Name'),
            filterType: 'text'
          },
          {
            id: 'visibility',
            title: __('Visibility'),
            placeholder: __('Filter by Visibility'),
            filterType: 'select',
            filterValues: visibilityNames
          },
          {
            id: 'catalog',
            title: __('Catalog'),
            placeholder: __('Filter by Catalog'),
            filterType: 'select',
            filterValues: categoryNames
          }
        ],
        resultsCount: vm.blueprintsList.length,
        appliedFilters: BlueprintsState.getFilters(),
        onFilterChange: filterChange
      },
      sortConfig: {
        fields: [
          {
            id: 'name',
            title: __('Name'),
            sortType: 'alpha'
          },
          {
            id: 'last_modified',
            title: __('Last Modified'),
            sortType: 'numeric'
          },
          {
            id: 'num_nodes',
            title: __('Items'),
            sortType: 'numeric'
          },
          {
            id: 'visibility',
            title: __('Visibility'),
            sortType: 'alpha'
          },
          {
            id: 'catalog',
            title: __('Catalog'),
            sortType: 'alpha'
          }
        ],
        onSortChange: sortChange,
        isAscending: BlueprintsState.getSort().isAscending,
        currentField: BlueprintsState.getSort().currentField
      },
      actionsConfig: {
        primaryActions: [
          {
            name: __('Create'),
            title: __('Create a new Blueprint'),
            actionFn: createBlueprint
          },
          {
            name: __('Delete'),
            title: __('Delete Blueprint'),
            actionFn: deleteBlueprints,
            isDisabled: (BlueprintsState.getSelectedBlueprints().length === 0)
          }
        ]
      }
    };

    function createBlueprint(action) {
      $state.go('blueprints.designer');
    }

    function editBlueprint(action, item) {
      $state.go('blueprints.designer', {blueprintId: item.id});
    }

    function duplicateBlueprint(action, item) {
      BlueprintsState.duplicateBlueprint(item);
      $state.go($state.current, {}, {reload: true});
    }

    function publishBlueprint(action, item) {
      if (item.num_nodes === 0) {
        Notifications.error(__('Cannot publish a blueprint with no service items.'), false, false);

        // Make sure all notifications disappear after delay
        if (angular.isDefined($rootScope.notifications) && $rootScope.notifications.data.length > 0) {
          for (var i = 0; i < $rootScope.notifications.data.length; i++) {
            $rootScope.notifications.data[i].isPersistent = false;
          }
        }
      } else {
        BlueprintDetailsModal.showModal('publish', item);
      }
    }

    function deleteBlueprint(action, item) {
      BlueprintDeleteModal.showModal([item]);
    }

    function deleteBlueprints(action) {
      BlueprintDeleteModal.showModal(BlueprintsState.getSelectedBlueprints());
    }

    function canDeleteBlueprints() {
      return BlueprintsState.getSelectedBlueprints().length > 0;
    }

    function updateActionForItemFn(action, item) {
      return (action.name === 'Publish') && (item.published !== null);
    }

    /* Apply the filtering to the data list */
    filterChange(BlueprintsState.getFilters());

    function handleClick(item, e) {
      $state.go('blueprints.designer', {blueprintId: item.id});
    }

    function handleCheckBoxChange(item, e) {
      BlueprintsState.handleSelectionChange(item);
      vm.toolbarConfig.actionsConfig.primaryActions[1].isDisabled = !canDeleteBlueprints();
    }

    function sortChange(sortId, isAscending) {
      vm.blueprintsList.sort(compareFn);

      /* Keep track of the current sorting state */
      BlueprintsState.setSort(sortId, vm.toolbarConfig.sortConfig.isAscending);
    }

    function compareFn(item1, item2) {
      var compValue = 0;
      if (vm.toolbarConfig.sortConfig.currentField.id === 'name') {
        compValue = item1.name.localeCompare(item2.name);
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'last_modified') {
        compValue = new Date(item1.last_modified) - new Date(item2.last_modified);
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'num_nodes') {
        compValue = item1.num_nodes - item2.num_nodes;
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'visibility') {
        compValue = item1.visibility.name.localeCompare(item2.visibility.name);
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'catalog') {
        if (!item1.catalog) {
          compValue = -1;
        } else if (!item2.catalog) {
          compValue = 1;
        } else {
          compValue = item1.catalog.name.localeCompare(item2.catalog.name);
        }
      }

      if (!vm.toolbarConfig.sortConfig.isAscending) {
        compValue = compValue * -1;
      }

      return compValue;
    }

    function filterChange(filters) {
      applyFilters(filters);
      vm.toolbarConfig.filterConfig.resultsCount = vm.blueprintsList.length;
    }

    function applyFilters(filters) {
      vm.blueprintsList = [];
      if (filters && filters.length > 0) {
        angular.forEach(vm.blueprints, filterChecker);
      } else {
        vm.blueprintsList = vm.blueprints;
      }

      /* Keep track of the current filtering state */
      BlueprintsState.setFilters(filters);

      /* Make sure sorting direction is maintained */
      sortChange(BlueprintsState.getSort().currentField, BlueprintsState.getSort().isAscending);

      function filterChecker(item) {
        if (matchesFilters(item, filters)) {
          vm.blueprintsList.push(item);
        }
      }
    }

    function matchesFilters(item, filters) {
      var matches = true;
      angular.forEach(filters, filterMatcher);

      function filterMatcher(filter) {
        if (!matchesFilter(item, filter)) {
          matches = false;

          return false;
        }
      }

      return matches;
    }

    function matchesFilter(item, filter) {
      if (filter.id === 'name') {
        return item.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1;
      } else if (filter.id === 'visibility') {
        return item.visibility.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1;
      } else if (filter.id === 'catalog') {
        if (filter.value.toLowerCase() === "unassigned" && !item.catalog) {
          return true;
        } else if (!item.catalog) {
          return false;
        } else {
          return item.catalog.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1;
        }
      }

      return false;
    }

    Language.fixState(BlueprintsState, vm.toolbarConfig);
  }
})();
<commit_msg>SSUI Designer: Blueprint List - Added Publish State filter<commit_after>(function() {
  'use strict';

  angular.module('app.states')
    .run(appRun);

  /** @ngInject */
  function appRun(routerHelper) {
    routerHelper.configureStates(getStates());
  }

  function getStates() {
    return {
      'blueprints.list': {
        url: '', // No url, this state is the index of projects
        templateUrl: 'app/states/blueprints/list/list.html',
        controller: StateController,
        controllerAs: 'vm',
        title: N_('Blueprint List'),
        resolve: {
          blueprints: resolveBlueprints,
          serviceCatalogs: resolveServiceCatalogs
        }
      }
    };
  }

  /** @ngInject */
  function resolveBlueprints(CollectionsApi) {
    var options = {
      mock: true,
      expand: 'resources'
    };

    return CollectionsApi.query('blueprints', options);
  }

  function resolveServiceCatalogs(CollectionsApi) {
    var options = {
      expand: 'resources',
      sort_by: 'name',
      sort_options: 'ignore_case'};

    return CollectionsApi.query('service_catalogs', options);
  }

  /** @ngInject */
  function StateController($state, blueprints, BlueprintsState, serviceCatalogs, BlueprintDetailsModal, BlueprintDeleteModal, Notifications,
                           $rootScope, Language) {
    /* jshint validthis: true */
    var vm = this;
    var categoryNames = [];
    var visibilityNames = ['Private', 'Public'];
    var publishStateNames = ['Draft', 'Published'];

    vm.title = __('Blueprint List');

    // For mock RESTFul api operations
    if (!BlueprintsState.getBlueprints()) {
      BlueprintsState.setBlueprints(blueprints.resources);
    }

    vm.blueprints = BlueprintsState.getBlueprints();
    vm.serviceCatalogs = serviceCatalogs.resources;

    angular.forEach(vm.blueprints, addMockFilters);
    angular.forEach(vm.serviceCatalogs, addCategoryFilter);

    function addMockFilters(blueprint) {
      if (!blueprint.catalog) {
        if (!categoryNames.includes(__('Unassigned'))) {
          categoryNames.push(__('Unassigned'));
        }
      } else {
        categoryNames.push(blueprint.catalog.name);
      }

      if (!visibilityNames.includes(blueprint.visibility.name)) {
        visibilityNames.push(blueprint.visibility.name);
      }
    }

    function addCategoryFilter(item) {
      categoryNames.push(item.name);
    }

    /* This notification 'splice' code doesn't work.  Splice needs a third argument, the items to splice in
     * Not sure what this code is trying to accomplish, but it exists in login, request list, & services list
    if (angular.isDefined($rootScope.notifications) && $rootScope.notifications.data.length > 0) {
      $rootScope.notifications.data.splice(0, $rootScope.notifications.data.length);
    }
    */

    vm.blueprintsList = angular.copy(vm.blueprints);

    vm.listConfig = {
      selectItems: false,
      showSelectBox: true,
      onClick: handleClick,
      onCheckBoxChange: handleCheckBoxChange
    };

    vm.actionButtons = [
      {
        name: __('Publish'),
        title: __('Publish Blueprint'),
        actionFn: publishBlueprint
      }
    ];

    vm.enableButtonForItemFn = function(action, item) {
      if (action.name === __('Publish')) {
        if (item.num_nodes > 0 && !item.published) {
          return true;
        } else {
          return false;
        }
      }
    };

    vm.menuActions = [
      {
        name: __('Edit'),
        title: __('Edit Blueprint'),
        actionFn: editBlueprint
      },
      {
        name: __('Duplicate'),
        title: __('Duplicate Blueprint'),
        actionFn: duplicateBlueprint
      },
      {
        name: __('Delete'),
        title: __('Delete Blueprint'),
        actionFn: deleteBlueprint
      }
    ];

    vm.toolbarConfig = {
      filterConfig: {
        fields: [
          {
            id: 'name',
            title: __('Name'),
            placeholder: __('Filter by Name'),
            filterType: 'text'
          },
          {
            id: 'visibility',
            title: __('Visibility'),
            placeholder: __('Filter by Visibility'),
            filterType: 'select',
            filterValues: visibilityNames
          },
          {
            id: 'catalog',
            title: __('Catalog'),
            placeholder: __('Filter by Catalog'),
            filterType: 'select',
            filterValues: categoryNames
          },
          {
            id: 'publishState',
            title: __('Publish State'),
            placeholder: __('Filter by Publish State'),
            filterType: 'select',
            filterValues: publishStateNames
          }
        ],
        resultsCount: vm.blueprintsList.length,
        appliedFilters: BlueprintsState.getFilters(),
        onFilterChange: filterChange
      },
      sortConfig: {
        fields: [
          {
            id: 'name',
            title: __('Name'),
            sortType: 'alpha'
          },
          {
            id: 'last_modified',
            title: __('Last Modified'),
            sortType: 'numeric'
          },
          {
            id: 'num_nodes',
            title: __('Items'),
            sortType: 'numeric'
          },
          {
            id: 'visibility',
            title: __('Visibility'),
            sortType: 'alpha'
          },
          {
            id: 'catalog',
            title: __('Catalog'),
            sortType: 'alpha'
          }
        ],
        onSortChange: sortChange,
        isAscending: BlueprintsState.getSort().isAscending,
        currentField: BlueprintsState.getSort().currentField
      },
      actionsConfig: {
        primaryActions: [
          {
            name: __('Create'),
            title: __('Create a new Blueprint'),
            actionFn: createBlueprint
          },
          {
            name: __('Delete'),
            title: __('Delete Blueprint'),
            actionFn: deleteBlueprints,
            isDisabled: (BlueprintsState.getSelectedBlueprints().length === 0)
          }
        ]
      }
    };

    function createBlueprint(action) {
      $state.go('blueprints.designer');
    }

    function editBlueprint(action, item) {
      $state.go('blueprints.designer', {blueprintId: item.id});
    }

    function duplicateBlueprint(action, item) {
      BlueprintsState.duplicateBlueprint(item);
      $state.go($state.current, {}, {reload: true});
    }

    function publishBlueprint(action, item) {
      if (item.num_nodes === 0) {
        Notifications.error(__('Cannot publish a blueprint with no service items.'), false, false);

        // Make sure all notifications disappear after delay
        if (angular.isDefined($rootScope.notifications) && $rootScope.notifications.data.length > 0) {
          for (var i = 0; i < $rootScope.notifications.data.length; i++) {
            $rootScope.notifications.data[i].isPersistent = false;
          }
        }
      } else {
        BlueprintDetailsModal.showModal('publish', item);
      }
    }

    function deleteBlueprint(action, item) {
      BlueprintDeleteModal.showModal([item]);
    }

    function deleteBlueprints(action) {
      BlueprintDeleteModal.showModal(BlueprintsState.getSelectedBlueprints());
    }

    function canDeleteBlueprints() {
      return BlueprintsState.getSelectedBlueprints().length > 0;
    }

    function updateActionForItemFn(action, item) {
      return (action.name === 'Publish') && (item.published !== null);
    }

    /* Apply the filtering to the data list */
    filterChange(BlueprintsState.getFilters());

    function handleClick(item, e) {
      $state.go('blueprints.designer', {blueprintId: item.id});
    }

    function handleCheckBoxChange(item, e) {
      BlueprintsState.handleSelectionChange(item);
      vm.toolbarConfig.actionsConfig.primaryActions[1].isDisabled = !canDeleteBlueprints();
    }

    function sortChange(sortId, isAscending) {
      vm.blueprintsList.sort(compareFn);

      /* Keep track of the current sorting state */
      BlueprintsState.setSort(sortId, vm.toolbarConfig.sortConfig.isAscending);
    }

    function compareFn(item1, item2) {
      var compValue = 0;
      if (vm.toolbarConfig.sortConfig.currentField.id === 'name') {
        compValue = item1.name.localeCompare(item2.name);
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'last_modified') {
        compValue = new Date(item1.last_modified) - new Date(item2.last_modified);
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'num_nodes') {
        compValue = item1.num_nodes - item2.num_nodes;
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'visibility') {
        compValue = item1.visibility.name.localeCompare(item2.visibility.name);
      } else if (vm.toolbarConfig.sortConfig.currentField.id === 'catalog') {
        if (!item1.catalog) {
          compValue = -1;
        } else if (!item2.catalog) {
          compValue = 1;
        } else {
          compValue = item1.catalog.name.localeCompare(item2.catalog.name);
        }
      }

      if (!vm.toolbarConfig.sortConfig.isAscending) {
        compValue = compValue * -1;
      }

      return compValue;
    }

    function filterChange(filters) {
      applyFilters(filters);
      vm.toolbarConfig.filterConfig.resultsCount = vm.blueprintsList.length;
    }

    function applyFilters(filters) {
      vm.blueprintsList = [];
      if (filters && filters.length > 0) {
        angular.forEach(vm.blueprints, filterChecker);
      } else {
        vm.blueprintsList = vm.blueprints;
      }

      /* Keep track of the current filtering state */
      BlueprintsState.setFilters(filters);

      /* Make sure sorting direction is maintained */
      sortChange(BlueprintsState.getSort().currentField, BlueprintsState.getSort().isAscending);

      function filterChecker(item) {
        if (matchesFilters(item, filters)) {
          vm.blueprintsList.push(item);
        }
      }
    }

    function matchesFilters(item, filters) {
      var matches = true;
      angular.forEach(filters, filterMatcher);

      function filterMatcher(filter) {
        if (!matchesFilter(item, filter)) {
          matches = false;

          return false;
        }
      }

      return matches;
    }

    function matchesFilter(item, filter) {
      if (filter.id === 'name') {
        return item.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1;
      } else if (filter.id === 'visibility') {
        return item.visibility.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1;
      } else if (filter.id === 'catalog') {
        if (filter.value.toLowerCase() === "unassigned" && !item.catalog) {
          return true;
        } else if (!item.catalog) {
          return false;
        } else {
          return item.catalog.name.toLowerCase().indexOf(filter.value.toLowerCase()) !== -1;
        }
      } else if (filter.id === 'publishState') {
        if ( (filter.value.toLowerCase() === "published" && item.published) ||
             (filter.value.toLowerCase() === "draft" && !item.published)) {
          return true;
        } else {
          return false;
        }
      }

      return false;
    }

    Language.fixState(BlueprintsState, vm.toolbarConfig);
  }
})();
<|endoftext|>


<commit_before>(function() {
  'use strict';

  angular
    .module('fusionSeedApp.controllers.login', ['fusionSeedApp.services.config'])
    .controller('LoginController', LoginController);

  function LoginController(ConfigService) {
    'ngInject';
    var vm = this;
    vm.appName = ConfigService.config.search_app_title;
  }
})();
<commit_msg>Added redirect to home if already logged in<commit_after>(function() {
  'use strict';

  angular
    .module('fusionSeedApp.controllers.login', ['fusionSeedApp.services.config'])
    .controller('LoginController', LoginController);

  function LoginController($state, ConfigService, AuthService) {
    'ngInject';
    var vm = this;
    vm.appName = ConfigService.config.search_app_title;

    AuthService.getSession().then(function(resp){
      $state.go('home');
    });
  }
})();
<|endoftext|>


<commit_before>"use strict";

export default {

  validate(isValid, newState, emptyState){
    if(!isValid){
      this.setState(
        Object.assign(this.state.validations, newState)
      );
    } else {
      this.setState(
        Object.assign(this.state.validations, emptyState)
      );
    }
    return isValid;
  }

};
<commit_msg>Remove common validator<commit_after><|endoftext|>


<commit_before>let mcache = require('memory-cache');

// Thanks to Guilherme Oenning
// https://goenning.net/2016/02/10/simple-server-side-cache-for-expressjs/

let cache = (duration) => {
  return (req, res, next) => {
    let key = `__express__${req.originalUrl || req.url}`;
    let cachedBody = mcache.get(key);
    if (cachedBody) {
      res.send(cachedBody)
      return
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        mcache.put(key, body, duration * 1000);
        res.sendResponse(body);
      }
      next();
    }
  }
}

module.exports = {
  cache
};
<commit_msg>Only send cached podcast list page if user not logged in<commit_after>let mcache = require('memory-cache');

// Thanks to Guilherme Oenning
// https://goenning.net/2016/02/10/simple-server-side-cache-for-expressjs/

let cache = (duration) => {
  return (req, res, next) => {
    let key = `__express__${req.originalUrl || req.url}`;
    let cachedBody = mcache.get(key);
    // TODO: how can we handle caching, but still load logged in user data on
    // the page?
    if (cachedBody && res.locals && !res.locals.isLoggedIn) {
      res.send(cachedBody)
      return
    } else {
      res.sendResponse = res.send;
      res.send = (body) => {
        mcache.put(key, body, duration * 1000);
        res.sendResponse(body);
      }
      next();
    }
  }
}

module.exports = {
  cache
};
<|endoftext|>


<commit_before>define('app_selector',
    ['jquery', 'format', 'l10n', 'log', 'requests', 'settings', 'templates', 'underscore', 'urls', 'utils', 'utils_local', 'z'],
    function($, format, l10n, log, requests, settings, nunjucks, _, urls, utils, utils_local, z) {
    'use strict';

    var gettext = l10n.gettext;
    var results_map = {};

    z.page.on('keypress input', '.app-selector input', _.debounce(function() {
        var $app_selector = $('.app-selector');
        $app_selector.find('.paginator').attr('data-offset', 0);
        if (this.value.length > 2) {
            $('.loading').show();
            $app_selector.addClass('focused');
            search_handler(this.value, 0);
        } else {
            $app_selector.removeClass('focused');
            $('.results').hide();
        }
    }, 250))

    .on('click', '.app-selector .paginator a:not(.disabled)', function() {
        var $this = $(this);
        var $paginator = $this.closest('.paginator');
        $('.results').hide();
        $('.loading').show();
        var offset = parseInt($paginator.data('offset') || 0, 10);
        offset = $this.hasClass('prev') ? (offset - 5) : (offset + 5);
        search_handler($('.app-selector input').val(), offset);
        $paginator.data('offset', offset);
    })

    .on('click', '.app-selector .result', function(evt) {
        evt.preventDefault();  // To prevent click-off to app detail page.
        var $app_selector = $('.app-selector');
        var $this = $(this);
        $app_selector.find('input[name="app"]').val($this.data('id'));
        // Trigger with ID.
        $('.results').hide();
        $app_selector.removeClass('focused');
        $('#app-selector').val('');
        if (z.body.is('[data-page-type~="apps"]')) {
            $('#slug').val(utils_local.slugify($this.find('.name a').text()));
        }
        z.page.trigger('app-selected', [results_map[$this.attr('data-id')]]);
    });

    function get_disabled_regions(app) {
        // Given app, do set difference between all regions and app's regions
        // to get the disabled regions.
        return Object.keys(settings.REGION_CHOICES_SLUG).filter(function(slug) {
            return app.regions
                      .map(function(region) { return region.slug; })
                      .indexOf(slug) < 0;
        });
    }

    var render_result = function(app, with_actions) {
        return nunjucks.env.render('app_selector/app_selector_result.html', {
            author: app.author,
            detail_url: settings.api_url + '/app/' + app.slug,
            device_types: app.device_types,
            disabled_regions: get_disabled_regions(app),
            icon: app.icons['32'],
            id: app.id,
            name: utils.translate(app.name),
            price: app.payment_required ? app.price_locale : gettext('Free'),
            rating: app.ratings.average,
            with_actions: with_actions
        });
    };

    function search_handler(q, offset) {
        var $paginator = $('.app-selector .paginator');
        var $results = $('.results');

        // Search.
        var search_url = urls.api.unsigned.params(
            'search', {'q': q, 'limit': 5, 'offset': offset});
        requests.get(search_url).done(function(data) {
            $results.find('.result').remove();
            $results.show();

            // Append results.
            if (data.objects.length === 0) {
                var no_results = nunjucks.env.render(
                    'app_selector/app_selector_no_results.html', {});
                $paginator.hide();
                $results.append(no_results);
            } else {
                $paginator.show();
                for (var i = 0; i < data.objects.length; i++) {
                    $results.append(render_result(data.objects[i]));
                    results_map[data.objects[i].id] = data.objects[i];
                }
            }

            var $desc = $paginator.find('.desc');
            var $next = $paginator.find('.next');
            var $prev = $paginator.find('.prev');
            var meta = data.meta;

            if (!meta.previous && !meta.next) {
                $paginator.hide();
            } else {
                $paginator.show();

                if (meta.previous) {
                    $prev.removeClass('disabled');
                } else {
                    $prev.addClass('disabled');
                }

                if (meta.next) {
                    $next.removeClass('disabled');
                } else {
                    $next.addClass('disabled');
                }

                // L10n: {0} refers to the position of the first app on the page,
                // {1} refers to the position of the last app on the page,
                // and {2} refers to the total number of apps across all pages.
                var desc = format.format(gettext('Apps {0}-{1} of {2}.'),
                    (meta.offset + 1), (meta.offset + meta.limit), meta.total_count);
                $desc.text(desc);

            }

            $('.loading').hide();
        });
    }

    return {
        render_result: render_result
    };
});
<commit_msg>fix missing slugify (bug 1049858)<commit_after>define('app_selector',
    ['jquery', 'format', 'l10n', 'log', 'requests', 'settings', 'templates', 'underscore', 'urls', 'utils', 'z'],
    function($, format, l10n, log, requests, settings, nunjucks, _, urls, utils, z) {
    'use strict';

    var gettext = l10n.gettext;
    var results_map = {};

    z.page.on('keypress input', '.app-selector input', _.debounce(function() {
        var $app_selector = $('.app-selector');
        $app_selector.find('.paginator').attr('data-offset', 0);
        if (this.value.length > 2) {
            $('.loading').show();
            $app_selector.addClass('focused');
            search_handler(this.value, 0);
        } else {
            $app_selector.removeClass('focused');
            $('.results').hide();
        }
    }, 250))

    .on('click', '.app-selector .paginator a:not(.disabled)', function() {
        var $this = $(this);
        var $paginator = $this.closest('.paginator');
        $('.results').hide();
        $('.loading').show();
        var offset = parseInt($paginator.data('offset') || 0, 10);
        offset = $this.hasClass('prev') ? (offset - 5) : (offset + 5);
        search_handler($('.app-selector input').val(), offset);
        $paginator.data('offset', offset);
    })

    .on('click', '.app-selector .result', function(evt) {
        evt.preventDefault();  // To prevent click-off to app detail page.
        var $app_selector = $('.app-selector');
        var $this = $(this);
        $app_selector.find('input[name="app"]').val($this.data('id'));
        // Trigger with ID.
        $('.results').hide();
        $app_selector.removeClass('focused');
        $('#app-selector').val('');
        if (z.body.is('[data-page-type~="apps"]')) {
            $('#slug').val(utils.slugify($this.find('.name a').text()));
        }
        z.page.trigger('app-selected', [results_map[$this.attr('data-id')]]);
    });

    function get_disabled_regions(app) {
        // Given app, do set difference between all regions and app's regions
        // to get the disabled regions.
        return Object.keys(settings.REGION_CHOICES_SLUG).filter(function(slug) {
            return app.regions
                      .map(function(region) { return region.slug; })
                      .indexOf(slug) < 0;
        });
    }

    var render_result = function(app, with_actions) {
        return nunjucks.env.render('app_selector/app_selector_result.html', {
            author: app.author,
            detail_url: settings.api_url + '/app/' + app.slug,
            device_types: app.device_types,
            disabled_regions: get_disabled_regions(app),
            icon: app.icons['32'],
            id: app.id,
            name: utils.translate(app.name),
            price: app.payment_required ? app.price_locale : gettext('Free'),
            rating: app.ratings.average,
            with_actions: with_actions
        });
    };

    function search_handler(q, offset) {
        var $paginator = $('.app-selector .paginator');
        var $results = $('.results');

        // Search.
        var search_url = urls.api.unsigned.params(
            'search', {'q': q, 'limit': 5, 'offset': offset});
        requests.get(search_url).done(function(data) {
            $results.find('.result').remove();
            $results.show();

            // Append results.
            if (data.objects.length === 0) {
                var no_results = nunjucks.env.render(
                    'app_selector/app_selector_no_results.html', {});
                $paginator.hide();
                $results.append(no_results);
            } else {
                $paginator.show();
                for (var i = 0; i < data.objects.length; i++) {
                    $results.append(render_result(data.objects[i]));
                    results_map[data.objects[i].id] = data.objects[i];
                }
            }

            var $desc = $paginator.find('.desc');
            var $next = $paginator.find('.next');
            var $prev = $paginator.find('.prev');
            var meta = data.meta;

            if (!meta.previous && !meta.next) {
                $paginator.hide();
            } else {
                $paginator.show();

                if (meta.previous) {
                    $prev.removeClass('disabled');
                } else {
                    $prev.addClass('disabled');
                }

                if (meta.next) {
                    $next.removeClass('disabled');
                } else {
                    $next.addClass('disabled');
                }

                // L10n: {0} refers to the position of the first app on the page,
                // {1} refers to the position of the last app on the page,
                // and {2} refers to the total number of apps across all pages.
                var desc = format.format(gettext('Apps {0}-{1} of {2}.'),
                    (meta.offset + 1), (meta.offset + meta.limit), meta.total_count);
                $desc.text(desc);

            }

            $('.loading').hide();
        });
    }

    return {
        render_result: render_result
    };
});
<|endoftext|>


<commit_before>var h = Cycle.h;
var Rx = Cycle.Rx;

Cycle.registerCustomElement('wrapper-element', function (user, props) {
  var view = Cycle.createView(function (props) {
    return {
      vtree$: props.get('children$').map(function (children) {
        return h('div.wrapper', {style: {backgroundColor: 'lightgray'}}, children);
      })
    };
  });

  user.inject(view).inject(props);
});

var view = Cycle.createView(function () {
  return {
    vtree$: Rx.Observable.just(
      h('div.everything', [
        h('wrapper-element', {key: 1}, [
          h('h3', 'I am supposed to be inside a gray box.')
        ])
      ])
    )
  };
});

var user = Cycle.createDOMUser('.js-container');

user.inject(view);
<commit_msg>Update wrapper example with Cycle Streams<commit_after>var h = Cycle.h;
var Rx = Cycle.Rx;

Cycle.registerCustomElement('wrapper-element', function (rootElem$, props) {
  var vtree$ = Cycle.createStream(function (children$) {
    return children$.map(function (children) {
      return h('div.wrapper', {style: {backgroundColor: 'lightgray'}}, children);
    });
  });

  rootElem$.inject(vtree$).inject(props.get('children$'));
});

var vtree$ = Rx.Observable.just(
  h('div.everything', [
    h('wrapper-element', {key: 1}, [
      h('h3', 'I am supposed to be inside a gray box.')
    ])
  ])
);

Cycle.render(vtree$, '.js-container');
<|endoftext|>


<commit_before>Template.residentActivityChart.rendered = function () {
  // Get resident id
  var residentId = this.data._id;

  // Get resident name
  var residentName = this.data.firstName + " " + this.data.lastInitial;

  // Get the resident activities
  var activities = Residents.findOne(residentId).activities().fetch();

  //TODO: Make sure there can be multiple activities in a single day.

  // Create a nest of activities grouped by activity date
  var nestedActivities = d3.nest()
    .key(function (activity) {
      return activity.activityDate;
    })

  // Get a sum of activities
  var summedActivities = nestedActivities.rollup(function (activity) {
      return {
        duration: d3.sum(activity, function (activity) {
          return activity.duration;
        })
      }
    })
    .entries(activities);

    summedActivities.map(function (activity) {
      // Create date and duration attributes with proper data types
      activity.date = new Date(activity.key);
      activity.duration = parseInt(activity.values.duration);

      // Delete unused key and values
      delete activity.values
      delete activity.key;
    })

  // Render the chart using MetricsGraphics charting library
  MG.data_graphic({
    title: "Daily activity in minutes.",
    description: "Showing daily activity minutes for " + residentName,
    y_label: 'Minutes',
    y_rug: true,
    data: summedActivities,
    chart_type: 'point',
    least_squares: true,
    full_width: true,
    height: 200,
    right: 40,
    target: document.getElementById('activity-chart'),
    x_accessor: 'date',
    y_accessor: 'duration'
  });
}
<commit_msg>Mouseover, format date, text string.<commit_after>Template.residentActivityChart.rendered = function () {
  // Get resident id
  var residentId = this.data._id;

  // Get resident name
  var residentName = this.data.firstName + " " + this.data.lastInitial;

  // Get the resident activities
  var activities = Residents.findOne(residentId).activities().fetch();

  //TODO: Make sure there can be multiple activities in a single day.

  // Create a nest of activities grouped by activity date
  var nestedActivities = d3.nest()
    .key(function (activity) {
      return activity.activityDate;
    })

  // Get a sum of activities
  var summedActivities = nestedActivities.rollup(function (activity) {
      return {
        duration: d3.sum(activity, function (activity) {
          return activity.duration;
        })
      }
    })
    .entries(activities);

    summedActivities.map(function (activity) {
      // Create date and duration attributes with proper data types
      activity.date = new Date(activity.key);
      activity.duration = parseInt(activity.values.duration);

      // Delete unused key and values
      delete activity.values
      delete activity.key;
    })

  // Render the chart using MetricsGraphics charting library
  MG.data_graphic({
    title: "Daily activity in minutes.",
    description: "Showing daily activity minutes for " + residentName,
    y_label: 'Minutes',
    y_rug: true,
    data: summedActivities,
    chart_type: 'point',
    least_squares: true,
    full_width: true,
    height: 200,
    right: 40,
    target: document.getElementById('activity-chart'),
    x_accessor: 'date',
    y_accessor: 'duration',
    mouseover: function (d, i) {
      var date = d.point.date;
      var formattedDate = moment(date).format("D.M.YYYY");
      var minutes = d.point.duration;
      d3.select('#activity-chart svg .mg-active-datapoint')
        .text(formattedDate + ' ' + minutes + ' minutes');
    }
  });
}
<|endoftext|>


<commit_before>import { getProp } from 'driveback-utils/dotProp';
import {
  getEnrichableVariableMappingProps,
  extractVariableMappingValues,
} from '../IntegrationUtils';

import Integration from '../Integration';
import {
  VIEWED_PAGE,
  VIEWED_PRODUCT_DETAIL,
  VIEWED_PRODUCT_LISTING,
  ADDED_PRODUCT,
  REMOVED_PRODUCT,
  COMPLETED_TRANSACTION,
  SEARCHED_PRODUCTS,
} from '../events/semanticEvents';

const SEMANTIC_EVENTS = [
  VIEWED_PAGE,
  VIEWED_PRODUCT_DETAIL,
  VIEWED_PRODUCT_LISTING,
  ADDED_PRODUCT,
  REMOVED_PRODUCT,
  COMPLETED_TRANSACTION,
  SEARCHED_PRODUCTS,
];

class REES46 extends Integration {
  constructor(digitalData, options) {
    const optionsWithDefaults = Object.assign({
      storeKey: '',
      feedWithGroupedProducts: false,
      productVariables: {},
    }, options);

    super(digitalData, optionsWithDefaults);

    this.addTag({
      type: 'script',
      attr: {
        src: 'https://cdn.rees46.com/v3.js',
      },
    });
  }

  initialize() {
    window.r46 = window.r46 || function r46Init() {
      (window.r46.q = window.r46.q || []).push(arguments);
    };
    window.r46('init', this.getOption('storeKey'));
  }

  getSemanticEvents() {
    return SEMANTIC_EVENTS;
  }

  getEnrichableEventProps(event) {
    switch (event.name) {
      case VIEWED_PAGE: return ['user', 'website'];
      case VIEWED_PRODUCT_LISTING: return ['listing.categoryId'];
      case SEARCHED_PRODUCTS: return ['listing.query'];
      case COMPLETED_TRANSACTION: return ['transaction'];
      case VIEWED_PRODUCT_DETAIL:
        return [
          ...getEnrichableVariableMappingProps(this.getOption('productVariables')),
          'product',
        ];
      default: return [];
    }
  }

  getProductVariables(event) {
    const { product } = event;
    const mapping = this.getOption('productVariables');
    return extractVariableMappingValues(
      { event, product },
      mapping,
      { multipleScopes: true },
    );
  }

  trackEvent(event) {
    const eventMap = {
      [VIEWED_PAGE]: this.onViewedPage.bind(this),
      [VIEWED_PRODUCT_DETAIL]: this.onViewedProductDetail.bind(this),
      [VIEWED_PRODUCT_LISTING]: this.onViewedProductListing.bind(this),
      [SEARCHED_PRODUCTS]: this.onSearchedProducts.bind(this),
      [ADDED_PRODUCT]: this.onAddedProduct.bind(this),
      [REMOVED_PRODUCT]: this.onRemovedProduct.bind(this),
      [COMPLETED_TRANSACTION]: this.onCompletedTransaction.bind(this),
    };
    if (eventMap[event.name]) {
      eventMap[event.name](event);
    }
  }

  onViewedPage(event) {
    const { user } = event;
    if (!user || !user.userId || !user.email) return;
    const gender = String(user.gender).toLowerCase();

    const rees46Data = cleanObject({
      id: user.userId,
      email: user.email,
      gender: ['m', 'f'].indexOf(gender) >= 0 ? gender : undefined,
      birthday: user.birthDate,
      location: getProp(event, 'website.regionId'),
    });

    window.r46('profile', 'set', rees46Data);
  }

  onViewedProductDetail(event) {
    const product = event.product || {};
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    const productId = (feedWithGroupedProducts) ? product.skuCode : product.id;
    if (!productId) return;

    const productVariables = this.getProductVariables(event);
    const { stock } = product;
    if (stock !== undefined) {
      productVariables.stock = (stock > 0);
    }

    if (Object.keys(productVariables).length > 0) {
      window.r46('track', 'view', {
        id: productId,
        ...productVariables,
      });
    } else {
      window.r46('track', 'view', productId);
    }
  }

  onAddedProduct(event) {
    const product = event.product || {};
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    const productId = (feedWithGroupedProducts) ? product.skuCode : product.id;
    if (productId) {
      window.r46('track', 'cart', {
        id: productId,
        amount: event.quantity || 1,
      });
    }
  }

  onRemovedProduct(event) {
    const product = event.product || {};
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    const productId = (feedWithGroupedProducts) ? product.skuCode : product.id;
    if (productId) {
      window.r46('track', 'remove_from_cart', productId);
    }
  }

  onViewedProductListing(event) {
    const listing = event.listing || {};
    const { categoryId } = listing;
    if (categoryId) {
      window.r46('track', 'category', categoryId);
    }
  }

  onSearchedProducts(event) {
    const listing = event.listing || {};
    const { query } = listing;
    if (query) {
      window.r46('track', 'search', query);
    }
  }

  onCompletedTransaction(event) {
    const transaction = event.transaction || {};
    const lineItems = transaction.lineItems || [];
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    if (lineItems.length) {
      window.r46('track', 'purchase', {
        products: lineItems.map(lineItem => ({
          id: (feedWithGroupedProducts)
            ? getProp(lineItem, 'product.skuCode') : getProp(lineItem, 'product.id'),
          price: getProp(lineItem, 'product.unitSalePrice'),
          amount: lineItem.quantity || 1,
        })),
        order: transaction.orderId,
        order_price: transaction.total,
      });
    }
  }
}

export default REES46;
<commit_msg>fix rees error<commit_after>import cleanObject from 'driveback-utils/cleanObject';
import { getProp } from 'driveback-utils/dotProp';
import {
  getEnrichableVariableMappingProps,
  extractVariableMappingValues,
} from '../IntegrationUtils';

import Integration from '../Integration';
import {
  VIEWED_PAGE,
  VIEWED_PRODUCT_DETAIL,
  VIEWED_PRODUCT_LISTING,
  ADDED_PRODUCT,
  REMOVED_PRODUCT,
  COMPLETED_TRANSACTION,
  SEARCHED_PRODUCTS,
} from '../events/semanticEvents';

const SEMANTIC_EVENTS = [
  VIEWED_PAGE,
  VIEWED_PRODUCT_DETAIL,
  VIEWED_PRODUCT_LISTING,
  ADDED_PRODUCT,
  REMOVED_PRODUCT,
  COMPLETED_TRANSACTION,
  SEARCHED_PRODUCTS,
];

class REES46 extends Integration {
  constructor(digitalData, options) {
    const optionsWithDefaults = Object.assign({
      storeKey: '',
      feedWithGroupedProducts: false,
      productVariables: {},
    }, options);

    super(digitalData, optionsWithDefaults);

    this.addTag({
      type: 'script',
      attr: {
        src: 'https://cdn.rees46.com/v3.js',
      },
    });
  }

  initialize() {
    window.r46 = window.r46 || function r46Init() {
      (window.r46.q = window.r46.q || []).push(arguments);
    };
    window.r46('init', this.getOption('storeKey'));
  }

  getSemanticEvents() {
    return SEMANTIC_EVENTS;
  }

  getEnrichableEventProps(event) {
    switch (event.name) {
      case VIEWED_PAGE: return ['user', 'website'];
      case VIEWED_PRODUCT_LISTING: return ['listing.categoryId'];
      case SEARCHED_PRODUCTS: return ['listing.query'];
      case COMPLETED_TRANSACTION: return ['transaction'];
      case VIEWED_PRODUCT_DETAIL:
        return [
          ...getEnrichableVariableMappingProps(this.getOption('productVariables')),
          'product',
        ];
      default: return [];
    }
  }

  getProductVariables(event) {
    const { product } = event;
    const mapping = this.getOption('productVariables');
    return extractVariableMappingValues(
      { event, product },
      mapping,
      { multipleScopes: true },
    );
  }

  trackEvent(event) {
    const eventMap = {
      [VIEWED_PAGE]: this.onViewedPage.bind(this),
      [VIEWED_PRODUCT_DETAIL]: this.onViewedProductDetail.bind(this),
      [VIEWED_PRODUCT_LISTING]: this.onViewedProductListing.bind(this),
      [SEARCHED_PRODUCTS]: this.onSearchedProducts.bind(this),
      [ADDED_PRODUCT]: this.onAddedProduct.bind(this),
      [REMOVED_PRODUCT]: this.onRemovedProduct.bind(this),
      [COMPLETED_TRANSACTION]: this.onCompletedTransaction.bind(this),
    };
    if (eventMap[event.name]) {
      eventMap[event.name](event);
    }
  }

  onViewedPage(event) {
    const { user } = event;
    if (!user || !user.userId || !user.email) return;
    const gender = String(user.gender).toLowerCase();

    const rees46Data = cleanObject({
      id: user.userId,
      email: user.email,
      gender: ['m', 'f'].indexOf(gender) >= 0 ? gender : undefined,
      birthday: user.birthDate,
      location: getProp(event, 'website.regionId'),
    });

    window.r46('profile', 'set', rees46Data);
  }

  onViewedProductDetail(event) {
    const product = event.product || {};
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    const productId = (feedWithGroupedProducts) ? product.skuCode : product.id;
    if (!productId) return;

    const productVariables = this.getProductVariables(event);
    const { stock } = product;
    if (stock !== undefined) {
      productVariables.stock = (stock > 0);
    }

    if (Object.keys(productVariables).length > 0) {
      window.r46('track', 'view', {
        id: productId,
        ...productVariables,
      });
    } else {
      window.r46('track', 'view', productId);
    }
  }

  onAddedProduct(event) {
    const product = event.product || {};
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    const productId = (feedWithGroupedProducts) ? product.skuCode : product.id;
    if (productId) {
      window.r46('track', 'cart', {
        id: productId,
        amount: event.quantity || 1,
      });
    }
  }

  onRemovedProduct(event) {
    const product = event.product || {};
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    const productId = (feedWithGroupedProducts) ? product.skuCode : product.id;
    if (productId) {
      window.r46('track', 'remove_from_cart', productId);
    }
  }

  onViewedProductListing(event) {
    const listing = event.listing || {};
    const { categoryId } = listing;
    if (categoryId) {
      window.r46('track', 'category', categoryId);
    }
  }

  onSearchedProducts(event) {
    const listing = event.listing || {};
    const { query } = listing;
    if (query) {
      window.r46('track', 'search', query);
    }
  }

  onCompletedTransaction(event) {
    const transaction = event.transaction || {};
    const lineItems = transaction.lineItems || [];
    const feedWithGroupedProducts = this.getOption('feedWithGroupedProducts');
    if (lineItems.length) {
      window.r46('track', 'purchase', {
        products: lineItems.map(lineItem => ({
          id: (feedWithGroupedProducts)
            ? getProp(lineItem, 'product.skuCode') : getProp(lineItem, 'product.id'),
          price: getProp(lineItem, 'product.unitSalePrice'),
          amount: lineItem.quantity || 1,
        })),
        order: transaction.orderId,
        order_price: transaction.total,
      });
    }
  }
}

export default REES46;
<|endoftext|>


<commit_before>
v.component.fab = {
  oninit: (vnode) => {
    vnode.state.onclick = (e) => {
      vnode.attrs.fab.onclick(e)
    }
  },
  oncreate: (vnode) => {
    var fab = mdc.ripple.MDCRipple.attachTo(vnode.dom)
  },
  view: (vnode) => [
    (v.state.admin || null) &&
    m('button.mdc-fab material-icons v-fab', {
      onclick: vnode.state.onclick
      },
      m('span.mdc-fab__icon', 'add')
    )
  ]
}
<commit_msg>Fix fab initialization<commit_after>
v.component.fab = {
  oninit: (vnode) => {
    vnode.state.onclick = (e) => {
      vnode.attrs.fab.onclick(e)
    }
  },
  oncreate: (vnode) => {
    if (vnode.dom) {
      var fab = mdc.ripple.MDCRipple.attachTo(vnode.dom)
    }
  },
  view: (vnode) => [
    (v.state.admin || null) &&
    m('button.mdc-fab material-icons v-fab', {
      onclick: vnode.state.onclick
      },
      m('span.mdc-fab__icon', 'add')
    )
  ]
}
<|endoftext|>


<commit_before>const GLib = imports.gi.GLib;
const Shell = imports.gi.Shell;

//self
const Self = imports.misc.extensionUtils.getCurrentExtension();
const LoggerModule = Self.imports.logger;
const Timer = Self.imports.timer;

// UI Imports
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const CustomElements = Self.imports.elements;
const Main = imports.ui.main;

// Filesystem
const Gio = imports.gi.Gio;

// Settings
const Prefs = Self.imports.settings;

var RandomWallpaperMenu = class {

	constructor(wallpaperController) {
		this.panelMenu = new PanelMenu.Button(0, "Random wallpaper");
		this.settings = new Prefs.Settings();
		this.wallpaperController = wallpaperController;
		this.logger = new LoggerModule.Logger('RWG3', 'RandomWallpaperEntry');
		this.hidePanelIconHandler = this.settings.observe('hide-panel-icon', this.updatePanelMenuVisibility.bind(this));

		// Panelmenu Icon
		this.statusIcon = new CustomElements.StatusElement();
		this.panelMenu.actor.add_child(this.statusIcon.icon);

		// new wallpaper button
		this.newWallpaperItem = new CustomElements.NewWallpaperElement();

		this.panelMenu.menu.addMenuItem(this.newWallpaperItem);

		this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

		// current background section
		this.currentBackgroundSection = new PopupMenu.PopupMenuSection();
		this.panelMenu.menu.addMenuItem(this.currentBackgroundSection);
		this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

		// history section
		this.historySection = new CustomElements.HistorySection();
		this.panelMenu.menu.addMenuItem(this.historySection);

		this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

		// clear history button
		this.clearHistoryItem = new PopupMenu.PopupMenuItem('Clear History');
		this.panelMenu.menu.addMenuItem(this.clearHistoryItem);

		// open wallpaper folder button
		this.openFolder = new PopupMenu.PopupMenuItem('Open Wallpaper Folder');
		this.panelMenu.menu.addMenuItem(this.openFolder);

		// settings button
		this.openSettings = new PopupMenu.PopupMenuItem('Settings');
		this.panelMenu.menu.addMenuItem(this.openSettings);

		/*
			add eventlistener
		*/
		this.wallpaperController.registerStartLoadingHook(this.statusIcon.startLoading.bind(this.statusIcon));
		this.wallpaperController.registerStopLoadingHook(this.statusIcon.stopLoading.bind(this.statusIcon));
		this.wallpaperController.registerStopLoadingHook(this.setHistoryList.bind(this));

		// new wallpaper event
		this.newWallpaperItem.connect('activate', () => {
			this.wallpaperController.fetchNewWallpaper();
		});

		// clear history event
		this.clearHistoryItem.connect('activate', () => {
			this.wallpaperController.deleteHistory();
		});

		// Open Wallpaper Folder
		this.openFolder.connect('activate', (event) => {
			let uri = GLib.filename_to_uri(this.wallpaperController.wallpaperlocation, "");
			Gio.AppInfo.launch_default_for_uri(uri, global.create_app_launch_context(0, -1))
		});

		this.openSettings.connect("activate", () => {
			// call gnome settings tool for this extension
			let app = Shell.AppSystem.get_default().lookup_app("gnome-shell-extension-prefs.desktop");
			if (app != null) {
				// only works in Gnome >= 3.12
				let info = app.get_app_info();
				let timestamp = global.display.get_current_time_roundtrip();
				info.launch_uris([Self.uuid], global.create_app_launch_context(timestamp, -1));
			}
		});

		this.panelMenu.menu.actor.connect('show', () => {
			this.newWallpaperItem.show();
		});

		// when the popupmenu disapears, check if the wallpaper is the original and
		// reset it if needed
		this.panelMenu.menu.actor.connect('hide', () => {
			this.wallpaperController.resetWallpaper();
		});

		this.panelMenu.menu.actor.connect('leave-event', () => {
			this.wallpaperController.resetWallpaper();
		});

		this.settings.observe('history', this.setHistoryList.bind(this));
	}

	init() {
		this.updatePanelMenuVisibility();
		this.setHistoryList();

		// add to panel
		Main.panel.addToStatusArea("random-wallpaper-menu", this.panelMenu);
	}

	cleanup() {
		this.clearHistoryList();
		this.panelMenu.destroy();

		// remove all signal handlers
		if (this.hidePanelIconHandler !== null) {
			this.settings.disconnect(this.hidePanelIconHandler);
		}
	}

	updatePanelMenuVisibility() {
		if (this.settings.get('hide-panel-icon', 'boolean')) {
			this.panelMenu.actor.hide();
		} else {
			this.panelMenu.actor.show();
		}
	}

	setCurrentBackgroundElement() {
		this.currentBackgroundSection.removeAll();

		let historyController = this.wallpaperController.getHistoryController();
		let history = historyController.history;

		if (history.length > 0) {
			let currentImage = new CustomElements.CurrentImageElement(history[0]);
			this.currentBackgroundSection.addMenuItem(currentImage);
		}
	}

	setHistoryList() {
		this.wallpaperController.update();
		this.setCurrentBackgroundElement();

		let historyController = this.wallpaperController.getHistoryController();
		let history = historyController.history;

		if (history.length <= 1) {
			this.clearHistoryList();
			return;
		}

		function onLeave(actor) {
			this.wallpaperController.resetWallpaper();
		}

		function onEnter(actor) {
			this.wallpaperController.previewWallpaper(actor.historyId);
		}

		function onSelect(actor) {
			this.wallpaperController.setWallpaper(actor.historyEntry.id);
		}

		this.historySection.updateList(history, onEnter.bind(this), onLeave.bind(this), onSelect.bind(this));
	}

	clearHistoryList() {
		this.historySection.clear();
	}

};
<commit_msg>fix opening the settings (opens overview for now)<commit_after>const GLib = imports.gi.GLib;
const Shell = imports.gi.Shell;

//self
const Self = imports.misc.extensionUtils.getCurrentExtension();
const LoggerModule = Self.imports.logger;
const Timer = Self.imports.timer;

// UI Imports
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const CustomElements = Self.imports.elements;
const Main = imports.ui.main;

// Filesystem
const Gio = imports.gi.Gio;

// Settings
const Prefs = Self.imports.settings;

var RandomWallpaperMenu = class {

	constructor(wallpaperController) {
		this.panelMenu = new PanelMenu.Button(0, "Random wallpaper");
		this.settings = new Prefs.Settings();
		this.wallpaperController = wallpaperController;
		this.logger = new LoggerModule.Logger('RWG3', 'RandomWallpaperEntry');
		this.hidePanelIconHandler = this.settings.observe('hide-panel-icon', this.updatePanelMenuVisibility.bind(this));

		// Panelmenu Icon
		this.statusIcon = new CustomElements.StatusElement();
		this.panelMenu.actor.add_child(this.statusIcon.icon);

		// new wallpaper button
		this.newWallpaperItem = new CustomElements.NewWallpaperElement();

		this.panelMenu.menu.addMenuItem(this.newWallpaperItem);

		this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

		// current background section
		this.currentBackgroundSection = new PopupMenu.PopupMenuSection();
		this.panelMenu.menu.addMenuItem(this.currentBackgroundSection);
		this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

		// history section
		this.historySection = new CustomElements.HistorySection();
		this.panelMenu.menu.addMenuItem(this.historySection);

		this.panelMenu.menu.addMenuItem(new PopupMenu.PopupSeparatorMenuItem());

		// clear history button
		this.clearHistoryItem = new PopupMenu.PopupMenuItem('Clear History');
		this.panelMenu.menu.addMenuItem(this.clearHistoryItem);

		// open wallpaper folder button
		this.openFolder = new PopupMenu.PopupMenuItem('Open Wallpaper Folder');
		this.panelMenu.menu.addMenuItem(this.openFolder);

		// settings button
		this.openSettings = new PopupMenu.PopupMenuItem('Settings');
		this.panelMenu.menu.addMenuItem(this.openSettings);

		/*
			add eventlistener
		*/
		this.wallpaperController.registerStartLoadingHook(this.statusIcon.startLoading.bind(this.statusIcon));
		this.wallpaperController.registerStopLoadingHook(this.statusIcon.stopLoading.bind(this.statusIcon));
		this.wallpaperController.registerStopLoadingHook(this.setHistoryList.bind(this));

		// new wallpaper event
		this.newWallpaperItem.connect('activate', () => {
			this.wallpaperController.fetchNewWallpaper();
		});

		// clear history event
		this.clearHistoryItem.connect('activate', () => {
			this.wallpaperController.deleteHistory();
		});

		// Open Wallpaper Folder
		this.openFolder.connect('activate', (event) => {
			let uri = GLib.filename_to_uri(this.wallpaperController.wallpaperlocation, "");
			Gio.AppInfo.launch_default_for_uri(uri, global.create_app_launch_context(0, -1))
		});

		this.openSettings.connect("activate", () => {
			// Fixme: opens the settings overview in 3.36 where you have to select the correct extension yourself.
			// call gnome settings tool for this extension
			let app = Shell.AppSystem.get_default().lookup_app("org.gnome.Extensions.desktop");

			if (app != null) {
				// only works in Gnome >= 3.12
				let info = app.get_app_info();
				let timestamp = global.display.get_current_time_roundtrip();
				info.launch_uris([Self.uuid], global.create_app_launch_context(timestamp, -1));
			}
		});

		this.panelMenu.menu.actor.connect('show', () => {
			this.newWallpaperItem.show();
		});

		// when the popupmenu disapears, check if the wallpaper is the original and
		// reset it if needed
		this.panelMenu.menu.actor.connect('hide', () => {
			this.wallpaperController.resetWallpaper();
		});

		this.panelMenu.menu.actor.connect('leave-event', () => {
			this.wallpaperController.resetWallpaper();
		});

		this.settings.observe('history', this.setHistoryList.bind(this));
	}

	init() {
		this.updatePanelMenuVisibility();
		this.setHistoryList();

		// add to panel
		Main.panel.addToStatusArea("random-wallpaper-menu", this.panelMenu);
	}

	cleanup() {
		this.clearHistoryList();
		this.panelMenu.destroy();

		// remove all signal handlers
		if (this.hidePanelIconHandler !== null) {
			this.settings.disconnect(this.hidePanelIconHandler);
		}
	}

	updatePanelMenuVisibility() {
		if (this.settings.get('hide-panel-icon', 'boolean')) {
			this.panelMenu.actor.hide();
		} else {
			this.panelMenu.actor.show();
		}
	}

	setCurrentBackgroundElement() {
		this.currentBackgroundSection.removeAll();

		let historyController = this.wallpaperController.getHistoryController();
		let history = historyController.history;

		if (history.length > 0) {
			let currentImage = new CustomElements.CurrentImageElement(history[0]);
			this.currentBackgroundSection.addMenuItem(currentImage);
		}
	}

	setHistoryList() {
		this.wallpaperController.update();
		this.setCurrentBackgroundElement();

		let historyController = this.wallpaperController.getHistoryController();
		let history = historyController.history;

		if (history.length <= 1) {
			this.clearHistoryList();
			return;
		}

		function onLeave(actor) {
			this.wallpaperController.resetWallpaper();
		}

		function onEnter(actor) {
			this.wallpaperController.previewWallpaper(actor.historyId);
		}

		function onSelect(actor) {
			this.wallpaperController.setWallpaper(actor.historyEntry.id);
		}

		this.historySection.updateList(history, onEnter.bind(this), onLeave.bind(this), onSelect.bind(this));
	}

	clearHistoryList() {
		this.historySection.clear();
	}

};
<|endoftext|>


<commit_before>var translations = require('./translations')

var mustache = require('mustache')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')

inherits(Lang, EventEmitter)

function Lang () {
  var self = this
  if (!(self instanceof Lang)) return new Lang()

  var langLocale = navigator.languages
    ? navigator.languages[0]
    : (navigator.language || navigator.userLanguage)

  self.lang = langLocale.split('-')[0]
  self.locale = langLocale.split('-')[1] // TODO: locale support

  // translate the DOM
  document.querySelector('#save > span').innerHTML = self.get('save')
  document.querySelector('#deploy > span').innerHTML = self.get('deploy')
  document.querySelector('#voice > span').innerHTML = self.get('talk')
  document.querySelector('#save > span').innerHTML = self.get('save')
}

Lang.prototype.get = function (key, data) {
  var self = this

  data = data || {}

  console.log(key)

  return (typeof translations[self.lang] != 'undefined') ? mustache.render(translations[self.lang][key], data) : mustache.render(translations['en'][key], data)
}

module.exports = new Lang()
<commit_msg>fix lang.js<commit_after>var translations = require('./translations')

var mustache = require('mustache')
var EventEmitter = require('events').EventEmitter
var inherits = require('inherits')

inherits(Lang, EventEmitter)

function Lang () {
  var self = this
  if (!(self instanceof Lang)) return new Lang()

  var langLocale = navigator.languages
    ? navigator.languages[0]
    : (navigator.language || navigator.userLanguage)

  self.lang = langLocale.split('-')[0]
  self.locale = langLocale.split('-')[1] // TODO: locale support

  // translate the DOM
  document.querySelector('#save > span').innerHTML = self.get('save')
  document.querySelector('#deploy > span').innerHTML = self.get('deploy')
  document.querySelector('#voice > span').innerHTML = self.get('talk')
  document.querySelector('#save > span').innerHTML = self.get('save')
}

Lang.prototype.get = function (key, data) {
  var self = this

  data = data || {}

  console.log(key)

  var lookup = translations[self.lang] || translations['en']
  return mustache.render(lookup[key] || translations['en'][key], data)
}

module.exports = new Lang()
<|endoftext|>