<commit_before>'use strict';

var setPrototypeOf    = require('es5-ext/object/set-prototype-of')
  , object            = require('es5-ext/object/valid-object')
  , value             = require('es5-ext/object/valid-value')
  , d                 = require('d/d')
  , getIterator       = require('es6-iterator/get')
  , forOf             = require('es6-iterator/for-of')
  , toStringTagSymbol = require('es6-symbol').toStringTag
  , genId             = require('time-uuid')
  , isNative          = require('./is-native-implemented')

  , isArray = Array.isArray, defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , WeakMapPoly;

module.exports = WeakMapPoly = function (/*iterable*/) {
	var iterable = arguments[0];
	if (!(this instanceof WeakMapPoly)) return new WeakMapPoly(iterable);
	if (this.__weakMapData__ !== undefined) {
		throw new TypeError(this + " cannot be reinitialized");
	}
	if (iterable != null) {
		if (!isArray(iterable)) iterable = getIterator(iterable);
	}
	defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId()));
	if (!iterable) return;
	forOf(iterable, function (val) {
		value(val);
		this.set(val[0], val[1]);
	}, this);
};

if (isNative) {
	if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
	WeakMapPoly.prototype = Object.create(WeakMap.prototype, {
		constructor: d(WeakMapPoly)
	});
}

Object.defineProperties(WeakMapPoly.prototype, {
	clear: d(function () {
		defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId()));
	}),
	delete: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			delete key[this.__weakMapData__];
			return true;
		}
		return false;
	}),
	get: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			return key[this.__weakMapData__];
		}
	}),
	has: d(function (key) {
		return hasOwnProperty.call(object(key), this.__weakMapData__);
	}),
	set: d(function (key, value) {
		defineProperty(object(key), this.__weakMapData__, d('c', value));
		return this;
	}),
	toString: d(function () { return '[object WeakMap]'; })
});
defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap'));
<commit_msg>Update up to changes in d package<commit_after>'use strict';

var setPrototypeOf    = require('es5-ext/object/set-prototype-of')
  , object            = require('es5-ext/object/valid-object')
  , value             = require('es5-ext/object/valid-value')
  , d                 = require('d')
  , getIterator       = require('es6-iterator/get')
  , forOf             = require('es6-iterator/for-of')
  , toStringTagSymbol = require('es6-symbol').toStringTag
  , genId             = require('time-uuid')
  , isNative          = require('./is-native-implemented')

  , isArray = Array.isArray, defineProperty = Object.defineProperty
  , hasOwnProperty = Object.prototype.hasOwnProperty
  , WeakMapPoly;

module.exports = WeakMapPoly = function (/*iterable*/) {
	var iterable = arguments[0];
	if (!(this instanceof WeakMapPoly)) return new WeakMapPoly(iterable);
	if (this.__weakMapData__ !== undefined) {
		throw new TypeError(this + " cannot be reinitialized");
	}
	if (iterable != null) {
		if (!isArray(iterable)) iterable = getIterator(iterable);
	}
	defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId()));
	if (!iterable) return;
	forOf(iterable, function (val) {
		value(val);
		this.set(val[0], val[1]);
	}, this);
};

if (isNative) {
	if (setPrototypeOf) setPrototypeOf(WeakMapPoly, WeakMap);
	WeakMapPoly.prototype = Object.create(WeakMap.prototype, {
		constructor: d(WeakMapPoly)
	});
}

Object.defineProperties(WeakMapPoly.prototype, {
	clear: d(function () {
		defineProperty(this, '__weakMapData__', d('c', '$weakMap$' + genId()));
	}),
	delete: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			delete key[this.__weakMapData__];
			return true;
		}
		return false;
	}),
	get: d(function (key) {
		if (hasOwnProperty.call(object(key), this.__weakMapData__)) {
			return key[this.__weakMapData__];
		}
	}),
	has: d(function (key) {
		return hasOwnProperty.call(object(key), this.__weakMapData__);
	}),
	set: d(function (key, value) {
		defineProperty(object(key), this.__weakMapData__, d('c', value));
		return this;
	}),
	toString: d(function () { return '[object WeakMap]'; })
});
defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d('c', 'WeakMap'));
<|endoftext|>


<commit_before>const path = require('path');
const image = require('../../../../lib/image');
const storage = require('../../../../adapters/storage');
const activeTheme = require('../../../../services/themes/active');

const SIZE_PATH_REGEX = /^\/size\/([^/]+)\//;

module.exports = function (req, res, next) {
    if (!SIZE_PATH_REGEX.test(req.url)) {
        return next();
    }

    const [sizeImageDir, requestedDimension] = req.url.match(SIZE_PATH_REGEX);
    const redirectToOriginal = () => {
        const url = req.originalUrl.replace(`/size/${requestedDimension}`, '');
        return res.redirect(url);
    };

    // CASE: image manipulator is uncapable of transforming file (e.g. .gif)
    const requestUrlFileExtension = path.parse(req.url).ext;
    if (!image.manipulator.canTransformFileExtension(requestUrlFileExtension)) {
        return redirectToOriginal();
    }

    const imageSizes = activeTheme.get().config('image_sizes');
    // CASE: no image_sizes config
    if (!imageSizes) {
        return redirectToOriginal();
    }

    const imageDimensions = Object.keys(imageSizes).reduce((dimensions, size) => {
        const {width, height} = imageSizes[size];
        const dimension = (width ? 'w' + width : '') + (height ? 'h' + height : '');
        return Object.assign({
            [dimension]: imageSizes[size]
        }, dimensions);
    }, {});

    const imageDimensionConfig = imageDimensions[requestedDimension];
    // CASE: unknown dimension
    if (!imageDimensionConfig || (!imageDimensionConfig.width && !imageDimensionConfig.height)) {
        return redirectToOriginal();
    }

    const storageInstance = storage.getStorage();
    // CASE: unsupported storage adapter but theme is using custom image_sizes
    if (typeof storageInstance.saveRaw !== 'function') {
        return redirectToOriginal();
    }

    storageInstance.exists(req.url).then((exists) => {
        if (exists) {
            return;
        }

        const originalImagePath = path.relative(sizeImageDir, req.url);

        return storageInstance.read({path: originalImagePath})
            .then((originalImageBuffer) => {
                return image.manipulator.resizeImage(originalImageBuffer, imageDimensionConfig);
            })
            .then((resizedImageBuffer) => {
                return storageInstance.saveRaw(resizedImageBuffer, req.url);
            });
    }).then(() => {
        next();
    }).catch(function (err) {
        if (err.code === 'SHARP_INSTALLATION') {
            return redirectToOriginal();
        }
        next(err);
    });
};
<commit_msg>🎨 Use unoptimised image when possible for dynamic images (#10314)<commit_after>const path = require('path');
const image = require('../../../../lib/image');
const storage = require('../../../../adapters/storage');
const activeTheme = require('../../../../services/themes/active');

const SIZE_PATH_REGEX = /^\/size\/([^/]+)\//;

module.exports = function (req, res, next) {
    if (!SIZE_PATH_REGEX.test(req.url)) {
        return next();
    }

    const [sizeImageDir, requestedDimension] = req.url.match(SIZE_PATH_REGEX);
    const redirectToOriginal = () => {
        const url = req.originalUrl.replace(`/size/${requestedDimension}`, '');
        return res.redirect(url);
    };

    // CASE: image manipulator is uncapable of transforming file (e.g. .gif)
    const requestUrlFileExtension = path.parse(req.url).ext;
    if (!image.manipulator.canTransformFileExtension(requestUrlFileExtension)) {
        return redirectToOriginal();
    }

    const imageSizes = activeTheme.get().config('image_sizes');
    // CASE: no image_sizes config
    if (!imageSizes) {
        return redirectToOriginal();
    }

    const imageDimensions = Object.keys(imageSizes).reduce((dimensions, size) => {
        const {width, height} = imageSizes[size];
        const dimension = (width ? 'w' + width : '') + (height ? 'h' + height : '');
        return Object.assign({
            [dimension]: imageSizes[size]
        }, dimensions);
    }, {});

    const imageDimensionConfig = imageDimensions[requestedDimension];
    // CASE: unknown dimension
    if (!imageDimensionConfig || (!imageDimensionConfig.width && !imageDimensionConfig.height)) {
        return redirectToOriginal();
    }

    const storageInstance = storage.getStorage();
    // CASE: unsupported storage adapter but theme is using custom image_sizes
    if (typeof storageInstance.saveRaw !== 'function') {
        return redirectToOriginal();
    }

    storageInstance.exists(req.url).then((exists) => {
        if (exists) {
            return;
        }

        const imagePath = path.relative(sizeImageDir, req.url);
        const {dir, name, ext} = path.parse(imagePath);
        const [imageNameMatched, imageName, imageNumber] = name.match(/^(.+?)(-\d+)?$/) || [null];

        if (!imageNameMatched) {
            // CASE: Image name does not contain any characters?
            // RESULT: Hand off to `next()` which will 404
            return;
        }
        const unoptimizedImagePath = path.join(dir, `${imageName}_o${imageNumber || ''}${ext}`);

        return storageInstance.exists(unoptimizedImagePath)
            .then((unoptimizedImageExists) => {
                if (unoptimizedImageExists) {
                    return unoptimizedImagePath;
                }
                return imagePath;
            })
            .then((path) => {
                return storageInstance.read({path});
            })
            .then((originalImageBuffer) => {
                return image.manipulator.resizeImage(originalImageBuffer, imageDimensionConfig);
            })
            .then((resizedImageBuffer) => {
                return storageInstance.saveRaw(resizedImageBuffer, req.url);
            });
    }).then(() => {
        next();
    }).catch(function (err) {
        if (err.code === 'SHARP_INSTALLATION') {
            return redirectToOriginal();
        }
        next(err);
    });
};
<|endoftext|>


<commit_before>(function() {
	// Initialize
	require.progress = 0;

	// Monitor Progress
	var monitor = {
		_modules: {

		},
		add: function(moduleId, dependencies, parent, cached) {

		},
		complete: function(moduleId) {

		},
		get: function(moduleId) {

		},
		update: function(moduleId) {

		},
		report: function() {

		}
	};

	// Setup Tracing
	var trace = function(group, args) {
		if (group === 'loader-finish-exec') {
			console.log('Completed', args[0]);
		} else if (group === 'loader-define-module') {
			console.log('New Module', args[0], args[1]);
		}
	};

	if (!require.trace.set) {
		require.trace = trace;
	} else {
		require.trace.set('loader-finish-exec', 1);
		require.trace.set('loader-define-module', 1);
		require.on('trace', function(args) {
			trace(args.shift(), args);
		});
	}
})();<commit_msg>Add cached modules<commit_after>(function() {
	// Initialize
	require.progress = 0;

	// Monitor Progress
	var monitor = {
		_modules: {

		},
		add: function(moduleId, dependencies, parent, cached) {

		},
		complete: function(moduleId) {

		},
		get: function(moduleId) {

		},
		update: function(moduleId) {

		},
		report: function() {

		}
	};

	// Add cached modules
	for (var moduleId in require.cache) {
		if (require.cache.hasOwnProperty(moduleId) && !/^url:/.test(moduleId)) {
			monitor.add(moduleId, null, null, true);
		}
	}

	// Setup Tracing
	var trace = function(group, args) {
		if (group === 'loader-finish-exec') {
			console.log('Completed', args[0]);
		} else if (group === 'loader-define-module') {
			console.log('New Module', args[0], args[1]);
		}
	};

	if (!require.trace.set) {
		require.trace = trace;
	} else {
		require.trace.set('loader-finish-exec', 1);
		require.trace.set('loader-define-module', 1);
		require.on('trace', function(args) {
			trace(args.shift(), args);
		});
	}
})();<|endoftext|>


<commit_before>hqDefine("reports/js/edit_scheduled_report", [
    "jquery",
    "underscore",
    "analytix/js/google",
    "hqwebapp/js/initial_page_data",
    "hqwebapp/js/multiselect_utils",
    "hqwebapp/js/widgets_v4",  // autocomplete widget for email recipient list
], function (
    $,
    _,
    googleAnalytics,
    initialPageData,
    multiselectUtils
) {
    var add_options_to_select = function ($select, opt_list, selected_val) {
        for (var i = 0; i < opt_list.length; i++) {
            var $opt = $('<option />').val(opt_list[i][0]).text(opt_list[i][1]);
            if (opt_list[i][0] === selected_val) {
                $opt.prop("selected", true);
            }
            $select.append($opt);
        }
        return $select;
    };

    var update_day_input = function (weekly_options, monthly_options, day_value) {
        var $interval = $interval || $('[name="interval"]');
        $('#div_id_day').remove();
        if ($interval.val() !== 'daily') {
            var opts = $interval.val() === 'weekly' ? weekly_options : monthly_options;
            var $day_select = $('<select id="id_day" class="select form-control" name="day" />');
            $day_select = add_options_to_select($day_select, opts, day_value);
            var $day_control_group = $('
')
                .append($('Day*'))
                .append($('
').append($day_select));
            $interval.closest('.form-group').after($day_control_group);
        }
    };

    var ScheduledReportFormHelper = function (options) {
        var self = this;
        self.weekly_options = options.weekly_options;
        self.monthly_options = options.monthly_options;
        self.day_value = options.day_value;

        self.init = function () {
            $(function () {
                update_day_input(self.weekly_options, self.monthly_options, self.day_value);
                $('[name="interval"]').change(function () {
                    update_day_input(self.weekly_options, self.monthly_options);
                });
            });
        };
    };

    var isConfigurableMap = initialPageData.get('is_configurable_map');
    var languagesMap = initialPageData.get('languages_map');
    var languagesForSelect = initialPageData.get('languages_for_select');
    var isOwner = initialPageData.get('is_owner');

    var updateUcrElements = function (selectedConfigs) {
        var showUcrElements = _.any(
            selectedConfigs, function (i) {return isConfigurableMap[i] === true;}
        );

        if (showUcrElements) {
            $("#ucr-privacy-warning").show();

            // Figure out which options to show in the select2
            var languageLists = _.map(selectedConfigs, function (i) {return languagesMap[i];});
            var languageSet = _.reduce(languageLists, function (memo, list) {
                _.map(list, function (e) {
                    memo[e] = true;
                });
                return memo;
            }, {});
            var currentLanguageOptions = Object.keys(languageSet).sort();
            var $id_language = $('#id_language');

            if (currentLanguageOptions.length === 1 && currentLanguageOptions[0] === 'en') {
                $id_language.val('en');
                $('#div_id_language').hide();
            } else {
                // Update the options of the select2
                var current = $id_language.val();
                $id_language.empty();

                // Populate the select2
                _.map(currentLanguageOptions, function (l) {
                    $id_language.append(
                        $("<option></option>").attr("value", l).text(languagesForSelect[l][1])
                    );
                });
                $id_language.val(current);
                $("#div_id_language").show();
            }
        } else {
            $("#div_id_language").hide();
            $("#ucr-privacy-warning").hide();
        }
    };

    $('#id_language').select2({
        placeholder: gettext("Select a language..."),
    });
    $("#id_config_ids").change(function () {
        updateUcrElements($(this).val());
    });
    if (!isOwner) {
        $('#id_config_ids').hide().after(
            $('#id_config_ids').children().map(function () {
                return $("
").text($(this).text()).get(0);
            })
        );
    }
    else {
        multiselectUtils.createFullMultiselectWidget(
            'id_config_ids',
            gettext("Available Reports"),
            gettext("Included Reports"),
            gettext("Search Reports...")
        );
    }
    updateUcrElements($("#id_config_ids").val());

    var scheduled_report_form_helper = new ScheduledReportFormHelper({
        weekly_options: initialPageData.get('weekly_day_options'),
        monthly_options: initialPageData.get('monthly_day_options'),
        day_value: initialPageData.get('day_value'),
    });
    scheduled_report_form_helper.init();

    $('#id-scheduledReportForm').submit(function () {
        googleAnalytics.track.event('Scheduled Reports', 'Create a scheduled report', '-', "", {}, function () {
            document.getElementById('id-scheduledReportForm').submit();
        });
        return false;
    });
});
<commit_msg>Add date picker calendar<commit_after>hqDefine("reports/js/edit_scheduled_report", [
    "jquery",
    "underscore",
    "analytix/js/google",
    "hqwebapp/js/initial_page_data",
    "hqwebapp/js/multiselect_utils",
    "hqwebapp/js/widgets_v4",  // autocomplete widget for email recipient list
    "jquery-ui/ui/datepicker",
], function (
    $,
    _,
    googleAnalytics,
    initialPageData,
    multiselectUtils
) {
    var add_options_to_select = function ($select, opt_list, selected_val) {
        for (var i = 0; i < opt_list.length; i++) {
            var $opt = $('<option />').val(opt_list[i][0]).text(opt_list[i][1]);
            if (opt_list[i][0] === selected_val) {
                $opt.prop("selected", true);
            }
            $select.append($opt);
        }
        return $select;
    };

    var update_day_input = function (weekly_options, monthly_options, day_value) {
        var $interval = $interval || $('[name="interval"]');
        $('#div_id_day').remove();
        if ($interval.val() !== 'daily') {
            var opts = $interval.val() === 'weekly' ? weekly_options : monthly_options;
            var $day_select = $('<select id="id_day" class="select form-control" name="day" />');
            $day_select = add_options_to_select($day_select, opts, day_value);
            var $day_control_group = $('
')
                .append($('Day*'))
                .append($('
').append($day_select));
            $interval.closest('.form-group').after($day_control_group);
        }
    };

    var ScheduledReportFormHelper = function (options) {
        var self = this;
        self.weekly_options = options.weekly_options;
        self.monthly_options = options.monthly_options;
        self.day_value = options.day_value;

        self.init = function () {
            $(function () {
                update_day_input(self.weekly_options, self.monthly_options, self.day_value);
                $('[name="interval"]').change(function () {
                    update_day_input(self.weekly_options, self.monthly_options);
                });
                $("#id_start_date").datepicker({dateFormat: "yy-mm-dd",});
            });
        };
    };

    var isConfigurableMap = initialPageData.get('is_configurable_map');
    var languagesMap = initialPageData.get('languages_map');
    var languagesForSelect = initialPageData.get('languages_for_select');
    var isOwner = initialPageData.get('is_owner');

    var updateUcrElements = function (selectedConfigs) {
        var showUcrElements = _.any(
            selectedConfigs, function (i) {return isConfigurableMap[i] === true;}
        );

        if (showUcrElements) {
            $("#ucr-privacy-warning").show();

            // Figure out which options to show in the select2
            var languageLists = _.map(selectedConfigs, function (i) {return languagesMap[i];});
            var languageSet = _.reduce(languageLists, function (memo, list) {
                _.map(list, function (e) {
                    memo[e] = true;
                });
                return memo;
            }, {});
            var currentLanguageOptions = Object.keys(languageSet).sort();
            var $id_language = $('#id_language');

            if (currentLanguageOptions.length === 1 && currentLanguageOptions[0] === 'en') {
                $id_language.val('en');
                $('#div_id_language').hide();
            } else {
                // Update the options of the select2
                var current = $id_language.val();
                $id_language.empty();

                // Populate the select2
                _.map(currentLanguageOptions, function (l) {
                    $id_language.append(
                        $("<option></option>").attr("value", l).text(languagesForSelect[l][1])
                    );
                });
                $id_language.val(current);
                $("#div_id_language").show();
            }
        } else {
            $("#div_id_language").hide();
            $("#ucr-privacy-warning").hide();
        }
    };

    $('#id_language').select2({
        placeholder: gettext("Select a language..."),
    });
    $("#id_config_ids").change(function () {
        updateUcrElements($(this).val());
    });
    if (!isOwner) {
        $('#id_config_ids').hide().after(
            $('#id_config_ids').children().map(function () {
                return $("
").text($(this).text()).get(0);
            })
        );
    }
    else {
        multiselectUtils.createFullMultiselectWidget(
            'id_config_ids',
            gettext("Available Reports"),
            gettext("Included Reports"),
            gettext("Search Reports...")
        );
    }
    updateUcrElements($("#id_config_ids").val());

    var scheduled_report_form_helper = new ScheduledReportFormHelper({
        weekly_options: initialPageData.get('weekly_day_options'),
        monthly_options: initialPageData.get('monthly_day_options'),
        day_value: initialPageData.get('day_value'),
    });
    scheduled_report_form_helper.init();

    $('#id-scheduledReportForm').submit(function () {
        googleAnalytics.track.event('Scheduled Reports', 'Create a scheduled report', '-', "", {}, function () {
            document.getElementById('id-scheduledReportForm').submit();
        });
        return false;
    });
});
<|endoftext|>


<commit_before>{
  "modules": [
    {
      "id": "people",
      "title": "People Directory"
    },
    {
      "id": "map",
      "title": "Campus Map"
    },
    {
      "id": "shuttleschedule",
      "title": "Shuttle Schedule"
    },
    {
      "id": "calendar",
      "title": "Calendar"
    }
    {
      "id": "stellar",
      "title": "Stellar",
      "subtitle": "class info"
    },
    {
      "id": "careers",
      "title": "Student Careers"
    },
    {
      "id": "emergency",
      "title": "Emergency Info"
    },
    {
      "id": "3down",
      "title": "3DOWN",
      "subtitle": "service status"
    },
    {
      "id": "techcash",
      "title": "TechCASH (BETA)",
      "platforms": ["iphone", "computer"],
      "auth": ["x509"]
    },
    {
      "id": "libraries",
      "title": "Libraries (BETA)",
      "platforms": ["iphone"]
    },
    {
      "id": "links",
      "title": "Useful Links"
    },
    {
      "id": "certificates",
      "title": "MIT Certificates",
      "platforms": ["iphone"],
      "extra": true,
      "url": "http://ca.mit.edu"
    },
    {
      "id": "webmitedu",
      "title": "Full MIT Website",
      "extra": true,
      "url": "http://web.mit.edu",
      "platforms": ["iphone", "android", "webos", "winmo", "blackberry", "palm", "symbian", "computer"]
    },
    {
      "id": "mobile-about",
      "title": "About this site",
      "extra": true,
      "required": true
    },
    {
      "id": "customize",
      "title": "Customize Home",
      "extra": true,
      "required": true
    },
    {
      "id": "download",
      "title": "Download",
      "extra": true,
      "platforms": ["blackberry"]
    }
  ]
}
<commit_msg>remove experimental file<commit_after><|endoftext|>


<commit_before>"use strict";

var uid = require('uid2');
var assert = require('assert');

var DEFAULT_TOKEN_LEN = 64;

module.exports = function (AccessToken) {

    /**
     * Anonymous Token
     *
     * ```js
     * assert(AccessToken.ANONYMOUS.id === '$anonymous');
     * ```
     */

    AccessToken.ANONYMOUS = new AccessToken({id: '$anonymous'});

    /**
     * Create a cryptographically random access token id.
     *
     * @param {Function} cb callback (err, token)
     */

    AccessToken.createAccessTokenId = function (cb) {
        uid(this.settings.accessTokenIdLength || DEFAULT_TOKEN_LEN, function (err, guid) {
            err ? cb(err) : cb(err, guid);
        });
    };

    /*!
     * Hook to create accessToken id.
     */

    AccessToken.hook('beforeCreate', function (data, next) {
        data = data || {};

        if (data.id) return next();

        AccessToken.createAccessTokenId(function (err, id) {
            if (err) return next(err);
            data.id = id;
            next();
        });
    });

    /**
     * Find a token for the given `ServerRequest`.
     *
     * @param {object} req
     * @param {Object} [options] Options for finding the token
     * @param {Function} cb (err, token)
     */

    AccessToken.findForRequest = function (req, options, cb) {
        var id = tokenIdForRequest(req, options);

        if (id) {
            this.findById(id, function (err, token) {
                if (err) return cb(err);
                if (!token) return cb();
                token.validate(function (err, isValid) {
                    if (err) return cb(err);
                    if (isValid) return cb(null, token);
                    var e = new Error('Invalid Access Token');
                    e.status = e.statusCode = 401;
                    cb(e);
                });
            });
        } else {
            process.nextTick(function () {
                cb();
            });
        }
    };

    /**
     * Validate the token.
     *
     * @callback {Function} cb (err, isValid)
     */

    AccessToken.prototype.validate = function (cb) {
        try {
            assert(this.created && typeof this.created.getTime === 'function', 'token.created must be a valid Date');
            assert(this.ttl !== 0, 'token.ttl must be not be 0');
            assert(this.ttl, 'token.ttl must exist');
            assert(this.ttl >= -1, 'token.ttl must be >= -1');

            var now = Date.now();
            var created = this.created.getTime();
            var elapsedSeconds = (now - created) / 1000;
            var secondsToLive = this.ttl;
            var isValid = elapsedSeconds < secondsToLive;

            if (isValid) {
                cb(null, isValid);
            } else {
                this.destroy(function (err) {
                    cb(err, isValid);
                });
            }
        } catch (e) {
            cb(e);
        }
    };

    function tokenIdForRequest(req, options) {
        var params = options.params || [];
        var headers = options.headers || [];
        var cookies = options.cookies || [];
        var i = 0;
        var length;
        var id;

        params = params.concat(['access_token']);
        headers = headers.concat(['X-Access-Token', 'authorization']);
        cookies = cookies.concat(['access_token', 'authorization']);

        for (length = params.length; i < length; i++) {
            id = req.param(params[i]);

            if (typeof id === 'string') {
                return id;
            }
        }

        for (i = 0, length = headers.length; i < length; i++) {
            id = req.header(headers[i]);

            if (typeof id === 'string') {
                // Add support for oAuth 2.0 bearer token
                // http://tools.ietf.org/html/rfc6750
                if (id.indexOf('Bearer ') === 0) {
                    id = id.substring(7);
                    // Decode from base64
                    var buf = new Buffer(id, 'base64');
                    id = buf.toString('utf8');
                }
                return id;
            }
        }

        if (req.signedCookies) {
            for (i = 0, length = cookies.length; i < length; i++) {
                id = req.signedCookies[cookies[i]];

                if (typeof id === 'string') {
                    return id;
                }
            }
        }
        return null;
    }
};<commit_msg>move token parser from access_token to token middleware<commit_after>"use strict";

var uid = require('uid2');
var assert = require('assert');

var DEFAULT_TOKEN_LEN = 64;

module.exports = function (AccessToken) {

    /**
     * Anonymous Token
     *
     * ```js
     * assert(AccessToken.ANONYMOUS.id === '$anonymous');
     * ```
     */

    AccessToken.ANONYMOUS = new AccessToken({id: '$anonymous'});

    /**
     * Create a cryptographically random access token id.
     *
     * @param {Function} cb callback (err, token)
     */

    AccessToken.createAccessTokenId = function (cb) {
        uid(this.settings.accessTokenIdLength || DEFAULT_TOKEN_LEN, function (err, guid) {
            err ? cb(err) : cb(err, guid);
        });
    };

    /*!
     * Hook to create accessToken id.
     */

    AccessToken.hook('beforeCreate', function (data, next) {
        data = data || {};

        if (data.id) return next();

        AccessToken.createAccessTokenId(function (err, id) {
            if (err) return next(err);
            data.id = id;
            next();
        });
    });

    /**
     * Find and validate a token for the given `id`.
     *
     * @param {String} id
     * @param {Function} cb (err, token)
     */
    AccessToken.findForId = function (id, cb) {
        if (id) {
            this.findById(id, function (err, token) {
                if (err) return cb(err);
                if (!token) return cb();
                token.validate(function (err, isValid) {
                    if (err) return cb(err);
                    if (isValid) return cb(null, token);
                    var e = new Error('Invalid Access Token');
                    e.status = e.statusCode = 401;
                    cb(e);
                });
            });
        } else {
            process.nextTick(function () {
                cb();
            });
        }
    };

    /**
     * Validate the token.
     *
     * @callback {Function} cb (err, isValid)
     */
    AccessToken.prototype.validate = function (cb) {
        try {
            assert(this.created && typeof this.created.getTime === 'function', 'token.created must be a valid Date');
            assert(this.ttl !== 0, 'token.ttl must be not be 0');
            assert(this.ttl, 'token.ttl must exist');
            assert(this.ttl >= -1, 'token.ttl must be >= -1');

            var now = Date.now();
            var created = this.created.getTime();
            var elapsedSeconds = (now - created) / 1000;
            var secondsToLive = this.ttl;
            var isValid = elapsedSeconds < secondsToLive;

            if (isValid) {
                cb(null, isValid);
            } else {
                this.destroy(function (err) {
                    cb(err, isValid);
                });
            }
        } catch (e) {
            cb(e);
        }
    };

};<|endoftext|>


<commit_before>'use strict';

const ordinal = require('../../lib/ordinal');

class Instance {
  constructor(instance) {
    this.State = instance.State;
    this.Quarter = instance.Quarter;
    this.Time = instance.Time;
    this.HomeScore = instance.HomeScore;
    this.AwayScore = instance.AwayScore;
  }
  timeNum() {
    return parseInt(this.Time.replace(/\D/g, ''));
  }
  scoreChanged(prevInstance) {
    return prevInstance.State !== this.State ||
      prevInstance.Quarter !== this.Quarter ||
      prevInstance.HomeScore !== this.HomeScore ||
      prevInstance.AwayScore !== this.AwayScore;
  }
  changeString(prevInstance, game) {
    let str = '';
    const scores = game.AwayTeam.Name + ' ' + this.AwayScore + ', ' +
      game.HomeTeam.Name + ' ' + this.HomeScore + '. ';
    const leadString = ' take the lead. ';
    const time = `${this.Time} ${ordinal(this.Quarter)} quarter.`;
    if (this.State !== prevInstance.State) {
      if (prevInstance.State === 'Pregame' && this.State === 'Progress') {
        str = `Start of game: ${game.AwayTeam.Name} vs ${game.HomeTeam.Name}`;
      }
      if (this.State === 'Final') {
        str = `Final${(prevInstance.Quarter === 'OT' ? ' OT' : '')}. ${scores}`;
      }
    } else if ((this.Quarter === prevInstance.Quarter && prevInstance.timeNum() >= this.timeNum()) || (prevInstance.Quarter < this.Quarter)) {
      if (prevInstance.AwayScore > this.AwayScore || prevInstance.HomeScore > this.HomeScore) {
        str = `Score correction. ${scores} ${time}`;
      } else if (prevInstance.AwayScore === prevInstance.HomeScore) {
        if (this.AwayScore > this.HomeScore) {
          str = game.AwayTeam.Name + leadString + scores + time;
        } else if (this.HomeScore > this.AwayScore){
          str = game.HomeTeam.Name + leadString + scores + time;
        }
      } else if (this.AwayScore === this.HomeScore) {
        if (prevInstance.AwayScore < prevInstance.HomeScore) {
          str = game.AwayTeam.Name + ' tie it up. ' + scores + time;
        } else if (prevInstance.HomeScore < prevInstance.AwayScore) {
          str = game.HomeTeam.Name + ' tie it up. ' + scores + time;
        }
      } else if (prevInstance.AwayScore < prevInstance.HomeScore && this.HomeScore < this.AwayScore) {
        str = game.AwayTeam.Name + leadString + scores + time;
      } else if (prevInstance.HomeScore < prevInstance.AwayScore && this.AwayScore < this.HomeScore) {
        str = game.HomeTeam.Name + leadString + scores + time;
      }
    }
    return str ? (str.trim() + ' ' + game.makeGameLink()) : '';
  }
}

Instance.parse = function(raw) {
  const instanceObj = {
    Time: raw.clock,
    HomeScore: raw.home.score.T,
    AwayScore: raw.away.score.T
  };
  if (!raw.qtr) {
    instanceObj.State = 'Pregame';
  } else if (!isNaN(parseInt(raw.qtr))) {
    instanceObj.State = 'Progress';
    instanceObj.Quarter = parseInt(raw.qtr) > 4 ? 'OT' : parseInt(raw.qtr);
  } else if (raw.qtr.toLocaleLowerCase().indexOf('final') !== -1) {
    instanceObj.State = 'Final';
  } else {
    instanceObj.State = raw.qtr;
  }

  return new Instance(instanceObj);
};

module.exports = Instance;
<commit_msg>switch NFL back to all scores<commit_after>'use strict';

const ordinal = require('../../lib/ordinal');

class Instance {
  constructor(instance) {
    this.State = instance.State;
    this.Quarter = instance.Quarter;
    this.Time = instance.Time;
    this.HomeScore = instance.HomeScore;
    this.AwayScore = instance.AwayScore;
  }
  timeNum() {
    return parseInt(this.Time.replace(/\D/g, ''));
  }
  scoreChanged(prevInstance) {
    return prevInstance.State !== this.State ||
      prevInstance.Quarter !== this.Quarter ||
      prevInstance.HomeScore !== this.HomeScore ||
      prevInstance.AwayScore !== this.AwayScore;
  }
  leadChangeString(prevInstance, game) {
    let str = '';
    const scores = game.AwayTeam.Name + ' ' + this.AwayScore + ', ' +
      game.HomeTeam.Name + ' ' + this.HomeScore + '. ';
    const leadString = ' take the lead. ';
    const time = `${this.Time} ${ordinal(this.Quarter)} quarter.`;
    if (this.State !== prevInstance.State) {
      if (prevInstance.State === 'Pregame' && this.State === 'Progress') {
        str = `Start of game: ${game.AwayTeam.Name} vs ${game.HomeTeam.Name}`;
      }
      if (this.State === 'Final') {
        str = `Final${(prevInstance.Quarter === 'OT' ? ' OT' : '')}. ${scores}`;
      }
    } else if ((this.Quarter === prevInstance.Quarter && prevInstance.timeNum() >= this.timeNum()) || (prevInstance.Quarter < this.Quarter)) {
      if (prevInstance.AwayScore > this.AwayScore || prevInstance.HomeScore > this.HomeScore) {
        str = `Score correction. ${scores} ${time}`;
      } else if (prevInstance.AwayScore === prevInstance.HomeScore) {
        if (this.AwayScore > this.HomeScore) {
          str = game.AwayTeam.Name + leadString + scores + time;
        } else if (this.HomeScore > this.AwayScore){
          str = game.HomeTeam.Name + leadString + scores + time;
        }
      } else if (this.AwayScore === this.HomeScore) {
        if (prevInstance.AwayScore < prevInstance.HomeScore) {
          str = game.AwayTeam.Name + ' tie it up. ' + scores + time;
        } else if (prevInstance.HomeScore < prevInstance.AwayScore) {
          str = game.HomeTeam.Name + ' tie it up. ' + scores + time;
        }
      } else if (prevInstance.AwayScore < prevInstance.HomeScore && this.HomeScore < this.AwayScore) {
        str = game.AwayTeam.Name + leadString + scores + time;
      } else if (prevInstance.HomeScore < prevInstance.AwayScore && this.AwayScore < this.HomeScore) {
        str = game.HomeTeam.Name + leadString + scores + time;
      }
    }
    return str ? (str.trim() + ' ' + game.makeGameLink()) : '';
  }
  allChangeString(prevInstance, game) {
    let str = '';
    const scores = game.AwayTeam.Name + ' ' + this.AwayScore + ', ' +
      game.HomeTeam.Name + ' ' + this.HomeScore + '. ';
    const time = `${this.Time} ${ordinal(this.Quarter)} quarter.`;
    if (this.State !== prevInstance.State) {
      if (prevInstance.State === 'Pregame' && this.State === 'Progress') {
        str = `Start of game: ${game.AwayTeam.Name} vs ${game.HomeTeam.Name}`;
      }
      if (this.State === 'Final') {
        str = `Final${(prevInstance.Quarter === 'OT' ? ' OT' : '')}. ${scores}`;
      }
    } else if ((this.Quarter === prevInstance.Quarter && prevInstance.timeNum() >= this.timeNum()) || (prevInstance.Quarter < this.Quarter)) {
      if (prevInstance.AwayScore > this.AwayScore || prevInstance.HomeScore > this.HomeScore) {
        str = `Score correction. ${scores} ${time}`;
      } else if (prevInstance.AwayScore !== this.AwayScore) {
        str = `${game.AwayTeam.Name} score. ${scores} ${time}`;
      } else if (prevInstance.HomeScore !== this.HomeScore) {
        str = `${game.HomeTeam.Name} score. ${scores} ${time}`;
      }
    }
    return str ? (str.trim() + ' ' + game.makeGameLink()) : '';
  }
  changeString(prevInstance, game) {
    return this.allChangeString(prevInstance, game);
  }
}

Instance.parse = function(raw) {
  const instanceObj = {
    Time: raw.clock,
    HomeScore: raw.home.score.T,
    AwayScore: raw.away.score.T
  };
  if (!raw.qtr) {
    instanceObj.State = 'Pregame';
  } else if (!isNaN(parseInt(raw.qtr))) {
    instanceObj.State = 'Progress';
    instanceObj.Quarter = parseInt(raw.qtr) > 4 ? 'OT' : parseInt(raw.qtr);
  } else if (raw.qtr.toLocaleLowerCase().indexOf('final') !== -1) {
    instanceObj.State = 'Final';
  } else {
    instanceObj.State = raw.qtr;
  }

  return new Instance(instanceObj);
};

module.exports = Instance;
<|endoftext|>


<commit_before>exports.BattleTypeChart = {
  "Bug": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 2,
      "Fire": 1,
      "Flying": 1,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 2,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"atk":30,"def":30,"spd":30}
  },
  "Dark": {
    "damageTaken": {
      "Bug": 1,
      "Dark": 2,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 2,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 3,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {}
  },
  "Dragon": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 1,
      "Electric": 2,
      "Fighting": 0,
      "Fire": 2,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 0,
      "Ice": 1,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 2
    },
    "HPivs": {"atk":30}
  },
  "Electric": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 2,
      "Fighting": 0,
      "Fire": 0,
      "Flying": 2,
      "Ghost": 0,
      "Grass": 0,
      "Ground": 1,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 2,
      "Water": 0
    },
    "HPivs": {"spa":30}
  },
  "Fighting": {
    "damageTaken": {
      "Bug": 2,
      "Dark": 2,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 0,
      "Fire": 0,
      "Flying": 1,
      "Ghost": 0,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 1,
      "Rock": 2,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"def":30,"spa":30,"spd":30,"spe":30}
  },
  "Fire": {
    "damageTaken": {
      brn: 3,
      "Bug": 2,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 0,
      "Fire": 2,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 1,
      "Ice": 2,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 2,
      "Water": 1
    },
    "HPivs": {"atk":30,"spa":30,"spe":30}
  },
  "Flying": {
    "damageTaken": {
      "Bug": 2,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 1,
      "Fighting": 2,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 3,
      "Ice": 1,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"hp":30,"atk":30,"def":30,"spa":30,"spd":30}
  },
  "Ghost": {
    "damageTaken": {
      "Bug": 2,
      "Dark": 1,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 3,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 1,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 3,
      "Poison": 2,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
      trapped: null,
    },
    "HPivs": {"def":30,"spd":30}
  },
  "Grass": {
    "damageTaken": {
      "Bug": 1,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 2,
      "Fighting": 0,
      "Fire": 1,
      "Flying": 1,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 2,
      "Ice": 1,
      "Normal": 0,
      "Poison": 1,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 2
    },
    "HPivs": {"atk":30,"spa":30}
  },
  "Ground": {
    "damageTaken": {
      sandstorm: 3,
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 3,
      "Fighting": 0,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 1,
      "Ground": 0,
      "Ice": 1,
      "Normal": 0,
      "Poison": 2,
      "Psychic": 0,
      "Rock": 2,
      "Steel": 0,
      "Water": 1
    },
    "HPivs": {"spa":30,"spd":30}
  },
  "Ice": {
    "damageTaken": {
      hail: 3,
      frz: 3,
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 1,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 0,
      "Ground": 0,
      "Ice": 2,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 1,
      "Water": 0
    },
    "HPivs": {"atk":30,"def":30}
  },
  "Normal": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 3,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    }
  },
  "Poison": {
    "damageTaken": {
      psn: 3,
      tox: 3,
      "Bug": 2,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 2,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 1,
      "Ice": 0,
      "Normal": 0,
      "Poison": 2,
      "Psychic": 1,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"def":30,"spa":30,"spd":30}
  },
  "Psychic": {
    "damageTaken": {
      "Bug": 1,
      "Dark": 1,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 2,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 1,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 2,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"atk":30,"spe":30}
  },
  "Rock": {
    "damageTaken": {
      sandstorm: 3,
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 2,
      "Flying": 2,
      "Ghost": 0,
      "Grass": 1,
      "Ground": 1,
      "Ice": 0,
      "Normal": 2,
      "Poison": 2,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 1,
      "Water": 1
    },
    "HPivs": {"def":30,"spd":30,"spe":30}
  },
  "Steel": {
    "damageTaken": {
      psn: 3,
      tox: 3,
      sandstorm: 3,
      "Bug": 2,
      "Dark": 2,
      "Dragon": 2,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 1,
      "Flying": 2,
      "Ghost": 2,
      "Grass": 2,
      "Ground": 1,
      "Ice": 2,
      "Normal": 2,
      "Poison": 3,
      "Psychic": 2,
      "Rock": 2,
      "Steel": 2,
      "Water": 0
    },
    "HPivs": {"spd":30}
  },
  "Water": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 1,
      "Fighting": 0,
      "Fire": 2,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 1,
      "Ground": 0,
      "Ice": 2,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 2,
      "Water": 2
    },
    "HPivs": {"atk":30,"def":30,"spa":30}
  },
  "Fairy": null
};
<commit_msg>Fix crash in 42b9ad<commit_after>exports.BattleTypeChart = {
  "Bug": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 2,
      "Fire": 1,
      "Flying": 1,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 2,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"atk":30,"def":30,"spd":30}
  },
  "Dark": {
    "damageTaken": {
      "Bug": 1,
      "Dark": 2,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 2,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 3,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {}
  },
  "Dragon": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 1,
      "Electric": 2,
      "Fighting": 0,
      "Fire": 2,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 0,
      "Ice": 1,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 2
    },
    "HPivs": {"atk":30}
  },
  "Electric": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 2,
      "Fighting": 0,
      "Fire": 0,
      "Flying": 2,
      "Ghost": 0,
      "Grass": 0,
      "Ground": 1,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 2,
      "Water": 0
    },
    "HPivs": {"spa":30}
  },
  "Fighting": {
    "damageTaken": {
      "Bug": 2,
      "Dark": 2,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 0,
      "Fire": 0,
      "Flying": 1,
      "Ghost": 0,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 1,
      "Rock": 2,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"def":30,"spa":30,"spd":30,"spe":30}
  },
  "Fire": {
    "damageTaken": {
      brn: 3,
      "Bug": 2,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 0,
      "Fire": 2,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 1,
      "Ice": 2,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 2,
      "Water": 1
    },
    "HPivs": {"atk":30,"spa":30,"spe":30}
  },
  "Flying": {
    "damageTaken": {
      "Bug": 2,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 1,
      "Fighting": 2,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 3,
      "Ice": 1,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"hp":30,"atk":30,"def":30,"spa":30,"spd":30}
  },
  "Ghost": {
    "damageTaken": {
      "Bug": 2,
      "Dark": 1,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 3,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 1,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 3,
      "Poison": 2,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 0,
      trapped: null
    },
    "HPivs": {"def":30,"spd":30}
  },
  "Grass": {
    "damageTaken": {
      "Bug": 1,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 2,
      "Fighting": 0,
      "Fire": 1,
      "Flying": 1,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 2,
      "Ice": 1,
      "Normal": 0,
      "Poison": 1,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 2
    },
    "HPivs": {"atk":30,"spa":30}
  },
  "Ground": {
    "damageTaken": {
      sandstorm: 3,
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 3,
      "Fighting": 0,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 1,
      "Ground": 0,
      "Ice": 1,
      "Normal": 0,
      "Poison": 2,
      "Psychic": 0,
      "Rock": 2,
      "Steel": 0,
      "Water": 1
    },
    "HPivs": {"spa":30,"spd":30}
  },
  "Ice": {
    "damageTaken": {
      hail: 3,
      frz: 3,
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 1,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 0,
      "Ground": 0,
      "Ice": 2,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 1,
      "Steel": 1,
      "Water": 0
    },
    "HPivs": {"atk":30,"def":30}
  },
  "Normal": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 3,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    }
  },
  "Poison": {
    "damageTaken": {
      psn: 3,
      tox: 3,
      "Bug": 2,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 2,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 2,
      "Ground": 1,
      "Ice": 0,
      "Normal": 0,
      "Poison": 2,
      "Psychic": 1,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"def":30,"spa":30,"spd":30}
  },
  "Psychic": {
    "damageTaken": {
      "Bug": 1,
      "Dark": 1,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 2,
      "Fire": 0,
      "Flying": 0,
      "Ghost": 1,
      "Grass": 0,
      "Ground": 0,
      "Ice": 0,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 2,
      "Rock": 0,
      "Steel": 0,
      "Water": 0
    },
    "HPivs": {"atk":30,"spe":30}
  },
  "Rock": {
    "damageTaken": {
      sandstorm: 3,
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 2,
      "Flying": 2,
      "Ghost": 0,
      "Grass": 1,
      "Ground": 1,
      "Ice": 0,
      "Normal": 2,
      "Poison": 2,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 1,
      "Water": 1
    },
    "HPivs": {"def":30,"spd":30,"spe":30}
  },
  "Steel": {
    "damageTaken": {
      psn: 3,
      tox: 3,
      sandstorm: 3,
      "Bug": 2,
      "Dark": 2,
      "Dragon": 2,
      "Electric": 0,
      "Fighting": 1,
      "Fire": 1,
      "Flying": 2,
      "Ghost": 2,
      "Grass": 2,
      "Ground": 1,
      "Ice": 2,
      "Normal": 2,
      "Poison": 3,
      "Psychic": 2,
      "Rock": 2,
      "Steel": 2,
      "Water": 0
    },
    "HPivs": {"spd":30}
  },
  "Water": {
    "damageTaken": {
      "Bug": 0,
      "Dark": 0,
      "Dragon": 0,
      "Electric": 1,
      "Fighting": 0,
      "Fire": 2,
      "Flying": 0,
      "Ghost": 0,
      "Grass": 1,
      "Ground": 0,
      "Ice": 2,
      "Normal": 0,
      "Poison": 0,
      "Psychic": 0,
      "Rock": 0,
      "Steel": 2,
      "Water": 2
    },
    "HPivs": {"atk":30,"def":30,"spa":30}
  },
  "Fairy": null
};
<|endoftext|>


<commit_before>const connector = require('./Connector')

let _where = ''
let _select = ''
let _from = ''
let _orderBy = ''
let _groupBy = ''
let _limit = ''
let _skip = ''
let _join = ''
let _insert = ''
let _delete = ''
let _update = ''
let _command = ''
let _table = ''
let _option = ''
let _params = []

/**
 * [Generate ? symbol for sql query for every parameter]
 * @param  {Array} columns [List of all parameters on sql query]
 * @return {String}        [Correct syntax for query builder of parameters]
 */
function returnSymbolParamsCount (columns) {
  let length = columns.length
  let symbols = Array(length).join('?, ')
  return symbols.slice(0, -2)
}

module.exports = {

  /**
   * [Select clause of sql query which select the columns (properties) of records]
   * @param  {Array} columns [Array or String All selected columns from table]
   * @return {QueryBuilder}  [Query Builder Creator of sql queries and connect to database]
   */
  select: function (columns) {
    if (Array.isArray(columns)) {
      _select = `SELECT ${columns.join(', ')}`
    } else if (columns.length > 0) {
      _select = `SELECT ${columns}`
    } else {
      throw new Error('The columns is not available in correct format!')
    }

    _option = 'select'
    return this
  },

  /**
   * [From clause of sql query which select the database table]
   * @param  {String} table [The name of database table]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  from: function (table) {
    if (table.length > 0 && !Array.isArray(table)) {
      _from = ` FROM ${table}`
      _table = table
      return this
    } else {
      throw new Error('The table variable is required to be string!')
    }
  },

  /**
   * [Set the name of database table]
   * @param  {String} table [The name of database table]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  table: function (table) {
    if (table.length > 0 && !Array.isArray(table)) {
      _table = table
      return this
    } else {
      throw new Error('The table variable is required to be string!')
    }
  },

  /**
   * [Add few more columns on select caluse of sql query]
   * @param  {String} columns [Array or String All selected columns from table]
   * @return {QueryBuilder}  [Query Builder Creator of sql queries and connect to database]
   */
  addSelect: function (columns) {
    if (!_select) {
      throw new Error('Please first use SELECT method before add new column on select method!')
    } else if (Array.isArray(columns)) {
      _select += ` ${columns.join(', ')}`
    } else if (columns.length > 0) {
      _select += ` ${columns}`
    } else {
      throw new Error('The columns is not available in correct format!')
    }

    return this
  },

  /**
   * [Insert clause on sql query which is create to add new record on database]
   * @param  {Array} columns [All columns which is to add on database]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  add: function (columns) {
    if (Array.isArray(columns)) {
      let symbols = returnSymbolParamsCount(columns)

      if (symbols.length > 0) {
        _insert = 'INSERT INTO `' + _table + '` ( ' + symbols + ' ) VALUES ( ' + symbols + ' )'
        _option = 'insert'
        return this
      } else {
        throw new Error('The columns is empty!')
      }
    } else {
      throw new Error('The columns is required to be array!')
    }
  },

  /**
   * [Delete clause on sql query which is delete record from database]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  delete: function () {
    if (_table) {
      _delete = `DELETE FROM ${_table}`
      _option = 'delete'
      return this
    } else {
      throw new Error('Is need to enter in which table is need to delete record!')
    }
  },

  /**
   * [Update clause on sql query which is update current record on database]
   * @param  {Array} columns [All columns which is update on databse]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  update: function (columns) {
    if (!Array.isArray(columns)) {
      throw new Error('The columns variable is required to be array!')
    }

    if (!_table) {
      throw new Error('Is need to enter in which table is need to delete record!')
    }

    let cl = columns.map((cl) => { return cl + ' = ?, ' })
    _update = `UPDATE ${_table} SET ${cl.join('').slice(0, -2)}`
    _option = 'update'
    return this
  },

  /**
   * [Join clause on sql query which is just join another table on sql query]
   * @param  {String} table [The database table which is need to join]
   * @param  {String} equal [The columns ids equals on both databases]
   * @param  {String} type  [Type of join clause (left, inner, outer etc)]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  join: function (table, equal, type) {
    if (typeof table === 'string' && table.length > 1 &&
    typeof equal === 'string' && equal.length > 1) {
      _join += ` ${type} JOIN ${table} ON ${equal}`
      return this
    } else {
      throw new Error('The table and equal variable is required to be string!')
    }
  },

  /**
   * [Take clause on sql query which is set how many records to take from database table]
   * @param  {Number} limit [How many items to take]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  take: function (limit) {
    limit = parseInt(limit)

    if (isNaN(limit)) {
      throw new Error('The limit variable is required to be Integer!')
    }

    _limit = ` LIMIT ${limit}`
    return this
  },

  /**
   * [Skip clause on sql query which is set how many records to skip from database table]
   * @param  {Number} count [How many items to skip]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  skip: function (count) {
    count = parseInt(count)

    if (isNaN(count)) {
      throw new Error('The count variable is required to be Integer!')
    }

    _skip = ` OFFSET ${count}`
    return this
  },

  /**
   * [Top clause on sql query which is set how many records to get from database table]
   * @param  {Number} count [How many items to show]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  top: function (count) {
    if (_select) {
      throw new Error('Is need to not have select!')
    }

    count = parseInt(count)

    if (isNaN(count)) {
      throw new Error('The count variable is required to be Integer!')
    }

    _select = `SELECT TOP ${count} `
    _option = 'select'
    return this
  },

  /**
   * [Order clause on sql query which is order by one column]
   * @param  {String}  column         [The column on table with which is to be ordered]
   * @param  {Boolean} [isDesc=false] [Do is DESC or ASC]
   * @return {QueryBuilder}           [Query Builder Creator of sql queries and connect to database]
   */
  orderBy: function (column, isDesc = false) {
    if (typeof column !== 'string') {
      throw new Error('The column variable is required to be string!')
    }

    _orderBy = ` ORDER BY ${column} `

    if (isDesc) {
      _orderBy += ' DESC '
    }

    return this
  },

  /**
   * [Group clause on sql query which is set the grouped by column]
   * @param  {String}  column         [The column on table with which is to be grouped]
   * @param  {Boolean} [isDesc=false] [Do is DESC or ASC]
   * @return {QueryBuilder}           [Query Builder Creator of sql queries and connect to database]
   */
  groupBy: function (column, isDesc = false) {
    if (typeof column !== 'string') {
      throw new Error('The column variable is required to be string!')
    }

    _groupBy = ` GROUP BY ${column} `

    if (isDesc) {
      _groupBy += ' DESC '
    }

    return this
  },

  /**
   * [Where clause on sql query which is check do column is some equal with param]
   * @param  {String} column         [Column from database table to check do is some equal with param]
   * @param  {String} [operator='='] [Operator for comparison the column and parameter]
   * @param  {String} [param=null]   [Value to check do column from database table is some equal with value]
   * @return {QueryBuilder}          [Query Builder Creator of sql queries and connect to database]
   */
  where: function (column, operator = '=', param = null) {
    if (typeof column === 'string' && typeof operator === 'string') {
      _where = ` WHERE ${column} ${operator.replace(/'"/g, '')} ?`

      if (param && !Array.isArray(param)) {
        _params.push(param)
      }

      return this
    } else {
      throw new Error('The column and operator variable is required to be string!')
    }
  },

  /**
   * [If is used the where clause then that is next where clause if is need both to be true]
   * @param  {String} column         [Column from database table to check do is some equal with param]
   * @param  {String} [operator='='] [Operator for comparison the column and parameter]
   * @param  {String} [param=null]   [Value to check do column from database table is some equal with value]
   * @return {QueryBuilder}          [Query Builder Creator of sql queries and connect to database]
   */
  andWhere: function (column, operator = '=', param = null) {
    return this
  },

  orWhere: function (column, operator = '=', param = null) {

  },

  /**
   * [Get all sql query parameters]
   * @return {Array} [SQL Query parameters]
   */
  getParameters: () => {
    return _params
  },

  /**
   * [Set parameters for created sql query]
   * @param  {Array} values [SQL query parameres only values]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  setParameters: function (values) {
    let len = values.length

    if (len > 0) {
      for (let i = 0; i < len; i++) {
        _params.push(values[i])
      }

      return this
    } else {
      throw new Error('The values variable is required to be array!')
    }
  },

  /**
   * [Get the created sql query]
   * @return {String} [SQL Query]
   */
  getCommand: () => {
    return _command
  },

  /**
   * [Set Your own SQL Query]
   * @param  {String} command [SQL Query]
   * @return {QueryBuilder}   [Query Builder Creator of sql queries and connect to database]
   */
  setCommand: function (command) {
    if (typeof command !== 'string') {
      throw new Error('The command variable is required to be string!')
    }
    _command = command
    return this
  },

  /**
   * [Prepare the sql query and set what kind of query is will used]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  prepare: function () {
    if (_option === 'select') {
      _command = _select + _from + _join + _groupBy + _where + _orderBy + _limit + _skip
    } else if (_option === 'insert') {
      _command = _insert
    } else if (_option === 'update') {
      _command = _update + _where
    } else if (_option === 'delete') {
      _command = _delete + _where
    } else {
      _command = _where + _limit + _skip
    }

    _select = ''
    _from = ''
    _join = ''
    _groupBy = ''
    _where = ''
    _orderBy = ''
    _limit = ''
    _skip = ''
    _insert = ''
    _update = ''
    _delete = ''

    return this
  },

  execute: function () {

  },

  get: () => {

  }
}
<commit_msg>Add the comments on execute and get functions<commit_after>const connector = require('./Connector')

let _where = ''
let _select = ''
let _from = ''
let _orderBy = ''
let _groupBy = ''
let _limit = ''
let _skip = ''
let _join = ''
let _insert = ''
let _delete = ''
let _update = ''
let _command = ''
let _table = ''
let _option = ''
let _params = []

/**
 * [Generate ? symbol for sql query for every parameter]
 * @param  {Array} columns [List of all parameters on sql query]
 * @return {String}        [Correct syntax for query builder of parameters]
 */
function returnSymbolParamsCount (columns) {
  let length = columns.length
  let symbols = Array(length).join('?, ')
  return symbols.slice(0, -2)
}

module.exports = {

  /**
   * [Select clause of sql query which select the columns (properties) of records]
   * @param  {Array} columns [Array or String All selected columns from table]
   * @return {QueryBuilder}  [Query Builder Creator of sql queries and connect to database]
   */
  select: function (columns) {
    if (Array.isArray(columns)) {
      _select = `SELECT ${columns.join(', ')}`
    } else if (columns.length > 0) {
      _select = `SELECT ${columns}`
    } else {
      throw new Error('The columns is not available in correct format!')
    }

    _option = 'select'
    return this
  },

  /**
   * [From clause of sql query which select the database table]
   * @param  {String} table [The name of database table]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  from: function (table) {
    if (table.length > 0 && !Array.isArray(table)) {
      _from = ` FROM ${table}`
      _table = table
      return this
    } else {
      throw new Error('The table variable is required to be string!')
    }
  },

  /**
   * [Set the name of database table]
   * @param  {String} table [The name of database table]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  table: function (table) {
    if (table.length > 0 && !Array.isArray(table)) {
      _table = table
      return this
    } else {
      throw new Error('The table variable is required to be string!')
    }
  },

  /**
   * [Add few more columns on select caluse of sql query]
   * @param  {String} columns [Array or String All selected columns from table]
   * @return {QueryBuilder}  [Query Builder Creator of sql queries and connect to database]
   */
  addSelect: function (columns) {
    if (!_select) {
      throw new Error('Please first use SELECT method before add new column on select method!')
    } else if (Array.isArray(columns)) {
      _select += ` ${columns.join(', ')}`
    } else if (columns.length > 0) {
      _select += ` ${columns}`
    } else {
      throw new Error('The columns is not available in correct format!')
    }

    return this
  },

  /**
   * [Insert clause on sql query which is create to add new record on database]
   * @param  {Array} columns [All columns which is to add on database]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  add: function (columns) {
    if (Array.isArray(columns)) {
      let symbols = returnSymbolParamsCount(columns)

      if (symbols.length > 0) {
        _insert = 'INSERT INTO `' + _table + '` ( ' + symbols + ' ) VALUES ( ' + symbols + ' )'
        _option = 'insert'
        return this
      } else {
        throw new Error('The columns is empty!')
      }
    } else {
      throw new Error('The columns is required to be array!')
    }
  },

  /**
   * [Delete clause on sql query which is delete record from database]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  delete: function () {
    if (_table) {
      _delete = `DELETE FROM ${_table}`
      _option = 'delete'
      return this
    } else {
      throw new Error('Is need to enter in which table is need to delete record!')
    }
  },

  /**
   * [Update clause on sql query which is update current record on database]
   * @param  {Array} columns [All columns which is update on databse]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  update: function (columns) {
    if (!Array.isArray(columns)) {
      throw new Error('The columns variable is required to be array!')
    }

    if (!_table) {
      throw new Error('Is need to enter in which table is need to delete record!')
    }

    let cl = columns.map((cl) => { return cl + ' = ?, ' })
    _update = `UPDATE ${_table} SET ${cl.join('').slice(0, -2)}`
    _option = 'update'
    return this
  },

  /**
   * [Join clause on sql query which is just join another table on sql query]
   * @param  {String} table [The database table which is need to join]
   * @param  {String} equal [The columns ids equals on both databases]
   * @param  {String} type  [Type of join clause (left, inner, outer etc)]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  join: function (table, equal, type) {
    if (typeof table === 'string' && table.length > 1 &&
    typeof equal === 'string' && equal.length > 1) {
      _join += ` ${type} JOIN ${table} ON ${equal}`
      return this
    } else {
      throw new Error('The table and equal variable is required to be string!')
    }
  },

  /**
   * [Take clause on sql query which is set how many records to take from database table]
   * @param  {Number} limit [How many items to take]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  take: function (limit) {
    limit = parseInt(limit)

    if (isNaN(limit)) {
      throw new Error('The limit variable is required to be Integer!')
    }

    _limit = ` LIMIT ${limit}`
    return this
  },

  /**
   * [Skip clause on sql query which is set how many records to skip from database table]
   * @param  {Number} count [How many items to skip]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  skip: function (count) {
    count = parseInt(count)

    if (isNaN(count)) {
      throw new Error('The count variable is required to be Integer!')
    }

    _skip = ` OFFSET ${count}`
    return this
  },

  /**
   * [Top clause on sql query which is set how many records to get from database table]
   * @param  {Number} count [How many items to show]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  top: function (count) {
    if (_select) {
      throw new Error('Is need to not have select!')
    }

    count = parseInt(count)

    if (isNaN(count)) {
      throw new Error('The count variable is required to be Integer!')
    }

    _select = `SELECT TOP ${count} `
    _option = 'select'
    return this
  },

  /**
   * [Order clause on sql query which is order by one column]
   * @param  {String}  column         [The column on table with which is to be ordered]
   * @param  {Boolean} [isDesc=false] [Do is DESC or ASC]
   * @return {QueryBuilder}           [Query Builder Creator of sql queries and connect to database]
   */
  orderBy: function (column, isDesc = false) {
    if (typeof column !== 'string') {
      throw new Error('The column variable is required to be string!')
    }

    _orderBy = ` ORDER BY ${column} `

    if (isDesc) {
      _orderBy += ' DESC '
    }

    return this
  },

  /**
   * [Group clause on sql query which is set the grouped by column]
   * @param  {String}  column         [The column on table with which is to be grouped]
   * @param  {Boolean} [isDesc=false] [Do is DESC or ASC]
   * @return {QueryBuilder}           [Query Builder Creator of sql queries and connect to database]
   */
  groupBy: function (column, isDesc = false) {
    if (typeof column !== 'string') {
      throw new Error('The column variable is required to be string!')
    }

    _groupBy = ` GROUP BY ${column} `

    if (isDesc) {
      _groupBy += ' DESC '
    }

    return this
  },

  /**
   * [Where clause on sql query which is check do column is some equal with param]
   * @param  {String} column         [Column from database table to check do is some equal with param]
   * @param  {String} [operator='='] [Operator for comparison the column and parameter]
   * @param  {String} [param=null]   [Value to check do column from database table is some equal with value]
   * @return {QueryBuilder}          [Query Builder Creator of sql queries and connect to database]
   */
  where: function (column, operator = '=', param = null) {
    if (typeof column === 'string' && typeof operator === 'string') {
      _where = ` WHERE ${column} ${operator.replace(/'"/g, '')} ?`

      if (param && !Array.isArray(param)) {
        _params.push(param)
      }

      return this
    } else {
      throw new Error('The column and operator variable is required to be string!')
    }
  },

  /**
   * [If is used the where clause then that is next where clause if is need both to be true]
   * @param  {String} column         [Column from database table to check do is some equal with param]
   * @param  {String} [operator='='] [Operator for comparison the column and parameter]
   * @param  {String} [param=null]   [Value to check do column from database table is some equal with value]
   * @return {QueryBuilder}          [Query Builder Creator of sql queries and connect to database]
   */
  andWhere: function (column, operator = '=', param = null) {
    return this
  },

  orWhere: function (column, operator = '=', param = null) {

  },

  /**
   * [Get all sql query parameters]
   * @return {Array} [SQL Query parameters]
   */
  getParameters: () => {
    return _params
  },

  /**
   * [Set parameters for created sql query]
   * @param  {Array} values [SQL query parameres only values]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  setParameters: function (values) {
    let len = values.length

    if (len > 0) {
      for (let i = 0; i < len; i++) {
        _params.push(values[i])
      }

      return this
    } else {
      throw new Error('The values variable is required to be array!')
    }
  },

  /**
   * [Get the created sql query]
   * @return {String} [SQL Query]
   */
  getCommand: () => {
    return _command
  },

  /**
   * [Set Your own SQL Query]
   * @param  {String} command [SQL Query]
   * @return {QueryBuilder}   [Query Builder Creator of sql queries and connect to database]
   */
  setCommand: function (command) {
    if (typeof command !== 'string') {
      throw new Error('The command variable is required to be string!')
    }
    _command = command
    return this
  },

  /**
   * [Prepare the sql query and set what kind of query is will used]
   * @return {QueryBuilder} [Query Builder Creator of sql queries and connect to database]
   */
  prepare: function () {
    if (_option === 'select') {
      _command = _select + _from + _join + _groupBy + _where + _orderBy + _limit + _skip
    } else if (_option === 'insert') {
      _command = _insert
    } else if (_option === 'update') {
      _command = _update + _where
    } else if (_option === 'delete') {
      _command = _delete + _where
    } else {
      _command = _where + _limit + _skip
    }

    _select = ''
    _from = ''
    _join = ''
    _groupBy = ''
    _where = ''
    _orderBy = ''
    _limit = ''
    _skip = ''
    _insert = ''
    _update = ''
    _delete = ''

    return this
  },

  /**
   * [Execute the created sql query]
   * @return {Boolean} [Do is executed correct]
   */
  execute: function () {
    return true
  },

  /**
   * [Get the result from created sql query]
   * @return {[type]} [SQL Query result]
   */
  get: () => {

  }
}
<|endoftext|>


<commit_before>"use strict";

const debug = require("debug")("bot-express:memory");
const redis = require("redis");
const rejson = require("redis-rejson");
rejson(redis);
Promise = require("bluebird");
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);

class MemoryRedis {
    constructor(options){
        this.client = redis.createClient(options);
    }

    get(key){
        return this.client.json_getAsync(key);
    }

    put(key, value, retention){
        return this.client.json_setAsync(key, value, 'EX', retention);
    }

    del(key){
        return this.client.json_delAsync(key);
    }
}

module.exports = MemoryRedis;
<commit_msg>improving<commit_after>"use strict";

const debug = require("debug")("bot-express:memory");
const redis = require("redis");
const rejson = require("redis-rejson");
rejson(redis);
Promise = require("bluebird");
Promise.promisifyAll(redis.RedisClient.prototype);
Promise.promisifyAll(redis.Multi.prototype);

class MemoryRedis {
    constructor(options){
        this.client = redis.createClient(options);
    }

    get(key){
        return this.client.json_getAsync(key);
    }

    put(key, value, retention){
        return this.client.json_setAsync(key, value, 'EX', retention);
    }

    del(key){
        return this.client.delAsync(key);
    }
}

module.exports = MemoryRedis;
<|endoftext|>


<commit_before>// @flow

import tinycolor from 'tinycolor2'
import {black, white} from './colors'

/**
 * Given a background and a set of foreground colors, returns the first
 * foreground color that is readable (at WCAG AA-Small), or black/white if
 * none of the options were readable.
 */
export function firstReadable(
	background: string,
	possibilities: Array<string>,
) {
	possibilities = possibilities.map(c => tinycolor(c))
	let readable = possibilities.find(c => tinycolor.isReadable(c, background))
	if (readable) {
		return readable.toRgbString()
	}
	return tinycolor.mostReadable(background, [black, white]).toRgbString()
}
<commit_msg>making flow happy with the type of possibilities<commit_after>// @flow

import tinycolor from 'tinycolor2'
import {black, white} from './colors'

/**
 * Given a background and a set of foreground colors, returns the first
 * foreground color that is readable (at WCAG AA-Small), or black/white if
 * none of the options were readable.
 */
export function firstReadable(background: string, possibilities: Array<any>) {
	possibilities = possibilities.map(c => tinycolor(c))
	let readable = possibilities.find(c => tinycolor.isReadable(c, background))
	if (readable) {
		return readable.toRgbString()
	}
	return tinycolor.mostReadable(background, [black, white]).toRgbString()
}
<|endoftext|>


<commit_before>!(function(){

  var module = {sel: d3.select('[data-module="debug"]')}
  addModule(module)

  var dialogue = [
    {
      "emote": "explaining",
      "speak": "There are bugs in your code! Click the line of code that looks like they are BUG-FREE. And to make it extra-realistic, we made it so that every time you don’t fix a bug, a new bug is born. This is the true experience of programming!"
    },
    {
      "emote": "chill"
    }
  ];

  // announce itself
  if (typeof(bot) != 'undefined'){
    module.bot = bot();
    module.sel.insert("div.bot", ":first-child").call(module.bot);
    module.oninit = function() {
      module.bot.dialogue(dialogue);
    }
  }

  var width = 960,
      height = 500

  var buggContainer = module.sel.append("div.bugg-container")
      .style("width", width+"px")
      .style("height", height+"px");

  var svg = buggContainer.append('svg')
      .attr({width: width, height: height})
      .style({position: 'absolute', top: '0px'})

  var bugs = [
    { img: 'emotes/pose_moth.gif',
      pos: [width*.01, height*.05],
      wrong: 'var salesPlusFour = "4" + sales;',
      right: 'var salesPlusFour = 4 + sales;'},
    { img: 'emotes/pose_moth2.gif',
      pos: [width*.75, height*.05],
      wrong: 'for (var i = 0; i < 10 i++)',
      right: 'for (var i = 0; i < 10; i++)'},
    { img: 'emotes/pose_moth.gif',
      pos: [width*.75, height*.75],
      wrong: 'if (newBug == oldBug)',
      right: 'if (newBug === oldBug)'},
    { img: 'emotes/pose_moth2.gif',
      pos: [width*.02, height*.75],
      right: 'var total += currentValue',
      wrong: 'var total = +currentValue'},
    { img: 'emotes/pose_moth.gif',
      pos: [width*.50, height*.50],
      wrong: 'isBetween = min < next < max',
      right: 'isBetween = min < next && next < max'},
    { img: 'emotes/pose_moth2.gif',
      pos: [width*.0, height*.4],
      wrong: 'var x = Math.Sin(θ)',
      right: 'var x = Math.sin(θ)'},
    { img: 'emotes/pose_moth.gif',
      pos: [width*.40, height*.10],
      wrong: 'obj.function()',
      right: 'obj && obj.function && obj.function'},
  ]

  bugs.forEach(function(d){
    d.correct = false
    d.img = _.sample(['images/emotes/pose_moth.gif','images/emotes/pose_moth2.gif'])
    d.t = Math.random()
    d.visable = false
    d.spawned = false
  })

  function addBug(d, prev){
    if (!d || d.visable) return

    d.visable = true

    d.div = buggContainer.append('div.bugg')

    d.imgEl = d.div.append('img.bug-img').attr('src', d.img)

    d.qcontainer = d.div.append('div.q-container')
    d.qcontainer
      .dataAppend(_.shuffle([d.right, d.wrong]), 'div.awnser')
        .text(ƒ())
        .on('click', function(e){
          if (d.correct) return

          if (d.right == e){
            d.correct = true
            d.imgEl.transition().delay(300).style('opacity', 0)
            d3.select(this).style('color', green)
            d.div.classed('correct', true)

            svg.append('g').dataAppend([[Math.random()*width, 0], [0, Math.random()*height]], 'path.lazer')
                .attr('d', function(e){ return ['M', e, 'L', e].join('') })
                .style({'stroke-width': 1, stroke: 'yellow'})
              .transition().duration(400)
                .attr('d', function(e){ return ['M', e, 'L', [d.pos[0] + 150, d.pos[1] + 50]].join('') })
                .style({'stroke-width': 8, stroke: red})
              .transition()
                .style('opacity', 0)
                .style('stroke-width', 50)

          } else{
            addBug(bugs.filter(_.negate(ƒ('visable')))[0], d)
            d3.select(this).style('color', red)
          }
        })

    if (prev && prev.pos){
      d.qcontainer.style('opacity', 0).style('pointer-events', 'none')
      d.imgEl.style('width', '0px')
        .transition().duration(800)
          .style('width', '100px')
      d.div.call(posAt, prev.pos)
        .transition().duration(1000).ease('cubic')
          .call(posAt, d.pos)
          .each('end', function(){
            d.qcontainer
                .style('pointer-events', 'all')
              .transition()
                .style('opacity', 1)
          })
      //todo - hide questions, till pos is done, scale bug size
    } else{
      d.div.call(posAt, d.pos)
    }

  }
  addBug(bugs[0])
  addBug(bugs[1])
  addBug(bugs[2])

  d3.timer(function(t){
    if (!module.active) return
    bugs.forEach(function(d){
      if (d.correct || !d.visable) return
      d.imgEl
        .style('-webkit-transform', 'rotate(' + Math.sin(t/500 + d.t*500)*30 + 'deg)')
        .style('padding-left', Math.sin(t/743 + d.t*500)*60 + 'px')
        .style('padding-top', Math.sin(t/343 + d.t*700)*20 + 'px')
    })
  })

  function posAt(sel, pos){
    sel .style('left', pos[0] + 'px')
        .style('top' , pos[1] + 'px')
  }
})();
<commit_msg>debug only loads on init<commit_after>!(function(){

  var module = {sel: d3.select('[data-module="debug"]'), }
  addModule(module)

  var dialogue = [
    {
      "emote": "explaining",
      "speak": "There are bugs in your code! Click the line of code that looks like they are BUG-FREE. And to make it extra-realistic, we made it so that every time you don’t fix a bug, a new bug is born. This is the true experience of programming!"
    },
    {
      "emote": "chill"
    }
  ];

  // announce itself
  if (typeof(bot) != 'undefined'){
    module.bot = bot();
    module.sel.insert("div.bot", ".bugg-container").call(module.bot);
    module.oninit = function() {
      module.bot.dialogue(dialogue);
      initDraw()
    }
  }

  var width = 960,
      height = 500

  var buggContainer = module.sel.append("div.bugg-container")
      .style("width", width+"px")
      .style("height", height+"px");

  function initDraw(){
    var svg = buggContainer.append('svg')
        .attr({width: width, height: height})
        .style({position: 'absolute', top: '0px'})

    var bugs = [
      { img: 'emotes/pose_moth.gif',
        pos: [width*.01, height*.05],
        wrong: 'var salesPlusFour = "4" + sales;',
        right: 'var salesPlusFour = 4 + sales;'},
      { img: 'emotes/pose_moth2.gif',
        pos: [width*.75, height*.05],
        wrong: 'for (var i = 0; i < 10 i++)',
        right: 'for (var i = 0; i < 10; i++)'},
      { img: 'emotes/pose_moth.gif',
        pos: [width*.75, height*.75],
        wrong: 'if (newBug == oldBug)',
        right: 'if (newBug === oldBug)'},
      { img: 'emotes/pose_moth2.gif',
        pos: [width*.02, height*.75],
        right: 'var total += currentValue',
        wrong: 'var total = +currentValue'},
      { img: 'emotes/pose_moth.gif',
        pos: [width*.50, height*.50],
        wrong: 'isBetween = min < next < max',
        right: 'isBetween = min < next && next < max'},
      { img: 'emotes/pose_moth2.gif',
        pos: [width*.0, height*.4],
        wrong: 'var x = Math.Sin(θ)',
        right: 'var x = Math.sin(θ)'},
      { img: 'emotes/pose_moth.gif',
        pos: [width*.40, height*.10],
        wrong: 'obj.function()',
        right: 'obj && obj.function && obj.function'},
    ]

    bugs.forEach(function(d){
      d.correct = false
      d.img = _.sample(['images/emotes/pose_moth.gif','images/emotes/pose_moth2.gif'])
      d.t = Math.random()
      d.visable = false
      d.spawned = false
    })

    function addBug(d, prev){
      if (!d || d.visable) return

      d.visable = true

      d.div = buggContainer.append('div.bugg')

      d.imgEl = d.div.append('img.bug-img').attr('src', d.img)

      d.qcontainer = d.div.append('div.q-container')
      d.qcontainer
        .dataAppend(_.shuffle([d.right, d.wrong]), 'div.awnser')
          .text(ƒ())
          .on('click', function(e){
            if (d.correct) return

            if (d.right == e){
              d.correct = true
              d.imgEl.transition().delay(300).style('opacity', 0)
              d3.select(this).style('color', green)
              d.div.classed('correct', true)

              svg.append('g').dataAppend([[Math.random()*width, 0], [0, Math.random()*height]], 'path.lazer')
                  .attr('d', function(e){ return ['M', e, 'L', e].join('') })
                  .style({'stroke-width': 1, stroke: 'yellow'})
                .transition().duration(400)
                  .attr('d', function(e){ return ['M', e, 'L', [d.pos[0] + 150, d.pos[1] + 50]].join('') })
                  .style({'stroke-width': 8, stroke: red})
                .transition()
                  .style('opacity', 0)
                  .style('stroke-width', 50)

            } else{
              addBug(bugs.filter(_.negate(ƒ('visable')))[0], d)
              d3.select(this).style('color', red)
            }
          })

      if (prev && prev.pos){
        d.qcontainer.style('opacity', 0).style('pointer-events', 'none')
        d.imgEl.style('width', '0px')
          .transition().duration(800)
            .style('width', '100px')
        d.div.call(posAt, prev.pos)
          .transition().duration(1000).ease('cubic')
            .call(posAt, d.pos)
            .each('end', function(){
              d.qcontainer
                  .style('pointer-events', 'all')
                .transition()
                  .style('opacity', 1)
            })
        //todo - hide questions, till pos is done, scale bug size
      } else{
        d.div.call(posAt, d.pos)
      }

    }
    addBug(bugs[0])
    addBug(bugs[1])
    addBug(bugs[2])

    d3.timer(function(t){
      if (!module.active) return
      bugs.forEach(function(d){
        if (d.correct || !d.visable) return
        d.imgEl
          .style('-webkit-transform', 'rotate(' + Math.sin(t/500 + d.t*500)*30 + 'deg)')
          .style('padding-left', Math.sin(t/743 + d.t*500)*60 + 'px')
          .style('padding-top', Math.sin(t/343 + d.t*700)*20 + 'px')
      })
    })

    function posAt(sel, pos){
      sel .style('left', pos[0] + 'px')
          .style('top' , pos[1] + 'px')
    }

  }

})();
<|endoftext|>