<commit_before>// The MIT License (MIT)

// Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.com

// 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";

    var Typed = function(el, options) {

        // chosen element to manipulate text
        this.el = $(el);

        // options
        this.options = $.extend({}, $.fn.typed.defaults, options);

        // attribute to type into
        this.isInput = this.el.is('input');
        this.attr = this.options.attr;

        // show cursor
        this.showCursor = this.isInput ? false : this.options.showCursor;

        // text content of element
        this.elContent = this.attr ? this.el.attr(this.attr) : this.el.text()

        // html or plain text
        this.contentType = this.options.contentType;

        // typing speed
        this.typeSpeed = this.options.typeSpeed;

        // add a delay before typing starts
        this.startDelay = this.options.startDelay;

        // backspacing speed
        this.backSpeed = this.options.backSpeed;

        // amount of time to wait before backspacing
        this.backDelay = this.options.backDelay;

        // input strings of text
        this.strings = this.options.strings;

        // character number position of current string
        this.strPos = 0;

        // current array position
        this.arrayPos = 0;

        // number to stop backspacing on.
        // default 0, can change depending on how many chars
        // you want to remove at the time
        this.stopNum = 0;

        // Looping logic
        this.loop = this.options.loop;
        this.loopCount = this.options.loopCount;
        this.curLoop = 0;

        // for stopping
        this.stop = false;

        // custom cursor
        this.cursorChar = this.options.cursorChar;

        // All systems go!
        this.build();
    };

    Typed.prototype = {

        constructor: Typed

        ,
        init: function() {
            // begin the loop w/ first current string (global self.string)
            // current string will be passed as an argument each time after this
            var self = this;
            self.timeout = setTimeout(function() {
                // Start typing
                self.typewrite(self.strings[self.arrayPos], self.strPos);
            }, self.startDelay);
        }

        ,
        build: function() {
            // Insert cursor
            if (this.showCursor === true) {
                this.cursor = $("" + this.cursorChar + "");
                this.el.after(this.cursor);
            }
            this.init();
        }

        // pass current string state to each function, types 1 char per call
        ,
        typewrite: function(curString, curStrPos) {
            // exit when stopped
            if (this.stop === true) {
                return;
            }

            // varying values for setTimeout during typing
            // can't be global since number changes each time loop is executed
            var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed;
            var self = this;

            // ------------- optional ------------- //
            // backpaces a certain string faster
            // ------------------------------------ //
            // if (self.arrayPos == 1){
            //  self.backDelay = 50;
            // }
            // else{ self.backDelay = 500; }

            // contain typing function in a timeout humanize'd delay
            self.timeout = setTimeout(function() {
                // check for an escape character before a pause value
                // format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^
                // single ^ are removed from string
                var charPause = 0;
                var substr = curString.substr(curStrPos);
                if (substr.charAt(0) === '^') {
                    var skip = 1; // skip atleast 1
                    if (/^\^\d+/.test(substr)) {
                        substr = /\d+/.exec(substr)[0];
                        skip += substr.length;
                        charPause = parseInt(substr);
                    }

                    // strip out the escape character and pause value so they're not printed
                    curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip);
                }

                if (self.contentType === 'html') {
                    // skip over html tags while typing
                    if (curString.substr(curStrPos).charAt(0) === '<') {
                        var tag = '';
                        while (curString.substr(curStrPos).charAt(0) !== '>') {
                            tag += curString.substr(curStrPos).charAt(0);
                            curStrPos++;
                        }
                        curStrPos++;
                        tag += '>';
                    }
                }

                // timeout for any pause after a character
                self.timeout = setTimeout(function() {
                    if (curStrPos === curString.length) {
                        // fires callback function
                        self.options.onStringTyped(self.arrayPos);

                        // is this the final string
                        if (self.arrayPos === self.strings.length - 1) {
                            // animation that occurs on the last typed string
                            self.options.callback();

                            self.curLoop++;

                            // quit if we wont loop back
                            if (self.loop === false || self.curLoop === self.loopCount)
                                return;
                        }

                        self.timeout = setTimeout(function() {
                            self.backspace(curString, curStrPos);
                        }, self.backDelay);
                    } else {

                        /* call before functions if applicable */
                        if (curStrPos === 0)
                            self.options.preStringTyped(self.arrayPos);

                        // start typing each new char into existing string
                        // curString: arg, self.el.html: original text inside element
                        var nextString = self.elContent + curString.substr(0, curStrPos + 1);
                        if (self.attr) {
                            self.el.attr(self.attr, nextString);
                        } else {
                            if (self.el.attr('type')) {
                                self.el.val(nextString);
                            } else if (self.contentType === 'html') {
                                self.el.html(nextString);
                            } else {
                                self.el.text(nextString);
                            }
                        }

                        // add characters one by one
                        curStrPos++;
                        // loop the function
                        self.typewrite(curString, curStrPos);
                    }
                    // end of character pause
                }, charPause);

                // humanized value for typing
            }, humanize);

        }

        ,
        backspace: function(curString, curStrPos) {
            // exit when stopped
            if (this.stop === true) {
                return;
            }

            // varying values for setTimeout during typing
            // can't be global since number changes each time loop is executed
            var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed;
            var self = this;

            self.timeout = setTimeout(function() {

                // ----- this part is optional ----- //
                // check string array position
                // on the first string, only delete one word
                // the stopNum actually represents the amount of chars to
                // keep in the current string. In my case it's 14.
                // if (self.arrayPos == 1){
                //  self.stopNum = 14;
                // }
                //every other time, delete the whole typed string
                // else{
                //  self.stopNum = 0;
                // }

                if (self.contentType === 'html') {
                    // skip over html tags while backspacing
                    if (curString.substr(curStrPos).charAt(0) === '>') {
                        var tag = '';
                        while (curString.substr(curStrPos).charAt(0) !== '<') {
                            tag -= curString.substr(curStrPos).charAt(0);
                            curStrPos--;
                        }
                        curStrPos--;
                        tag += '<';
                    }
                }

                // ----- continue important stuff ----- //
                // replace text with base text + typed characters
                var nextString = self.elContent + curString.substr(0, curStrPos);
                if (self.attr) {
                    self.el.attr(self.attr, nextString);
                } else {
                    if (self.el.attr('type')) {
                        self.el.val(nextString);
                    } else if (self.contentType === 'html') {
                        self.el.html(nextString);
                    } else {
                        self.el.text(nextString);
                    }
                }

                // if the number (id of character in current string) is
                // less than the stop number, keep going
                if (curStrPos > self.stopNum) {
                    // subtract characters one by one
                    curStrPos--;
                    // loop the function
                    self.backspace(curString, curStrPos);
                }
                // if the stop number has been reached, increase
                // array position to next string
                else if (curStrPos <= self.stopNum) {
                    self.arrayPos++;

                    if (self.arrayPos === self.strings.length) {
                        self.arrayPos = 0;
                        self.init();
                    } else
                        self.typewrite(self.strings[self.arrayPos], curStrPos);
                }

                // humanized value for typing
            }, humanize);

        }

        // Start & Stop currently not working

        // , stop: function() {
        //     var self = this;

        //     self.stop = true;
        //     clearInterval(self.timeout);
        // }

        // , start: function() {
        //     var self = this;
        //     if(self.stop === false)
        //        return;

        //     this.stop = false;
        //     this.init();
        // }

        // Reset and rebuild the element
        ,
        reset: function() {
            var self = this;
            clearInterval(self.timeout);
            var id = this.el.attr('id');
            this.el.after('')
            this.el.remove();
            this.cursor.remove();
            // Send the callback
            self.options.resetCallback();
        }

    };

    $.fn.typed = function(option) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('typed'),
                options = typeof option == 'object' && option;
            if (!data) $this.data('typed', (data = new Typed(this, options)));
            if (typeof option == 'string') data[option]();
        });
    };

    $.fn.typed.defaults = {
        strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
        // typing speed
        typeSpeed: 0,
        // time before typing starts
        startDelay: 0,
        // backspacing speed
        backSpeed: 0,
        // time before backspacing
        backDelay: 500,
        // loop
        loop: false,
        // false = infinite
        loopCount: false,
        // show cursor
        showCursor: true,
        // character for cursor
        cursorChar: "|",
        // attribute to type (null == text)
        attr: null,
        // either html or text
        contentType: 'html',
        // call when done callback function
        callback: function() {},
        // starting callback function before each string
        preStringTyped: function() {},
        //callback for every typed string
        onStringTyped: function() {},
        // callback for reset
        resetCallback: function() {}
    };

}(window.jQuery);
<commit_msg>Noticed that the check for an input field is already happening and used that check when applying typewriter text to input.<commit_after>// The MIT License (MIT)

// Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.com

// 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";

    var Typed = function(el, options) {

        // chosen element to manipulate text
        this.el = $(el);

        // options
        this.options = $.extend({}, $.fn.typed.defaults, options);

        // attribute to type into
        this.isInput = this.el.is('input');
        this.attr = this.options.attr;

        // show cursor
        this.showCursor = this.isInput ? false : this.options.showCursor;

        // text content of element
        this.elContent = this.attr ? this.el.attr(this.attr) : this.el.text()

        // html or plain text
        this.contentType = this.options.contentType;

        // typing speed
        this.typeSpeed = this.options.typeSpeed;

        // add a delay before typing starts
        this.startDelay = this.options.startDelay;

        // backspacing speed
        this.backSpeed = this.options.backSpeed;

        // amount of time to wait before backspacing
        this.backDelay = this.options.backDelay;

        // input strings of text
        this.strings = this.options.strings;

        // character number position of current string
        this.strPos = 0;

        // current array position
        this.arrayPos = 0;

        // number to stop backspacing on.
        // default 0, can change depending on how many chars
        // you want to remove at the time
        this.stopNum = 0;

        // Looping logic
        this.loop = this.options.loop;
        this.loopCount = this.options.loopCount;
        this.curLoop = 0;

        // for stopping
        this.stop = false;

        // custom cursor
        this.cursorChar = this.options.cursorChar;

        // All systems go!
        this.build();
    };

    Typed.prototype = {

        constructor: Typed

        ,
        init: function() {
            // begin the loop w/ first current string (global self.string)
            // current string will be passed as an argument each time after this
            var self = this;
            self.timeout = setTimeout(function() {
                // Start typing
                self.typewrite(self.strings[self.arrayPos], self.strPos);
            }, self.startDelay);
        }

        ,
        build: function() {
            // Insert cursor
            if (this.showCursor === true) {
                this.cursor = $("" + this.cursorChar + "");
                this.el.after(this.cursor);
            }
            this.init();
        }

        // pass current string state to each function, types 1 char per call
        ,
        typewrite: function(curString, curStrPos) {
            // exit when stopped
            if (this.stop === true) {
                return;
            }

            // varying values for setTimeout during typing
            // can't be global since number changes each time loop is executed
            var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed;
            var self = this;

            // ------------- optional ------------- //
            // backpaces a certain string faster
            // ------------------------------------ //
            // if (self.arrayPos == 1){
            //  self.backDelay = 50;
            // }
            // else{ self.backDelay = 500; }

            // contain typing function in a timeout humanize'd delay
            self.timeout = setTimeout(function() {
                // check for an escape character before a pause value
                // format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^
                // single ^ are removed from string
                var charPause = 0;
                var substr = curString.substr(curStrPos);
                if (substr.charAt(0) === '^') {
                    var skip = 1; // skip atleast 1
                    if (/^\^\d+/.test(substr)) {
                        substr = /\d+/.exec(substr)[0];
                        skip += substr.length;
                        charPause = parseInt(substr);
                    }

                    // strip out the escape character and pause value so they're not printed
                    curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip);
                }

                if (self.contentType === 'html') {
                    // skip over html tags while typing
                    if (curString.substr(curStrPos).charAt(0) === '<') {
                        var tag = '';
                        while (curString.substr(curStrPos).charAt(0) !== '>') {
                            tag += curString.substr(curStrPos).charAt(0);
                            curStrPos++;
                        }
                        curStrPos++;
                        tag += '>';
                    }
                }

                // timeout for any pause after a character
                self.timeout = setTimeout(function() {
                    if (curStrPos === curString.length) {
                        // fires callback function
                        self.options.onStringTyped(self.arrayPos);

                        // is this the final string
                        if (self.arrayPos === self.strings.length - 1) {
                            // animation that occurs on the last typed string
                            self.options.callback();

                            self.curLoop++;

                            // quit if we wont loop back
                            if (self.loop === false || self.curLoop === self.loopCount)
                                return;
                        }

                        self.timeout = setTimeout(function() {
                            self.backspace(curString, curStrPos);
                        }, self.backDelay);
                    } else {

                        /* call before functions if applicable */
                        if (curStrPos === 0)
                            self.options.preStringTyped(self.arrayPos);

                        // start typing each new char into existing string
                        // curString: arg, self.el.html: original text inside element
                        var nextString = self.elContent + curString.substr(0, curStrPos + 1);
                        if (self.attr) {
                            self.el.attr(self.attr, nextString);
                        } else {
                            if (self.isInput) {
                                self.el.val(nextString);
                            } else if (self.contentType === 'html') {
                                self.el.html(nextString);
                            } else {
                                self.el.text(nextString);
                            }
                        }

                        // add characters one by one
                        curStrPos++;
                        // loop the function
                        self.typewrite(curString, curStrPos);
                    }
                    // end of character pause
                }, charPause);

                // humanized value for typing
            }, humanize);

        }

        ,
        backspace: function(curString, curStrPos) {
            // exit when stopped
            if (this.stop === true) {
                return;
            }

            // varying values for setTimeout during typing
            // can't be global since number changes each time loop is executed
            var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed;
            var self = this;

            self.timeout = setTimeout(function() {

                // ----- this part is optional ----- //
                // check string array position
                // on the first string, only delete one word
                // the stopNum actually represents the amount of chars to
                // keep in the current string. In my case it's 14.
                // if (self.arrayPos == 1){
                //  self.stopNum = 14;
                // }
                //every other time, delete the whole typed string
                // else{
                //  self.stopNum = 0;
                // }

                if (self.contentType === 'html') {
                    // skip over html tags while backspacing
                    if (curString.substr(curStrPos).charAt(0) === '>') {
                        var tag = '';
                        while (curString.substr(curStrPos).charAt(0) !== '<') {
                            tag -= curString.substr(curStrPos).charAt(0);
                            curStrPos--;
                        }
                        curStrPos--;
                        tag += '<';
                    }
                }

                // ----- continue important stuff ----- //
                // replace text with base text + typed characters
                var nextString = self.elContent + curString.substr(0, curStrPos);
                if (self.attr) {
                    self.el.attr(self.attr, nextString);
                } else {
                    if (self.isInput) {
                        self.el.val(nextString);
                    } else if (self.contentType === 'html') {
                        self.el.html(nextString);
                    } else {
                        self.el.text(nextString);
                    }
                }

                // if the number (id of character in current string) is
                // less than the stop number, keep going
                if (curStrPos > self.stopNum) {
                    // subtract characters one by one
                    curStrPos--;
                    // loop the function
                    self.backspace(curString, curStrPos);
                }
                // if the stop number has been reached, increase
                // array position to next string
                else if (curStrPos <= self.stopNum) {
                    self.arrayPos++;

                    if (self.arrayPos === self.strings.length) {
                        self.arrayPos = 0;
                        self.init();
                    } else
                        self.typewrite(self.strings[self.arrayPos], curStrPos);
                }

                // humanized value for typing
            }, humanize);

        }

        // Start & Stop currently not working

        // , stop: function() {
        //     var self = this;

        //     self.stop = true;
        //     clearInterval(self.timeout);
        // }

        // , start: function() {
        //     var self = this;
        //     if(self.stop === false)
        //        return;

        //     this.stop = false;
        //     this.init();
        // }

        // Reset and rebuild the element
        ,
        reset: function() {
            var self = this;
            clearInterval(self.timeout);
            var id = this.el.attr('id');
            this.el.after('')
            this.el.remove();
            this.cursor.remove();
            // Send the callback
            self.options.resetCallback();
        }

    };

    $.fn.typed = function(option) {
        return this.each(function() {
            var $this = $(this),
                data = $this.data('typed'),
                options = typeof option == 'object' && option;
            if (!data) $this.data('typed', (data = new Typed(this, options)));
            if (typeof option == 'string') data[option]();
        });
    };

    $.fn.typed.defaults = {
        strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
        // typing speed
        typeSpeed: 0,
        // time before typing starts
        startDelay: 0,
        // backspacing speed
        backSpeed: 0,
        // time before backspacing
        backDelay: 500,
        // loop
        loop: false,
        // false = infinite
        loopCount: false,
        // show cursor
        showCursor: true,
        // character for cursor
        cursorChar: "|",
        // attribute to type (null == text)
        attr: null,
        // either html or text
        contentType: 'html',
        // call when done callback function
        callback: function() {},
        // starting callback function before each string
        preStringTyped: function() {},
        //callback for every typed string
        onStringTyped: function() {},
        // callback for reset
        resetCallback: function() {}
    };

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


<commit_before>'use strict';

var gulp = require('gulp');

var typescript = require('gulp-tsc');

var paths = {
    json: ['*.json', 'lib/**/*.json'],
    js: ['gulpfile.js'],
    ts: ['lib/**/*.ts'],
    tests: ['__tests__/**/*.ts']
};

gulp.task('clean', function () {
    var rimraf = require('gulp-rimraf');
    return gulp.src('dist', {read: false})
        .pipe(rimraf());
});

gulp.task('lint', function(){
    var jsonlint = require('gulp-jsonlint');
    var jshint = require('gulp-jshint');
    var tslint = require('gulp-tslint');

    gulp.src(paths.json)
        .pipe(jsonlint())
        .pipe(jsonlint.reporter());

    gulp.src(paths.js)
        .pipe(jshint())
        .pipe(jshint.reporter());

    gulp.src(paths.ts)
        .pipe(tslint(require('./tslint.json')))
        .pipe(tslint.report('verbose'));
});

gulp.task('compile', ['clean', 'lint'], function(){
    return gulp.src(paths.ts)
        .pipe(typescript())
        .pipe(gulp.dest('dist/'));
});

gulp.task('compile-tests', ['clean'], function(){
    return gulp.src(paths.tests)
        .pipe(typescript())
        .pipe(gulp.dest('dist/'));
});

gulp.task('jest', ['compile-tests'], function () {
    var jest = require('gulp-jest');
    return gulp.src('dist/__TESTS__/').pipe(jest({ rootDir: __dirname + '/dist' }));
});

gulp.task('default', ['compile', 'jest']);<commit_msg>Fix jest task<commit_after>'use strict';

var gulp = require('gulp');

var typescript = require('gulp-tsc');

var paths = {
    json: ['*.json', 'lib/**/*.json'],
    js: ['gulpfile.js'],
    ts: ['lib/**/*.ts'],
    tests: ['__tests__/**/*.ts']
};

gulp.task('clean', function () {
    var rimraf = require('gulp-rimraf');
    return gulp.src('dist', {read: false})
        .pipe(rimraf());
});

gulp.task('lint', function(){
    var jsonlint = require('gulp-jsonlint');
    var jshint = require('gulp-jshint');
    var tslint = require('gulp-tslint');

    gulp.src(paths.json)
        .pipe(jsonlint())
        .pipe(jsonlint.reporter());

    gulp.src(paths.js)
        .pipe(jshint())
        .pipe(jshint.reporter());

    gulp.src(paths.ts)
        .pipe(tslint(require('./tslint.json')))
        .pipe(tslint.report('verbose'));
});

gulp.task('compile', ['clean', 'lint'], function(){
    return gulp.src(paths.ts)
        .pipe(typescript())
        .pipe(gulp.dest('dist/'));
});

gulp.task('compile-tests', ['clean'], function(){
    return gulp.src(paths.tests)
        .pipe(typescript())
        .pipe(gulp.dest('dist/'));
});

gulp.task('jest', ['compile-tests'], function () {
    var jest = require('gulp-jest');
    return gulp.src('dist/__tests__/').pipe(jest({ rootDir: __dirname + '/dist' }));
});

gulp.task('default', ['compile', 'jest']);<|endoftext|>


<commit_before>module.exports = new Interface();

function Interface() {
	var env = new (require('./environment'))();

	this.compile = function(schema) {
		return SchemaInterface(env.compile(schema));
	};

	this.validate = env.validate.bind(env);

	this.getLastErrors = env.getLastErrors.bind(env);
	this.isLastValid = env.isLastValid.bind(env);

	this.environment = function() { return new Interface(); };

	require('./variables').apply(env);
	require('./types').apply(env);
	require('./validators').apply(env);

	require('./schemas').apply(env);
}

function SchemaInterface(schema) {
	var result = {};

	result.validate = schema.validate.bind(schema);
	result.getLastErrors = schema.getLastErrors.bind(schema);
	result.isLastValid = schema.isLastValid.bind(schema);

	return result;
}
<commit_msg>Fix caching<commit_after>module.exports = new Interface();

var schemas = {};

function Interface() {
	var env = new (require('./environment'))();

	this.compile = function(schema) {
		if (schema.id && schemas[schema.id]) { return schemas[schema.id]; }

		var sch = env.compile(schema);
		schemas[sch.id] = sch;
		return sch;
	};

	this.validate = env.validate.bind(env);

	this.getLastErrors = env.getLastErrors.bind(env);
	this.isLastValid = env.isLastValid.bind(env);

	this.environment = function() { return new Interface(); };

	require('./variables').apply(env);
	require('./types').apply(env);
	require('./validators').apply(env);

	require('./schemas').apply(env);
}

function SchemaInterface(schema) {
	var result = {};

	result.validate = schema.validate.bind(schema);
	result.getLastErrors = schema.getLastErrors.bind(schema);
	result.isLastValid = schema.isLastValid.bind(schema);

	return result;
}
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var jsonlint = require("gulp-jsonlint");
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var plumber = require('gulp-plumber');

gulp.task('static', function() {
    gulp.src('source/*.js')
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('json', function(cb) {
    gulp.src(["**/*.json", "!./node_modules/**/*.json"])
        .pipe(jsonlint())
        .pipe(jsonlint.reporter());
    cb();
});

gulp.task('test', function(cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function(err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function() {
            cb(mochaErr);
        });
});

gulp.task('default', ['json', 'static', 'test']);
<commit_msg>Set NODE_ENV inside Gulpfile<commit_after>'use strict';

var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var jsonlint = require("gulp-jsonlint");
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var plumber = require('gulp-plumber');

gulp.task('static', function() {
    gulp.src('source/*.js')
        .pipe(excludeGitignore())
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('json', ['set-test-env'], function(cb) {
    gulp.src(["**/*.json", "!./node_modules/**/*.json"])
        .pipe(jsonlint())
        .pipe(jsonlint.reporter());
    cb();
});

gulp.task('test', ['set-test-env'], function(cb) {
    var mochaErr;

    gulp.src('test/**/*.js')
        .pipe(plumber())
        .pipe(mocha({reporter: 'spec'}))
        .on('error', function(err) {
            mochaErr = err;
        })
        .pipe(istanbul.writeReports())
        .on('end', function() {
            cb(mochaErr);
        });
});

gulp.task('set-test-env', function(cb) {
    process.env.NODE_ENV = 'test';
    cb();
});

gulp.task('default', ['set-test-env', 'json', 'static', 'test']);
<|endoftext|>


<commit_before>/**
 * HTTP Basic Auth for Node.js
 *
 * @package basic
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var basic   = require('./basic');

/**
 * Export
 */
module.exports = function (handler) {
    // Default handler method
    if (typeof handler !== 'function') {
        handler = function (user, pass, callback) {
            callback(null);
        };
    }

    // Return middleware
    return function (req, res, callback) {
        var header = req.headers['Authorization'] || req.headers['authorization'];
        if (!header) callback(401);

        var auth = basic(header);
        handler(auth.username, auth.password, callback);
    };
};<commit_msg>Resolve lint errors<commit_after>/**
 * HTTP Basic Auth for Node.js
 *
 * @package basic
 * @author Andrew Sliwinski <andrew@diy.org>
 */

/**
 * Dependencies
 */
var basic   = require('./basic');

/**
 * Export
 */
module.exports = function (handler) {
    // Default handler method
    if (typeof handler !== 'function') {
        handler = function (user, pass, callback) {
            callback(null);
        };
    }

    // Return middleware
    return function (req, res, callback) {
        var header = req.headers.Authorization || req.headers.authorization;
        if (!header) callback(401);

        var auth = basic(header);
        handler(auth.username, auth.password, callback);
    };
};<|endoftext|>


<commit_before>var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence').use(gulp);

gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: 'app'
        }
    });
});

gulp.task('sass', function() {
    return gulp.src('app/scss/**/*/scss') //Source all files ending with.scss in scss directory and its subdirectories
      .pipe(sass())
      .pipe(gulp.dest('app/css'))
      .pipe(browserSync.reload({
          stream: true
      }))
});

gulp.task('useref', function() {
    return gulp.src('app/*.html') //Source all html files
      .pipe(useref())
      .pipe(gulpIf('*.js', uglify())) //Minifies only if it is js file
      .pipe(gulpIf('*.css', cssnano())) //Minifies only if it is css file
      .pipe(gulp.dest('dist'))
});

gulp.task('imagemin', function() {
    return gulp.src('app/images/**/*.+(png|jpg|gif|swg)')
      .pipe(cache(imagemin({
          gif: {
              interlaced: true
          }
      })))
      .pipe(gulp.dest('dist/images'))
});

gulp.task('fonts', function() {
    return gulp.src('app/fonts/**/*')
      .pipe(gulp.dest('dist/fonts'))
});

gulp.task('watch', ['browserSync', 'sass'], function() {
    gulp.watch('app/scss/**/*.scss', ['sass']);
    gulp.watch('app/*.html', browserSync.reload);
    gulp.watch('app/js/**/*.js', browserSync.reload);
});

gulp.task('clean:dist', function() {
    return  del.sync('dist');
});

gulp.task('default', function(callback) {
  runSequence(['sass', 'browserSync', 'watch'],
    callback
  );
});

gulp.task('build', function(callback) {
    runSequence('clean:dist', ['sass', 'useref', 'imagemin', 'fonts'], callback);
});
<commit_msg>del.sync update<commit_after>var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence').use(gulp);

gulp.task('browserSync', function() {
    browserSync.init({
        server: {
            baseDir: 'app'
        }
    });
});

gulp.task('sass', function() {
    return gulp.src('app/scss/**/*/scss') //Source all files ending with.scss in scss directory and its subdirectories
      .pipe(sass())
      .pipe(gulp.dest('app/css'))
      .pipe(browserSync.reload({
          stream: true
      }))
});

gulp.task('watch', function() {
    gulp.watch('app/scss/**/*.scss', ['sass']);
    gulp.watch('app/*.html', browserSync.reload);
    gulp.watch('app/js/**/*.js', browserSync.reload);
});

gulp.task('useref', function() {
    return gulp.src('app/*.html') //Source all html files
      .pipe(useref())
      .pipe(gulpIf('*.js', uglify())) //Minifies only if it is js file
      .pipe(gulpIf('*.css', cssnano())) //Minifies only if it is css file
      .pipe(gulp.dest('dist'))
});

gulp.task('imagemin', function() {
    return gulp.src('app/images/**/*.+(png|jpg|gif|swg)')
      .pipe(cache(imagemin({
          gif: {
              interlaced: true
          }
      })))
      .pipe(gulp.dest('dist/images'))
});

gulp.task('fonts', function() {
    return gulp.src('app/fonts/**/*')
      .pipe(gulp.dest('dist/fonts'))
});

gulp.task('clean:dist', function() {
    return  del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});

gulp.task('default', function(callback) {
  runSequence(['sass', 'browserSync', 'watch'],
    callback
  );
});

gulp.task('build', function(callback) {
    runSequence('clean:dist', ['sass', 'useref', 'imagemin', 'fonts'], callback);
});
<|endoftext|>


<commit_before>const get = require('get-value');
const chalk = require('chalk');
const merge = require('webpack-merge');
const stylelint = require('stylelint');
const isPlainObject = require('is-plain-object');
const moduleAvailable = require('module-available');

const plugin = {
    name: 'StylelintBarePlugin'
};

module.exports = class StylelintBarePlugin {
    constructor(options = {}) {
        if ( typeof options !== 'undefined' && !isPlainObject(options) ) {
            throw new Error(`${plugin.name} options should be an object`);
        }

        this.warnings = [];
        this.errors = [];
        this.shouldError = false;

        this.options = merge({
            files: '**/*.s?(c|a)ss',
            emitErrors: true,
            failOnError: false,
            formatter: (() => {
                if ( get(stylelint, 'formatters.string') ) {
                    return stylelint.formatters.string;
                } else if ( moduleAvailable('stylelint/dist/formatters/stringFormatter') ) {
                    return require('stylelint/dist/formatters/stringFormatter').default;
                }
            })()
        }, options);

        // Mutate option.files to array
        if ( !Array.isArray(this.options.files) ) {
            this.options.files = [this.options.files];
        }

        // Make sure the formatter is set up correctly
        if ( typeof this.options.formatter !== 'function' ) {
            throw new Error(`The formatter for ${plugin.name} is not of type 'function'`);
        }
    }

    lint(compilation, callback) {
        stylelint.lint(this.options).then((linter) => {
            this.warnings = linter.results.map((file) => {
                return Object.assign({}, file, {
                    warnings: file.warnings.filter((warning) => warning.severity === 'warning')
                });
            }).filter((file) => file.warnings.length);

            this.errors = linter.results.map((file) => {
                return Object.assign({}, file, {
                    warnings: file.warnings.filter((warning) => warning.severity === 'error')
                });
            }).filter((file) => file.warnings.length);

            this.shouldError = this.options.failOnError && this.errors.length;

            callback();
        }).catch((e) => {
            console.error(chalk.red(['', `Error in ${plugin.name}`].join('\n')));
            console.trace(chalk.red(e));
        });
    }

    report(compilation) {
        if ( this.options.emitErrors ) {
            compilation.errors.push(new Error(this.options.formatter(this.errors)));
            compilation.warnings.push(new Error(this.options.formatter(this.warnings)));
        } else {
            compilation.warnings.push(new Error(this.options.formatter(this.errors.concat(this.warnings))));
        }

        this.errors = [];
        this.warnings = [];
    }

    apply(compiler) {
        // Run the linter when required
        const linter = this.lint.bind(this);
        compiler.hooks.run.tapAsync(plugin, linter);
        compiler.hooks.watchRun.tapAsync(plugin, linter);

        const reporter = this.report.bind(this);
        const hook = this.options.emitErrors ? 'afterCompile' : 'afterEmit';
        compiler.hooks[hook].tap(plugin, reporter);

        compiler.hooks.done.tap(plugin, () => {
            if ( this.shouldError ) {
                // Throw in the next tick to make sure the webpack output
                // containing the linter warnings and errors is at least shown
                setTimeout(() => {
                    throw new Error('Failed because of a stylelint error.');
                });
            }
        })
    }
};
<commit_msg>Improves when warnings/errors get added to the webpack object<commit_after>const get = require('get-value');
const chalk = require('chalk');
const merge = require('webpack-merge');
const stylelint = require('stylelint');
const isPlainObject = require('is-plain-object');
const moduleAvailable = require('module-available');

const plugin = {
    name: 'StylelintBarePlugin'
};

module.exports = class StylelintBarePlugin {
    constructor(options = {}) {
        if ( typeof options !== 'undefined' && !isPlainObject(options) ) {
            throw new Error(`${plugin.name} options should be an object`);
        }

        this.warnings = [];
        this.errors = [];
        this.shouldError = false;

        this.options = merge({
            files: '**/*.s?(c|a)ss',
            emitErrors: true,
            failOnError: false,
            formatter: (() => {
                if ( get(stylelint, 'formatters.string') ) {
                    return stylelint.formatters.string;
                } else if ( moduleAvailable('stylelint/dist/formatters/stringFormatter') ) {
                    return require('stylelint/dist/formatters/stringFormatter').default;
                }
            })()
        }, options);

        // Mutate option.files to array
        if ( !Array.isArray(this.options.files) ) {
            this.options.files = [this.options.files];
        }

        // Make sure the formatter is set up correctly
        if ( typeof this.options.formatter !== 'function' ) {
            throw new Error(`The formatter for ${plugin.name} is not of type 'function'`);
        }
    }

    lint(compilation, callback) {
        stylelint.lint(this.options).then((linter) => {
            this.warnings = linter.results.map((file) => {
                return Object.assign({}, file, {
                    warnings: file.warnings.filter((warning) => warning.severity === 'warning')
                });
            }).filter((file) => file.warnings.length);

            this.errors = linter.results.map((file) => {
                return Object.assign({}, file, {
                    warnings: file.warnings.filter((warning) => warning.severity === 'error')
                });
            }).filter((file) => file.warnings.length);

            this.shouldError = this.options.failOnError && this.errors.length;

            callback();
        }).catch((e) => {
            console.error(chalk.red(['', `Error in ${plugin.name}`].join('\n')));
            console.trace(chalk.red(e));
        });
    }

    report(compilation) {
        if ( this.options.emitErrors ) {
            if ( this.errors.length ) {
                compilation.errors.push(new Error(this.options.formatter(this.errors)));
            }

            if ( this.warnings.length ) {
                compilation.warnings.push(new Error(this.options.formatter(this.warnings)));
            }
        } else {
            if ( this.warnings.length || this.errors.length ) {
                compilation.warnings.push(new Error(this.options.formatter(this.errors.concat(this.warnings))));
            }
        }

        this.errors = [];
        this.warnings = [];
    }

    apply(compiler) {
        const linter = this.lint.bind(this);
        compiler.hooks.run.tapAsync(plugin, linter);
        compiler.hooks.watchRun.tapAsync(plugin, linter);

        const reporter = this.report.bind(this);
        compiler.hooks[this.options.emitErrors ? 'afterCompile' : 'afterEmit'].tap(plugin, reporter);

        compiler.hooks.done.tap(plugin, () => {
            if ( this.shouldError ) {
                // Throw in the next tick to make sure the webpack output
                // containing the linter warnings and errors is at least shown
                setTimeout(() => {
                    throw new Error('Failed because of a stylelint error.');
                });
            }
        })
    }
};
<|endoftext|>


<commit_before>var gulp = require('gulp');
var sync = require('browser-sync');
var colors = require('colors');
var deploy = 'public';
var browser = 'google chrome';

gulp.task('tape', function () {
  var tape = require('gulp-tape');
  var tapColorize = require('tap-colorize');
  return gulp.src('test/*.js')
    .pipe(tape({
      reporter: tapColorize()
    }));
});

gulp.task('pug', function () {
  var pug = require('gulp-pug');
  return gulp.src('views/pug/*.pug')
    .pipe(pug())
    .pipe(gulp.dest(deploy));
});

gulp.task('riot', function () {
  var riot = require('gulp-riot');
  gulp.src('views/tag/*.tag')
      .pipe(riot())
      .pipe(gulp.dest(deploy));
});

gulp.task("babel", function () {
  var babel = require("gulp-babel");
  return gulp.src("app.js")
    .pipe(babel())
    .pipe(gulp.dest(deploy));
});

gulp.task('less', function () {
  var less = require('gulp-less');
  return gulp.src('views/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('views/css'));
});

gulp.task('img', function () {
  var imagemin = require('gulp-imagemin');
  return gulp.src('views/img/*')
    .pipe(imagemin())
    .pipe(gulp.dest(deploy + '/img'));
});

gulp.task('minify', function () {
  var cleancss = require('gulp-clean-css');
  return gulp.src('views/css/*.css')
    .pipe(cleancss())
    .pipe(gulp.dest('views/css'));
});

gulp.task('rename', function () {
  var rename = require('gulp-rename');
  return gulp.src('views/css/*.css')
    .pipe(rename({extname: '.min.css'}))
    .pipe(gulp.dest(deploy + '/css'));
});

gulp.task('bower', function () {
  var bower = require('gulp-bower');
  return bower('bower_modules/')
    .pipe(gulp.dest(deploy));
});

gulp.task('build', ['pug', 'less', 'rename'], function () {
  return console.log('Build Successful!'.green);
});

gulp.task('deploy', ['build', 'minify', 'img', 'bower'], function () {
  return console.log('Deploy Successful!'.green);
});

gulp.task('open', function () {
  var open = require('gulp-open');
  return gulp.src(['./'])
    .pipe(open({
      uri: 'http://localhost:8080/?port=5858',
      app: browser
    }));
});

gulp.task('inspector', ['sync'], function () {
  var inspector = require('gulp-node-inspector');
  gulp.src([])
    .pipe(inspector({
    saveLiveEdit: true,
    preload: true,
    inject: true
    }));
    console.log('Inspector Successful!'.green);
});

gulp.task('sync', ['build', 'nodemon', 'watch'], function () {
    sync.init({
      proxy: 'localhost:2000',
      port: 3000,
      ui: false,
      online: false,
      browser: browser
    });
});

gulp.task('watch', function () {
  gulp.watch('views/pug/*.pug', ['pug']);
  gulp.watch('views/less/*.less', ['less']);
  gulp.watch('views/css/*.css', ['rename']);
  gulp.watch(deploy + '/css/*.min.css').on('change', sync.reload);
  gulp.watch(deploy + '/*.html').on('change', sync.reload);
  gulp.watch(deploy + '/img/*').on('change', sync.reload);
  return console.log('Watch Successful!'.green);
});

gulp.task('nodemon', function (cb) {
  var nodemon = require('gulp-nodemon');
  var run = false;
  nodemon({
    script: './bin/www',
    ignore: ['./bower_modules', './public'],
    watch: [
      'app.js',
      'controllers/*.js',
      'models/*.js',
      'gulpfile.js'
    ],
    debug: true,
    verbose: true
  }).on('start', function () {
    if (!run) {
      cb();
      run = true;
      console.log("Nodemon Started!".green);
    }
  })
  .on('error', function (err) {
      throw err;
  });
});

gulp.task('karma', function (done) {
  var Server = require('karma').Server;
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

gulp.task('shell', function () {
  var shell = require('gulp-shell');
  return gulp.src('*.js', {read: false})
    .pipe(shell([
      'echo <%= f(file.path) %>',
      'ls -l <%= file.path %>'
    ], {
      templateData: {
        f: function (s) {
          return s.replace(/$/, '.bak');
        }
      }
    }));
});
<commit_msg>Change Const to Var<commit_after>/*jshint esnext: true */
const gulp = require('gulp');
const sync = require('browser-sync');
const colors = require('colors');
const deploy = 'public';
const browser = 'google chrome';

gulp.task('tape', function () {
  const tape = require('gulp-tape');
  const tapColorize = require('tap-colorize');
  return gulp.src('test/*.js')
    .pipe(tape({
      reporter: tapColorize()
    }));
});

gulp.task('pug', function () {
  const pug = require('gulp-pug');
  return gulp.src('views/pug/*.pug')
    .pipe(pug())
    .pipe(gulp.dest(deploy));
});

gulp.task('riot', function () {
  const riot = require('gulp-riot');
  gulp.src('views/tag/*.tag')
      .pipe(riot())
      .pipe(gulp.dest(deploy));
});

gulp.task("babel", function () {
  const babel = require("gulp-babel");
  return gulp.src("app.js")
    .pipe(babel())
    .pipe(gulp.dest(deploy));
});

gulp.task('less', function () {
  const less = require('gulp-less');
  return gulp.src('views/less/*.less')
    .pipe(less())
    .pipe(gulp.dest('views/css'));
});

gulp.task('img', function () {
  const imagemin = require('gulp-imagemin');
  return gulp.src('views/img/*')
    .pipe(imagemin())
    .pipe(gulp.dest(deploy + '/img'));
});

gulp.task('minify', function () {
  const cleancss = require('gulp-clean-css');
  return gulp.src('views/css/*.css')
    .pipe(cleancss())
    .pipe(gulp.dest('views/css'));
});

gulp.task('rename', function () {
  const rename = require('gulp-rename');
  return gulp.src('views/css/*.css')
    .pipe(rename({extname: '.min.css'}))
    .pipe(gulp.dest(deploy + '/css'));
});

gulp.task('bower', function () {
  const bower = require('gulp-bower');
  return bower('bower_modules/')
    .pipe(gulp.dest(deploy));
});

gulp.task('build', ['pug', 'less', 'rename'], function () {
  return console.log('Build Successful!'.green);
});

gulp.task('deploy', ['build', 'minify', 'img', 'bower'], function () {
  return console.log('Deploy Successful!'.green);
});

gulp.task('open', function () {
  const open = require('gulp-open');
  return gulp.src(['./'])
    .pipe(open({
      uri: 'http://localhost:8080/?port=5858',
      app: browser
    }));
});

gulp.task('inspector', ['sync'], function () {
  const inspector = require('gulp-node-inspector');
  gulp.src([])
    .pipe(inspector({
    saveLiveEdit: true,
    preload: true,
    inject: true
    }));
    console.log('Inspector Successful!'.green);
});

gulp.task('sync', ['build', 'nodemon', 'watch'], function () {
    sync.init({
      proxy: 'localhost:2000',
      port: 3000,
      ui: false,
      online: false,
      browser: browser
    });
});

gulp.task('watch', function () {
  gulp.watch('views/pug/*.pug', ['pug']);
  gulp.watch('views/less/*.less', ['less']);
  gulp.watch('views/css/*.css', ['rename']);
  gulp.watch(deploy + '/css/*.min.css').on('change', sync.reload);
  gulp.watch(deploy + '/*.html').on('change', sync.reload);
  gulp.watch(deploy + '/img/*').on('change', sync.reload);
  return console.log('Watch Successful!'.green);
});

gulp.task('nodemon', function (cb) {
  const nodemon = require('gulp-nodemon');
  var run = false;
  nodemon({
    script: './bin/www',
    ignore: ['./bower_modules', './public'],
    watch: [
      'app.js',
      'controllers/*.js',
      'models/*.js',
      'gulpfile.js'
    ],
    debug: true,
    verbose: true
  }).on('start', function () {
    if (!run) {
      cb();
      run = true;
      console.log("Nodemon Started!".green);
    }
  })
  .on('error', function (err) {
      throw err;
  });
});

gulp.task('karma', function (done) {
  const Server = require('karma').Server;
  new Server({
    configFile: __dirname + '/karma.conf.js',
    singleRun: true
  }, done).start();
});

gulp.task('shell', function () {
  const shell = require('gulp-shell');
  return gulp.src('*.js', {read: false})
    .pipe(shell([
      'echo <%= f(file.path) %>',
      'ls -l <%= file.path %>'
    ], {
      templateData: {
        f: function (s) {
          return s.replace(/$/, '.bak');
        }
      }
    }));
});
<|endoftext|>


<commit_before>'use strict';

var gutil = require('gulp-util');
var through2 = require('through2');
var minimatch = require('minimatch');
var async = require('async');
var _ = require('lodash');
var plur = require('plur');

var sharpVinyl = require('./sharp');
var prepareConfig = require('./config');

var PLUGIN_NAME = require('../package.json').name;

function gulpResponsive(config, options) {

  var statistics = {
    total: 0,
    matched: 0,
    created: 0,
    unmatched: 0,
    unmatchedBlocked: 0,
    unmatchedPassed: 0
  };

  options = _.defaults({}, options, {
    errorOnUnusedConfig: true,
    errorOnUnusedImage: true,
    errorOnEnlargement: true,
    passThroughUnused: false,
    silent: true,
    stats: true
  });

  config = prepareConfig(config || [], options);

  return through2.obj(function (file, enc, done) {
      var that = this;

      if (file.isNull()) {
        this.push(file);
        return done();
      }

      if (file.isStream()) {
        return done(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      }

      statistics.total++;
      var matched = config.filter(function(conf) {
        return minimatch(file.relative, conf.name);
      });

      if (matched.length === 0) {
        statistics.unmatched++;
        var message = 'File `' + file.relative + '`: Image does not match any config';
        if (options.errorOnUnusedImage) {
          return done(new gutil.PluginError(PLUGIN_NAME, message));
        } else if (options.passThroughUnused) {
          this.push(file);
          statistics.unmatchedPassed++;
          if (!options.silent){
            gutil.log(PLUGIN_NAME + ': (pass through without changes)', gutil.colors.magenta(message));
          }
          return done();
        }
        statistics.unmatchedBlocked++;
        if (!options.silent){
          gutil.log(PLUGIN_NAME + ': (skip for processing)', gutil.colors.magenta(message));
        }
        return done();
      }

      statistics.matched++;
      async.each(matched, function(conf, cb) {
        // config item matched (can be matched multiple times)
        conf.mathed = true;

        sharpVinyl(file, conf, options, function(err, newFile) {
          if (err) {
            return cb(err);
          }
          if (newFile) {
            that.push(newFile);
            statistics.created++;
          }
          cb();
        });
      }, done);
    }, function(cb) {
      var notMatched = config.filter(function(conf) {
        return !conf.mathed;
      });

      if (options.stats && !(options.silent && statistics.created === 0)){
        var msg =
          'Created ' + statistics.created + ' ' + plur('image', statistics.created) +
          gutil.colors.dim.white(' (matched ' + statistics.matched + ' of ' +
          statistics.total + ' ' + plur('image', statistics.total) + ')');

        gutil.log(PLUGIN_NAME + ':', gutil.colors.green(msg));
      }

      if (notMatched.length > 0 && (!options.silent || options.errorOnUnusedConfig)) {
        var message = 'Available images do not match the following config:';
        notMatched.forEach(function(conf) {
          message += '\n  - `' + conf.name + '`';
        });
        if (options.errorOnUnusedConfig) {
          return cb(new gutil.PluginError(PLUGIN_NAME, message));
        } else {
          gutil.log(PLUGIN_NAME + ':', gutil.colors.magenta(message));
        }
      }
      cb();
    }
  );
}

module.exports = gulpResponsive;
<commit_msg>Fix default silent option<commit_after>'use strict';

var gutil = require('gulp-util');
var through2 = require('through2');
var minimatch = require('minimatch');
var async = require('async');
var _ = require('lodash');
var plur = require('plur');

var sharpVinyl = require('./sharp');
var prepareConfig = require('./config');

var PLUGIN_NAME = require('../package.json').name;

function gulpResponsive(config, options) {

  var statistics = {
    total: 0,
    matched: 0,
    created: 0,
    unmatched: 0,
    unmatchedBlocked: 0,
    unmatchedPassed: 0
  };

  options = _.defaults({}, options, {
    errorOnUnusedConfig: true,
    errorOnUnusedImage: true,
    errorOnEnlargement: true,
    passThroughUnused: false,
    silent: false,
    stats: true
  });

  config = prepareConfig(config || [], options);

  return through2.obj(function (file, enc, done) {
      var that = this;

      if (file.isNull()) {
        this.push(file);
        return done();
      }

      if (file.isStream()) {
        return done(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
      }

      statistics.total++;
      var matched = config.filter(function(conf) {
        return minimatch(file.relative, conf.name);
      });

      if (matched.length === 0) {
        statistics.unmatched++;
        var message = 'File `' + file.relative + '`: Image does not match any config';
        if (options.errorOnUnusedImage) {
          return done(new gutil.PluginError(PLUGIN_NAME, message));
        } else if (options.passThroughUnused) {
          this.push(file);
          statistics.unmatchedPassed++;
          if (!options.silent){
            gutil.log(PLUGIN_NAME + ': (pass through without changes)', gutil.colors.magenta(message));
          }
          return done();
        }
        statistics.unmatchedBlocked++;
        if (!options.silent){
          gutil.log(PLUGIN_NAME + ': (skip for processing)', gutil.colors.magenta(message));
        }
        return done();
      }

      statistics.matched++;
      async.each(matched, function(conf, cb) {
        // config item matched (can be matched multiple times)
        conf.mathed = true;

        sharpVinyl(file, conf, options, function(err, newFile) {
          if (err) {
            return cb(err);
          }
          if (newFile) {
            that.push(newFile);
            statistics.created++;
          }
          cb();
        });
      }, done);
    }, function(cb) {
      var notMatched = config.filter(function(conf) {
        return !conf.mathed;
      });

      if (options.stats && !(options.silent && statistics.created === 0)){
        var msg =
          'Created ' + statistics.created + ' ' + plur('image', statistics.created) +
          gutil.colors.dim.white(' (matched ' + statistics.matched + ' of ' +
          statistics.total + ' ' + plur('image', statistics.total) + ')');

        gutil.log(PLUGIN_NAME + ':', gutil.colors.green(msg));
      }

      if (notMatched.length > 0 && (!options.silent || options.errorOnUnusedConfig)) {
        var message = 'Available images do not match the following config:';
        notMatched.forEach(function(conf) {
          message += '\n  - `' + conf.name + '`';
        });
        if (options.errorOnUnusedConfig) {
          return cb(new gutil.PluginError(PLUGIN_NAME, message));
        } else {
          gutil.log(PLUGIN_NAME + ':', gutil.colors.magenta(message));
        }
      }
      cb();
    }
  );
}

module.exports = gulpResponsive;
<|endoftext|>


<commit_before>// Dependencies
var request = require('request');

// Includes
var login = require('./util/login.js'),
  getSession = require('./util/getSession.js'),
  getCurrentUser = require('./util/getCurrentUser.js'),
  setRank = require('./setRank.js'),
  getRoles = require('./util/getRoles.js'),
  getToken = require('./util/getToken.js'),
  getInputs = require('./util/getInputs.js'),
  getVerificationInputs = require('./util/getVerificationInputs.js'),
  getRankInGroup = require('./util/getRankInGroup.js'),
  getRolesetInGroupWithJar = require('./util/getRolesetInGroupWithJar.js'),
  exile = require('./exile.js'),
  message = require('./message.js'),
  handleJoinRequest = require('./handleJoinRequest.js').handle,
  getRequestId = require('./handleJoinRequest.js').request,
  getUserId = require('./util/getUserId.js'),
  shout = require('./shout.js'),
  post = require('./post.js');

var cache = require('./cache/index.js');

var settings = require('../settings.json');

// Vars
var _jar = request.jar(); // Default cookie jar
var _cache = cache.new([{
  name: 'XCSRF',
  expire: settings.cache.XCSRF
}, {
  name: 'Roles',
  expire: settings.cache.Roles
}]);

// Define
function makeCallbackArray(options, success, failure, always) {
  return {success: options.success || success, failure: options.failure || failure, always: options.always || options.callback || always};
}

exports.login = function(options, password, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  login(options.jar || jar || _jar, options.username || options, options.password || password, callbacks);
};

exports.getSession = function(options) {
  getSession(options.jar || options || _jar);
};

exports.getCurrentUser = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getCurrentUser(options.jar || jar || _jar, options.option || typeof options === 'string' && options, callbacks);
};

exports.getRoles = function(options, rank, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRoles(options.group || options, options.rank || rank, callbacks);
};

exports.getToken = function(options, jar, callback, failure) {
  var callbacks = {failure: options.failure || failure};
  getToken(options.jar || jar || _jar, options.url || options, callback, callbacks);
};

function setRankMain(options, target, roleset, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var url = 'http://www.roblox.com/groups/api/change-member-rank?groupId=' + (options.group || options) + '&newRoleSetId=' + (options.roleset || roleset) + '&targetUserId=' + (options.target || target);
  var run = function(token) {
    setRank(jar, url, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'setRank', {
      done: run,
      add: function(done) {
        getToken(jar, url, done, callbacks);
      }
    });
  }
}

exports.setRank = function(options) {
  if (options.rank) {
    getRoles(options.group, options.rank, {success: function(role) {
      options.roleset = role;
      setRankMain(options);
    }, failure: options.failure});
  } else
    setRankMain.apply(undefined, arguments);
};

exports.message = function(options, subject, body, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var run = function(token) {
    message(jar, options.recipient || options, options.subject || subject, options.body || body, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'message', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/messages/send', done, callbacks);
      }
    });
  }
};

exports.shout = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  shout(options.jar || jar || _jar, options.group || options, options.message || message, callbacks);
};

exports.handleJoinRequest = function(options, username, accept, jar, token, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var form = {
    groupJoinRequestId: 0,
    accept: options.accept || accept
  };
  var run = function(token) {
    handleJoinRequest(jar, token, form, callbacks);
  };
  cache.addIf(_cache, 'XCSRF', 'handleJoinRequest', {
    done: run,
    add: function(done) {
      getRequestId(jar, options.group || options, options.username || username, function(id) {
        form.groupJoinRequestId = id;
        getToken(jar, 'http://www.roblox.com/group/handle-join-request', done, callbacks, form);
      }, callbacks);
    }
  });
};

exports.post = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  post(options.jar || jar || _jar, options.group, options.message, callbacks);
};

exports.getRankInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, callbacks);
};

exports.getRolesetInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, {success: function(rank) {
    getRoles(options.group, rank, callbacks);
  }, failure: callbacks.failure});
};

exports.getRolesetInGroupWithJar = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRolesetInGroupWithJar(options.jar || jar || _jar, options.group || options, callbacks);
};

function exileMain(options, json, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  var run = function(token) {
    exile(options.jar || jar || _jar, token, json, callbacks);
  };
  if (options.token || token)
    run(options.token || token);
  else {
    cache.addIf(_cache, 'XCSRF', 'exile', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/My/Groups.aspx/ExileUserAndDeletePosts', done, callbacks, undefined, json);
      }
    });
  }
}

exports.exile = function(options, target, senderRoleSetId, deleteAllPosts, token, jar, success, failure, always) {
  jar = options.jar || jar || _jar;
  var json = {
    userId: options.target || target,
    deleteAllPostsOption: options.deleteAllPosts || deleteAllPosts || false,
    rolesetId: options.senderRoleSetId || senderRoleSetId,
    selectedGroupId: options.group || options
  };
  if (!options.senderRoleSetId && !senderRoleSetId) {
    var opt = {
      group: options.group || options,
      jar: jar,
      success: function(roleset) {
        json.rolesetId = roleset;
        exileMain(options, json, token, jar, success, failure, always);
      },
      failure: options.failure || failure
    };
    exports.getRolesetInGroupWithJar(opt);
  } else
    exileMain(options, json, token, jar, success, failure, always);
};

exports.getJar = function() {
  return _jar;
};

exports.setJar = function(jar) {
  _jar = jar;
};

exports.getUserId = function(jar) {
  return getUserId(jar);
};

exports.getInputs = function(options, find) {
  return getInputs(options.html || options, options.find || find);
};

exports.getVerificationInputs = function(options) {
  return getVerificationInputs(options.html || options);
};
<commit_msg>Update<commit_after>// Dependencies
var request = require('request');

// Includes
var login = require('./util/login.js'),
  getSession = require('./util/getSession.js'),
  getCurrentUser = require('./util/getCurrentUser.js'),
  setRank = require('./setRank.js'),
  getRoles = require('./util/getRoles.js'),
  getRole = require('./util/getRole.js'),
  getToken = require('./util/getToken.js'),
  getInputs = require('./util/getInputs.js'),
  getVerificationInputs = require('./util/getVerificationInputs.js'),
  getRankInGroup = require('./util/getRankInGroup.js'),
  getRolesetInGroupWithJar = require('./util/getRolesetInGroupWithJar.js'),
  exile = require('./exile.js'),
  message = require('./message.js'),
  handleJoinRequest = require('./handleJoinRequest.js').handle,
  getRequestId = require('./handleJoinRequest.js').request,
  getUserId = require('./util/getUserId.js'),
  shout = require('./shout.js'),
  post = require('./post.js');

var cache = require('./cache/index.js');

var settings = require('../settings.json');

// Vars
var _jar = request.jar(); // Default cookie jar
var _cache = cache.new([{
  name: 'XCSRF',
  expire: settings.cache.XCSRF
}, {
  name: 'Roles',
  expire: settings.cache.Roles
}]);

// Define
function makeCallbackArray(options, success, failure, always) {
  return {success: options.success || success, failure: options.failure || failure, always: options.always || options.callback || always};
}

exports.login = function(options, password, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  login(options.jar || jar || _jar, options.username || options, options.password || password, callbacks);
};

exports.getSession = function(options) {
  getSession(options.jar || options || _jar);
};

exports.getCurrentUser = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getCurrentUser(options.jar || jar || _jar, options.option || typeof options === 'string' && options, callbacks);
};

exports.getRoles = function(options, rank, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  var group = options.group || options;
  rank = options.rank || rank;
  success = function(roles) {
    var response = roles;
    if (rank)
      response = getRole(roles, rank);
    callbacks.success(response);
  };
  cache.addIf(_cache, 'Roles', group, {
    done: success,
    add: function(done) {
      getRoles(group || options, {success: function(roles) {
        done(roles);
      }, failure: callbacks.failure});
    }
  }, true);
};

exports.getToken = function(options, jar, callback, failure) {
  var callbacks = {failure: options.failure || failure};
  getToken(options.jar || jar || _jar, options.url || options, callback, callbacks);
};

function setRankMain(options, target, roleset, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var url = 'http://www.roblox.com/groups/api/change-member-rank?groupId=' + (options.group || options) + '&newRoleSetId=' + (options.roleset || roleset) + '&targetUserId=' + (options.target || target);
  var run = function(token) {
    setRank(jar, url, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'setRank', {
      done: run,
      add: function(done) {
        getToken(jar, url, done, callbacks);
      }
    });
  }
}

exports.setRank = function(options) {
  if (options.rank) {
    exports.getRoles(options.group, options.rank, function(role) {
      options.roleset = role;
      setRankMain(options);
    }, options.failure);
  } else
    setRankMain.apply(undefined, arguments);
};

exports.message = function(options, subject, body, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var run = function(token) {
    message(jar, options.recipient || options, options.subject || subject, options.body || body, token, callbacks);
  };
  if (token)
    run(token);
  else {
    cache.addIf(_cache, 'XCSRF', 'message', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/messages/send', done, callbacks);
      }
    });
  }
};

exports.shout = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  shout(options.jar || jar || _jar, options.group || options, options.message || message, callbacks);
};

exports.handleJoinRequest = function(options, username, accept, jar, token, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  jar = options.jar || jar || _jar;
  var form = {
    groupJoinRequestId: 0,
    accept: options.accept || accept
  };
  var run = function(token) {
    handleJoinRequest(jar, token, form, callbacks);
  };
  cache.addIf(_cache, 'XCSRF', 'handleJoinRequest', {
    done: run,
    add: function(done) {
      getRequestId(jar, options.group || options, options.username || username, function(id) {
        form.groupJoinRequestId = id;
        getToken(jar, 'http://www.roblox.com/group/handle-join-request', done, callbacks, form);
      }, callbacks);
    }
  });
};

exports.post = function(options, message, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  post(options.jar || jar || _jar, options.group, options.message, callbacks);
};

exports.getRankInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, callbacks);
};

exports.getRolesetInGroup = function(options, group, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRankInGroup(options.player || options, options.group || group, {success: function(rank) {
    getRoles(options.group, rank, callbacks);
  }, failure: callbacks.failure});
};

exports.getRolesetInGroupWithJar = function(options, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  getRolesetInGroupWithJar(options.jar || jar || _jar, options.group || options, callbacks);
};

function exileMain(options, json, token, jar, success, failure, always) {
  var callbacks = makeCallbackArray(options, success, failure, always);
  var run = function(token) {
    exile(options.jar || jar || _jar, token, json, callbacks);
  };
  if (options.token || token)
    run(options.token || token);
  else {
    cache.addIf(_cache, 'XCSRF', 'exile', {
      done: run,
      add: function(done) {
        getToken(jar, 'http://www.roblox.com/My/Groups.aspx/ExileUserAndDeletePosts', done, callbacks, undefined, json);
      }
    });
  }
}

exports.exile = function(options, target, senderRoleSetId, deleteAllPosts, token, jar, success, failure, always) {
  jar = options.jar || jar || _jar;
  var json = {
    userId: options.target || target,
    deleteAllPostsOption: options.deleteAllPosts || deleteAllPosts || false,
    rolesetId: options.senderRoleSetId || senderRoleSetId,
    selectedGroupId: options.group || options
  };
  if (!options.senderRoleSetId && !senderRoleSetId) {
    var opt = {
      group: options.group || options,
      jar: jar,
      success: function(roleset) {
        json.rolesetId = roleset;
        exileMain(options, json, token, jar, success, failure, always);
      },
      failure: options.failure || failure
    };
    exports.getRolesetInGroupWithJar(opt);
  } else
    exileMain(options, json, token, jar, success, failure, always);
};

exports.getJar = function() {
  return _jar;
};

exports.setJar = function(jar) {
  _jar = jar;
};

exports.getUserId = function(jar) {
  return getUserId(jar);
};

exports.getInputs = function(options, find) {
  return getInputs(options.html || options, options.find || find);
};

exports.getVerificationInputs = function(options) {
  return getVerificationInputs(options.html || options);
};
<|endoftext|>


<commit_before>describe("relativechange.js lib", function () {
    var tests_data = [
        { ini: 100, fin: 400, chng: 3,     pctg: 300, mltplr: 4 },
        { ini: 400, fin: 100, chng: -0.75, pctg: -75, mltplr: 0.25 },
        { ini: 100, fin: 100, chng: 0,     pctg: 0,   mltplr: 1 },
        { ini: 1,   fin: 2,   chng: 1,     pctg: 100, mltplr: 2 },
        { ini: 5,   fin: 2.5, chng: -0.5,  pctg: -50, mltplr: 0.5 }
    ];

    function _testloop(callback) {
        for (var i=0; i<tests_data.length; i++) {
            var t = tests_data[i];
            callback(t);
        }
    }

    describe("RawRelativeChange:", function () {
        it("should not exist in global scope", function () {
            expect(window.RawRelativeChange).toBeUndefined();
        });
        it("should exist in RelativeChange scope", function () {
            expect(RelativeChange.Raw).toBeDefined();
        });
        it("initial & final values -> RelativeChange", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.calculate(t.ini, t.fin).val()).toEqual(t.chng);
            });
        });
        it("raw change value -> RelativeChange", function () {
            var change = tests_data[0].change;
            console.log(RelativeChange.Raw)
            expect(RelativeChange.Raw.fromRaw(change).val()).toEqual(change);
        });
        it("percentage value -> RelativeChange", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.fromPercentage(t.pctg).val()).toEqual(t.chng);
            });
        });
        it("multiplier value -> RelativeChange", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.fromMultiplier(t.mltplr).val()).toEqual(t.chng);
            });
        });
        it("RelativeChange -> RelativeChangePercentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.calculate(t.ini, t.fin).percentage().val()).toEqual(t.pctg);
            });
        });
        it("RelativeChange -> RelativeChangeMultiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.calculate(t.ini, t.fin).multiplier().val()).toEqual(t.mltplr);
            });
        });
    });

    describe("PercentageRelativeChange:", function () {
        it("should not exist in global scope", function () {
            expect(window.PercentageRelativeChange).toBeUndefined();
        });
        it("should exist in RelativeChange scope", function () {
            expect(RelativeChange.Percentage).toBeDefined();
        });
        it("initial & final values -> RelativeChangePercentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.calculate(t.ini, t.fin).val()).toEqual(t.pctg);
            });
        });
        it("percentage value -> RelativeChangePercentage", function () {
            var percentage = tests_data[0].percentage;
            expect(RelativeChange.Percentage.fromPercentage(percentage).val()).toEqual(percentage);
        });
        it("raw change value -> RelativeChangePercentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.fromRaw(t.chng).val()).toEqual(t.pctg);
            });
        });
        it("multiplier value -> RelativeChangePercentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.fromMultiplier(t.mltplr).val()).toEqual(t.pctg);
            });
        });
        it("RelativeChangePercentage -> RelativeChange", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.calculate(t.ini, t.fin).raw().val()).toEqual(t.chng);
            });
        });
        it("RelativeChangePercentage -> RelativeChangeMultiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.calculate(t.ini, t.fin).multiplier().val()).toEqual(t.mltplr);
            });
        });
    });

    describe("MultiplierRelativeChange:", function () {
        it("should not exist in global scope", function () {
            expect(window.MultiplierRelativeChange).toBeUndefined();
        });
        it("should exist in RelativeChange scope", function () {
            expect(RelativeChange.Multiplier).toBeDefined();
        });
        it("initial & final values -> RelativeChangeMultiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).val()).toEqual(t.mltplr);
            });
        });
        it("multiplier value -> RelativeChangeMultiplier", function () {
            var multiplier = tests_data[0].multiplier;
            expect(RelativeChange.Multiplier.fromMultiplier(multiplier).val()).toEqual(multiplier);
        });
        it("raw change value -> RelativeChangeMultiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.fromRaw(t.chng).val()).toEqual(t.mltplr);
            });
        });
        it("percentage value -> RelativeChangeMultiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.fromPercentage(t.pctg).val()).toEqual(t.mltplr);
            });
        });
        it("RelativeChangeMultiplier -> RelativeChange", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).raw().val()).toEqual(t.chng);
            });
        });
        it("RelativeChangeMultiplier -> RelativeChangePercentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).percentage().val()).toEqual(t.pctg);
            });
        });
    });
});<commit_msg>Fixed some test descriptions<commit_after>describe("relativechange.js lib", function () {
    var tests_data = [
        { ini: 100, fin: 400, chng: 3,     pctg: 300, mltplr: 4 },
        { ini: 400, fin: 100, chng: -0.75, pctg: -75, mltplr: 0.25 },
        { ini: 100, fin: 100, chng: 0,     pctg: 0,   mltplr: 1 },
        { ini: 1,   fin: 2,   chng: 1,     pctg: 100, mltplr: 2 },
        { ini: 5,   fin: 2.5, chng: -0.5,  pctg: -50, mltplr: 0.5 }
    ];

    function _testloop(callback) {
        for (var i=0; i<tests_data.length; i++) {
            var t = tests_data[i];
            callback(t);
        }
    }

    describe("RawRelativeChange:", function () {
        it("should not exist in global scope", function () {
            expect(window.RawRelativeChange).toBeUndefined();
        });
        it("should exist in RelativeChange scope", function () {
            expect(RelativeChange.Raw).toBeDefined();
        });
        it("initial & final values -> RelativeChange.Raw", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.calculate(t.ini, t.fin).val()).toEqual(t.chng);
            });
        });
        it("raw change value -> RelativeChange.Raw", function () {
            var change = tests_data[0].change;
            console.log(RelativeChange.Raw)
            expect(RelativeChange.Raw.fromRaw(change).val()).toEqual(change);
        });
        it("percentage value -> RelativeChange.Raw", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.fromPercentage(t.pctg).val()).toEqual(t.chng);
            });
        });
        it("multiplier value -> RelativeChange.Raw", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.fromMultiplier(t.mltplr).val()).toEqual(t.chng);
            });
        });
        it("RelativeChange.Raw -> RelativeChange.Percentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.calculate(t.ini, t.fin).percentage().val()).toEqual(t.pctg);
            });
        });
        it("RelativeChange.Raw -> RelativeChange.Multiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Raw.calculate(t.ini, t.fin).multiplier().val()).toEqual(t.mltplr);
            });
        });
    });

    describe("PercentageRelativeChange:", function () {
        it("should not exist in global scope", function () {
            expect(window.PercentageRelativeChange).toBeUndefined();
        });
        it("should exist in RelativeChange scope", function () {
            expect(RelativeChange.Percentage).toBeDefined();
        });
        it("initial & final values -> RelativeChange.Percentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.calculate(t.ini, t.fin).val()).toEqual(t.pctg);
            });
        });
        it("percentage value -> RelativeChange.Percentage", function () {
            var percentage = tests_data[0].percentage;
            expect(RelativeChange.Percentage.fromPercentage(percentage).val()).toEqual(percentage);
        });
        it("raw change value -> RelativeChange.Percentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.fromRaw(t.chng).val()).toEqual(t.pctg);
            });
        });
        it("multiplier value -> RelativeChange.Percentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.fromMultiplier(t.mltplr).val()).toEqual(t.pctg);
            });
        });
        it("RelativeChange.Percentage -> RelativeChange.Raw", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.calculate(t.ini, t.fin).raw().val()).toEqual(t.chng);
            });
        });
        it("RelativeChange.Percentage -> RelativeChange.Multiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Percentage.calculate(t.ini, t.fin).multiplier().val()).toEqual(t.mltplr);
            });
        });
    });

    describe("MultiplierRelativeChange:", function () {
        it("should not exist in global scope", function () {
            expect(window.MultiplierRelativeChange).toBeUndefined();
        });
        it("should exist in RelativeChange scope", function () {
            expect(RelativeChange.Multiplier).toBeDefined();
        });
        it("initial & final values -> RelativeChange.Multiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).val()).toEqual(t.mltplr);
            });
        });
        it("multiplier value -> RelativeChange.Multiplier", function () {
            var multiplier = tests_data[0].multiplier;
            expect(RelativeChange.Multiplier.fromMultiplier(multiplier).val()).toEqual(multiplier);
        });
        it("raw change value -> RelativeChange.Multiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.fromRaw(t.chng).val()).toEqual(t.mltplr);
            });
        });
        it("percentage value -> RelativeChange.Multiplier", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.fromPercentage(t.pctg).val()).toEqual(t.mltplr);
            });
        });
        it("RelativeChange.Multiplier -> RelativeChange.Raw", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).raw().val()).toEqual(t.chng);
            });
        });
        it("RelativeChange.Multiplier -> RelativeChange.Percentage", function () {
            _testloop(function (t) {
                expect(RelativeChange.Multiplier.calculate(t.ini, t.fin).percentage().val()).toEqual(t.pctg);
            });
        });
    });
});<|endoftext|>


<commit_before>/**
 * @module yeoman-generator
 */

'use strict';
var Environment = require('yeoman-environment');
var deprecate = require('./util/deprecate');

/**
 * The generator system is a framework for node to author reusable and
 * composable Generators, for a vast majority of use-case.
 *
 * Inspired and based off the work done on Thor and Rails 3 Generators, we try
 * to provide the same kind of infrastructure.
 *
 * Generators are registered by namespace, where namespaces are mapping the
 * structure of the file system with `:` being simply converted to `/`.
 *
 * Generators are standard node modules, they are simply required as usual, and
 * they can be shipped into reusable npm packages.
 *
 * The lookup is done depending on the configured load path, which is by
 * default `lib/generators` in every generators package installed (ie.
 * `node_modules/yeoman-backbone/lib/generators`)
 *
 * @example
 *    var yeoman = require('yeoman-generators');
 *
 *    var env = yeoman('angular:model')
 *      .run(function(err) {
 *        console.log('done!');
 *      });
 *
 * @alias module:yeoman-generator
 */

var yeoman = module.exports = function createEnv() {
  return Environment.createEnv.apply(Environment, arguments);
};

// hoist up top level class the generator extend
yeoman.Base = require('./base');
yeoman.NamedBase = require('./named-base');

deprecate.property(
  'NamedBase constructor is deprecated. See https://github.com/yeoman/generator/issues/882',
  yeoman,
  'NamedBase'
);

/**
 * Test helpers
 * {@link module:test/helpers}
 */
Object.defineProperty(yeoman, 'test', {
  get: function () {
    deprecate.log('yeoman.test is deprecated. Instead `require(\'yeoman-test\')`.');
    return require('yeoman-test');
  }
});

/**
 * Test assertions helpers
 * {@link https://github.com/yeoman/yeoman-assert}
 */
yeoman.assert = require('yeoman-assert');
deprecate.property(
  'yeoman.assert is deprecated. Instead `require(\'yeoman-assert\')`. See https://github.com/yeoman/generator/issues/883',
  yeoman,
  'assert'
);

/**
 * Yeoman base's generators
 * @enum generators
 */
yeoman.generators = {
  /**
   * Base Generator
   * {@link Base}
   */
  Base: yeoman.Base,

  /**
   * Named Base Generator
   * {@link NamedBase}
   */
  NamedBase: require('./named-base')
};
deprecate.property(
  'require(\'yeoman-generator\').generators.Base is deprecated. Use require(\'yeoman-generator\').Base directly',
  yeoman,
  'generators'
);
<commit_msg>Fix deprecation message for using `NamedBase` (#969)<commit_after>/**
 * @module yeoman-generator
 */

'use strict';
var Environment = require('yeoman-environment');
var deprecate = require('./util/deprecate');

/**
 * The generator system is a framework for node to author reusable and
 * composable Generators, for a vast majority of use-case.
 *
 * Inspired and based off the work done on Thor and Rails 3 Generators, we try
 * to provide the same kind of infrastructure.
 *
 * Generators are registered by namespace, where namespaces are mapping the
 * structure of the file system with `:` being simply converted to `/`.
 *
 * Generators are standard node modules, they are simply required as usual, and
 * they can be shipped into reusable npm packages.
 *
 * The lookup is done depending on the configured load path, which is by
 * default `lib/generators` in every generators package installed (ie.
 * `node_modules/yeoman-backbone/lib/generators`)
 *
 * @example
 *    var yeoman = require('yeoman-generators');
 *
 *    var env = yeoman('angular:model')
 *      .run(function(err) {
 *        console.log('done!');
 *      });
 *
 * @alias module:yeoman-generator
 */

var yeoman = module.exports = function createEnv() {
  return Environment.createEnv.apply(Environment, arguments);
};

// hoist up top level class the generator extend
yeoman.Base = require('./base');
yeoman.NamedBase = require('./named-base');

deprecate.property(
  'NamedBase constructor is deprecated. See https://github.com/yeoman/generator/issues/882',
  yeoman,
  'NamedBase'
);

/**
 * Test helpers
 * {@link module:test/helpers}
 */
Object.defineProperty(yeoman, 'test', {
  get: function () {
    deprecate.log('yeoman.test is deprecated. Instead `require(\'yeoman-test\')`.');
    return require('yeoman-test');
  }
});

/**
 * Test assertions helpers
 * {@link https://github.com/yeoman/yeoman-assert}
 */
yeoman.assert = require('yeoman-assert');
deprecate.property(
  'yeoman.assert is deprecated. Instead `require(\'yeoman-assert\')`. See https://github.com/yeoman/generator/issues/883',
  yeoman,
  'assert'
);

/**
 * Yeoman base's generators
 * @enum generators
 */
yeoman.generators = {
  /**
   * Base Generator
   * {@link Base}
   */
  Base: yeoman.Base,

  /**
   * Named Base Generator
   * {@link NamedBase}
   */
  NamedBase: require('./named-base')
};
deprecate.property(
  'require(\'yeoman-generator\').generators.Base is deprecated. Use require(\'yeoman-generator\').Base directly',
  yeoman.generators,
  'Base'
);
deprecate.property(
  'NamedBase constructor is deprecated. See https://github.com/yeoman/generator/issues/882',
  yeoman.generators,
  'NamedBase'
);
<|endoftext|>