<commit_before>var gulp = require('gulp');
var path = require('path');
var runSequence = require('run-sequence');
var BuildTaskDoc = require('./BuildTaskDoc');
var config = require('./config');
var bump = require('gulp-bump');
var gutil = require('gulp-util');
var ghPages = require('gulp-gh-pages');
var git = require('gulp-git');
var del = require('del');
var fs = require('fs');

var getPackageJsonVersion = function () {
  return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
};

gulp.task('bump', function () {
  var bumpType = config.bump || "patch";
  return gulp.src(['./bower.json', './package.json'])
    .pipe(bump({type: bumpType}).on('error', gutil.log))
    .pipe(gulp.dest('./'));
});

gulp.task('commit-build-to-git', function () {
  return gulp.src('.')
    .pipe(git.commit('[Prerelease] Build and release new version', {args: '-a'}));
});

gulp.task('push-to-master', function (cb) {
  git.push(config.git.remoteUrl, 'DEV', {quiet: true}, cb);
});

gulp.task('create-new-tag-version', function (cb) {
  var version = getPackageJsonVersion();
  git.tag(version, 'Created Tag for version: ' + version, function (error) {
    if(error) {
      return cb(error);
    }
    git.push(config.git.remoteUrl, 'master', {args: '--tags', quiet: true}, cb);
  });
});

gulp.task('update-gh-pages', function() {
  return gulp.src(path.join(config.DEV, '**/*'))
    .pipe(ghPages({
      remoteUrl: config.git.remoteUrl
    }));
});

gulp.task('deploy-demo-page', function(callback) {
  runSequence(
    'build-demo',
    'update-gh-pages',
    function (error) {
      if(error){
        console.log(error.message.red);
      }
      console.log('BUILD FINISHED SUCCESSFULLY'.green);
      callback();
    });
});

gulp.task('release', function (callback) {
  config.env = 'production';
  runSequence(
    'build',
    'bump',
    'commit-build-to-git',
    'push-to-master',
    //'create-new-tag-version',
    //'deploy-demo-page',
    function (error) {
      if (error) {
        console.log(error.message.red);
      } else {
        console.log('RELEASE FINISHED SUCCESSFULLY'.green);
      }
      callback(error);
    });
});

module.exports = new BuildTaskDoc("release", "Creates a new version of the player and releases it. \n" +
"Increasing version, creating new tag and so on (--bump [patch(default)/minor/major])", 1.1);<commit_msg>Enabled release task back<commit_after>var gulp = require('gulp');
var path = require('path');
var runSequence = require('run-sequence');
var BuildTaskDoc = require('./BuildTaskDoc');
var config = require('./config');
var bump = require('gulp-bump');
var gutil = require('gulp-util');
var ghPages = require('gulp-gh-pages');
var git = require('gulp-git');
var del = require('del');
var fs = require('fs');

var getPackageJsonVersion = function () {
  return JSON.parse(fs.readFileSync('./package.json', 'utf8')).version;
};

gulp.task('bump', function () {
  var bumpType = config.bump || "patch";
  return gulp.src(['./bower.json', './package.json'])
    .pipe(bump({type: bumpType}).on('error', gutil.log))
    .pipe(gulp.dest('./'));
});

gulp.task('commit-build-to-git', function () {
  return gulp.src('.')
    .pipe(git.commit('[Prerelease] Build and release new version', {args: '-a'}));
});

gulp.task('push-to-master', function (cb) {
  git.push(config.git.remoteUrl, 'master', {quiet: true}, cb);
});

gulp.task('create-new-tag-version', function (cb) {
  var version = getPackageJsonVersion();
  git.tag(version, 'Created Tag for version: ' + version, function (error) {
    if(error) {
      return cb(error);
    }
    git.push(config.git.remoteUrl, 'master', {args: '--tags', quiet: true}, cb);
  });
});

gulp.task('update-gh-pages', function() {
  return gulp.src(path.join(config.DEV, '**/*'))
    .pipe(ghPages({
      remoteUrl: config.git.remoteUrl
    }));
});

gulp.task('deploy-demo-page', function(callback) {
  runSequence(
    'build-demo',
    'update-gh-pages',
    function (error) {
      if(error){
        console.log(error.message.red);
      }
      console.log('BUILD FINISHED SUCCESSFULLY'.green);
      callback();
    });
});

gulp.task('release', function (callback) {
  config.env = 'production';
  runSequence(
    'build',
    'bump',
    'commit-build-to-git',
    'push-to-master',
    'create-new-tag-version',
    'deploy-demo-page',
    function (error) {
      if (error) {
        console.log(error.message.red);
      } else {
        console.log('RELEASE FINISHED SUCCESSFULLY'.green);
      }
      callback(error);
    });
});

module.exports = new BuildTaskDoc("release", "Creates a new version of the player and releases it. \n" +
"Increasing version, creating new tag and so on (--bump [patch(default)/minor/major])", 1.1);<|endoftext|>


<commit_before>const templates = require('./config/notificationTemplates')
const { notifyKey } = require('../config').notifications
const logger = require('../../log.js')
const { isEmpty } = require('../utils/functionalHelpers')

module.exports = function createNotificationService(notifyClient, audit) {
  async function notify(username, type, notificationData) {
    if (notifyKey === 'NOTIFY_OFF') {
      logger.warn('No notification API key - notifications disabled')
      return
    }

    if (isEmpty(notificationData) || isEmpty(notificationData.emails)) {
      logger.warn('No email addresses for notification', notificationData)
      return
    }

    if (isEmpty(templates[type])) {
      logger.error(`Unmapped notification template type: $type`)
      return
    }

    const { templateId } = templates[type]

    notificationData.emails.forEach(async email => {
      try {
        await notifyClient.sendEmail(templateId, email, { personalisation: notificationData })
      } catch (error) {
        logger.error('Error sending notification email ', email)
        logger.error(error.stack)
        logger.error('error notifying for type', type)
        logger.error('error notifying for data', notificationData)
      }
    })

    auditEvent(username, notificationData.booking_id, type, notificationData)
  }

  function auditEvent(user, bookingId, notificationType, notificationData) {
    audit.record('NOTIFY', user, {
      bookingId,
      notificationType,
      notificationData,
    })
  }

  return {
    notify,
  }
}
<commit_msg>Send notifications in parallel<commit_after>const templates = require('./config/notificationTemplates')
const { notifyKey } = require('../config').notifications
const logger = require('../../log.js')
const { isEmpty } = require('../utils/functionalHelpers')

module.exports = function createNotificationService(notifyClient, audit) {
  async function notify(username, type, notificationData) {
    if (notifyKey === 'NOTIFY_OFF') {
      logger.warn('No notification API key - notifications disabled')
      return
    }

    if (isEmpty(notificationData) || isEmpty(notificationData.emails)) {
      logger.warn('No email addresses for notification', notificationData)
      return
    }

    if (isEmpty(templates[type])) {
      logger.error(`Unmapped notification template type: $type`)
      return
    }

    const { templateId } = templates[type]

    notificationData.emails.forEach(email => {
      notifyClient
        .sendEmail(templateId, email, { personalisation: notificationData })
        .then(() => {
          logger.info(`Successful notify for email: ${email}`)
        })
        .catch(error => {
          logger.error('Error sending notification email ', email)
          logger.error(error.stack)
          logger.error('error notifying for type', type)
          logger.error('error notifying for data', notificationData)
        })
    })

    auditEvent(username, notificationData.booking_id, type, notificationData)
  }

  function auditEvent(user, bookingId, notificationType, notificationData) {
    audit.record('NOTIFY', user, {
      bookingId,
      notificationType,
      notificationData,
    })
  }

  return {
    notify,
  }
}
<|endoftext|>


<commit_before>import Router from 'koa-router'

const router = new Router()

router.get('/all', async (ctx, next) => {
    ctx.accepts('application/json')
    ctx.body = {
        'code': 200,
        'data': [{
            'id': 1,
            'name': 'pro1'
        }, {
            'id': 2,
            'name': 'pro2'
        }],
        'msg': 'ok'
    }
})

export default router
<commit_msg>rm accepts<commit_after>import Router from 'koa-router'

const router = new Router()

router.get('/all', async (ctx, next) => {
    ctx.body = {
        'code': 200,
        'data': [{
            'id': 1,
            'name': 'pro1'
        }, {
            'id': 2,
            'name': 'pro2'
        }],
        'msg': 'ok'
    }
})

export default router
<|endoftext|>


<commit_before>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: false
		},
		parentWidget: null,
		element: null
	},

	initialize: function(options){
		this.latchEvents('adoption');
		this.pseudos = [];
		this.childWidgets = [];
		var parent, kbManager;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
			if (options.keyboardOptions && options.keyboardOptions.manager) {
				kbManager = options.keyboardOptions.manager;
				delete options.keyboardOptions.manager;
			}
		}
		this.setOptions(options);
		this.prefix = this.ns + '-' + this.name;
		this.element = this.options.element || new Element('div');
		this.element.set({
			id: this.element.get('id') || this.options.id || this.prefix+new Date().getTime()
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass([this.ns, this.prefix, this.options.className].join(' '));
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];

		var kbOptions = $merge(this.options.keyboardOptions, options ? options.keyboardOptions || {} : {});
		kbOptions.manager = kbManager || (parent ? parent.keyboard : null);
		this.keyboard = new Keyboard(kbOptions);
		this.keyboard.widget = this;
		this.keyboard.addEvent('deactivate', this.blur.bind(this));

		if (parent) this.setParent(parent);
	},

	addClass: function(className){
		this.classes.include(className);
		return this;
	},

	removeClass: function(className) {
		this.classes.erase(className);
		return this;
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	//not visible
	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	//engaged; the button is down, the select list is expanded, the mouse is clicking this thing
	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	//has keyboard control
	focus: function(){
		if (!this.keyboard.isActive()){
			this.keyboard.activate();
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			focused = this;
			this.render();
		}
		return this;
	},

	//non-interactive
	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states
	//visible
	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},
	//the button is released, the select list is contracted, the mouse is up
	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	//focus has shifted to another widget
	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.keyboard.deactivate();
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},
	//the widget is interactable
	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	addShortcut: function(name, shortcut) {
		this.keyboard.addShortcut(name, shortcut);
	},

	addShortcuts: function(obj) {
		this.keyboard.addShortcuts(obj);
	},

	removeShortcut: function(name) {
		this.keyboard.removeShortcut(name);
	},

	removeShortcuts: function(names) {
		this.keyboard.removeShortcuts(names);
	},

	getShortcut: function(name) {
		return this.keyboard.getShortcut(name);
	},

	getShortcuts: function() {
		return this.keyboard.getShortcuts();
	},

	destroy: function(){
		this.removeParent();
		$A(this.childWidgets).each(function(widget) {
			widget.destroy();
		});
		if (this.childWidgets.length && window.console && console.warn) {
			this.childWidgets.each(function(widget) {
				console.warn("warning: %s called the destroy method of %s but it failed. Ensure that destroy method calls this.parent", this.prefix, widget.prefix);
			}, this);
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<commit_msg>redrawing widgets when a class is added/removed<commit_after>/*
Script: ART.Widget.js

License:
	MIT-style license.
*/

// Base widget class. Based on » http://gist.github.com/85837
(function(){

var counting, focused;

ART.Widget = new Class({

	Implements: [Options, Events],

	ns: 'art',
	name: 'widget',

	options: {
		// onShow: $empty,
		// onHide: $empty,
		// onFocus: $empty,
		// onBlur: $empty,
		// onEnable: $empty,
		// onDisable: $empty,
		// onDestroy: $empty,
		// onAdoption: $empty(parentWidget),
		// onOrphan: $empty(previousParent),
		// id: null,
		// style: null,
		renderWhileHidden: false,
		className: '',
		keyboardOptions: {
			active: false
		},
		parentWidget: null,
		element: null
	},

	initialize: function(options){
		this.latchEvents('adoption');
		this.pseudos = [];
		this.childWidgets = [];
		var parent, kbManager;
		if (options) {
			if (options.parentWidget) {
				parent = options.parentWidget;
				delete options.parentWidget;
			}
			if (options.keyboardOptions && options.keyboardOptions.manager) {
				kbManager = options.keyboardOptions.manager;
				delete options.keyboardOptions.manager;
			}
		}
		this.setOptions(options);
		this.prefix = this.ns + '-' + this.name;
		this.element = this.options.element || new Element('div');
		this.element.set({
			id: this.element.get('id') || this.options.id || this.prefix+new Date().getTime()
		}).store(this.prefix, this).store('widget', this);
		this.element.addClass([this.ns, this.prefix, this.options.className].join(' '));
		this.classes = this.options.classes;
		this.classes = (this.options.className) ? this.options.className.split(' ') : [];

		var kbOptions = $merge(this.options.keyboardOptions, options ? options.keyboardOptions || {} : {});
		kbOptions.manager = kbManager || (parent ? parent.keyboard : null);
		this.keyboard = new Keyboard(kbOptions);
		this.keyboard.widget = this;
		this.keyboard.addEvent('deactivate', this.blur.bind(this));

		if (parent) this.setParent(parent);
	},

	addClass: function(className){
		this.classes.include(className);
		this.redraw();
		return this;
	},

	removeClass: function(className) {
		this.classes.erase(className);
		this.redraw();
		return this;
	},

	getSelector: function(){
		var selector = (this.parentWidget) ? this.parentWidget.getSelector() + ' ' : '';
		selector += this.name;
		if (this.classes.length) selector += '.' + this.classes.join('.');
		if (this.pseudos.length) selector += ':' + this.pseudos.join(':');
		return selector;
	},

	addPseudo: function(pseudo){
		this.pseudos.include(pseudo);
	},

	removePseudo: function(pseudo){
		this.pseudos.erase(pseudo);
	},

	setParent: function(widget, initing){
		if (!initing) this.removeParent();
		this.parentWidget = widget;
		widget.childWidgets.include(this);
		this.parentWidget.keyboard.manage(this.keyboard);
		this.enable();
		this.fireEvent('adoption', widget);
		return this;
	},

	removeParent: function(){
		this.prevParent = this.parentWidget || this.prevParent;
		if (!this.prevParent) return;
		if (this.parentWidget) {
			this.parentWidget.childWidgets.erase(this);
			Keyboard.manager.manage(this.keyboard);
			this.parentWidget = null;
		}
		this.fireEvent('orphan', this.prevParent);
	},

	// render

	requireToRender: function(){
		this.requiredToRender = this.requiredToRender || [];
		$A(arguments).each(function(requirement) {
			this.requiredToRender.push(requirement);
		}, this);
	},

	readyToRender: function() {
		if (!this.requiredToRender || !this.requiredToRender.length) return;
		$A(arguments).each(function(requirement) {
			this.requiredToRender.erase(requirement);
		}, this);
	},

	redraw: function(){
		if (counting) this._counters();
		this.childWidgets.each(function(child) {
			child.render();
		});
		return this;
	},

	isReadyToRender: function(){
		var isReady = (!this.requiredToRender || !this.requiredToRender.length) && !this.destroyed && (this.options.renderWhileHidden || !this.hidden);
		if (isReady && this.parentWidget) isReady = this.parentWidget.isReadyToRender();
		return isReady;
	},

	render: function(override){
		if (this.isReadyToRender()) this.redraw(override);
		return this;
	},

	// special states

	//not visible
	hide: function(){
		if (!this.hidden){
			this.hidden = true;
			this.fireEvent('hide');
			this.element.addClass(this.prefix + '-hidden');
			this.addPseudo('hidden');
			this.render();
		}
		return this;
	},

	//engaged; the button is down, the select list is expanded, the mouse is clicking this thing
	activate: function(){
		if (!this.active){
			this.active = true;
			this.fireEvent('activate');
			this.element.addClass(this.prefix + '-active');
			this.addPseudo('active');
			this.render();
		}
		return this;
	},

	//has keyboard control
	focus: function(){
		if (!this.keyboard.isActive()){
			this.keyboard.activate();
			this.focused = true;
			this.fireEvent('focus');
			this.element.addClass(this.prefix + '-focused');
			this.addPseudo('focus');
			focused = this;
			this.render();
		}
		return this;
	},

	//non-interactive
	disable: function(byParent){
		this.disabledByParent = false;
		if (!this.disabled){
			if (byParent) this.disabledByParent = true;
			this.blur();
			this.fireEvent('disable');
			this.keyboard.deactivate();
			this.childWidgets.each(function(child){
				child.disable(true);
			});
			this.element.addClass(this.prefix + '-disabled');
			this.addPseudo('disabled');
			this.disabled = true;
			this.render();
		}
		return this;
	},

	// normal states
	//visible
	show: function(){
		if (this.hidden){
			this.hidden = false;
			this.fireEvent('show');
			this.element.removeClass(this.prefix + '-hidden');
			this.removePseudo('hidden');
			this.render();
		}
		return this;
	},
	//the button is released, the select list is contracted, the mouse is up
	deactivate: function(){
		if (this.active){
			this.active = false;
			this.fireEvent('deactivate');
			this.element.removeClass(this.prefix + '-active');
			this.removePseudo('active');
			this.render();
		}
		return this;
	},

	//focus has shifted to another widget
	blur: function(){
		if (this.focused){
			this.focused = false;
			this.fireEvent('blur');
			this.keyboard.deactivate();
			this.element.removeClass(this.prefix + '-focused');
			this.removePseudo('focus');
			this.render();
		}
		return this;
	},
	//the widget is interactable
	enable: function(){
		if (this.parentWidget && this.parentWidget.disabled) {
			this.disabledByParent = true;
			return this;
		};
		delete this.disabledByParent;
		if (this.disabled){
			this.disabled = false;
			this.fireEvent('enable');
			this.element.removeClass(this.prefix + '-disabled');
			this.removePseudo('disabled');
			this.render();
		}
		this.childWidgets.each(function(child){
			if (child.disabledByParent) {
				child.enable();
				delete child.disabledByParent;
			}
		});
		return this;
	},

	attachKeys: function(events){
		this.keyboard.addEvents(events);
	},

	detachKeys: function(events) {
		this.keyboard.removeEvents(events);
	},

	addShortcut: function(name, shortcut) {
		this.keyboard.addShortcut(name, shortcut);
	},

	addShortcuts: function(obj) {
		this.keyboard.addShortcuts(obj);
	},

	removeShortcut: function(name) {
		this.keyboard.removeShortcut(name);
	},

	removeShortcuts: function(names) {
		this.keyboard.removeShortcuts(names);
	},

	getShortcut: function(name) {
		return this.keyboard.getShortcut(name);
	},

	getShortcuts: function() {
		return this.keyboard.getShortcuts();
	},

	destroy: function(){
		this.removeParent();
		$A(this.childWidgets).each(function(widget) {
			widget.destroy();
		});
		if (this.childWidgets.length && window.console && console.warn) {
			this.childWidgets.each(function(widget) {
				console.warn("warning: %s called the destroy method of %s but it failed. Ensure that destroy method calls this.parent", this.prefix, widget.prefix);
			}, this);
		}
		this.element.destroy();
		this.destroyed = true;
		return this.fireEvent('destroy');
	},

	// toElement

	toElement: function(){
		return this.element;
	},

	_redrawCount: 0,
	_counters: function(){
		this._redrawCount++;
		$clear(this._countTimer);
		this._countTimer = (function(){
			this._redrawCount = 0;
		}).delay(1000, this);
		console.log('redraw %s: ', this.name, this._redrawCount, this.element);
	}

});

ART._counts = function(){
	counting = !counting;
	if (counting) console.log('counting widget renders');
	else console.log('disabling widget render counts');
};

})();<|endoftext|>


<commit_before>Five = {
	n : 'Five',
	tis : [ {
		t : 'c',
		ln : 'ValueType',
		ps : [ {
			t : 'v',
			n : 'value'
		} ]
	}, {
		ln : 'AnyAttributeType',
		ps : [ {
			t : 'aa',
			n : 'attributes'
		} ]
	}, {
		ln : 'AttributeType',
		ps : [ {
			t : 'a',
			n : 'attribute',
		} ]
	}, {
		ln : 'ElementType',
		ps : [ {
			t : 'e',
			n : 'element',
		}, {
			n : 'elements',
			en : 'element',
			wen : 'elements',
		}, {
			n : 'item',
			col : true,
		}, {
			n : 'items',
			en : 'item',
			wen : 'items',
			col : true,
		} ]
	}, {
		ln : 'ElementsType',
		ps : [ {
			t : 'es',
			n : 'ab',
			etis : [ {
				en : 'a',
				ti : 'Five.ValueType'
			}, {
				en : 'b',
				ti : 'Integer'
			} ]
		}, {
			t : 'es',
			n : 'abs',
			wen : 'abs',
			etis : [ {
				en : 'a',
				ti : 'Five.ValueType'
			}, {
				en : 'b',
				ti : 'Integer'
			} ]
		}, {
			t : 'es',
			n : 'cd',
			col : true,
			etis : [ {
				en : 'c',
				ti : 'Integer'
			}, {
				en : 'd',
				ti : 'Five.ValueType'
			} ]
		}, {
			t : 'es',
			n : 'cds',
			col : true,
			wen : 'cds',
			etis : [ {
				en : 'c',
				ti : 'Integer'
			}, {
				en : 'd',
				ti : 'Five.ValueType'
			} ]
		} ]
	}, {
		ln : 'ElementRefType',
		ps : [ {
			t : 'er',
			n : 'element',
		}, {
			t : 'er',
			n : 'element1',
		}, {
			t : 'er',
			n : 'elements',
			en : 'element',
			wen : 'elements',
		}, {
			t : 'er',
			n : 'elements1',
			en : 'element1',
			wen : 'elements1',
			ti : 'Double'
		}, {
			t : 'er',
			n : 'item',
			col : true,
		}, {
			t : 'er',
			n : 'items',
			en : 'item',
			wen : 'items',
			col : true,
		}, {
			t : 'er',
			n : 'mixes',
			en : 'mix',
			wen : 'mixes',
			col : true,
			ti : 'Five.ValueType'
		}, {
			t : 'er',
			n : 'mix',
			col : true,
			ti : 'Five.ValueType'
		} ]
	}, {
		ln : 'ElementRefsType',
		ps : [ {
			t : 'ers',
			n : 'element',
			etis : [ {
				en : 'element'
			} ]
		}, {
			t : 'ers',
			n : 'element1',
			etis : [ {
				en : 'element1'
			} ]
		}, {
			t : 'ers',
			n : 'elements',
			wen : 'elements',
			etis : [ {
				en : 'element'
			} ]
		}, {
			t : 'ers',
			n : 'elements1',
			wen : 'elements1',
			etis : [ {
				en : 'element1',
				ti : 'Double'
			} ]
		}, {
			t : 'ers',
			n : 'item',
			col : true,
			etis : [ {
				en : 'item'
			} ]
		}, {
			t : 'ers',
			n : 'items',
			wen : 'items',
			col : true,
			etis : [ {
				en : 'item'
			} ]
		}, {
			t : 'ers',
			n : 'mixes',
			wen : 'mixes',
			col : true,
			etis : [ {
				en : 'mix',
				ti : 'Five.ValueType'
			} ]
		}, {
			t : 'ers',
			n : 'mix',
			col : true,
			etis : [ {
				en : 'mix',
				ti : 'Five.ValueType'
			} ]
		} ]
	}, {
		ln : 'AnyElementType',
		ps : [ {
			t : 'a',
			n : 'attribute'
		}, {
			t : 'ae',
			n : 'any',
			col : true
		} ]
	}, {
		ln : 'SimpleTypesType',
		ps : [ {
			n : 'date',
			ti : 'Date'
		}, {
			n : 'double',
			ti : 'Double'
		}, {
			n : 'integer',
			ti : 'Integer'
		}, {
			n : 'string'
		}, {
			n : 'dates',
			ti : {
				t : 'list',
				ti : 'Date'

			}
		}, {
			n : 'doubles',
			ti : {
				t : 'list',
				ti : 'Double'
			}
		}, {
			n : 'integers',
			ti : {
				t : 'list',
				ti : 'Integer'
			}
		}, {
			n : 'strings',
			ti : {
				t : 'list'
			}
		}, {
			n : 'doublesList',
			ti : {
				t : 'list',
				ti : {
					t : 'list',
					ti : 'Double'
				},
				s : ', '
			}
		} ]
	}, {
		ln : 'ElementMapType',
		ps : [ {
			t : 'em',
			n : 'element',
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		}, {
			t : 'em',
			n : 'elements',
			wen : 'elements',
			en : 'element',
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		}, {
			t : 'em',
			n : 'elementCollection',
			col : true,
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		}, {
			t : 'em',
			n : 'elementsCollection',
			wen : 'elementsCollection',
			en : 'element',
			col : true,
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		} ]
	}, {
		t : 'enumInfo',
		ln : 'EnumInfoArray',
		vs : [ 'a', 'b', 'c' ]
	}, {
		t : 'enumInfo',
		ln : 'EnumInfoObject',
		vs : {
			'a' : 'AA',
			'b' : 'BB',
			'c' : 'CC'
		}
	}, {
		t : 'enumInfo',
		ln : 'StringEnumInfoArray',
		vs : [ 'a', 'b', 'c' ]
	}, {
		t : 'enumInfo',
		ln : 'StringEnumInfoObject',
		vs : {
			'a' : 'AA',
			'b' : 'BB',
			'c' : 'CC'
		}
	}, {
		t : 'enumInfo',
		ln : 'IntegerEnumInfoArray',
		bti : 'Integer',
		vs : [ 1, '2', 3 ]
	}, {
		t : 'enumInfo',
		ln : 'IntegerEnumInfoObject',
		bti : 'Integer',
		vs : {
			'one' : 1,
			'two' : '2',
			'three' : 3
		}
	} ],
	eis : [ {
		en : 'value',
		ti : 'Five.ValueType'
	}, {
		en : 'anyAttribute',
		ti : 'Five.AnyAttributeType'
	}, {
		en : 'attribute',
		ti : 'Five.AttributeType'
	}, {
		en : 'element',
		ti : 'Five.ElementType'
	}, {
		en : 'elements',
		ti : 'Five.ElementsType'
	}, {
		en : 'elementRef',
		ti : 'Five.ElementRefType'
	}, {
		en : 'elementRefs',
		ti : 'Five.ElementRefsType'
	}, {
		en : 'anyElement',
		ti : 'Five.AnyElementType'
	}, {
		en : 'simpleTypes',
		ti : 'Five.SimpleTypesType'
	}, {
		en : 'element',
		sc : 'Five.ElementRefType'
	}, {
		en : 'item',
		sc : 'Five.ElementRefType'
	}, {
		en : 'mix',
		ti : 'Five.ValueType',
		sc : 'Five.ElementRefType'
	}, {
		en : 'elementMap',
		ti : 'Five.ElementMapType'
	}, {
		en : 'enumInfoArray',
		ti : 'Five.EnumInfoArray'
	}, {
		en : 'enumInfoObject',
		ti : 'Five.EnumInfoObject'
	}, {
		en : 'stringEnumInfoArray',
		ti : 'Five.StringEnumInfoArray'
	}, {
		en : 'stringEnumInfoObject',
		ti : 'Five.StringEnumInfoObject'
	}, {
		en : 'integerEnumInfoArray',
		ti : 'Five.IntegerEnumInfoArray'
	}, {
		en : 'integerEnumInfoObject',
		ti : 'Five.IntegerEnumInfoObject'
	}, {
		en : 'anyType',
		ti : 'AnyType'
	} ]
};
Six = {
	n : 'Six',
	eis : [ {
		en : 'string'
	} ]
};<commit_msg>Fixed commas.<commit_after>Five = {
	n : 'Five',
	tis : [ {
		t : 'c',
		ln : 'ValueType',
		ps : [ {
			t : 'v',
			n : 'value'
		} ]
	}, {
		ln : 'AnyAttributeType',
		ps : [ {
			t : 'aa',
			n : 'attributes'
		} ]
	}, {
		ln : 'AttributeType',
		ps : [ {
			t : 'a',
			n : 'attribute'
		} ]
	}, {
		ln : 'ElementType',
		ps : [ {
			t : 'e',
			n : 'element'
		}, {
			n : 'elements',
			en : 'element',
			wen : 'elements'
		}, {
			n : 'item',
			col : true
		}, {
			n : 'items',
			en : 'item',
			wen : 'items',
			col : true
		} ]
	}, {
		ln : 'ElementsType',
		ps : [ {
			t : 'es',
			n : 'ab',
			etis : [ {
				en : 'a',
				ti : 'Five.ValueType'
			}, {
				en : 'b',
				ti : 'Integer'
			} ]
		}, {
			t : 'es',
			n : 'abs',
			wen : 'abs',
			etis : [ {
				en : 'a',
				ti : 'Five.ValueType'
			}, {
				en : 'b',
				ti : 'Integer'
			} ]
		}, {
			t : 'es',
			n : 'cd',
			col : true,
			etis : [ {
				en : 'c',
				ti : 'Integer'
			}, {
				en : 'd',
				ti : 'Five.ValueType'
			} ]
		}, {
			t : 'es',
			n : 'cds',
			col : true,
			wen : 'cds',
			etis : [ {
				en : 'c',
				ti : 'Integer'
			}, {
				en : 'd',
				ti : 'Five.ValueType'
			} ]
		} ]
	}, {
		ln : 'ElementRefType',
		ps : [ {
			t : 'er',
			n : 'element'
		}, {
			t : 'er',
			n : 'element1'
		}, {
			t : 'er',
			n : 'elements',
			en : 'element',
			wen : 'elements'
		}, {
			t : 'er',
			n : 'elements1',
			en : 'element1',
			wen : 'elements1',
			ti : 'Double'
		}, {
			t : 'er',
			n : 'item',
			col : true
		}, {
			t : 'er',
			n : 'items',
			en : 'item',
			wen : 'items',
			col : true
		}, {
			t : 'er',
			n : 'mixes',
			en : 'mix',
			wen : 'mixes',
			col : true,
			ti : 'Five.ValueType'
		}, {
			t : 'er',
			n : 'mix',
			col : true,
			ti : 'Five.ValueType'
		} ]
	}, {
		ln : 'ElementRefsType',
		ps : [ {
			t : 'ers',
			n : 'element',
			etis : [ {
				en : 'element'
			} ]
		}, {
			t : 'ers',
			n : 'element1',
			etis : [ {
				en : 'element1'
			} ]
		}, {
			t : 'ers',
			n : 'elements',
			wen : 'elements',
			etis : [ {
				en : 'element'
			} ]
		}, {
			t : 'ers',
			n : 'elements1',
			wen : 'elements1',
			etis : [ {
				en : 'element1',
				ti : 'Double'
			} ]
		}, {
			t : 'ers',
			n : 'item',
			col : true,
			etis : [ {
				en : 'item'
			} ]
		}, {
			t : 'ers',
			n : 'items',
			wen : 'items',
			col : true,
			etis : [ {
				en : 'item'
			} ]
		}, {
			t : 'ers',
			n : 'mixes',
			wen : 'mixes',
			col : true,
			etis : [ {
				en : 'mix',
				ti : 'Five.ValueType'
			} ]
		}, {
			t : 'ers',
			n : 'mix',
			col : true,
			etis : [ {
				en : 'mix',
				ti : 'Five.ValueType'
			} ]
		} ]
	}, {
		ln : 'AnyElementType',
		ps : [ {
			t : 'a',
			n : 'attribute'
		}, {
			t : 'ae',
			n : 'any',
			col : true
		} ]
	}, {
		ln : 'SimpleTypesType',
		ps : [ {
			n : 'date',
			ti : 'Date'
		}, {
			n : 'double',
			ti : 'Double'
		}, {
			n : 'integer',
			ti : 'Integer'
		}, {
			n : 'string'
		}, {
			n : 'dates',
			ti : {
				t : 'l',
				ti : 'Date'

			}
		}, {
			n : 'doubles',
			ti : {
				t : 'l',
				ti : 'Double'
			}
		}, {
			n : 'integers',
			ti : {
				t : 'l',
				ti : 'Integer'
			}
		}, {
			n : 'strings',
			ti : {
				t : 'l'
			}
		}, {
			n : 'doublesList',
			ti : {
				t : 'l',
				ti : {
					t : 'l',
					ti : 'Double'
				},
				sep : ', '
			}
		} ]
	}, {
		ln : 'ElementMapType',
		ps : [ {
			t : 'em',
			n : 'element',
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		}, {
			t : 'em',
			n : 'elements',
			wen : 'elements',
			en : 'element',
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		}, {
			t : 'em',
			n : 'elementCollection',
			col : true,
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		}, {
			t : 'em',
			n : 'elementsCollection',
			wen : 'elementsCollection',
			en : 'element',
			col : true,
			k : {
				t : 'a',
				n : 'key'
			},
			v : {
				t : 'v',
				n : 'value'
			}
		} ]
	}, {
		t : 'enum',
		ln : 'EnumInfoArray',
		vs : [ 'a', 'b', 'c' ]
	}, {
		t : 'enum',
		ln : 'EnumInfoObject',
		vs : {
			'a' : 'AA',
			'b' : 'BB',
			'c' : 'CC'
		}
	}, {
		t : 'enum',
		ln : 'StringEnumInfoArray',
		vs : [ 'a', 'b', 'c' ]
	}, {
		t : 'enum',
		ln : 'StringEnumInfoObject',
		vs : {
			'a' : 'AA',
			'b' : 'BB',
			'c' : 'CC'
		}
	}, {
		t : 'enum',
		ln : 'IntegerEnumInfoArray',
		bti : 'Integer',
		vs : [ 1, '2', 3 ]
	}, {
		t : 'enum',
		ln : 'IntegerEnumInfoObject',
		bti : 'Integer',
		vs : {
			'one' : 1,
			'two' : '2',
			'three' : 3
		}
	} ],
	eis : [ {
		en : 'value',
		ti : 'Five.ValueType'
	}, {
		en : 'anyAttribute',
		ti : 'Five.AnyAttributeType'
	}, {
		en : 'attribute',
		ti : 'Five.AttributeType'
	}, {
		en : 'element',
		ti : 'Five.ElementType'
	}, {
		en : 'elements',
		ti : 'Five.ElementsType'
	}, {
		en : 'elementRef',
		ti : 'Five.ElementRefType'
	}, {
		en : 'elementRefs',
		ti : 'Five.ElementRefsType'
	}, {
		en : 'anyElement',
		ti : 'Five.AnyElementType'
	}, {
		en : 'simpleTypes',
		ti : 'Five.SimpleTypesType'
	}, {
		en : 'element',
		sc : 'Five.ElementRefType'
	}, {
		en : 'item',
		sc : 'Five.ElementRefType'
	}, {
		en : 'mix',
		ti : 'Five.ValueType',
		sc : 'Five.ElementRefType'
	}, {
		en : 'elementMap',
		ti : 'Five.ElementMapType'
	}, {
		en : 'enumInfoArray',
		ti : 'Five.EnumInfoArray'
	}, {
		en : 'enumInfoObject',
		ti : 'Five.EnumInfoObject'
	}, {
		en : 'stringEnumInfoArray',
		ti : 'Five.StringEnumInfoArray'
	}, {
		en : 'stringEnumInfoObject',
		ti : 'Five.StringEnumInfoObject'
	}, {
		en : 'integerEnumInfoArray',
		ti : 'Five.IntegerEnumInfoArray'
	}, {
		en : 'integerEnumInfoObject',
		ti : 'Five.IntegerEnumInfoObject'
	}, {
		en : 'anyType',
		ti : 'AnyType'
	} ]
};
Six = {
	n : 'Six',
	eis : [ {
		en : 'string'
	} ]
};<|endoftext|>


<commit_before>(function (angular) {
    "use strict";

    angular.module("ng.deviceDetector", ["reTree", "uaDeviceDetector"])
        .service("detectUtils", ["deviceDetector", "uaDeviceDetector",
            function (deviceDetector, uaDeviceDetector) {
                var deviceInfo = deviceDetector;

                this.isMobile = function () {
                    return deviceInfo.device !== 'unknown';
                };

                this.isAndroid = function () {
                    return (deviceInfo.device === uaDeviceDetector.DEVICES.ANDROID || deviceInfo.OS === uaDeviceDetector.OS.ANDROID);
                };

                this.isIOS = function () {
                    return (deviceInfo.os === uaDeviceDetector.OS.IOS || deviceInfo.device === uaDeviceDetector.DEVICES.I_POD ||
                        deviceInfo.device === uaDeviceDetector.DEVICES.IPHONE);
                };
            }
        ])
        .provider("deviceDetector", function () {
            var customDetectors = [];
            this.addCustom = function (customDetectorName, customDetectorRE) {
                customDetectors.push({ name: customDetectorName, re: customDetectorRE });
            };
            this.$get = [
                "$window",
                "uaDeviceDetector",
                "reTree",
                function (
                    $window,
                    uaDeviceDetector,
                    reTree
                ) {
                    var ua = $window.navigator.userAgent;
                    var deviceInfo = uaDeviceDetector.parseUserAgent(ua, customDetectors);
                    deviceInfo.parseUserAgent = function (ua) { return uaDeviceDetector.parseUserAgent(ua, customDetectors) };
                    return deviceInfo;
                }];
        }
        )
        .directive('deviceDetector', ["deviceDetector", function (deviceDetector) {
            function customClassName(name) {
                return 'is-' + name.toLowerCase().replace(/[^0-9a-z]+/g, '-');
            }

            return {
                restrict: "A",
                link: function (scope, elm/*, attrs*/) {
                    elm.addClass('os-' + deviceDetector.os);
                    elm.addClass('browser-' + deviceDetector.browser);
                    elm.addClass('device-' + deviceDetector.device);
                    elm.toggleClass('is-mobile', deviceDetector.isMobile());
                    elm.toggleClass('is-tablet', deviceDetector.isTablet());
                    elm.toggleClass('is-desktop', deviceDetector.isDesktop());
                    Object.keys(deviceDetector.custom).forEach(function (customKey) {
                        elm.toggleClass(customClassName(customKey), deviceDetector.custom[customKey]);
                    });
                }
            };
        }]);
})(angular);
<commit_msg>Pass MaxTouchPoints and Platform to uaDeviceDetector when using Angular. Fixes issue with iPad reporting as Desktop #87<commit_after>(function (angular) {
    "use strict";

    angular.module("ng.deviceDetector", ["reTree", "uaDeviceDetector"])
        .service("detectUtils", ["deviceDetector", "uaDeviceDetector",
            function (deviceDetector, uaDeviceDetector) {
                var deviceInfo = deviceDetector;

                this.isMobile = function () {
                    return deviceInfo.device !== 'unknown';
                };

                this.isAndroid = function () {
                    return (deviceInfo.device === uaDeviceDetector.DEVICES.ANDROID || deviceInfo.OS === uaDeviceDetector.OS.ANDROID);
                };

                this.isIOS = function () {
                    return (deviceInfo.os === uaDeviceDetector.OS.IOS || deviceInfo.device === uaDeviceDetector.DEVICES.I_POD ||
                        deviceInfo.device === uaDeviceDetector.DEVICES.IPHONE);
                };
            }
        ])
        .provider("deviceDetector", function () {
            var customDetectors = [];
            this.addCustom = function (customDetectorName, customDetectorRE) {
                customDetectors.push({ name: customDetectorName, re: customDetectorRE });
            };
            this.$get = [
                "$window",
                "uaDeviceDetector",
                "reTree",
                function (
                    $window,
                    uaDeviceDetector,
                    reTree
                ) {
                    var ua = $window.navigator.userAgent;
                    var platform = $window.navigator.platform;
                    var maxTouchPoints= $window.navigator.maxTouchPoints;
                    var deviceInfo = uaDeviceDetector.parseUserAgent(ua, customDetectors, platform, maxTouchPoints );
                    deviceInfo.parseUserAgent = function (ua, platform, maxTouchPoints) { return uaDeviceDetector.parseUserAgent(ua, customDetectors, platform, maxTouchPoints) };
                    return deviceInfo;
                }];
        }
        )
        .directive('deviceDetector', ["deviceDetector", function (deviceDetector) {
            function customClassName(name) {
                return 'is-' + name.toLowerCase().replace(/[^0-9a-z]+/g, '-');
            }

            return {
                restrict: "A",
                link: function (scope, elm/*, attrs*/) {
                    elm.addClass('os-' + deviceDetector.os);
                    elm.addClass('browser-' + deviceDetector.browser);
                    elm.addClass('device-' + deviceDetector.device);
                    elm.toggleClass('is-mobile', deviceDetector.isMobile());
                    elm.toggleClass('is-tablet', deviceDetector.isTablet());
                    elm.toggleClass('is-desktop', deviceDetector.isDesktop());
                    Object.keys(deviceDetector.custom).forEach(function (customKey) {
                        elm.toggleClass(customClassName(customKey), deviceDetector.custom[customKey]);
                    });
                }
            };
        }]);
})(angular);
<|endoftext|>


<commit_before>function search_share(query){
	$.get(search_url,{query:query},function(data){
		//console.log(data);
		$('#searchResults').html('');
		$.each(data.results,function(index,result){
			var split_at = result.lastIndexOf("/")+1;
			var directory = result.substring(0, split_at-1);
			var dir_link = ''+directory+' /';
			var file = result.substring(split_at);
			var file_link = file == '' ? '' : ''+file+'';
			$('#searchResults').append('
'+dir_link+' '+file_link+'
');
		});
	});
}

function get_selected_names(){
	var selection = [];
	$('.action-check:checked').each(function(){
		selection.push($(this).closest('tr').attr('data-id'));
	});
	return selection;
}
function generate_rsync_strings(share,subpath){
	var re = new RegExp(' ', 'g');
	var selection = get_selected_names();
	for(var i in selection){
		if (selection[i].indexOf(' ') > -1)
			selection[i] = "'"+selection[i].replace(re,'\\ ')+"'";
	}

	var path = subpath ? '/'+ share + '/' + subpath: '/'+share+'/';
	if (path.indexOf(' ') > -1)
		path = "'"+path.replace(re,'\\ ')+"'";
	var files = selection.length > 0 ? '{'+selection.join(',')+'}' : '';
	var download_string = "rsync -vrzt adam@phymaptest:"+path+files+" /to/my/local/directory";
	var upload_string = "rsync -vrzt /path/to/my/files  adam@phymaptest:"+path;

	$('#rsync-download-command').text(download_string);
	$('#rsync-upload-command').text(upload_string);
	$('#rsync-download').modal('show');
}
function generate_rsync_download(share,subpath){
	var re = new RegExp(' ', 'g');
	var selection = get_selected_names();
	for(var i in selection){
		if (selection[i].indexOf(' ') > -1)
			selection[i] = "'"+selection[i].replace(re,'\\ ')+"'";
	}

	var path = subpath ? '/'+ share + '/' + subpath: '/'+share+'/';
	if (path.indexOf(' ') > -1)
		path = "'"+path.replace(re,'\\ ')+"'";
	var files = selection.length > 0 ? '{'+selection.join(',')+'}' : '';
	var download_all_string = "rsync -vrzt "+rsync_url+":"+path+" /to/my/local/directory";
	var download_string = "rsync -vrzt "+rsync_url+":"+path+files+" /to/my/local/directory";

	$('#rsync-download-selected').text(download_string);
	$('#rsync-download-all').text(download_all_string);
	$('#rsync-download').modal('show');
}
function generate_rsync_upload(share,subpath){
	var re = new RegExp(' ', 'g');
	var path = subpath ? '/'+ share + '/' + subpath: '/'+share+'/';
	if (path.indexOf(' ') > -1)
		path = "'"+path.replace(re,'\\ ')+"'";
	var upload_string = "rsync -vrzt /path/to/my/files "+rsync_url+":"+path;
	$('#rsync-upload-command').text(upload_string);
	$('#rsync-upload').modal('show');
}
function delete_paths(url,selection){
	BC.ajax(
		{
			'url':url,
			'data':{'json':JSON.stringify({'selection':selection})},
			'success':function(data){
				if(data.failed.length !=0){
					var message = "The following files were unable to be deleted: " + data.failed.join(', ');
					message += "
The filesystem may be read only.";
					$.bootstrapGrowl(message,{type:'error',delay: 10000});
				}
				if(data.deleted){
					$.each(data.deleted,function(index,item){
						$('#file-table [data-id="'+item+'"]').addClass('error').addClass('deleted');
					});
					setTimeout(function(){
							$('#file-table tr.deleted').fadeOut({
								'duration':500,
								'complete':function(){filetable.fnDeleteRow($(this)[0]);toggle_table_visibility();}
									});
							}
						,500);
				}
			}
		}
	);
}
function archive_files(url,selection){
	BC.ajax(
		{
			'url':url,
			'data':{'json':JSON.stringify({'selection':selection})},
			'success':function(data){
				if(data.url){
					var message = 'Archive ready for download';
					$.bootstrapGrowl(message,{delay: 100000000,type:'success'});
				}
			}
		}
	);
}

function toggle_table_visibility(){
	if($('#file-table tbody tr').length == 1){
		$('#add-files-message').removeClass('hidden');
	}else{
		$('#add-files-message').addClass('hidden');
	}
}
function open_metadata_form(){
	var row = $(this).closest('tr');
	$('#edit-metadata-form').html($('#edit-meta-data-form-clean').html());
	$('#edit-metadata-form [name=notes]').val(row.attr('data-notes'));
	$('#edit-metadata-form [name=tags]').val(row.attr('data-tags'));
	$('#metadata-label').text(row.attr('data-id'));
	$('#metadata-id').val(row.attr('data-id'));
	$('#edit-metadata').modal('show');
}
function preview_share_action(){
	var row = $(this).closest('tr');
	var path = subpath ? subpath + row.attr('data-id') : row.attr('data-id');
	preview_file(share,path);
}

function edit_metadata(){
	var id = $('#metadata-id').val();
	var url = metadata_url+id;

	BC.ajax_form_submit('#edit-metadata-form',
		{
			'ajax':{
				'url':url,
				'data':{'tags':$('#edit-metadata-form [name=tags]').val(),'notes':$('#edit-metadata-form [name=notes]').val()}
			},
			'success':function(data){
				if(data.name){
					$('#edit-metadata').modal('hide');
					var row = $('#file-table [data-id="'+id+'"]');
					var tags_html = BC.run_template('tags-template',data.tags);
					var rowIndex = filetable.fnGetPosition(row[0]);
					filetable.fnUpdate(tags_html,rowIndex,2);//2 is for column index
//					row.find('.tags').html(tags_html);
					row.attr('data-notes',data.notes);
					row.attr('data-tags',data.tags);
					var name_col = row.find('.name');
					name_col.attr('data-toggle','tooltip');
					name_col.attr('title',data.notes);
				}
			}
		}
	);
//	BC.ajax(
//			{
//				'url':url,
//				'data':{'tags':$('#edit-metadata-form [name=tags]').val(),'notes':$('#edit-metadata-form [name=notes]').val()},
//				'success':function(data){
//					if(data.name){
//						$('#edit-metadata').modal('hide');
//						var row = $('#file-table [data-id="'+id+'"]');
//						var tags_html = BC.run_template('tags-template',data.tags);
//						row.find('.tags').html(tags_html);
//						row.attr('data-notes',data.notes);
//						row.attr('data-tags',data.tags);
//						var name_col = row.find('.name');
//						name_col.attr('data-toggle','tooltip');
//						name_col.attr('title',data.notes);
//					}
//				}
//			}
//		);
}
function create_folder(){
		BC.ajax_form_submit('#new-folder-form',{
			'success':function(data){
				$.each(data.objects,function(index,obj){
					var html = BC.run_template('directory-template',obj);
					//var row = '
<input class="action-check" type="checkbox"/>	'+obj.name+'
';
                    var row = $(html).prependTo('#file-table');
                    filetable.fnAddTr(row[0]);
                    $.bootstrapGrowl('"'+obj.name+'" folder created',{type:'info',delay: 3000});
				});
				$('#new-folder').modal('hide');
				toggle_table_visibility();
			}
		});
		return false;
}
$(function () {
	$(document).on('click','[data-action="edit-metadata"]',open_metadata_form);
	$(document).on('click','[data-action="preview"]',preview_share_action);
	toggle_table_visibility();
	BC.load_templates()
    $('#fileupload').fileupload({
        url: upload_file_url,
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
            	var old = $('#file-table tr[data-id="'+file.name+'"]');
            	if(old.length!=0){
            		old.addClass('warning');
            		$.bootstrapGrowl('Overwrote file: '+file.name,{type:'info',delay: 3000});
            	}
            	else{
            		file.download = share_perms.indexOf('download_share_files') > -1;
            		//var row = '
<input class="action-check" type="checkbox"/>	'+file.name+'	'+file.size+'	'+file.modified+'
';
            		var row = BC.run_template('file-template',file);
            		if($('#file-table .directory').length==0)
                    	var row = $(row).prependTo('#file-table tbody');
                    else
                    	var row = $(row).insertAfter('#file-table .directory:last');
            		filetable.fnAddTr(row[0]);
            		$.bootstrapGrowl('Successfully uploaded '+file.name,{type:'success',delay: 3000});
            	}
            });
            $('#progress').hide();
            toggle_table_visibility();
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css(
                'width',
                progress + '%'
            );
        },
        start: function(e){
        	$('#progress').show();
        }
    });
    $('#create-folder').click(create_folder);
    $('#new-folder-form').submit(create_folder);
    $('#toggle-checkbox').change(function(){
		$('.action-check').prop('checked',$(this).prop('checked'));
    });
    $('#download-zip').click(function(){
    	archive_files(archive_files_url,get_selected_names());
    });
    $('#download-rsync').click(function(){
    	generate_rsync_download(share,subpath);
    });
    $('#upload-rsync').click(function(){
    	generate_rsync_upload(share,subpath);
    });
    $('#delete-button').click(function(){
    	if(confirm('Are you sure you want to delete these files/folders?'))
			delete_paths(delete_paths_url,get_selected_names());
    });
    $('#launch-action').click(function(){
    	switch($('#action').val()){
    		case 'download':
    			archive_files(archive_files_url,get_selected_names());
    			break;
    		case 'delete':
    			//alert('delete '+get_selected_names());
    			if(confirm('Are you sure you want to delete these files/folders?'))
    				delete_paths(delete_paths_url,get_selected_names());
    			break;
    		case 'rsync':
    			generate_rsync_strings(share,subpath);
    	}
    });
    $('#searchButton').click(function(){search_share($('#searchBox').val())});
    $('#save-metadata').click(edit_metadata);
    $('#file-table').on('click','span.tag',function(){hide_other_tags($(this).text())});
    filtered_tags = [];
    $('#reset-tag-button').click(reset_tags);
});
function hide_other_tags(tag){
	if(filtered_tags.indexOf(tag) >= 0)
		return;
	filtered_tags.push(tag);
	$('tr.file,tr.directory','#file-table').each(function(index,row){
		if($(row).attr('data-tags')=='')
			$(row).addClass('hide-me');
		var tags=$(row).attr('data-tags').split(',');
		if(tags.indexOf(tag) < 0)
			$(row).addClass('hide-me');
	});
	$('#file-table tr.hide-me').hide();
	$('#filtered-tags').text(filtered_tags.join(', '));
	$('#reset-tags').show();
//	setTimeout(function(){
//		$('#file-table tr.hide-me').hide();
//			$('#file-table tr.hide-me').fadeOut({
//				'duration':200//,
////				'complete':function(){$(this).remove();}
//			});
//		}
//	,500);
}
function reset_tags(){
	$('#file-table tr.hide-me').show().removeClass('hide-me');
	$('#reset-tags').hide();
	filtered_tags = [];
}<commit_msg>prevent user from creating empty zipfiles<commit_after>function search_share(query){
	$.get(search_url,{query:query},function(data){
		//console.log(data);
		$('#searchResults').html('');
		$.each(data.results,function(index,result){
			var split_at = result.lastIndexOf("/")+1;
			var directory = result.substring(0, split_at-1);
			var dir_link = ''+directory+' /';
			var file = result.substring(split_at);
			var file_link = file == '' ? '' : ''+file+'';
			$('#searchResults').append('
'+dir_link+' '+file_link+'
');
		});
	});
}

function get_selected_names(){
	var selection = [];
	$('.action-check:checked').each(function(){
		selection.push($(this).closest('tr').attr('data-id'));
	});
	return selection;
}
function generate_rsync_strings(share,subpath){
	var re = new RegExp(' ', 'g');
	var selection = get_selected_names();
	for(var i in selection){
		if (selection[i].indexOf(' ') > -1)
			selection[i] = "'"+selection[i].replace(re,'\\ ')+"'";
	}

	var path = subpath ? '/'+ share + '/' + subpath: '/'+share+'/';
	if (path.indexOf(' ') > -1)
		path = "'"+path.replace(re,'\\ ')+"'";
	var files = selection.length > 0 ? '{'+selection.join(',')+'}' : '';
	var download_string = "rsync -vrzt adam@phymaptest:"+path+files+" /to/my/local/directory";
	var upload_string = "rsync -vrzt /path/to/my/files  adam@phymaptest:"+path;

	$('#rsync-download-command').text(download_string);
	$('#rsync-upload-command').text(upload_string);
	$('#rsync-download').modal('show');
}
function generate_rsync_download(share,subpath){
	var re = new RegExp(' ', 'g');
	var selection = get_selected_names();
	for(var i in selection){
		if (selection[i].indexOf(' ') > -1)
			selection[i] = "'"+selection[i].replace(re,'\\ ')+"'";
	}

	var path = subpath ? '/'+ share + '/' + subpath: '/'+share+'/';
	if (path.indexOf(' ') > -1)
		path = "'"+path.replace(re,'\\ ')+"'";
	var files = selection.length > 0 ? '{'+selection.join(',')+'}' : '';
	var download_all_string = "rsync -vrzt "+rsync_url+":"+path+" /to/my/local/directory";
	var download_string = "rsync -vrzt "+rsync_url+":"+path+files+" /to/my/local/directory";

	$('#rsync-download-selected').text(download_string);
	$('#rsync-download-all').text(download_all_string);
	$('#rsync-download').modal('show');
}
function generate_rsync_upload(share,subpath){
	var re = new RegExp(' ', 'g');
	var path = subpath ? '/'+ share + '/' + subpath: '/'+share+'/';
	if (path.indexOf(' ') > -1)
		path = "'"+path.replace(re,'\\ ')+"'";
	var upload_string = "rsync -vrzt /path/to/my/files "+rsync_url+":"+path;
	$('#rsync-upload-command').text(upload_string);
	$('#rsync-upload').modal('show');
}
function delete_paths(url,selection){
	BC.ajax(
		{
			'url':url,
			'data':{'json':JSON.stringify({'selection':selection})},
			'success':function(data){
				if(data.failed.length !=0){
					var message = "The following files were unable to be deleted: " + data.failed.join(', ');
					message += "
The filesystem may be read only.";
					$.bootstrapGrowl(message,{type:'error',delay: 10000});
				}
				if(data.deleted){
					$.each(data.deleted,function(index,item){
						$('#file-table [data-id="'+item+'"]').addClass('error').addClass('deleted');
					});
					setTimeout(function(){
							$('#file-table tr.deleted').fadeOut({
								'duration':500,
								'complete':function(){filetable.fnDeleteRow($(this)[0]);toggle_table_visibility();}
									});
							}
						,500);
				}
			}
		}
	);
}
function archive_files(url,selection){
	if(selection.length  == 0)
		alert('Please select at least 1 file to be archived.');
	else
		BC.ajax(
			{
				'url':url,
				'data':{'json':JSON.stringify({'selection':selection})},
				'success':function(data){
					if(data.url){
						var message = 'Archive ready for download';
						$.bootstrapGrowl(message,{delay: 100000000,type:'success'});
					}
				}
			}
		);
}

function toggle_table_visibility(){
	if($('#file-table tbody tr').length == 1){
		$('#add-files-message').removeClass('hidden');
	}else{
		$('#add-files-message').addClass('hidden');
	}
}
function open_metadata_form(){
	var row = $(this).closest('tr');
	$('#edit-metadata-form').html($('#edit-meta-data-form-clean').html());
	$('#edit-metadata-form [name=notes]').val(row.attr('data-notes'));
	$('#edit-metadata-form [name=tags]').val(row.attr('data-tags'));
	$('#metadata-label').text(row.attr('data-id'));
	$('#metadata-id').val(row.attr('data-id'));
	$('#edit-metadata').modal('show');
}
function preview_share_action(){
	var row = $(this).closest('tr');
	var path = subpath ? subpath + row.attr('data-id') : row.attr('data-id');
	preview_file(share,path);
}

function edit_metadata(){
	var id = $('#metadata-id').val();
	var url = metadata_url+id;

	BC.ajax_form_submit('#edit-metadata-form',
		{
			'ajax':{
				'url':url,
				'data':{'tags':$('#edit-metadata-form [name=tags]').val(),'notes':$('#edit-metadata-form [name=notes]').val()}
			},
			'success':function(data){
				if(data.name){
					$('#edit-metadata').modal('hide');
					var row = $('#file-table [data-id="'+id+'"]');
					var tags_html = BC.run_template('tags-template',data.tags);
					var rowIndex = filetable.fnGetPosition(row[0]);
					filetable.fnUpdate(tags_html,rowIndex,2);//2 is for column index
//					row.find('.tags').html(tags_html);
					row.attr('data-notes',data.notes);
					row.attr('data-tags',data.tags);
					var name_col = row.find('.name');
					name_col.attr('data-toggle','tooltip');
					name_col.attr('title',data.notes);
				}
			}
		}
	);
//	BC.ajax(
//			{
//				'url':url,
//				'data':{'tags':$('#edit-metadata-form [name=tags]').val(),'notes':$('#edit-metadata-form [name=notes]').val()},
//				'success':function(data){
//					if(data.name){
//						$('#edit-metadata').modal('hide');
//						var row = $('#file-table [data-id="'+id+'"]');
//						var tags_html = BC.run_template('tags-template',data.tags);
//						row.find('.tags').html(tags_html);
//						row.attr('data-notes',data.notes);
//						row.attr('data-tags',data.tags);
//						var name_col = row.find('.name');
//						name_col.attr('data-toggle','tooltip');
//						name_col.attr('title',data.notes);
//					}
//				}
//			}
//		);
}
function create_folder(){
		BC.ajax_form_submit('#new-folder-form',{
			'success':function(data){
				$.each(data.objects,function(index,obj){
					var html = BC.run_template('directory-template',obj);
					//var row = '
<input class="action-check" type="checkbox"/>	'+obj.name+'
';
                    var row = $(html).prependTo('#file-table');
                    filetable.fnAddTr(row[0]);
                    $.bootstrapGrowl('"'+obj.name+'" folder created',{type:'info',delay: 3000});
				});
				$('#new-folder').modal('hide');
				toggle_table_visibility();
			}
		});
		return false;
}
$(function () {
	$(document).on('click','[data-action="edit-metadata"]',open_metadata_form);
	$(document).on('click','[data-action="preview"]',preview_share_action);
	toggle_table_visibility();
	BC.load_templates()
    $('#fileupload').fileupload({
        url: upload_file_url,
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
            	var old = $('#file-table tr[data-id="'+file.name+'"]');
            	if(old.length!=0){
            		old.addClass('warning');
            		$.bootstrapGrowl('Overwrote file: '+file.name,{type:'info',delay: 3000});
            	}
            	else{
            		file.download = share_perms.indexOf('download_share_files') > -1;
            		//var row = '
<input class="action-check" type="checkbox"/>	'+file.name+'	'+file.size+'	'+file.modified+'
';
            		var row = BC.run_template('file-template',file);
            		if($('#file-table .directory').length==0)
                    	var row = $(row).prependTo('#file-table tbody');
                    else
                    	var row = $(row).insertAfter('#file-table .directory:last');
            		filetable.fnAddTr(row[0]);
            		$.bootstrapGrowl('Successfully uploaded '+file.name,{type:'success',delay: 3000});
            	}
            });
            $('#progress').hide();
            toggle_table_visibility();
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('#progress .bar').css(
                'width',
                progress + '%'
            );
        },
        start: function(e){
        	$('#progress').show();
        }
    });
    $('#create-folder').click(create_folder);
    $('#new-folder-form').submit(create_folder);
    $('#toggle-checkbox').change(function(){
		$('.action-check').prop('checked',$(this).prop('checked'));
    });
    $('#download-zip').click(function(){
    	archive_files(archive_files_url,get_selected_names());
    });
    $('#download-rsync').click(function(){
    	generate_rsync_download(share,subpath);
    });
    $('#upload-rsync').click(function(){
    	generate_rsync_upload(share,subpath);
    });
    $('#delete-button').click(function(){
    	if(confirm('Are you sure you want to delete these files/folders?'))
			delete_paths(delete_paths_url,get_selected_names());
    });
    $('#launch-action').click(function(){
    	switch($('#action').val()){
    		case 'download':
    			archive_files(archive_files_url,get_selected_names());
    			break;
    		case 'delete':
    			//alert('delete '+get_selected_names());
    			if(confirm('Are you sure you want to delete these files/folders?'))
    				delete_paths(delete_paths_url,get_selected_names());
    			break;
    		case 'rsync':
    			generate_rsync_strings(share,subpath);
    	}
    });
    $('#searchButton').click(function(){search_share($('#searchBox').val())});
    $('#save-metadata').click(edit_metadata);
    $('#file-table').on('click','span.tag',function(){hide_other_tags($(this).text())});
    filtered_tags = [];
    $('#reset-tag-button').click(reset_tags);
});
function hide_other_tags(tag){
	if(filtered_tags.indexOf(tag) >= 0)
		return;
	filtered_tags.push(tag);
	$('tr.file,tr.directory','#file-table').each(function(index,row){
		if($(row).attr('data-tags')=='')
			$(row).addClass('hide-me');
		var tags=$(row).attr('data-tags').split(',');
		if(tags.indexOf(tag) < 0)
			$(row).addClass('hide-me');
	});
	$('#file-table tr.hide-me').hide();
	$('#filtered-tags').text(filtered_tags.join(', '));
	$('#reset-tags').show();
//	setTimeout(function(){
//		$('#file-table tr.hide-me').hide();
//			$('#file-table tr.hide-me').fadeOut({
//				'duration':200//,
////				'complete':function(){$(this).remove();}
//			});
//		}
//	,500);
}
function reset_tags(){
	$('#file-table tr.hide-me').show().removeClass('hide-me');
	$('#reset-tags').hide();
	filtered_tags = [];
}<|endoftext|>


<commit_before>var remote = require('electron').remote;
var BrowserWindow = remote.BrowserWindow;
var ipcMain = remote.ipcMain;
var path = require('path');

var invisMsgBtn = document.getElementById('invis-msg');

invisMsgBtn.addEventListener('click', function (clickEvent) {
  var invisPath = 'file://' + path.join(process.cwd(), 'sections/communication/invisible.html')
  var win = new BrowserWindow({ width: 0, height: 0, show: false });
  win.loadURL(invisPath);
  win.webContents.on('did-finish-load', function (clickEvent) {
    // after invisible page loads, pass the original event
    // then use the main process browser window web contents get the window
    // from the event and then use webcontents to send a message that
    // the invisible window can listen for
    var appWindow = BrowserWindow.fromWebContents(clickEvent.sender)
    appWindow.webContents.send('send-ping', 'whoooooooh!');
  });
});

ipcMain.on('ping-reply', function (event, arg) {
  var message = "Invisible window reply: " + arg;
  document.getElementById('invis-reply').innerHTML = message;
})
<commit_msg>Ok it didn't work, and this doesn't either<commit_after>var remote = require('electron').remote;
var BrowserWindow = remote.BrowserWindow;
var ipcMain = remote.ipcMain;
var path = require('path');

var invisMsgBtn = document.getElementById('invis-msg');

invisMsgBtn.addEventListener('click', function (clickEvent) {
  // var appWindow = BrowserWindow.fromWebContents(clickEvent.sender);
  var appWindowID = BrowserWindow.getFocusedWindow().id

  var invisPath = 'file://' + path.join(process.cwd(), 'sections/communication/invisible.html')
  var win = new BrowserWindow({ width: 400, height: 400, show: true });
  win.loadURL(invisPath);
  console.log("win id:", win.id)
  win.webContents.on('did-finish-load', function (clickEvent) {
    // after invisible page loads, pass the original click event
    // then use that to get the web contents from the main process browser window
    // from there send a message that the invisible window can listen for
    var appWindow = BrowserWindow.fromId(appWindowID)
    console.log("appWindow id:", appWindowID)
    console.log("title", appWindow.webContents.getTitle())
    appWindow.webContents.send('send-ping', 'ping!');
  });
});

ipcMain.on('ping-reply', function (event, arg) {
  var message = "Invisible window reply: " + arg;
  document.getElementById('invis-reply').innerHTML = message;
})
<|endoftext|>


<commit_before>import React from 'react'
import 'babel-polyfill'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { FormattedMessage } from 'react-intl'
import * as actionCreators from '../../actions/transactions'
import AddTransaction from '../Modals/AddTransaction.js'
import EditTransaction from '../Modals/EditTransaction.js'
import TextField from 'material-ui/TextField'
import Toggle from 'material-ui/Toggle'
import Checkbox from 'material-ui/Checkbox'
import Snackbar from 'material-ui/Snackbar'
import { GridLoader } from 'halogen'

import {
  Table,
  TableBody,
  TableFooter,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn
} from 'material-ui/Table'

import styles from './styles.scss'

function mapStateToProps(state) {
  return {
    data: state.transactions.data,
    token: state.auth.token,
    loaded: state.transactions.loaded,
    isFetching: state.transactions.isFetching,
    selectedAccount: state.accounts.selectedAccount
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch)
}

@connect(mapStateToProps, mapDispatchToProps)
export default class TransactionsList extends React.Component {
  state = {
    fixedHeader: true,
    fixedFooter: true,
    stripedRows: true,
    showRowHover: false,
    selectable: false,
    multiSelectable: false,
    enableSelectAll: false,
    deselectOnClickaway: false,
    showCheckboxes: false,
    height: '400px',
    snackOpen: false,
    snackMessage: ''
  }

  fetchData(account_id = null) {
    if (account_id === null) {
      account_id = this.props.selectedAccount
    }
    if (account_id !== null) {
      const token = this.props.token
      this.props.fetchTransactionsData(token, account_id)
    }
  }

  showSnack(snackMessage) {
    this.setState({
      snackMessage,
      snackOpen: true
    })
  }

  handleSnackClose() {
    this.setState({
      snackOpen: false
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectedAccount !== this.props.selectedAccount) {
      this.fetchData(nextProps.selectedAccount)
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // Do not scroll on ticking
    if (prevProps.data !== this.props.data) {
      this.scrollToBottom()
    }
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled
    })
  }

  handleChange = event => {
    this.setState({ height: event.target.value })
  }

  scrollToBottom() {
    if (this.refs.table !== undefined) {
      this.refs.table.refs.tableDiv.scrollTop = this.refs.table.refs.tableDiv.scrollHeight
    }
  }

  createTransaction(transaction) {
    const token = this.props.token
    let call = async () =>
      await await this.props.createTransaction(token, transaction)
    call().then(() => {
      this.fetchData()
      this.props.updateBalance()
      this.showSnack(<FormattedMessage id="transactionsList.snack.create" />)
    })
  }

  editTransaction(transaction) {
    const token = this.props.token
    let call = async () =>
      await await this.props.editTransaction(token, transaction)
    call().then(() => {
      this.fetchData()
      this.props.updateBalance()
      this.showSnack(<FormattedMessage id="transactionsList.snack.edit" />)
    })
  }

  deleteTransaction(id) {
    const token = this.props.token
    let call = async () => await await this.props.deleteTransaction(token, id)
    call().then(() => {
      this.fetchData()
      this.props.updateBalance()
      this.showSnack(<FormattedMessage id="transactionsList.snack.delete" />)
    })
  }

  tickTransaction(id_transaction, isChecked) {
    const token = this.props.token
    let call = async () =>
      await await this.props.tickTransaction(token, id_transaction, isChecked)
    call().then(() => {
      this.props.updateBalance()
    })
  }

  renderTransactionsList(transactions) {
    transactions.sort((a, b) => {
      if (new Date(a.date) < new Date(b.date)) return -1
      if (new Date(a.date) > new Date(b.date)) return 1
      if (a.id  b.id) return 1
      return 0
    })
    // filter future recurring transactions
    transactions = transactions.filter(element => {
      return (
        element.recurring_group_id === null ||
        (element.recurring_group_id !== null &&
          new Date(element.date) <= new Date())
      )
    })
    const rows = transactions.map((row, index) => {
      let credit =
        parseFloat(row.amount) < 0 ? '' : Number(row.amount).toFixed(2)
      let debit =
        parseFloat(row.amount) < 0 ? Number(row.amount).toFixed(2) : ''
      return (
        <TableRow key={row.transaction_id}>
          <TableRowColumn className={styles.tickColumn}>
            <Checkbox
              defaultChecked={Boolean(row.tick)}
              onCheck={(e, isChecked) =>
                this.tickTransaction(row.transaction_id, isChecked)}
            />
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            {row.date.toString()}
          </TableRowColumn>
          <TableRowColumn className={styles.largeColumn}>
            {row.label}
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            {debit}
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            {credit}
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            <EditTransaction
              fields={row}
              editTransaction={this.editTransaction.bind(this)}
              deleteTransaction={this.deleteTransaction.bind(this)}
            />
          </TableRowColumn>
        </TableRow>
      )
    })
    return rows
  }

  render() {
    if (
      this.props.selectedAccount === undefined ||
      this.props.selectedAccount === null
    ) {
      return (

            <FormattedMessage id="transactionsList.noAccount" />

      )
    }

    return (

        {!this.props.loaded
          ? <GridLoader color="#00BCD4" size="16px" margin="4px" />
          :

                <TableHeader
                  displaySelectAll={this.state.showCheckboxes}
                  adjustForCheckbox={this.state.showCheckboxes}
                  enableSelectAll={this.state.enableSelectAll}
                >
                  <TableRow>
                    <TableHeaderColumn className={styles.tickColumn}>
                      <FormattedMessage id="transactionsList.table.tick" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn}>
                      <FormattedMessage id="transactionsList.table.date" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.largeColumn}>
                      <FormattedMessage id="transactionsList.table.label" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn}>
                      <FormattedMessage id="transactionsList.table.debit" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn}>
                      <FormattedMessage id="transactionsList.table.credit" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn} />
                  </TableRow>
                </TableHeader>
                <TableBody
                  displayRowCheckbox={this.state.showCheckboxes}
                  deselectOnClickaway={this.state.deselectOnClickaway}
                  showRowHover={this.state.showRowHover}
                  stripedRows={this.state.stripedRows}
                  style={{ height: '100%' }}
                >
                  {this.renderTransactionsList(this.props.data)}
                </TableBody>
                <TableFooter adjustForCheckbox={this.state.showCheckboxes}>
                  <TableRow>
                    <TableRowColumn colSpan="5">
                      <AddTransaction
                        selectedAccount={this.props.selectedAccount}
                        createTransaction={this.createTransaction.bind(this)}
                      />
                    </TableRowColumn>
                  </TableRow>
                </TableFooter>

              <Snackbar
                open={this.state.snackOpen}
                message={this.state.snackMessage}
                autoHideDuration={4000}
                onRequestClose={this.handleSnackClose.bind(this)}
              />

}

    )
  }
}

TransactionsList.propTypes = {
  fetchTransactionsData: React.PropTypes.func,
  loaded: React.PropTypes.bool,
  data: React.PropTypes.any,
  token: React.PropTypes.string,
  selectedAccount: React.PropTypes.number
}
<commit_msg>Fix width of transactions list<commit_after>import React from 'react'
import 'babel-polyfill'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { FormattedMessage } from 'react-intl'
import * as actionCreators from '../../actions/transactions'
import AddTransaction from '../Modals/AddTransaction.js'
import EditTransaction from '../Modals/EditTransaction.js'
import TextField from 'material-ui/TextField'
import Toggle from 'material-ui/Toggle'
import Checkbox from 'material-ui/Checkbox'
import Snackbar from 'material-ui/Snackbar'
import { GridLoader } from 'halogen'

import {
  Table,
  TableBody,
  TableFooter,
  TableHeader,
  TableHeaderColumn,
  TableRow,
  TableRowColumn
} from 'material-ui/Table'

import styles from './styles.scss'

function mapStateToProps(state) {
  return {
    data: state.transactions.data,
    token: state.auth.token,
    loaded: state.transactions.loaded,
    isFetching: state.transactions.isFetching,
    selectedAccount: state.accounts.selectedAccount
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch)
}

@connect(mapStateToProps, mapDispatchToProps)
export default class TransactionsList extends React.Component {
  state = {
    fixedHeader: true,
    fixedFooter: true,
    stripedRows: true,
    showRowHover: false,
    selectable: false,
    multiSelectable: false,
    enableSelectAll: false,
    deselectOnClickaway: false,
    showCheckboxes: false,
    height: '400px',
    width: '100%',
    snackOpen: false,
    snackMessage: ''
  }

  fetchData(account_id = null) {
    if (account_id === null) {
      account_id = this.props.selectedAccount
    }
    if (account_id !== null) {
      const token = this.props.token
      this.props.fetchTransactionsData(token, account_id)
    }
  }

  showSnack(snackMessage) {
    this.setState({
      snackMessage,
      snackOpen: true
    })
  }

  handleSnackClose() {
    this.setState({
      snackOpen: false
    })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.selectedAccount !== this.props.selectedAccount) {
      this.fetchData(nextProps.selectedAccount)
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // Do not scroll on ticking
    if (prevProps.data !== this.props.data) {
      this.scrollToBottom()
    }
  }

  handleToggle = (event, toggled) => {
    this.setState({
      [event.target.name]: toggled
    })
  }

  handleChange = event => {
    this.setState({ height: event.target.value })
  }

  scrollToBottom() {
    if (this.refs.table !== undefined) {
      this.refs.table.refs.tableDiv.scrollTop = this.refs.table.refs.tableDiv.scrollHeight
    }
  }

  createTransaction(transaction) {
    const token = this.props.token
    let call = async () =>
      await await this.props.createTransaction(token, transaction)
    call().then(() => {
      this.fetchData()
      this.props.updateBalance()
      this.showSnack(<FormattedMessage id="transactionsList.snack.create" />)
    })
  }

  editTransaction(transaction) {
    const token = this.props.token
    let call = async () =>
      await await this.props.editTransaction(token, transaction)
    call().then(() => {
      this.fetchData()
      this.props.updateBalance()
      this.showSnack(<FormattedMessage id="transactionsList.snack.edit" />)
    })
  }

  deleteTransaction(id) {
    const token = this.props.token
    let call = async () => await await this.props.deleteTransaction(token, id)
    call().then(() => {
      this.fetchData()
      this.props.updateBalance()
      this.showSnack(<FormattedMessage id="transactionsList.snack.delete" />)
    })
  }

  tickTransaction(id_transaction, isChecked) {
    const token = this.props.token
    let call = async () =>
      await await this.props.tickTransaction(token, id_transaction, isChecked)
    call().then(() => {
      this.props.updateBalance()
    })
  }

  renderTransactionsList(transactions) {
    transactions.sort((a, b) => {
      if (new Date(a.date) < new Date(b.date)) return -1
      if (new Date(a.date) > new Date(b.date)) return 1
      if (a.id  b.id) return 1
      return 0
    })
    // filter future recurring transactions
    transactions = transactions.filter(element => {
      return (
        element.recurring_group_id === null ||
        (element.recurring_group_id !== null &&
          new Date(element.date) <= new Date())
      )
    })
    const rows = transactions.map((row, index) => {
      let credit =
        parseFloat(row.amount) < 0 ? '' : Number(row.amount).toFixed(2)
      let debit =
        parseFloat(row.amount) < 0 ? Number(row.amount).toFixed(2) : ''
      return (
        <TableRow key={row.transaction_id}>
          <TableRowColumn className={styles.tickColumn}>
            <Checkbox
              defaultChecked={Boolean(row.tick)}
              onCheck={(e, isChecked) =>
                this.tickTransaction(row.transaction_id, isChecked)}
            />
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            {row.date.toString()}
          </TableRowColumn>
          <TableRowColumn className={styles.largeColumn}>
            {row.label}
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            {debit}
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            {credit}
          </TableRowColumn>
          <TableRowColumn className={styles.smallColumn}>
            <EditTransaction
              fields={row}
              editTransaction={this.editTransaction.bind(this)}
              deleteTransaction={this.deleteTransaction.bind(this)}
            />
          </TableRowColumn>
        </TableRow>
      )
    })
    return rows
  }

  render() {
    if (
      this.props.selectedAccount === undefined ||
      this.props.selectedAccount === null
    ) {
      return (

            <FormattedMessage id="transactionsList.noAccount" />

      )
    }

    return (

        {!this.props.loaded
          ? <GridLoader color="#00BCD4" size="16px" margin="4px" />
          :

                <TableHeader
                  displaySelectAll={this.state.showCheckboxes}
                  adjustForCheckbox={this.state.showCheckboxes}
                  enableSelectAll={this.state.enableSelectAll}
                >
                  <TableRow>
                    <TableHeaderColumn className={styles.tickColumn}>
                      <FormattedMessage id="transactionsList.table.tick" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn}>
                      <FormattedMessage id="transactionsList.table.date" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.largeColumn}>
                      <FormattedMessage id="transactionsList.table.label" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn}>
                      <FormattedMessage id="transactionsList.table.debit" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn}>
                      <FormattedMessage id="transactionsList.table.credit" />
                    </TableHeaderColumn>
                    <TableHeaderColumn className={styles.smallColumn} />
                  </TableRow>
                </TableHeader>
                <TableBody
                  displayRowCheckbox={this.state.showCheckboxes}
                  deselectOnClickaway={this.state.deselectOnClickaway}
                  showRowHover={this.state.showRowHover}
                  stripedRows={this.state.stripedRows}
                  style={{ height: '100%', width: '100%' }}
                >
                  {this.renderTransactionsList(this.props.data)}
                </TableBody>
                <TableFooter adjustForCheckbox={this.state.showCheckboxes}>
                  <TableRow>
                    <TableRowColumn colSpan="5">
                      <AddTransaction
                        selectedAccount={this.props.selectedAccount}
                        createTransaction={this.createTransaction.bind(this)}
                      />
                    </TableRowColumn>
                  </TableRow>
                </TableFooter>

              <Snackbar
                open={this.state.snackOpen}
                message={this.state.snackMessage}
                autoHideDuration={4000}
                onRequestClose={this.handleSnackClose.bind(this)}
              />

}

    )
  }
}

TransactionsList.propTypes = {
  fetchTransactionsData: React.PropTypes.func,
  loaded: React.PropTypes.bool,
  data: React.PropTypes.any,
  token: React.PropTypes.string,
  selectedAccount: React.PropTypes.number
}
<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2016  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import React, { PropTypes } from 'react';
import { form as inform } from 'react-inform';
import Loader from 'react-loader';
import { sortBy } from 'lodash';

import GeoInput from '../geo-input';
import Message from '../message';
import { LOADER_OPTIONS } from '../../consts/loader';

class SchoolEditForm extends React.Component {
  static displayName = 'SchoolEditForm';

  static propTypes = {
    countries: PropTypes.objectOf(PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired
    })).isRequired,
    fields: PropTypes.shape({
      description: PropTypes.shape().isRequired,
      name: PropTypes.shape({
        error: PropTypes.string
      }).isRequired
    }).isRequired,
    form: PropTypes.shape({
      forceValidate: PropTypes.func,
      isValid: PropTypes.func,
      onValues: PropTypes.func
    }).isRequired,
    saveHandler: PropTypes.func.isRequired,
    school: PropTypes.shape({
      description: PropTypes.string,
      id: PropTypes.string,
      lat: PropTypes.number,
      lon: PropTypes.number,
      name: PropTypes.string
    }).isRequired
  };

  componentDidMount() {
    const {
      form,
      school
     } = this.props;

    form.onValues(school);
  }

  submitHandler = (event) => {
    event.preventDefault();

    const { fields, form } = this.props;

    form.forceValidate();

    if (!form.isValid()) {
      return;
    }

    let theForm = event.target;

    const isOpenValue = fields.is_open.value;
    let isOpenDbValue = null;
    if (isOpenValue === 'yes') {
      isOpenDbValue = true;
    } else if (isOpenValue === 'no') {
      isOpenDbValue = false;
    }

    this.props.saveHandler(
      theForm.id.value,
      {
        name: fields.name.value,
        description: fields.description.value,
        country_id: fields.country_id.value,
        lat: theForm.lat.value,
        lon: theForm.lon.value,
        is_open: isOpenDbValue,
        principal_name: fields.principal_name.value,
        principal_surname: fields.principal_surname.value,
      }
    );
  };

  render() {
    const { countries, fields, form, school, processing } = this.props;
    const initialLocation = {lat: school.lat, lon: school.lon};

    let is_open = 'unknown';

    if (school.is_open === true) {
      is_open = 'yes';
    } else if (school.is_open === false) {
      is_open = 'no';
    }

    return (
      <form onSubmit={this.submitHandler}>
        <input name="id" type="hidden" value={school.id} />

          Name
          <input
            className="input input-block content layout__row layout__row-small"
            defaultValue={school.name}
            type="text"
            id="name"
            {...fields.name}
          />

          {fields.name.error &&
            <Message message={fields.name.error} />
          }

          Is it open?
          <select
            className="input input-block input-select layout__row layout__row-small"
            defaultValue={is_open}
            id="is_open"
            {...fields.is_open}
          >
            <option value="unknown">unknown</option>
            <option value="yes">Yes</option>
            <option value="no">No</option>
          </select>

          Description
            <textarea
              className="input input-block input-textarea content layout__row layout__row-small"
              defaultValue={school.description}
              id="description"
              {...fields.description}
            />

          Country
          <select
            className="input input-block input-select layout__row layout__row-small"
            defaultValue={school.country_id}
            id="country_id"
            {...fields.country_id}
          >
            <option value="">unknown</option>
            {sortBy(countries, 'name').map(country => <option value={country.id} key={country.id}>{country.name}</option>)}
          </select>

        <GeoInput initialLocation={initialLocation} />

          Principal Name
          <input
            className="input input-block content layout__row layout__row-small"
            defaultValue={school.principal_name}
            type="text"
            id="principal_name"
            {...fields.principal_name}
          />

          Principal Surname
          <input
            className="input input-block content layout__row layout__row-small"
            defaultValue={school.principal_surname}
            type="text"
            id="principal_name"
            {...fields.principal_surname}
          />

            <Loader loaded={!processing} options={{...LOADER_OPTIONS, left: '90%'}}>
              <button
                className="button button-wide button-green"
                disabled={!form.isValid()}
                type="submit"
              >
                Save
              </button>
            </Loader>

      </form>
    );
  }
}

const fields = ['name', 'description', 'is_open', 'principal_name', 'principal_surname', 'country_id'];
const validate = values => {
  const { name } = values;
  const errors = {};

  if (!name) {
    errors.name = 'Name is required';
  }

  return errors;
};

const WrappedSchoolEditForm = inform({
  fields,
  validate
})(SchoolEditForm);

export default WrappedSchoolEditForm;
<commit_msg>Extract text-input row of form into component<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2016  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import React, { PropTypes } from 'react';
import { form as inform } from 'react-inform';
import Loader from 'react-loader';
import { sortBy } from 'lodash';

import GeoInput from '../geo-input';
import Message from '../message';
import { LOADER_OPTIONS } from '../../consts/loader';

const TextInputField = ({ defaultValue, field, name, title, type='text' }) => {
  const id = `input_${name}`;

  return (

      {title}
      <input
        className="input input-block content layout__row layout__row-small"
        defaultValue={defaultValue}
        id={id}
        type={type}
        {...field}
      />

      {field.error &&
        <Message message={field.error} />
      }

  );
};

class SchoolEditForm extends React.Component {
  static displayName = 'SchoolEditForm';

  static propTypes = {
    countries: PropTypes.objectOf(PropTypes.shape({
      id: PropTypes.string.isRequired,
      name: PropTypes.string.isRequired
    })).isRequired,
    fields: PropTypes.shape({
      description: PropTypes.shape().isRequired,
      name: PropTypes.shape({
        error: PropTypes.string
      }).isRequired
    }).isRequired,
    form: PropTypes.shape({
      forceValidate: PropTypes.func,
      isValid: PropTypes.func,
      onValues: PropTypes.func
    }).isRequired,
    saveHandler: PropTypes.func.isRequired,
    school: PropTypes.shape({
      description: PropTypes.string,
      id: PropTypes.string,
      lat: PropTypes.number,
      lon: PropTypes.number,
      name: PropTypes.string
    }).isRequired
  };

  componentDidMount() {
    const {
      form,
      school
     } = this.props;

    form.onValues(school);
  }

  submitHandler = (event) => {
    event.preventDefault();

    const { fields, form } = this.props;

    form.forceValidate();

    if (!form.isValid()) {
      return;
    }

    let theForm = event.target;

    const isOpenValue = fields.is_open.value;
    let isOpenDbValue = null;
    if (isOpenValue === 'yes') {
      isOpenDbValue = true;
    } else if (isOpenValue === 'no') {
      isOpenDbValue = false;
    }

    this.props.saveHandler(
      theForm.id.value,
      {
        name: fields.name.value,
        description: fields.description.value,
        country_id: fields.country_id.value,
        lat: theForm.lat.value,
        lon: theForm.lon.value,
        is_open: isOpenDbValue,
        principal_name: fields.principal_name.value,
        principal_surname: fields.principal_surname.value,
      }
    );
  };

  render() {
    const { countries, fields, form, school, processing } = this.props;
    const initialLocation = {lat: school.lat, lon: school.lon};

    let is_open = 'unknown';

    if (school.is_open === true) {
      is_open = 'yes';
    } else if (school.is_open === false) {
      is_open = 'no';
    }

    return (
      <form onSubmit={this.submitHandler}>
        <input name="id" type="hidden" value={school.id} />

        <TextInputField defaultValue={school.name} field={fields.name} name="name" title="Name" />

          Is it open?
          <select
            className="input input-block input-select layout__row layout__row-small"
            defaultValue={is_open}
            id="is_open"
            {...fields.is_open}
          >
            <option value="unknown">unknown</option>
            <option value="yes">Yes</option>
            <option value="no">No</option>
          </select>

          Description
            <textarea
              className="input input-block input-textarea content layout__row layout__row-small"
              defaultValue={school.description}
              id="description"
              {...fields.description}
            />

          Country
          <select
            className="input input-block input-select layout__row layout__row-small"
            defaultValue={school.country_id}
            id="country_id"
            {...fields.country_id}
          >
            <option value="">unknown</option>
            {sortBy(countries, 'name').map(country => <option value={country.id} key={country.id}>{country.name}</option>)}
          </select>

        <GeoInput initialLocation={initialLocation} />

        <TextInputField defaultValue={school.principal_name} field={fields.principal_name} name="principal_name" title="Principal Name" />
        <TextInputField defaultValue={school.principal_surname} field={fields.principal_surname} name="principal_surname" title="Principal Surname" />

            <Loader loaded={!processing} options={{...LOADER_OPTIONS, left: '90%'}}>
              <button
                className="button button-wide button-green"
                disabled={!form.isValid()}
                type="submit"
              >
                Save
              </button>
            </Loader>

      </form>
    );
  }
}

const fields = ['name', 'description', 'is_open', 'principal_name', 'principal_surname', 'country_id'];
const validate = values => {
  const { name } = values;
  const errors = {};

  if (!name) {
    errors.name = 'Name is required';
  }

  return errors;
};

const WrappedSchoolEditForm = inform({
  fields,
  validate
})(SchoolEditForm);

export default WrappedSchoolEditForm;
<|endoftext|>


<commit_before>/*
 * @desc still not doing what I want!
 */
var temp = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
    temp2 = [1,2,3,4,5,6,7,8,9],

    picker = function (inputArray, numOfPoints) {
        var i = 1,
            tempArray = [],
            subArray = [],
            dataLength = 0,
            point = 0,
            pointsToDistribute = 0;

        // first item
        subArray.push(inputArray[0]);

        tempArray = inputArray.slice(1,this.length - 1);
        dataLength = tempArray.length;

        console.log("tempArray", tempArray);

        // numOfPoints - firstItem - lastItem
        pointsToDistribute = numOfPoints - 2;
        console.log("pointsToDistribute", pointsToDistribute);

        var interval = Math.floor(dataLength / pointsToDistribute);

        console.log("interval", interval);

        for (; i <= pointsToDistribute; i+=1) {

            point = tempArray[i*interval-1];
            console.log("point",point);

            subArray.push(point);
        }

        // last item
        subArray.push(inputArray[inputArray.length-1]);

        return subArray;
    };

picker(temp, 5);
<commit_msg>script update, close to expected results, also changed hardcoded array into anon IIFE<commit_after>/*
 * @desc close to solution, slightly off
 */
var temp = (function() {
        var i = 0,
            sub = [];

            for (; i<40; i+=1) {
                sub.push(i);
            }
            return sub;
    }()),
    temp2 =  (function() {
        var i = 0,
            sub = [];

            for (; i<100; i+=1) {
                sub.push(i);
            }
            return sub;
    }()),

    picker = function (inputArray, numOfPoints) {
        var i = 1,
            tempArray = [],
            subArray = [],
            dataLength = 0,
            point = 0,
            pointsToDistribute = 0;

        // first item
        subArray.push(inputArray[0]);

        tempArray = inputArray.slice(1,this.length - 1);
        dataLength = tempArray.length;

        console.log("tempArray", tempArray);

        // numOfPoints - firstItem - lastItem
        pointsToDistribute = numOfPoints - 2;
        console.log("pointsToDistribute", pointsToDistribute);

        var interval = Math.floor(dataLength / pointsToDistribute);

        console.log("interval", interval);

        for (; i <= pointsToDistribute; i+=1) {

            point = tempArray[i*interval-1];
            console.log("point",point);

            subArray.push(point);
        }

        // last item
        subArray.push(inputArray[inputArray.length-1]);

        return subArray;
    };

picker(temp, 5);
<|endoftext|>