@function validateArgs

validate args if schema is set

@param {object} args
@param {object} methodMeta

@returns {any}

@throws {Error}
334397
function validateArgs (args, methodMeta) {
    // do not validate if no schema
    if (!defined(methodMeta.schema.args)) {
        return args
    }
    // do not validate if disabled
    if (!methodMeta.validateArgs) {
        return args
    }
    // get validator
    var ajv = methodMeta.ajv
    // throw error if validation fails
    if (!ajv.validate(methodMeta.schema.args.id, args)) {
        // create error
        var error = new Error(`${methodMeta.signature}: invalid args - ${ajv.errorsText()}`)
        // add ajv errors to error data
        error.data = ajv.errors
        // throw error
        throw error
    }
    // return possibly modified args
    return args
}
451192
function checkSchemaErrors(schemaJSON)
    {

      //check against the proper schema definition
      // var vck = self.validator.validateMultiple(schemaJSON, schemaSpec, true);
       var valCheck = self.validateFunction.apply(self.validator, [schemaJSON, schemaSpec, true]);
       
       //grab all possible errors
       var checkErrors = {length: 0};
       var checkWarnings = {length: 0};

       //if we're valid -- which we almost certainly are -- just keep going
       if(!valCheck.valid)
       {
          //let it be known -- this is a weird error
          self.log("Invalid from v4 JSON schema perspective: ", valCheck[errorKey]);

          checkErrors["root"] = valCheck[errorKey];
          checkErrors.length++;

          //not valid, throw it back
          return checkErrors;
       }


       //make sure we have some properties -- otherwise there is literally no validation/
       //during the move process, this is overridden, but it's a good check nonetheless
       if(!schemaJSON.properties && !schemaJSON.items)
       {
          checkErrors["root"] = "No properties/items defined at root. Schema has no validation without properties!";
          checkErrors.length++;
       }

       //going to need to traverse our schema object
       var tJSON = traverse(schemaJSON);

       tJSON.forEach(function(node)
       {
        //skip the root please
        if(this.isRoot || this.path.join(pathDelim).indexOf('required') != -1)
          return;

        //this should be a warning
        if(!self.requireByDefault && !this.isLeaf && !this.node.required)
        {
            //if you don't have a required object, then you're gonna have a bad time
            //this is a warning
            checkWarnings[this.path.join(pathDelim)] = "warning: if you disable requireByDefault and don't put require arrays, validation will ignore those properties.";
            checkWarnings.length++;

        }
        if(this.key == "properties" && this.node.properties)
        {
           checkErrors[this.path.join(pathDelim)] = "Properties inside properties is meaningless.";
           checkErrors.length++;
        }
        if(this.key == "type" && typeof this.node != "string")
        {
            //for whatever reason, there is a type defined, but not a string in it's place? Waa?
            checkErrors[this.path.join(pathDelim)] = "Types must be string";
            checkErrors.length++;
        }
        if(this.key == "type" && !self.typeRegExp.test(this.node.toLowerCase()))
        {
           checkErrors[this.path.join(pathDelim)] = "Types must be one of " + self.validTypes + " not " + this.node;
           checkErrors.length++;
        }
        if(this.isLeaf)
        {
          //if you don't have a type, and there is no ref object
          if(!this.parent.node.properties && (this.key != "type" && this.key != "$ref") && !this.parent.node.type && !this.parent.node["$ref"])
          {
              checkErrors[this.path.join(pathDelim)] = "Object doesn't have any properties, a valid type, or a reference, therefore it is invalid in the WIN spec.";
              checkErrors.length++;
          }
        }
        //not a leaf, you don't have a reference
        if(!self.allowAnyObjects && !this.isLeaf && !this.node["$ref"] )
        {
          //special case for items -- doesn't apply
          if(this.node.type == "object" && this.key != "items")
          {
            //we're going to check if the list of keys to follow have any non keywords
            //for instance if {type: "object", otherThing: "string"} keys = type, otherThing
            //if instead it's just {type : "object", required : []}, keys = type, required 
            //notice that the top has non-keyword keys, and the bottom example does not 
            //we're looking for the bottom example and rejecting it
            var bHasNonKeywords = hasNonKeywords(this.keys);
            
            //if you ONLY have keywords -- you don't have any other object types
            //you are a violation of win spec and you allow any object or array to be passed in
            if(!bHasNonKeywords){
              // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
              checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'object' type with no inner properties";
              checkErrors.length++;
            }
          }
          else if(this.node.type == "array")
          {
            //if you are an array and you have no items -- not allowed!
            if(!this.node.items){
              // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
              checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'array' type with no inner items";
              checkErrors.length++;
            }
            else
            {
              //if you have a ref -- you're okay for us!
              var bIemsHaveNonKey = this.node.items["$ref"] || this.node.items["type"] || hasNonKeywords(this.node.items.properties || {});
               if(!bIemsHaveNonKey){
                // self.log("Current: ".magenta, this.key, " Keys: ".cyan, this.keys || "none, node: " + this.node, " has non? ".red + bHasNonKeywords);
                checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off, therefore you cannot simple have an 'array' type with no non-keyword inner items";
                checkErrors.length++;
              }
            }
          }
        
        }
        //if you're an array
        if(this.node.type == "array")
        {
          //grab your items
          var items = this.node.items;
          if(!items && !self.allowAnyObjects)
          {
             checkErrors[this.path.join(pathDelim)] = "AllowAnyObjects is off for arrays, therefore you cannot simple have an 'array' type with no inner items";
              checkErrors.length++;
          }
          else
          {
            items = items || {};
            //we have items -- we shouldn't have a reference type && other items
            if(items.properties && items["$ref"])
            {
              checkErrors[this.path.join(pathDelim)] = "Array items in WIN cannot have properties AND a reference type. One or the other.";
              checkErrors.length++;
            }
          }
        }


       });

       if(checkErrors.length || checkWarnings.length)
        return {errors: checkErrors, warnings: checkWarnings};
      else
        return null;

    }
1028669
private boolean verifyProvide(Node methodName, Node arg) {
    if (!verifyLastArgumentIsString(methodName, arg)) {
      return false;
    }

    if (!NodeUtil.isValidQualifiedName(
        compiler.getOptions().getLanguageIn().toFeatureSet(), arg.getString())) {
      compiler.report(
          JSError.make(
              arg,
              INVALID_PROVIDE_ERROR,
              arg.getString(),
              compiler.getOptions().getLanguageIn().toString()));
      return false;
    }

    return true;
  }
65106
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);
  var index = parseInt(args[1])
    , value = info.db.getKey(args[0], info);
  if(value === undefined) {
    throw NoSuchKey;
  }else if(isNaN(index) || (index < 0 || index >= value.getLength())) {
    throw IndexRange;
  }
  args[1] = index;
}
727486
function _validateIsModel(model) {
  let parentClass = Object.getPrototypeOf(model);
  while (parentClass.name !== 'Model' && parentClass.name !== '') {
    parentClass = Object.getPrototypeOf(parentClass);
  }
  validationUtils.booleanTrue(
    parentClass.name === 'Model',
    'Parameter is not an Objection.js model'
  );
}
1284561
function schema (args) {
    // get args object
    args = requireValidOptionalObject(args)
    // get colunmn and index information from database
    return Promise.all([
        this.mysql().query(sql.describe(this)),
        this.mysql().query(sql.showCreateTable(this)),
        this.mysql().query(sql.showIndexes(this)),
    ])
    // build schema from database response
    .then(res => {
        // get columns and indexes from describe and show index queries
        var columns = res[0][0]
        var createTable = res[1][0]
        var indexes = res[2][0]
        // schema data
        var schema = {
            columns: {},
            indexes: [],
        }
        // get first and only create table record
        createTable = _.get(createTable, "[0]['Create Table']", '')
        // get engine and charset from create table sql
        var engine = createTable.match(/ENGINE=(\w+)/)
        schema.engine = engine && engine[1] || ''
        var charset = createTable.match(/DEFAULT CHARSET=(\w+)/)
        schema.charset = charset && charset[1] || ''
        // build column data
        _.each(columns, dbColumn => {
            var column = schema.columns[dbColumn.Field] = {}
            // check unsigned
            if (dbColumn.Type.match(/unsigned$/)) {
                column.unsigned = true
                dbColumn.Type = dbColumn.Type.replace(/ unsigned/, '')
            }
            // char id column
            if (dbColumn.Type === 'char(32)') {
                // model must not be set for binary ids
                assert.ok(this.binaryIds === false, 'binaryIds must be disabled for char id columns')
                // set type
                column.type = 'id'
            }
            // binary id column
            else if (dbColumn.Type === 'binary(16)') {
                // model must be set for binary ids
                assert.ok(this.binaryIds === true, 'binaryIds must be enabled for binary id columns')
                // set type
                column.type = 'id'
            }
            // all other column types
            else  {
                // require valid type
                assert.ok(sql.columnTypesInverse[dbColumn.Type], 'unrecognized column type '+dbColumn.Type)
                // map database to internal type
                column.type = sql.columnTypesInverse[dbColumn.Type]
            }
            // is column nullable
            if (dbColumn.Null === 'NO') {
                column.null = false
            }
            // set default if not null
            if (dbColumn.Default) {
                column.default = dbColumn.Default
                // convert boolean
                if (column.type === 'boolean') {
                    column.default = column.default === '1' ? true : false
                }
            }
        })
        // map of indexes by key name since keys may cover multiple columns
        var indexesByKey = {}
        // build map of indexes by key name
        _.each(indexes, dbIndex => {
            // create entry for index if it does not already exist
            if (!indexesByKey[dbIndex.Key_name]) {
                indexesByKey[dbIndex.Key_name] = {
                    columns: {}
                }
            }
            // get entry for index
            var index = indexesByKey[dbIndex.Key_name]
            // add column with sequence in index
            index.columns[dbIndex.Column_name] = parseInt(dbIndex.Seq_in_index)
            // add unique flag if true
            if (dbIndex.Non_unique === '0') {
                index.unique = true
            }
        })
        // add indexes to schema
        _.each(indexesByKey, (index, name) => {
            var indexColumns = _.keys(index.columns)
            // multi-column index
            if (indexColumns.length > 1) {
                // sort index columns by the Seq_in_index value - these may
                // always be in order so this may not be needed
                indexColumns = _.sortBy(indexColumns, indexColumn => index.columns[indexColumn])
                // create schema index entry
                var schemaIndex = {
                    columns: indexColumns,
                }
                // set unique flag
                if (index.unique) {
                    schemaIndex.unique = true
                }
                // add index to schema
                schema.indexes.push(schemaIndex)
            }
            // single column index
            else {
                // get first and only column
                var indexColumn = indexColumns[0]
                // PRIMARY KEY
                if (name === 'PRIMARY') {
                    schema.columns[indexColumn].primary = true
                }
                // unique index
                else if (index.unique) {
                    schema.columns[indexColumn].unique = true
                }
                // non-unique index
                else {
                    schema.columns[indexColumn].index = true
                }
            }
        })
        // resolve with schema
        return schema
    })
    .catch(err => {
        // reject on anything besides a table does not exist error
        // if table does not exist resolve with undefined
        if (err.errno !== 1146) {
            throw err
        }
    })
}
298585
function (methodName, argName) {
            var required = this.findParameter(methodName, argName).required;
            //default is false, so if "required" is undefined, return false anyway
            if (required) {
                return true;
            }
            return false;
        }
1106631
function(method) {
		return function(object, options) {
			//console.log("client-store schema validation", this.schema);
			var schema = this.schema;
			if (!schema)
				return deep.Arguments([object, options]);
			options = options || {};
			var id = options.id || object.id,
				query = null;
			if (id) {
				query = id.split("/");
				if (query.length > 1) {
					id = query.shift();
					query = "/" + query.join("/");
				} else
					query = null;
			}
			var finalise = function(schema) {
				if (!query) { // validate whole object
					var report = deep.validate(object, schema);
					if (!report.valid)
						return deep.errors.PreconditionFail(method + " failed", report);
				} else { // partial validation : could be unrelevant as it could depend of whole item structure
					// what TODO here...? : if nothing : it should be validated remotely
				}
				return deep.Arguments([object, options]);
			};
			if (typeof schema === 'string')
				return deep.get(schema)
					.done(finalise);
			return finalise(schema);
		};
	}
1254281
function Validation(schema, custom) {
		Inspection.prototype.constructor.call(this, schema, _merge(Validation.custom, custom));
		var _error = [];

		this._basicFields = Object.keys(_validationAttribut);
		this._customFields = Object.keys(this._custom);
		this.origin = null;

		this.report = function (message, code, reason) {
			var newErr = {
				code: code || this.userCode || null,
				reason: reason || 'unknown',
				message: this.userError || message || 'is invalid',
				property: this.userAlias ? (this.userAlias + ' (' + this._dumpStack() + ')') : this._dumpStack()
			};
			_error.push(newErr);
			return this;
		};

		this.result = function () {
			return {
				error: _error,
				valid: _error.length === 0,
				format: function () {
					if (this.valid === true) {
						return 'Candidate is valid';
					}
					return this.error.map(function (i) {
						return 'Property ' + i.property + ': ' + i.message;
					}).join('\n');
				}
			};
		};
	}
1054534
function initModelValidate (args) {
    var controller = this
    var model = this.model
    // if model does not have schema do not add validate controller
    if (!model.schemaData) {
        return
    }
    // get accountId column
    var accountIdColumn = model.columnName('accountId') 
    // set role to authenticated if model requires account id
    var role = args.defaultRole || (accountIdColumn && model.columns[accountIdColumn].null === false ? 'authenticated' : 'all')
    // index inputs
    var input = {
        // validate schema data
        meta: 'query.meta',
    }
    // instance data is in body under model name
    input[model.name] = 'body.'+model.name
    // create path if it does not exist
    if (!this.paths['/validate']) {
        this.paths['/validate'] = {}
    }
    // add POST /validate handler
    this.paths['/validate'].post = [
        {
            before: function (args) {
                // do validation
                return beforeValidate(controller, args)
            },
            input: input,
            method: function (args) {
                // if before didnt have errors data is valid
                return {valid: true}
            },
            role: role,
            methodName: 'validate',
        },
    ]
}
34202
protected function _validateArguments($methodName, $args) {
        if (!array_key_exists($methodName, $this->_allowedArguments)
            || $this->_allowedArguments[$methodName] === '*'
        ) {
            return true;
        }

        $unknownArgs = array_diff(array_keys($args), $this->_allowedArguments[$methodName]);
        if (!count($unknownArgs)) {
            return true;
        }
        // Report the first erroneous argument
        $errorStr = current($unknownArgs);
        // Show the value of the argument if the index is numeric
        if (is_numeric($errorStr)) {
            $errorStr = $args[$unknownArgs[0]];
        }
        Garp_Cli::errorOut('Unexpected argument ' . $errorStr);
        return false;
    }
585056
def validate_arguments(self, locals_dict):
        '''
        
        '''

        for key, value, validator in self.__map_arguments(locals_dict):
            if not self.__is_valid(value, validator):
                key_name = repr(key)
                func_name = self.__function.__name__
                annotation = self.__argument_annotation.get(key)
                message = self.ARG_TYPE_ERROR_MESSAGE.format(
                    key_name,
                    func_name,
                    self.__format_expectation(annotation),
                    value.__class__.__name__)
                raise TypesafetyError(message)
670042
function checkArgs(args) {
  if (args.length !== 2) {
    console.warn(`WWWW Checking claudia args: args.length !== 2, is: ${args.length}`, inspect({args}));
  }
}
27936
async function validateArguments(args, operation) {
    let error = new Error();
    let body = undefined;

    error.name = 'ArgumentError';
    if (!operation) {
        let verbs = ["add", "clone", "delete", "export", "package", "get", "import", "list", "publish", "query", "set", "suggest", "train", "update"];
        if (verbs.indexOf(args._[0]) < 0)
            error.message = `'${args._[0]}' is not a valid action`;
        else if (args._.length >= 2)
            error.message = `'${args._[1]}' is not a valid resource`;
        else
            error.message = `missing resource\n`;
        throw error;
    }

    switch (operation.target[0]){
        case "userazureaccounts":
        case "appazureaccounts":
            switch (operation.methodAlias) {
                case "list":
                    if (args.hasOwnProperty("armToken")) {
                        args.customHeaders["Authorization"] = `Bearer ${args.armToken}`;
                    }
                    break;
                }
                break;
                case "appazureaccount":
                    switch (operation.methodAlias) {
                        case "add":
                        case "delete":
                            if (args.hasOwnProperty("armToken")) {
                                args.customHeaders["Authorization"] = `Bearer ${args.armToken}`;
                            }
                            break;
                        }
                        break;
    }

    const entitySpecified = typeof args.in === 'string';
    const entityRequired = !!operation.entityName;

    if (entityRequired) {
        if (entitySpecified) {
            body = await getFileInput(args);
        }
        else {
            // make up a request body from command line args
            switch (operation.target[0]) {
                case "version":
                    switch (operation.methodAlias) {
                        case "publish":
                            if (args.versionId) {
                                body = {
                                    versionId: `${args.versionId}`,
                                    isStaging: args.staging === 'true'
                                };
                            }
                            break;
                        case "rename":
                        case "update":
                        case "clone":
                            if (args.newVersionId) {
                                body = {
                                    version: `${args.newVersionId}`
                                };
                            }
                            break;
                    }
                    break;

                case "settings":
                    switch (operation.methodAlias) {
                        case "update":
                            if (args.hasOwnProperty("public")) {
                                body = {
                                    isPublic: args.public === 'true'
                                };
                            }
                            break;
                    }
                    break;
                case "versionsettings":
                    switch (operation.methodAlias) {
                        case "update":
                            if (args.hasOwnProperty("useAllTrainingData")) {
                                body = [{
                                    name: "UseAllTrainingData",
                                    value: args.useAllTrainingData === 'true' ? 'true' : 'false'
                                }];
                            }
                            break;
                    }
                    break;
                case "appazureaccount":
                    if (args.azureSubscriptionId && args.resourceGroup && args.accountName) {
                        body = {
                            azureSubscriptionId: `${args.azureSubscriptionId}`,
                            resourceGroup: `${args.resourceGroup}`,
                            accountName: `${args.accountName}`
                        };
                    }
                    break;

                default:
                    error.message = `The --in requires an input of type: ${operation.entityType}`;
                    throw error;
            }
        }
    }
    return body;
    // Note that the ServiceBase will validate params that may be required.
}
386796
public static void assertTrueOrInvalidMethodSignException(boolean expression, SQLiteModelMethod method,
			String messageFormat, Object... args) {
		if (!expression)
			throw (new InvalidMethodSignException(method, String.format(messageFormat, args)));
	}
1325035
function beforeValidate (controller, args) {
    // get model from controller
    var model = controller.model
    // get model data from input
    var data = args[model.name]
    // get schema id
    var schemaId = args.meta || !model.schemaDataId
        ? model.schemaId
        : model.schemaDataId
    // if validating meta data convert property names to columns names
    if (args.meta) {
        // clone data before modifying - shallow since only property names are
        // being modified
        data = _.clone(data)
        // iterate over all data properties
        _.each(data, (val, key) => {
            // get column name for key
            var columnName = model.columnName(key)
            // if property does not map to column then skip
            if (!columnName) {
                return
            }
            // use column name for validation
            if (columnName !== key) {
                // copy value to column name
                data[columnName] = val
                // delete entry for original property
                delete data[key]
            }
        })
    }
    // get global validator
    var validator = model.global().validator
    // throw error if validation failed
    if (!validator.validate(schemaId, data)) {
        // throw error
        httpError(400, 'Validation Error', validator.errors)
    }
}
1228469
function checkArgs() {
  if (arguments.length === 0) {
    throw new Error('no argument for executing resource service');
  }

  var args = arguments[0];
  if (args.name === void 0) {
    throw new Error('no name for executing resource service');
  }

  return args;
}