<commit_before>var nohm = require('nohm').Nohm,
	nconf = require('nconf'),
	request = require('request'),
	redis = require('redis'),
	async = require('async-mini');

// @TODO get rid of nohm
module.exports = function (callback) {
	// connecting to redis
	var client = redis.createClient(nconf.get('redis:port'), nconf.get('redis:hostname')),
		db = nconf.get('redis:db'),
		auth = nconf.get('redis:auth');

	if (auth) {
		client.auth(auth);
	}

	client.on('connect', function () {
		if (db) {
			client.select(db);
		}

		console.log('Nohm has connected to redis.');

		nohm.setClient(client);
		callback(client);
	});

	client.on('end', function () {
		console.log('Nohm has discconected from redis.');
	});
};

nohm.model('User', {
	properties: {
		username: {
			type: 'string',
			unique: true,
			validations: ['notEmpty']
		},
		// if the coords are non-nullable
		// (can't check it with nohm)
		coords: {
			type: 'boolean',
			defaultValue: false
		},
		lng: {
			type: 'float',
			index: true
		},
		lat: {
			type: 'float',
			index: true
		},
		first_name: {
			type: 'string',
			validations: [
				['length', { max: 20 }]
			]
		},
		selfie: {
			type: 'string',
			validations: [
				['length', { max: 10 }]
			]
		},
		type: {
			type: 'string',
			defaultValue: 'unknown',
			validations: [
				function (value, options, callback) {
					callback(~['unknown', 'guy', 'gal'].indexOf(value));
				}
			]
		}
	},
	methods: {
		selfie: function () {
			var data = this.p('selfie');

			if (data) {
				return 'http://i.imgur.com/' + data.split(':').join('t.');
			}

			return '';
		},
		values: function () {
			var object = this.allProperties();

			object.selfie = this.selfie();
			return object;
		},
		providers: function (callback) {
			this.getAll('ProviderUser', 'default', function (error, ids) {
				if (error) {
					callback(error);
				}

				var loads = [],
					providers = [];

				ids.forEach(function (id) {
					loads.push(function (callback) {
						var providerUser = nohm.factory('ProviderUser', id, function (error) {
							providers.push(providerUser);
							callback(error);
						});
					})
				});

				async.parallel(loads, function (error) {
					callback(error, providers);
				});
			});
		}
	}
});

var providers = nconf.get('passport');

nohm.model('ProviderUser', {
	properties: {
		name: {
			type: 'string',
			validations: ['notEmpty']
		},
		accessToken: {
			type: 'string',
			validations: ['notEmpty']
		},
		refreshToken: {
			type: 'string',
			validations: ['notEmpty']
		},
		account: {
			type: 'string',
			validations: ['notEmpty'],
			index: true
		}
	},
	methods: {
		refreshAccessToken: function (callback) {
			var self = this,
				provider = providers[this.p('name')];

			request.post({
				url: provider.refreshURL,
				form: {
					refresh_token: this.p('refreshToken'),
					client_id: provider.clientID,
					client_secret: provider.clientSecret,
					grant_type: 'refresh_token'
				},
				json: true
			}, function (error, response, body) {
				if (error) {
					callback(error);
					return;
				}

				self.p('accessToken', body.access_token);
				self.save(function (error) {
					callback(error);
				});
			});
		}
	}
});
<commit_msg>Selfie limit increased<commit_after>var nohm = require('nohm').Nohm,
	nconf = require('nconf'),
	request = require('request'),
	redis = require('redis'),
	async = require('async-mini');

// @TODO get rid of nohm
module.exports = function (callback) {
	// connecting to redis
	var client = redis.createClient(nconf.get('redis:port'), nconf.get('redis:hostname')),
		db = nconf.get('redis:db'),
		auth = nconf.get('redis:auth');

	if (auth) {
		client.auth(auth);
	}

	client.on('connect', function () {
		if (db) {
			client.select(db);
		}

		console.log('Nohm has connected to redis.');

		nohm.setClient(client);
		callback(client);
	});

	client.on('end', function () {
		console.log('Nohm has discconected from redis.');
	});
};

nohm.model('User', {
	properties: {
		username: {
			type: 'string',
			unique: true,
			validations: ['notEmpty']
		},
		// if the coords are non-nullable
		// (can't check it with nohm)
		coords: {
			type: 'boolean',
			defaultValue: false
		},
		lng: {
			type: 'float',
			index: true
		},
		lat: {
			type: 'float',
			index: true
		},
		first_name: {
			type: 'string',
			validations: [
				['length', { max: 20 }]
			]
		},
		selfie: {
			type: 'string',
			validations: [
				['length', { max: 20 }]
			]
		},
		type: {
			type: 'string',
			defaultValue: 'unknown',
			validations: [
				function (value, options, callback) {
					callback(~['unknown', 'guy', 'gal'].indexOf(value));
				}
			]
		}
	},
	methods: {
		selfie: function () {
			var data = this.p('selfie');

			if (data) {
				return 'http://i.imgur.com/' + data.split(':').join('t.');
			}

			return '';
		},
		values: function () {
			var object = this.allProperties();

			object.selfie = this.selfie();
			return object;
		},
		providers: function (callback) {
			this.getAll('ProviderUser', 'default', function (error, ids) {
				if (error) {
					callback(error);
				}

				var loads = [],
					providers = [];

				ids.forEach(function (id) {
					loads.push(function (callback) {
						var providerUser = nohm.factory('ProviderUser', id, function (error) {
							providers.push(providerUser);
							callback(error);
						});
					})
				});

				async.parallel(loads, function (error) {
					callback(error, providers);
				});
			});
		}
	}
});

var providers = nconf.get('passport');

nohm.model('ProviderUser', {
	properties: {
		name: {
			type: 'string',
			validations: ['notEmpty']
		},
		accessToken: {
			type: 'string',
			validations: ['notEmpty']
		},
		refreshToken: {
			type: 'string',
			validations: ['notEmpty']
		},
		account: {
			type: 'string',
			validations: ['notEmpty'],
			index: true
		}
	},
	methods: {
		refreshAccessToken: function (callback) {
			var self = this,
				provider = providers[this.p('name')];

			request.post({
				url: provider.refreshURL,
				form: {
					refresh_token: this.p('refreshToken'),
					client_id: provider.clientID,
					client_secret: provider.clientSecret,
					grant_type: 'refresh_token'
				},
				json: true
			}, function (error, response, body) {
				if (error) {
					callback(error);
					return;
				}

				self.p('accessToken', body.access_token);
				self.save(function (error) {
					callback(error);
				});
			});
		}
	}
});
<|endoftext|>


<commit_before>"use strict";

var babelify     = require('babelify'),
    browserify   = require('browserify'),
    buffer       = require('vinyl-buffer'),
    gulp         = require('gulp'),
    sass         = require('gulp-sass'),
    glob         = require('glob'),
    gutil        = require('gulp-util'),
    rename       = require('gulp-rename'),
    source       = require('vinyl-source-stream'),
    colors       = require('colors'),
    watchify     = require('watchify'),
    autoprefixer = require('gulp-autoprefixer');

var config = {
    js: {
        src: 'js/src/pages/*.*',       // Entry point
        outputDir: '../static/js',      // Directory to save bundle to
    },
    css: {
        main: './sass/main.scss',
        pages: './sass/pages/*.scss',
        outputDir: '../static/css'
    }
};

gulp.task('css', function() {
  // main.scss
  gulp.src(config.css.main)
    .pipe(sass().on('error', gutil.log))
    .pipe(autoprefixer({
      browsers: ['last 3 versions'],
      cascade: false
    }))
    .pipe(gulp.dest(config.css.outputDir));

  // pages
  gulp.src(config.css.pages)
    .pipe(sass().on('error', gutil.log))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gulp.dest(config.css.outputDir + '/pages'));
});

function compileJS(watch) {
    var pages = glob.sync(config.js.src);

    pages.forEach(function(page) {                    // Each page will have its own bundle
        var bundleName = page.split('/').pop();       // This will be the filename of the output bundle

        var bundler = browserify({
            entries: [page],
            debug: true,
            cache: {},                          // Watchify uses cache stuff in order to quickly
            packageCache: {},                   // regenerate the compiled files
            plugin: watch ? [watchify] : [],
          }).transform(babelify, { presets : [ 'react' ] });  // Then, babelify, with React preset

        // We declare this as a function because we are going to bind it to the update event.
        function bundle() {
            var startTime = new Date().getTime();

            // Add options to add to "base" bundler passed as parameter
            bundler
              .bundle()                                    // Start bundle
              .on('error', gutil.log)
              .pipe(source(page))                          // Entry point
              .pipe(buffer())                              // Convert to gulp pipeline
              .pipe(rename(bundleName.replace("jsx", "js")))
              .pipe(gulp.dest(config.js.outputDir))        // Save 'bundle' to output
              .on('end', function() {
                var time = (new Date().getTime() - startTime) / 1000;
                return console.log(bundleName.cyan + " was browserified: " + (time + 's').magenta);
              })
          }

        bundler.on('update', bundle);                      // This event comes from watchify
        bundle();
    });
}

gulp.task('watch', function () {
    compileJS(true);
    gulp.watch('./sass/**', ['css']);
});

gulp.task('build', function () {
    compileJS(false);
    gulp.start('css');
});

<commit_msg>watch stuff<commit_after>"use strict";

var babelify     = require('babelify'),
    browserify   = require('browserify'),
    buffer       = require('vinyl-buffer'),
    gulp         = require('gulp'),
    sass         = require('gulp-sass'),
    glob         = require('glob'),
    gutil        = require('gulp-util'),
    rename       = require('gulp-rename'),
    source       = require('vinyl-source-stream'),
    colors       = require('colors'),
    watchify     = require('watchify'),
    autoprefixer = require('gulp-autoprefixer');

var config = {
    js: {
        src: 'js/src/pages/*.*',       // Entry point
        outputDir: '../static/js',      // Directory to save bundle to
    },
    css: {
        main: './sass/main.scss',
        pages: './sass/pages/*.scss',
        outputDir: '../static/css'
    }
};

gulp.task('css', function() {
  // main.scss
  gulp.src(config.css.main)
    .pipe(sass().on('error', gutil.log))
    .pipe(autoprefixer({
      browsers: ['last 3 versions'],
      cascade: false
    }))
    .pipe(gulp.dest(config.css.outputDir));

  // pages
  gulp.src(config.css.pages)
    .pipe(sass().on('error', gutil.log))
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(gulp.dest(config.css.outputDir + '/pages'));
});

function compileJS(watch) {
    var pages = glob.sync(config.js.src);

    pages.forEach(function(page) {                    // Each page will have its own bundle
        var bundleName = page.split('/').pop();       // This will be the filename of the output bundle

        var bundler = browserify({
            entries: [page],
            debug: watch,
            cache: {},                          // Watchify uses cache stuff in order to quickly
            packageCache: {},                   // regenerate the compiled files
            plugin: watch ? [watchify] : [],
          }).transform(babelify, { presets : [ 'react' ] });  // Then, babelify, with React preset

        // We declare this as a function because we are going to bind it to the update event.
        function bundle() {
            var startTime = new Date().getTime();

            // Add options to add to "base" bundler passed as parameter
            bundler
              .bundle()                                    // Start bundle
              .on('error', gutil.log)
              .pipe(source(page))                          // Entry point
              .pipe(buffer())                              // Convert to gulp pipeline
              .pipe(rename(bundleName.replace("jsx", "js")))
              .pipe(gulp.dest(config.js.outputDir))        // Save 'bundle' to output
              .on('end', function() {
                var time = (new Date().getTime() - startTime) / 1000;
                return console.log(bundleName.cyan + " was browserified: " + (time + 's').magenta);
              })
          }

        bundler.on('update', bundle);                      // This event comes from watchify
        bundle();
    });
}

gulp.task('watch', function () {
    compileJS(true);
    gulp.watch('./sass/**', ['css']);
});

gulp.task('build', function () {
    compileJS(false);
    gulp.start('css');
});

<|endoftext|>


<commit_before>import React from 'react';
import Motion from 'flavours/glitch/util/optional_motion';
import spring from 'react-motion/lib/spring';
import PropTypes from 'prop-types';
import classNames from 'classnames';

export default class IconButton extends React.PureComponent {

  static propTypes = {
    className: PropTypes.string,
    title: PropTypes.string.isRequired,
    icon: PropTypes.string.isRequired,
    onClick: PropTypes.func,
    size: PropTypes.number,
    active: PropTypes.bool,
    pressed: PropTypes.bool,
    expanded: PropTypes.bool,
    style: PropTypes.object,
    activeStyle: PropTypes.object,
    disabled: PropTypes.bool,
    inverted: PropTypes.bool,
    animate: PropTypes.bool,
    flip: PropTypes.bool,
    overlay: PropTypes.bool,
    tabIndex: PropTypes.string,
    label: PropTypes.string,
  };

  static defaultProps = {
    size: 18,
    active: false,
    disabled: false,
    animate: false,
    overlay: false,
    tabIndex: '0',
  };

  handleClick = (e) =>  {
    e.preventDefault();

    if (!this.props.disabled) {
      this.props.onClick(e);
    }
  }

  render () {
    let style = {
      fontSize: `${this.props.size}px`,
      height: `${this.props.size * 1.28571429}px`,
      lineHeight: `${this.props.size}px`,
      ...this.props.style,
      ...(this.props.active ? this.props.activeStyle : {}),
    };
    if (!this.props.label) {
      style.width = `${this.props.size * 1.28571429}px`;
    } else {
      style.textAlign = 'left';
    }

    const {
      active,
      animate,
      className,
      disabled,
      expanded,
      icon,
      inverted,
      flip,
      overlay,
      pressed,
      tabIndex,
      title,
    } = this.props;

    const classes = classNames(className, 'icon-button', {
      active,
      disabled,
      inverted,
      overlayed: overlay,
    });

    const flipDeg = flip ? -180 : -360;
    const rotateDeg = active ? flipDeg : 0;

    const motionDefaultStyle = {
      rotate: rotateDeg,
    };

    const springOpts = {
      stiffness: this.props.flip ? 60 : 120,
      damping: 7,
    };
    const motionStyle = {
      rotate: animate ? spring(rotateDeg, springOpts) : 0,
    };

    if (!animate) {
      // Perf optimization: avoid unnecessary <Motion> components unless
      // we actually need to animate.
      return (
        <button
          aria-label={title}
          aria-pressed={pressed}
          aria-expanded={expanded}
          title={title}
          className={classes}
          onClick={this.handleClick}
          style={style}
          tabIndex={tabIndex}
          disabled={disabled}
        >
          <i className={`fa fa-fw fa-${icon}`} aria-hidden='true' />
        </button>
      );
    }

    return (
      <Motion defaultStyle={motionDefaultStyle} style={motionStyle}>
        {({ rotate }) =>
          (<button
            aria-label={title}
            aria-pressed={pressed}
            aria-expanded={expanded}
            title={title}
            className={classes}
            onClick={this.handleClick}
            style={style}
            tabIndex={tabIndex}
            disabled={disabled}
          >
            <i style={{ transform: `rotate(${rotate}deg)` }} className={`fa fa-fw fa-${icon}`} aria-hidden='true' />
            {this.props.label}
          </button>)
        }
      </Motion>
    );
  }

}
<commit_msg>[Glitch] Port changes to IconButton<commit_after>import React from 'react';
import Motion from 'flavours/glitch/util/optional_motion';
import spring from 'react-motion/lib/spring';
import PropTypes from 'prop-types';
import classNames from 'classnames';

export default class IconButton extends React.PureComponent {

  static propTypes = {
    className: PropTypes.string,
    title: PropTypes.string.isRequired,
    icon: PropTypes.string.isRequired,
    onClick: PropTypes.func,
    onMouseDown: PropTypes.func,
    onKeyDown: PropTypes.func,
    size: PropTypes.number,
    active: PropTypes.bool,
    pressed: PropTypes.bool,
    expanded: PropTypes.bool,
    style: PropTypes.object,
    activeStyle: PropTypes.object,
    disabled: PropTypes.bool,
    inverted: PropTypes.bool,
    animate: PropTypes.bool,
    flip: PropTypes.bool,
    overlay: PropTypes.bool,
    tabIndex: PropTypes.string,
    label: PropTypes.string,
  };

  static defaultProps = {
    size: 18,
    active: false,
    disabled: false,
    animate: false,
    overlay: false,
    tabIndex: '0',
  };

  handleClick = (e) =>  {
    e.preventDefault();

    if (!this.props.disabled) {
      this.props.onClick(e);
    }
  }

  handleMouseDown = (e) => {
    if (!this.props.disabled && this.props.onMouseDown) {
      this.props.onMouseDown(e);
    }
  }

  handleKeyDown = (e) => {
    if (!this.props.disabled && this.props.onKeyDown) {
      this.props.onKeyDown(e);
    }
  }

  render () {
    let style = {
      fontSize: `${this.props.size}px`,
      height: `${this.props.size * 1.28571429}px`,
      lineHeight: `${this.props.size}px`,
      ...this.props.style,
      ...(this.props.active ? this.props.activeStyle : {}),
    };
    if (!this.props.label) {
      style.width = `${this.props.size * 1.28571429}px`;
    } else {
      style.textAlign = 'left';
    }

    const {
      active,
      animate,
      className,
      disabled,
      expanded,
      icon,
      inverted,
      flip,
      overlay,
      pressed,
      tabIndex,
      title,
    } = this.props;

    const classes = classNames(className, 'icon-button', {
      active,
      disabled,
      inverted,
      overlayed: overlay,
    });

    const flipDeg = flip ? -180 : -360;
    const rotateDeg = active ? flipDeg : 0;

    const motionDefaultStyle = {
      rotate: rotateDeg,
    };

    const springOpts = {
      stiffness: this.props.flip ? 60 : 120,
      damping: 7,
    };
    const motionStyle = {
      rotate: animate ? spring(rotateDeg, springOpts) : 0,
    };

    if (!animate) {
      // Perf optimization: avoid unnecessary <Motion> components unless
      // we actually need to animate.
      return (
        <button
          aria-label={title}
          aria-pressed={pressed}
          aria-expanded={expanded}
          title={title}
          className={classes}
          onClick={this.handleClick}
          onMouseDown={this.handleMouseDown}
          onKeyDown={this.handleKeyDown}
          style={style}
          tabIndex={tabIndex}
          disabled={disabled}
        >
          <i className={`fa fa-fw fa-${icon}`} aria-hidden='true' />
        </button>
      );
    }

    return (
      <Motion defaultStyle={motionDefaultStyle} style={motionStyle}>
        {({ rotate }) =>
          (<button
            aria-label={title}
            aria-pressed={pressed}
            aria-expanded={expanded}
            title={title}
            className={classes}
            onClick={this.handleClick}
            onMouseDown={this.handleMouseDown}
            onKeyDown={this.handleKeyDown}
            style={style}
            tabIndex={tabIndex}
            disabled={disabled}
          >
            <i style={{ transform: `rotate(${rotate}deg)` }} className={`fa fa-fw fa-${icon}`} aria-hidden='true' />
            {this.props.label}
          </button>)
        }
      </Motion>
    );
  }

}
<|endoftext|>


<commit_before>// Dependencies
var chalk = require('chalk');
var sassLint = require('sass-lint');
var path = require('path');

// Helper Utils
var formatter = require('./formatter');

/**
 * Linter
 *
 * @param {String} sasslint file globbing pattern
 * @param {Object} config scsslint configuration
 * @return {Array} file report containing error/warning files
 */
function lint(input, options) {
  // Run sassLint via lintFiles, which takes a glob
  var report = sassLint.lintFiles(input, {}, options.configFile);
  var fileReport = [];

  if (report.length) {
    report.forEach(function(file) {

      if (file.warningCount && options.quiet) {
        file.warningCount = 0;
      }

      if (file.errorCount || file.warningCount) {
        // We can't easily use webpack's outputing for info,
        // so this get's prettified, and dumped to terminal
        console.log(formatter(file.messages, file.filePath));
      }

      // Push seperate error counts and warning counts w/ filenames return
      if (file.errorCount) {
        fileReport.push({
          'error': true,
          'file': file.filePath
        });
      }

      if (file.warningCount) {
        fileReport.push({
          'error': false,
          'file': file.filePath
        });
      }
    });
  }

  // Allow dying on sasslint error of set
  if (options.failOnError && file.errorCount) {
    throw new Error('Failed because of a sasslint error.\n');
  } else if (options.failOnWarning && file.warningCount) {
    throw new Error('Failed because of a sasslint warning.\n');
  }

  return fileReport;
}

module.exports = lint;<commit_msg>Have dying happen properly<commit_after>// Dependencies
var chalk = require('chalk');
var sassLint = require('sass-lint');
var path = require('path');

// Helper Utils
var formatter = require('./formatter');

/**
 * Linter
 *
 * @param {String} sasslint file globbing pattern
 * @param {Object} config scsslint configuration
 * @return {Array} file report containing error/warning files
 */
function lint(input, options) {
  // Run sassLint via lintFiles, which takes a glob
  var report = sassLint.lintFiles(input, {}, options.configFile);
  var fileReport = [];

  if (report.length) {
    report.forEach(function(file) {

      if (file.warningCount && options.quiet) {
        file.warningCount = 0;
      }

      if (file.errorCount || file.warningCount) {
        // We can't easily use webpack's outputing for info,
        // so this get's prettified, and dumped to terminal
        console.log(formatter(file.messages, file.filePath));
      }

      // Push seperate error counts and warning counts w/ filenames return
      if (file.errorCount) {
        fileReport.push({
          'error': true,
          'file': file.filePath
        });
      }

      if (file.warningCount) {
        fileReport.push({
          'error': false,
          'file': file.filePath
        });
      }

      // Allow dying on sasslint error of set
      if (options.failOnError && file.errorCount) {
        throw new Error('Failed because of a sasslint error.\n');
      } else if (options.failOnWarning && file.warningCount) {
        throw new Error('Failed because of a sasslint warning.\n');
      }
    });
  }

  return fileReport;
}

module.exports = lint;<|endoftext|>


<commit_before>/**
 * Resources
 *
 * https://gist.github.com/2489540
 *
 */

module.exports = function( grunt ) {

	"use strict";

	// readOptionalJSON
	// by Ben Alman
	// https://gist.github.com/2876125
	function readOptionalJSON( filepath ) {
		var data = {};
		try {
			data = grunt.file.readJSON( filepath );
			grunt.verbose.write( "Reading " + filepath + "..." ).ok();
		} catch(e) {}
		return data;
	}

	var file = grunt.file,
		log = grunt.log,
		verbose = grunt.verbose,
		config = grunt.config,
		distpaths = [
			"dist/jquery.js",
			"dist/jquery.min.js"
		];

	grunt.initConfig({
		pkg: "<json:package.json>",
		dst: readOptionalJSON("dist/.destination.json"),
		meta: {
			banner: "/*! jQuery v<%= pkg.version %> jquery.com | jquery.org/license */"
		},
		compare_size: {
			files: distpaths
		},
		selector: {
			"src/selector.js": [
				"src/sizzle-jquery.js",
				"src/sizzle/sizzle.js"
			]
		},
		build: {
			"dist/jquery.js": [
				"src/intro.js",
				"src/core.js",
				"src/callbacks.js",
				"src/deferred.js",
				"src/support.js",
				"src/data.js",
				"src/queue.js",
				"src/attributes.js",
				"src/event.js",
				"src/selector.js",
				"src/traversing.js",
				"src/manipulation.js",

				{ flag: "css", src: "src/css.js" },
				"src/serialize.js",
				{ flag: "ajax", src: "src/ajax.js" },
				{ flag: "ajax/jsonp", src: "src/ajax/jsonp.js", needs: [ "ajax", "ajax/script" ]  },
				{ flag: "ajax/script", src: "src/ajax/script.js", needs: ["ajax"]  },
				{ flag: "ajax/xhr", src: "src/ajax/xhr.js", needs: ["ajax"]  },
				{ flag: "effects", src: "src/effects.js", needs: ["css"] },
				{ flag: "offset", src: "src/offset.js", needs: ["css"] },
				{ flag: "dimensions", src: "src/dimensions.js", needs: ["css"] },
				{ flag: "deprecated", src: "src/deprecated.js" },

				"src/exports.js",
				"src/outro.js"
			]
		},
		min: {
			"dist/jquery.min.js": [ "<banner>", "dist/jquery.js" ]
		},

		lint: {
			dist: "dist/jquery.js",
			grunt: "grunt.js",
			tests: "test/unit/**/*.js"
		},

		jshint: (function() {
			function jshintrc( path ) {
				return readOptionalJSON( (path || "") + ".jshintrc" ) || {};
			}

			return {
				grunt: jshintrc(),
				dist: jshintrc( "src/" ),
				tests: jshintrc( "test/" )
			};
		})(),

		qunit: {
			files: "test/index.html"
		},
		watch: {
			files: [
				"<config:lint.grunt>", "<config:lint.tests>",
				"src/**/*.js"
			],
			tasks: "dev"
		},
		uglify: {
			codegen: {
				ascii_only: true
			}
		}
	});

	// Default grunt.
	grunt.registerTask( "default", "update_submodules selector build:*:* lint min dist:* compare_size" );

	// Short list as a high frequency watch task
	grunt.registerTask( "dev", "selector build:*:* lint" );

	// Load grunt tasks from NPM packages
	grunt.loadNpmTasks( "grunt-compare-size" );
	grunt.loadNpmTasks( "grunt-git-authors" );
	grunt.loadNpmTasks( "grunt-update-submodules" );

	grunt.registerTask( "testswarm", function( commit, configFile ) {
		var testswarm = require( "testswarm" ),
			testUrls = [],
			config = grunt.file.readJSON( configFile ).jquery,
			tests = "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue serialize support traversing Sizzle".split(" ");

		tests.forEach(function( test ) {
			testUrls.push( config.testUrl + commit + "/test/index.html?module=" + test );
		});

		testswarm({
			url: config.swarmUrl,
			pollInterval: 10000,
			timeout: 1000 * 60 * 30,
			done: this.async()
		}, {
			authUsername: config.authUsername,
			authToken: config.authToken,
			jobName: "jQuery commit #" + commit.substr( 0, 10 ) + "",
			runMax: config.runMax,
			"runNames[]": tests,
			"runUrls[]": testUrls,
			"browserSets[]": ["popular"]
		});
	});

	// Build src/selector.js
	grunt.registerMultiTask( "selector", "Build src/selector.js", function() {

		var name = this.file.dest,
				files = this.file.src,
				sizzle = {
					api: file.read( files[0] ),
					src: file.read( files[1] )
				},
				compiled, parts;

		/**

			sizzle-jquery.js -> sizzle between "EXPOSE" blocks,
			replace define & window.Sizzle assignment

			// EXPOSE
			if ( typeof define === "function" && define.amd ) {
				define(function() { return Sizzle; });
			} else {
				window.Sizzle = Sizzle;
			}
			// EXPOSE

			Becomes...

			Sizzle.attr = jQuery.attr;
			jQuery.find = Sizzle;
			jQuery.expr = Sizzle.selectors;
			jQuery.expr[":"] = jQuery.expr.pseudos;
			jQuery.unique = Sizzle.uniqueSort;
			jQuery.text = Sizzle.getText;
			jQuery.isXMLDoc = Sizzle.isXML;
			jQuery.contains = Sizzle.contains;

		 */

		// Break into 3 pieces
		parts = sizzle.src.split("// EXPOSE");
		// Replace the if/else block with api
		parts[1] = sizzle.api;
		// Rejoin the pieces
		compiled = parts.join("");

		verbose.write("Injected sizzle-jquery.js into sizzle.js");

		// Write concatenated source to file
		file.write( name, compiled );

		// Fail task if errors were logged.
		if ( this.errorCount ) {
			return false;
		}

		// Otherwise, print a success message.
		log.writeln( "File '" + name + "' created." );
	});

	// Special "alias" task to make custom build creation less grawlix-y
	grunt.registerTask( "custom", function() {
		var done = this.async(),
				args = [].slice.call(arguments),
				modules = args.length ? args[0].replace(/,/g, ":") : "";

		// Translation example
		//
		//   grunt custom:+ajax,-dimensions,-effects,-offset
		//
		// Becomes:
		//
		//   grunt build:*:*:+ajax:-dimensions:-effects:-offset

		grunt.log.writeln( "Creating custom build...\n" );

		grunt.utils.spawn({
			cmd: process.platform === "win32" ? "grunt.cmd" : "grunt",
			args: [ "build:*:*:" + modules, "min" ]
		}, function( err, result ) {
			if ( err ) {
				grunt.verbose.error();
				done( err );
				return;
			}

			grunt.log.writeln( result.replace("Done, without errors.", "") );

			done();
		});
	});

	// Special concat/build task to handle various jQuery build requirements
	//
	grunt.registerMultiTask(
		"build",
		"Concatenate source (include/exclude modules with +/- flags), embed date/version",
		function() {
			// Concat specified files.
			var compiled = "",
				modules = this.flags,
				explicit = Object.keys(modules).length > 1,
				optIn = !modules["*"],
				name = this.file.dest,
				excluded = {},
				version = config( "pkg.version" ),
				excluder = function( flag, needsFlag ) {
					// explicit > implicit, so set this first and let it be overridden by explicit
					if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
						excluded[ flag ] = false;
					}

					if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
						// explicit exclusion from flag or dependency
						excluded[ flag ] = true;
					} else if ( modules[ "+" + flag ] && ( excluded[ needsFlag ] === false ) ) {
						// explicit inclusion from flag or dependency overriding a weak inclusion
						delete excluded[ needsFlag ];
					}
				};

			// append commit id to version
			if ( process.env.COMMIT ) {
				version += " " + process.env.COMMIT;
			}

			// figure out which files to exclude based on these rules in this order:
			//  explicit > implicit (explicit also means a dependency/dependent that was explicit)
			//  exclude > include
			// examples:
			//  *:                 none (implicit exclude)
			//  *:*                all (implicit include)
			//  *:*:-effects       all except effects (explicit > implicit)
			//  *:*:-css           all except css and its deps (explicit)
			//  *:*:-css:+effects  all except css and its deps (explicit exclude from dep. trumps explicit include)
			//  *:+effects         none except effects and its deps (explicit include from dep. trumps implicit exclude)
			this.file.src.forEach(function( filepath ) {
				var flag = filepath.flag;

				if ( flag ) {

					excluder(flag);

					// check for dependencies
					if ( filepath.needs ) {
						filepath.needs.forEach(function( needsFlag ) {
							excluder( flag, needsFlag );
						});
					}
				}
			});

			// append excluded modules to version
			if ( Object.keys( excluded ).length ) {
				version += " -" + Object.keys( excluded ).join( ",-" );
				// set pkg.version to version with excludes, so minified file picks it up
				grunt.config.set( "pkg.version", version );
			}

			// conditionally concatenate source
			this.file.src.forEach(function( filepath ) {
				var flag = filepath.flag,
						specified = false,
						omit = false,
						message = "";

				if ( flag ) {
					if ( excluded[ flag ] !== undefined ) {
						message = ( "Excluding " + flag ).red;
						specified = true;
						omit = true;
					} else {
						message = ( "Including " + flag ).green;

						// If this module was actually specified by the
						// builder, then st the flag to include it in the
						// output list
						if ( modules[ "+" + flag ] ) {
							specified = true;
						}
					}

					// Only display the inclusion/exclusion list when handling
					// an explicit list.
					//
					// Additionally, only display modules that have been specified
					// by the user
					if ( explicit && specified ) {
						grunt.log.writetableln([ 27, 30 ], [
							message,
							( "(" + filepath.src + ")").grey
						]);
					}

					filepath = filepath.src;
				}

				if ( !omit ) {
					compiled += file.read( filepath );
				}
			});

			// Embed Version
			// Embed Date
			compiled = compiled.replace( /@VERSION/g, version )
				.replace( "@DATE", function () {
					var date = new Date();

					// YYYY-MM-DD
					return [
						date.getFullYear(),
						date.getMonth() + 1,
						date.getDate()
					].join( "-" );
				});

			// Write concatenated source to file
			file.write( name, compiled );

			// Fail task if errors were logged.
			if ( this.errorCount ) {
				return false;
			}

			// Otherwise, print a success message.
			log.writeln( "File '" + name + "' created." );
		});

	// Allow custom dist file locations
	grunt.registerTask( "dist", function() {
		var flags, paths, stored;

		// Check for stored destination paths
		// ( set in dist/.destination.json )
		stored = Object.keys( config("dst") );

		// Allow command line input as well
		flags = Object.keys( this.flags );

		// Combine all output target paths
		paths = [].concat( stored, flags ).filter(function( path ) {
			return path !== "*";
		});

		// Ensure the dist files are pure ASCII
		var fs = require("fs"),
			nonascii = false;
		distpaths.forEach(function( filename ) {
			var buf = fs.readFileSync( filename, "utf8" ),
			i, c;
			if ( buf.length !== Buffer.byteLength( buf, "utf8" ) ) {
				log.writeln( filename + ": Non-ASCII characters detected:" );
				for ( i = 0; i < buf.length; i++ ) {
					c = buf.charCodeAt( i );
					if ( c > 127 ) {
						log.writeln( "- position " + i + ": " + c );
						log.writeln( "-- " + buf.substring( i - 20, i + 20 ) );
						nonascii = true;
					}
				}
			}
		});
		if ( nonascii ) {
			return false;
		}

		// Proceed only if there are actual
		// paths to write to
		if ( paths.length ) {

			// 'distpaths' is declared at the top of the
			// module.exports function scope. It is an array
			// of default files that jQuery creates
			distpaths.forEach(function( filename ) {
				paths.forEach(function( path ) {
					var created;

					if ( !/\/$/.test( path ) ) {
						path += "/";
					}

					created = path + filename.replace( "dist/", "" );

					file.write( created, file.read(filename) );

					log.writeln( "File '" + created + "' created." );
				});
			});
		}
	});
};
<commit_msg>Fix builds with partial ajax support (e.g., custom:ajax/xhr)<commit_after>/**
 * Resources
 *
 * https://gist.github.com/2489540
 *
 */

module.exports = function( grunt ) {

	"use strict";

	// readOptionalJSON
	// by Ben Alman
	// https://gist.github.com/2876125
	function readOptionalJSON( filepath ) {
		var data = {};
		try {
			data = grunt.file.readJSON( filepath );
			grunt.verbose.write( "Reading " + filepath + "..." ).ok();
		} catch(e) {}
		return data;
	}

	var file = grunt.file,
		log = grunt.log,
		verbose = grunt.verbose,
		config = grunt.config,
		distpaths = [
			"dist/jquery.js",
			"dist/jquery.min.js"
		];

	grunt.initConfig({
		pkg: "<json:package.json>",
		dst: readOptionalJSON("dist/.destination.json"),
		meta: {
			banner: "/*! jQuery v<%= pkg.version %> jquery.com | jquery.org/license */"
		},
		compare_size: {
			files: distpaths
		},
		selector: {
			"src/selector.js": [
				"src/sizzle-jquery.js",
				"src/sizzle/sizzle.js"
			]
		},
		build: {
			"dist/jquery.js": [
				"src/intro.js",
				"src/core.js",
				"src/callbacks.js",
				"src/deferred.js",
				"src/support.js",
				"src/data.js",
				"src/queue.js",
				"src/attributes.js",
				"src/event.js",
				"src/selector.js",
				"src/traversing.js",
				"src/manipulation.js",

				{ flag: "css", src: "src/css.js" },
				"src/serialize.js",
				{ flag: "ajax", src: "src/ajax.js" },
				{ flag: "ajax/script", src: "src/ajax/script.js", needs: ["ajax"]  },
				{ flag: "ajax/jsonp", src: "src/ajax/jsonp.js", needs: [ "ajax", "ajax/script" ]  },
				{ flag: "ajax/xhr", src: "src/ajax/xhr.js", needs: ["ajax"]  },
				{ flag: "effects", src: "src/effects.js", needs: ["css"] },
				{ flag: "offset", src: "src/offset.js", needs: ["css"] },
				{ flag: "dimensions", src: "src/dimensions.js", needs: ["css"] },
				{ flag: "deprecated", src: "src/deprecated.js" },

				"src/exports.js",
				"src/outro.js"
			]
		},
		min: {
			"dist/jquery.min.js": [ "<banner>", "dist/jquery.js" ]
		},

		lint: {
			dist: "dist/jquery.js",
			grunt: "grunt.js",
			tests: "test/unit/**/*.js"
		},

		jshint: (function() {
			function jshintrc( path ) {
				return readOptionalJSON( (path || "") + ".jshintrc" ) || {};
			}

			return {
				grunt: jshintrc(),
				dist: jshintrc( "src/" ),
				tests: jshintrc( "test/" )
			};
		})(),

		qunit: {
			files: "test/index.html"
		},
		watch: {
			files: [
				"<config:lint.grunt>", "<config:lint.tests>",
				"src/**/*.js"
			],
			tasks: "dev"
		},
		uglify: {
			codegen: {
				ascii_only: true
			}
		}
	});

	// Default grunt.
	grunt.registerTask( "default", "update_submodules selector build:*:* lint min dist:* compare_size" );

	// Short list as a high frequency watch task
	grunt.registerTask( "dev", "selector build:*:* lint" );

	// Load grunt tasks from NPM packages
	grunt.loadNpmTasks( "grunt-compare-size" );
	grunt.loadNpmTasks( "grunt-git-authors" );
	grunt.loadNpmTasks( "grunt-update-submodules" );

	grunt.registerTask( "testswarm", function( commit, configFile ) {
		var testswarm = require( "testswarm" ),
			testUrls = [],
			config = grunt.file.readJSON( configFile ).jquery,
			tests = "ajax attributes callbacks core css data deferred dimensions effects event manipulation offset queue serialize support traversing Sizzle".split(" ");

		tests.forEach(function( test ) {
			testUrls.push( config.testUrl + commit + "/test/index.html?module=" + test );
		});

		testswarm({
			url: config.swarmUrl,
			pollInterval: 10000,
			timeout: 1000 * 60 * 30,
			done: this.async()
		}, {
			authUsername: config.authUsername,
			authToken: config.authToken,
			jobName: "jQuery commit #" + commit.substr( 0, 10 ) + "",
			runMax: config.runMax,
			"runNames[]": tests,
			"runUrls[]": testUrls,
			"browserSets[]": ["popular"]
		});
	});

	// Build src/selector.js
	grunt.registerMultiTask( "selector", "Build src/selector.js", function() {

		var name = this.file.dest,
				files = this.file.src,
				sizzle = {
					api: file.read( files[0] ),
					src: file.read( files[1] )
				},
				compiled, parts;

		/**

			sizzle-jquery.js -> sizzle between "EXPOSE" blocks,
			replace define & window.Sizzle assignment

			// EXPOSE
			if ( typeof define === "function" && define.amd ) {
				define(function() { return Sizzle; });
			} else {
				window.Sizzle = Sizzle;
			}
			// EXPOSE

			Becomes...

			Sizzle.attr = jQuery.attr;
			jQuery.find = Sizzle;
			jQuery.expr = Sizzle.selectors;
			jQuery.expr[":"] = jQuery.expr.pseudos;
			jQuery.unique = Sizzle.uniqueSort;
			jQuery.text = Sizzle.getText;
			jQuery.isXMLDoc = Sizzle.isXML;
			jQuery.contains = Sizzle.contains;

		 */

		// Break into 3 pieces
		parts = sizzle.src.split("// EXPOSE");
		// Replace the if/else block with api
		parts[1] = sizzle.api;
		// Rejoin the pieces
		compiled = parts.join("");

		verbose.write("Injected sizzle-jquery.js into sizzle.js");

		// Write concatenated source to file
		file.write( name, compiled );

		// Fail task if errors were logged.
		if ( this.errorCount ) {
			return false;
		}

		// Otherwise, print a success message.
		log.writeln( "File '" + name + "' created." );
	});

	// Special "alias" task to make custom build creation less grawlix-y
	grunt.registerTask( "custom", function() {
		var done = this.async(),
				args = [].slice.call(arguments),
				modules = args.length ? args[0].replace(/,/g, ":") : "";

		// Translation example
		//
		//   grunt custom:+ajax,-dimensions,-effects,-offset
		//
		// Becomes:
		//
		//   grunt build:*:*:+ajax:-dimensions:-effects:-offset

		grunt.log.writeln( "Creating custom build...\n" );

		grunt.utils.spawn({
			cmd: process.platform === "win32" ? "grunt.cmd" : "grunt",
			args: [ "build:*:*:" + modules, "min" ]
		}, function( err, result ) {
			if ( err ) {
				grunt.verbose.error();
				done( err );
				return;
			}

			grunt.log.writeln( result.replace("Done, without errors.", "") );

			done();
		});
	});

	// Special concat/build task to handle various jQuery build requirements
	//
	grunt.registerMultiTask(
		"build",
		"Concatenate source (include/exclude modules with +/- flags), embed date/version",
		function() {
			// Concat specified files.
			var compiled = "",
				modules = this.flags,
				optIn = !modules["*"],
				explicit = optIn || Object.keys(modules).length > 1,
				name = this.file.dest,
				deps = {},
				excluded = {},
				version = config( "pkg.version" ),
				excluder = function( flag, needsFlag ) {
					// optIn defaults implicit behavior to weak exclusion
					if ( optIn && !modules[ flag ] && !modules[ "+" + flag ] ) {
						excluded[ flag ] = false;
					}

					// explicit or inherited strong exclusion
					if ( excluded[ needsFlag ] || modules[ "-" + flag ] ) {
						excluded[ flag ] = true;

					// explicit inclusion overrides weak exclusion
					} else if ( excluded[ needsFlag ] === false &&
						( modules[ flag ] || modules[ "+" + flag ] ) ) {

						delete excluded[ needsFlag ];

						// ...all the way down
						if ( deps[ needsFlag ] ) {
							deps[ needsFlag ].forEach(function( subDep ) {
								modules[ needsFlag ] = true;
								excluder( needsFlag, subDep );
							});
						}
					}
				};

			// append commit id to version
			if ( process.env.COMMIT ) {
				version += " " + process.env.COMMIT;
			}

			// figure out which files to exclude based on these rules in this order:
			//  dependency explicit exclude
			//  > explicit exclude
			//  > explicit include
			//  > dependency implicit exclude
			//  > implicit exclude
			// examples:
			//  *                  none (implicit exclude)
			//  *:*                all (implicit include)
			//  *:*:-css           all except css and dependents (explicit > implicit)
			//  *:*:-css:+effects  same (excludes effects because explicit include is trumped by explicit exclude of dependency)
			//  *:+effects         none except effects and its dependencies (explicit include trumps implicit exclude of dependency)
			this.file.src.forEach(function( filepath ) {
				var flag = filepath.flag;

				if ( flag ) {

					excluder(flag);

					// check for dependencies
					if ( filepath.needs ) {
						deps[ flag ] = filepath.needs;
						filepath.needs.forEach(function( needsFlag ) {
							excluder( flag, needsFlag );
						});
					}
				}
			});

			// append excluded modules to version
			if ( Object.keys( excluded ).length ) {
				version += " -" + Object.keys( excluded ).join( ",-" );
				// set pkg.version to version with excludes, so minified file picks it up
				grunt.config.set( "pkg.version", version );
			}

			// conditionally concatenate source
			this.file.src.forEach(function( filepath ) {
				var flag = filepath.flag,
						specified = false,
						omit = false,
						message = "";

				if ( flag ) {
					if ( excluded[ flag ] !== undefined ) {
						message = ( "Excluding " + flag ).red;
						specified = true;
						omit = true;
					} else {
						message = ( "Including " + flag ).green;

						// If this module was actually specified by the
						// builder, then st the flag to include it in the
						// output list
						if ( modules[ "+" + flag ] ) {
							specified = true;
						}
					}

					// Only display the inclusion/exclusion list when handling
					// an explicit list.
					//
					// Additionally, only display modules that have been specified
					// by the user
					if ( explicit && specified ) {
						grunt.log.writetableln([ 27, 30 ], [
							message,
							( "(" + filepath.src + ")").grey
						]);
					}

					filepath = filepath.src;
				}

				if ( !omit ) {
					compiled += file.read( filepath );
				}
			});

			// Embed Version
			// Embed Date
			compiled = compiled.replace( /@VERSION/g, version )
				.replace( "@DATE", function () {
					var date = new Date();

					// YYYY-MM-DD
					return [
						date.getFullYear(),
						date.getMonth() + 1,
						date.getDate()
					].join( "-" );
				});

			// Write concatenated source to file
			file.write( name, compiled );

			// Fail task if errors were logged.
			if ( this.errorCount ) {
				return false;
			}

			// Otherwise, print a success message.
			log.writeln( "File '" + name + "' created." );
		});

	// Allow custom dist file locations
	grunt.registerTask( "dist", function() {
		var flags, paths, stored;

		// Check for stored destination paths
		// ( set in dist/.destination.json )
		stored = Object.keys( config("dst") );

		// Allow command line input as well
		flags = Object.keys( this.flags );

		// Combine all output target paths
		paths = [].concat( stored, flags ).filter(function( path ) {
			return path !== "*";
		});

		// Ensure the dist files are pure ASCII
		var fs = require("fs"),
			nonascii = false;
		distpaths.forEach(function( filename ) {
			var buf = fs.readFileSync( filename, "utf8" ),
			i, c;
			if ( buf.length !== Buffer.byteLength( buf, "utf8" ) ) {
				log.writeln( filename + ": Non-ASCII characters detected:" );
				for ( i = 0; i < buf.length; i++ ) {
					c = buf.charCodeAt( i );
					if ( c > 127 ) {
						log.writeln( "- position " + i + ": " + c );
						log.writeln( "-- " + buf.substring( i - 20, i + 20 ) );
						nonascii = true;
					}
				}
			}
		});
		if ( nonascii ) {
			return false;
		}

		// Proceed only if there are actual
		// paths to write to
		if ( paths.length ) {

			// 'distpaths' is declared at the top of the
			// module.exports function scope. It is an array
			// of default files that jQuery creates
			distpaths.forEach(function( filename ) {
				paths.forEach(function( path ) {
					var created;

					if ( !/\/$/.test( path ) ) {
						path += "/";
					}

					created = path + filename.replace( "dist/", "" );

					file.write( created, file.read(filename) );

					log.writeln( "File '" + created + "' created." );
				});
			});
		}
	});
};
<|endoftext|>


<commit_before>import Component from '@ember/component'
import { all as PromiseAll } from 'rsvp';
import { inject as service } from '@ember/service';
import { get, set, setProperties } from '@ember/object';
import layout from './template';
import NewOrEdit from 'ui/mixins/new-or-edit';

const CUSTOM = 'custom';

export default Component.extend(NewOrEdit,{
  layout,
  globalStore: service(),

  user: null,
  primaryResource: null,

  mode: null,
  custom: null,
  editing: false,
  type: null,
  cTyped: null,
  stdUser: null,
  admin: null,

  init() {
    this._super(...arguments);
    let mode = null;
    let editing = get(this, 'editing');
    let dfu = get(this, 'defaultUser');
    let current = dfu.get(`${get(this, 'type')}RoleBindings`);
    let custom  = get(this, 'model.roles').filterBy('hidden', false).filter((role) => {
      return role.get('id') !== `${get(this, 'type')}-admin`
        && role.get('id') !== `${get(this, 'type')}-owner`
        && role.get('id') !== `${get(this, 'type')}-member`
        && role.get('context') === `${get(this, 'type')}`;
    }).map((role) => {
      const binding = current.findBy('roleTemplateId', get(role, 'id')) || null;
      return {
        role,
        active: !!binding,
        existing: binding,
      }
    });
    if (editing && current.length === 1) {
      mode = get(current, 'firstObject.roleTemplateId');
    } else if (editing && current.length > 1){
      mode = CUSTOM;
    } else {
      mode = `${get(this, 'type')}-member`;
    }
    let model = {
      type: `${get(this, 'type')}RoleTemplateBinding`,
      subjectKind: 'User',
      subjectName: null,
    };
    set(model, `${get(this, 'type')}Id`, get(this, `model.${get(this, 'type')}.id`))
    setProperties(this, {
      primaryResource: this.make(model),
      defaultUser: dfu,
      custom: custom,
      mode: mode,
      stdUser: `${get(this, 'type')}-member`,
      admin: `${get(this, 'type')}-owner`,
      cTyped: get(this, 'type').capitalize()
    });
  },

  make(role) {
    return get(this, 'globalStore').createRecord(role);
  },

  actions: {
    save() {
      let mode = get(this, 'mode');
      let add = [];
      let remove = [];
      let pr = get(this, 'primaryResource');
      const custom = get(this, 'custom');

      switch ( mode ) {
      case `${get(this, 'type')}-owner`:
      case `${get(this, 'type')}-member`:
        set(pr, 'roleTemplateId', mode);
        add = [ pr ];
        break;
      case CUSTOM:
        add = custom.filterBy('active',true ).filterBy('existing',null).map((x) => {
          let neu = get(this, 'primaryResource').clone();
          set(neu, 'roleTemplateId', get(x, 'role.id'));
          return neu;
        });
        remove = custom.filterBy('active',false).filterBy('existing').map(y => y.existing);
        break;
      }

      debugger;
      return PromiseAll(add.map(x => x.save())).then(() => {
        return PromiseAll(remove.map(x => x.delete())).then(() => {
          return this.doneSaving();
        });
      });
    },

  }

});
<commit_msg>remove debugger<commit_after>import Component from '@ember/component'
import { all as PromiseAll } from 'rsvp';
import { inject as service } from '@ember/service';
import { get, set, setProperties } from '@ember/object';
import layout from './template';
import NewOrEdit from 'ui/mixins/new-or-edit';

const CUSTOM = 'custom';

export default Component.extend(NewOrEdit,{
  layout,
  globalStore: service(),

  user: null,
  primaryResource: null,

  mode: null,
  custom: null,
  editing: false,
  type: null,
  cTyped: null,
  stdUser: null,
  admin: null,

  init() {
    this._super(...arguments);
    let mode = null;
    let editing = get(this, 'editing');
    let dfu = get(this, 'defaultUser');
    let current = dfu.get(`${get(this, 'type')}RoleBindings`);
    let custom  = get(this, 'model.roles').filterBy('hidden', false).filter((role) => {
      return role.get('id') !== `${get(this, 'type')}-admin`
        && role.get('id') !== `${get(this, 'type')}-owner`
        && role.get('id') !== `${get(this, 'type')}-member`
        && role.get('context') === `${get(this, 'type')}`;
    }).map((role) => {
      const binding = current.findBy('roleTemplateId', get(role, 'id')) || null;
      return {
        role,
        active: !!binding,
        existing: binding,
      }
    });
    if (editing && current.length === 1) {
      mode = get(current, 'firstObject.roleTemplateId');
    } else if (editing && current.length > 1){
      mode = CUSTOM;
    } else {
      mode = `${get(this, 'type')}-member`;
    }
    let model = {
      type: `${get(this, 'type')}RoleTemplateBinding`,
      subjectKind: 'User',
      subjectName: null,
    };
    set(model, `${get(this, 'type')}Id`, get(this, `model.${get(this, 'type')}.id`))
    setProperties(this, {
      primaryResource: this.make(model),
      defaultUser: dfu,
      custom: custom,
      mode: mode,
      stdUser: `${get(this, 'type')}-member`,
      admin: `${get(this, 'type')}-owner`,
      cTyped: get(this, 'type').capitalize()
    });
  },

  make(role) {
    return get(this, 'globalStore').createRecord(role);
  },

  actions: {
    save() {
      let mode = get(this, 'mode');
      let add = [];
      let remove = [];
      let pr = get(this, 'primaryResource');
      const custom = get(this, 'custom');

      switch ( mode ) {
      case `${get(this, 'type')}-owner`:
      case `${get(this, 'type')}-member`:
        set(pr, 'roleTemplateId', mode);
        add = [ pr ];
        break;
      case CUSTOM:
        add = custom.filterBy('active',true ).filterBy('existing',null).map((x) => {
          let neu = get(this, 'primaryResource').clone();
          set(neu, 'roleTemplateId', get(x, 'role.id'));
          return neu;
        });
        remove = custom.filterBy('active',false).filterBy('existing').map(y => y.existing);
        break;
      }

      return PromiseAll(add.map(x => x.save())).then(() => {
        return PromiseAll(remove.map(x => x.delete())).then(() => {
          return this.doneSaving();
        });
      });
    },

  }

});
<|endoftext|>


<commit_before>/*!
 * jQuery blockUI plugin
 * Version 2.70.0-2014.11.23
 * Requires jQuery v1.7 or later
 *
 * Examples at: http://malsup.com/jquery/block/
 * Copyright (c) 2007-2013 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Thanks to Amir-Hossein Sobhi for some excellent contributions!
 */

;(function() {
/*jshint eqeqeq:false curly:false latedef:false */
"use strict";

	function setup($) {
		$.fn._fadeIn = $.fn.fadeIn;

		var noOp = $.noop || function() {};

		// this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle
		// confusing userAgent strings on Vista)
		var msie = /MSIE/.test(navigator.userAgent);
		var ie6  = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent);
		var mode = document.documentMode || 0;
		var setExpr = $.isFunction( document.createElement('div').style.setExpression );

		// global $ methods for blocking/unblocking the entire page
		$.blockUI   = function(opts) { install(window, opts); };
		$.unblockUI = function(opts) { remove(window, opts); };

		// convenience method for quick growl-like notifications  (http://www.google.com/search?q=growl)
		$.growlUI = function(title, message, timeout, onClose) {
			var $m = $('

');
			if (title) $m.append('
'+title+'
');
			if (message) $m.append('
'+message+'
');
			if (timeout === undefined) timeout = 3000;

			// Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications
			var callBlock = function(opts) {
				opts = opts || {};

				$.blockUI({
					message: $m,
					fadeIn : typeof opts.fadeIn  !== 'undefined' ? opts.fadeIn  : 700,
					fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000,
					timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout,
					centerY: false,
					showOverlay: false,
					onUnblock: onClose,
					css: $.blockUI.defaults.growlCSS
				});
			};

			callBlock();
			var nonmousedOpacity = $m.css('opacity');
			$m.mouseover(function() {
				callBlock({
					fadeIn: 0,
					timeout: 30000
				});

				var displayBlock = $('.blockMsg');
				displayBlock.stop(); // cancel fadeout if it has started
				displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency
			}).mouseout(function() {
				$('.blockMsg').fadeOut(1000);
			});
			// End konapun additions
		};

		// plugin method for blocking element content
		$.fn.block = function(opts) {
			if ( this[0] === window ) {
				$.blockUI( opts );
				return this;
			}
			var fullOpts = $.extend({}, $.blockUI.defaults, opts || {});
			this.each(function() {
				var $el = $(this);
				if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked'))
					return;
				$el.unblock({ fadeOut: 0 });
			});

			return this.each(function() {
				if ($.css(this,'position') == 'static') {
					this.style.position = 'relative';
					$(this).data('blockUI.static', true);
				}
				this.style.zoom = 1; // force 'hasLayout' in ie
				install(this, opts);
			});
		};

		// plugin method for unblocking element content
		$.fn.unblock = function(opts) {
			if ( this[0] === window ) {
				$.unblockUI( opts );
				return this;
			}
			return this.each(function() {
				remove(this, opts);
			});
		};

		$.blockUI.version = 2.70; // 2nd generation blocking at no extra cost!

		// override these in your code to change the default behavior and style
		$.blockUI.defaults = {
			// message displayed when blocking (use null for no message)
			message:  '
Please wait...
',

			title: null,		// title string; only used when theme == true
			draggable: true,	// only used when theme == true (requires jquery-ui.js to be loaded)

			theme: false, // set to true to use with jQuery UI themes

			// styles for the message when blocking; if you wish to disable
			// these and use an external stylesheet then do this in your code:
			// $.blockUI.defaults.css = {};
			css: {
				padding:	0,
				margin:		0,
				width:		'30%',
				top:		'40%',
				left:		'35%',
				textAlign:	'center',
				color:		'#000',
				border:		'3px solid #aaa',
				backgroundColor:'#fff',
				cursor:		'wait'
			},

			// minimal style set used when themes are used
			themedCSS: {
				width:	'30%',
				top:	'40%',
				left:	'35%'
			},

			// styles for the overlay
			overlayCSS:  {
				backgroundColor:	'#000',
				opacity:			0.6,
				cursor:				'wait'
			},

			// style to replace wait cursor before unblocking to correct issue
			// of lingering wait cursor
			cursorReset: 'default',

			// styles applied when using $.growlUI
			growlCSS: {
				width:		'350px',
				top:		'10px',
				left:		'',
				right:		'10px',
				border:		'none',
				padding:	'5px',
				opacity:	0.6,
				cursor:		'default',
				color:		'#fff',
				backgroundColor: '#000',
				'-webkit-border-radius':'10px',
				'-moz-border-radius':	'10px',
				'border-radius':		'10px'
			},

			// IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w
			// (hat tip to Jorge H. N. de Vasconcelos)
			/*jshint scripturl:true */
			iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank',

			// force usage of iframe in non-IE browsers (handy for blocking applets)
			forceIframe: false,

			// z-index for the blocking overlay
			baseZ: 1000,

			// set these to true to have the message automatically centered
			centerX: true, // <-- only effects element blocking (page block controlled via css above)
			centerY: true,

			// allow body element to be stetched in ie6; this makes blocking look better
			// on "short" pages.  disable if you wish to prevent changes to the body height
			allowBodyStretch: true,

			// enable if you want key and mouse events to be disabled for content that is blocked
			bindEvents: true,

			// be default blockUI will supress tab navigation from leaving blocking content
			// (if bindEvents is true)
			constrainTabKey: true,

			// fadeIn time in millis; set to 0 to disable fadeIn on block
			fadeIn:  200,

			// fadeOut time in millis; set to 0 to disable fadeOut on unblock
			fadeOut:  400,

			// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
			timeout: 0,

			// disable if you don't want to show the overlay
			showOverlay: true,

			// if true, focus will be placed in the first available input field when
			// page blocking
			focusInput: true,

            // elements that can receive focus
            focusableElements: ':input:enabled:visible',

			// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
			// no longer needed in 2012
			// applyPlatformOpacityRules: true,

			// callback method invoked when fadeIn has completed and blocking message is visible
			onBlock: null,

			// callback method invoked when unblocking has completed; the callback is
			// passed the element that has been unblocked (which is the window object for page
			// blocks) and the options that were passed to the unblock call:
			//	onUnblock(element, options)
			onUnblock: null,

			// callback method invoked when the overlay area is clicked.
			// setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used.
			onOverlayClick: null,

			// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
			quirksmodeOffsetHack: 4,

			// class name of the message block
			blockMsgClass: 'blockMsg',

			// if it is already blocked, then ignore it (don't unblock and reblock)
			ignoreIfBlocked: false
		};

		// private data and functions follow...

		var pageBlock = null;
		var pageBlockEls = [];

		function install(el, opts) {
			var css, themedCSS;
			var full = (el == window);
			var msg = (opts && opts.message !== undefined ? opts.message : undefined);
			opts = $.extend({}, $.blockUI.defaults, opts || {});

			if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked'))
				return;

			opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {});
			css = $.extend({}, $.blockUI.defaults.css, opts.css || {});
			if (opts.onOverlayClick)
				opts.overlayCSS.cursor = 'pointer';

			themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {});
			msg = msg === undefined ? opts.message : msg;

			// remove the current block (if there is one)
			if (full && pageBlock)
				remove(window, {fadeOut:0});

			// if an existing element is being used as the blocking content then we capture
			// its current place in the DOM (and current display style) so we can restore
			// it when we unblock
			if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) {
				var node = msg.jquery ? msg[0] : msg;
				var data = {};
				$(el).data('blockUI.history', data);
				data.el = node;
				data.parent = node.parentNode;
				data.display = node.style.display;
				data.position = node.style.position;
				if (data.parent)
					data.parent.removeChild(node);
			}

			$(el).data('blockUI.onUnblock', opts.onUnblock);
			var z = opts.baseZ;

			// blockUI uses 3 layers for blocking, for simplicity they are all used on every platform;
			// layer1 is the iframe layer which is used to supress bleed through of underlying content
			// layer2 is the overlay layer which has opacity and a wait cursor (by default)
			// layer3 is the message content that is displayed while blocking
			var lyr1, lyr2, lyr3, s;
			if (msie || opts.forceIframe)
				lyr1 = $('');
			else
				lyr1 = $('

');

			if (opts.theme)
				lyr2 = $('

');
			else
				lyr2 = $('

');

			if (opts.theme && full) {
				s = '
';
				if ( opts.title ) {
					s += '
'+(opts.title || ' ')+'
';
				}
				s += '

';
				s += '
';
			}
			else if (opts.theme) {
				s = '
';
				if ( opts.title ) {
					s += '
'+(opts.title || ' ')+'
';
				}
				s += '

';
				s += '
';
			}
			else if (full) {
				s = '

';
			}
			else {
				s = '

';
			}
			lyr3 = $(s);

			// if we have a message, style it
			if (msg) {
				if (opts.theme) {
					lyr3.css(themedCSS);
					lyr3.addClass('ui-widget-content');
				}
				else
					lyr3.css(css);
			}

			// style the overlay
			if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/)
				lyr2.css(opts.overlayCSS);
			lyr2.css('position', full ? 'fixed' : 'absolute');

			// make iframe layer transparent in IE
			if (msie || opts.forceIframe)
				lyr1.css('opacity',0.0);

			//$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el);
			var layers = [lyr1,lyr2,lyr3], $par = full ? $('body') : $(el);
			$.each(layers, function() {
				this.appendTo($par);
			});

			if (opts.theme && opts.draggable && $.fn.draggable) {
				lyr3.draggable({
					handle: '.ui-dialog-titlebar',
					cancel: 'li'
				});
			}

			// ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling)
			var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0);
			if (ie6 || expr) {
				// give body 100% height
				if (full && opts.allowBodyStretch && $.support.boxModel)
					$('html,body').css('height','100%');

				// fix ie6 issue when blocked element has a border width
				if ((ie6 || !$.support.boxModel) && !full) {
					var t = sz(el,'borderTopWidth'), l = sz(el,'borderLeftWidth');
					var fixT = t ? '(0 - '+t+')' : 0;
					var fixL = l ? '(0 - '+l+')' : 0;
				}

				// simulate fixed position
				$.each(layers, function(i,o) {
					var s = o[0].style;
					s.position = 'absolute';
					if (i < 2) {
						if (full)
							s.setExpression('height','Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:'+opts.quirksmodeOffsetHack+') + "px"');
						else
							s.setExpression('height','this.parentNode.offsetHeight + "px"');
						if (full)
							s.setExpression('width','jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"');
						else
							s.setExpression('width','this.parentNode.offsetWidth + "px"');
						if (fixL) s.setExpression('left', fixL);
						if (fixT) s.setExpression('top', fixT);
					}
					else if (opts.centerY) {
						if (full) s.setExpression('top','(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"');
						s.marginTop = 0;
					}
					else if (!opts.centerY && full) {
						var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0;
						var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + '+top+') + "px"';
						s.setExpression('top',expression);
					}
				});
			}

			// show the message
			if (msg) {
				if (opts.theme)
					lyr3.find('.ui-widget-content').append(msg);
				else
					lyr3.append(msg);
				if (msg.jquery || msg.nodeType)
					$(msg).show();
			}

			if ((msie || opts.forceIframe) && opts.showOverlay)
				lyr1.show(); // opacity is zero
			if (opts.fadeIn) {
				var cb = opts.onBlock ? opts.onBlock : noOp;
				var cb1 = (opts.showOverlay && !msg) ? cb : noOp;
				var cb2 = msg ? cb : noOp;
				if (opts.showOverlay)
					lyr2._fadeIn(opts.fadeIn, cb1);
				if (msg)
					lyr3._fadeIn(opts.fadeIn, cb2);
			}
			else {
				if (opts.showOverlay)
					lyr2.show();
				if (msg)
					lyr3.show();
				if (opts.onBlock)
					opts.onBlock.bind(lyr3)();
			}

			// bind key and mouse events
			bind(1, el, opts);

			if (full) {
				pageBlock = lyr3[0];
				pageBlockEls = $(opts.focusableElements,pageBlock);
				if (opts.focusInput)
					setTimeout(focus, 20);
			}
			else
				center(lyr3[0], opts.centerX, opts.centerY);

			if (opts.timeout) {
				// auto-unblock
				var to = setTimeout(function() {
					if (full)
						$.unblockUI(opts);
					else
						$(el).unblock(opts);
				}, opts.timeout);
				$(el).data('blockUI.timeout', to);
			}
		}

		// remove the block
		function remove(el, opts) {
			var count;
			var full = (el == window);
			var $el = $(el);
			var data = $el.data('blockUI.history');
			var to = $el.data('blockUI.timeout');
			if (to) {
				clearTimeout(to);
				$el.removeData('blockUI.timeout');
			}
			opts = $.extend({}, $.blockUI.defaults, opts || {});
			bind(0, el, opts); // unbind events

			if (opts.onUnblock === null) {
				opts.onUnblock = $el.data('blockUI.onUnblock');
				$el.removeData('blockUI.onUnblock');
			}

			var els;
			if (full) // crazy selector to handle odd field errors in ie6/7
				els = $('body').children().filter('.blockUI').add('body > .blockUI');
			else
				els = $el.find('>.blockUI');

			// fix cursor issue
			if ( opts.cursorReset ) {
				if ( els.length > 1 )
					els[1].style.cursor = opts.cursorReset;
				if ( els.length > 2 )
					els[2].style.cursor = opts.cursorReset;
			}

			if (full)
				pageBlock = pageBlockEls = null;

			if (opts.fadeOut) {
				count = els.length;
				els.stop().fadeOut(opts.fadeOut, function() {
					if ( --count === 0)
						reset(els,data,opts,el);
				});
			}
			else
				reset(els, data, opts, el);
		}

		// move blocking element back into the DOM where it started
		function reset(els,data,opts,el) {
			var $el = $(el);
			if ( $el.data('blockUI.isBlocked') )
				return;

			els.each(function(i,o) {
				// remove via DOM calls so we don't lose event handlers
				if (this.parentNode)
					this.parentNode.removeChild(this);
			});

			if (data && data.el) {
				data.el.style.display = data.display;
				data.el.style.position = data.position;
				data.el.style.cursor = 'default'; // #59
				if (data.parent)
					data.parent.appendChild(data.el);
				$el.removeData('blockUI.history');
			}

			if ($el.data('blockUI.static')) {
				$el.css('position', 'static'); // #22
			}

			if (typeof opts.onUnblock == 'function')
				opts.onUnblock(el,opts);

			// fix issue in Safari 6 where block artifacts remain until reflow
			var body = $(document.body), w = body.width(), cssW = body[0].style.width;
			body.width(w-1).width(w);
			body[0].style.width = cssW;
		}

		// bind/unbind the handler
		function bind(b, el, opts) {
			var full = el == window, $el = $(el);

			// don't bother unbinding if there is nothing to unbind
			if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked')))
				return;

			$el.data('blockUI.isBlocked', b);

			// don't bind events when overlay is not in use or if bindEvents is false
			if (!full || !opts.bindEvents || (b && !opts.showOverlay))
				return;

			// bind anchors and inputs for mouse and key events
			var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove';
			if (b)
				$(document).bind(events, opts, handler);
			else
				$(document).unbind(events, handler);

		// former impl...
		//		var $e = $('a,:input');
		//		b ? $e.bind(events, opts, handler) : $e.unbind(events, handler);
		}

		// event handler to suppress keyboard/mouse events when blocking
		function handler(e) {
			// allow tab navigation (conditionally)
			if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) {
				if (pageBlock && e.data.constrainTabKey) {
					var els = pageBlockEls;
					var fwd = !e.shiftKey && e.target === els[els.length-1];
					var back = e.shiftKey && e.target === els[0];
					if (fwd || back) {
						setTimeout(function(){focus(back);},10);
						return false;
					}
				}
			}
			var opts = e.data;
			var target = $(e.target);
			if (target.hasClass('blockOverlay') && opts.onOverlayClick)
				opts.onOverlayClick(e);

			// allow events within the message content
			if (target.parents('div.' + opts.blockMsgClass).length > 0)
				return true;

			// allow events for content that is not being blocked
			return target.parents().children().filter('div.blockUI').length === 0;
		}

		function focus(back) {
			if (!pageBlockEls)
				return;
			var e = pageBlockEls[back===true ? pageBlockEls.length-1 : 0];
			if (e)
				e.focus();
		}

		function center(el, x, y) {
			var p = el.parentNode, s = el.style;
			var l = ((p.offsetWidth - el.offsetWidth)/2) - sz(p,'borderLeftWidth');
			var t = ((p.offsetHeight - el.offsetHeight)/2) - sz(p,'borderTopWidth');
			if (x) s.left = l > 0 ? (l+'px') : '0';
			if (y) s.top  = t > 0 ? (t+'px') : '0';
		}

		function sz(el, p) {
			return parseInt($.css(el,p),10)||0;
		}

	}

	/*global define:true */
	if (typeof define === 'function' && define.amd && define.amd.jQuery) {
		define(['jquery'], setup);
	} else {
		setup(jQuery);
	}

})();
<commit_msg>Delete jquery.blockUI.js<commit_after><|endoftext|>


<commit_before>import { EventEmitter } from 'events';
import assign from 'react/lib/Object.assign';

var dummyData = [
  { id: 1, title: 'Ipsum Cursus Venenatis Etiam' },
  { id: 2, title: 'Nullam Nibh Pharetra Vulputate' }
];

var API = assign({}, EventEmitter.prototype, {

  start () {
    setTimeout(() => {
      this.emit('success', dummyData);
    }, 1000);
  },

  stop () {
    console.log('stop api');
  }

});

export default API;
<commit_msg>stash<commit_after>import { EventEmitter } from 'events';
import assign from 'react/lib/Object.assign';

var API = assign({}, EventEmitter.prototype, {

  start () {
    this.source = new EventSource('/data-stream');

    this.source.addEventListener('message', function(e) {
      console.log('received message');
      console.log(arguments);
    }, false);
  },

  stop () {
    this.source.close();
  }

});

export default API;
<|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence');
var clean = require('gulp-clean');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var cssnano = require('gulp-cssnano');
var minifyHTML = require('gulp-minify-html');

gulp.task('default', function() {
	// place code for your default task here
});

gulp.task('build', function(callback) {
 	runSequence(
		'build-clean',
		'build-js',
		'build-css',
		'build-html',
		callback);
});

gulp.task('build-clean', function() {
	return gulp.src('dist').pipe(clean());
});

gulp.task('build-js', function() {
	gulp.src([
		'src/vendor/jspdf/jspdf.min.js',
		'src/vendor/sdate/sdate.js',
		'src/js/life-calendar.js',
		'src/js/app.js'
	])
	.pipe(concat('scripts.min.js'))
	.pipe(uglify())
	.pipe(gulp.dest('dist'))
});

gulp.task('build-css', function() {
	return gulp.src([
		'src/vendor/bootstrap/css/bootstrap.min.css',
		'src/css/main.css'
	])
	.pipe(concat('styles.min.css'))
	.pipe(cssnano())
	.pipe(gulp.dest('dist'));
});

gulp.task('build-html', function() {
	return gulp.src('src/index.html')
		.pipe(minifyHTML({ empty: true }))
		.pipe(gulp.dest('dist'));
});
<commit_msg>Update gulp tasks<commit_after>const gulp = require('gulp');
const clean = require('gulp-clean');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const cleanCSS = require('gulp-clean-css');
const htmlmin = require('gulp-htmlmin');

gulp.task('clean', () => {
	return gulp.src('dist').pipe(clean());
});

gulp.task('scripts', () => {
	return gulp.src([
		'src/vendor/jspdf/jspdf.min.js',
		'src/vendor/sdate/sdate.js',
		'src/js/life-calendar.js',
		'src/js/app.js'
	])
	.pipe(concat('scripts.min.js'))
	.pipe(uglify())
	.pipe(gulp.dest('dist'))
});

gulp.task('styles', () => {
	return gulp.src([
		'src/vendor/bootstrap/css/bootstrap.min.css',
		'src/css/main.css'
	])
	.pipe(concat('styles.min.css'))
	.pipe(cleanCSS())
	.pipe(gulp.dest('dist'));
});

gulp.task('html', () => {
	return gulp.src('src/index.html')
		.pipe(htmlmin({ collapseWhitespace: true }))
		.pipe(gulp.dest('dist'));
});

gulp.task('build',
	gulp.series(
		'clean',
		'scripts',
		'styles',
		'html',
	)
);

gulp.task('default', gulp.series('build'));
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View, FlatList, TouchableOpacity } from 'react-native';
import Cell from './DataTable/Cell';
import { dataTableStyles } from '../globalStyles/index';
import { HeaderCell, HeaderRow } from './DataTable/index';
import { getItemLayout } from '../pages/dataTableUtilities';

/**
 * Simple table component for rendering a large list of un-changing data.
 * Only offers a selection feature.
 *
 * Usage:
 * Pass an array - data: [ { id, .. }, { id, .. }, .. ]
 * Also an array - columns: [ { key, alignText, title } ] (example: getColumns.js)
 * Such that each column.key is a field within an object in the data array.
 *
 * selectRow should be a function: (rowId) => { ... }
 *
 * extraData, an object with the shape: {rowId1: [bool], rowId2: [bool], ... } used
 * to trigger styling effects on selected rows.
 */
export const SimpleTable = React.memo(
  React.forwardRef(({ data, columns, selectRow, extraData }, ref) => {
    const {
      cellText,
      cellContainer,
      selectedRow: selectedRowStyle,
      alternateRow: alternateRowStyle,
      row: basicRowStyle,
      headerRow,
      headerCells,
    } = dataTableStyles;

    const renderCells = useCallback(rowData => {
      const { id } = rowData;

      return columns.map(({ key, width, alignText }, index) => (
        <Cell
          value={rowData[key]}
          viewStyle={cellContainer[alignText]}
          textStyle={cellText[alignText]}
          isLastCell={index === columns.length - 1}
          width={width}
          key={`${id}${key}`}
        />
      ));
    }, []);

    const renderRow = useCallback(
      ({ item, index }) => {
        const { id } = item;
        const isSelected = extraData[id];
        const rowStyle = isSelected
          ? selectedRowStyle
          : (index % 2 === 0 && alternateRowStyle) || basicRowStyle;

        return (
          <SimpleRow
            rowData={item}
            rowIndex={index}
            rowKey={id}
            style={rowStyle}
            renderCells={renderCells}
            onPress={selectRow}
            isSelected={isSelected}
          />
        );
      },
      [extraData]
    );

    const renderHeaderCells = useCallback(
      () =>
        columns.map(({ title, width, alignText }, index) => (
          <HeaderCell
            title={title}
            containerStyle={headerCells[alignText]}
            textStyle={cellText[alignText]}
            isLastCell={index === columns.length - 1}
            width={width}
          />
        )),
      [columns]
    );

    const renderHeaders = useCallback(
      () => <HeaderRow style={headerRow} columns={columns} renderCells={renderHeaderCells} />,
      [columns]
    );

    return (
      <FlatList
        ref={ref}
        data={data}
        getItemLayout={getItemLayout}
        renderItem={renderRow}
        stickyHeaderIndices={[0]}
        ListHeaderComponent={renderHeaders}
        extraData={extraData}
      />
    );
  })
);

SimpleTable.propTypes = {
  data: PropTypes.array.isRequired,
  columns: PropTypes.array.isRequired,
  selectRow: PropTypes.func.isRequired,
  extraData: PropTypes.object.isRequired,
};

const SimpleRow = React.memo(({ rowData, style, rowKey, renderCells, onPress }) => {
  const onSelect = useCallback(() => onPress(rowKey), [rowKey, onPress]);
  return (
    <TouchableOpacity onPress={onSelect} key={rowKey}>
      <View style={style}>{renderCells(rowData)}</View>
    </TouchableOpacity>
  );
});

SimpleRow.defaultProps = {
  onPress: null,
};

SimpleRow.propTypes = {
  rowData: PropTypes.object.isRequired,
  rowKey: PropTypes.string.isRequired,
  style: PropTypes.object.isRequired,
  renderCells: PropTypes.func.isRequired,
  onPress: PropTypes.func,
};
<commit_msg>Add update SimpleTable extraData access<commit_after>/* eslint-disable react/forbid-prop-types */
import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import { View, FlatList, TouchableOpacity } from 'react-native';
import Cell from './DataTable/Cell';
import { dataTableStyles } from '../globalStyles/index';
import { HeaderCell, HeaderRow } from './DataTable/index';
import { getItemLayout } from '../pages/dataTableUtilities';

/**
 * Simple table component for rendering a large list of un-changing data.
 * Only offers a selection feature.
 *
 * Usage:
 * Pass an array - data: [ { id, .. }, { id, .. }, .. ]
 * Also an array - columns: [ { key, alignText, title } ] (example: getColumns.js)
 * Such that each column.key is a field within an object in the data array.
 *
 * selectRow should be a function: (rowId) => { ... }
 *
 * extraData, an object with the shape: {rowId1: [bool], rowId2: [bool], ... } used
 * to trigger styling effects on selected rows.
 */
export const SimpleTable = React.memo(
  React.forwardRef(({ data, columns, selectRow, extraData }, ref) => {
    const {
      cellText,
      cellContainer,
      selectedRow: selectedRowStyle,
      alternateRow: alternateRowStyle,
      row: basicRowStyle,
      headerRow,
      headerCells,
    } = dataTableStyles;

    const renderCells = useCallback(rowData => {
      const { id } = rowData;

      return columns.map(({ key, width, alignText }, index) => (
        <Cell
          value={rowData[key]}
          viewStyle={cellContainer[alignText]}
          textStyle={cellText[alignText]}
          isLastCell={index === columns.length - 1}
          width={width}
          key={`${id}${key}`}
        />
      ));
    }, []);

    const renderRow = useCallback(
      ({ item, index }) => {
        const { id } = item;
        const isSelected = extraData?.[id];
        const rowStyle = isSelected
          ? selectedRowStyle
          : (index % 2 === 0 && alternateRowStyle) || basicRowStyle;

        return (
          <SimpleRow
            rowData={item}
            rowIndex={index}
            rowKey={id}
            style={rowStyle}
            renderCells={renderCells}
            onPress={selectRow}
            isSelected={isSelected}
          />
        );
      },
      [extraData]
    );

    const renderHeaderCells = useCallback(
      () =>
        columns.map(({ title, width, alignText }, index) => (
          <HeaderCell
            title={title}
            containerStyle={headerCells[alignText]}
            textStyle={cellText[alignText]}
            isLastCell={index === columns.length - 1}
            width={width}
          />
        )),
      [columns]
    );

    const renderHeaders = useCallback(
      () => <HeaderRow style={headerRow} columns={columns} renderCells={renderHeaderCells} />,
      [columns]
    );

    return (
      <FlatList
        ref={ref}
        data={data}
        getItemLayout={getItemLayout}
        renderItem={renderRow}
        stickyHeaderIndices={[0]}
        ListHeaderComponent={renderHeaders}
        extraData={extraData}
      />
    );
  })
);

SimpleTable.propTypes = {
  data: PropTypes.array.isRequired,
  columns: PropTypes.array.isRequired,
  selectRow: PropTypes.func.isRequired,
  extraData: PropTypes.object.isRequired,
};

const SimpleRow = React.memo(({ rowData, style, rowKey, renderCells, onPress }) => {
  const onSelect = useCallback(() => onPress(rowKey), [rowKey, onPress]);
  return (
    <TouchableOpacity onPress={onSelect} key={rowKey}>
      <View style={style}>{renderCells(rowData)}</View>
    </TouchableOpacity>
  );
});

SimpleRow.defaultProps = {
  onPress: null,
};

SimpleRow.propTypes = {
  rowData: PropTypes.object.isRequired,
  rowKey: PropTypes.string.isRequired,
  style: PropTypes.object.isRequired,
  renderCells: PropTypes.func.isRequired,
  onPress: PropTypes.func,
};
<|endoftext|>


<commit_before>var myChart;

function computeRolls(dice, amount) {
    var diceRolls = [];

    // Initializes the array
    for (var i = 0; i < 1000; ++i) {
        diceRolls[i] = 0
    }

    for (var i = 0; i < 1000; ++i) {
        for (var j = 0; j < amount; ++j) {
            diceRolls[i] += math.randomInt(1, parseInt(dice) + 1);
        }
    }

    return diceRolls;
}

function computeHistogram(diceRolls) {
    var histogram = [];

    var diceTypeList = document.getElementById("dicetype");
    var diceType = diceTypeList.options[diceTypeList.selectedIndex].value;
    var minValue = document.getElementById("diceamount").value;
    var maxValue = minValue * diceType

    for (var i = minValue; i <= maxValue; ++i)
    {
        histogram[i] = 0
    }

    for (var i = 0; i < diceRolls.length; ++i) {
        histogram[diceRolls[i]]++;
    }

    //Normalizing
    for (var i = 0; i < histogram.length; ++i){
        histogram[i] = 100*histogram[i]/1000;
    }

    return histogram;
}

function generateChart() {
    var diceTypeList = document.getElementById("dicetype");
    var diceType = diceTypeList.options[diceTypeList.selectedIndex].value;
    var diceNumber = document.getElementById("diceamount").value;
    var diceRolls = computeRolls(diceType, diceNumber);
    var histogram = computeHistogram(diceRolls);

    // Creates chart labels based on dice thrown
    var resultLabels = [];
    for (var i = 0; i <= diceNumber * diceType; i++)
    {
        resultLabels.push( i.toString() );
    }

    var div = document.getElementById("chartdiv");
    var context = document.getElementById("DiceRollChart");

    // Cleans chart if already created
    if (myChart != null)
        myChart.destroy();

    myChart = new Chart(context, {
        type: 'bar',
        data: {
            labels: resultLabels,
            datasets: [{
                label: 'Result Probability',
                data: histogram,
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            },
            responsive: true
        }
    });
}<commit_msg>Adds license information to script.js<commit_after>/***
MIT License

Copyright (c) 2017 Bruno Baère Pederassi Lomba de Araujo

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/

var myChart;

function computeRolls(dice, amount) {
    var diceRolls = [];

    // Initializes the array
    for (var i = 0; i < 1000; ++i) {
        diceRolls[i] = 0
    }

    for (var i = 0; i < 1000; ++i) {
        for (var j = 0; j < amount; ++j) {
            diceRolls[i] += math.randomInt(1, parseInt(dice) + 1);
        }
    }

    return diceRolls;
}

function computeHistogram(diceRolls) {
    var histogram = [];

    var diceTypeList = document.getElementById("dicetype");
    var diceType = diceTypeList.options[diceTypeList.selectedIndex].value;
    var minValue = document.getElementById("diceamount").value;
    var maxValue = minValue * diceType

    for (var i = minValue; i <= maxValue; ++i)
    {
        histogram[i] = 0
    }

    for (var i = 0; i < diceRolls.length; ++i) {
        histogram[diceRolls[i]]++;
    }

    //Normalizing
    for (var i = 0; i < histogram.length; ++i){
        histogram[i] = 100*histogram[i]/1000;
    }

    return histogram;
}

function generateChart() {
    var diceTypeList = document.getElementById("dicetype");
    var diceType = diceTypeList.options[diceTypeList.selectedIndex].value;
    var diceNumber = document.getElementById("diceamount").value;
    var diceRolls = computeRolls(diceType, diceNumber);
    var histogram = computeHistogram(diceRolls);

    // Creates chart labels based on dice thrown
    var resultLabels = [];
    for (var i = 0; i <= diceNumber * diceType; i++)
    {
        resultLabels.push( i.toString() );
    }

    var div = document.getElementById("chartdiv");
    var context = document.getElementById("DiceRollChart");

    // Cleans chart if already created
    if (myChart != null)
        myChart.destroy();

    myChart = new Chart(context, {
        type: 'bar',
        data: {
            labels: resultLabels,
            datasets: [{
                label: 'Result Probability',
                data: histogram,
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            },
            responsive: true
        }
    });
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    grunt.initConfig({

        exec: {
          build: {
            command: 'node r.js -o r.config.js',
            stdout: true,
            stderr: true
          },
          deploy : {
            command : 'git subtree push --prefix bin heroku master'
          }
        },

        cssmin: {
          css: {
            src: 'bin/public/css/main_temp.css',
            dest: 'bin/public/css/main.css'
          }
        },

        imageEmbed: {
          dist: {
            src: [ "src/public/css/main.css" ],
            dest: "bin/public/css/main_temp.css",
            deleteAfterEncoding : false
          }
        },

        jsdoc : {
          dist : {
              src: ['src/public/js/**'],
              dest: 'docs'
          }
        },

        copy: {
          init: {
            files: {
              'bin/': 'src/**'
            }
          },

          js : {
            files: {
              'bin/public/js/libs/require-min.js' : 'src/public/js/libs/require-min.js'
            }
          }
        },

        clean: {
          init: ['bin', 'docs'],
          js : 'bin/public/js',
          css : 'bin/public/css',
          post : ['bin/public/css/main_temp.css', 'bin/public/css/img', 'bin/.DS_Store', 'bin/public/test', 'bin/test']
        }

    });

    grunt.loadNpmTasks('grunt-contrib');
    grunt.loadNpmTasks('grunt-jsdoc-plugin');
    grunt.loadNpmTasks('grunt-image-embed');
    grunt.loadNpmTasks('grunt');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-css');

    grunt.registerTask('bump', function(versionType) {
      versionType = grunt.option('type') || 'patch';
      var package = grunt.file.readJSON('package.json');
      package.version = grunt.helper('bump_version', package.version, versionType || 'patch');
      grunt.file.write('package.json', JSON.stringify(package, null, '  '));

      var packageDeploy = grunt.file.readJSON('src/package.json');
      packageDeploy.version = package.version;
      packageDeploy.name = package.name;
      packageDeploy.author = package.author;
      packageDeploy.description = package.description;
      packageDeploy.bugs = package.bugs;
      packageDeploy.scripts.start = "node server";
      grunt.file.write('src/package.json', JSON.stringify(packageDeploy, null, '  '));
      grunt.log.ok('Version bumped to ' + packageDeploy.version);
    })

    grunt.registerHelper('bump_version', function(version, versionType) {
      var type = {
        patch: 2,
        minor: 1,
        major: 0
      };

      var parts = version.split('.');
      var idx = type[versionType || 'patch'];

      parts[idx] = parseInt(parts[idx], 10) + 1;
      while(++idx < parts.length) {
        parts[idx] = 0;
      }
      return parts.join('.');
    });

    grunt.registerTask('default',  'bump clean:init copy:init clean:css imageEmbed cssmin clean:js copy:js exec:build clean:post');
    grunt.registerTask('deploy', 'exec:deploy');

};<commit_msg>mongolab heroku test<commit_after>module.exports = function(grunt) {

    grunt.initConfig({

        exec: {
          build: {
            command: 'node r.js -o r.config.js',
            stdout: true,
            stderr: true
          },
          deploy : {
            command : 'git subtree push --prefix bin heroku master'
          }
        },

        cssmin: {
          css: {
            src: 'bin/public/css/main_temp.css',
            dest: 'bin/public/css/main.css'
          }
        },

        imageEmbed: {
          dist: {
            src: [ "src/public/css/main.css" ],
            dest: "bin/public/css/main_temp.css",
            deleteAfterEncoding : false
          }
        },

        jsdoc : {
          dist : {
              src: ['src/public/js/**'],
              dest: 'docs'
          }
        },

        copy: {
          init: {
            files: {
              'bin/': 'src/**'
            }
          },

          js : {
            files: {
              'bin/public/js/libs/require-min.js' : 'src/public/js/libs/require-min.js'
            }
          }
        },

        clean: {
          init: ['bin', 'docs'],
          js : 'bin/public/js',
          css : 'bin/public/css',
          post : ['bin/public/css/main_temp.css', 'bin/public/css/img', 'bin/.DS_Store', 'bin/public/test', 'bin/test']
        }

    });

    grunt.loadNpmTasks('grunt-contrib');
    grunt.loadNpmTasks('grunt-jsdoc-plugin');
    grunt.loadNpmTasks('grunt-image-embed');
    grunt.loadNpmTasks('grunt');
    grunt.loadNpmTasks('grunt-exec');
    grunt.loadNpmTasks('grunt-css');

    grunt.registerTask('bump', function(versionType) {
      versionType = grunt.option('type') || 'patch';
      var package = grunt.file.readJSON('package.json');
      package.version = grunt.helper('bump_version', package.version, versionType || 'patch');
      grunt.file.write('package.json', JSON.stringify(package, null, '  '));

      var packageDeploy = grunt.file.readJSON('src/package.json');
      packageDeploy.version = package.version;
      packageDeploy.name = package.name;
      packageDeploy.author = package.author;
      packageDeploy.description = package.description;
      packageDeploy.bugs = package.bugs;
      packageDeploy.scripts.start = "node server";
      grunt.file.write('src/package.json', JSON.stringify(packageDeploy, null, '  '));
      grunt.log.ok('Version bumped to ' + packageDeploy.version);
    })

    grunt.registerHelper('bump_version', function(version, versionType) {
      var type = {
        patch: 2,
        minor: 1,
        major: 0
      };

      var parts = version.split('.');
      var idx = type[versionType || 'patch'];

      parts[idx] = parseInt(parts[idx], 10) + 1;
      while(++idx < parts.length) {
        parts[idx] = 0;
      }
      return parts.join('.');
    });

    grunt.registerTask('default',  'bump clean:init copy:init clean:css imageEmbed cssmin clean:js copy:js');
    grunt.registerTask('deploy', 'exec:deploy');

};<|endoftext|>


<commit_before>'use strict'

var fs = require('fs');
var gulp = require('gulp');
var iife = require("gulp-iife");
var header = require('gulp-header');
var concat = require('gulp-concat');
var minify = require('gulp-minify');
var karma = require('karma').Server;

var pkg = JSON.parse(fs.readFileSync('./package.json'));
var src = [
  'src/module.js',
  'src/directive.js'
];

var banner = ['/**',
  ' * <%= pkg.name %> v<%= pkg.version %>',
  ' * <%= pkg.description %>',
  ' * @link <%= pkg.homepage %>',
  ' * @author <%= pkg.author %>',
  ' * @example <<input ng-model="nationalid" maxlength="10" min-length="10" islet-iran-national-id />',
  ' * @license under <%= pkg.license %>',
  ' */',
  ''].join('\n');

gulp.task('js', jsTask);
gulp.task('watch', watchTask);
gulp.task('test', testTask);
gulp.task('default', ['test', 'js', 'watch']);

function jsTask() {
  gulp.src(src)
    .pipe(concat(pkg.name + '.js'))
    .pipe(iife())
    .pipe(minify({
      ext: {src:'.js', min:'.min.js'}
    }))
    .pipe(header(banner, { pkg : pkg }))
    .pipe(gulp.dest('dist'));
}

function testTask(done) {
  new karma({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
}

function watchTask() {
  gulp.watch('src/*.js', ['test', 'js']);
}
<commit_msg>Improve karma task runner error handling<commit_after>'use strict'

var fs = require('fs');
var gulp = require('gulp');
var iife = require("gulp-iife");
var header = require('gulp-header');
var concat = require('gulp-concat');
var minify = require('gulp-minify');
var karma = require('karma').Server;

var pkg = JSON.parse(fs.readFileSync('./package.json'));
var src = [
  'src/module.js',
  'src/directive.js'
];

var banner = ['/**',
  ' * <%= pkg.name %> v<%= pkg.version %>',
  ' * <%= pkg.description %>',
  ' * @link <%= pkg.homepage %>',
  ' * @author <%= pkg.author %>',
  ' * @example <<input ng-model="nationalid" maxlength="10" min-length="10" islet-iran-national-id />',
  ' * @license under <%= pkg.license %>',
  ' */',
  ''].join('\n');

gulp.task('js', jsTask);
gulp.task('watch', watchTask);
gulp.task('test', testTask);
gulp.task('default', ['test', 'js', 'watch']);

function jsTask() {
  gulp.src(src)
    .pipe(concat(pkg.name + '.js'))
    .pipe(iife())
    .pipe(minify({
      ext: {src:'.js', min:'.min.js'}
    }))
    .pipe(header(banner, { pkg : pkg }))
    .pipe(gulp.dest('dist'));
}

function testTask(done) {
  new karma({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, function() {
    done();
  }).start();
}

function watchTask() {
  gulp.watch(['src/**/*.js', 'test/**/*.spec.js'], ['test', 'js']);
}
<|endoftext|>