text:
/*!
 * Isntit - a simple javascript validation library
 * version: 1.1.0
 * (c) 2016-2017 stoempsaucisse
 * Released under the MIT License.
 */

'use strict';

/**
 * Default configuration object.
 *
 * @type {Object}
 * @property {string}  env=NODE_ENV The environement for current runtime
 * @property {boolean} silent=false   Whether to silence warnings when devtools are enabled
 * @property {string[]} checkersSteps='before','during'  The list of validation steps chronolgicaly ordered.
 * @see  Step
 * @property {regexp}  confirmationRE=/(.+)_confirmation$/  The RegExp to test against to detect if a fieldname is a shorthand for the {@link Checker|confirms} checker.
 * @property {regexp}  emailRE=/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i  The RegExp to validate emails.
 * @copyright Many thanks to Jan Goyvaerts for his {@link http://www.regular-expressions.info/email.html|email regular expression}
 * @property {regexp}  emptyStringRE=/^[\s\t\n\r]+$/  The RegExp that defines which strings are considered as empty. This is used by {@link Isntit.isEmpty}
 * @property {string[]} emptyValues=null,undefined,'undefined'  The values to consider as empty. This is used by {@link Isntit.isEmpty}
 * @property {Object.<string, MessageTypes>} messages The fallback error messages tu use when validation against default checkers fails. Use the {@link Checker|checker name} as key.
 * @property {string} noLabelChar=^ Any error message starting with this chaaracter will never be prepended with the corresponding field name (even when {@link Options| options.fullMessages}) is true.
 */
var config = {
    env: process.env.NODE_ENV,
    silent: false,
    checkersSteps: ['before', 'during'],
    confirmationRE: /(.+)_confirmation$/,
    /**
     * Many thanks to Jan Goyvaerts for his email regular expression
     * @url : http://www.regular-expressions.info/email.html
     */
    emailRE: /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i,
    emptyStringRE: /^[\s\t\n\r]+$/,
    emptyValues: [null, undefined, 'undefined'],
    messages: {
        confirms: "should be sames as %{field}",
        required: "is required",
        email: "is not a valid email",
        format: "",
        length: function(context) {
            var rule = context.ruleSet['length'];
            if(rule.is) {
                return 'must be exactly %{is} characters long';
            }
            if(rule.min && rule.max) {
                return 'must be between %{min} and %{max} characters long';
            }
            if(rule.min) {
                return 'must be minimum %{min} characters long';
            }
            if(rule.max) {
                return 'must be maximum %{min} characters long';
            }
        },
        numeric: {
            onlyInteger: 'must be an integer',
            noStrings: 'strings are not allowed',
            equalTo: 'must be equal to %{equalTo}',
            notEqualTo: 'must not be equal to %{notEqualTo}',
            greaterThan: 'must be greater than %{greaterThan}',
            greaterThanOrEqualTo: 'must be greater than or equal to %{greaterThanOrEqualTo}',
            lessThan: 'must be less than %{lessThan}',
            lessThanOrEqualTo: 'must be less than or equal to %{lessThanOrEqualTo}'
        },
        notValid: "is not valid."
    },
    noLabelChar: "^"
};

/**
 * Perform no operation.
 *
 * @ignore
 */
function noop() {}

/**
 * Check whether the object has the property.
 *
 * @param {Object} obj The object for which the presence of a property with name = key.
 * @param {string} key The name of the property for which the presence is being checked.
 *
 * @returns {boolean} Whether given object has a property named as given key.
 *
 * @ignore
 */
function hasOwn (obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
}
// const hasOwnProperty = Object.prototype.hasOwnProperty

/**
 * Quick object check - this is primarily used to tell
 * Objects from primitive values when we know the value
 * is a JSON-compliant type.
 *
 * @param {Object} obj An object that needs to be checked if it actualy is one.
 *
 * @returns {boolean} Whether given object actualy is an object.
 *
 * @ignore
 */
function isObject (obj) {
  return obj !== null && typeof obj === 'object'
}

/**
 * Swap key-values pairs from object
 *
 * @param {Object} json  A flat object from which key-values should be swaped.
 *
 * @returns {Object}  An new object where the keys are the values from given object and the values are the keys from given object.
 *
 * @ignore
 */

var warn = noop;
/* eslint-disable no-console */
if ( config.env !== 'production') {
    var hasConsole = typeof console !== 'undefined';
    warn = function(msg, obj) {
        if (hasConsole && (!config.silent)) {
            if (obj) {
                console.error(("[Isntit warn]: " + msg), obj);
            } else {
                console.error(("[Isntit warn]: " + msg));
            }
        }
    };
}

/**
 * Parse a string to replace placeholders.
 *
 * @param    {string}                   str           The string to parse for
 *                                                    `%{placeholder}`.
 * @param    {Object.<string, string>}  replacements  A collection of
 *                                                    placeholder: value.
 *
 * @returns  {string}                                 The string with
 *                                                    placeholders replaced with
 *                                                    corresponding values.
 *                                                    If there is no match for
 *                                                    placeholder: value in
 *                                                    replacements, then `%{placeholder}`
 *                                                    will remain in the string.
 *
 * @alias Isntit.printf
 */
function printf(str, replacements) {
    return str.replace(/\%\{([\w\d_\.]+)\}/g, function(match, placeholder){
        if (typeof replacements[placeholder] != 'undefined') {
            return replacements[placeholder];
        }
        warn(("There is no replacement for " + match + " in " + str), replacements);
        return match;
    });
}

/**
 * Uppercase the first character of given string
 *
 * @ignore
 *
 * @param    {string}  str  The string to capitalize.
 *
 * @returns  {string}  The capitalized string.
 */
function ucfirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

/**
 * A simple javascript validation library
 *
 * @param        {Rules}    [rules={}]    Validation rules
 * @param        {Options}  [options={}]  Runtime options
 *
 * @constructor
 */
function Isntit$1(rules, options) {
    // called as function
    if (!(this instanceof Isntit$1)) {
        warn('Isntit([rules [, options]]) is a constructor and should be called with the "new" keyword.');
        return new Isntit$1(rules, options);
    }
    if (options && options.config) {
        Object.assign(config, options.config);
        delete options.config;
    }
    Object.assign(this.options, options || {});
    this.cache = {
        checkersToStep: {},
        messages: {}

    };
    this.checkRules(rules);
    this.rules = rules || {};
    this.errors = {};
}

/**
 * The validation rules object to pass to the {@link Isntit} constructor or to Isntit's validate method.
 *
 * @typedef   {Object.<string, Object>}  Rules
 * @property  {(Object.<string, Constraints>|boolean)}  `fieldName`  The rules to validate the value of field.
 * @property  {Constraints|boolean}  `fieldName`.`checkerName`  The constraints to pass to the checker.
 */

/**
 * The constraints to pass to corresponding {@link Checker|checker}.
 *
 * @typedef   {Object.<string, *>}  Constraints
 * @property {ErrorMessageProvider} [message] A customized error message.
 * @property {string|number|boolean} [`constraintName`]  The value of a constraint to pass to the checker.
 * @see  confirms|required|email|format|length|numeric
 */

/**
 * Check that the value is the same as the value in another field.
 *
 * @type {Constraints}
 * @property {string}               field     The field this field should confirm.
 * @property {boolean}              [strict]  Whether to compare strictly ('===') both field values or not ('==').
 * @property {ErrorMessageProvider} [message] A customized error message.
 * @example
 * "password_confirmation": true
 * // is converted to
 * "password_confirmation": {
 *     confirms: {
 *         field: "password"
 *     }
 * }
 */
var confirms = {
    validate: function(value, context) {
        var data = context.data;
        var _confirms = context.ruleSet.confirms;
        _confirms['otherValue'] = data[_confirms.field];
        return (_confirms.strict) ?
            (value === _confirms.otherValue) :
            (value == _confirms.otherValue);
    },
    types: ['boolean', { field: 'string' }]
};

/**
 * Check that a field is not empty (uses {@link Isntit.isEmpty}).
 *
 * @type  {(boolean|Constraints)}
 * @property {ErrorMessageProvider} [message] A customized error message.
 */
var required = {
    validate: function(value) {
        return !Isntit$1.isEmpty(value);
    },
    types: 'boolean'
};

/**
 * Check that the value is formated as an email (uses {@link Config|config.emailRE}).
 *
 * @name email
 * @type  {Constraints}
 * @property {ErrorMessageProvider} [message] A customized error message.
 */
var email = {
    validate: function(value){
        return config.emailRE.test(value);
    },
    preprocess: function(value) {
        var I = this;
        if (typeof value !== 'string') {
            I.cache.messages['email::preprocess'] = 'Values checked for email MUST be of type string. Given: ' + value;
            return false;
        }
        return true;

    },
    types: 'boolean'
};

/**
 * Check that the value matches against given RegExp.
 *
 * @name format
 * @type  {(regexp|Constraints)}
 * @property {regexp} pattern The RegExp to test against.
 * @property {ErrorMessageProvider} [message] A customized error message.
 */
var format = {
    validate: function(value, context) {
        var ruleSet = context.ruleSet;
        var RE = (ruleSet.format instanceof RegExp) ? ruleSet.format : ruleSet.format.pattern;
        return (RE.test(value));
    },
    preprocess: function(value) {
        var I = this;
        if (typeof value !== 'string' && typeof value !== 'number') {
            I.cache.messages['format::preprocess'] = 'Values checked for format MUST either be of type string or number. Given: ' + value;
            return false;
        }
        return true;

    },
    types: ['regexp', { pattern: 'regexp' }]
};

/**
 * Check that value comply with legth constraints.
 *
 * @name length
 * @type  {Constraints}
 * @property {number} [is] The exact length of the value.
 * @property {number} [min] The minimum length of the value.
 * @property {number} [max] The maximum length of the value.
 * @property {ErrorMessageProvider} [message] A customized error message.
 */
var length = {
    validate: {
        is: function(value, context) {
            return (value.length == context.ruleSet['length'].is);
        },
        min: function(value, context) {
            return (value.length >= context.ruleSet['length'].min);
        },
        max: function(value, context) {
            return (value.length <= context.ruleSet['length'].max);
        }
    },
    preprocess: function(value) {
        var I = this;
        if (value.length === undefined) {
            I.cache.messages['length::preprocess'] = 'Values checked for length MUST have a length property. Given: ' + value;
            return false;
        }
        return true;
    },
    types: {
        __all: 'number'
    }
};

/**
 * Check value by comparing it with given constraints.
 *
 * @name numeric
 * @type  {Constraints}
 * @property {number} [equalTo]
 * @property {number} [notEqualTo]
 * @property {number} [greaterThan]
 * @property {number} [greaterThanOrEqualTo]
 * @property {number} [lessThan]
 * @property {number} [lessThanOrEqualTo]
 * @property {number} [greaterThan]
 * @property {boolean} [noStrings]  Whether to accept numbers as strings
 * @property {boolean} [onlyIntegers]  Whether to accept only integers.
 * @property {ErrorMessageProvider} [message] A customized error message.
 */
var numeric = {
    validate: {
        equalTo: function(value, context) {
            return (+value == context.ruleSet['numeric'].equalTo);
        },
        notEqualTo: function(value, context) {
            return (+value != context.ruleSet['numeric'].notEqualTo);
        },
        greaterThan: function(value, context) {
            return (+value > context.ruleSet['numeric'].greaterThan);
        },
        greaterThanOrEqualTo: function(value, context) {
            return (+value >= context.ruleSet['numeric'].greaterThanOrEqualTo);
        },
        lessThan: function(value, context) {
            return (+value < context.ruleSet['numeric'].lessThan);
        },
        lessThanOrEqualTo: function(value, context) {
            return (+value <= context.ruleSet['numeric'].lessThanOrEqualTo);
        },
        noStrings: function(value) {
            return (typeof value !== 'string');
        },
        onlyInteger: function(value) {
            return ((+value) % 1 === 0);
        }

    },
    preprocess: function(value) {
        var I = this;
        if (typeof value !== 'string' && typeof value !== 'number') {
            I.cache.messages['numeric::preprocess'] = 'Values checked for numeric MUST either be of type string or number. Given: ' + value;
            return false;
        }
        return true;

    },
    types: {
        noStrings: 'boolean',
        onlyInteger: 'boolean',
        __others: 'number'
    }
};

/**
 * To customize the error messages you can either provide a string,
 * a function that returns a string or an object with `constraintName`s
 * as keys to a appropriated error message string. All error messages strings
 * are parsed by {@link Isntit.printf} to replace any `%{placeholders}`
 * with corresponding value taken from {@Constraints} properties (other than `message`).
 *
 * @typedef {(MessageString|MessageFunction|MessageObject)} ErrorMessageProvider
 */
/**
 * The message to show if corresponding checker fails.
 * This string is passed to {@link Isntit.printf} to replace `%{placeholders}`
 * with corresponding value taken from {@Constraints} properties (other than message).
 *
 * @typedef {string} MessageString  The string to show when the value is not valid.
 */
/**
 * A function that returns an error message should corresponding checker validation fail.
 *
 * @typedef {function}  MessageFunction
 * @param {Context} context  The context in which the failed checker has been called.
 * @param {string} [constraint]  The name of the constraint that failed for which a error message should be returned.
 * @returns {MessageString}
 */
/**
 * An object with `constraintName`s as keys and {@link MessageString}s or {@link MessageFunction}s as value.
 *
 * @typedef {Object.<string, (MessageString|MessageFunction)>}  MessageObject
 * @property {MessageString} [{@link Checker|`constraintName`}] A constraintName-MessageString pair.
 */

/**
 * The options object to pass to the {@link Isntit} constructor.
 *
 * @typedef   {Object}   Options
 * @property  {boolean}  [capitalize=true]    Whether to capitalize the first character of error messages.
 * @property  {boolean}  [devtools=true]      Whether to enable devtools (only for development build).
 * @property  {boolean}  [fullMessages=false]  Whether to prefix error messages with corresponding field name.
 * @property  {Object}   [config]        The {@link config} properties to override.
 */
Isntit$1.prototype.options = {
    capitalize: true,
    devtools: config.env !== 'production',
    fullMessages: false
};

/**
 * Collection of {@link Checker|checker}s ordered in separated steps.
 * The validation process simply loops over this Object. Step names have no effect
 * on the order.
 *
 * @typedef   {Object}  Checkers
 * @property  {Step}    before  A collection of checkers to call 'before' validation.
 * @property  {Step}    during  A collection of checkers called 'during' validation.
 * @property  {Step}    [`stepName`]  A collection of checkers to call in the 'stepName'.
 */

/**
 * A collection of {@link Checker|checker}s. Validation happens by steps. If one rule fails during current step, validation ends at the end of this step.
 *
 * @typedef  {Object.<string, Checker>}  Step
 */

/**
 * A checker is responsible for the validation of data. It holds the validation logic and the optional pre-validation check and type rules.
 *
 * @typedef  {Object.<string, (Object|function)>}  Checker
 * @property {(function|Object.<string, function>)} validate  The logic that validates the value. Receives value and the current {@link Context|context} as arguments.
 * @property {function} [preporcess]  A function that is called before actually validating the value. This is generaly used to check the type of given value and fail if the type is wrong without even trying to validate it.
 * @property {TypeRule} [types] When devtools are enabled, {@link Constraints|field rules} are checked with {@link checkType} to enforce the right types of constraints values.
 * @example
 * length: {
 *      validate: {
 *          is: function(value, context) {
 *              return (value.length == context.ruleSet['length'].is);
 *          },
 *          min: function(value, context) {
 *              return (value.length >= context.ruleSet['length'].min);
 *          },
 *          max: function(value, context) {
 *              return (value.length <= context.ruleSet['length'].max);
 *          }
 *      },
 *      preprocess: function(value, context) {
 *          var I = this;
 *          if (value.length === undefined) {
 *              I.cache.messages['length::preprocess'] = 'Values checked for length MUST have a length property. Given: ' + value;
 *              return false;
 *          }
 *          return true;
 *      },
 *      types: {
 *          __all: 'number'
 *      }
 *  }
 */

/**
 * The default checker collection.
 *
 * @type      {Checkers}
 * @property  {Step}    before    Checkers that are called before any other validation.
 * @property  {Checker} before.confirms  Check that the current field value is equal to the value of the field constraint. {@link confirms}
 * @property  {Checker} before.require Check that given value {@link Isntit.isEmpty|is not empty}. {@link require}
 * @property {Step} during The main validation step.
 * @property {Checker} during.email Check given value against the {@link Config|config.emailRE} RegExp.  {@link email}
 * @property {Checker} during.format Check given value against the pattern constraint.  {@link format}
 * @property {Checker} during.length Check the length of given value.  {@link length}
 * @property {Checker} during.numeric Compare given value against the rule constraints.  {@link numeric}
 * @see  Constraints
 */
var checkers = {
    before: {
        confirms: confirms,
        required: required
    },
    during: {
        email: email,
        format: format,
        length: length,
        numeric: numeric
    }
};

/**
 * Get the collection of steps and checkers currently in use.
 *
 * @returns  {Checkers}     The current Checkers.
 *
 * @see  Step
 */
Isntit$1.getCheckers = function() {
    return checkers;
};

/**
 * Register a checker. You may add a checker to a new or existing step or override an existing checker.
 *
 * @param    {Checker}  checker        The checker to register.
 * @param    {string}   name           The name to use.
 * @param    {string}   step           The step to register this checker to
 * @param    {string[]} checkersSteps  A list of steps to use dureing validation. Note that the order matters.
 * @see  Step
 */
Isntit$1.registerChecker = function(checker, name, step, checkersSteps) {
    var I = this;
    if (typeof checker !== 'function' && !hasOwn(checker, 'validate')) {
        if (arguments.length > 3) {
            warn('Instance methode registerChecker() signature is:\n(object[, step[, checkersSteps]]), supplemental arguments will be ignored.', Array.from(arguments));
        }
        for(var key in checker) {
            checkersSteps = step;
            if(config.checkersSteps.indexOf(key) !== -1) {
                step = key;
                for(name in checker[step]) {
                    I.registerChecker(checker[step][name], name, step, checkersSteps);
                }
            } else {
                step = name;
                I.registerChecker(checker[key], key, step, checkersSteps);
            }
        }
    } else {
        step = step || 'during';
        if (typeof name === 'undefined') {
            throw new Error('When registering a callback as checker, you must provide a name for it: registerChecker(callable, name[, step[, checkersSteps]])');
        }
        if(!hasOwn(checkers, step)) {
            checkers[step] = {};
            if (typeof checkersSteps === 'undefined') {
                config.checkersSteps.push(step);
            }
        }
        if (hasOwn(checker, 'validate')) {
            checkers[step][name] = checker;
        } else {
            checkers[step][name] = {
                validate: checker
            };
        }
    }
};

/**
 * Check if an object is considered as empty.
 *
 * @param    {*}        obj  Any javascript object
 *
 * @returns  {boolean}  Return if given object is empty or not.
 *
 * @see {@link Config|config.emptyStringRE}
 */
Isntit$1.isEmpty = function(obj) {
    var typeOf = typeof obj;
    if ((typeOf === 'string' || typeOf === 'array') && obj.length === 0) {
        return true;
    }
    if ((typeOf === 'string') && config.emptyStringRE.test(obj)) {
        return true;
    }
    if (isObject(obj) && Object.keys(obj).length === 0) {
        return true;
    }
    for (var i = 0; i < config.emptyValues.length; i++) {
        if (obj === config.emptyValues[i]) {
            return true;
        }
    }
    return false;
};

// Wraper to string.printf
// Documentation: see './string.printf'
Isntit$1.printf = printf;

// Wraper to string.ucfirst
// Documentation: see './string.ucfirst'
Isntit$1.ucfirst = ucfirst;

/**
 * Set that an error occured in given context durring current validation.
 *
 * @param    {Context}  context          The Context in which the error occured.
 * @param    {string}   fieldName        The name of the field under validation.
 * @param    {string}   ruleName         The name of the checker currently called.
 * @param    {string}   [constraintName] The name of the constraint of the checker currently called.
 *
 * @private
 */
function _setError(context, fieldName, ruleName, constraintName) {
    var I = this;
    if (!hasOwn(I.errors, fieldName)) {
        I.errors[fieldName] = {};
    }
    if (constraintName) {
        if (!hasOwn(I.errors[fieldName], ruleName)) {
            I.errors[fieldName][ruleName] = {};
        }
        I.errors[fieldName][ruleName][constraintName] = true;
    } else {
        I.errors[fieldName][ruleName] = true;
    }
}

/**
 * Check given value against given {@link Checker|checker} or its appropriated {@link Constraints|constraints}.
 *
 * @param    {Checker}  checker  The Checker currently to call.
 * @param    {*}        value    The value that must be checked.
 * @param    {Context}  context  The context in which the value has to be checked.
 *
 * @private
 */
function _callChecker(checker, value, context) {
    var I = this;
    if (typeof checker.validate === 'function') {
        if (!checker.validate.call(I, value, context)) {
            _setError.call(I, context, context.fieldName, context.ruleName);
        }
    } else {
        for (var constraint in context.ruleSet[context.ruleName]) {
            if (!checker.validate[constraint].call(I, value, context)) {
                _setError.call(I, context, context.fieldName, context.ruleName, constraint);
            }
        }
    }
}

/**
 * Get the appropriated error message in given {@link Context|context}.
 * Error messages are cached if not already and retrieved from cache.
 *
 * @param    {Context}  context       The Context in which the error happened.
 * @param    {string}   [constraint]  The name of the Constraint where the error happened.
 *
 * @returns  {string}                 The appropriated error message.
 *
 * @private
 */
function _getMsg(context, constraint) {
    var I = this;
    var key = context.ruleName + (constraint ? '::' + constraint : '');
    if (!I.cache.messages[key]) {
        var message;
        // Get the message from possible sources
        message = context.ruleSet[context.ruleName].message ||
            config.messages[context.ruleName] ||
            config.messages.notValid;
        // If constraint exists and is a prop on message, retrieve it or invalid
        if (isObject(message)) {
            message = message[constraint] || config.messages.notValid;
        }
        // If message is a function call it else asume its just a string
        I.cache.messages[key] = (typeof message === 'function') ?
            message(context, constraint) :
            message;
    }
    return I.cache.messages[key];
}

/**
 * Handle, prepare and set error messages for display.
 *
 * @param    {string}   fieldName  The name of the field currently under validation.
 * @param    {*}        value      The value of the field currently under validation.
 * @param    {Context}  context    The current Context in which value is validated.
 *
 * @private
 */
function _handleErrors(fieldName, value, context) {
    var I = this;
    var message = [];
    // Loop through rules
    for(var ruleName in I.errors[fieldName]) {
        if (I.errors[fieldName][ruleName] === true) {
            message.push(_getMsg.call(I, context));
        } else {
            for(var constraint in I.errors[fieldName][ruleName]) {
                message.push(_getMsg.call(I, context, constraint));
            }
        }
    }
    // Flatten message
    message = message.join(', ');
    // Prepare replacements for parsing
    var replacements = {
        value: context.value,
        label: context.ruleSet.label || context.fieldName
    };
    // Add properties from rule definition :
    // length.min = 1, numeric.noStrings = false,...
    Object.assign(replacements, context.ruleSet[context.ruleName]);
    // Should the message be prepended with %{label}
    var noPrepend = message.charAt(0) === config.noLabelChar;
    var fullMessage = context.rules[context.fieldName][context.ruleName]['fullMessage'] || I.options.fullMessages;
    if (fullMessage && !noPrepend) {
        message = '%{label} ' + message;
    }
    if (noPrepend) {
        message = message.substr(1);
    }
    // Parse message
    message = printf(message, replacements);
    // Should the message be prepended capitalized
    var capitalize = context.rules[context.fieldName][context.ruleName]['capitalize'] || I.options.capitalize;
    if (capitalize) {
        message = ucfirst(message);
    }
    // Replace array of messages with parsed message
    I.errors[context.fieldName] = message;
}

/**
 * The context in which the validate function of a checker is called (passed as second argument).
 *
 * @typedef  {Object}                       Context
 * @property {*}                            value        The value of the field under validation.
 * @property {string}                       `fieldName`  The name of the field under validation.
 * @property {Object.<string, *>}           data         The whole data object that is currently validated.
 * @property {string}                       `ruleName`   The name of the checker currently called.
 * @property {Object.<string, Constraints>}  ruleSet      The collection of rules to check current field against.
 * @property {Rules}                        rules        All the rules curently used during validation.
 * @property {string}                       step         The name of the current {@link Step|step}.
 *
 * @see  Checker
 */
/**
 * Looping through all registered checkers, step by step, to validate the given value.
 *
 * @param    {*}  value      The value under validation.
 * @param    {string}  fieldName  The name of the field under validation.
 * @param    {Object.<string, *>}  data       The data under validation.
 * @param    {Rules}  rules      The rules the data must comply with.
 *
 * @private
 */
function _loopThroughCheckers(value, fieldName, data, rules) {
    var I = this;
    for (var i = 0; i < config.checkersSteps.length; i++) {
        var step = config.checkersSteps[i];
        // Looping on rules for current data field
        for (var ruleName in rules[fieldName]) {
            // Select the right checker
            var checker = checkers[step][ruleName];
            if (typeof checker !== 'undefined') {
                // Exit loop and warn if rule === false
                if (rules[fieldName][ruleName] === false) {
                    warn(("Rule definition for '" + ruleName + "' set to 'false', are you shure?"), rules[fieldName]);
                    break;

                }
                // Set the current context
                var context = {
                    value: value,
                    fieldName: fieldName,
                    data: data,
                    ruleName: ruleName,
                    ruleSet: rules[fieldName],
                    rules: rules,
                    step: step
                };
                // Call preprocess
                if (typeof checker.preprocess === "function" && !checker.preprocess.call(I, value, context)) {
                    _setError.call(I, context, context.fieldName, context.ruleName, 'preprocess');
                } else {
                    _callChecker.call(I, checker, value, context);
                }
                if (hasOwn(I.errors, fieldName)) {
                    _handleErrors.call(I, fieldName, value, context);
                }
            }
        }
        if (typeof I.errors[fieldName] !== 'undefined') {
            break;
        }
    }
}

/**
 * Validate given data.
 *
 * @param    {Object.<string, *>}  data   The data to validate.
 * @param    {Rules}  [rules=this.rules]  The rules to validate aginst. If omited, the rules passed to the constructor are used.
 *
 * @returns  {boolean|Object.<string, string>}         Returns true if all data validates or a collection of fieldName-errorMessage pairs.
 */
Isntit$1.prototype.validate = function(data, rules) {
    var I = this;
    if (rules) {
        I.checkRules(rules);
    } else {
        rules = I.rules;
    }
    I.errors = {};
    // Looping on fields in data
    for (var fieldName in data) {
        if(hasOwn(data, fieldName)) {
            // Check if it is a shorthand for confirms
            if (rules[fieldName] === true) {
                var matches = fieldName.match(config.confirmationRE);
                if (matches) {
                    rules[fieldName] = {
                        confirms: {
                            field: matches[1]
                        }
                    };
                }
            }
            // Get the value to check
            var value = data[fieldName];
            _loopThroughCheckers.call(I, value, fieldName, data, rules);
        }
    }
    return (Isntit$1.isEmpty(I.errors)) ? true : I.errors;
};

Isntit$1.prototype.getCheckers = function() {
    return checkers;
};

Isntit$1.prototype.getMessages = function() {
    return this.errors;
};

Isntit$1.prototype.getStep = function(ruleName) {
    var I = this;
    if (!I.cache.checkersToStep[ruleName]) {
        for (var i = 0; i < config.checkersSteps.length; i++) {
            if (checkers[config.checkersSteps[i]][ruleName]) {
                I.cache.checkersToStep[ruleName] = config.checkersSteps[i];
                break;
            }
        }
        if (!I.cache.checkersToStep[ruleName]) {
            warn('No step found for "' + ruleName + '". Given: ' + JSON.stringify(checkers));
            return false;
        }
    }
    return I.cache.checkersToStep[ruleName];
};

Isntit$1.version = '1.1.0';

module.exports = Isntit$1;


text:
function changeScreanToAddPDF(id_Produit){
	var table = document.getElementById("myTable");
            var rowCount = table.rows.length;

    		var row = table.insertRow(rowCount);

    var index = id_Produit.parentNode.parentNode.rowIndex;
	var elemtIdProduit = table.rows[index].cells[0].innerHTML;
	var elemtNameProduit = table.rows[index].cells[1].innerHTML;

	// Store
sessionStorage.setItem("id_Produit", elemtIdProduit);
sessionStorage.setItem("nomProduit", elemtNameProduit);

 // Create our XMLHttpRequest object
    updReq = getXMLHttp();
    // Create some variables we need to send to our PHP file
    var url = "file-uploading/view.php";

    var idProd = sessionStorage.getItem("id_Produit");

    var vars = "idProduit="+idProd;
	updReq.open('POST', url, true);

        updReq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

        updReq.onreadystatechange = function() {//Call a function when the state changes.
                if(updReq.readyState == 4 && updReq.status == 200) {

                   window.location.replace("file-uploading/index.php");

                }

        }
        updReq.send(vars);

}

	function getXMLHttp()
	{
  var xmlHttp

  try
  {
    //Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    //Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e)
      {
        alert("Your browser does not support AJAX!")
        return false;
      }
    }
  }
  return xmlHttp;
}

function changeScreanToViewPDF(id_Produit){
	var table = document.getElementById("myTable");
            var rowCount = table.rows.length;

    		var row = table.insertRow(rowCount);

    var index = id_Produit.parentNode.parentNode.rowIndex;
	var elemtIdProduit = table.rows[index].cells[0].innerHTML;
	var elemtNameProduit = table.rows[index].cells[1].innerHTML;

	// Store
sessionStorage.setItem("id_Produit", elemtIdProduit);
sessionStorage.setItem("nomProduit", elemtNameProduit);

	window.location.replace("file-uploading/view.html");

}

function getFiles() {
	if(sessionStorage.getItem("UserLogged") == null){
		alert("Permission non accordée !\nVeuillez saisir vos paramètres d'accès");

		window.location.replace("index.html");
		sessionStorage.clear();
	}else{
		var data = {
      "idProduit": sessionStorage.getItem("id_Produit"),

    };

	$.ajax({    //create an ajax request to load_page.php
        type: "POST",
        url: "view.php",
        dataType: "json",   //expect json to be returned
        data: data,
        success: function(response){

            var t = $('#myTable').DataTable();

            for (var i = 0; i < response.d.length-1; i++) {

                t.row.add( [
                    response.d[i].id_file,
                    response.d[i].file,
                    response.d[i].content_type,
                    response.d[i].size,
                    '<input type="button"  class="btn btn-primary btn-xs" value = "Afficher" onClick="Javascript:doGetPDF(this)" >',
                    '<input type="button" class="btn btn-danger btn-xs" value = "Supprimer" data-title="Delete" data-toggle="modal" onClick="Javascript:doDeletePDF(this)" data-target="#delete" >'

                    // '<input type="button"  class="btn btn-primary btn-xs" value = "Afficher" onClick="Javascript:changeScreanToEdit(this)" >',
                ] ).draw();

            }
        }

    });

 }
}

redpajama_set_name: RedPajamaGithub


text:
package org.renjin.compiler.pipeline.accessor;

import org.objectweb.asm.MethodVisitor;
import org.renjin.compiler.pipeline.ComputeMethod;

import static org.objectweb.asm.Opcodes.*;

public abstract class Accessor {

  public abstract void init(ComputeMethod method);

  /**
   * The index is on the stack, the method should
   * push the corresponding double on to the stack.
   * @param method
   */
  public void pushDouble(ComputeMethod method) {

  }

  public abstract void pushLength(ComputeMethod method);

  protected final void pushOperandIndex(MethodVisitor mv, int operandIndex) {
    if(operandIndex == 0) {
      mv.visitInsn(ICONST_0);
    } else if(operandIndex == 1) {
      mv.visitInsn(ICONST_1);
    } else if(operandIndex == 2) {
      mv.visitInsn(ICONST_2);
    } else if(operandIndex == 3) {
      mv.visitInsn(ICONST_3);
    } else if(operandIndex == 4) {
      mv.visitInsn(ICONST_4);
    } else if(operandIndex == 5) {
      mv.visitInsn(ICONST_5);
    } else if(operandIndex < Byte.MAX_VALUE) {
      mv.visitIntInsn(BIPUSH, operandIndex);
    } else {
      throw new UnsupportedOperationException("operandIndex: " + operandIndex);
    }
  }

  public void pushInt(ComputeMethod method) {
    pushDouble(method);
    method.getVisitor().visitInsn(D2I);
  }

}


text:
package com.vonage.quickstart.account;

import com.vonage.client.VonageClient;
import com.vonage.client.account.AccountClient;
import com.vonage.client.account.SettingsResponse;

import static com.vonage.quickstart.Util.envVar;

public class ConfigureAccount {
    private static final String VONAGE_API_KEY = envVar("VONAGE_API_KEY");
    private static final String VONAGE_API_SECRET = envVar("VONAGE_API_SECRET");
    private static final String SMS_CALLBACK_URL = envVar("SMS_CALLBACK_URL");

    public static void main(String[] args) throws Exception {
        VonageClient client = VonageClient.builder()
                .apiKey(VONAGE_API_KEY)
                .apiSecret(VONAGE_API_SECRET)
                .build();

        AccountClient accountClient = client.getAccountClient();

        SettingsResponse response = accountClient.updateSmsIncomingUrl(SMS_CALLBACK_URL);
        System.out.println("SMS Callback URL is now " + response.getIncomingSmsUrl());
    }
}


text:
package com.facebook.buck.features.apple.projectV2;

import static org.junit.Assert.fail;

import com.facebook.buck.apple.xcode.xcodeproj.PBXFileReference;
import com.facebook.buck.apple.xcode.xcodeproj.PBXGroup;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;

public class PBXTestUtils {
  public static PBXFileReference assertHasFileReferenceWithNameAndReturnIt(
      PBXGroup group, String fileName) {
    ImmutableList<PBXFileReference> candidates =
        FluentIterable.from(group.getChildren())
            .filter(input -> input.getName().equals(fileName))
            .filter(PBXFileReference.class)
            .toList();
    if (candidates.size() != 1) {
      fail("Could not find a unique subgroup by its name");
    }
    return candidates.get(0);
  }

  public static PBXGroup assertHasSubgroupAndReturnIt(PBXGroup group, String subgroupName) {
    ImmutableList<PBXGroup> candidates =
        FluentIterable.from(group.getChildren())
            .filter(input -> input.getName().equals(subgroupName))
            .filter(PBXGroup.class)
            .toList();
    if (candidates.size() != 1) {
      fail("Could not find a unique subgroup by its name");
    }
    return candidates.get(0);
  }

  public static PBXGroup assertHasSubgroupPathAndReturnLast(
      PBXGroup root, ImmutableList<String> components) {
    PBXGroup group = root;
    for (String component : components) {
      group = assertHasSubgroupAndReturnIt(group, component);
    }
    return group;
  }
}


text:
package org.apache.pluto.util.assemble.file;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.pluto.util.UtilityException;
import org.apache.pluto.util.assemble.Assembler;
import org.apache.pluto.util.assemble.AssemblerConfig;
import org.apache.pluto.util.assemble.io.WebXmlStreamingAssembly;

/**
 *
 * @author David H. DeWolf
 * @version 1.0
 * @since Nov 8, 2004
 */
public class FileAssemblerAnt implements Assembler {

    // Constructor -------------------------------------------------------------

    /**
     * Default no-arg constructor.
     */
    public FileAssemblerAnt() {
    	// Do nothing.
    }

    // Assembler Impl ----------------------------------------------------------

    public void assemble(AssemblerConfig config) throws UtilityException {
        try {
            InputStream webXmlIn = new FileInputStream(
            		config.getWebappDescriptor());
            InputStream portletXmlIn = new FileInputStream(
            		config.getPortletDescriptor());
            FileOutputStream webXmlOut = new FileOutputStream(
            		config.getDestination());
            WebXmlStreamingAssembly.assembleStream(webXmlIn, portletXmlIn, webXmlOut, DISPATCH_SERVLET_CLASS);
        } catch (IOException ex) {
            throw new UtilityException(ex.getMessage(), ex, null);
        }
    }
}


text:
package fr.laas.fape.acting.messages

import fr.laas.fape.anml.model.concrete.{ActRef, TPRef}
import fr.laas.fape.planning.core.execution.model.AtomicAction

import scala.collection.JavaConverters._

case class Success(a: AtomicAction)
case class Failed(req: ExecutionRequest)
case class Execute(a: AtomicAction)

object AAction {
  def apply(id: ActRef, name: String, params: Seq[String], start: Int, minDur: Int, maxDur: Int) = new AtomicAction(id, name, params.asJava, start, minDur, maxDur)
  def unapply(a: AtomicAction) : Option[(ActRef, String, Seq[String], Int, Int, Int)] = Some(a.id, a.name, a.params.asScala.toList, a.mStartTime, a.minDuration, a.maxDuration)
}

sealed trait ObserverMessage
object GetProblemFromScene extends ObserverMessage
case class ProblemFromScene(anml: String) extends ObserverMessage
object ErrorOnProblemGeneration extends ObserverMessage

case class TimepointExecuted(tp: TPRef, time: Int)
case class TimepointActive(tp: TPRef)


text:
<?php
/**
 * An example of a local config file
 * Please name your local config as "config-local.php"
 */
return [
    'db.dsn' => 'mysql:dbname=test;charset=utf8',
    'db.user' => 'root',
    'db.password' => '',
];


text:
<?php

class Aitsu_Persistence_ArticleProperty extends Aitsu_Persistence_Abstract {

	protected $_id = null;
	protected $_idartlang = null;
	protected $_data = null;

	protected function __construct($id) {

		$this->_id = $id;
	}

	public static function factory($id = null) {

		static $instance = array ();

		if ($id == null || !isset ($instance[$id])) {
			$instance[$id] = new self($id);
		}

		return $instance[$id];
	}

	public function load($reload = false) {

		if (!$reload && ($this->_id == null || $this->_data !== null)) {
			return $this;
		}

		$properties = Aitsu_Db :: fetchAll('' .
		'select distinct ' .
		'	ptype.identifier, ' .
		'	ptype.type, ' .
		'	prop.textvalue, ' .
		'	prop.floatvalue, ' .
		'	prop.datevalue ' .
		'from _aitsu_article_property as prop ' .
		'left join _aitsu_property as ptype on prop.propertyid = ptype.propertyid ' .
		'left join _art_lang as artlang on prop.idartlang = artlang.idartlang ' .
		'where ' .
		'	artlang.idartlang = :idartlang ' .
		'	and ptype.propertyid is not null ' .
		'order by ' .
		'	ptype.identifier asc ', array (
			':idartlang' => $this->_id
		));

		if (!$properties) {
			return;
		}

		foreach ($properties as $property) {
			$nameSpace = strtok($property['identifier'], ':');
			$name = strtok(':');
			$type = $property['type'] == 'serialized' ? 'text' : $property['type'];
			$value = $property[$type . 'value'];
			$this->_data[$nameSpace][$name] = (object) array (
				'value' => $property['type'] == 'serialized' ? unserialize($value) : $value,
				'type' => $property['type']
			);
		}

		return $this;
	}

	public function __get($key) {

		if ($this->_data === null) {
			$this->load();
		}

		if (!isset ($this->_data[$key])) {
			$this->_data[$key] = array ();
		}

		return $this->_data[$key];
	}

	public function __set($key, $value) {

		if ($this->_data === null) {
			$this->_data = array ();
		}

		$this->_data[$key] = $value;
	}

	public function __isset($key) {

		return isset ($this->_data[$key]);
	}

	public function save() {

		if (empty ($this->_data)) {
			return;
		}

		Aitsu_Db :: startTransaction();

		try {
			$properties = array ();
			$results = Aitsu_Db :: fetchAll('select * from _aitsu_property');
			if ($results) {
				foreach ($results as $result) {
					$properties[$result['identifier']] = array (
						'type' => $result['type'],
						'id' => $result['propertyid']
					);
				}
			}

			Aitsu_Db :: query('delete from _aitsu_article_property where idartlang = :idartlang', array (
				':idartlang' => $this->_id
			));

			foreach ($this->_data as $nameSpace => $tokens) {
				foreach ($tokens as $token => $value) {
					if (!array_key_exists($nameSpace . ':' . $token, $properties)) {
						/*
						 * Add entry in properties table.
						 */
						$insertId = Aitsu_Db :: query('' .
						'insert into _aitsu_property (identifier, type) ' .
						'values (:identifier, :type)', array (
							':identifier' => $nameSpace . ':' . $token,
							':type' => $value->type
						))->getLastInsertId();
						$properties[$nameSpace . ':' . $token] = array (
							'type' => $value->type,
							'id' => $insertId
						);
					}

					if ($properties[$nameSpace . ':' . $token]['type'] != $value->type) {
						/*
						 * Type seems to have changed.
						 */
						Aitsu_Db :: query('' .
						'update _aitsu_property set type = :type ' .
						'where identifier = :identifier', array (
							':type' => $value->type,
							':identifier' => $nameSpace . ':' . $token
						));
						$properties[$nameSpace . ':' . $token]['type'] = $value->type;
					}

					/*
					 * Add value to the properties table.
					 */
					$type = $value->type == 'serialized' ? 'text' : $value->type;
					Aitsu_Db :: query('' .
					'insert into _aitsu_article_property ' .
					'(propertyid, idartlang, ' . $type . 'value) ' .
					'values ' .
					'(:propertyid, :idartlang, :type)', array (
						'propertyid' => $properties[$nameSpace . ':' . $token]['id'],
						':idartlang' => $this->_id,
						':type' => $value->type == 'serialized' ? serialize($value->value) : $value->value
					));
				}
			}

			Aitsu_Persistence_Article :: touch($this->_id);

			Aitsu_Db :: commit();
		} catch (Exception $e) {
			Aitsu_Db :: rollback();
			throw $e;
		}

		return $this;
	}

	public function remove() {

		return $this;
	}

	public function unsetValue($nameSpace, $token) {

		if (isset ($this->data[$nameSpace][$token])) {
			unset ($this->data[$nameSpace][$token]);
		}
	}

	public function setValue($nameSpace, $token, $value, $type = 'text') {

		if ($type == 'float') {
			$value = str_replace(',', '.', $value);
		}

		$this->_data[$nameSpace][$token] = (object) array (
			'value' => $value,
			'type' => $type
		);
	}

}


text:
package org.apache.wicket.markup.html.image;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.core.util.string.UrlUtils;

/**
 * A behavior that converts the provider url fragment to a context-relative url. For example if the
 * current url is http://localhost/context/product/1231 and the specified url is
 * images/border.jpg the generated url will be ../../images/border.jpg
 *
 * @author Igor Vaynberg (ivaynberg)
 */
public class ContextPathGenerator extends Behavior
{
	private static final long serialVersionUID = 1L;

	private final IModel<String> contextRelativePath;

	/**
	 * Constructor
	 *
	 * @param contextRelativePath
	 *            context-relative path, eg images/border.jpg
	 */
	public ContextPathGenerator(IModel<String> contextRelativePath)
	{
		this.contextRelativePath = contextRelativePath;
	}

	/**
	 * Constructor
	 *
	 * @param contextRelativePath
	 *            context-relative path, eg images/border.jpg
	 */
	public ContextPathGenerator(String contextRelativePath)
	{
		this.contextRelativePath = new Model<String>(contextRelativePath);
	}

	/** {@inheritDoc} **/
	@Override
	public void onComponentTag(Component component, ComponentTag tag)
	{
		// get path
		final String path = contextRelativePath.getObject();

		final String rewritten = UrlUtils.rewriteToContextRelative(path, RequestCycle.get());

		tag.put("src", rewritten);
	}

	/** {@inheritDoc} **/
	@Override
	public void detach(Component component)
	{
		contextRelativePath.detach();
		super.detach(component);
	}

}