<commit_before>const { Formik } = formik;

const schema = yup.object({
  firstName: yup.string().required(),
  lastName: yup.string().required(),
  username: yup.string().required(),
  city: yup.string().required(),
  state: yup.string().required(),
  zip: yup.string().required(),
  terms: yup.bool().required(),
});

function FormExample() {
  return (
    <Formik
      validationSchema={schema}
      onSubmit={console.log}
      initialValues={{
        firstName: 'Mark',
        lastName: 'Otto',
      }}
    >
      {({
        handleSubmit,
        handleChange,
        handleBlur,
        values,
        touched,
        isValid,
        errors,
      }) => (
        <Form noValidate onSubmit={handleSubmit}>
          <Form.Row>
            <Form.Group as={Col} md="4" controlId="validationFormik01">
              <Form.Label>First name</Form.Label>
              <Form.Control
                type="text"
                name="firstName"
                value={values.firstName}
                onChange={handleChange}
                isValid={touched.firstName && !errors.firstName}
              />
              <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="4" controlId="validationFormik02">
              <Form.Label>Last name</Form.Label>
              <Form.Control
                type="text"
                name="lastName"
                value={values.lastName}
                onChange={handleChange}
                isValid={touched.lastName && !errors.lastName}
              />

              <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="4" controlId="validationFormikUsername">
              <Form.Label>Username</Form.Label>
              <InputGroup>
                <InputGroup.Prepend>
                  <InputGroup.Text id="inputGroupPrepend">@</InputGroup.Text>
                </InputGroup.Prepend>
                <Form.Control
                  type="text"
                  placeholder="Username"
                  aria-describedby="inputGroupPrepend"
                  name="username"
                  value={values.username}
                  onChange={handleChange}
                  isInvalid={!!errors.username}
                />
                <Form.Control.Feedback type="invalid">
                  {errors.username}
                </Form.Control.Feedback>
              </InputGroup>
            </Form.Group>
          </Form.Row>
          <Form.Row>
            <Form.Group as={Col} md="6" controlId="validationFormik03">
              <Form.Label>City</Form.Label>
              <Form.Control
                type="text"
                placeholder="City"
                name="city"
                value={values.city}
                onChange={handleChange}
                isInvalid={!!errors.city}
              />

              <Form.Control.Feedback type="invalid">
                {errors.city}
              </Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="3" controlId="validationFormik04">
              <Form.Label>State</Form.Label>
              <Form.Control
                type="text"
                placeholder="State"
                name="state"
                value={values.state}
                onChange={handleChange}
                isInvalid={!!errors.state}
              />
              <Form.Control.Feedback type="invalid">
                {errors.state}
              </Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="3" controlId="validationFormik05">
              <Form.Label>Zip</Form.Label>
              <Form.Control
                type="text"
                placeholder="Zip"
                name="zip"
                value={values.zip}
                onChange={handleChange}
                isInvalid={!!errors.zip}
              />

              <Form.Control.Feedback type="invalid">
                {errors.zip}
              </Form.Control.Feedback>
            </Form.Group>
          </Form.Row>
          <Form.Group>
            <Form.Check
              required
              name="terms"
              label="Agree to terms and conditions"
              onChange={handleChange}
              isInvalid={!!errors.terms}
              feedback={errors.terms}
              id="validationFormik0"
            />
          </Form.Group>
          <Button type="submit">Submit form</Button>
        </Form>
      )}
    </Formik>
  );
}

render(<FormExample />);
<commit_msg>docs: fix bug in example in <Form> validation with Formik<commit_after>const { Formik } = formik;

const schema = yup.object().shape({
  firstName: yup.string().required(),
  lastName: yup.string().required(),
  username: yup.string().required(),
  city: yup.string().required(),
  state: yup.string().required(),
  zip: yup.string().required(),
  terms: yup.bool().required().oneOf([true], "Terms must be accepted"),
});

function FormExample() {
  return (
    <Formik
      validationSchema={schema}
      onSubmit={console.log}
      initialValues={{
        firstName: 'Mark',
        lastName: 'Otto',
        username: '',
        city: '',
        state: '',
        zip: '',
        terms: false,
      }}
    >
      {({
        handleSubmit,
        handleChange,
        handleBlur,
        values,
        touched,
        isValid,
        errors,
      }) => (
        <Form noValidate onSubmit={handleSubmit}>
          <Form.Row>
            <Form.Group as={Col} md="4" controlId="validationFormik01">
              <Form.Label>First name</Form.Label>
              <Form.Control
                type="text"
                name="firstName"
                value={values.firstName}
                onChange={handleChange}
                isValid={touched.firstName && !errors.firstName}
              />
              <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="4" controlId="validationFormik02">
              <Form.Label>Last name</Form.Label>
              <Form.Control
                type="text"
                name="lastName"
                value={values.lastName}
                onChange={handleChange}
                isValid={touched.lastName && !errors.lastName}
              />

              <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="4" controlId="validationFormikUsername">
              <Form.Label>Username</Form.Label>
              <InputGroup>
                <InputGroup.Prepend>
                  <InputGroup.Text id="inputGroupPrepend">@</InputGroup.Text>
                </InputGroup.Prepend>
                <Form.Control
                  type="text"
                  placeholder="Username"
                  aria-describedby="inputGroupPrepend"
                  name="username"
                  value={values.username}
                  onChange={handleChange}
                  isInvalid={!!errors.username}
                />
                <Form.Control.Feedback type="invalid">
                  {errors.username}
                </Form.Control.Feedback>
              </InputGroup>
            </Form.Group>
          </Form.Row>
          <Form.Row>
            <Form.Group as={Col} md="6" controlId="validationFormik03">
              <Form.Label>City</Form.Label>
              <Form.Control
                type="text"
                placeholder="City"
                name="city"
                value={values.city}
                onChange={handleChange}
                isInvalid={!!errors.city}
              />

              <Form.Control.Feedback type="invalid">
                {errors.city}
              </Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="3" controlId="validationFormik04">
              <Form.Label>State</Form.Label>
              <Form.Control
                type="text"
                placeholder="State"
                name="state"
                value={values.state}
                onChange={handleChange}
                isInvalid={!!errors.state}
              />
              <Form.Control.Feedback type="invalid">
                {errors.state}
              </Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="3" controlId="validationFormik05">
              <Form.Label>Zip</Form.Label>
              <Form.Control
                type="text"
                placeholder="Zip"
                name="zip"
                value={values.zip}
                onChange={handleChange}
                isInvalid={!!errors.zip}
              />

              <Form.Control.Feedback type="invalid">
                {errors.zip}
              </Form.Control.Feedback>
            </Form.Group>
          </Form.Row>
          <Form.Group>
            <Form.Check
              required
              name="terms"
              label="Agree to terms and conditions"
              onChange={handleChange}
              isInvalid={!!errors.terms}
              feedback={errors.terms}
              id="validationFormik0"
            />
          </Form.Group>
          <Button type="submit">Submit form</Button>
        </Form>
      )}
    </Formik>
  );
}

render(<FormExample />);
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

const PaginationButton = ({
  active = false,
  children,
  className,
  disabled = false,
  href,
  onSelect
}) => {
  const classes = {
    'waves-effect': true,
    disabled,
    active
  };

  const linkProps = href ? { href } : null;

  return (

      {children}

  );
};

PaginationButton.propTypes = {
  active: PropTypes.bool,
  children: PropTypes.node,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  href: PropTypes.string,
  onSelect: PropTypes.func
};

export default PaginationButton;
<commit_msg>fix: remove waves effect when button is disabled (#960)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';

const PaginationButton = ({
  active = false,
  children,
  className,
  disabled = false,
  href,
  onSelect
}) => {
  const classes = {
    'waves-effect': !disabled,
    disabled,
    active
  };

  const linkProps = href ? { href } : null;

  return (

      {children}

  );
};

PaginationButton.propTypes = {
  active: PropTypes.bool,
  children: PropTypes.node,
  className: PropTypes.string,
  disabled: PropTypes.bool,
  href: PropTypes.string,
  onSelect: PropTypes.func
};

export default PaginationButton;
<|endoftext|>


<commit_before>'use strict';
// Projects controller

angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$sce', '$location', '$window', '$timeout', 'Authentication', 'Projects', 'FileUploader', 'linkify',
	function($scope, $stateParams, $sce, $location, $window, $timeout, Authentication, Projects, FileUploader, linkify ) {
		$scope.authentication = Authentication;

		// Create file uploader instance
		$scope.uploader = new FileUploader({
			url: '/api/projects/picture'
		});

		$scope.uploaderC = new FileUploader({
			url: '/api/projects/picture'
		});

		// Create new Project
		$scope.create = function() {
			// Create new Project object
			//if((this.essentialDetails && essentialDetails.litDetails.standards) || (this.essentialDetails && this.essentialDetails.mathDetails.standards) || (this.essentialDetails && essentialDetails.scienceDetails.standards) || (this.essentialDetails && essentialDetails.ssDetails.standards)){

			$scope.essentialDetails.overallStandards = '';

			if($scope.essentialDetails.litDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.litDetails.standards + ', ';
			}
			if($scope.essentialDetails.mathDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.mathDetails.standards + ', ';
			}
			if($scope.essentialDetails.scienceDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.scienceDetails.standards + ', ';
			}
			if($scope.essentialDetails.ssDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.ssDetails.standards + ', ';
			}
			if($scope.essentialDetails.otherSubject[0].standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[0].standards + ', ';
			}
			if($scope.essentialDetails.otherSubject[1].standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[1].standards + ', ';
			}
			if($scope.essentialDetails.otherSubject[2].standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[2].standards + ', ';
			}
			if($scope.essentialDetails.otherSubject[3].standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[3].standards + ', ';
			}
			if($scope.essentialDetails.otherSubject[4].standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[4].standards;
			}

			//this.essentialDetails.overallStandards = this.essentialDetails.litDetails.standards + ', ' + this.essentialDetails.mathDetails.standards + ', ' + this.essentialDetails.scienceDetails.standards + ', ' + this.essentialDetails.ssDetails.standards;
			//}
			//else{
				//this.essentialDetails.overallStandards = '';
			//}
			var project = new Projects ({
				name: this.name,
				created: this.created,
				user: this.user,
				status: this.status,
				isPublic: this.isPublic,
				minGrade: this.minGrade,
				maxGrade: this.maxGrade,
				ask: this.ask,
				imagine: this.imagine,
				essentialDetails: this.essentialDetails,
				rating: null
			});

		$scope.additionalSubjects = ['Dance', 'English Language Development', 'Gifted', 'Health Education', 'Music', 'Physical Education',
		'Special Skills', 'Technology', 'Theatre', 'Visual Art'];

			// Redirect after save
			project.$save(function(response) {

				// Start upload of picture

				if($scope.uploaderC.queue.length > 0) {

					$scope.uploaderC.queue[0].url = '/api/projects/picture/' + response._id;
					$scope.uploaderC.uploadAll();
				}

				// Clear form fields
				$scope.name = '';

				$location.path('projects/' + response._id);

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

		};

		// Remove existing Project
		$scope.remove = function( project ) {
			if ( project ) { project.$remove();

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

		$scope.CombineStandards = function(){
			$scope.project.essentialDetails.overallStandards = $scope.project.essentialDetails.litDetails[0].standards + ', ' + $scope.project.essentialDetails.mathDetails[0].standards + ', ' + $scope.project.essentialDetails.scienceDetails[0].standards + ', ' + $scope.project.essentialDetails.ssDetails[0].standards;
		};

		// Update existing Project
		$scope.update = function() {
            console.log('In $scope.update');

			var project = $scope.project;

			project.imagine.plan = '';

			project.$update(function() {

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

			if ($scope.uploader.queue.length > 0) {
				$scope.uploader.queue[0].url = '/api/projects/picture/' + project._id;
				$scope.uploader.uploadAll();
			}
		};

		// Find a list of Projects
		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			});

		};

		// Called after the user selected a new picture file
		$scope.uploader.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.project.imagine.plan = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

		$scope.linkify = function(link) {
			return $sce.trustAsHtml(linkify.normal(link));
		};

		$scope.uploaderC.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.imageURL = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

/*	-------------------------------------Star Rating Stuff-------------------------------------- */

		//an array containing the name of the glyphicon to use for each star
		$scope.glyphs = new Array(
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty'
		);

		/*
			Runs when a star glyphicon is hovered into. It sets all the stars up to the current one
			to have the filled-in star glyphicon.
		*/
		$scope.rating_hover = function(num){
			for(var i = 0; i < num; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star';
			}
			for(i = num; i < 5; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star-empty';
			}
		};

		//Runs when a star glyphicon is hovered out of. Resets the  stars' highlighing to the current rating
		$scope.reset_hover = function(){
			$scope.rating_hover($scope.rating);
		};

		//Prints out user's current rating of the project
		$scope.getMyRating = function(){

			if ($scope.project.rating && $scope.project.rating.ratings ){
				var rater = $scope.project.rating.ratings.filter(isRater)[0];
				console.log(rater);
				if (typeof rater === 'undefined'){
					$scope.rating = 0;	//current rating
					return 'You haven\'t yet rated this project. Give it a couple of stars?';
				}
				$scope.rating = rater.num;
				$scope.reset_hover();
				return ('Your currently rate this project at ' + rater.num + ' stars');
			}
			$scope.rating = 0;	//current rating
			return 'This project has not yet been rated. Give it a couple of stars?';

		};

        // Function to find the current rater
        var isRater = function(value){
			return value.reviewer === $scope.authentication.user._id;
        };

		//Changes the user's rating of the project
		$scope.rate = function(){
			console.log('In $scope.rate');
			if(!$scope.project.rating){
				$scope.project.rating = {
					ratings : [
						{
							num: $scope.rating,
							reviewer: $scope.authentication.user._id
						}
					],
					avg_rating : $scope.rating
				};
			} else {
                var rater = $scope.project.rating.ratings.filter(isRater)[0];
                var length = $scope.project.rating.ratings.length;
				var rateToRemove = 0;

                var newLength = length + 1;

                if(length === 0)
                {
                    $scope.project.rating.avg_rating = 0;
                }

				if(typeof rater !== 'undefined') {
                    rateToRemove = rater.num;
                    var rateIndex = $scope.project.rating.ratings.indexOf(rater);
                    $scope.project.rating.ratings.splice(rateIndex, 1);
                    newLength -= 1;
                }

				$scope.project.rating.avg_rating = ($scope.project.rating.avg_rating * length + $scope.rating - rateToRemove)/(newLength);

				$scope.project.rating.ratings.push({
						num: $scope.rating,
						reviewer: $scope.authentication.user._id
				});
			}
			$scope.update();

		};

	}
]);
<commit_msg>Create project finally passes all tests, now to add it to edit projects<commit_after>'use strict';
// Projects controller

angular.module('projects').controller('ProjectsController', ['$scope', '$stateParams', '$sce', '$location', '$window', '$timeout', 'Authentication', 'Projects', 'FileUploader', 'linkify',
	function($scope, $stateParams, $sce, $location, $window, $timeout, Authentication, Projects, FileUploader, linkify ) {
		$scope.authentication = Authentication;

		// Create file uploader instance
		$scope.uploader = new FileUploader({
			url: '/api/projects/picture'
		});

		$scope.uploaderC = new FileUploader({
			url: '/api/projects/picture'
		});

		// Create new Project
		$scope.create = function() {
			// Create new Project object

			$scope.essentialDetails.overallStandards = '';

			if($scope.essentialDetails.litDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.litDetails.standards + ', ';
			}
			if($scope.essentialDetails.mathDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.mathDetails.standards + ', ';
			}
			if($scope.essentialDetails.scienceDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.scienceDetails.standards + ', ';
			}
			if($scope.essentialDetails.ssDetails.standards !== undefined){
				$scope.essentialDetails.overallStandards += $scope.essentialDetails.ssDetails.standards + ', ';
			}
			if(typeof $scope.essentialDetails.otherSubject !== 'undefined'){
				if(typeof $scope.essentialDetails.otherSubject[0] !== 'undefined'){
					if($scope.essentialDetails.otherSubject[0].standards !== undefined){
						$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[0].standards + ', ';
					}
				}
				if(typeof $scope.essentialDetails.otherSubject[1] !== 'undefined'){
					if($scope.essentialDetails.otherSubject[1].standards !== undefined){
						$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[1].standards + ', ';
					}
				}
				if(typeof $scope.essentialDetails.otherSubject[2] !== 'undefined'){
					if($scope.essentialDetails.otherSubject[2].standards !== undefined){
						$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[2].standards + ', ';
					}
				}
				if(typeof $scope.essentialDetails.otherSubject[3] !== 'undefined'){
					if($scope.essentialDetails.otherSubject[3].standards !== undefined){
						$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[3].standards + ', ';
					}
				}
				if(typeof $scope.essentialDetails.otherSubject[4] !== 'undefined'){
					if($scope.essentialDetails.otherSubject[4].standards !== undefined){
						$scope.essentialDetails.overallStandards += $scope.essentialDetails.otherSubject[4].standards + ', ';
					}
				}

			}

			$scope.essentialDetails.overallStandards = $scope.essentialDetails.overallStandards.slice(0, -2);

			var project = new Projects ({
				name: this.name,
				created: this.created,
				user: this.user,
				status: this.status,
				isPublic: this.isPublic,
				minGrade: this.minGrade,
				maxGrade: this.maxGrade,
				ask: this.ask,
				imagine: this.imagine,
				essentialDetails: this.essentialDetails,
				rating: null
			});

		$scope.additionalSubjects = ['Dance', 'English Language Development', 'Gifted', 'Health Education', 'Music', 'Physical Education',
		'Special Skills', 'Technology', 'Theatre', 'Visual Art'];

			// Redirect after save
			project.$save(function(response) {

				// Start upload of picture

				if($scope.uploaderC.queue.length > 0) {

					$scope.uploaderC.queue[0].url = '/api/projects/picture/' + response._id;
					$scope.uploaderC.uploadAll();
				}

				// Clear form fields
				$scope.name = '';

				$location.path('projects/' + response._id);

			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});

		};

		// Remove existing Project
		$scope.remove = function( project ) {
			if ( project ) { project.$remove();

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

		$scope.CombineStandards = function(){
			$scope.project.essentialDetails.overallStandards = $scope.project.essentialDetails.litDetails[0].standards + ', ' + $scope.project.essentialDetails.mathDetails[0].standards + ', ' + $scope.project.essentialDetails.scienceDetails[0].standards + ', ' + $scope.project.essentialDetails.ssDetails[0].standards;
		};

		// Update existing Project
		$scope.update = function() {
            console.log('In $scope.update');

			var project = $scope.project;

			project.imagine.plan = '';

			project.$update(function() {

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

			if ($scope.uploader.queue.length > 0) {
				$scope.uploader.queue[0].url = '/api/projects/picture/' + project._id;
				$scope.uploader.uploadAll();
			}
		};

		// Find a list of Projects
		$scope.find = function() {
			$scope.projects = Projects.query();
		};

		// Find existing Project
		$scope.findOne = function() {
			$scope.project = Projects.get({
				projectId: $stateParams.projectId
			});

		};

		// Called after the user selected a new picture file
		$scope.uploader.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.project.imagine.plan = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

		$scope.linkify = function(link) {
			return $sce.trustAsHtml(linkify.normal(link));
		};

		$scope.uploaderC.onAfterAddingFile = function (fileItem) {
			if ($window.FileReader) {
				var fileReader = new FileReader();
				fileReader.readAsDataURL(fileItem._file);

				fileReader.onload = function (fileReaderEvent) {
					$timeout(function () {
						$scope.imageURL = fileReaderEvent.target.result;
					}, 0);
				};
			}
		};

/*	-------------------------------------Star Rating Stuff-------------------------------------- */

		//an array containing the name of the glyphicon to use for each star
		$scope.glyphs = new Array(
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty',
			'gold glyphicon glyphicon-star-empty'
		);

		/*
			Runs when a star glyphicon is hovered into. It sets all the stars up to the current one
			to have the filled-in star glyphicon.
		*/
		$scope.rating_hover = function(num){
			for(var i = 0; i < num; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star';
			}
			for(i = num; i < 5; i++){
				$scope.glyphs[i] = 'gold glyphicon glyphicon-star-empty';
			}
		};

		//Runs when a star glyphicon is hovered out of. Resets the  stars' highlighing to the current rating
		$scope.reset_hover = function(){
			$scope.rating_hover($scope.rating);
		};

		//Prints out user's current rating of the project
		$scope.getMyRating = function(){

			if ($scope.project.rating && $scope.project.rating.ratings ){
				var rater = $scope.project.rating.ratings.filter(isRater)[0];
				console.log(rater);
				if (typeof rater === 'undefined'){
					$scope.rating = 0;	//current rating
					return 'You haven\'t yet rated this project. Give it a couple of stars?';
				}
				$scope.rating = rater.num;
				$scope.reset_hover();
				return ('Your currently rate this project at ' + rater.num + ' stars');
			}
			$scope.rating = 0;	//current rating
			return 'This project has not yet been rated. Give it a couple of stars?';

		};

        // Function to find the current rater
        var isRater = function(value){
			return value.reviewer === $scope.authentication.user._id;
        };

		//Changes the user's rating of the project
		$scope.rate = function(){
			console.log('In $scope.rate');
			if(!$scope.project.rating){
				$scope.project.rating = {
					ratings : [
						{
							num: $scope.rating,
							reviewer: $scope.authentication.user._id
						}
					],
					avg_rating : $scope.rating
				};
			} else {
                var rater = $scope.project.rating.ratings.filter(isRater)[0];
                var length = $scope.project.rating.ratings.length;
				var rateToRemove = 0;

                var newLength = length + 1;

                if(length === 0)
                {
                    $scope.project.rating.avg_rating = 0;
                }

				if(typeof rater !== 'undefined') {
                    rateToRemove = rater.num;
                    var rateIndex = $scope.project.rating.ratings.indexOf(rater);
                    $scope.project.rating.ratings.splice(rateIndex, 1);
                    newLength -= 1;
                }

				$scope.project.rating.avg_rating = ($scope.project.rating.avg_rating * length + $scope.rating - rateToRemove)/(newLength);

				$scope.project.rating.ratings.push({
						num: $scope.rating,
						reviewer: $scope.authentication.user._id
				});
			}
			$scope.update();

		};

	}
]);
<|endoftext|>


<commit_before>var worker = {};

/**
 * Wraps a Java JsonMessage.
 */
function wrap_message(jmessage) {
  var message = {};
  message.__jmessage = jmessage;
  message.id = jmessage.id();
  message.body = JSON.parse(jmessage.body().encode());
  message.tag = jmessage.tag();
  message.parent = jmessage.parent();
  message.ancestor = jmessage.ancestor();
  message.source = jmessage.source();
  message.auditor = jmessage.auditor();
  message.copy = function() {
    return wrap_message(jmessage.copy());
  }
  return message;
}

worker.Worker = function() {

  var that = this;
  var jworker = new net.kuujo.vertigo.component.worker.DefaultWorker(__jvertx, __jcontainer, new net.kuujo.vertigo.context.WorkerContext(__jcontainer.config()));

  this.start = function(handler) {
    if (handler) {
      handler = adaptAsyncResultHandler(handler, function(result) {
        return that;
      });
      jworker.start(handler);
    }
    else {
      jworker.start();
    }
    return that;
  }

  this.messageHandler = function(handler) {
    jworker.messageHandler(function(jmessage) {
      handler(wrap_message(jmessage));
    });
    return that;
  }

  this.emit = function() {
    var args = Array.prototype.slice.call(arguments);
    var data = getArgValue('object', args);
    var tag = getArgValue('string', args);
    jworker.emit(new org.vertx.java.core.json.JsonObject(JSON.stringify(data)), tag);
    return that;
  }

  this.ack = function(message) {
    jworker.ack(message.__jmessage);
    return that;
  }

  this.fail = function(message, failMessage) {
    jworker.fail(message.__jmessage, failMessage);
    return that;
  }

}

module.exports = worker;
<commit_msg>Clean up worker.js.<commit_after>/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
load('vertx/helpers.js');

var worker = {};

/**
 * Wraps a Java JsonMessage.
 */
function wrap_message(jmessage) {
  var message = {};
  message.__jmessage = jmessage;
  message.id = jmessage.id();
  message.body = JSON.parse(jmessage.body().encode());
  message.tag = jmessage.tag();
  message.parent = jmessage.parent();
  message.ancestor = jmessage.ancestor();
  message.source = jmessage.source();
  message.auditor = jmessage.auditor();
  message.copy = function() {
    return wrap_message(jmessage.copy());
  }
  return message;
}

/**
 * A basic worker.
 */
worker.Worker = function() {

  var that = this;
  var jworker = new net.kuujo.vertigo.component.worker.BasicWorker(__jvertx, __jcontainer, net.kuujo.vertigo.context.WorkerContext.fromJson(__jcontainer.config()));

  var config = jworker.config();
  if (config != null) {
    this.config = JSON.parse(config.encode());
  }
  else {
    this.config = {};
  }

  /**
   * Starts the worker.
   */
  this.start = function(handler) {
    if (handler) {
      handler = adaptAsyncResultHandler(handler, function(result) {
        return that;
      });
      jworker.start(handler);
    }
    else {
      jworker.start();
    }
    return that;
  }

  /**
   * Sets a message handler on the worker.
   */
  this.messageHandler = function(handler) {
    jworker.messageHandler(function(jmessage) {
      handler(wrap_message(jmessage));
    });
    return that;
  }

  /**
   * Emits a message.
   */
  this.emit = function(data) {
    var args = Array.prototype.slice.call(arguments);
    args.shift();
    var tag = getArgValue('string', args);
    if (typeof(data) != 'object') {
      throw 'Invalid data type for emit()';
    }
    else {
      jworker.emit(new org.vertx.java.core.json.JsonObject(JSON.stringify(data)), tag);
    }
    return that;
  }

  /**
   * Acks a message.
   */
  this.ack = function(message) {
    jworker.ack(message.__jmessage);
    return that;
  }

  /**
   * Fails a message.
   */
  this.fail = function(message, failMessage) {
    jworker.fail(message.__jmessage, failMessage);
    return that;
  }

}

module.exports = worker;
<|endoftext|>


<commit_before>/**
 * @author Alexey Kuzmin <alexey@alexeykuzmin.com>
 * @fileoverview Promise based wrapper for Chrome Extension API.
 * @see https://developer.chrome.com/extensions/api_index
 * @license MIT
 * @version 2.0.0
 */

;(function(global) {
  'use strict';

  let apiGuy = {
    /**
     * @param {!Object} apiObject
     * @param {string} methodName
     * @param {Arguments} callArguments Arguments to be passes to method call.
     */
    callMethod(apiObject, methodName, callArguments) {
      let originalMethod = apiObject[methodName];
      let callArgumentsArray = Array.from(callArguments);

      return new Promise((resolve, reject) => {
        let callback = apiGuy.processResponse_.bind(null, resolve, reject);
        callArgumentsArray.push(callback);
        originalMethod.apply(apiObject, callArgumentsArray);
      });
    },

    /**
     * @param {!Function} callback
     * @param {!Function} errback
     * @param {...} var_args Response from Extension API.
     * @private
     */
    processResponse_(callback, errback, var_args) {
      let error = global.chrome.runtime.lastError;
      if (typeof error == 'object') {
        errback(new Error(error.message));
        return;
      }

      /** @type {*|Array.<*>} */
      let response = Array.from(arguments).slice(2);

      if (response.length < 2)
        response = response[0];  // undefined if response is empty

      callback(response);
    }
  };

  let wrapGuy = {
    /**
     * @param {!Object} api API object to wrap.
     * @return {!Object}
     */
    wrapApi(api) {
      return wrapGuy.wrapObject_(api);
    },

    /**
     * Returns true if |apiEntry| is an API Event object,
     * returns false otherwise.
     * @param {!Object} apiEntry
     * @return {boolean}
     * @private
     */
    isApiEvent_(apiEntry) {
      var entryPrototype = Object.getPrototypeOf(apiEntry);
      return (entryPrototype !== Object &&
          entryPrototype.constructor.name === 'Event');
    },

    /**
     * Returns true if function with given name looks like constructor,
     * returns false otherwise.
     * @param {string} functionName
     * @return {boolean}
     * @private
     */
    isConstructor_(functionName) {
      let firstLetter = functionName[0];
      return firstLetter == firstLetter.toUpperCase();
    },

    /**
     * Wraps API object.
     * @param {!Object} apiObject
     * @return {!Object}
     * @private
     */
    wrapObject_(apiObject) {
      let wrappedObject = {};

      for (let keyName of Object.keys(apiObject)) {
        wrapGuy.wrapObjectField_(wrappedObject, apiObject, keyName);
      }

      return wrappedObject;
    },

    /**
     * Wraps single object field.
     * @param {!Object} wrappedObject
     * @param {!Object} apiObject
     * @param {string} keyName
     * @return {?}
     * @private
     */
    wrapObjectField_(wrappedObject, apiObject, keyName) {
      let apiEntry = apiObject[keyName];
      let entryType = typeof apiEntry;
      let value = null;

      if (entryType == 'function' && !wrapGuy.isConstructor_(keyName))
        value = wrapGuy.wrapMethod_(apiObject, keyName);
      else if (entryType == 'object' && !wrapGuy.isApiEvent_(apiEntry))
        value = wrapGuy.wrapObject_(apiEntry);

      if (value)
        wrappedObject[keyName] = value;
    },

    /**
     * Wraps API method.
     * @param {!Object} apiObject
     * @param {string} methodName
     * @return {!Function}
     * @private
     */
    wrapMethod_(apiObject, methodName) {
      return function() {
        return apiGuy.callMethod(apiObject, methodName, arguments);
      }
    }
  };

  let chromise = wrapGuy.wrapApi(global.chrome);

  global.chromise = chromise;

}(window));
<commit_msg>Use rest parameters when processing API response<commit_after>/**
 * @author Alexey Kuzmin <alexey@alexeykuzmin.com>
 * @fileoverview Promise based wrapper for Chrome Extension API.
 * @see https://developer.chrome.com/extensions/api_index
 * @license MIT
 * @version 2.0.0
 */

;(function(global) {
  'use strict';

  let apiGuy = {
    /**
     * @param {!Object} apiObject
     * @param {string} methodName
     * @param {Arguments} callArguments Arguments to be passes to method call.
     */
    callMethod(apiObject, methodName, callArguments) {
      let originalMethod = apiObject[methodName];
      let callArgumentsArray = Array.from(callArguments);

      return new Promise((resolve, reject) => {
        let callback = apiGuy.processResponse_.bind(null, resolve, reject);
        callArgumentsArray.push(callback);
        originalMethod.apply(apiObject, callArgumentsArray);
      });
    },

    /**
     * @param {!Function} callback
     * @param {!Function} errback
     * @param {!Array} response Response from Extension API.
     * @private
     */
    processResponse_(callback, errback, ...response) {
      let error = global.chrome.runtime.lastError;
      if (typeof error == 'object') {
        errback(new Error(error.message));
        return;
      }

      if (response.length < 2)
        response = response[0];  // undefined if response is empty

      callback(response);
    }
  };

  let wrapGuy = {
    /**
     * @param {!Object} api API object to wrap.
     * @return {!Object}
     */
    wrapApi(api) {
      return wrapGuy.wrapObject_(api);
    },

    /**
     * Returns true if |apiEntry| is an API Event object,
     * returns false otherwise.
     * @param {!Object} apiEntry
     * @return {boolean}
     * @private
     */
    isApiEvent_(apiEntry) {
      var entryPrototype = Object.getPrototypeOf(apiEntry);
      return (entryPrototype !== Object &&
          entryPrototype.constructor.name === 'Event');
    },

    /**
     * Returns true if function with given name looks like constructor,
     * returns false otherwise.
     * @param {string} functionName
     * @return {boolean}
     * @private
     */
    isConstructor_(functionName) {
      let firstLetter = functionName[0];
      return firstLetter == firstLetter.toUpperCase();
    },

    /**
     * Wraps API object.
     * @param {!Object} apiObject
     * @return {!Object}
     * @private
     */
    wrapObject_(apiObject) {
      let wrappedObject = {};

      for (let keyName of Object.keys(apiObject)) {
        wrapGuy.wrapObjectField_(wrappedObject, apiObject, keyName);
      }

      return wrappedObject;
    },

    /**
     * Wraps single object field.
     * @param {!Object} wrappedObject
     * @param {!Object} apiObject
     * @param {string} keyName
     * @return {?}
     * @private
     */
    wrapObjectField_(wrappedObject, apiObject, keyName) {
      let apiEntry = apiObject[keyName];
      let entryType = typeof apiEntry;
      let value = null;

      if (entryType == 'function' && !wrapGuy.isConstructor_(keyName))
        value = wrapGuy.wrapMethod_(apiObject, keyName);
      else if (entryType == 'object' && !wrapGuy.isApiEvent_(apiEntry))
        value = wrapGuy.wrapObject_(apiEntry);

      if (value)
        wrappedObject[keyName] = value;
    },

    /**
     * Wraps API method.
     * @param {!Object} apiObject
     * @param {string} methodName
     * @return {!Function}
     * @private
     */
    wrapMethod_(apiObject, methodName) {
      return function() {
        return apiGuy.callMethod(apiObject, methodName, arguments);
      }
    }
  };

  let chromise = wrapGuy.wrapApi(global.chrome);

  global.chromise = chromise;

}(window));
<|endoftext|>


<commit_before>/**
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-tidoop (FI-WARE project).
 *
 * fiware-tidoop is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
 * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 * fiware-tidoop is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with fiware-tidoop. If not, see
 * http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License please contact with
 * francisco dot romerobueno at telefonica dot com
 */

/**
 * Command runner.
 *
 * Author: frb
 */

// Module dependencies
var spawn = require('child_process').spawn;

function run(cmd, params, callback) {
    var execution = spawn(cmd, params);
    var result = '';

    execution.stdout.on('data', function (data) {
        result += 'stdout: ' + data.toString();
    });

    execution.stderr.on('data', function (data) {
        result += 'stderr: ' + data.toString();
    });

    execution.on('close', function (code) {
        return callback(null, result);
    });
} // run

module.exports = {
    run: run
} // module.exports
<commit_msg>ADD different stderr and stdout accumulator strings in the cmd runner<commit_after>/**
 * Copyright 2015 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-tidoop (FI-WARE project).
 *
 * fiware-tidoop is free software: you can redistribute it and/or modify it under the terms of the GNU Affero
 * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 * fiware-tidoop is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with fiware-tidoop. If not, see
 * http://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License please contact with
 * francisco dot romerobueno at telefonica dot com
 */

/**
 * Command runner.
 *
 * Author: frb
 */

// Module dependencies
var spawn = require('child_process').spawn;

function run(cmd, params, callback) {
    var execution = spawn(cmd, params);
    var resStdout = '';
    var resStderr = '';

    execution.stdout.on('data', function (data) {
        resStdout += data.toString();
    });

    execution.stderr.on('data', function (data) {
        resStderr += + data.toString();
    });

    execution.on('close', function (code) {
        return callback(null, resStdout.length == 0 ? null : resStdout);
    });
} // run

module.exports = {
    run: run
} // module.exports
<|endoftext|>


<commit_before>/*************************************************************************
 *   Copyright (C) 2011-2013 by Paul-Louis Ageneau                       *
 *   paul-louis (at) ageneau (dot) org                                   *
 *                                                                       *
 *   This file is part of TeapotNet.                                     *
 *                                                                       *
 *   TeapotNet is free software: you can redistribute it and/or modify   *
 *   it under the terms of the GNU Affero General Public License as      *
 *   published by the Free Software Foundation, either version 3 of      *
 *   the License, or (at your option) any later version.                 *
 *                                                                       *
 *   TeapotNet is distributed in the hope that it will be useful, but    *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the        *
 *   GNU Affero General Public License for more details.                 *
 *                                                                       *
 *   You should have received a copy of the GNU Affero General Public    *
 *   License along with TeapotNet.                                       *
 *   If not, see <http://www.gnu.org/licenses/>.                         *
 *************************************************************************/

function listDirectory(url, object, showButtons) {

	$(object).empty();

	if(showButtons) {
		var location = url.split('?')[0];
		//var parentLink = (location[location.length-1] == '/' ? '..' : '.');
		$(object)
			//.append(' '+data.length+' files')
			//.append('')
			.append('');

		$(object).find('a.refreshlink').click(function() {
			listDirectory(url, object, showButtons);
			return false;
		});
	}

	$(object).append('

');

	listDirectoryRec(url, object);
}

function listDirectoryRec(url, object) {
	var table = $(object).find('table.files');
	var next = table.find('tr').length;

	$.ajax({
		url: url.appendParam("next", next),
		dataType: 'json',
		timeout: 300000
	})
	.done(function(data) {
		$(object).find('.gifloading').remove();

		if(data && data.length > 0) {

			if(table.length == 0) {
				$(object).append('

');
				table = $(object).find('table.files');
			}

			for(var i=0; i<data.length; i++) {
				var resource = data[i];

				var existing = table.find("td.filename:contains('"+resource.name.escape()+"')").parent();
				if(existing.length > 0) {
					if(parseInt(existing.find('td.time').text()) > resource.time) continue;
					existing.hide();
				}

				var link = '/file/' + resource.digest;
				var line;
				if(resource.type == "directory") {
					line = '
';
					line+= '	';
					line+= ''+resource.name.escape()+'	';
					line+= '	';
					line+= ''+formatTime(resource.time).escape()+'	';
					line+= ''+resource.time+'	';
					line+= '	';
					line+= '
';
				}
				else {
					var pos = resource.name.escape().lastIndexOf('.');
					var extension = (pos > 0 ? resource.name.escape().substring(pos+1,resource.name.escape().length) : '');
					var isPlayable = (resource.type != "directory") && isPlayableResource(resource.name);

					line = '
';
					line+= '	';
					line+= ''+extension.toUpperCase()+' <a href="'+link.escape()+(isPlayable && deviceAgent.indexOf('android') < 0 ? '?play=1' : '')+'">'+resource.name.escape()+'	';
					line+= ''+formatBytes(resource.size, 2)+'	';
					line+= ''+formatTime(resource.time).escape()+'	';
					line+= ''+resource.time+'	';
					line+= '';
					if(isPlayable) line+= '';
					line+= '	';
					line+= '
';
				}
				table.append(line);

				if(resource.name.length > 0 && (resource.name[0] == '_' || resource.name[0] == '.'))
					table.find('tr:last').hide();
			}

			table.find('tr').css('cursor', 'pointer').click(function() {
				window.location.href = $(this).find('a').attr('href');
			});

			// Order files
			table.html(table.find('tr').detach().sort(function(a,b){
				if($(a).hasClass("directory") && !$(b).hasClass("directory")) return false;
				if($(b).hasClass("directory") && !$(a).hasClass("directory")) return true;
				return $(a).find(".filename a").text() > $(b).find(".filename a").text();
			}));

			listDirectoryRec(url, object);
		}
		else {
			if(table.find('tr:visible').length == 0) {
				$(object).append('
No files
');
			}
		}
	})
	.fail(function(jqXHR, textStatus) {
		$(object).find('.gifloading').remove();

		if(table.find('tr:visible').length == 0) {
			$(object).append('
Unable to access files
');
		}
	});
}

function listFileSelector(url, object, input, inputName, parents) {

	$(object).html('');

	$.ajax({
		url: url,
		dataType: 'json',
		timeout: 30000
	})
	.done(function(data) {
		if(!data) data = [];

		$(object).html('
Select a file
')

		if(parents.length > 0) {
			$(object)
				.append(' '+data.length+' files')
				.append('')
				.find('a.parentlink').click(function() {
					var parentUrl = parents.pop();
					listFileSelector(parentUrl, object, input, inputName, parents);
					return false;
				});
		}

		$(object)
			.append('')
			.find('a.refreshlink').click(function() {
				listFileSelector(url, object, input, inputName, parents);
				return false;
			});

		//$(object).append('Choose another file');

		if(UrlUpload)
		{
			$(object).append('<form id="uploadform" action="'+UrlUpload+'" method="post" enctype="mutipart/form-data"><input type="hidden" name="token" value="'+TokenDirectory+'"><input type="file" id="selector_file" name="selector_file" size="30"></form>');
			$('#selector_file')
				.css('visibility', 'hidden').css('display', 'inline').css('width', '0px').css('margin', '0px').css('padding', '0px')
				.after('Other file')
				.change(function() {
					$(object).children().hide();
					$(object).append('Please wait...');

					$('#uploadform').ajaxSubmit({
						timeout: 600000,
						dataType: 'json',
						error: function() {
							alert('Unable to send the file.');
							$(inputName).val("").change();
							$(input).val("").change();
							$(object).remove();
						},
						success: function(resources) {
							if(resources != null && resources.length > 0)
							{
								var resource = resources[0];
								$(inputName).val(resource.name).change();
								$(input).val(resource.digest).change();
								$(object).remove();
							}
						}
					});
				});
		}

		$(object)
			.append('Cancel')
			.find('a.quitlink').click(function() {
				$(inputName).val("").change();
				$(input).val("").change();
				$(object).remove();
				return false;
			});

		$(object).append('

');
		var table = $(object).find('table');

		for(var i=0; i<data.length; i++) {
			var resource = data[i];

			var line = '
';
			var func;
			(function(resource) { // copy resource (only the reference is passed to callbacks)

			  	if(resource.name.length > 0 && (resource.name[0] == '_' || resource.name[0] == '.'))
					if(resource.name == "_upload") resource.name = "Sent files";
					else return;

				if(resource.type == "directory") {
					line+= '	';
					line+= ''+resource.name.escape()+'	';

					func = function() {
						var link = "/file/" + resource.digest + "?json";
						parents.push(url);
						listFileSelector(link, object, input, inputName, parents);
						return false;
					};
				}
				else {
					line+= '	';
					line+= ''+resource.name.escape()+'	';

					func = function() {
						$(inputName).val(resource.name).change();
						$(input).val(resource.digest).change();
						$(object).remove();
						return false;
					};
				}
			})(resource);
			line+= '
';
			table.append(line);
			table.find('tr:last').click(func).css('cursor', 'pointer');
			table.find('tr:last a').click(func);
		}
	})
	.fail(function(jqXHR, textStatus) {
		$(object)
			.html('')

		if(parents.length > 0) {
			$(object)
				.append('0 files')
				.append('')
				.find('a.parentlink').click(function() {
					var parentUrl = parents.pop();
					listFileSelector(parentUrl, object, input, inputName, parents);
					return false;
				});
		}

		$(object)
			.append('Retry')
			.append('Cancel')
			.append('
Unable to access files
')
			.find('a.refreshlink').click(function() {
				listFileSelector(url, object, input, inputName, parents);
				return false;
			})
			.find('a.quitlink').click(function() {
				$(inputName).val("").change();
				$(input).val("").change();
				$(object).remove();
				return false;
			});
	});
}

function createFileSelector(url, object, input, inputName)
{
	if($(object).html()) {
		$(object).html("");
		$(inputName).val("").change();
		$(input).val("").change();
		return;
	}

	$(object).show();
	$(object).html('

');
	var div = $(object).find('div');
	listFileSelector(url, div, input, inputName, []);
}

function isPlayableResource(fileName)
{
	return (isAudio(fileName) || isVideo(fileName));
}

function isAudio(fileName)
{
	var regexp = new RegExp("(mp3|ogg|ogga|flac|wav|ape|aac|m4a|mp4a|wma)$","i");
	return regexp.test(fileName);
}

function isVideo(fileName)
{
	var regexp = new RegExp("(avi|mkv|ogv|ogx|ogm|wmv|asf|flv|mpg|mpeg|mp4|m4v|mov|3gp|3g2|divx|xvid|rm|rv)$","i");
	return regexp.test(fileName);
}

<commit_msg>Disabled refresh link<commit_after>/*************************************************************************
 *   Copyright (C) 2011-2013 by Paul-Louis Ageneau                       *
 *   paul-louis (at) ageneau (dot) org                                   *
 *                                                                       *
 *   This file is part of TeapotNet.                                     *
 *                                                                       *
 *   TeapotNet is free software: you can redistribute it and/or modify   *
 *   it under the terms of the GNU Affero General Public License as      *
 *   published by the Free Software Foundation, either version 3 of      *
 *   the License, or (at your option) any later version.                 *
 *                                                                       *
 *   TeapotNet is distributed in the hope that it will be useful, but    *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of          *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the        *
 *   GNU Affero General Public License for more details.                 *
 *                                                                       *
 *   You should have received a copy of the GNU Affero General Public    *
 *   License along with TeapotNet.                                       *
 *   If not, see <http://www.gnu.org/licenses/>.                         *
 *************************************************************************/

function listDirectory(url, object, showButtons) {

	$(object).empty();

	if(showButtons) {
		var location = url.split('?')[0];
		//var parentLink = (location[location.length-1] == '/' ? '..' : '.');
		//$(object)
		//	.append(' '+data.length+' files')
		//	.append('')
		//	.append('');
		//	.find('a.refreshlink').click(function() {
		//		listDirectory(url, object, showButtons);
		//		return false;
		//	});
	}

	$(object).append('

');

	listDirectoryRec(url, object);
}

function listDirectoryRec(url, object) {
	var table = $(object).find('table.files');
	var next = table.find('tr').length;

	$.ajax({
		url: url.appendParam("next", next),
		dataType: 'json',
		timeout: 300000
	})
	.done(function(data) {
		$(object).find('.gifloading').remove();

		if(data && data.length > 0) {

			if(table.length == 0) {
				$(object).append('

');
				table = $(object).find('table.files');
			}

			for(var i=0; i<data.length; i++) {
				var resource = data[i];

				var existing = table.find("td.filename:contains('"+resource.name.escape()+"')").parent();
				if(existing.length > 0) {
					if(parseInt(existing.find('td.time').text()) > resource.time) continue;
					existing.hide();
				}

				var link = '/file/' + resource.digest;
				var line;
				if(resource.type == "directory") {
					line = '
';
					line+= '	';
					line+= ''+resource.name.escape()+'	';
					line+= '	';
					line+= ''+formatTime(resource.time).escape()+'	';
					line+= ''+resource.time+'	';
					line+= '	';
					line+= '
';
				}
				else {
					var pos = resource.name.escape().lastIndexOf('.');
					var extension = (pos > 0 ? resource.name.escape().substring(pos+1,resource.name.escape().length) : '');
					var isPlayable = (resource.type != "directory") && isPlayableResource(resource.name);

					line = '
';
					line+= '	';
					line+= ''+extension.toUpperCase()+' <a href="'+link.escape()+(isPlayable && deviceAgent.indexOf('android') < 0 ? '?play=1' : '')+'">'+resource.name.escape()+'	';
					line+= ''+formatBytes(resource.size, 2)+'	';
					line+= ''+formatTime(resource.time).escape()+'	';
					line+= ''+resource.time+'	';
					line+= '';
					if(isPlayable) line+= '';
					line+= '	';
					line+= '
';
				}
				table.append(line);

				if(resource.name.length > 0 && (resource.name[0] == '_' || resource.name[0] == '.'))
					table.find('tr:last').hide();
			}

			table.find('tr').css('cursor', 'pointer').click(function() {
				window.location.href = $(this).find('a').attr('href');
			});

			// Order files
			table.html(table.find('tr').detach().sort(function(a,b){
				if($(a).hasClass("directory") && !$(b).hasClass("directory")) return false;
				if($(b).hasClass("directory") && !$(a).hasClass("directory")) return true;
				return $(a).find(".filename a").text() > $(b).find(".filename a").text();
			}));

			listDirectoryRec(url, object);
		}
		else {
			if(table.find('tr:visible').length == 0) {
				$(object).append('
No files
');
			}
		}
	})
	.fail(function(jqXHR, textStatus) {
		$(object).find('.gifloading').remove();

		if(table.find('tr:visible').length == 0) {
			$(object).append('
Unable to access files
');
		}
	});
}

function listFileSelector(url, object, input, inputName, parents) {

	$(object).html('');

	$.ajax({
		url: url,
		dataType: 'json',
		timeout: 30000
	})
	.done(function(data) {
		if(!data) data = [];

		$(object).html('
Select a file
')

		if(parents.length > 0) {
			$(object)
				.append(' '+data.length+' files')
				.append('')
				.find('a.parentlink').click(function() {
					var parentUrl = parents.pop();
					listFileSelector(parentUrl, object, input, inputName, parents);
					return false;
				});
		}

		//$(object)
		//	.append('')
		//	.find('a.refreshlink').click(function() {
		//		listFileSelector(url, object, input, inputName, parents);
		//		return false;
		//	});

		if(UrlUpload)
		{
			$(object).append('<form id="uploadform" action="'+UrlUpload+'" method="post" enctype="mutipart/form-data"><input type="hidden" name="token" value="'+TokenDirectory+'"><input type="file" id="selector_file" name="selector_file" size="30"></form>');
			$('#selector_file')
				.css('visibility', 'hidden').css('display', 'inline').css('width', '0px').css('margin', '0px').css('padding', '0px')
				.after('Other file')
				.change(function() {
					$(object).children().hide();
					$(object).append('Please wait...');

					$('#uploadform').ajaxSubmit({
						timeout: 600000,
						dataType: 'json',
						error: function() {
							alert('Unable to send the file.');
							$(inputName).val("").change();
							$(input).val("").change();
							$(object).remove();
						},
						success: function(resources) {
							if(resources != null && resources.length > 0)
							{
								var resource = resources[0];
								$(inputName).val(resource.name).change();
								$(input).val(resource.digest).change();
								$(object).remove();
							}
						}
					});
				});
		}

		$(object)
			.append('Cancel')
			.find('a.quitlink').click(function() {
				$(inputName).val("").change();
				$(input).val("").change();
				$(object).remove();
				return false;
			});

		$(object).append('

');
		var table = $(object).find('table');

		for(var i=0; i<data.length; i++) {
			var resource = data[i];

			var line = '
';
			var func;
			(function(resource) { // copy resource (only the reference is passed to callbacks)

			  	if(resource.name.length > 0 && (resource.name[0] == '_' || resource.name[0] == '.'))
					if(resource.name == "_upload") resource.name = "Sent files";
					else return;

				if(resource.type == "directory") {
					line+= '	';
					line+= ''+resource.name.escape()+'	';

					func = function() {
						var link = "/file/" + resource.digest + "?json";
						parents.push(url);
						listFileSelector(link, object, input, inputName, parents);
						return false;
					};
				}
				else {
					line+= '	';
					line+= ''+resource.name.escape()+'	';

					func = function() {
						$(inputName).val(resource.name).change();
						$(input).val(resource.digest).change();
						$(object).remove();
						return false;
					};
				}
			})(resource);
			line+= '
';
			table.append(line);
			table.find('tr:last').click(func).css('cursor', 'pointer');
			table.find('tr:last a').click(func);
		}
	})
	.fail(function(jqXHR, textStatus) {
		$(object)
			.html('')

		if(parents.length > 0) {
			$(object)
				.append('0 files')
				.append('')
				.find('a.parentlink').click(function() {
					var parentUrl = parents.pop();
					listFileSelector(parentUrl, object, input, inputName, parents);
					return false;
				});
		}

		$(object)
			//.append('Retry')
			.append('Cancel')
			.append('
Unable to access files
')
			//.find('a.refreshlink').click(function() {
			//	listFileSelector(url, object, input, inputName, parents);
			//	return false;
			//})
			.find('a.quitlink').click(function() {
				$(inputName).val("").change();
				$(input).val("").change();
				$(object).remove();
				return false;
			});
	});
}

function createFileSelector(url, object, input, inputName)
{
	if($(object).html()) {
		$(object).html("");
		$(inputName).val("").change();
		$(input).val("").change();
		return;
	}

	$(object).show();
	$(object).html('

');
	var div = $(object).find('div');
	listFileSelector(url, div, input, inputName, []);
}

function isPlayableResource(fileName)
{
	return (isAudio(fileName) || isVideo(fileName));
}

function isAudio(fileName)
{
	var regexp = new RegExp("(mp3|ogg|ogga|flac|wav|ape|aac|m4a|mp4a|wma)$","i");
	return regexp.test(fileName);
}

function isVideo(fileName)
{
	var regexp = new RegExp("(avi|mkv|ogv|ogx|ogm|wmv|asf|flv|mpg|mpeg|mp4|m4v|mov|3gp|3g2|divx|xvid|rm|rv)$","i");
	return regexp.test(fileName);
}

<|endoftext|>


<commit_before>const motel = require('../src/index');
const makeTest = require('./make-test');
const assert = require('assert');

makeTest('Catch an attribute mutation on root', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.setAttribute('data-vacancy', 'users/a');
  }, elmt);
  assert.deepEqual(results, [{ id: 'a' }]);
});

makeTest('Catch an attribute mutation on child', async function() {
  const elmt = document.createElement('div');
  const child = document.createElement('div');
  elmt.appendChild(child);
  const results = await vacancyTest('users/:id', undefined, () => {
    child.setAttribute('data-vacancy', 'users/b');
  }, elmt);
  assert.deepEqual(results, [{ id: 'b' }]);
});

makeTest('Catch an attribute mutation on grandchild', async function() {
  const elmt = document.createElement('div');
  const child = document.createElement('div');
  const grandchild = document.createElement('div');
  elmt.appendChild(child);
  child.appendChild(grandchild);
  const results = await vacancyTest('users/:id', undefined, () => {
    grandchild.setAttribute('data-vacancy', 'users/c');
  }, elmt);
  assert.deepEqual(results, [{ id: 'c' }]);
});

makeTest('Catch a child addition', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    const child = document.createElement('div');
    child.setAttribute('data-vacancy', 'users/sdf');
    elmt.appendChild(child);
  }, elmt);
  assert.deepEqual(results, [{ id: 'sdf' }]);
});

makeTest('Catch a grandchild addition', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    const child = document.createElement('div');
    const grandchild = document.createElement('div');
    child.appendChild(grandchild);
    grandchild.setAttribute('data-vacancy', 'users/hj');
    elmt.appendChild(child);
  }, elmt);
  assert.deepEqual(results, [{ id: 'hj' }]);
});

makeTest('Catch multiple attribute additions', async function() {
  const elmt = make('

');
  const results = await vacancyTest('users/:id', undefined, () => {
    let i = 0;
    for (const desc of elmt.querySelectorAll('div')) {
      desc.setAttribute('data-vacancy', `users/${i++}`);
    }
  }, elmt);
  assert.deepEqual(results, [
    { id: '0' },
    { id: '1' },
    { id: '2' },
  ]);
});

makeTest('Catch multiple node additions', async function() {
  const elmt = make();
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.innerHTML = `

    `;
  }, elmt);
  assert.deepEqual(results, [
    { id: '4' },
    { id: '5' },
    { id: '6' },
  ]);
});

makeTest('Catch nested node additions', async function() {
  const elmt = make();
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.innerHTML = `

    `;
  }, elmt);
  assert.deepEqual(results, [
    { id: '4' },
    { id: '5' },
    { id: '6' },
  ]);
});

makeTest('Catch nested attribute mutations', async function() {
  const elmt = make('');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.querySelector('.a').setAttribute('data-vacancy', 'users/a');
    elmt.querySelector('.b').setAttribute('data-vacancy', 'users/b');
  }, elmt);
  assert.deepEqual(results, [
    { id: 'a' },
    { id: 'b' },
  ]);
});

makeTest('Allow multiple sends', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', (params, send) => {
    send(1);
    send(2);
  }, () => {
    elmt.setAttribute('data-vacancy', 'users/a');
  }, elmt);
  assert.deepEqual(results, [1, 2]);
});

makeTest('Allow async sends', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', async function(params, send) {
    send(1);
    await wait(1);
    send(2);
  }, () => {
    elmt.setAttribute('data-vacancy', 'users/a');
  }, elmt);
  assert.deepEqual(results, [1, 2]);
});

makeTest('Allow JSON for multiple vacancies', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    const json = JSON.stringify(['users/a', 'users/b']);
    elmt.setAttribute('data-vacancy', json);
  }, elmt);
  assert.deepEqual(results, [{ id: 'a' }, { id: 'b' }]);
});

makeTest('Gracefully handle malformed JSON', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.setAttribute('data-vacancy', JSON.stringify(['users/a', 'users/b']) + '}}}');
  }, elmt);
  assert.deepEqual(results, []);
});

makeTest('De-dupe vacancies', async function() {
  const elmt = make('

');
  const results = await vacancyTest('users/:id', undefined, () => {
    for (const desc of elmt.querySelectorAll('div')) {
      desc.setAttribute('data-vacancy', 'users/a');
    }
  }, elmt);
  assert.deepEqual(results, [{ id: 'a' }]);
});

// ----------------------------------------

function make(html = '') {
  const el = document.createElement('div');
  el.innerHTML = html;
  return el;
}

function defaultHandler(params, send) {
  send(params);
}

function vacancyTest(pattern, handler = defaultHandler, trigger, el) {
  return new Promise(resolve => {
    const vacancies = motel();
    const output = [];
    vacancies.listen(pattern, handler);
    vacancies.subscribe(arg => output.push(arg));
    vacancies.connect(el);
    trigger();
    wait(100).then(() => {
      vacancies.disconnect();
      resolve(output);
    });
  });
}

function wait(t) {
  return new Promise(resolve => setTimeout(resolve, t));
}

async function autoExecute() {
  for (const button of document.querySelectorAll('button.run')) {
    button.click();
  }
}

autoExecute();
<commit_msg>Add unit test<commit_after>const motel = require('../src/index');
const makeTest = require('./make-test');
const assert = require('assert');

makeTest('Catch an attribute mutation on root', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.setAttribute('data-vacancy', 'users/a');
  }, elmt);
  assert.deepEqual(results, [{ id: 'a' }]);
});

makeTest('Catch an attribute mutation on child', async function() {
  const elmt = document.createElement('div');
  const child = document.createElement('div');
  elmt.appendChild(child);
  const results = await vacancyTest('users/:id', undefined, () => {
    child.setAttribute('data-vacancy', 'users/b');
  }, elmt);
  assert.deepEqual(results, [{ id: 'b' }]);
});

makeTest('Catch an attribute mutation on grandchild', async function() {
  const elmt = document.createElement('div');
  const child = document.createElement('div');
  const grandchild = document.createElement('div');
  elmt.appendChild(child);
  child.appendChild(grandchild);
  const results = await vacancyTest('users/:id', undefined, () => {
    grandchild.setAttribute('data-vacancy', 'users/c');
  }, elmt);
  assert.deepEqual(results, [{ id: 'c' }]);
});

makeTest('Catch a child addition', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    const child = document.createElement('div');
    child.setAttribute('data-vacancy', 'users/sdf');
    elmt.appendChild(child);
  }, elmt);
  assert.deepEqual(results, [{ id: 'sdf' }]);
});

makeTest('Catch a grandchild addition', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    const child = document.createElement('div');
    const grandchild = document.createElement('div');
    child.appendChild(grandchild);
    grandchild.setAttribute('data-vacancy', 'users/hj');
    elmt.appendChild(child);
  }, elmt);
  assert.deepEqual(results, [{ id: 'hj' }]);
});

makeTest('Catch multiple attribute additions', async function() {
  const elmt = make('

');
  const results = await vacancyTest('users/:id', undefined, () => {
    let i = 0;
    for (const desc of elmt.querySelectorAll('div')) {
      desc.setAttribute('data-vacancy', `users/${i++}`);
    }
  }, elmt);
  assert.deepEqual(results, [
    { id: '0' },
    { id: '1' },
    { id: '2' },
  ]);
});

makeTest('Catch multiple node additions', async function() {
  const elmt = make();
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.innerHTML = `

    `;
  }, elmt);
  assert.deepEqual(results, [
    { id: '4' },
    { id: '5' },
    { id: '6' },
  ]);
});

makeTest('Catch nested node additions', async function() {
  const elmt = make();
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.innerHTML = `

    `;
  }, elmt);
  assert.deepEqual(results, [
    { id: '4' },
    { id: '5' },
    { id: '6' },
  ]);
});

makeTest('Catch nested attribute mutations', async function() {
  const elmt = make('');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.querySelector('.a').setAttribute('data-vacancy', 'users/a');
    elmt.querySelector('.b').setAttribute('data-vacancy', 'users/b');
  }, elmt);
  assert.deepEqual(results, [
    { id: 'a' },
    { id: 'b' },
  ]);
});

makeTest('Allow multiple sends', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', (params, send) => {
    send(1);
    send(2);
  }, () => {
    elmt.setAttribute('data-vacancy', 'users/a');
  }, elmt);
  assert.deepEqual(results, [1, 2]);
});

makeTest('Allow async sends', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', async function(params, send) {
    send(1);
    await wait(1);
    send(2);
  }, () => {
    elmt.setAttribute('data-vacancy', 'users/a');
  }, elmt);
  assert.deepEqual(results, [1, 2]);
});

makeTest('Allow JSON for multiple vacancies', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    const json = JSON.stringify(['users/a', 'users/b']);
    elmt.setAttribute('data-vacancy', json);
  }, elmt);
  assert.deepEqual(results, [{ id: 'a' }, { id: 'b' }]);
});

makeTest('Gracefully handle malformed JSON', async function() {
  const elmt = document.createElement('div');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.setAttribute('data-vacancy', JSON.stringify(['users/a', 'users/b']) + '}}}');
  }, elmt);
  assert.deepEqual(results, []);
});

makeTest('De-dupe vacancies', async function() {
  const elmt = make('

');
  const results = await vacancyTest('users/:id', undefined, () => {
    for (const desc of elmt.querySelectorAll('div')) {
      desc.setAttribute('data-vacancy', 'users/a');
    }
  }, elmt);
  assert.deepEqual(results, [{ id: 'a' }]);
});

makeTest('Catch both an attribute mutation and a node addition', async function() {
  const elmt = make('');
  const results = await vacancyTest('users/:id', undefined, () => {
    elmt.setAttribute('data-vacancy', 'users/x');
    const i = elmt.querySelector('i');
    i.setAttribute('data-vacancy', 'users/a');
    i.innerHTML = '';
  }, elmt);
  assert.deepEqual(results, [{ id: 'x' }, { id: 'a' }, { id: 'b' }]);
});

// ----------------------------------------

function make(html = '') {
  const el = document.createElement('div');
  el.innerHTML = html;
  return el;
}

function defaultHandler(params, send) {
  send(params);
}

function vacancyTest(pattern, handler = defaultHandler, trigger, el) {
  return new Promise(resolve => {
    const vacancies = motel();
    const output = [];
    vacancies.listen(pattern, handler);
    vacancies.subscribe(arg => output.push(arg));
    vacancies.connect(el);
    trigger();
    wait(100).then(() => {
      vacancies.disconnect();
      resolve(output);
    });
  });
}

function wait(t) {
  return new Promise(resolve => setTimeout(resolve, t));
}

async function autoExecute() {
  for (const button of document.querySelectorAll('button.run')) {
    button.click();
  }
}

autoExecute();
<|endoftext|>


<commit_before>/**
	_moon.ContextualPopup_ is a popup window control with Moonstone visual styling
	applied.  It extends [enyo.Popup](#enyo.Popup) and is designed to be used with
	[moon.ContextualPopupDecorator](#moon.ContextualPopupDecorator).
*/
enyo.kind({
	name : "moon.ContextualPopup",
	kind : "enyo.Popup",

	//* @protected
	layoutKind : "ContextualLayout",
	classes    : "moon-body-text moon-contextual-popup",

	handlers: {
		onRequestShowPopup        : "requestShow",
		onRequestHidePopup        : "requestHide",
		onActivate                : "decorateActivateEvent",
		onRequestScrollIntoView   : "_preventEventBubble",
		onSpotlightContainerLeave : "onLeave"
	},
	//* @public
	published: {
		/**
			When true, spotlight cannot leave the constraints of the _moon.Popup_
			unless it is explicitly closed.
		*/
		spotlightModal: false,
		/**
			When false, _closeButton_ is hidden; when true, it is shown. When
			_showCloseButton_ is set to "auto" (the default), _closeButton_ is shown
			when _spotlightModal_ is true.
		*/
		showCloseButton: "auto"
	},
	//* @protected
	spotlight: "container",
	floating:true,
	/**
		Determines whether a scrim will appear when the popup is modal.
		Note that modal scrims are transparent, so you won't see them.
	*/
	scrimWhenModal: true,
	// Layout parameters

	//* Vertical flush layout margin
	vertFlushMargin:0,
	//* Horizontal flush layout margin
	horizFlushMargin:0,
	//* Popups wider than this value are considered wide (for layout purposes)
	widePopup: 200,
	//* Popups longer than this value are considered long (for layout purposes)
	longPopup: 200,
	//* Do not allow horizontal flush popups past spec'd amount of buffer space on left/right screen edge
	horizBuffer: 16,
	activator: null,
	tools: [
		{name: "client", classes: "moon-neutral moon-contextual-popup-client"},
		{name: "closeButton", kind: "moon.IconButton", icon: "closex", classes: "moon-popup-close", ontap: "closePopup", spotlight: false}
	],
	//* Creates chrome.
	initComponents: function() {
		this.createChrome(this.tools);
		this.inherited(arguments);
		this.eventsToCapture = enyo.clone(this.eventsToCapture);
		this.eventsToCapture.onSpotlightKeyDown = "capturedKeyDown";
	},
	//* Renders the contextual popup.
	render: function() {
		this.allowHtmlChanged();
		this.contentChanged();
		this.inherited(arguments);
	},
	//* Performs control-specific tasks before/after showing _moon.ContextualPopup_.
	requestShow: function(inSender, inEvent) {
		var n = inEvent.activator.hasNode();
		this.activator = inEvent.activator;
		if (n) {
			this.activatorOffset = this.getPageOffset(n);
		}
		this.show();
		this.configCloseButton();
		if (enyo.Spotlight.isSpottable(this)) {
			enyo.Spotlight.setPointerMode(false);
			enyo.Spotlight.spot(this);
		}
		return true;
	},
	decorateActivateEvent: function(inSender, inEvent) {
		inEvent.sentFromPopup = this;
	},
	getPageOffset: function(inNode) {
		// getBoundingClientRect returns top/left values which are relative to the viewport and not absolute
		var r = inNode.getBoundingClientRect();

		var pageYOffset = (window.pageYOffset === undefined) ? document.documentElement.scrollTop : window.pageYOffset;
		var pageXOffset = (window.pageXOffset === undefined) ? document.documentElement.scrollLeft : window.pageXOffset;
		var rHeight = (r.height === undefined) ? (r.bottom - r.top) : r.height;
		var rWidth = (r.width === undefined) ? (r.right - r.left) : r.width;

		return {top: r.top + pageYOffset, left: r.left + pageXOffset, height: rHeight, width: rWidth};
	},
	//* Dismisses popup if Escape keypress is detected
	keydown: function(inSender, inEvent) {
		if (this.showing && this.autoDismiss && inEvent.keyCode == 27 /* escape */) {
			enyo.Spotlight.spot(this.activator);
			this.hide();
		}
	},
	closePopup: function(inSender, inEvent) {
		enyo.Spotlight.spot(this.activator);
		this.$.closeButton.removeClass("pressed");
		this.hide();
	},
	//* Determines whether to display _closeButton_.
	configCloseButton: function() {
		if (this.showCloseButton === true || (this.spotlightModal && this.showCloseButton !== false)) {
			this.$.closeButton.show();
			this.$.closeButton.spotlight = true;
			this.addClass("reserve-close");
		} else {
			this.$.closeButton.hide();
			this.$.closeButton.spotlight = false;
			this.removeClass("reserve-close");
		}
	},
	contentChanged: function() {
		this.$.client.setContent(this.content);
	},
	allowHtmlChanged: function() {
		this.$.client.setAllowHtml(this.allowHtml);
	},
	//* Called when _this.spotlightModal_ changes.
	spotlightModalChanged: function() {
		this.configCloseButton();
	},
	//* Called when _this.showCloseButton_ changes.
	showCloseButtonChanged: function() {
		this.configCloseButton();
	},
	capturedKeyDown: function(inSender, inEvent) {
		if (inEvent.keyCode == 13) {
			this.downEvent = inEvent;
		}
		return this.modal;
	},
	onLeave: function(oSender, oEvent) {
		if (oEvent.originator == this) {
			enyo.Spotlight.spot(this.activator);
			this.hide();
		}
	},
	_preventEventBubble: function(inSender, inEvent) {
		return true;
	},
	showHideScrim: function(inShow) {
		if (this.floating && (this.scrim || (this.modal && this.scrimWhenModal))) {
			var scrim = this.getScrim();
			if (inShow && this.modal && this.scrimWhenModal) {
				// move scrim to just under the popup to obscure rest of screen
				var i = this.getScrimZIndex();
				this._scrimZ = i;
				scrim.showAtZIndex(i);
			} else {
				scrim.hideAtZIndex(this._scrimZ);
			}
			enyo.call(scrim, "addRemoveClass", [this.scrimClassName, scrim.showing]);
		}
	},
	getScrimZIndex: function() {
		// Position scrim directly below popup
		return this.findZIndex()-1;
	},
	getScrim: function() {
		// show a transparent scrim for modal popups if scrimWhenModal is true
		// if scrim is true, then show a regular scrim.
		if (this.modal && this.scrimWhenModal) {
			return moon.scrimTransparent.make();
		}
		return moon.scrim.make();
	},
	findZIndex: function() {
		// a default z value
		var z = this.defaultZ;
		if (this._zIndex) {
			z = this._zIndex;
		} else if (this.hasNode()) {
			// Re-use existing zIndex if it has one
			z = Number(enyo.dom.getComputedStyleValue(this.node, "z-index")) || z;
		}
		this._zIndex = z;
		return this._zIndex;
	},
	showingChanged: function() {
		this.inherited(arguments);
		this.showHideScrim(this.showing);
	}
});
<commit_msg>ContextualPopup should not have initial focus in pointer mode<commit_after>/**
	_moon.ContextualPopup_ is a popup window control with Moonstone visual styling
	applied.  It extends [enyo.Popup](#enyo.Popup) and is designed to be used with
	[moon.ContextualPopupDecorator](#moon.ContextualPopupDecorator).
*/
enyo.kind({
	name : "moon.ContextualPopup",
	kind : "enyo.Popup",

	//* @protected
	layoutKind : "ContextualLayout",
	classes    : "moon-body-text moon-contextual-popup",

	handlers: {
		onRequestShowPopup        : "requestShow",
		onRequestHidePopup        : "requestHide",
		onActivate                : "decorateActivateEvent",
		onRequestScrollIntoView   : "_preventEventBubble",
		onSpotlightContainerLeave : "onLeave"
	},
	//* @public
	published: {
		/**
			When true, spotlight cannot leave the constraints of the _moon.Popup_
			unless it is explicitly closed.
		*/
		spotlightModal: false,
		/**
			When false, _closeButton_ is hidden; when true, it is shown. When
			_showCloseButton_ is set to "auto" (the default), _closeButton_ is shown
			when _spotlightModal_ is true.
		*/
		showCloseButton: "auto"
	},
	//* @protected
	spotlight: "container",
	floating:true,
	/**
		Determines whether a scrim will appear when the popup is modal.
		Note that modal scrims are transparent, so you won't see them.
	*/
	scrimWhenModal: true,
	// Layout parameters

	//* Vertical flush layout margin
	vertFlushMargin:0,
	//* Horizontal flush layout margin
	horizFlushMargin:0,
	//* Popups wider than this value are considered wide (for layout purposes)
	widePopup: 200,
	//* Popups longer than this value are considered long (for layout purposes)
	longPopup: 200,
	//* Do not allow horizontal flush popups past spec'd amount of buffer space on left/right screen edge
	horizBuffer: 16,
	activator: null,
	tools: [
		{name: "client", classes: "moon-neutral moon-contextual-popup-client"},
		{name: "closeButton", kind: "moon.IconButton", icon: "closex", classes: "moon-popup-close", ontap: "closePopup", spotlight: false}
	],
	//* Creates chrome.
	initComponents: function() {
		this.createChrome(this.tools);
		this.inherited(arguments);
		this.eventsToCapture = enyo.clone(this.eventsToCapture);
		this.eventsToCapture.onSpotlightKeyDown = "capturedKeyDown";
	},
	//* Renders the contextual popup.
	render: function() {
		this.allowHtmlChanged();
		this.contentChanged();
		this.inherited(arguments);
	},
	//* Performs control-specific tasks before/after showing _moon.ContextualPopup_.
	requestShow: function(inSender, inEvent) {
		var n = inEvent.activator.hasNode();
		this.activator = inEvent.activator;
		if (n) {
			this.activatorOffset = this.getPageOffset(n);
		}
		this.show();
		this.configCloseButton();
		if (enyo.Spotlight.isSpottable(this)) {
			enyo.Spotlight.spot(this);
		}
		return true;
	},
	decorateActivateEvent: function(inSender, inEvent) {
		inEvent.sentFromPopup = this;
	},
	getPageOffset: function(inNode) {
		// getBoundingClientRect returns top/left values which are relative to the viewport and not absolute
		var r = inNode.getBoundingClientRect();

		var pageYOffset = (window.pageYOffset === undefined) ? document.documentElement.scrollTop : window.pageYOffset;
		var pageXOffset = (window.pageXOffset === undefined) ? document.documentElement.scrollLeft : window.pageXOffset;
		var rHeight = (r.height === undefined) ? (r.bottom - r.top) : r.height;
		var rWidth = (r.width === undefined) ? (r.right - r.left) : r.width;

		return {top: r.top + pageYOffset, left: r.left + pageXOffset, height: rHeight, width: rWidth};
	},
	//* Dismisses popup if Escape keypress is detected
	keydown: function(inSender, inEvent) {
		if (this.showing && this.autoDismiss && inEvent.keyCode == 27 /* escape */) {
			enyo.Spotlight.spot(this.activator);
			this.hide();
		}
	},
	closePopup: function(inSender, inEvent) {
		enyo.Spotlight.spot(this.activator);
		this.$.closeButton.removeClass("pressed");
		this.hide();
	},
	//* Determines whether to display _closeButton_.
	configCloseButton: function() {
		if (this.showCloseButton === true || (this.spotlightModal && this.showCloseButton !== false)) {
			this.$.closeButton.show();
			this.$.closeButton.spotlight = true;
			this.addClass("reserve-close");
		} else {
			this.$.closeButton.hide();
			this.$.closeButton.spotlight = false;
			this.removeClass("reserve-close");
		}
	},
	contentChanged: function() {
		this.$.client.setContent(this.content);
	},
	allowHtmlChanged: function() {
		this.$.client.setAllowHtml(this.allowHtml);
	},
	//* Called when _this.spotlightModal_ changes.
	spotlightModalChanged: function() {
		this.configCloseButton();
	},
	//* Called when _this.showCloseButton_ changes.
	showCloseButtonChanged: function() {
		this.configCloseButton();
	},
	capturedKeyDown: function(inSender, inEvent) {
		if (inEvent.keyCode == 13) {
			this.downEvent = inEvent;
		}
		return this.modal;
	},
	onLeave: function(oSender, oEvent) {
		if (oEvent.originator == this) {
			enyo.Spotlight.spot(this.activator);
			this.hide();
		}
	},
	_preventEventBubble: function(inSender, inEvent) {
		return true;
	},
	showHideScrim: function(inShow) {
		if (this.floating && (this.scrim || (this.modal && this.scrimWhenModal))) {
			var scrim = this.getScrim();
			if (inShow && this.modal && this.scrimWhenModal) {
				// move scrim to just under the popup to obscure rest of screen
				var i = this.getScrimZIndex();
				this._scrimZ = i;
				scrim.showAtZIndex(i);
			} else {
				scrim.hideAtZIndex(this._scrimZ);
			}
			enyo.call(scrim, "addRemoveClass", [this.scrimClassName, scrim.showing]);
		}
	},
	getScrimZIndex: function() {
		// Position scrim directly below popup
		return this.findZIndex()-1;
	},
	getScrim: function() {
		// show a transparent scrim for modal popups if scrimWhenModal is true
		// if scrim is true, then show a regular scrim.
		if (this.modal && this.scrimWhenModal) {
			return moon.scrimTransparent.make();
		}
		return moon.scrim.make();
	},
	findZIndex: function() {
		// a default z value
		var z = this.defaultZ;
		if (this._zIndex) {
			z = this._zIndex;
		} else if (this.hasNode()) {
			// Re-use existing zIndex if it has one
			z = Number(enyo.dom.getComputedStyleValue(this.node, "z-index")) || z;
		}
		this._zIndex = z;
		return this._zIndex;
	},
	showingChanged: function() {
		this.inherited(arguments);
		this.showHideScrim(this.showing);
	}
});
<|endoftext|>


<commit_before>import {
    Vessels
} from '/imports/api/vessels/vessels.coffee';

import './vessel.tpl.jade';

const EntityForm = require('/imports/api/EntityForm/EntityForm.js')

var db = Vessels;
var templateName = 'vessel';
var publicationName = 'vessel';
var sections = [{
    header: 'identificationSection',
    contents: [{
        key: 'name',
        value: 'Super vessel 8000'
    }, {
        key: 'flag',
        value: 'Germany'
    }, {
        key: 'type',
        value: 'rc',
        dropdownContainer: 'types'
    }, {
        key: 'callsign',
        value: '12341234'
    }, {
        key: 'eni',
        value: '12341234'
    }, {
        key: 'imo',
        value: '12341234'
    }, {
        key: 'mmsi',
        value: '12341234'
    }],
}, {
    header: 'visitSection',
    contents: [{
        key: 'lastVisit',
        value: '12341234'
    }, {
        key: 'nextVisitAfter',
        value: '12341234'
    }, {
        key: 'languages',
        value: '12341234'
    }, {
        key: 'comments',
        value: '12341234'
    }]
}]

new EntityForm(
    db,
    templateName,
    publicationName,
    sections);
<commit_msg>remove fake data<commit_after>import {
    Vessels
} from '/imports/api/vessels/vessels.coffee';

import './vessel.tpl.jade';

const EntityForm = require('/imports/api/EntityForm/EntityForm.js');

var db = Vessels;
var templateName = 'vessel';
var publicationName = 'vessel';
var sections = [{
    header: 'identificationSection',
    contents: [{
        key: 'name'
    }, {
        key: 'flag'
    }, {
        key: 'type',
        dropdownContainer: 'types'
    }, {
        key: 'callsign'
    }, {
        key: 'eni'
    }, {
        key: 'imo'
    }, {
        key: 'mmsi'
    }],
}, {
    header: 'visitSection',
    contents: [{
        key: 'lastVisit'
    }, {
        key: 'nextVisitAfter'
    }, {
        key: 'languages'
    }, {
        key: 'comments'
    }]
}];

new EntityForm(
    db,
    templateName,
    publicationName,
    sections);
<|endoftext|>


<commit_before>function new_question(question) {
	$('#question').text(question);
	$('#answer_seq2seq').text('');
	$('.robot').hide();
	start_spinner();
}

function new_chatbot_answer(seq2seq) {
	$('.robot').show();
	$('#answer_seq2seq').text(seq2seq);
	suggestions_random = get_random_suggestions(suggestions);
    load_suggestions(suggestions_random);
	stop_spinner();
}

function submit(input_text) {
	console.log("Chatbot input:", input_text)
	$('#input_text').val('');
	new_question(input_text);
	url = "/chatbot/ubuntuseq2seq"
	$.ajax({
	  type: "POST",
	  url: url,
	  data: {"question": input_text},
	  dataType: 'text',
	  success: function(data) {
	  	data = JSON.parse(data);
	  	var seq2seq = data.seq2seq;
	  	new_chatbot_answer(seq2seq)
	  }
	});
}

function load_suggestions(suggestions){
	for (var c in suggestions) {
		$('#suggestions').html($('#suggestions').html() + '

' + suggestions[c] + '

');
	}
	$('.suggestion .panel-body').matchHeight();
	$('.suggestion .panel-body').click(function(e){
		query = $(e.target).text();
		submit(query);
	})
}

function get_random_suggestions(suggestions) {
	var random_indexes = []
	while(random_indexes.length < 6){
	    var random_number = Math.ceil(Math.random()*(suggestions.length-1));
	    if(random_indexes.indexOf(random_number) > -1) continue;
	    random_indexes[random_indexes.length] = random_number;
	}

	suggestions_random = []
	for (var i in random_indexes) {
		suggestions_random.push(suggestions[random_indexes[i]]);
	}
	return suggestions_random
}

$(document).ready(function(){

	$('#input_text').keyup(function(e){
	    if(e.keyCode == 13) {
	    	input_text = $('#input_text').val();
	    	if (input_text != '') submit(input_text, $('#project_value').text().toLowerCase());
	    }
	});

	$('#search_button').click(function(e){
		input_text = $('#input_text').val();
	    if (input_text != '') submit(input_text, $('#project_value').text().toLowerCase());
	})
	$.getJSON("../static/javascripts/lists/chatbot_seq2seq_ubuntu.json", function(json) {
		suggestions = json.candidates;
		suggestions_random = get_random_suggestions(suggestions);
	    load_suggestions(suggestions_random);
	});
	$('.robot').hide();
});<commit_msg>Resetting suggestions after question<commit_after>function new_question(question) {
	$('#question').text(question);
	$('#answer_seq2seq').text('');
	$('#suggestions').text('');
	$('.robot').hide();
	start_spinner();
}

function new_chatbot_answer(seq2seq) {
	$('#answer_seq2seq').text(seq2seq);
	suggestions_random = get_random_suggestions(suggestions);
    load_suggestions(suggestions_random);
	stop_spinner();
}

function submit(input_text) {
	console.log("Chatbot input:", input_text)
	$('#input_text').val('');
	new_question(input_text);
	url = "/chatbot/ubuntuseq2seq"
	$.ajax({
	  type: "POST",
	  url: url,
	  data: {"question": input_text},
	  dataType: 'text',
	  success: function(data) {
	  	data = JSON.parse(data);
	  	var seq2seq = data.seq2seq;
	  	new_chatbot_answer(seq2seq)
	  }
	});
}

function load_suggestions(suggestions){
	for (var c in suggestions) {
		$('#suggestions').html($('#suggestions').html() + '

' + suggestions[c] + '

');
	}
	$('.suggestion .panel-body').matchHeight();
	$('.suggestion .panel-body').click(function(e){
		query = $(e.target).text();
		submit(query);
	})
}

function get_random_suggestions(suggestions) {
	var random_indexes = []
	while(random_indexes.length < 6){
	    var random_number = Math.ceil(Math.random()*(suggestions.length-1));
	    if(random_indexes.indexOf(random_number) > -1) continue;
	    random_indexes[random_indexes.length] = random_number;
	}

	suggestions_random = []
	for (var i in random_indexes) {
		suggestions_random.push(suggestions[random_indexes[i]]);
	}
	return suggestions_random
}

$(document).ready(function(){

	$('#input_text').keyup(function(e){
	    if(e.keyCode == 13) {
	    	input_text = $('#input_text').val();
	    	if (input_text != '') submit(input_text, $('#project_value').text().toLowerCase());
	    }
	});

	$('#search_button').click(function(e){
		input_text = $('#input_text').val();
	    if (input_text != '') submit(input_text, $('#project_value').text().toLowerCase());
	})
	$.getJSON("../static/javascripts/lists/chatbot_seq2seq_ubuntu.json", function(json) {
		suggestions = json.candidates;
		suggestions_random = get_random_suggestions(suggestions);
	    load_suggestions(suggestions_random);
	});
	$('.robot').hide();
});<|endoftext|>