<commit_before>/* =========================================================
 * HappyR Dialog is based on bootstrap modal by Twitter Inc.
 *
 * Documentation and examples is found at http://developer.happyr.se
 *
 * =========================================================
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 <HappyRecruiting, Twitter Inc>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of
 * the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 *  THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 *  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 * ========================================================= */

!function ($) {

    "use strict"; // jshint ;_;

    /**
     * Constructor for happyr-dialogs
     * @param element
     * @param options
     * @constructor
     */
    var HappyrDialog = function (element, options) {
	    var that=this;
        this.options = options;
        this.$element = $(element);

        this.$element.delegate('[data-dismiss="happyr-dialog"]', 'click.dismiss.happyr-dialog', $.proxy(this.hide, this));

        this.$element.hide();

        //add stuff to the dialog
        happyrDialog_addWrapper(this.$element, options);

        if(this.options.remote){
            var $dialogBody=this.$element.find('.happyr-dialog-body');

            //add loader image
            if(options.loaderImage !== undefined){
                $dialogBody.html('');
            }

			/**
			* What to do when ajax content is loaded
			*/
			var ajaxContentLoaded=function(){
				if( options.submitFormOnConfirm ){
					that.$element.trigger('ajax-loaded');

                    //run callback
                    if(that.options.ajaxCallback != undefined){
                        happyrDialog_runCallback(that.options.ajaxCallback, $(element));
                    }

                    var $form=$('form', that.$element);
                    if($form.length > 0){
                        //remove previous listeners
                        $(document).off('happyr-dialog-confirm.submit-dialog');

                        //add new listener
                        $(document).one('happyr-dialog-confirm.submit-dialog', function(e){
                            if(options.getFormResultInDialog){
                                $.ajax({
                                    type: $form.attr('method') ? $form.attr('method'): 'POST',
                                    url: $form.attr('action'),
                                    data: $form.serialize(),
                                    success: function (data) {
                                        if(options.hideAfterFormSubmit && options.validateFormResponse(data)){
                                            $("#happyr-dialog").happyrDialog('hide');
                                        }

                                        $dialogBody.html(data);
										ajaxContentLoaded();
                                    }
                                });
                            }
                            else if(options.hideAfterFormSubmit){
                                $form.submit();
                                $("#happyr-dialog").happyrDialog('hide');
                            }
                        });
                    }
                }
			}

			//there is a bug i jQuery that strips form tags when you do load..
			//$dialogBody.load(this.options.remote, ajaxContentLoaded);
			$.get(this.options.remote,function(response){
				//clear the body
				$dialogBody.html("");
				$dialogBody.append(response);

				ajaxContentLoaded();
			});
        }
    };

    HappyrDialog.prototype = {

        constructor: HappyrDialog,

        /**
         * Toggle show/hide
         * @returns {*}
         */
        toggle: function () {
            return this[!this.isShown ? 'show' : 'hide']();
        },

        /**
         * Show dialog
         */
        show: function () {
            var that = this;
            var e = $.Event('show');

            this.$element.trigger(e);

            if (this.isShown || e.isDefaultPrevented()) {
                return;
            }

            this.isShown = true;
            this._enableEscape();

            if (!that.$element.parent().length) {
                that.$element.appendTo(document.body); //don't move dialogs dom position
            }

            var triggerShowEvents=function () {
                that.$element.focus().trigger('shown');
                $(document).trigger('happyr-dialog-shown');
            };

            var showDialog=function(){
                that.$element.show();
                that.$element.attr('aria-hidden', false);
                that.enforceFocus();
            }

            this._showBackdrop();
            if(that.options.animate){
                that.$element
                    .css('opacity',0)
                    .css('top','-25%');

                showDialog();
                that.$element.animate({ top: '10%', opacity: '1' },
                    that.options.animation.timeDialogShow, 'swing', triggerShowEvents);

            }
            else{
                showDialog();
                triggerShowEvents();
            }

        },

        /**
         * Hide dialog
         * @param e
         */
        hide: function (e) {
            if(e){
                e.preventDefault();
            }

            var that = this;
            e = $.Event('hide');
            this.$element.trigger(e);

            if (!this.isShown || e.isDefaultPrevented()) {
                return;
            }

            this.isShown = false;
            this._enableEscape();
            $(document).off('focusin.happyr-dialog');

            var hideDialog=function(){
                that.$element.attr('aria-hidden', true);
                that.$element.hide();
                that.$element.trigger('hidden');
                $(document).trigger('happyr-dialog-close');
            };

            this._hideBackdrop();
            if(that.options.animate){
                that.$element.animate({ top: '-25%', opacity: '0' }, that.options.animation.timeDialogHide, 'swing',hideDialog);
            }
            else{
                hideDialog();
            }

        },

        /**
         * Focus on dialog
         */
        enforceFocus: function () {
            var that = this;
            $(document).on('focusin.happyr-dialog', function (e) {
                if(that.options.enforceFocus){
                    if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
                        that.$element.focus()
                    }
                }
            });
        },

        /**
         * Enable to hide the dialog when escape key is pressed
         * @private
         */
        _enableEscape: function () {
            var that = this
            if (this.isShown && this.options.keyboard) {
                this.$element.on('keyup.dismiss.happyr-dialog', function ( e ) {
                    e.which == 27 && that.hide()
                })
            } else if (!this.isShown) {
                this.$element.off('keyup.dismiss.happyr-dialog')
            }
        },

        /**
         * Crete the backdrop and show it
         * @private
         */
        _showBackdrop: function () {
            var that = this;

            if (this.options.backdrop) {

                this.$backdrop = $('
')
                    .appendTo(document.body);

                this.$backdrop.click(
                    this.options.backdrop == 'static' ?
                        $.proxy(this.$element[0].focus, this.$element[0])
                        : $.proxy(this.hide, this)
                );

                if(this.options.animate){
                    //set opacity = 0
                    this.$backdrop.css('opacity',0);
                    this.$backdrop.show();

                    //fade to 0.8
                    this.$backdrop.fadeTo(
                        that.options.animation.timeBackdropShow,
                        that.options.animation.opacityBackdrop
                    );
                }
                else{
                    this.$backdrop.show();
                }
            }
        },

        /**
         * Hide and remove backdrop
         * @private
         */
        _hideBackdrop: function(){
            if (!this.$backdrop) {
                return;
            }

            var that = this;

            var removeBackdrop=function(){
                that.$backdrop && that.$backdrop.remove();
                that.$backdrop = null;
            }

            //should we animate it away?
            if(this.options.animate){
                //fade to 0
                this.$backdrop.fadeTo(that.options.animation.timeDialogHide,0,removeBackdrop);
            }
            else{
                removeBackdrop();
            }

        }
    };

    $.extend({
        /**
         * Add function to easy extend the settings
         * @param settings
         */
        happyrDialogSetDefaults: function(settings){
            $.fn.happyrDialog.defaults=$.extend(
                true,
                $.fn.happyrDialog.defaults,
                settings
            );
        }
    });

    // save current dialog impl
    var old = $.fn.happyrDialog;

    /**
     * Register the plugin with jQuery and make sure it works as expected
     * @param option
     * @returns {*}
     */
    $.fn.happyrDialog = function (option) {

        return this.each(function () {
            var $this = $(this);
            var data = $this.data('happyrDialog');
            var options = $.extend(true,  {}, $.fn.happyrDialog.defaults, $this.data(), typeof option === 'object' && option);

            //if no dialog or not dialog visible
            if(!data || !data.isShown){
                //create dialog
                $this.data('happyrDialog', (data = new HappyrDialog(this, options)));
            }

            if (typeof option === 'string') {
                data[option]();
            }
            else if(option !== undefined && option.action !== undefined){
               data[option.action]();
            }
            else if (options.show) {
                data.show();
            }

        });
    };

    /**
     * Default options
     */
    $.fn.happyrDialog.defaults = {
        animate: true,
        animation: {
            timeBackdropShow: 200,
            timeBackdropHide: 200,
            timeDialogShow: 300,
            timeDialogHide: 300,
            opacityBackdrop: 0.8
        },
        backdrop: true,
        enforceFocus: true,
        hideAfterFormSubmit: false,
        keyboard: true,
        show: true,
        showHeader: true,
        showFooter: true,
        showButtonClose: true,
        showButtonConfirm: true,
        showButtonHeaderClose: true,
        showTitle: true,
        submitFormOnConfirm: true,
        texts: {
            close: 'Close',
            confirm: 'Confirm'
        },
        getFormResultInDialog: true,
        validateFormResponse: function(data){
            return false;
        }
    };

    $.fn.happyrDialog.Constructor = HappyrDialog;

    /**
     * Just ignore if the object is initialized again
     *
     * @returns this
     */
    $.fn.happyrDialog.noConflict = function () {
        $.fn.happyrDialog = old;
        return this;
    };

    /**
     * Auto add dialog if clickable element data-toggle="happyr-dialog" is defined
     */
    $(document).on('click.happyr-dialog.data-api', '[data-toggle="happyr-dialog"]', function (e) {
        var $this = $(this);
        var href = $this.attr('href');
        var $target = $($this.attr('data-target') || (href && !href.match(/[?=\/&]/) && href.replace(/.*(?=#[^\s]+$)/, ''))); //strip for ie7
        var elementSettings=happyrDialog_convertStringToObject($this.attr('data-happyr-dialog-settings'));

        if($this.attr('data-happyr-dialog-title')){
            elementSettings.texts=$.extend(true, elementSettings.texts,
                {title: $this.attr('data-happyr-dialog-title')});
        }

        elementSettings=$.extend(true,
            {
                remote:!/#/.test(href) && href,
                action: 'toggle'
            },
            $target.data(),
            $this.data(),
            elementSettings
        );

        //make sure the button/link does not behave as normal
        e.preventDefault();

        //if no target found
        if($target.length === 0){
            //try to get autogenerated
            $target=$("#happyr-dialog");

            //if target still not found
            if($target.length === 0){
                //Create a target
                $target=$('
')
                    .appendTo(document.body);
            }
        }

        $target
            .happyrDialog(elementSettings)
            .one('hide', function () {
                $this.focus();
            });
    });

    /**
     * Take a string like "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" and
     * convert it to an object
     *
     * @param string
     * @returns Object
     */
    function happyrDialog_convertStringToObject(string){
        if(string === undefined || string === ""){
            return {};
        }
        return JSON.parse(JSON.stringify(eval("("+string+")")));
    }

    /**
     * Add header, footer and content to the dialog
     * @param $element
     * @param options
     */
    function happyrDialog_addWrapper($element,options){
        //save the current content
        var body;
        if($('.happyr-dialog-body',$element).length > 0){
            body=$element.find('.happyr-dialog-body').html();
        }
        else{
            body=$element.html();
        }

        //Clear the contents
        $element.html("");

        //add wrapper
        $element.addClass("happyr-dialog");

        if(options.showHeader){
            happyrDialog_addHeader($element,options);
        }

        //add the body
        var $bodyWrapper=$("

").addClass('happyr-dialog-body').append(body);

        $element.append($bodyWrapper);

        if(options.showFooter){
            happyrDialog_addFooter($element,options);
        }
    }

    /**
     * Add a header on the dialog
     *
     * @param $element
     * @param options
     */
    function happyrDialog_addHeader($element,options){
        //start header
        var $header=$("

").addClass('happyr-dialog-header');

        if(options.showTitle && options.texts.title !== undefined){
            //add heading
            var $title=$("
"+options.texts.title+"
");
            $header.append($title);
        }

        if(options.showButtonHeaderClose){
            //add close button
            var $closeButton=$("<button type='button' class='close' title='"+options.texts.close+"' data-dismiss='happyr-dialog' aria-hidden='true'>x</button>");
            $header.append($closeButton);
        }

        //add clear fix
        $header.append($("

").addClass("happyr-dialog-clearfix"));

        //end header
        $element.append($header);
    }

    /**
     * Add the footer
     *
     * @param $element
     * @param options
     */
    function happyrDialog_addFooter($element,options){

        var $wrapper=$("

").addClass('happyr-dialog-footer');
        var $footer=$("

").addClass("padder");

        if(options.showButtonClose){
            //add buttons
            var $closeButton=$("<button class='btn' data-dismiss='happyr-dialog' aria-hidden='true'>"+options.texts.close+"</button>");
            $footer.append($closeButton);
        }

        if(options.showButtonConfirm){
            var $confirmButton=$("<button class='btn btn-primary'>"+options.texts.confirm+"</button>");
            $confirmButton.click(function(e){
                $(document).trigger('happyr-dialog-confirm');
            });
            $footer.append($confirmButton);
        }

        $wrapper.append($footer);
        $element.append($wrapper);
    }

    /**
     * Run a callback function with parameter..
     *
     * @param callback
     * @param param
     */
    function happyrDialog_runCallback(callback, param){

        if(typeof callback === 'function'){
            return callback(param);
        }

        var fn = window[callback];
        if(typeof fn === 'function') {
            return fn(param);
        }
    }

}(window.jQuery);
<commit_msg>minor<commit_after>/* =========================================================
 * HappyR Dialog is based on bootstrap modal by Twitter Inc.
 *
 * Documentation and examples is found at http://developer.happyr.se
 *
 * =========================================================
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 <HappyRecruiting, Twitter Inc>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of
 * the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 *  THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 *  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 *  SOFTWARE.
 *
 * ========================================================= */

!function ($) {

    "use strict"; // jshint ;_;

    /**
     * Constructor for happyr-dialogs
     * @param element
     * @param options
     * @constructor
     */
    var HappyrDialog = function (element, options) {
	    var that=this;
        this.options = options;
        this.$element = $(element);

        this.$element.delegate('[data-dismiss="happyr-dialog"]', 'click.dismiss.happyr-dialog', $.proxy(this.hide, this));

        this.$element.hide();

        //add stuff to the dialog
        happyrDialog_addWrapper(this.$element, options);

        if(this.options.remote){
            var $dialogBody=this.$element.find('.happyr-dialog-body');

            //add loader image
            if(options.loaderImage !== undefined){
                $dialogBody.html('');
            }

			/**
			* What to do when ajax content is loaded
			*/
			var ajaxContentLoaded=function(){
				if( options.submitFormOnConfirm ){
					that.$element.trigger('ajax-loaded');

                    //run callback
                    if(that.options.ajaxCallback != undefined){
                        happyrDialog_runCallback(that.options.ajaxCallback, $(element));
                    }

                    var $form=$('form', that.$element);
                    if($form.length > 0){
                        //remove previous listeners
                        $(document).off('happyr-dialog-confirm.submit-dialog');

                        //add new listener
                        $(document).one('happyr-dialog-confirm.submit-dialog', function(e){
                            if(options.getFormResultInDialog){
                                $.ajax({
                                    type: $form.attr('method') ? $form.attr('method'): 'POST',
                                    url: $form.attr('action'),
                                    data: $form.serialize(),
                                    success: function (data) {
                                        if(options.hideAfterFormSubmit && options.validateFormResponse(data)){
                                            $("#happyr-dialog").happyrDialog('hide');
                                            //we dont need to run any more code..
                                            return;
                                        }

                                        $dialogBody.html(data);
										ajaxContentLoaded();
                                    }
                                });
                            }
                            else if(options.hideAfterFormSubmit){
                                $form.submit();
                                $("#happyr-dialog").happyrDialog('hide');
                            }
                        });
                    }
                }
			}

			//there is a bug i jQuery that strips form tags when you do load..
			//$dialogBody.load(this.options.remote, ajaxContentLoaded);
			$.get(this.options.remote,function(response){
				//clear the body
				$dialogBody.html("");
				$dialogBody.append(response);

				ajaxContentLoaded();
			});
        }
    };

    HappyrDialog.prototype = {

        constructor: HappyrDialog,

        /**
         * Toggle show/hide
         * @returns {*}
         */
        toggle: function () {
            return this[!this.isShown ? 'show' : 'hide']();
        },

        /**
         * Show dialog
         */
        show: function () {
            var that = this;
            var e = $.Event('show');

            this.$element.trigger(e);

            if (this.isShown || e.isDefaultPrevented()) {
                return;
            }

            this.isShown = true;
            this._enableEscape();

            if (!that.$element.parent().length) {
                that.$element.appendTo(document.body); //don't move dialogs dom position
            }

            var triggerShowEvents=function () {
                that.$element.focus().trigger('shown');
                $(document).trigger('happyr-dialog-shown');
            };

            var showDialog=function(){
                that.$element.show();
                that.$element.attr('aria-hidden', false);
                that.enforceFocus();
            }

            this._showBackdrop();
            if(that.options.animate){
                that.$element
                    .css('opacity',0)
                    .css('top','-25%');

                showDialog();
                that.$element.animate({ top: '10%', opacity: '1' },
                    that.options.animation.timeDialogShow, 'swing', triggerShowEvents);

            }
            else{
                showDialog();
                triggerShowEvents();
            }

        },

        /**
         * Hide dialog
         * @param e
         */
        hide: function (e) {
            if(e){
                e.preventDefault();
            }

            var that = this;
            e = $.Event('hide');
            this.$element.trigger(e);

            if (!this.isShown || e.isDefaultPrevented()) {
                return;
            }

            this.isShown = false;
            this._enableEscape();
            $(document).off('focusin.happyr-dialog');

            var hideDialog=function(){
                that.$element.attr('aria-hidden', true);
                that.$element.hide();
                that.$element.trigger('hidden');
                $(document).trigger('happyr-dialog-close');
            };

            this._hideBackdrop();
            if(that.options.animate){
                that.$element.animate({ top: '-25%', opacity: '0' }, that.options.animation.timeDialogHide, 'swing',hideDialog);
            }
            else{
                hideDialog();
            }

        },

        /**
         * Focus on dialog
         */
        enforceFocus: function () {
            var that = this;
            $(document).on('focusin.happyr-dialog', function (e) {
                if(that.options.enforceFocus){
                    if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
                        that.$element.focus()
                    }
                }
            });
        },

        /**
         * Enable to hide the dialog when escape key is pressed
         * @private
         */
        _enableEscape: function () {
            var that = this
            if (this.isShown && this.options.keyboard) {
                this.$element.on('keyup.dismiss.happyr-dialog', function ( e ) {
                    e.which == 27 && that.hide()
                })
            } else if (!this.isShown) {
                this.$element.off('keyup.dismiss.happyr-dialog')
            }
        },

        /**
         * Crete the backdrop and show it
         * @private
         */
        _showBackdrop: function () {
            var that = this;

            if (this.options.backdrop) {

                this.$backdrop = $('
')
                    .appendTo(document.body);

                this.$backdrop.click(
                    this.options.backdrop == 'static' ?
                        $.proxy(this.$element[0].focus, this.$element[0])
                        : $.proxy(this.hide, this)
                );

                if(this.options.animate){
                    //set opacity = 0
                    this.$backdrop.css('opacity',0);
                    this.$backdrop.show();

                    //fade to 0.8
                    this.$backdrop.fadeTo(
                        that.options.animation.timeBackdropShow,
                        that.options.animation.opacityBackdrop
                    );
                }
                else{
                    this.$backdrop.show();
                }
            }
        },

        /**
         * Hide and remove backdrop
         * @private
         */
        _hideBackdrop: function(){
            if (!this.$backdrop) {
                return;
            }

            var that = this;

            var removeBackdrop=function(){
                that.$backdrop && that.$backdrop.remove();
                that.$backdrop = null;
            }

            //should we animate it away?
            if(this.options.animate){
                //fade to 0
                this.$backdrop.fadeTo(that.options.animation.timeDialogHide,0,removeBackdrop);
            }
            else{
                removeBackdrop();
            }

        }
    };

    $.extend({
        /**
         * Add function to easy extend the settings
         * @param settings
         */
        happyrDialogSetDefaults: function(settings){
            $.fn.happyrDialog.defaults=$.extend(
                true,
                $.fn.happyrDialog.defaults,
                settings
            );
        }
    });

    // save current dialog impl
    var old = $.fn.happyrDialog;

    /**
     * Register the plugin with jQuery and make sure it works as expected
     * @param option
     * @returns {*}
     */
    $.fn.happyrDialog = function (option) {

        return this.each(function () {
            var $this = $(this);
            var data = $this.data('happyrDialog');
            var options = $.extend(true,  {}, $.fn.happyrDialog.defaults, $this.data(), typeof option === 'object' && option);

            //if no dialog or not dialog visible
            if(!data || !data.isShown){
                //create dialog
                $this.data('happyrDialog', (data = new HappyrDialog(this, options)));
            }

            if (typeof option === 'string') {
                data[option]();
            }
            else if(option !== undefined && option.action !== undefined){
               data[option.action]();
            }
            else if (options.show) {
                data.show();
            }

        });
    };

    /**
     * Default options
     */
    $.fn.happyrDialog.defaults = {
        animate: true,
        animation: {
            timeBackdropShow: 200,
            timeBackdropHide: 200,
            timeDialogShow: 300,
            timeDialogHide: 300,
            opacityBackdrop: 0.8
        },
        backdrop: true,
        enforceFocus: true,
        hideAfterFormSubmit: false,
        keyboard: true,
        show: true,
        showHeader: true,
        showFooter: true,
        showButtonClose: true,
        showButtonConfirm: true,
        showButtonHeaderClose: true,
        showTitle: true,
        submitFormOnConfirm: true,
        texts: {
            close: 'Close',
            confirm: 'Confirm'
        },
        getFormResultInDialog: true,
        validateFormResponse: function(data){
            return false;
        }
    };

    $.fn.happyrDialog.Constructor = HappyrDialog;

    /**
     * Just ignore if the object is initialized again
     *
     * @returns this
     */
    $.fn.happyrDialog.noConflict = function () {
        $.fn.happyrDialog = old;
        return this;
    };

    /**
     * Auto add dialog if clickable element data-toggle="happyr-dialog" is defined
     */
    $(document).on('click.happyr-dialog.data-api', '[data-toggle="happyr-dialog"]', function (e) {
        var $this = $(this);
        var href = $this.attr('href');
        var $target = $($this.attr('data-target') || (href && !href.match(/[?=\/&]/) && href.replace(/.*(?=#[^\s]+$)/, ''))); //strip for ie7
        var elementSettings=happyrDialog_convertStringToObject($this.attr('data-happyr-dialog-settings'));

        if($this.attr('data-happyr-dialog-title')){
            elementSettings.texts=$.extend(true, elementSettings.texts,
                {title: $this.attr('data-happyr-dialog-title')});
        }

        elementSettings=$.extend(true,
            {
                remote:!/#/.test(href) && href,
                action: 'toggle'
            },
            $target.data(),
            $this.data(),
            elementSettings
        );

        //make sure the button/link does not behave as normal
        e.preventDefault();

        //if no target found
        if($target.length === 0){
            //try to get autogenerated
            $target=$("#happyr-dialog");

            //if target still not found
            if($target.length === 0){
                //Create a target
                $target=$('
')
                    .appendTo(document.body);
            }
        }

        $target
            .happyrDialog(elementSettings)
            .one('hide', function () {
                $this.focus();
            });
    });

    /**
     * Take a string like "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }" and
     * convert it to an object
     *
     * @param string
     * @returns Object
     */
    function happyrDialog_convertStringToObject(string){
        if(string === undefined || string === ""){
            return {};
        }
        return JSON.parse(JSON.stringify(eval("("+string+")")));
    }

    /**
     * Add header, footer and content to the dialog
     * @param $element
     * @param options
     */
    function happyrDialog_addWrapper($element,options){
        //save the current content
        var body;
        if($('.happyr-dialog-body',$element).length > 0){
            body=$element.find('.happyr-dialog-body').html();
        }
        else{
            body=$element.html();
        }

        //Clear the contents
        $element.html("");

        //add wrapper
        $element.addClass("happyr-dialog");

        if(options.showHeader){
            happyrDialog_addHeader($element,options);
        }

        //add the body
        var $bodyWrapper=$("

").addClass('happyr-dialog-body').append(body);

        $element.append($bodyWrapper);

        if(options.showFooter){
            happyrDialog_addFooter($element,options);
        }
    }

    /**
     * Add a header on the dialog
     *
     * @param $element
     * @param options
     */
    function happyrDialog_addHeader($element,options){
        //start header
        var $header=$("

").addClass('happyr-dialog-header');

        if(options.showTitle && options.texts.title !== undefined){
            //add heading
            var $title=$("
"+options.texts.title+"
");
            $header.append($title);
        }

        if(options.showButtonHeaderClose){
            //add close button
            var $closeButton=$("<button type='button' class='close' title='"+options.texts.close+"' data-dismiss='happyr-dialog' aria-hidden='true'>x</button>");
            $header.append($closeButton);
        }

        //add clear fix
        $header.append($("

").addClass("happyr-dialog-clearfix"));

        //end header
        $element.append($header);
    }

    /**
     * Add the footer
     *
     * @param $element
     * @param options
     */
    function happyrDialog_addFooter($element,options){

        var $wrapper=$("

").addClass('happyr-dialog-footer');
        var $footer=$("

").addClass("padder");

        if(options.showButtonClose){
            //add buttons
            var $closeButton=$("<button class='btn' data-dismiss='happyr-dialog' aria-hidden='true'>"+options.texts.close+"</button>");
            $footer.append($closeButton);
        }

        if(options.showButtonConfirm){
            var $confirmButton=$("<button class='btn btn-primary'>"+options.texts.confirm+"</button>");
            $confirmButton.click(function(e){
                $(document).trigger('happyr-dialog-confirm');
            });
            $footer.append($confirmButton);
        }

        $wrapper.append($footer);
        $element.append($wrapper);
    }

    /**
     * Run a callback function with parameter..
     *
     * @param callback
     * @param param
     */
    function happyrDialog_runCallback(callback, param){

        if(typeof callback === 'function'){
            return callback(param);
        }

        var fn = window[callback];
        if(typeof fn === 'function') {
            return fn(param);
        }
    }

}(window.jQuery);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var cors = require('./cors');
var HttpError = require('./errors').HttpError;
var facebook = require('../libs/facebook');
var winston = require('winston');

router.use(cors);

/*
 * Show the newest company, week_work_time, job_title
 * GET /
 * [page = 0]
 */
router.get('/latest', function(req, res, next) {
    var page = req.query.page || 0;
    var limit = req.query.limit || 25;

    limit = parseInt(limit);
    if (isNaN(limit) || limit > 50) {
        throw new HttpError("limit is not allow");
    }

    var collection = req.db.collection('workings');
    var q = {};
    var opt = {
            company: 1,
            week_work_time: 1,
            job_title: 1,
            created_at: 1,
        };
    collection.find(q, opt).sort({created_at: -1}).skip(limit * page).limit(limit).toArray().then(function(results) {
        res.send(results);
    }).catch(function(err) {
        next(new HttpError("Internal Server Error", 500));
    });
});

/*
 *  When developing, you can set environment to skip facebook auth
 */
if (! process.env.SKIP_FACEBOOK_AUTH) {

router.post('/', function(req, res, next) {
    var access_token = req.body.access_token;

    facebook.access_token_auth(access_token).then(function(facebook) {
        winston.info("facebook auth success", {access_token: access_token});

        req.facebook = facebook;
        next();
    }).catch(function(err) {
        winston.info("facebook auth fail", {access_token: access_token});

        next(new HttpError("Unauthorized", 401));
    });
});

}

/*
 * POST /
 * company_id | company_name
 * job_title: string
 * week_work_time: integer
 * [salary_min]
 * [salary_max]
 * [salary_type]: suggest "hour", "month", "year"
 * [work_year]
 * [review]
 */
router.post('/', function(req, res, next) {
    /*
     * Prepare and collect the data from request
     */
    var author = {};

    if (req.body.email && (typeof req.body.email === "string") && req.body.email !== "") {
        author.email = req.body.email;
    }

    if (req.facebook) {
        author.id = req.facebook.id,
        author.name = req.facebook.name,
        author.type = "facebook";
    } else {
        author.id = "-1";
        author.type = "test";
    }

    var data = {
        author: author,
        company: {},
        created_at: new Date(),
    };

    // pick these fields only
    // make sure the field is string
    [
        "job_title", "week_work_time",
        "overtime_frequency",
        "day_promised_work_time", "day_real_work_time",
    ].forEach(function(field, i) {
        if (req.body[field] && (typeof req.body[field] === "string") && req.body[field] !== "") {
            data[field] = req.body[field];
        }
    });
    if (req.body.company_id && (typeof req.body.company_id === "string") && req.body.company_id !== "") {
        data.company.id = req.body.company_id;
    }
    if (req.body.company_name && (typeof req.body.company_name === "string") && req.body.company_name !== "") {
        data.company.name = req.body.company_name;
    }

    /*
     * Check all the required fields, or raise an 422 http error
     */
    try {
        validateWorking(data);
    } catch (err) {
        winston.info("workings insert data fail", data);

        next(err);
        return;
    }

    /*
     * So, here, the data are well-down
     */

    var collection = req.db.collection("workings");
    var companyCollection = req.db.collection("companies");

    // use company id to search company
    function searchCompanyById(id) {
        return companyCollection.find({
            id: id,
        }).toArray();
    }

    // use company name to search company
    function searchCompanyByName(name) {
        return companyCollection.find({
            name: name,
        }).toArray();
    }

    Promise.resolve(data).then(function(data) {
        console.log("autocompletion company");
        /*
         * 如果使用者有給定 company id，將 company name 補成查詢到的公司
         *
         * 如果使用者是給定 company name，如果只找到一間公司，才補上 id
         *
         * 其他情況看 issue #7
         */
        if (data.company.id) {
            return searchCompanyById(data.company.id).then(function(results) {
                if (results.length === 0) {
                    throw new HttpError("company_id is invalid", 429);
                }

                data.company.name = results[0].name;
                return data;
            });
        } else {
            return searchCompanyByName(data.company.name).then(function(results) {
                if (results.length === 1) {
                    data.company.id = results[0].id;
                    return data;
                } else {
                    return data;
                }
            });
        }
    }).then(function(data) {
        return checkQuota(req.db, {id: data.author.id, type: data.author.type}).then(function() {
            return data;
        });
    }).then(function(data) {
        return collection.insert(data);
    }).then(function(result) {
        winston.info("workings insert data success", data);

        res.send(data);
    }).catch(function(err) {
        winston.info("workings insert data fail", data);

        next(err);
    });
});

function validateWorking(data) {
    if (! data.job_title) {
        throw new HttpError("job_title is required", 422);
    }

    if (! data.week_work_time) {
        throw new HttpError("week_work_time is required", 422);
    }
    data.week_work_time = parseInt(data.week_work_time);
    if (isNaN(data.week_work_time)) {
        throw new HttpError("week_work_time need to be a number", 422);
    }
    if (data.week_work_time < 0 || data.week_work_time > 168) {
        throw new HttpError("week_work_time must be 0~168", 422);
    }

    if (! data.overtime_frequency) {
        throw new HttpError("overtime_frequency is required", 422);
    }
    if (["0", "1", "2", "3"].indexOf(data.overtime_frequency) === -1) {
        throw new HttpError("overtime_frequency must be 0, 1, 2, 3", 422);
    }
    data.overtime_frequency = parseInt(data.overtime_frequency);

    if (! data.day_promised_work_time) {
        throw new HttpError("day_promised_work_time is required", 422);
    }
    data.day_promised_work_time = parseInt(data.day_promised_work_time);
    if (isNaN(data.day_promised_work_time)) {
        throw new HttpError("day_promised_work_time need to be a number", 422);
    }
    if (data.day_promised_work_time < 0 || data.day_promised_work_time > 24) {
        throw new HttpError("day_promised_work_time must be 0~24", 422);
    }

    if (! data.day_real_work_time) {
        throw new HttpError("day_real_work_time is required", 422);
    }
    data.day_real_work_time = parseInt(data.day_real_work_time);
    if (isNaN(data.day_real_work_time)) {
        throw new HttpError("day_real_work_time need to be a number", 422);
    }
    if (data.day_real_work_time < 0 || data.day_real_work_time > 24) {
        throw new HttpError("day_real_work_time must be 0~24", 422);
    }

    if (! (data.company.id || data.company.name)) {
        throw new HttpError("company_id or company_name is required", 422);
    }
}

function checkQuota(db, author) {
    var collection = db.collection('authors');

    return collection.findAndModify(
        {
            _id: {id: author.id, type: author.type},
            queries_count: {$lt: 10},
        },
        [
        ],
        {
            $inc: { queries_count: 1 },
        },
        {
            upsert: true,
            new: true,
        }
    ).then(function(result) {
        if (result.value.queries_count > 10) {
            throw new HttpError("Quota Exceeds", 429);
        }

        return result.value.queries_count;
    }).catch(function(err) {
        throw new HttpError("Quota Exceeds", 429);
    });

}

module.exports = router;
<commit_msg>docs and wording<commit_after>var express = require('express');
var router = express.Router();
var cors = require('./cors');
var HttpError = require('./errors').HttpError;
var facebook = require('../libs/facebook');
var winston = require('winston');

router.use(cors);

/*
 * Show the newest company, week_work_time, job_title
 * GET /
 * [page = 0]
 */
router.get('/latest', function(req, res, next) {
    var page = req.query.page || 0;
    var limit = req.query.limit || 25;

    limit = parseInt(limit);
    if (isNaN(limit) || limit > 50) {
        throw new HttpError("limit is not allow");
    }

    var collection = req.db.collection('workings');
    var q = {};
    var opt = {
            company: 1,
            week_work_time: 1,
            job_title: 1,
            created_at: 1,
        };
    collection.find(q, opt).sort({created_at: -1}).skip(limit * page).limit(limit).toArray().then(function(results) {
        res.send(results);
    }).catch(function(err) {
        next(new HttpError("Internal Server Error", 500));
    });
});

/*
 *  When developing, you can set environment to skip facebook auth
 */
if (! process.env.SKIP_FACEBOOK_AUTH) {

router.post('/', function(req, res, next) {
    var access_token = req.body.access_token;

    facebook.access_token_auth(access_token).then(function(facebook) {
        winston.info("facebook auth success", {access_token: access_token});

        req.facebook = facebook;
        next();
    }).catch(function(err) {
        winston.info("facebook auth fail", {access_token: access_token});

        next(new HttpError("Unauthorized", 401));
    });
});

}

/*
 * POST /
 * company_id | company_name
 * job_title: string
 * week_work_time: integer
 * [salary_min]
 * [salary_max]
 * [salary_type]: suggest "hour", "month", "year"
 * [work_year]
 * [review]
 */
router.post('/', function(req, res, next) {
    /*
     * Prepare and collect the data from request
     */
    var author = {};

    if (req.body.email && (typeof req.body.email === "string") && req.body.email !== "") {
        author.email = req.body.email;
    }

    if (req.facebook) {
        author.id = req.facebook.id,
        author.name = req.facebook.name,
        author.type = "facebook";
    } else {
        author.id = "-1";
        author.type = "test";
    }

    var data = {
        author: author,
        company: {},
        created_at: new Date(),
    };

    // pick these fields only
    // make sure the field is string
    [
        "job_title", "week_work_time",
        "overtime_frequency",
        "day_promised_work_time", "day_real_work_time",
    ].forEach(function(field, i) {
        if (req.body[field] && (typeof req.body[field] === "string") && req.body[field] !== "") {
            data[field] = req.body[field];
        }
    });
    if (req.body.company_id && (typeof req.body.company_id === "string") && req.body.company_id !== "") {
        data.company.id = req.body.company_id;
    }
    if (req.body.company_name && (typeof req.body.company_name === "string") && req.body.company_name !== "") {
        data.company.name = req.body.company_name;
    }

    /*
     * Check all the required fields, or raise an 422 http error
     */
    try {
        validateWorking(data);
    } catch (err) {
        winston.info("workings insert data fail", data);

        next(err);
        return;
    }

    /*
     * So, here, the data are well-down
     */

    var collection = req.db.collection("workings");
    var companyCollection = req.db.collection("companies");

    // use company id to search company
    function searchCompanyById(id) {
        return companyCollection.find({
            id: id,
        }).toArray();
    }

    // use company name to search company
    function searchCompanyByName(name) {
        return companyCollection.find({
            name: name,
        }).toArray();
    }

    Promise.resolve(data).then(function(data) {
        console.log("autocompletion company");
        /*
         * 如果使用者有給定 company id，將 company name 補成查詢到的公司
         *
         * 如果使用者是給定 company name，如果只找到一間公司，才補上 id
         *
         * 其他情況看 issue #7
         */
        if (data.company.id) {
            return searchCompanyById(data.company.id).then(function(results) {
                if (results.length === 0) {
                    throw new HttpError("company_id is invalid", 429);
                }

                data.company.name = results[0].name;
                return data;
            });
        } else {
            return searchCompanyByName(data.company.name).then(function(results) {
                if (results.length === 1) {
                    data.company.id = results[0].id;
                    return data;
                } else {
                    return data;
                }
            });
        }
    }).then(function(data) {
        return checkQuota(req.db, {id: data.author.id, type: data.author.type}).then(function() {
            return data;
        });
    }).then(function(data) {
        return collection.insert(data);
    }).then(function(result) {
        winston.info("workings insert data success", data);

        res.send(data);
    }).catch(function(err) {
        winston.info("workings insert data fail", data);

        next(err);
    });
});

function validateWorking(data) {
    if (! data.job_title) {
        throw new HttpError("job_title is required", 422);
    }

    if (! data.week_work_time) {
        throw new HttpError("week_work_time is required", 422);
    }
    data.week_work_time = parseInt(data.week_work_time);
    if (isNaN(data.week_work_time)) {
        throw new HttpError("week_work_time need to be a number", 422);
    }
    if (data.week_work_time < 0 || data.week_work_time > 168) {
        throw new HttpError("week_work_time must be 0~168", 422);
    }

    if (! data.overtime_frequency) {
        throw new HttpError("overtime_frequency is required", 422);
    }
    if (["0", "1", "2", "3"].indexOf(data.overtime_frequency) === -1) {
        throw new HttpError("overtime_frequency must be 0, 1, 2, 3", 422);
    }
    data.overtime_frequency = parseInt(data.overtime_frequency);

    if (! data.day_promised_work_time) {
        throw new HttpError("day_promised_work_time is required", 422);
    }
    data.day_promised_work_time = parseInt(data.day_promised_work_time);
    if (isNaN(data.day_promised_work_time)) {
        throw new HttpError("day_promised_work_time need to be a number", 422);
    }
    if (data.day_promised_work_time < 0 || data.day_promised_work_time > 24) {
        throw new HttpError("day_promised_work_time must be 0~24", 422);
    }

    if (! data.day_real_work_time) {
        throw new HttpError("day_real_work_time is required", 422);
    }
    data.day_real_work_time = parseInt(data.day_real_work_time);
    if (isNaN(data.day_real_work_time)) {
        throw new HttpError("day_real_work_time need to be a number", 422);
    }
    if (data.day_real_work_time < 0 || data.day_real_work_time > 24) {
        throw new HttpError("day_real_work_time must be 0~24", 422);
    }

    if (! (data.company.id || data.company.name)) {
        throw new HttpError("company_id or company_name is required", 422);
    }
}

/*
 * Check the quota, limit queries <= 10
 *
 * The quota checker use author as _id
 *
 * @return  Promise
 *
 * Fullfilled with newest queries_count
 * Rejected with HttpError
 */
function checkQuota(db, author) {
    var collection = db.collection('authors');

    return collection.findAndModify(
        {
            _id: author,
            queries_count: {$lt: 10},
        },
        [
        ],
        {
            $inc: { queries_count: 1 },
        },
        {
            upsert: true,
            new: true,
        }
    ).then(function(result) {
        if (result.value.queries_count > 10) {
            throw new HttpError("Quota Exceeds", 429);
        }

        return result.value.queries_count;
    }).catch(function(err) {
        throw new HttpError("Quota Exceeds", 429);
    });

}

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

/* CI Test mode - script which purpose is to test if CI enviroment is working
 * properly by running one simple test for android and ios native layer and
 * node layer.
 */

var fs = require('fs-extra-promise');

var updateUnitTestConfig = function() {
  var locationOfUnitTestConfig = '../../TestServer/UnitTestConfig.js';

  try {
    var originalContent = fs.readFileSync(locationOfUnitTestConfig);
    var newContent = originalContent.toString().replace(/-?[0-9]/g, '-1');

    fs.writeFileSync(locationOfUnitTestConfig, newContent);
  } catch (e) {
    console.log(e);
    console.log('Failed to update the UnitTestConfig.js file!');
  }
};

var updateThaliTestSuiteFunction = function() {
  var locationOfAndroidBeforeCompile = '../../../scripts/android/before_compile.js';

  try {
    var originalContent = fs.readFileSync(locationOfAndroidBeforeCompile);
    var newContent = originalContent.toString().replace('Test.java', 'CITest');

    fs.writeFileSync(locationOfAndroidBeforeCompile, newContent, 'utf-8');
  } catch (e) {
    console.log(e);
    console.log('Failed to update function in androidBeforeCompile.js file!');
  }
};

var copyCINativeTestClass = function() {
  try {
    var path = '../../../scripts/android/before_compile.js';

    var originalContent = fs.readFileSync(path);
    var oldFunc = 'fs.copySync(sourceFile, targetFile);';
    var newFunc = 'fs.copySync(appRoot + \'plugins/org.thaliproject.p2p/src/android/test/CITestClass.java\', appRoot + \'platforms/android/CITestClass.java\');';
    var newContent = originalContent.toString().replace(oldFunc, newFunc);

    fs.writeFileSync(path, newContent);
  } catch (e) {
    console.log(e);
    console.log('Failed to create CITestClass.java file!');
  }
};

var updateRunTestsToRunOnlyOneNodeTest = function() {
  var locationOfRunTests = './runTests.js';

  try {
    var originalContent = fs.readFileSync(locationOfRunTests);
    var newContent = originalContent.toString().replace('fileName.indexOf(\'test\') === 0)', 'fileName.indexOf(\'CITest\') === 0)');

    fs.writeFileSync(locationOfRunTests, newContent);
  } catch (e) {
    console.log(e);
    console.log('Failed to modify runTests.js file!');
  }
};

var copyCINodeTestClass = function() {
  try {
    fs.renameSync('bv_tests/disabled/CITestClass.js', 'bv_tests/CITestClass.js');
  } catch (e) {
    console.log(e);
    console.log('Failed to copy CI node test class file!');
  }
};

var removeAlliOSTestsButOne = function() {
  try {
    var oldPathTest = '../../../lib/ios/ThaliCore/ThaliCoreTests/SimpleTestCase.swift';
    var newPathTest = '../../../lib/ios/ThaliCore/SimpleTestCase.swift';

    var oldPathInfo = '../../../lib/ios/ThaliCore/ThaliCoreTests/Supporting Files/Info.plist';
    var newPathInfo = '../../../lib/ios/ThaliCore/Info.plist';

    fs.renameSync(oldPathTest, newPathTest);
    fs.renameSync(oldPathInfo, newPathInfo);

    fs.removeSync('../../../lib/ios/ThaliCore/ThaliCoreTests');

    fs.mkdirsSync('../../../lib/ios/ThaliCore/ThaliCoreTests/Supporting Files');
    fs.renameSync(newPathTest, oldPathTest);
    fs.renameSync(newPathInfo, oldPathInfo);

  } catch (e) {
    console.log(e);
    console.log('Failed to remove all iOS test files but one');
  }
};

updateUnitTestConfig();
copyCINodeTestClass();
copyCINativeTestClass();
updateThaliTestSuiteFunction();
updateRunTestsToRunOnlyOneNodeTest();
//removeAlliOSTestsButOne();
<commit_msg>Fixed wrong path<commit_after>'use strict';

/* CI Test mode - script which purpose is to test if CI enviroment is working
 * properly by running one simple test for android and ios native layer and
 * node layer.
 */

var fs = require('fs-extra-promise');

var updateUnitTestConfig = function() {
  var locationOfUnitTestConfig = '../../TestServer/UnitTestConfig.js';

  try {
    var originalContent = fs.readFileSync(locationOfUnitTestConfig);
    var newContent = originalContent.toString().replace(/-?[0-9]/g, '-1');

    fs.writeFileSync(locationOfUnitTestConfig, newContent);
  } catch (e) {
    console.log(e);
    console.log('Failed to update the UnitTestConfig.js file!');
  }
};

var updateThaliTestSuiteFunction = function() {
  var locationOfAndroidBeforeCompile = '../../../scripts/android/before_compile.js';

  try {
    var originalContent = fs.readFileSync(locationOfAndroidBeforeCompile);
    var newContent = originalContent.toString().replace('Test.java', 'CITest');

    fs.writeFileSync(locationOfAndroidBeforeCompile, newContent, 'utf-8');
  } catch (e) {
    console.log(e);
    console.log('Failed to update function in androidBeforeCompile.js file!');
  }
};

var copyCINativeTestClass = function() {
  try {
    var path = '../../../scripts/android/before_compile.js';

    var originalContent = fs.readFileSync(path);
    var oldFunc = 'fs.copySync(sourceFile, targetFile);';
    var newFunc = 'fs.copySync(appRoot + \'plugins/org.thaliproject.p2p/src/android/java/io/jxcore/node/test/CITestClass.java\', appRoot + \'platforms/android/src/io/jxcore/node/CITestClass.java\');';
    var newContent = originalContent.toString().replace(oldFunc, newFunc);

    fs.writeFileSync(path, newContent);
  } catch (e) {
    console.log(e);
    console.log('Failed to create CITestClass.java file!');
  }
};

var updateRunTestsToRunOnlyOneNodeTest = function() {
  var locationOfRunTests = './runTests.js';

  try {
    var originalContent = fs.readFileSync(locationOfRunTests);
    var newContent = originalContent.toString().replace('fileName.indexOf(\'test\') === 0)', 'fileName.indexOf(\'CITest\') === 0)');

    fs.writeFileSync(locationOfRunTests, newContent);
  } catch (e) {
    console.log(e);
    console.log('Failed to modify runTests.js file!');
  }
};

var copyCINodeTestClass = function() {
  try {
    fs.renameSync('bv_tests/disabled/CITestClass.js', 'bv_tests/CITestClass.js');
  } catch (e) {
    console.log(e);
    console.log('Failed to copy CI node test class file!');
  }
};

var removeAlliOSTestsButOne = function() {
  try {
    var oldPathTest = '../../../lib/ios/ThaliCore/ThaliCoreTests/SimpleTestCase.swift';
    var newPathTest = '../../../lib/ios/ThaliCore/SimpleTestCase.swift';

    var oldPathInfo = '../../../lib/ios/ThaliCore/ThaliCoreTests/Supporting Files/Info.plist';
    var newPathInfo = '../../../lib/ios/ThaliCore/Info.plist';

    fs.renameSync(oldPathTest, newPathTest);
    fs.renameSync(oldPathInfo, newPathInfo);

    fs.removeSync('../../../lib/ios/ThaliCore/ThaliCoreTests');

    fs.mkdirsSync('../../../lib/ios/ThaliCore/ThaliCoreTests/Supporting Files');
    fs.renameSync(newPathTest, oldPathTest);
    fs.renameSync(newPathInfo, oldPathInfo);

  } catch (e) {
    console.log(e);
    console.log('Failed to remove all iOS test files but one');
  }
};

updateUnitTestConfig();
copyCINodeTestClass();
copyCINativeTestClass();
updateThaliTestSuiteFunction();
updateRunTestsToRunOnlyOneNodeTest();
//removeAlliOSTestsButOne();
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var uglifycss = require('gulp-uglifycss');
var minifyHTML = require('gulp-minify-html');
var minifyInline = require('gulp-minify-inline');
var mainBowerFiles = require('main-bower-files');

var js_folder = [
	'src/js/*.js',
	'src/views/js/*.js'
];

var html_folder = [
	'src/*.html',
	'src/views/*.html'
];

var css_folder = [
	'src/css/*.css',
	'src/views/css/*.css'
];

var img_folder = [
	'src/img/*.{png,jpg}',
	'src/views/images/*.{png,jpg}'
];

gulp.task('minifyhtml', function() {
  return gulp.src(html_folder, { base: 'src/'})
			.pipe(minifyHTML())
			.pipe(minifyInline())
			.pipe(gulp.dest('dist'));
});

// Minify CSS
gulp.task('minifycss', function() {
  return gulp.src(css_folder, { base: 'src/'})
			.pipe(uglifycss())
			.pipe(gzip())
			.pipe(gulp.dest('dist'));
});

// Minify JavaScript
gulp.task('minifyjs', function() {
  return gulp.src(js_folder, { base: 'src/'})
			.pipe(uglify())
			.pipe(gzip())
			.pipe(gulp.dest('dist'));
});

// Do everything by default
gulp.task('default', ['minifyhtml', 'minifycss', 'minifyjs']);

<commit_msg>feat: Add required task builds for dist<commit_after>'use strict';

var gulp = require('gulp');
var uglify = require('gulp-uglify');
var uglifycss = require('gulp-uglifycss');
var minifyHTML = require('gulp-minify-html');
var minifyInline = require('gulp-minify-inline');
var mainBowerFiles = require('main-bower-files');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var concat = require('gulp-concat');

var js_folder = [
	'src/js/modernizr.js',
	'bower_components/jquery/dist/jquery.min.js',
	'bower_components/knockout/dist/knockout.js',
	'src/js/foundation.js',
	'src/js/foundation.topbar.js',
	'src/js/model.js',
	'src/js/app.js'
];

var html_folder = [
	'src/*.html',
	'src/views/*.html'
];

var css_folder = [
	'src/css/*.css',
	'src/views/css/*.css'
];

var img_folder = [
	'src/img/*'
];

gulp.task('minifyhtml', function() {
	return gulp.src(html_folder, { base: 'src/'})
		.pipe(minifyHTML())
		.pipe(minifyInline())
		.pipe(gulp.dest('dist'));
});

gulp.task('sass', function () {
	console.log('Running Sass');
	return gulp.src('src/scss/app.scss')
		.pipe(sass())
		.pipe(uglifycss())
		.pipe(rename('app.min.css'))
		.pipe(gulp.dest('dist/css'));
		//.pipe(browserSync.reload({stream:true}));
});

// Minify JavaScript
gulp.task('minifyjs', function() {
	return gulp.src(js_folder)
		.pipe(concat('all.js'))
		.pipe(uglify())
		.pipe(rename('app.min.js'))
		.pipe(gulp.dest('dist/js'));
});

gulp.task('moveimg', function(){
	return gulp.src(img_folder)
		.pipe(gulp.dest('dist/img'));
});

// Do everything by default
gulp.task('default', ['minifyhtml', 'sass', 'minifyjs', 'moveimg']);

<|endoftext|>


<commit_before>// Some bootstrapping
// Let's serve up the data file via json
var http = require( 'http' );
// Let's get the filestream api to write the temp data
var fs = require( 'fs' );
// Let's get the GPIO api for the rpi
var gpio = require( 'rpi-gpio' );
// Global request object for http get/post
var needle = require('needle');
// Global SPI object
var spi = require( 'spi' );

var spiADC = {
	'options': {
		'channel': 0,
		'spiMaxSpeed': 20000,
		'resistances_to_keep': 100,
		'ignore_data_beyond_pct': 0.05
	},
	'SPI': spi,
	'isOpen': false,
	'device': '',
	'resistances': [],
	'res_index': 0,
	'series_resistor': 9860,
	'thermistor': {
		'nominal_resistance': 10000,
		'nominal_temp': 25,
		'bcoefficient': 3950,
		'calibration_offset': 0
	},
	open: function(){
		if(this.isOpen === true){
			console.log( 'Cannot open a device that is already open!' );
			return;
		}

		this.device = new this.SPI.Spi('/dev/spidev0.0', {'maxSpeed': this.options.spiMaxSpeed}, function(s){s.open();});

		this.isOpen = true;
	},
	handleSpiData: function(device, buf){

		var data = ((buf[1]&3) << 8) + buf[2];

		// Let's exclude data readings that are 0
		// and readings that are more than +/- 5% of the previous reading (indicates a spike we should ignore)
		if( data === 0 || Math.abs( ( data - this.resistances[this.resistances.length-1] ) / this.resistances[this.resistances.length-1] ) > this.options.ignore_data_beyond_pct ){
			// Let's discard this reading
			return -1;
		}
		return data;
	},
	storeSpiData: function( device, data ){
		this.resistances[this.res_index] = data;
	},
	setNextResistanceIndex: function(){
		this.res_index++;
		if(this.res_index >= (this.options.resistances_to_keep -1) ){
			this.res_index = 0;
		}
	},
	read: function(){
		var self = this;
		var txbuf = new Buffer([1, (8 + this.options.channel) << 4, 0]);
		var rxbuf = new Buffer([ 0x00, 0x00, 0x00 ]);

		this.device.transfer( txbuf, rxbuf, function( device, buf ){
			var data = self.handleSpiData( device, buf );

			if( data > 0 ){
				self.storeSpiData( device, data );
				self.setNextResistanceIndex();
			}
		});
	},
	getAverageData: function(){
		if( this.resistances.length === 0 ){
			return 0;
		}

		var sum = 0;
		for(var i = 0; i < this.resistances.length; i++){
			sum += parseFloat(this.resistances[i]);
		}

		return sum / this.resistances.length + this.thermistor.calibration_offset;

	},
	calculate_thermistor_resistance: function( average_raw ){
		console.log('average raw: ' + average_raw);

		var thermistor_resistance =  (1023 / average_raw) - 1;
		thermistor_resistance = this.series_resistor / thermistor_resistance;

		return thermistor_resistance;
	},
	steinhart: function( thermistor_resistance ){
		var steinhart = thermistor_resistance / this.thermistor.nominal_resistance;

		steinhart = Math.log( steinhart );
		steinhart = steinhart / this.thermistor.bcoefficient;
		steinhart += 1.0 / (this.thermistor.nominal_temp + 273.15);
		steinhart = 1.0 / steinhart;
		steinhart -= 273.15;

		return steinhart;
	},
	getAverageTemperature: function( average_resistance) {
		var thermistor_resistance = this.calculate_thermistor_resistance( average_resistance );
		var steinhart = this.steinhart( thermistor_resistance );

		console.log('thermistor resistance: ' + thermistor_resistance);
		console.log('thermistor temperature: ' + Math.round( steinhart * 100 ) / 100);

		return steinhart;
	}
};
var DataLogger = {
	'options': {
		'logfile': '',
		'endpointUrl': 'http://192.168.1.126/dev/test.php',
		'timeout': 5000
	},
	'txError': false,
	'data': [],
	init: function(logfile){
		this.options.logfile = logfile;
		// Return this object to be used once init'd
		return this;
	},
	addDataPoint: function(model){
		this.data.push(model);
	},
	writeDataToFile : function(){
		if( this.txError ) {
			return;
		}

		/* First load in the file contents */
		var self = this;
		fs.readFile(self.options.logfile, {'encoding': 'ascii'}, function (err, data) {
			if (err){
				throw err;
			}

			try{
				var fileData = [];

				if( data !== null && data !== '' ){
					fileData = JSON.parse(data);
				}

				var combinedData = fileData.concat(self.data);

				fs.writeFile(self.options.logfile, JSON.stringify(combinedData), { 'flag' : 'r+'}, function (err) {
					if (err){
						console.log(err);
						throw err;
					}

					self.data = [];
					console.log('It\'s saved!');
				});
			}catch( err ){
				//
			}
		});

	},
	readDataFile : function(){
		return fs.readFileSync(this.options.logfile, {'encoding': 'ascii'} );
	},
	sendDataUpdate: function(){
		var self = this;

		if( self.data.length === 0 ){
			return;
		}

		var postData = {
			payload: {
				value: JSON.stringify(self.data),
				content_type: 'application/json'
			}
		};

		needle.post( self.options.endpointUrl, postData, { timeout: self.options.timeout, multipart: true },
			function (error, response, body) {
				if (error || response.statusCode != 200) {
					/* We've got an error to deal with, let's set the error code till we get a successful send */
					self.txError = true;

					console.log('Error: ' + error);
					console.log('Response: ' + response);

				}else{
					self.txError = false;
				}
			}
		);
	}
};

var DataPointModel = {
	create: function(timestamp, data){
		return [timestamp, data];
	}
};

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
	response.writeHead( 200, {
		'Content-Type': 'application/json'
	});

	response.end( DataLogger.readDataFile() );
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

DataLogger.init( '../data/readings.data' );

/* Open the spi device */
spiADC.open();
/* Start reading the data from the spi device every XX ms */
setInterval( function(){ spiADC.read(); }, 1 / spiADC.options.resistances_to_keep);
/* Let's get an average every XX ms */
setInterval( function(){
	var averageData = spiADC.getAverageData();
	var averageTemp = Math.round( spiADC.getAverageTemperature( averageData ) * 100 ) / 100;
	var model = DataPointModel.create( Math.round(new Date().getTime() / 1000), averageTemp );
	DataLogger.addDataPoint(model);
}, 1000);
/* Write the data we've captured to the data file and send our updates to the web app */
setInterval( function(){
	DataLogger.sendDataUpdate();
	DataLogger.writeDataToFile();
}, 20000);
<commit_msg>cleaning up spi object references<commit_after>// Some bootstrapping
// Let's serve up the data file via json
var http = require( 'http' );
// Let's get the filestream api to write the temp data
var fs = require( 'fs' );
// Let's get the GPIO api for the rpi
var gpio = require( 'rpi-gpio' );
// Global request object for http get/post
var needle = require('needle');
// Global SPI object
var spi = require( 'spi' );

var spiADC = {
	'options': {
		'channel': 0,
		'spiMaxSpeed': 20000,
		'resistances_to_keep': 100,
		'ignore_data_beyond_pct': 0.05
	},
	'SPI': spi,
	'isOpen': false,
	'device': '',
	'resistances': [],
	'res_index': 0,
	'series_resistor': 9860,
	'thermistor': {
		'nominal_resistance': 10000,
		'nominal_temp': 25,
		'bcoefficient': 3950,
		'calibration_offset': 0
	},
	open: function(){
		if(this.isOpen === true){
			console.log( 'Cannot open a device that is already open!' );
			return;
		}

		this.device = new this.SPI.Spi('/dev/spidev0.0', {'maxSpeed': this.options.spiMaxSpeed}, function(s){s.open();});

		this.isOpen = true;
	},
	handleSpiData: function(device, buf){

		var data = ((buf[1]&3) << 8) + buf[2];

		// Let's exclude data readings that are 0
		// and readings that are more than +/- 5% of the previous reading (indicates a spike we should ignore)
		if( data === 0 || Math.abs( ( data - this.resistances[this.resistances.length-1] ) / this.resistances[this.resistances.length-1] ) > this.options.ignore_data_beyond_pct ){
			// Let's discard this reading
			return -1;
		}
		return data;
	},
	storeSpiData: function( device, data ){
		this.resistances[this.res_index] = data;
	},
	setNextResistanceIndex: function(){
		this.res_index++;
		if(this.res_index >= (this.options.resistances_to_keep -1) ){
			this.res_index = 0;
		}
	},
	read: function(){
		var self = this;
		var txbuf = new Buffer([1, (8 + this.options.channel) << 4, 0]);
		var rxbuf = new Buffer([ 0x00, 0x00, 0x00 ]);

		this.device.transfer( txbuf, rxbuf, function( device, buf ){
			var data = self.handleSpiData( device, buf );

			if( data > 0 ){
				self.storeSpiData( device, data );
				self.setNextResistanceIndex();
			}
		});
	},
	getAverageData: function(){
		if( this.resistances.length === 0 ){
			return 0;
		}

		var sum = 0;
		for(var i = 0; i < this.resistances.length; i++){
			sum += parseFloat(this.resistances[i]);
		}

		return sum / this.resistances.length + this.thermistor.calibration_offset;

	},
	calculate_thermistor_resistance: function( average_raw ){
		console.log('average raw: ' + average_raw);

		var thermistor_resistance =  (1023 / average_raw) - 1;
		thermistor_resistance = this.series_resistor / thermistor_resistance;

		return thermistor_resistance;
	},
	steinhart: function( thermistor_resistance ){
		var steinhart = thermistor_resistance / this.thermistor.nominal_resistance;

		steinhart = Math.log( steinhart );
		steinhart = steinhart / this.thermistor.bcoefficient;
		steinhart += 1.0 / (this.thermistor.nominal_temp + 273.15);
		steinhart = 1.0 / steinhart;
		steinhart -= 273.15;

		return steinhart;
	},
	getAverageTemperature: function( average_resistance) {
		var thermistor_resistance = this.calculate_thermistor_resistance( average_resistance );
		var steinhart = this.steinhart( thermistor_resistance );

		console.log('thermistor resistance: ' + thermistor_resistance);
		console.log('thermistor temperature: ' + Math.round( steinhart * 100 ) / 100);

		return steinhart;
	}
};
var DataLogger = {
	'options': {
		'logfile': '',
		'endpointUrl': 'http://192.168.1.126/dev/test.php',
		'timeout': 5000
	},
	'txError': false,
	'data': [],
	init: function(logfile){
		this.options.logfile = logfile;
		// Return this object to be used once init'd
		return this;
	},
	addDataPoint: function(model){
		this.data.push(model);
	},
	writeDataToFile : function(){
		if( this.txError ) {
			return;
		}

		/* First load in the file contents */
		var self = this;
		fs.readFile(self.options.logfile, {'encoding': 'ascii'}, function (err, data) {
			if (err){
				throw err;
			}

			try{
				var fileData = [];

				if( data !== null && data !== '' ){
					fileData = JSON.parse(data);
				}

				var combinedData = fileData.concat(self.data);

				fs.writeFile(self.options.logfile, JSON.stringify(combinedData), { 'flag' : 'r+'}, function (err) {
					if (err){
						console.log(err);
						throw err;
					}

					self.data = [];
					console.log('It\'s saved!');
				});
			}catch( err ){
				//
			}
		});

	},
	readDataFile : function(){
		return fs.readFileSync(this.options.logfile, {'encoding': 'ascii'} );
	},
	sendDataUpdate: function(){
		var self = this;

		if( self.data.length === 0 ){
			return;
		}

		var postData = {
			payload: {
				value: JSON.stringify(self.data),
				content_type: 'application/json'
			}
		};

		needle.post( self.options.endpointUrl, postData, { timeout: self.options.timeout, multipart: true },
			function (error, response, body) {
				if (error || response.statusCode != 200) {
					/* We've got an error to deal with, let's set the error code till we get a successful send */
					self.txError = true;

					console.log('Error: ' + error);
					console.log('Response: ' + response);

				}else{
					self.txError = false;
				}
			}
		);
	}
};

var DataPointModel = {
	create: function(timestamp, data){
		return [timestamp, data];
	}
};

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
	response.writeHead( 200, {
		'Content-Type': 'application/json'
	});

	response.end( DataLogger.readDataFile() );
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

DataLogger.init( '../data/readings.data' );

/* Open the spi device */
spiADC.open();
/* Start reading the data from the spi device every XX ms */
setInterval( function(){ spiADC.read(); }, 1 / spiADC.options.resistances_to_keep);
/* Let's get an average every XX ms */
setInterval( function(){
	var averageData = spiADC.getAverageData();
	var averageTemp = Math.round( spiADC.getAverageTemperature( averageData ) * 100 ) / 100;
	var model = DataPointModel.create( Math.round(new Date().getTime() / 1000), averageTemp );
	DataLogger.addDataPoint(model);
}, 3000);
/* Write the data we've captured to the data file and send our updates to the web app */
setInterval( function(){
	DataLogger.sendDataUpdate();
	DataLogger.writeDataToFile();
}, 20000);
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	defaultAssets = require('./config/assets/default'),
	testAssets = require('./config/assets/test'),
	gulp = require('gulp'),
	gulpLoadPlugins = require('gulp-load-plugins'),
	runSequence = require('run-sequence'),
	plugins = gulpLoadPlugins();

// Set NODE_ENV to 'test'
gulp.task('env:test', function () {
	process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
	process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function () {
	process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function () {
	return plugins.nodemon({
		script: 'server.js',
		nodeArgs: ['--debug'],
		ext: 'js,html',
		watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
	});
});

// Watch Files For Changes
gulp.task('watch', function() {
	// Start livereload
	plugins.livereload.listen();

	// Add watch rules
	gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.server.allJS, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.js, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.livereload.changed);
});

// CSS linting task
gulp.task('csslint', function (done) {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.csslint('.csslintrc'))
		.pipe(plugins.csslint.reporter())
		.pipe(plugins.csslint.reporter(function (file) {
			if (!file.csslint.errorCount) {
				done();
			}
		}));
});

// JS linting task
gulp.task('jshint', function () {
	return gulp.src(_.union(defaultAssets.server.allJS, defaultAssets.client.js, testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e))
		.pipe(plugins.jshint())
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.jshint.reporter('fail'));
});

// JS minifying task
gulp.task('uglify', function () {
	return gulp.src(defaultAssets.client.js)
		.pipe(plugins.ngAnnotate())
		.pipe(plugins.uglify({
			mangle: false
		}))
		.pipe(plugins.concat('application.min.js'))
		.pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function () {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.cssmin())
		.pipe(plugins.concat('application.min.css'))
		.pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function () {
	return gulp.src(defaultAssets.client.sass)
		.pipe(plugins.sass())
		.pipe(plugins.rename(function (path) {
			path.dirname = path.dirname.replace('/scss', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
	return gulp.src(defaultAssets.client.less)
		.pipe(plugins.less())
		.pipe(plugins.rename(function (path) {
			path.dirname = path.dirname.replace('/less', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Connect to MongoDB using the mongoose module
gulp.task('openMongoose', function (done) {
	var mongoose = require('./config/lib/mongoose.js');

	mongoose.connect(function() {
		done();
	});
});

gulp.task('closeMongoose', function (done) {
	var mongoose = require('./config/lib/mongoose.js');

	mongoose.disconnect(function(err) {
		done(err);
	});
});

// Mocha tests task
gulp.task('mocha', function () {
	return gulp.src(testAssets.tests.server)
		.pipe(plugins.mocha({
			reporter: 'spec'
		}));
});

// Karma test runner task
gulp.task('karma', function (done) {
	return gulp.src([])
		.pipe(plugins.karma({
			configFile: 'karma.conf.js',
			action: 'run',
			singleRun: true
		}))
		.on('error', function (err) {
			// Make sure failed tests cause gulp to exit non-zero
			throw err;
		});
});

// Selenium standalone WebDriver update task
gulp.task('webdriver-update', plugins.protractor.webdriver_update);

// Protractor test runner task
gulp.task('protractor', function () {
	gulp.src([])
		.pipe(plugins.protractor.protractor({
			configFile: "protractor.conf.js"
		}))
		.on('error', function (e) {
			throw e
		})
});

// Lint CSS and JavaScript files.
gulp.task('lint', function(done) {
	runSequence('less', 'sass', ['csslint', 'jshint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function(done) {
	runSequence('env:dev' ,'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function(done) {
	runSequence('env:test', 'openMongoose', ['karma', 'mocha'], 'closeMongoose', done);
});

// Run the project in development mode
gulp.task('default', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in debug mode
gulp.task('debug', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function(done) {
	runSequence('build', 'lint', ['nodemon', 'watch'], done);
});
<commit_msg>#450 Now the mocha task synchronously calls mongoose connect and disconnect.<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	defaultAssets = require('./config/assets/default'),
	testAssets = require('./config/assets/test'),
	gulp = require('gulp'),
	gulpLoadPlugins = require('gulp-load-plugins'),
	runSequence = require('run-sequence'),
	plugins = gulpLoadPlugins();

// Set NODE_ENV to 'test'
gulp.task('env:test', function () {
	process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function () {
	process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function () {
	process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function () {
	return plugins.nodemon({
		script: 'server.js',
		nodeArgs: ['--debug'],
		ext: 'js,html',
		watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
	});
});

// Watch Files For Changes
gulp.task('watch', function() {
	// Start livereload
	plugins.livereload.listen();

	// Add watch rules
	gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.server.allJS, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.js, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.livereload.changed);
});

// CSS linting task
gulp.task('csslint', function (done) {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.csslint('.csslintrc'))
		.pipe(plugins.csslint.reporter())
		.pipe(plugins.csslint.reporter(function (file) {
			if (!file.csslint.errorCount) {
				done();
			}
		}));
});

// JS linting task
gulp.task('jshint', function () {
	return gulp.src(_.union(defaultAssets.server.allJS, defaultAssets.client.js, testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e))
		.pipe(plugins.jshint())
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.jshint.reporter('fail'));
});

// JS minifying task
gulp.task('uglify', function () {
	return gulp.src(defaultAssets.client.js)
		.pipe(plugins.ngAnnotate())
		.pipe(plugins.uglify({
			mangle: false
		}))
		.pipe(plugins.concat('application.min.js'))
		.pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function () {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.cssmin())
		.pipe(plugins.concat('application.min.css'))
		.pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function () {
	return gulp.src(defaultAssets.client.sass)
		.pipe(plugins.sass())
		.pipe(plugins.rename(function (path) {
			path.dirname = path.dirname.replace('/scss', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function () {
	return gulp.src(defaultAssets.client.less)
		.pipe(plugins.less())
		.pipe(plugins.rename(function (path) {
			path.dirname = path.dirname.replace('/less', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Mocha tests task
gulp.task('mocha', function (done) {
	// Open mongoose connections
	var mongoose = require('./config/lib/mongoose.js');

	var error;
	mongoose.connect(function() {
		gulp.src(testAssets.tests.server)
			.pipe(plugins.mocha({
				reporter: 'spec'
			}))
			.on('error', function (err) {
				error = new Error('Mocha tests failed');
			}).on('end', function() {
				mongoose.disconnect(function(){
					done(error);
				});
			});
	});

});

// Karma test runner task
gulp.task('karma', function (done) {
	return gulp.src([])
		.pipe(plugins.karma({
			configFile: 'karma.conf.js',
			action: 'run',
			singleRun: true
		}));
});

// Selenium standalone WebDriver update task
gulp.task('webdriver-update', plugins.protractor.webdriver_update);

// Protractor test runner task
gulp.task('protractor', function () {
	gulp.src([])
		.pipe(plugins.protractor.protractor({
			configFile: "protractor.conf.js"
		}))
		.on('error', function (e) {
			throw e
		})
});

// Lint CSS and JavaScript files.
gulp.task('lint', function(done) {
	runSequence('less', 'sass', ['csslint', 'jshint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function(done) {
	runSequence('env:dev' ,'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function(done) {
	runSequence('env:test', ['karma', 'mocha'], done);
});

// Run the project in development mode
gulp.task('default', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in debug mode
gulp.task('debug', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function(done) {
	runSequence('build', 'lint', ['nodemon', 'watch'], done);
});
<|endoftext|>


<commit_before>'use strict';

exports.info = {
	url: '/test_case',
	method: 'get'
};

exports.preMiddleware = [
	'pre-middleware3',
	[
		'pre-middleware4',
		{
			string: 'middlewareOptionString'
		}
	]
];

exports.postMiddleware = [
	'post-middleware2'
];

exports.main = function(req, res, next) {
	res.send('');
	next();
};
<commit_msg>Test case fixed<commit_after>'use strict';

exports.info = {
	url: '/test_case',
	method: 'get'
};

exports.preMiddleware = [
	'pre-middleware3',
	{
		name: 'pre-middleware4',
		options: {
			string: 'middlewareOptionString'
		}
	}
];

exports.postMiddleware = [
	'post-middleware2'
];

exports.main = function(req, res, next) {
	res.send('');
	next();
};
<|endoftext|>


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

  // Dependencies
  const babel = require('gulp-babel');
  const ghPages = require('gulp-gh-pages');
  const gulp = require('gulp');
  const gulpif = require('gulp-if');
  const mergeStream = require('merge-stream');
  const PolymerProject = require('polymer-build').PolymerProject;
  const uglify = require('gulp-uglify');

  /**
   * The Polymer Project is a programmatic interface to the Polymer-cli objects.
   *
   * This is done because their usual wrapper "polymer serve" and "polymer build" are not properly handling
   * es2015 style javascript. They will eventually process it, but for the moment we use Babel to pre transpile
   * all the code before sending it to the rest of the pathway.
   */
  const project = new PolymerProject({
    entrypoint: 'index.html',
    shell: 'src/c1d3r-app/c1d3r-app.html',
    sources: [
      "src/**/*",
      "bower.json"
    ],
    includeDependencies: [
      "bower_components/webcomponentsjs/webcomponents-lite.min.js",
      "manifest.json",
      "images/**/*",
      "data/**/*"
    ]
  });

  gulp.task('build', () => {
    //noinspection JSCheckFunctionSignatures
    const sourcesStream = project.sources()
        .pipe(project.splitHtml())
        .pipe(gulpif(/\.js$/, babel({presets: ['es2015']})))
        .pipe(project.rejoinHtml());

    mergeStream(sourcesStream, project.dependencies())
        .pipe(project.analyzer)
        .pipe(project.bundler)
        .pipe(gulp.dest('build/bundled'));
  });

  gulp.task('deploy', () => {
    return gulp.src('./build/bundled/**/*')
        .pipe(ghPages());
  });
})();
<commit_msg>Put back gulp to es5<commit_after>(function() {
  'use strict';

  // Dependencies
  const babel = require('gulp-babel');
  const ghPages = require('gulp-gh-pages');
  const gulp = require('gulp');
  const gulpif = require('gulp-if');
  const mergeStream = require('merge-stream');
  const PolymerProject = require('polymer-build').PolymerProject;
  const uglify = require('gulp-uglify');

  /**
   * The Polymer Project is a programmatic interface to the Polymer-cli objects.
   *
   * This is done because their usual wrapper "polymer serve" and "polymer build" are not properly handling
   * es2015 style javascript. They will eventually process it, but for the moment we use Babel to pre transpile
   * all the code before sending it to the rest of the pathway.
   */
  const project = new PolymerProject({
    entrypoint: 'index.html',
    shell: 'src/c1d3r-app/c1d3r-app.html',
    sources: [
      "src/**/*",
      "bower.json"
    ],
    includeDependencies: [
      "bower_components/webcomponentsjs/webcomponents-lite.min.js",
      "manifest.json",
      "images/**/*",
      "data/**/*"
    ]
  });

  gulp.task('build', () => {
    //noinspection JSCheckFunctionSignatures
    const sourcesStream = project.sources()
        .pipe(project.splitHtml())
        .pipe(gulpif(/\.js$/, babel({presets: ['es2015']})))
        .pipe(project.rejoinHtml());

    mergeStream(sourcesStream, project.dependencies())
        .pipe(project.analyzer)
        .pipe(project.bundler)
        .pipe(gulp.dest('build/bundled'));
  });

  gulp.task('deploy', () => {
    return gulp.src('./build/bundled/**/*')
        .pipe(ghPages());
  });
})();
<|endoftext|>