<commit_before>
import Event from '../models/event.js';
import moment from 'moment';

const Q = new WeakMap();
const SERVICE = new WeakMap();

class EventForm {

	constructor(EventCategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
		Q.set(this, $q);
		SERVICE.set(this, EventsService);

		this.service = EventsService;
		this.vneuesService = VenuesService;
		this.categoriesService = EventCategoriesService;
		this.UserService = UserService;
		this.notificationService = Notification;
		this.params = $stateParams;
		this.rootScope = $rootScope;
		this.state = $state;

		this.restrict = 'EA';
        this.replace = true;
        this.templateUrl = 'templates/events/directives/form.html';
        this.scope = {
        };
	}

	submit(draft) {
		let event = this.model;
		let context = this;
		event.starts_at = moment(event.starts_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");
		event.ends_at = moment(event.ends_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");

		for (var i = 0; i < event.images.length; i++) {
            if (typeof event.images[i] === 'string') {
                continue;
            } else {
                let img = $('#'+event.images[i].id).cropit('export');
                if(!img) {
                    context.event.images.splice(i, 1);
                    continue;
                }
                event.images[i] = img;
            }
        }
        if(draft === true) {
            event.draft = draft;
        }

		if(!this.UserService.authenticated) {

            this.service.addUnsentEvent(event);
            this.notifyNeedsLogin();
            this.UserService.goLogin();
            return;
        }

        this.service.submit(event).then(function (response) {
            if(response.success === false) {
                context.errors = response.errors;
                window.scrollTo(0, 0);
            } else {
                console.log(response.event);
                if(draft) {
                    context.notifySuccessDraft(response.event.name);
                    context.state.go('venvast.events.drafts');
                } else {
                    context.notifySuccessCreate(response.event.name);
                    context.state.go('venvast.events.organize');
                }
            }
        });
		console.log(event);
	}

	link(scope, element) {
		let context = this;
		scope.createVenue = false;
		this.scope = scope;
		scope.submit = this.submit;

		scope.event = this.initModel();
		scope.addEntryOption = this.addEntryOption;
		scope.addEntryDesc = this.addEntryDesc;
		scope.deleteExistingImage = this.deleteExistingImage;
        scope.selectImage = this.selectImage;
        scope.deleteImage = this.deleteImage;
        scope.addImage = this.addImage;
        scope.getZoom = this.getZoom;
        scope.notificationService = this.notificationService;
        scope.notifyNeedsLogin = this.notifyNeedsLogin;
        scope.notifySuccessDraft = this.notifySuccessDraft;
        scope.notifySuccessCreate = this.notifySuccessCreate;
        scope.state = this.state;
        scope.UserService = this.UserService;
        scope.service = SERVICE.get(this);
	}

	addEntryOption () {
		this.model.entry_options.push({
			title: null,
			fee: 0,
			description: false
		});
	}

	addEntryDesc($index) {
		this.model.entry_options[$index].description = '';
	}

	initModel() {
        let context = this;
        if (this.params.slug) {
            this.initExistingModel();
        } else {
            this.initEmptyModel();
        }
        context.scope.dayAliases = [
            'Sun', 'Mon', 'Tue',
            'Wed', 'Thu', 'Fri',
            'Sat'
        ];
    }

	initExistingModel() {
        let context = this;
        SERVICE.get(this).gettingEditable(this.params.slug).then(function (response) {
            context.scope.model = response;
            let model = context.scope.model;
            if (response.venue) {
                $('#venue-search').val(response.venue.name);
                model.venue = model.venue.id;
            }
            context.categoriesService.gettingCategories().then((categories) => {
                context.initImageCropper(context.scope.model);
                context.addExistingImages(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
            });
        });
	}

	initEmptyModel () {
        this.scope.model = {
            name: null,
            categories: [],
            starts_at: moment().add(6, 'h').format('YYYY.DD.MM H:mm'),
            ends_at: moment().add(9, 'h').format('YYYY.DD.MM H:mm'),
            description: null,
            venue: true,
            phone: null,
            email: null,
            website: null,
            free_entry: true,
            entry_options: [],
            locale: 'en',
            agree_conditions: false,
            images: []
        }
        context.categoriesService.gettingCategories().then((categories) => {
                context.initImageCropper(context.scope.model);
                context.addExistingImages(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
        });
    }

    initDateFrom () {
        let model = this.scope.model.starts_at;
        let end = this.scope.model.ends_at;
        $('#date_start').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            defaultSelect: false,
            onShow: function (ct) {
                // this.setOptions({
                //     maxDate: end ? end : false
                // });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initDateTo () {
        let model = this.scope.model.ends_at;
        let start = this.scope.model.starts_at;
        $('#date_end').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            startDate: model,
            maxDate: false,
            defaultSelect: false,
            onShow: function (ct) {
                this.setOptions({
                    minDate: start ? start : false
                });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initTypeAhed() {
    	let input = $('#venue-search');
    	let context = this;
    	console.log("INited typeahead for element: ", input);
    	$(input).typeahead({
            source: function(query, process) {
                context.vneuesService.typeAheadRequest('mode', query).then(function(data) {
                	console.log("Got data");
                    return process(data);
                });

            },
            select: function () {
                var val = this.$menu.find('.active').data('value');
                this.$element.data('active', val);
                if(this.autoSelect || val) {
                    var newVal = this.updater(val);

                    if (!newVal) {
                        newVal = "";
                    }

                    this.$element
                        .val(newVal.name)
                        .change();
                    this.afterSelect(newVal);
                }
                return this.hide();
            },
            afterSelect: function (element) {
                context.scope.model.venue = element.id;
            },
            displayText: function(item) {
                return '
' +
                '
' + item.name + '

' + item.category + '

'; //

            },
            highlighter: function(item) {
                return unescape(item);
            },
            minLength: 3,
            maxItem: 5,
            autoSelect: true
        });
    }

      addImage(model) {
        var finalWidth  = 900;
        var finalHeight = 300;
        let length = model.images.length;
        let image = {id: 'image-'+ length};
        let context = this;
        model.images.push(image);
        setTimeout(function(image) {
            $('#'+image.id).cropit({
                exportZoom: context.getZoom(finalHeight, finalWidth, '#'+image.id)
            });
        }, 1000, image);
    }

    initImageCropper(model) {
        if(model.images.length === 0) {
            this.addImage(model);
        }
    }

    addExistingImages (model) {
        this.scope.existingImages = model.images.slice();
    }

    deleteExistingImage (index) {
        this.scope.existingImages.splice(index, 1);
    }

    getZoom(finalHeight, finalWidth, selectContext) {
        let sizeRatio = finalHeight / finalWidth;
        let newWidth = $('.cropit-preview').width();
        let newHeight = newWidth * sizeRatio;
        return finalWidth / newWidth;
    }

    selectImage(image) {
        $('.cropit-image-input', '#'+image.id).click();
    }

    deleteImage(image) {
        if (this.model.images.length > 1) {
            for (var i = 0; i < this.model.images.length; i++) {
                let img = this.model.images[i];
                if(img.id === image.id) {
                    this.model.images.splice(i, 1);
                }
            }
        }
        $('.cropit-preview-image', '#'+image.id).attr('src', '');
    }

    notifySuccessCreate(name) {
        this.notificationService.success({title: "Event saved", message: "New event " + name + " successfully created! You can now check it at organizer panel
Menu -> Events -> Organize", delay: 10000});
    }

    notifySuccessDraft(name) {
        this.notificationService.primary({title: "Draft saved", message: "New draft of event " + name + " successfully saved! You can find it at organizer panel
Menu -> Events -> Drafts", delay: 10000});
    }

    notifyNeedsLogin() {
        this.notificationService.warning({title: "Success, but you have to login first!", message: "You are almost done but to be sure that you are not a robot, login to your account please. Don't worry you will not loose your data!
You'll be redirected to the login page in a moment.", delay: 10000});
    }

	static directiveFactory(CategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
        EventForm.instance = new EventForm(CategoriesService, EventsService, UserService, Notification, VenuesService,  $stateParams, $rootScope, $state, $q);
        return EventForm.instance;
    }

}

EventForm.$inject = ['CategoriesService', 'EventsService', 'UserService', 'Notification', 'VenuesService', '$stateParams', '$rootScope', '$state', '$q'];

export default EventForm;<commit_msg>Directive fix<commit_after>
import Event from '../models/event.js';
import moment from 'moment';

const Q = new WeakMap();
const SERVICE = new WeakMap();

class EventForm {

	constructor(EventCategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
		Q.set(this, $q);
		SERVICE.set(this, EventsService);

		this.service = EventsService;
		this.vneuesService = VenuesService;
		this.categoriesService = EventCategoriesService;
		this.UserService = UserService;
		this.notificationService = Notification;
		this.params = $stateParams;
		this.rootScope = $rootScope;
		this.state = $state;

		this.restrict = 'EA';
        this.replace = true;
        this.templateUrl = 'templates/events/directives/form.html';
        this.scope = {
        };
	}

	submit(draft) {
		let event = this.model;
		let context = this;
		event.starts_at = moment(event.starts_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");
		event.ends_at = moment(event.ends_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");

		for (var i = 0; i < event.images.length; i++) {
            if (typeof event.images[i] === 'string') {
                continue;
            } else {
                let img = $('#'+event.images[i].id).cropit('export');
                if(!img) {
                    context.event.images.splice(i, 1);
                    continue;
                }
                event.images[i] = img;
            }
        }
        if(draft === true) {
            event.draft = draft;
        }

		if(!this.UserService.authenticated) {

            this.service.addUnsentEvent(event);
            this.notifyNeedsLogin();
            this.UserService.goLogin();
            return;
        }

        this.service.submit(event).then(function (response) {
            if(response.success === false) {
                context.errors = response.errors;
                window.scrollTo(0, 0);
            } else {
                console.log(response.event);
                if(draft) {
                    context.notifySuccessDraft(response.event.name);
                    context.state.go('venvast.events.drafts');
                } else {
                    context.notifySuccessCreate(response.event.name);
                    context.state.go('venvast.events.organize');
                }
            }
        });
		console.log(event);
	}

	link(scope, element) {
		let context = this;
		scope.createVenue = false;
		this.scope = scope;
		scope.submit = this.submit;

		scope.event = this.initModel();
		scope.addEntryOption = this.addEntryOption;
		scope.addEntryDesc = this.addEntryDesc;
		scope.deleteExistingImage = this.deleteExistingImage;
        scope.selectImage = this.selectImage;
        scope.deleteImage = this.deleteImage;
        scope.addImage = this.addImage;
        scope.getZoom = this.getZoom;
        scope.notificationService = this.notificationService;
        scope.notifyNeedsLogin = this.notifyNeedsLogin;
        scope.notifySuccessDraft = this.notifySuccessDraft;
        scope.notifySuccessCreate = this.notifySuccessCreate;
        scope.state = this.state;
        scope.UserService = this.UserService;
        scope.service = SERVICE.get(this);
	}

	addEntryOption () {
		this.model.entry_options.push({
			title: null,
			fee: 0,
			description: false
		});
	}

	addEntryDesc($index) {
		this.model.entry_options[$index].description = '';
	}

	initModel() {
        let context = this;
        if (this.params.slug) {
            this.initExistingModel();
        } else {
            this.initEmptyModel();
        }
        context.scope.dayAliases = [
            'Sun', 'Mon', 'Tue',
            'Wed', 'Thu', 'Fri',
            'Sat'
        ];
    }

	initExistingModel() {
        let context = this;
        SERVICE.get(this).gettingEditable(this.params.slug).then(function (response) {
            context.scope.model = response;
            let model = context.scope.model;
            if (response.venue) {
                $('#venue-search').val(response.venue.name);
                model.venue = model.venue.id;
            }
            context.categoriesService.gettingCategories().then((categories) => {
                context.initImageCropper(context.scope.model);
                context.addExistingImages(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
            });
        });
	}

	initEmptyModel () {
        let context = this;
        this.scope.model = {
            name: null,
            categories: [],
            starts_at: moment().add(6, 'h').format('YYYY.DD.MM H:mm'),
            ends_at: moment().add(9, 'h').format('YYYY.DD.MM H:mm'),
            description: null,
            venue: true,
            phone: null,
            email: null,
            website: null,
            free_entry: true,
            entry_options: [],
            locale: 'en',
            agree_conditions: false,
            images: []
        }
        context.categoriesService.gettingCategories().then((categories) => {
                context.initImageCropper(context.scope.model);
                context.addExistingImages(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
        });
    }

    initDateFrom () {
        let model = this.scope.model.starts_at;
        let end = this.scope.model.ends_at;
        $('#date_start').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            defaultSelect: false,
            onShow: function (ct) {
                // this.setOptions({
                //     maxDate: end ? end : false
                // });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initDateTo () {
        let model = this.scope.model.ends_at;
        let start = this.scope.model.starts_at;
        $('#date_end').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            startDate: model,
            maxDate: false,
            defaultSelect: false,
            onShow: function (ct) {
                this.setOptions({
                    minDate: start ? start : false
                });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initTypeAhed() {
    	let input = $('#venue-search');
    	let context = this;
    	console.log("INited typeahead for element: ", input);
    	$(input).typeahead({
            source: function(query, process) {
                context.vneuesService.typeAheadRequest('mode', query).then(function(data) {
                	console.log("Got data");
                    return process(data);
                });

            },
            select: function () {
                var val = this.$menu.find('.active').data('value');
                this.$element.data('active', val);
                if(this.autoSelect || val) {
                    var newVal = this.updater(val);

                    if (!newVal) {
                        newVal = "";
                    }

                    this.$element
                        .val(newVal.name)
                        .change();
                    this.afterSelect(newVal);
                }
                return this.hide();
            },
            afterSelect: function (element) {
                context.scope.model.venue = element.id;
            },
            displayText: function(item) {
                return '
' +
                '
' + item.name + '

' + item.category + '

'; //

            },
            highlighter: function(item) {
                return unescape(item);
            },
            minLength: 3,
            maxItem: 5,
            autoSelect: true
        });
    }

      addImage(model) {
        var finalWidth  = 900;
        var finalHeight = 300;
        let length = model.images.length;
        let image = {id: 'image-'+ length};
        let context = this;
        model.images.push(image);
        setTimeout(function(image) {
            $('#'+image.id).cropit({
                exportZoom: context.getZoom(finalHeight, finalWidth, '#'+image.id)
            });
        }, 1000, image);
    }

    initImageCropper(model) {
        if(model.images.length === 0) {
            this.addImage(model);
        }
    }

    addExistingImages (model) {
        this.scope.existingImages = model.images.slice();
    }

    deleteExistingImage (index) {
        this.scope.existingImages.splice(index, 1);
    }

    getZoom(finalHeight, finalWidth, selectContext) {
        let sizeRatio = finalHeight / finalWidth;
        let newWidth = $('.cropit-preview').width();
        let newHeight = newWidth * sizeRatio;
        return finalWidth / newWidth;
    }

    selectImage(image) {
        $('.cropit-image-input', '#'+image.id).click();
    }

    deleteImage(image) {
        if (this.model.images.length > 1) {
            for (var i = 0; i < this.model.images.length; i++) {
                let img = this.model.images[i];
                if(img.id === image.id) {
                    this.model.images.splice(i, 1);
                }
            }
        }
        $('.cropit-preview-image', '#'+image.id).attr('src', '');
    }

    notifySuccessCreate(name) {
        this.notificationService.success({title: "Event saved", message: "New event " + name + " successfully created! You can now check it at organizer panel
Menu -> Events -> Organize", delay: 10000});
    }

    notifySuccessDraft(name) {
        this.notificationService.primary({title: "Draft saved", message: "New draft of event " + name + " successfully saved! You can find it at organizer panel
Menu -> Events -> Drafts", delay: 10000});
    }

    notifyNeedsLogin() {
        this.notificationService.warning({title: "Success, but you have to login first!", message: "You are almost done but to be sure that you are not a robot, login to your account please. Don't worry you will not loose your data!
You'll be redirected to the login page in a moment.", delay: 10000});
    }

	static directiveFactory(CategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
        EventForm.instance = new EventForm(CategoriesService, EventsService, UserService, Notification, VenuesService,  $stateParams, $rootScope, $state, $q);
        return EventForm.instance;
    }

}

EventForm.$inject = ['CategoriesService', 'EventsService', 'UserService', 'Notification', 'VenuesService', '$stateParams', '$rootScope', '$state', '$q'];

export default EventForm;<|endoftext|>


<commit_before>/* jslint node: true, esnext: true */
"use strict";

const rgm = require('./RegistrarMixin');

/**
 * provide services and hold service configuration
 */

module.exports = (superclass) => class extends superclass {

	constructor() {
		super();
		rgm.defineRegistrarProperties(this, 'service');
	}

	/**
	 * adds a pre configured service
	 */
	addService(service) {
		this.services[service.name] = service;
		if (service.autostart) {
			service.start();
		}

		return service;
	}
};
<commit_msg>fix: add config arg to constructor<commit_after>/* jslint node: true, esnext: true */
"use strict";

const rgm = require('./RegistrarMixin');

/**
 * provide services and hold service configuration
 */

module.exports = (superclass) => class extends superclass {

	constructor(config) {
		super(config);
		rgm.defineRegistrarProperties(this, 'service');
	}

	/**
	 * adds a pre configured service
	 */
	addService(service) {
		this.services[service.name] = service;
		if (service.autostart) {
			service.start();
		}

		return service;
	}
};
<|endoftext|>


<commit_before>
import Event from '../models/event.js';
import moment from 'moment';

const Q = new WeakMap();
const SERVICE = new WeakMap();

class EventForm {

	constructor(EventCategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
		Q.set(this, $q);
		SERVICE.set(this, EventsService);

		this.service = EventsService;
		this.vneuesService = VenuesService;
		this.categoriesService = EventCategoriesService;
		this.UserService = UserService;
		this.notificationService = Notification;
		this.params = $stateParams;
		this.rootScope = $rootScope;
		this.state = $state;

		this.restrict = 'EA';
        this.replace = true;
        this.templateUrl = 'templates/events/directives/form.html';
        this.scope = {
        };
	}

	submit(draft) {
		let event = this.model;
        event.submitting = true;
		let context = this;
		event.starts_at = moment(event.starts_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");
		event.ends_at = moment(event.ends_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");

		for (var i = 0; i < event.images.length; i++) {
            if (typeof event.images[i] === 'string') {
                continue;
            } else {
                let img = $('#'+event.images[i].id).slice();
                img = img.cropit('export');
                if(!img) {
                    event.images.splice(i, 1);
                    continue;
                }
                event.images[i] = img;
            }
        }
        if(this.existingImages && this.existingImages.length > 0) {
            for (var i = 0; i < this.existingImages.length; i++) {
                event.images.push(this.existingImages[i]);
            }
        }

        if(draft === true) {
            event.draft = draft;
        }

		if(!this.UserService.authenticated) {

            this.service.addUnsentEvent(event);
            this.notifyNeedsLogin();
            this.UserService.goLogin();
            return;
        }

        this.service.submit(event).then(function (response) {
            event.submitting = false;
            if(response.success === false) {
                context.errors = response.errors;
                window.scrollTo(0, 0);
            } else {
                if(draft === true) {
                    context.notifySuccessDraft(response.event.name);
                    context.state.go('venvast.events.drafts');
                } else {
                    context.notifySuccessCreate(response.event.name);
                    context.state.go('venvast.events.organize');
                }
            }
        });
		console.log(event);
	}

	link(scope, element) {
		let context = this;
		scope.createVenue = false;
		this.scope = scope;
		scope.submit = this.submit;

		scope.event = this.initModel();
		scope.addEntryOption = this.addEntryOption;
		scope.addEntryDesc = this.addEntryDesc;
		scope.deleteExistingImage = this.deleteExistingImage;
        scope.selectImage = this.selectImage;
        scope.deleteImage = this.deleteImage;
        scope.addImage = this.addImage;
        scope.getZoom = this.getZoom;
        scope.notificationService = this.notificationService;
        scope.notifyNeedsLogin = this.notifyNeedsLogin;
        scope.notifySuccessDraft = this.notifySuccessDraft;
        scope.notifySuccessCreate = this.notifySuccessCreate;
        scope.state = this.state;
        scope.UserService = this.UserService;
        scope.service = SERVICE.get(this);
	}

	addEntryOption () {
		this.model.entry_options.push({
			title: null,
			fee: 0,
			description: false
		});
	}

	addEntryDesc($index) {
		this.model.entry_options[$index].description = '';
	}

	initModel() {
        let context = this;
        if (this.params.slug) {
            this.initExistingModel();
        } else {
            this.initEmptyModel();
        }
        context.scope.dayAliases = [
            'Sun', 'Mon', 'Tue',
            'Wed', 'Thu', 'Fri',
            'Sat'
        ];
    }

	initExistingModel() {
        let context = this;
        SERVICE.get(this).gettingEditable(this.params.slug).then(function (response) {
            context.scope.model = response;
            let model = context.scope.model;
            model.submitting = false;
            if (response.venue) {
                $('#venue-search').val(response.venue.name);
                model.venue = model.venue.id;
            }
            context.categoriesService.gettingCategories().then((categories) => {
                context.addExistingImages(context.scope.model);
                context.initImageCropper(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
                context.initTypeAhed()
            });
        });
	}

	initEmptyModel () {
        let context = this;
        this.scope.model = {
            name: null,
            categories: [],
            starts_at: moment().add(6, 'h').format('YYYY.DD.MM H:mm'),
            ends_at: moment().add(9, 'h').format('YYYY.DD.MM H:mm'),
            description: null,
            venue: true,
            phone: null,
            email: null,
            submitting: false,
            website: null,
            free_entry: true,
            entry_options: [],
            locale: 'en',
            agree_conditions: false,
            images: []
        }
        context.categoriesService.gettingCategories().then((categories) => {
                context.addExistingImages(context.scope.model);
                context.initImageCropper(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
                context.initTypeAhed();
        });
    }

    initDateFrom () {
        let model = this.scope.model.starts_at;
        let end = this.scope.model.ends_at;
        $('#date_start').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            defaultSelect: false,
            onShow: function (ct) {
                // this.setOptions({
                //     maxDate: end ? end : false
                // });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initDateTo () {
        let model = this.scope.model.ends_at;
        let start = this.scope.model.starts_at;
        $('#date_end').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            startDate: model,
            maxDate: false,
            defaultSelect: false,
            onShow: function (ct) {
                this.setOptions({
                    minDate: start ? start : false
                });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initTypeAhed() {
    	let input = $('#venue-search');
    	let context = this;
    	console.log("INited typeahead for element: ", input);
    	$(input).typeahead({
            source: function(query, process) {
                context.vneuesService.typeAheadRequest('mode', query).then(function(data) {
                	console.log("Got data");
                    return process(data);
                });

            },
            select: function () {
                var val = this.$menu.find('.active').data('value');
                this.$element.data('active', val);
                if(this.autoSelect || val) {
                    var newVal = this.updater(val);

                    if (!newVal) {
                        newVal = "";
                    }

                    this.$element
                        .val(newVal.name)
                        .change();
                    this.afterSelect(newVal);
                }
                return this.hide();
            },
            afterSelect: function (element) {
                context.scope.model.venue = element.id;
            },
            displayText: function(item) {
                return '
' +
                '
' + item.name + '

' + item.category + '

'; //

            },
            highlighter: function(item) {
                return unescape(item);
            },
            minLength: 3,
            maxItem: 5,
            autoSelect: true
        });
    }

      addImage(model) {
        var finalWidth  = 900;
        var finalHeight = 300;
        let length = model.images.length;
        let image = {id: 'image-'+ length};
        let context = this;
        model.images.push(image);
        setTimeout(function(image) {
            $('#'+image.id).cropit({
                exportZoom: context.getZoom(finalHeight, finalWidth, '#'+image.id)
            });
        }, 1000, image);
    }

    initImageCropper(model) {
        if(model.images.length === 0) {
            this.addImage(model);
        }
    }

    addExistingImages (model) {
        this.scope.existingImages = model.images.slice();
        model.images = [];
    }

    deleteExistingImage (index) {
        this.$parent.existingImages.splice(index, 1);
    }

    getZoom(finalHeight, finalWidth, selectContext) {
        let sizeRatio = finalHeight / finalWidth;
        let newWidth = $('.cropit-preview').width();
        let newHeight = newWidth * sizeRatio;
        return finalWidth / newWidth;
    }

    selectImage(image) {
        $('.cropit-image-input', '#'+image.id).click();
    }

    deleteImage(image) {
        if (this.model.images.length > 1) {
            for (var i = 0; i < this.model.images.length; i++) {
                let img = this.model.images[i];
                if(img.id === image.id) {
                    this.model.images.splice(i, 1);
                }
            }
        }
        $('.cropit-preview-image', '#'+image.id).attr('src', '');
    }

    notifySuccessCreate(name) {
        this.notificationService.success({title: "Event saved", message: "New event " + name + " successfully created! You can now check it at organizer panel
Menu -> Events -> Organize", delay: 10000});
    }

    notifySuccessDraft(name) {
        this.notificationService.primary({title: "Draft saved", message: "New draft of event " + name + " successfully saved! You can find it at organizer panel
Menu -> Events -> Drafts", delay: 10000});
    }

    notifyNeedsLogin() {
        this.notificationService.warning({title: "Success, but you have to login first!", message: "You are almost done but to be sure that you are not a robot, login to your account please. Don't worry you will not loose your data!
You'll be redirected to the login page in a moment.", delay: 10000});
    }

	static directiveFactory(CategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
        EventForm.instance = new EventForm(CategoriesService, EventsService, UserService, Notification, VenuesService,  $stateParams, $rootScope, $state, $q);
        return EventForm.instance;
    }

}

EventForm.$inject = ['CategoriesService', 'EventsService', 'UserService', 'Notification', 'VenuesService', '$stateParams', '$rootScope', '$state', '$q'];

export default EventForm;<commit_msg>Try to fix event post update<commit_after>
import Event from '../models/event.js';
import moment from 'moment';
import angular from 'angular';

const Q = new WeakMap();
const SERVICE = new WeakMap();

class EventForm {

	constructor(EventCategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
		Q.set(this, $q);
		SERVICE.set(this, EventsService);

		this.service = EventsService;
		this.vneuesService = VenuesService;
		this.categoriesService = EventCategoriesService;
		this.UserService = UserService;
		this.notificationService = Notification;
		this.params = $stateParams;
		this.rootScope = $rootScope;
		this.state = $state;

		this.restrict = 'EA';
        this.replace = true;
        this.templateUrl = 'templates/events/directives/form.html';
        this.scope = {
        };
	}

	submit(draft) {
        let event = {};
		angular.copy(this.model, event);
        event.submitting = true;
		let context = this;
		event.starts_at = moment(event.starts_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");
		event.ends_at = moment(event.ends_at, "YYYY.DD.MM H:mm").format("DD.MM.YYYY H:mm");

		for (var i = 0; i < event.images.length; i++) {
            if (typeof event.images[i] === 'string') {
                continue;
            } else {
                let img = $('#'+event.images[i].id).slice();
                img = img.cropit('export');
                if(!img) {
                    event.images.splice(i, 1);
                    continue;
                }
                event.images[i] = img;
            }
        }
        if(this.existingImages && this.existingImages.length > 0) {
            for (var i = 0; i < this.existingImages.length; i++) {
                event.images.push(this.existingImages[i]);
            }
        }

        if(draft === true) {
            event.draft = draft;
        }

		if(!this.UserService.authenticated) {

            this.service.addUnsentEvent(event);
            this.notifyNeedsLogin();
            this.UserService.goLogin();
            return;
        }

        this.service.submit(event).then(function (response) {
            event.submitting = false;
            if(response.success === false) {
                context.errors = response.errors;
                window.scrollTo(0, 0);
            } else {
                if(draft === true) {
                    context.notifySuccessDraft(response.event.name);
                    context.state.go('venvast.events.drafts');
                } else {
                    context.notifySuccessCreate(response.event.name);
                    context.state.go('venvast.events.organize');
                }
            }
        });
		console.log(event);
	}

	link(scope, element) {
		let context = this;
		scope.createVenue = false;
		this.scope = scope;
		scope.submit = this.submit;

		scope.event = this.initModel();
		scope.addEntryOption = this.addEntryOption;
		scope.addEntryDesc = this.addEntryDesc;
		scope.deleteExistingImage = this.deleteExistingImage;
        scope.selectImage = this.selectImage;
        scope.deleteImage = this.deleteImage;
        scope.addImage = this.addImage;
        scope.getZoom = this.getZoom;
        scope.notificationService = this.notificationService;
        scope.notifyNeedsLogin = this.notifyNeedsLogin;
        scope.notifySuccessDraft = this.notifySuccessDraft;
        scope.notifySuccessCreate = this.notifySuccessCreate;
        scope.state = this.state;
        scope.UserService = this.UserService;
        scope.service = SERVICE.get(this);
	}

	addEntryOption () {
		this.model.entry_options.push({
			title: null,
			fee: 0,
			description: false
		});
	}

	addEntryDesc($index) {
		this.model.entry_options[$index].description = '';
	}

	initModel() {
        let context = this;
        if (this.params.slug) {
            this.initExistingModel();
        } else {
            this.initEmptyModel();
        }
        context.scope.dayAliases = [
            'Sun', 'Mon', 'Tue',
            'Wed', 'Thu', 'Fri',
            'Sat'
        ];
    }

	initExistingModel() {
        let context = this;
        SERVICE.get(this).gettingEditable(this.params.slug).then(function (response) {
            context.scope.model = response;
            let model = context.scope.model;
            model.submitting = false;
            if (response.venue) {
                $('#venue-search').val(response.venue.name);
                model.venue = model.venue.id;
            }
            context.categoriesService.gettingCategories().then((categories) => {
                context.addExistingImages(context.scope.model);
                context.initImageCropper(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
                context.initTypeAhed()
            });
        });
	}

	initEmptyModel () {
        let context = this;
        this.scope.model = {
            name: null,
            categories: [],
            starts_at: moment().add(6, 'h').format('YYYY.DD.MM H:mm'),
            ends_at: moment().add(9, 'h').format('YYYY.DD.MM H:mm'),
            description: null,
            venue: true,
            phone: null,
            email: null,
            submitting: false,
            website: null,
            free_entry: true,
            entry_options: [],
            locale: 'en',
            agree_conditions: false,
            images: []
        }
        context.categoriesService.gettingCategories().then((categories) => {
                context.addExistingImages(context.scope.model);
                context.initImageCropper(context.scope.model);
                context.initDateFrom();
                context.initDateTo();
                context.scope.categories = categories;
                context.initTypeAhed();
        });
    }

    initDateFrom () {
        let model = this.scope.model.starts_at;
        let end = this.scope.model.ends_at;
        $('#date_start').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            defaultSelect: false,
            onShow: function (ct) {
                // this.setOptions({
                //     maxDate: end ? end : false
                // });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initDateTo () {
        let model = this.scope.model.ends_at;
        let start = this.scope.model.starts_at;
        $('#date_end').datetimepicker({
            timepicker: true,
            format: "Y.d.m H:i",
            value: model,
            minDate: moment().toDate(),
            startDate: model,
            maxDate: false,
            defaultSelect: false,
            onShow: function (ct) {
                this.setOptions({
                    minDate: start ? start : false
                });
            },
            onSelectDate: function(ct) {
                model = moment(ct).format('YYYY.DD.MM H:mm');
            }
        });
    }

    initTypeAhed() {
    	let input = $('#venue-search');
    	let context = this;
    	console.log("INited typeahead for element: ", input);
    	$(input).typeahead({
            source: function(query, process) {
                context.vneuesService.typeAheadRequest('mode', query).then(function(data) {
                	console.log("Got data");
                    return process(data);
                });

            },
            select: function () {
                var val = this.$menu.find('.active').data('value');
                this.$element.data('active', val);
                if(this.autoSelect || val) {
                    var newVal = this.updater(val);

                    if (!newVal) {
                        newVal = "";
                    }

                    this.$element
                        .val(newVal.name)
                        .change();
                    this.afterSelect(newVal);
                }
                return this.hide();
            },
            afterSelect: function (element) {
                context.scope.model.venue = element.id;
            },
            displayText: function(item) {
                return '
' +
                '
' + item.name + '

' + item.category + '

'; //

            },
            highlighter: function(item) {
                return unescape(item);
            },
            minLength: 3,
            maxItem: 5,
            autoSelect: true
        });
    }

      addImage(model) {
        var finalWidth  = 900;
        var finalHeight = 300;
        let length = model.images.length;
        let image = {id: 'image-'+ length};
        let context = this;
        model.images.push(image);
        setTimeout(function(image) {
            $('#'+image.id).cropit({
                exportZoom: context.getZoom(finalHeight, finalWidth, '#'+image.id)
            });
        }, 1000, image);
    }

    initImageCropper(model) {
        if(model.images.length === 0) {
            this.addImage(model);
        }
    }

    addExistingImages (model) {
        this.scope.existingImages = model.images.slice();
        model.images = [];
    }

    deleteExistingImage (index) {
        this.$parent.existingImages.splice(index, 1);
    }

    getZoom(finalHeight, finalWidth, selectContext) {
        let sizeRatio = finalHeight / finalWidth;
        let newWidth = $('.cropit-preview').width();
        let newHeight = newWidth * sizeRatio;
        return finalWidth / newWidth;
    }

    selectImage(image) {
        $('.cropit-image-input', '#'+image.id).click();
    }

    deleteImage(image) {
        if (this.model.images.length > 1) {
            for (var i = 0; i < this.model.images.length; i++) {
                let img = this.model.images[i];
                if(img.id === image.id) {
                    this.model.images.splice(i, 1);
                }
            }
        }
        $('.cropit-preview-image', '#'+image.id).attr('src', '');
    }

    notifySuccessCreate(name) {
        this.notificationService.success({title: "Event saved", message: "New event " + name + " successfully created! You can now check it at organizer panel
Menu -> Events -> Organize", delay: 10000});
    }

    notifySuccessDraft(name) {
        this.notificationService.primary({title: "Draft saved", message: "New draft of event " + name + " successfully saved! You can find it at organizer panel
Menu -> Events -> Drafts", delay: 10000});
    }

    notifyNeedsLogin() {
        this.notificationService.warning({title: "Success, but you have to login first!", message: "You are almost done but to be sure that you are not a robot, login to your account please. Don't worry you will not loose your data!
You'll be redirected to the login page in a moment.", delay: 10000});
    }

	static directiveFactory(CategoriesService, EventsService, UserService, Notification, VenuesService, $stateParams, $rootScope, $state, $q) {
        EventForm.instance = new EventForm(CategoriesService, EventsService, UserService, Notification, VenuesService,  $stateParams, $rootScope, $state, $q);
        return EventForm.instance;
    }

}

EventForm.$inject = ['CategoriesService', 'EventsService', 'UserService', 'Notification', 'VenuesService', '$stateParams', '$rootScope', '$state', '$q'];

export default EventForm;<|endoftext|>


<commit_before>'use strict';

const lo_isNumber = require('lodash.isnumber');
const lo_isString = require('lodash.isstring');
const lo_isObject = require('lodash.isobject');
const lo_has = require('lodash.has');

const math = require('mathjs');

module.exports = (context) => {
  const app = context.app;
  const clipboard = context.clipboard;
  const toast = context.toast;
  const indexer = context.indexer;

  function startup() {
    indexer.set('math', (query) => {
      const answer = calculate(query);
      if (!answer)
        return;
      return makeResultItem('primaryText', query, answer);
    });
  }

  function search(query, res) {
    const answer = calculate(query);
    if (!answer)
      return;
    res.add(makeResultItem('title', query, answer));
  }

  function makeResultItem(titleKey, query, answer) {
    const result = {};
    result[titleKey] = `${query.trim()} = ${answer}`;
    result.group = 'Math';
    result.payload = answer;
    return result;
  }

  function calculate(query) {
    try {
      const ans = math.eval(query);
      if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
        const ansString = ans.toString();
        if (ansString.trim() !== query.trim())
          return ansString;
      }
    } catch (e) { }
  }

  function execute(id, payload) {
    app.setQuery(`=${payload}`);
    clipboard.writeText(payload);
    toast.enqueue(`${payload} has copied into clipboard`);
  }

  return { startup, search, execute };
};
<commit_msg>hain-plugin-math: Change to print meaningless results with strict '=' prefix<commit_after>'use strict';

const lo_isNumber = require('lodash.isnumber');
const lo_isString = require('lodash.isstring');
const lo_isObject = require('lodash.isobject');
const lo_has = require('lodash.has');

const math = require('mathjs');

module.exports = (context) => {
  const app = context.app;
  const clipboard = context.clipboard;
  const toast = context.toast;
  const indexer = context.indexer;

  function startup() {
    indexer.set('math', (query) => {
      const answer = calculate(query, false);
      if (!answer)
        return;
      return makeResultItem('primaryText', query, answer);
    });
  }

  function search(query, res) {
    const answer = calculate(query, true);
    if (!answer)
      return;
    res.add(makeResultItem('title', query, answer));
  }

  function makeResultItem(titleKey, query, answer) {
    const result = {};
    result[titleKey] = `${query.trim()} = ${answer}`;
    result.group = 'Math';
    result.payload = answer;
    return result;
  }

  function calculate(query, showRedundantResult) {
    try {
      const ans = math.eval(query);
      if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
        const ansString = ans.toString();
        const isResultMeaningful = (ansString.trim() !== query.trim());
        if (isResultMeaningful || showRedundantResult)
          return ansString;
      }
    } catch (e) { }
  }

  function execute(id, payload) {
    app.setQuery(`=${payload}`);
    clipboard.writeText(payload);
    toast.enqueue(`${payload} has copied into clipboard`);
  }

  return { startup, search, execute };
};
<|endoftext|>


<commit_before>define(
  'ephox.alloy.events.GuiEvents',

  [
    'ephox.alloy.alien.Keys',
    'ephox.alloy.api.events.SystemEvents',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.katamari.api.Arr',
    'ephox.sand.api.PlatformDetection',
    'ephox.sugar.api.events.DomEvent',
    'ephox.sugar.api.node.Node',
    'ephox.sugar.api.search.Traverse',
    'global!setTimeout'
  ],

  function (Keys, SystemEvents, FieldSchema, ValueSchema, Arr, PlatformDetection, DomEvent, Node, Traverse, setTimeout) {
    var isDangerous = function (event) {
      // Will trigger the Back button in the browser
      return event.raw().which === Keys.BACKSPACE()[0] && !Arr.contains([ 'input', 'textarea' ], Node.name(event.target()));
    };

    var isFirefox = PlatformDetection.detect().browser.isFirefox();

    var settingsSchema = ValueSchema.objOfOnly([
      // triggerEvent(eventName, event)
      FieldSchema.strictFunction('triggerEvent'),
      FieldSchema.strictFunction('broadcastEvent'),
      FieldSchema.defaulted('stopBackspace', true)
    ]);

    var bindFocus = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'focus', handler);
      } else {
        return DomEvent.bind(container, 'focusin', handler);
      }
    };

    var bindBlur = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'blur', handler);
      } else {
        return DomEvent.bind(container, 'focusout', handler);
      }
    };

    var setup = function (container, rawSettings) {
      var settings = ValueSchema.asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);

      // These events are just passed through ... no additional processing
      var simpleEvents = Arr.map([
        'click',
        'selectstart',
        'mousedown',
        'mouseup',
        'mouseover',
        'mousemove',
        'mouseout',
        'focusin',
        'input',
        'contextmenu',
        'change',
        'transitionend',
        // Test the drag events
        'dragstart',
        'dragover',
        'drop',

        'touchstart',
        'touchend',
        'touchmove',
        'gesturestart'
      ], function (type) {
        return DomEvent.bind(container, type, function (event) {
          var stopped = settings.triggerEvent(type, event);
          if (stopped) event.kill();
        });
      });

      var onKeydown = DomEvent.bind(container, 'keydown', function (event) {
        // Prevent default of backspace when not in input fields.
        var stopped = settings.triggerEvent('keydown', event);
        if (stopped) event.kill();
        else if (settings.stopBackspace === true && isDangerous(event)) { event.prevent(); }
      });

      var onFocusOut = bindBlur(container, function (event) {
        var stopped = settings.triggerEvent('focusout', event);
        if (stopped) event.kill();

        // INVESTIGATE: Come up with a better way of doing this. Related target can be used, but not on FF.
        // It allows the active element to change before firing the blur that we will listen to
        // for things like closing popups
        setTimeout(function () {
          settings.triggerEvent(SystemEvents.postBlur(), event);
        }, 0);
      });

      var defaultView = Traverse.defaultView(container);
      var onWindowScroll = DomEvent.bind(defaultView, 'scroll', function (event) {
        var stopped = settings.broadcastEvent(SystemEvents.windowScroll(), event);
        if (stopped) event.kill();
      });

      var unbind = function () {
        Arr.each(simpleEvents, function (e) {
          e.unbind();
        });
        onKeydown.unbind();
        onFocusOut.unbind();
        onWindowScroll.unbind();
      };

      return {
        unbind: unbind
      };
    };

    return {
      setup: setup
    };
  }
);<commit_msg>TM-38: dispatching events specific to device<commit_after>define(
  'ephox.alloy.events.GuiEvents',

  [
    'ephox.alloy.alien.Keys',
    'ephox.alloy.api.events.SystemEvents',
    'ephox.boulder.api.FieldSchema',
    'ephox.boulder.api.ValueSchema',
    'ephox.katamari.api.Arr',
    'ephox.sand.api.PlatformDetection',
    'ephox.sugar.api.events.DomEvent',
    'ephox.sugar.api.node.Node',
    'ephox.sugar.api.search.Traverse',
    'global!setTimeout'
  ],

  function (Keys, SystemEvents, FieldSchema, ValueSchema, Arr, PlatformDetection, DomEvent, Node, Traverse, setTimeout) {
    var isDangerous = function (event) {
      // Will trigger the Back button in the browser
      return event.raw().which === Keys.BACKSPACE()[0] && !Arr.contains([ 'input', 'textarea' ], Node.name(event.target()));
    };

    var isFirefox = PlatformDetection.detect().browser.isFirefox();

    var settingsSchema = ValueSchema.objOfOnly([
      // triggerEvent(eventName, event)
      FieldSchema.strictFunction('triggerEvent'),
      FieldSchema.strictFunction('broadcastEvent'),
      FieldSchema.defaulted('stopBackspace', true)
    ]);

    var bindFocus = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'focus', handler);
      } else {
        return DomEvent.bind(container, 'focusin', handler);
      }
    };

    var bindBlur = function (container, handler) {
      if (isFirefox) {
        // https://bugzilla.mozilla.org/show_bug.cgi?id=687787
        return DomEvent.capture(container, 'blur', handler);
      } else {
        return DomEvent.bind(container, 'focusout', handler);
      }
    };

    var setup = function (container, rawSettings) {
      var settings = ValueSchema.asRawOrDie('Getting GUI events settings', settingsSchema, rawSettings);

      var pointerEvents = PlatformDetection.detect().deviceType.isTouch() ? [
        'touchstart',
        'touchmove',
        'touchend',
        'gesturestart'
      ] : [
        'mousedown',
        'mouseup',
        'mouseover',
        'mousemove',
        'mouseout',
        'click'
      ];

      // These events are just passed through ... no additional processing
      var simpleEvents = Arr.map(
        pointerEvents.concat([
          'selectstart',
          'focusin',
          'input',
          'contextmenu',
          'change',
          'transitionend',
          // Test the drag events
          'dragstart',
          'dragover',
          'drop'
        ]),
        function (type) {
          return DomEvent.bind(container, type, function (event) {
            var stopped = settings.triggerEvent(type, event);
            if (stopped) event.kill();
          });
        }
      );

      var onKeydown = DomEvent.bind(container, 'keydown', function (event) {
        // Prevent default of backspace when not in input fields.
        var stopped = settings.triggerEvent('keydown', event);
        if (stopped) event.kill();
        else if (settings.stopBackspace === true && isDangerous(event)) { event.prevent(); }
      });

      var onFocusOut = bindBlur(container, function (event) {
        var stopped = settings.triggerEvent('focusout', event);
        if (stopped) event.kill();

        // INVESTIGATE: Come up with a better way of doing this. Related target can be used, but not on FF.
        // It allows the active element to change before firing the blur that we will listen to
        // for things like closing popups
        setTimeout(function () {
          settings.triggerEvent(SystemEvents.postBlur(), event);
        }, 0);
      });

      var defaultView = Traverse.defaultView(container);
      var onWindowScroll = DomEvent.bind(defaultView, 'scroll', function (event) {
        var stopped = settings.broadcastEvent(SystemEvents.windowScroll(), event);
        if (stopped) event.kill();
      });

      var unbind = function () {
        Arr.each(simpleEvents, function (e) {
          e.unbind();
        });
        onKeydown.unbind();
        onFocusOut.unbind();
        onWindowScroll.unbind();
      };

      return {
        unbind: unbind
      };
    };

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


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var Mirror = require("../worker/mirror").Mirror;
var parse = require("./json/json_parse");

var JsonWorker = exports.JsonWorker = function(sender) {
    Mirror.call(this, sender);
    this.setTimeout(200);
};

oop.inherits(JsonWorker, Mirror);

(function() {

    this.onUpdate = function() {
        var value = this.doc.getValue();

        try {
            var result = parse(value);
        } catch (e) {
            var pos = this.doc.indexToPosition(e.at-1);
            this.sender.emit("error", {
                row: pos.row,
                column: pos.column,
                text: e.message,
                type: "error"
            });
            return;
        }
        this.sender.emit("ok");
    };

}).call(JsonWorker.prototype);

});
<commit_msg>do not show error for empty json files<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var Mirror = require("../worker/mirror").Mirror;
var parse = require("./json/json_parse");

var JsonWorker = exports.JsonWorker = function(sender) {
    Mirror.call(this, sender);
    this.setTimeout(200);
};

oop.inherits(JsonWorker, Mirror);

(function() {

    this.onUpdate = function() {
        var value = this.doc.getValue();

        try {
            if (value)
                parse(value);
        } catch (e) {
            var pos = this.doc.indexToPosition(e.at-1);
            this.sender.emit("error", {
                row: pos.row,
                column: pos.column,
                text: e.message,
                type: "error"
            });
            return;
        }
        this.sender.emit("ok");
    };

}).call(JsonWorker.prototype);

});
<|endoftext|>


<commit_before>(function (window, angular) {
  'use strict';

  /**
   * @ngdoc overview
   * @name angulartics.intercom
   * Enables analytics support for Intercom (http://intercom.io)
   */
  angular
    .module('angulartics.intercom', ['angulartics'])
    .directive('analyticsIntercom', ['$analytics', function ($analytics) {
      return {
        restrict: 'A',
        priority: 100,
        link: function (scope, el, attr) {
          if ($analytics.settings.intercomRequiresAttribute) {
            var props = scope.$eval(attr.analyticsProperties) || {};

            props.intercomEnabled = true;
            attr.analyticsProperties = JSON.stringify(props);
          }
        }
      };
    }])
    .config(['$analyticsProvider', function ($analyticsProvider) {
      $analyticsProvider.registerPageTrack(function (path) {
        if (!window.Intercom) {
          return;
        }

        if (!$analyticsProvider.settings.intercomRequiresAttribute) {
          window.Intercom('trackEvent', 'visit_page', {
            url: path
          });
        }
      });

      /**
       * Track Event in GA
       * @name eventTrack
       *
       * @param {string} action Required 'action' (string) associated with the event
       * @param {object} properties Comprised of the mandatory field 'category' (string) and optional  fields 'label' (string), 'value' (integer) and 'noninteraction' (boolean)
       *
       * Sends events like 'click_users_search_users'
       */
      $analyticsProvider.registerEventTrack(function (action, properties) {
        if (!window.Intercom) {
          return;
        } else if ($analyticsProvider.settings.intercomRequiresAttribute && !properties.intercomEnabled) {
          return;
        }

        var eventFormat = $analyticsProvider.settings.eventFormat || {
          eventType: false,
          category: false,
          label: false
        };

        properties = properties || {};

        var tokens = [ action ];

        if (properties.eventType && eventFormat.eventType) {
          tokens.unshift(properties.eventType);
        }

        if (properties.category && eventFormat.category) {
          tokens.push(properties.category);
        }

        if (properties.label && eventFormat.label) {
          tokens.push(properties.label);
        }

        delete properties.eventType;
        delete properties.category;
        delete properties.label;
        delete properties.intercom;
        delete properties.intercomEnabled;

        if (JSON.stringify(properties) === '{}') {
          properties = undefined;
        }

        window.Intercom('trackEvent', tokens.join(' ').toLowerCase(), properties);
      });

      /**
       * Set Username
       * @name setUsername
       *
       * @param {string} userId Registers User ID of user for use with other hits
       */
      $analyticsProvider.registerSetUsername(function (userId) {
        if (window.Intercom) {
          window.Intercom('update', { user_id: userId });
        }
      });
    }]);
})(window, window.angular);
<commit_msg>Default properties earlier so it doesn't npe.<commit_after>(function (window, angular) {
  'use strict';

  /**
   * @ngdoc overview
   * @name angulartics.intercom
   * Enables analytics support for Intercom (http://intercom.io)
   */
  angular
    .module('angulartics.intercom', ['angulartics'])
    .directive('analyticsIntercom', ['$analytics', function ($analytics) {
      return {
        restrict: 'A',
        priority: 100,
        link: function (scope, el, attr) {
          if ($analytics.settings.intercomRequiresAttribute) {
            var props = scope.$eval(attr.analyticsProperties) || {};

            props.intercomEnabled = true;
            attr.analyticsProperties = JSON.stringify(props);
          }
        }
      };
    }])
    .config(['$analyticsProvider', function ($analyticsProvider) {
      $analyticsProvider.registerPageTrack(function (path) {
        if (!window.Intercom) {
          return;
        }

        if (!$analyticsProvider.settings.intercomRequiresAttribute) {
          window.Intercom('trackEvent', 'visit_page', {
            url: path
          });
        }
      });

      /**
       * Track Event in GA
       * @name eventTrack
       *
       * @param {string} action Required 'action' (string) associated with the event
       * @param {object} properties Comprised of the mandatory field 'category' (string) and optional  fields 'label' (string), 'value' (integer) and 'noninteraction' (boolean)
       *
       * Sends events like 'click_users_search_users'
       */
      $analyticsProvider.registerEventTrack(function (action, properties) {
        properties = properties || {};

        if (!window.Intercom) {
          return;
        } else if ($analyticsProvider.settings.intercomRequiresAttribute && !properties.intercomEnabled) {
          return;
        }

        var eventFormat = $analyticsProvider.settings.eventFormat || {
          eventType: false,
          category: false,
          label: false
        };

        var tokens = [ action ];

        if (properties.eventType && eventFormat.eventType) {
          tokens.unshift(properties.eventType);
        }

        if (properties.category && eventFormat.category) {
          tokens.push(properties.category);
        }

        if (properties.label && eventFormat.label) {
          tokens.push(properties.label);
        }

        delete properties.eventType;
        delete properties.category;
        delete properties.label;
        delete properties.intercom;
        delete properties.intercomEnabled;

        if (JSON.stringify(properties) === '{}') {
          properties = undefined;
        }

        window.Intercom('trackEvent', tokens.join(' ').toLowerCase(), properties);
      });

      /**
       * Set Username
       * @name setUsername
       *
       * @param {string} userId Registers User ID of user for use with other hits
       */
      $analyticsProvider.registerSetUsername(function (userId) {
        if (window.Intercom) {
          window.Intercom('update', { user_id: userId });
        }
      });
    }]);
})(window, window.angular);
<|endoftext|>


<commit_before>(function(window, angular, undefined) {'use strict';

/**
 * @ngdoc overview
 * @name angulartics.mixpanel
 * Enables analytics support for Mixpanel (http://mixpanel.com)
 */
angular.module('angulartics.mixpanel', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {

  angulartics.waitForVendorApi('mixpanel', 500, '__loaded', function (mixpanel) {
    $analyticsProvider.registerSetUsername(function (userId) {
      mixpanel.identify(userId);
    });
    $analyticsProvider.registerSetAlias(function (userId) {
      mixpanel.alias(userId);
    });
    $analyticsProvider.registerSetSuperPropertiesOnce(function (properties) {
      mixpanel.register_once(properties);
    });
    $analyticsProvider.registerSetSuperProperties(function (properties) {
      mixpanel.register(properties);
    });
    $analyticsProvider.registerSetUserPropertiesOnce(function (properties) {
      mixpanel.people.set_once(properties);
    });
    $analyticsProvider.registerSetUserProperties(function (properties) {
      mixpanel.people.set(properties);
    });
    $analyticsProvider.registerPageTrack(function (path) {
      mixpanel.track( "Page Viewed", { "page": path } );
    });
    $analyticsProvider.registerEventTrack(function (action, properties) {
      mixpanel.track(action, properties);
    });
    $analyticsProvider.registerTimeEvent(function (action) {
      mixpanel.time_event(action);
    });
  });

}]);

})(window, window.angular);
<commit_msg>changed to user timing like in angulartics repo<commit_after>(function(window, angular, undefined) {'use strict';

/**
 * @ngdoc overview
 * @name angulartics.mixpanel
 * Enables analytics support for Mixpanel (http://mixpanel.com)
 */
angular.module('angulartics.mixpanel', ['angulartics'])
.config(['$analyticsProvider', function ($analyticsProvider) {

  angulartics.waitForVendorApi('mixpanel', 500, '__loaded', function (mixpanel) {
    $analyticsProvider.registerSetUsername(function (userId) {
      mixpanel.identify(userId);
    });
    $analyticsProvider.registerSetAlias(function (userId) {
      mixpanel.alias(userId);
    });
    $analyticsProvider.registerSetSuperPropertiesOnce(function (properties) {
      mixpanel.register_once(properties);
    });
    $analyticsProvider.registerSetSuperProperties(function (properties) {
      mixpanel.register(properties);
    });
    $analyticsProvider.registerSetUserPropertiesOnce(function (properties) {
      mixpanel.people.set_once(properties);
    });
    $analyticsProvider.registerSetUserProperties(function (properties) {
      mixpanel.people.set(properties);
    });
    $analyticsProvider.registerPageTrack(function (path) {
      mixpanel.track( "Page Viewed", { "page": path } );
    });
    $analyticsProvider.registerEventTrack(function (action, properties) {
      mixpanel.track(action, properties);
    });
    $analyticsProvider.registerUserTimings(function (action) {
      mixpanel.time_event(action);
    });
  });

}]);

})(window, window.angular);
<|endoftext|>


<commit_before>'use strict';

const ParserInterface = require('../parser-interface');
const meow = require('meow')

class ArgumentParser extends ParserInterface {
  parse () {
    const options = {
      alias: {
        c: 'cluster',
        p: 'port',
        v: 'version'
      },
      boolean: [ // options that are always boolean
        'cluster'
      ],
      default: {
        cluster: false,
        port: 3000
      }
    }
    const help = `
      Usage:
        $ npm start [-- <options>]

      Options:
        -c, --cluster Enable cluster mode (default: disable)
        -p, --port    Specific listening port (default: 3000)

      Examples
        $ npm start -- -c -p 8000
    `
    const processOptions = meow(help, options)

    return processOptions.flags
  }
}

module.exports = ArgumentParser
<commit_msg>Fixed style<commit_after>'use strict'

const ParserInterface = require('../parser-interface')
const meow = require('meow')

class ArgumentParser extends ParserInterface {
  parse () {
    const options = {
      alias: {
        c: 'cluster',
        p: 'port',
        v: 'version'
      },
      boolean: [ // options that are always boolean
        'cluster'
      ],
      default: {
        cluster: false,
        port: 3000
      }
    }
    const help = `
      Usage:
        $ npm start [-- <options>]

      Options:
        -c, --cluster Enable cluster mode (default: disable)
        -p, --port    Specific listening port (default: 3000)

      Examples
        $ npm start -- -c -p 8000
    `
    const processOptions = meow(help, options)

    return processOptions.flags
  }
}

module.exports = ArgumentParser
<|endoftext|>


<commit_before>'use strict';

var Utils = require('./../utils')
  , Helpers = require('./helpers')
  , Transaction = require('../transaction');

module.exports = (function() {
  var HasOne = function(srcDAO, targetDAO, options) {
    this.associationType = 'HasOne';
    this.source = srcDAO;
    this.target = targetDAO;
    this.options = options;
    this.isSingleAssociation = true;
    this.isSelfAssociation = (this.source === this.target);
    this.as = this.options.as;

    if (Utils._.isObject(this.options.foreignKey)) {
      this.foreignKeyAttribute = this.options.foreignKey;
      this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
    } else {
      this.foreignKeyAttribute = {};
      this.foreignKey = this.options.foreignKey;
    }

    if (this.as) {
      this.isAliased = true;
      this.options.name = {
        singular: this.as
      };
    } else {
      this.as = this.target.options.name.singular;
      this.options.name = this.target.options.name;
    }

    if (!this.options.foreignKey) {
      this.options.foreignKey = Utils._.camelizeIf(
        [
          Utils._.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
          this.source.primaryKeyAttribute
        ].join('_'),
        !this.source.options.underscored
      );
    }

    this.identifier = this.foreignKey || Utils._.camelizeIf(
      [
        Utils._.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
        this.source.primaryKeyAttribute
      ].join('_'),
      !this.source.options.underscored
    );

    this.sourceIdentifier = this.source.primaryKeyAttribute;
    this.associationAccessor = this.as;
    this.options.useHooks = options.useHooks;

    // Get singular name, trying to uppercase the first letter, unless the model forbids it
    var singular = Utils.uppercaseFirst(this.options.name.singular);

    this.accessors = {
      get: 'get' + singular,
      set: 'set' + singular,
      create: 'create' + singular
    };
  };

  // the id is in the target table
  HasOne.prototype.injectAttributes = function() {
    var newAttributes = {}
      , keyType = this.source.rawAttributes[this.sourceIdentifier].type;

    newAttributes[this.identifier] = Utils._.defaults(this.foreignKeyAttribute, { type: this.options.keyType || keyType });
    Utils.mergeDefaults(this.target.rawAttributes, newAttributes);

    if (this.options.constraints !== false) {
      this.options.onDelete = this.options.onDelete || 'SET NULL';
      this.options.onUpdate = this.options.onUpdate || 'CASCADE';
    }
    Helpers.addForeignKeyConstraints(this.target.rawAttributes[this.identifier], this.source, this.target, this.options);

    // Sync attributes and setters/getters to DAO prototype
    this.target.refreshAttributes();

    Helpers.checkNamingCollision(this);

    return this;
  };

  HasOne.prototype.injectGetter = function(instancePrototype) {
    var association = this;

    instancePrototype[this.accessors.get] = function(params) {
      var where = {};

      params = params || {};
      params.where = (params.where && [params.where]) || [];

      where[association.identifier] = this.get(association.sourceIdentifier);
      params.where.push(where);

      params.where = new Utils.and(params.where);

      return association.target.find(params);
    };

    return this;
  };

  HasOne.prototype.injectSetter = function(instancePrototype) {
    var association = this;

    instancePrototype[this.accessors.set] = function(associatedInstance, options) {
      var instance = this;

      return instance[association.accessors.get](options).then(function(oldInstance) {
        if (oldInstance) {
          oldInstance[association.identifier] = null;
          return oldInstance.save(Utils._.extend({}, options, {
            fields: [association.identifier],
            allowNull: [association.identifier],
            association: true
          }));
        }
      }).then(function() {
        if (associatedInstance) {
          if (!(associatedInstance instanceof association.target.Instance)) {
            var tmpInstance = {};
            tmpInstance[association.target.primaryKeyAttribute] = associatedInstance;
            associatedInstance = association.target.build(tmpInstance, {
              isNewRecord: false
            });
          }
          associatedInstance.set(association.identifier, instance.get(association.sourceIdentifier));
          return associatedInstance.save(options);
        }
        return null;
      });
    };

    return this;
  };

  HasOne.prototype.injectCreator = function(instancePrototype) {
    var association = this;

    instancePrototype[this.accessors.create] = function(values, options) {
      var instance = this;
      options = options || {};

      values[association.identifier] = instance.get(association.sourceIdentifier);
      if (options.fields) options.fields.push(association.identifier);
      return association.target.create(values, options);
    };

    return this;
  };

  return HasOne;
})();
<commit_msg>Fix for #2327<commit_after>'use strict';

var Utils = require('./../utils')
  , Helpers = require('./helpers')
  , Transaction = require('../transaction');

module.exports = (function() {
  var HasOne = function(srcDAO, targetDAO, options) {
    this.associationType = 'HasOne';
    this.source = srcDAO;
    this.target = targetDAO;
    this.options = options;
    this.isSingleAssociation = true;
    this.isSelfAssociation = (this.source === this.target);
    this.as = this.options.as;

    if (Utils._.isObject(this.options.foreignKey)) {
      this.foreignKeyAttribute = this.options.foreignKey;
      this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
    } else {
      this.foreignKeyAttribute = {};
      this.foreignKey = this.options.foreignKey;
    }

    if (this.as) {
      this.isAliased = true;
      this.options.name = {
        singular: this.as
      };
    } else {
      this.as = this.target.options.name.singular;
      this.options.name = this.target.options.name;
    }

    if (!this.options.foreignKey) {
      this.options.foreignKey = Utils._.camelizeIf(
        [
          Utils._.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
          this.source.primaryKeyAttribute
        ].join('_'),
        !this.source.options.underscored
      );
    }

    this.identifier = this.foreignKey || Utils._.camelizeIf(
      [
        Utils._.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
        this.source.primaryKeyAttribute
      ].join('_'),
      !this.source.options.underscored
    );

    this.sourceIdentifier = this.source.primaryKeyAttribute;
    this.associationAccessor = this.as;
    this.options.useHooks = options.useHooks;

    // Get singular name, trying to uppercase the first letter, unless the model forbids it
    var singular = Utils.uppercaseFirst(this.options.name.singular);

    this.accessors = {
      get: 'get' + singular,
      set: 'set' + singular,
      create: 'create' + singular
    };
  };

  // the id is in the target table
  HasOne.prototype.injectAttributes = function() {
    var newAttributes = {}
      , keyType = this.source.rawAttributes[this.sourceIdentifier].type;

    newAttributes[this.identifier] = Utils._.defaults(this.foreignKeyAttribute, { type: this.options.keyType || keyType });
    Utils.mergeDefaults(this.target.rawAttributes, newAttributes);

    if (this.options.constraints !== false) {
      this.options.onDelete = this.options.onDelete || 'SET NULL';
      this.options.onUpdate = this.options.onUpdate || 'CASCADE';
    }
    Helpers.addForeignKeyConstraints(this.target.rawAttributes[this.identifier], this.source, this.target, this.options);

    // Sync attributes and setters/getters to DAO prototype
    this.target.refreshAttributes();

    Helpers.checkNamingCollision(this);

    return this;
  };

  HasOne.prototype.injectGetter = function(instancePrototype) {
    var association = this;

    instancePrototype[this.accessors.get] = function(params) {
      var where = {};

      params = params || {};
      params.where = (params.where && [params.where]) || [];

      where[association.identifier] = this.get(association.sourceIdentifier);
      params.where.push(where);

      params.where = new Utils.and(params.where);

      return association.target.find(params);
    };

    return this;
  };

  HasOne.prototype.injectSetter = function(instancePrototype) {
    var association = this;

    instancePrototype[this.accessors.set] = function(associatedInstance, options) {
      var instance = this;

      return instance[association.accessors.get](options).then(function(oldInstance) {
        if (oldInstance) {
          oldInstance[association.identifier] = null;
          return oldInstance.save(Utils._.extend({}, options, {
            fields: [association.identifier],
            allowNull: [association.identifier],
            association: true
          }));
        }
      }).then(function() {
        if (associatedInstance) {
          if (!(associatedInstance instanceof association.target.Instance)) {
            var tmpInstance = {};
            tmpInstance[association.target.primaryKeyAttribute] = associatedInstance;
            associatedInstance = association.target.build(tmpInstance, {
              isNewRecord: false
            });
          }
          associatedInstance.set(association.identifier, instance.get(association.sourceIdentifier));
          return associatedInstance.save(options);
        }
        return null;
      });
    };

    return this;
  };

  HasOne.prototype.injectCreator = function(instancePrototype) {
    var association = this;

    instancePrototype[this.accessors.create] = function(values, options) {
      var instance = this;
      values = values || {};
      options = options || {};

      values[association.identifier] = instance.get(association.sourceIdentifier);
      if (options.fields) options.fields.push(association.identifier);
      return association.target.create(values, options);
    };

    return this;
  };

  return HasOne;
})();
<|endoftext|>


<commit_before>const Boom = require('boom');
const Controller = require('../controller');

class _AuthController extends Controller {

    constructor(auth) {
        super({
            prefix: '/api',
            default: {
                auth: false,
            },
            routes: {
                auth_user: {
                    auth: {mode: 'required'},
                },
                auth_logout: {
                    auth: {mode: 'required'},
                },
            }
        });

        /** @type Auth */
        this.auth = auth;
    }

    async auth_login_post(request, reply) {
        let {username, password} = request.payload;
        let {id_token} = await this.auth.login({username, password, request});
        reply({id_token});
    }

    async auth_logout(request, reply) {
        let {session, user} = request;
        await user.logout(session);
        reply('LOGGED_OUT');
    }

    async auth_user(request, reply) {
        reply({user: request.user});
    }

    async oauth_$clientID_login(request, reply, {clientID}) {
        let redirect_uri = await this.auth.oauth_login(clientID);
        reply({redirect_uri});
    }

    async oauth_$clientID_authorize(request, reply, {clientID}) {
        let {id_token, user} = await this.auth.oauth_authorize(clientID, request);
        reply({id_token, user});
    }

}

module.exports = _AuthController;<commit_msg>auth is not internal!<commit_after>const Boom = require('boom');
const Controller = require('../controller');

class $AuthController extends Controller {

    constructor(auth) {
        super({
            prefix: '/api',
            default: {
                auth: false,
            },
            routes: {
                auth_user: {
                    auth: {mode: 'required'},
                },
                auth_logout: {
                    auth: {mode: 'required'},
                },
            }
        });

        /** @type Auth */
        this.auth = auth;
    }

    async auth_login_post(request, reply) {
        let {username, password} = request.payload;
        let {id_token} = await this.auth.login({username, password, request});
        reply({id_token});
    }

    async auth_logout(request, reply) {
        let {session, user} = request;
        await user.logout(session);
        reply('LOGGED_OUT');
    }

    async auth_user(request, reply) {
        reply({user: request.user});
    }

    async oauth_$clientID_login(request, reply, {clientID}) {
        let redirect_uri = await this.auth.oauth_login(clientID);
        reply({redirect_uri});
    }

    async oauth_$clientID_authorize(request, reply, {clientID}) {
        let {id_token, user} = await this.auth.oauth_authorize(clientID, request);
        reply({id_token, user});
    }

}

module.exports = $AuthController;<|endoftext|>


<commit_before>/**
 * Copyright 2013-2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @providesModule HTMLDOMPropertyConfig
 */

/*jslint bitwise: true*/

"use strict";

var DOMProperty = require('DOMProperty');

var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
  DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
  DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;

var HTMLDOMPropertyConfig = {
  isCustomAttribute: RegExp.prototype.test.bind(
    /^(data|aria)-[a-z_][a-z\d_.\-]*$/
  ),
  Properties: {
    /**
     * Standard Properties
     */
    accept: null,
    accessKey: null,
    action: null,
    allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    allowTransparency: MUST_USE_ATTRIBUTE,
    alt: null,
    async: HAS_BOOLEAN_VALUE,
    autoComplete: null,
    // autoFocus is polyfilled/normalized by AutoFocusMixin
    // autoFocus: HAS_BOOLEAN_VALUE,
    autoPlay: HAS_BOOLEAN_VALUE,
    cellPadding: null,
    cellSpacing: null,
    charSet: MUST_USE_ATTRIBUTE,
    checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    className: MUST_USE_PROPERTY,
    cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    colSpan: null,
    content: null,
    contentEditable: null,
    contextMenu: MUST_USE_ATTRIBUTE,
    controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    crossOrigin: null,
    data: null, // For `<object />` acts as `src`.
    dateTime: MUST_USE_ATTRIBUTE,
    defer: HAS_BOOLEAN_VALUE,
    dir: null,
    disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    download: HAS_OVERLOADED_BOOLEAN_VALUE,
    draggable: null,
    encType: null,
    form: MUST_USE_ATTRIBUTE,
    formNoValidate: HAS_BOOLEAN_VALUE,
    frameBorder: MUST_USE_ATTRIBUTE,
    height: MUST_USE_ATTRIBUTE,
    hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    href: null,
    hrefLang: null,
    htmlFor: null,
    httpEquiv: null,
    icon: null,
    id: MUST_USE_PROPERTY,
    label: null,
    lang: null,
    list: null,
    loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    max: null,
    maxLength: MUST_USE_ATTRIBUTE,
    mediaGroup: null,
    method: null,
    min: null,
    multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    name: null,
    noValidate: HAS_BOOLEAN_VALUE,
    pattern: null,
    placeholder: null,
    poster: null,
    preload: null,
    radioGroup: null,
    readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    rel: null,
    required: HAS_BOOLEAN_VALUE,
    role: MUST_USE_ATTRIBUTE,
    rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    rowSpan: null,
    sandbox: null,
    scope: null,
    scrollLeft: MUST_USE_PROPERTY,
    scrolling: null,
    scrollTop: MUST_USE_PROPERTY,
    seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    span: HAS_POSITIVE_NUMERIC_VALUE,
    spellCheck: null,
    src: null,
    srcDoc: MUST_USE_PROPERTY,
    srcSet: null,
    start: HAS_NUMERIC_VALUE,
    step: null,
    style: null,
    tabIndex: null,
    target: null,
    title: null,
    type: null,
    value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
    width: MUST_USE_ATTRIBUTE,
    wmode: MUST_USE_ATTRIBUTE,

    /**
     * Non-standard Properties
     */
    autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
    autoCorrect: null, // Supported in Mobile Safari for keyboard hints
    itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
    itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    property: null // Supports OG in meta tags
  },
  DOMAttributeNames: {
    className: 'class',
    htmlFor: 'for',
    httpEquiv: 'http-equiv'
  },
  DOMPropertyNames: {
    autoCapitalize: 'autocapitalize',
    autoComplete: 'autocomplete',
    autoCorrect: 'autocorrect',
    autoFocus: 'autofocus',
    autoPlay: 'autoplay',
    encType: 'enctype',
    hrefLang: 'hreflang',
    radioGroup: 'radiogroup',
    spellCheck: 'spellcheck',
    srcDoc: 'srcdoc',
    srcSet: 'srcset'
  }
};

module.exports = HTMLDOMPropertyConfig;
<commit_msg>Handle className properly on SVG nodes<commit_after>/**
 * Copyright 2013-2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @providesModule HTMLDOMPropertyConfig
 */

/*jslint bitwise: true*/

"use strict";

var DOMProperty = require('DOMProperty');
var ExecutionEnvironment = require('ExecutionEnvironment');

var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
  DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
  DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;

var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
  var implementation = document.implementation;
  hasSVG = (
    implementation &&
    implementation.hasFeature &&
    implementation.hasFeature(
      'http://www.w3.org/TR/SVG11/feature#BasicStructure',
      '1.1'
    )
  );
}

var HTMLDOMPropertyConfig = {
  isCustomAttribute: RegExp.prototype.test.bind(
    /^(data|aria)-[a-z_][a-z\d_.\-]*$/
  ),
  Properties: {
    /**
     * Standard Properties
     */
    accept: null,
    accessKey: null,
    action: null,
    allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    allowTransparency: MUST_USE_ATTRIBUTE,
    alt: null,
    async: HAS_BOOLEAN_VALUE,
    autoComplete: null,
    // autoFocus is polyfilled/normalized by AutoFocusMixin
    // autoFocus: HAS_BOOLEAN_VALUE,
    autoPlay: HAS_BOOLEAN_VALUE,
    cellPadding: null,
    cellSpacing: null,
    charSet: MUST_USE_ATTRIBUTE,
    checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    // To set className on SVG elements, it's necessary to use .setAttribute;
    // this works on HTML elements too in all browsers except IE8. Conveniently,
    // IE8 doesn't support SVG and so we can simply use the attribute in
    // browsers that support SVG and the property in browsers that don't,
    // regardless of whether the element is HTML or SVG.
    className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
    cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    colSpan: null,
    content: null,
    contentEditable: null,
    contextMenu: MUST_USE_ATTRIBUTE,
    controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    crossOrigin: null,
    data: null, // For `<object />` acts as `src`.
    dateTime: MUST_USE_ATTRIBUTE,
    defer: HAS_BOOLEAN_VALUE,
    dir: null,
    disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    download: HAS_OVERLOADED_BOOLEAN_VALUE,
    draggable: null,
    encType: null,
    form: MUST_USE_ATTRIBUTE,
    formNoValidate: HAS_BOOLEAN_VALUE,
    frameBorder: MUST_USE_ATTRIBUTE,
    height: MUST_USE_ATTRIBUTE,
    hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    href: null,
    hrefLang: null,
    htmlFor: null,
    httpEquiv: null,
    icon: null,
    id: MUST_USE_PROPERTY,
    label: null,
    lang: null,
    list: null,
    loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    max: null,
    maxLength: MUST_USE_ATTRIBUTE,
    mediaGroup: null,
    method: null,
    min: null,
    multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    name: null,
    noValidate: HAS_BOOLEAN_VALUE,
    pattern: null,
    placeholder: null,
    poster: null,
    preload: null,
    radioGroup: null,
    readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    rel: null,
    required: HAS_BOOLEAN_VALUE,
    role: MUST_USE_ATTRIBUTE,
    rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    rowSpan: null,
    sandbox: null,
    scope: null,
    scrollLeft: MUST_USE_PROPERTY,
    scrolling: null,
    scrollTop: MUST_USE_PROPERTY,
    seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
    selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
    size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
    span: HAS_POSITIVE_NUMERIC_VALUE,
    spellCheck: null,
    src: null,
    srcDoc: MUST_USE_PROPERTY,
    srcSet: null,
    start: HAS_NUMERIC_VALUE,
    step: null,
    style: null,
    tabIndex: null,
    target: null,
    title: null,
    type: null,
    value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
    width: MUST_USE_ATTRIBUTE,
    wmode: MUST_USE_ATTRIBUTE,

    /**
     * Non-standard Properties
     */
    autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
    autoCorrect: null, // Supported in Mobile Safari for keyboard hints
    itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
    itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
    property: null // Supports OG in meta tags
  },
  DOMAttributeNames: {
    className: 'class',
    htmlFor: 'for',
    httpEquiv: 'http-equiv'
  },
  DOMPropertyNames: {
    autoCapitalize: 'autocapitalize',
    autoComplete: 'autocomplete',
    autoCorrect: 'autocorrect',
    autoFocus: 'autofocus',
    autoPlay: 'autoplay',
    encType: 'enctype',
    hrefLang: 'hreflang',
    radioGroup: 'radiogroup',
    spellCheck: 'spellcheck',
    srcDoc: 'srcdoc',
    srcSet: 'srcset'
  }
};

module.exports = HTMLDOMPropertyConfig;
<|endoftext|>


<commit_before>/*eslint-disable */
//last id 40001

export default [
  { "id": "ser-40001", "name": "2017 USAC National Championships", "url": "http://www.ncnca.org/ncncaseries/2017-usac-national-championships", "shortName": "UNC" },
]
<commit_msg>add CC and VPRS series<commit_after>/*eslint-disable */
//last id 40001

export default [
  { "id": "ser-40001", "name": "2017 USAC National Championships", "url": "http://www.ncnca.org/ncncaseries/2017-usac-national-championships", "shortName": "UNC" },
  { "id": "ser-40002", "name": "2017 Cal Cup", "url": "http://www.ncnca.org/ncncaseries/2017-cal-cup", "shortName": "CC" },
  { "id": "ser-40003", "name": "2017 Velo Promo Road Series", "url": "http://www.ncnca.org/ncncaseries/2017-velo-promo-road-series", "shortName": "VPRS" },
]
<|endoftext|>