This validation function for Apache CouchDB was generated by couchster: https://github.com/OldSneerJaw/couchster
426117
function(newDoc, oldDoc, userContext, securityInfo) {
  // Whether the given value is either null or undefined
  function isValueNullOrUndefined(value) {
    return value === void 0 || value === null;
  }

  // Whether the given document is missing/nonexistant (i.e. null or undefined) or deleted (its "_deleted" property is true)
  function isDocumentMissingOrDeleted(candidate) {
    return isValueNullOrUndefined(candidate) || candidate._deleted;
  }

  // A property validator that is suitable for use on type identifier properties. Ensures the value is a string, is neither null nor
  // undefined, is not an empty string and cannot be modified.
  var typeIdValidator = {
    type: 'string',
    required: true,
    mustNotBeEmpty: true,
    immutable: true
  };

  // A type filter that matches on the document's type property
  function simpleTypeFilter(newDoc, oldDoc, candidateDocType) {
    if (oldDoc) {
      if (newDoc._deleted) {
        return oldDoc.type === candidateDocType;
      } else {
        return newDoc.type === oldDoc.type && oldDoc.type === candidateDocType;
      }
    } else {
      return newDoc.type === candidateDocType;
    }
  }

  // Add the specified padding to the right of the given string value until its length matches the desired length
  function padRight(value, desiredLength, padding) {
    while (value.length < desiredLength) {
      value += padding;
    }

    return value;
  }

  // Determine if a given value is an integer. Exists because Number.isInteger is not supported by CouchDB's JavaScript engine.
  function isValueAnInteger(value) {
    return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  }

  // Retrieves the effective value of a top-level document constraint (e.g. "channels", "documentIdRegexPattern", "accessAssignments")
  function resolveDocumentConstraint(constraintDefinition) {
    if (typeof constraintDefinition === 'function') {
      var dbName = userContext ? userContext.db : null;

      return constraintDefinition(newDoc, oldDoc, dbName);
    } else {
      return constraintDefinition;
    }
  }

  var utils = {
    isDocumentMissingOrDeleted: isDocumentMissingOrDeleted,
    isValueAnInteger: isValueAnInteger,
    isValueNullOrUndefined: isValueNullOrUndefined,
    padRight: padRight,
    resolveDocumentConstraint: resolveDocumentConstraint
  };

  // The document authorization module is responsible for verifying the user's permissions (e.g. roles, usernames)
  var authorizationModule = importValidationFunctionFragment('./authorization-module.js')(utils);

  // The document validation module is responsible for verifying the document's contents
  var validationModule = importValidationFunctionFragment('./validation-module.js')(utils, simpleTypeFilter, typeIdValidator);

  var rawDocDefinitions = $DOCUMENT_DEFINITIONS_PLACEHOLDER$;

  var docDefinitions;
  if (typeof rawDocDefinitions === 'function') {
    docDefinitions = rawDocDefinitions();
  } else {
    docDefinitions = rawDocDefinitions;
  }

  function getDocumentType() {
    for (var docType in docDefinitions) {
      var docDefn = docDefinitions[docType];
      if (docDefn.typeFilter(newDoc, oldDoc, docType)) {
        return docType;
      }
    }

    // The document type does not exist
    return null;
  }

  // Now put the pieces together
  var theDocType = getDocumentType();

  if (isValueNullOrUndefined(theDocType)) {
    if (newDoc._deleted && authorizationModule.isAdminUser(userContext, securityInfo)) {
      // Attempting to delete a document whose type is unknown. This may occur if the document belongs to a type that existed
      // in a previous version of the document definitions but has since been removed. Only an admin may proceed.
      return;
    } else {
      throw { forbidden: 'Unknown document type' };
    }
  }

  var theDocDefinition = docDefinitions[theDocType];

  var customActionMetadata = {
    documentTypeId: theDocType,
    documentDefinition: theDocDefinition
  };

  if (theDocDefinition.customActions && typeof theDocDefinition.customActions.onTypeIdentificationSucceeded === 'function') {
    theDocDefinition.customActions.onTypeIdentificationSucceeded(newDoc, oldDoc, customActionMetadata, userContext, securityInfo);
  }

  customActionMetadata.authorization = authorizationModule.authorize(newDoc, oldDoc, userContext, securityInfo, theDocDefinition);

  if (theDocDefinition.customActions && typeof theDocDefinition.customActions.onAuthorizationSucceeded === 'function') {
    theDocDefinition.customActions.onAuthorizationSucceeded(newDoc, oldDoc, customActionMetadata, userContext, securityInfo);
  }

  validationModule.validateDoc(newDoc, oldDoc, userContext, securityInfo, theDocDefinition, theDocType);

  if (theDocDefinition.customActions && typeof theDocDefinition.customActions.onValidationSucceeded === 'function') {
    theDocDefinition.customActions.onValidationSucceeded(newDoc, oldDoc, customActionMetadata, userContext, securityInfo);
  }
}
500477
function(db, couchdb, concurrentDocLimit, docsToDownload) {
  if (docsToDownload.length) {
    var changeSet = docsToDownload.splice(0, concurrentDocLimit);

    return couchdb.allDocs({
      include_docs: true,
      keys: _.pluck(changeSet, 'id')
    }).then(function(couchDbResult) {
      log.debug('Pulled ' + couchDbResult.rows.length + ' results from couchdb');

      log.debug('Clearing any existing documents from postgresql');

      return deleteDocuments(db, _.pluck(couchDbResult.rows, 'id'))
        .then(function() {
          return couchDbResult;
        });
    }).then(function(couchDbResult) {
      log.debug('Inserting ' + couchDbResult.rows.length + ' results into postgresql');

      var insertSql = format(INSERT_DOC_STMT,
        couchDbResult.rows.map(function(row) {
          return [row.doc];
        }));

      insertSql = sanitise(insertSql);

      return db.query(insertSql);
    }).then(function() {
      return loadAndStoreDocs(db, couchdb, concurrentDocLimit, docsToDownload);
    });
  }
}
1346384
function validate () {
  var env = state.env('NODE_ENV');
  var uri = state.env('MONGO_URI');
  var notTestEnv = env !== 'test';
  if (notTestEnv) {
    throw new Error('NODE_ENV must be set to "test".');
  }
  var notTestDb = word.test(uri) === false;
  if (notTestDb) {
    throw new Error('MONGO_URI must contain "test" word.');
  }
}
155169
def validate(self, obj, pointer=None):
        

        pointer = pointer or '#'

        validator = deepcopy(self)
        validator.errors = []
        validator.fail_fast = False

        obj = deepcopy(obj)
        obj = validator.validate_enum(obj, pointer)
        obj = validator.validate_type(obj, pointer)
        obj = validator.validate_disallow(obj, pointer)
        obj = validator.validate_extends(obj, pointer)

        if validator.is_array(obj):
            obj = validator.validate_max_items(obj, pointer)
            obj = validator.validate_min_items(obj, pointer)
            obj = validator.validate_items(obj, pointer)
            obj = validator.validate_unique_items(obj, pointer)

        if validator.is_number(obj):
            obj = validator.validate_maximum(obj, pointer)
            obj = validator.validate_minimum(obj, pointer)
            obj = validator.validate_divisible_by(obj, pointer)

        if validator.is_object(obj):
            obj = validator.validate_dependencies(obj, pointer)
            obj = validator.validate_properties(obj, pointer)

        if validator.is_string(obj):
            obj = validator.validate_max_length(obj, pointer)
            obj = validator.validate_min_length(obj, pointer)
            obj = validator.validate_pattern(obj, pointer)
            obj = validator.validate_format(obj, pointer)

        if validator.errors:
            raise ValidationError('multiple errors',
                                  obj,
                                  errors=validator.errors)

        return obj
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;
}
625460
function validate(extension, name) {
  'use strict';

  var errMsg = (name) ? 'Error in ' + name + ' extension->' : 'Error in unnamed extension',
    ret = {
      valid: true,
      error: ''
    };

  if (!showdown.helper.isArray(extension)) {
    extension = [extension];
  }

  for (var i = 0; i < extension.length; ++i) {
    var baseMsg = errMsg + ' sub-extension ' + i + ': ',
        ext = extension[i];
    if (typeof ext !== 'object') {
      ret.valid = false;
      ret.error = baseMsg + 'must be an object, but ' + typeof ext + ' given';
      return ret;
    }

    if (!showdown.helper.isString(ext.type)) {
      ret.valid = false;
      ret.error = baseMsg + 'property "type" must be a string, but ' + typeof ext.type + ' given';
      return ret;
    }

    var type = ext.type = ext.type.toLowerCase();

    // normalize extension type
    if (type === 'language') {
      type = ext.type = 'lang';
    }

    if (type === 'html') {
      type = ext.type = 'output';
    }

    if (type !== 'lang' && type !== 'output' && type !== 'listener') {
      ret.valid = false;
      ret.error = baseMsg + 'type ' + type + ' is not recognized. Valid values: "lang/language", "output/html" or "listener"';
      return ret;
    }

    if (type === 'listener') {
      if (showdown.helper.isUndefined(ext.listeners)) {
        ret.valid = false;
        ret.error = baseMsg + '. Extensions of type "listener" must have a property called "listeners"';
        return ret;
      }
    } else {
      if (showdown.helper.isUndefined(ext.filter) && showdown.helper.isUndefined(ext.regex)) {
        ret.valid = false;
        ret.error = baseMsg + type + ' extensions must define either a "regex" property or a "filter" method';
        return ret;
      }
    }

    if (ext.listeners) {
      if (typeof ext.listeners !== 'object') {
        ret.valid = false;
        ret.error = baseMsg + '"listeners" property must be an object but ' + typeof ext.listeners + ' given';
        return ret;
      }
      for (var ln in ext.listeners) {
        if (ext.listeners.hasOwnProperty(ln)) {
          if (typeof ext.listeners[ln] !== 'function') {
            ret.valid = false;
            ret.error = baseMsg + '"listeners" property must be an hash of [event name]: [callback]. listeners.' + ln +
              ' must be a function but ' + typeof ext.listeners[ln] + ' given';
            return ret;
          }
        }
      }
    }

    if (ext.filter) {
      if (typeof ext.filter !== 'function') {
        ret.valid = false;
        ret.error = baseMsg + '"filter" must be a function, but ' + typeof ext.filter + ' given';
        return ret;
      }
    } else if (ext.regex) {
      if (showdown.helper.isString(ext.regex)) {
        ext.regex = new RegExp(ext.regex, 'g');
      }
      if (!ext.regex instanceof RegExp) {
        ret.valid = false;
        ret.error = baseMsg + '"regex" property must either be a string or a RegExp object, but ' + typeof ext.regex + ' given';
        return ret;
      }
      if (showdown.helper.isUndefined(ext.replace)) {
        ret.valid = false;
        ret.error = baseMsg + '"regex" extensions must implement a replace string or function';
        return ret;
      }
    }
  }
  return ret;
}
751078
function validate(cmd, args, info) {
  AbstractCommand.prototype.validate.apply(this, arguments);

  var source = '' + args[0]
    , destination = '' + args[1];

  if(!info.db.getKey(args[0], info)) {
    throw NoSuchKey;
  }else if(source === destination) {
    throw SourceDestination;
  }
  args[0] = source;
  args[1] = destination;
}
690080
function getValidator (options, schema) {
  options = options || {};
  options.schemas = options.schemas || {};
  options.formats = options.formats || {};

  if (!schema || !_.isObject(schema)) {
    var err = new Error('Please pass a valid schema!');
    debug(err);
    throw err;
  }

  var tv4 = tv4Module.freshApi();

  _.each(options.schemas, function (v, k) {
    tv4.addSchema(k, v);
  });

  tv4.addFormat(options.formats);

  return function (data) {
    var validation = tv4.validateMultiple(data, schema);

    if (validation.missing.length > 0) {
      var missingString = validation.missing[0];

      for (var m = 1, lenM = validation.missing.length; m < lenM; m++) {
        missingString += ', ' + validation.missing[m];
      }

      var err = new Error('Validation schema(s) "' + missingString + '" missing!');
      debug(err);
      return err;
    }

    if (!validation.valid) {
      var errors = validation.errors;
      var firstError = validation.errors[0];
      if (firstError.message.indexOf('not match any schemas') >= 0 && firstError.subErrors && firstError.subErrors.length > 0) {
        firstError = firstError.subErrors[0];
        errors = firstError.subErrors;
      }
      return new ValidationError(firstError.dataPath + ' => ' + firstError.message, errors);
    }

    return null;
  };
}
71694
function validateContentType(cb) {
        if (!_.isUndefined(kontx.args.meta) && !_.isUndefined(kontx.args.meta.type)) {
            db.contentTypes.getById(kontx.args.meta.type.toString()).then(
                function(contentType) {
                    cb(null, contentType);
                },
                function() {
                    cb(createError(400, messages.invalid_content_type));
                });
        } else {
            cb(createError(400, messages.invalid_content_type));
        }

    }
1369929
function validateVuln (doc) {
	log(`validateVuln: doc ${JSON.stringify(doc)}`);
	const validateVulnQuery = { pattern: doc.pattern, language: doc.language, evilInput: doc.evilInput, nPumps: 250000, timeLimit: 1 };

	const tmpFile = `/tmp/validate-uploads-${process.pid}.json`;
	fs.writeFileSync(tmpFile, JSON.stringify(validateVulnQuery));

	try {
		const cmd = `${process.env.VULN_REGEX_DETECTOR_ROOT}/src/validate/validate-vuln.pl ${tmpFile} 2>/dev/null`;
		const stdout = childProcess.execSync(cmd, {encoding: 'utf8'});
		const result = JSON.parse(stdout);
		log(JSON.stringify(result));
		return result.timedOut === 1;
	} catch (e) {
		log(`Error: ${JSON.stringify(e)}`);
		return false;
	} finally {
		fs.unlinkSync(tmpFile);
	}
}
225528
function validateChecksum(requester, params) {
        params = params || {
            filePath: installerPath,
            expectedChecksum: _updateParams.checksum
        };

        var hash = crypto.createHash('sha256'),
            currentRequester = requester || "";

        if (fs.existsSync(params.filePath)) {
            var stream = fs.createReadStream(params.filePath);

            stream.on('data', function (data) {
                hash.update(data);
            });

            stream.on('end', function () {
                var calculatedChecksum = hash.digest('hex'),
                    isValidChecksum = (params.expectedChecksum === calculatedChecksum),
                    status;

                if (isValidChecksum) {
                    if (process.platform === "darwin") {
                        status = {
                            valid: true,
                            installerPath: installerPath,
                            logFilePath: logFilePath,
                            installStatusFilePath: installStatusFilePath
                        };
                    } else if (process.platform === "win32") {
                        status = {
                            valid: true,
                            installerPath: quoteAndConvert(installerPath, true),
                            logFilePath: quoteAndConvert(logFilePath, true),
                            installStatusFilePath: installStatusFilePath
                        };
                    }
                } else {
                    status = {
                        valid: false,
                        err: nodeErrorMessages.CHECKSUM_DID_NOT_MATCH
                    };
                }
                postMessageToBrackets(MessageIds.NOTIFY_VALIDATION_STATUS, currentRequester, status);
            });
        } else {
            var status = {
                valid: false,
                err: nodeErrorMessages.INSTALLER_NOT_FOUND
            };
            postMessageToBrackets(MessageIds.NOTIFY_VALIDATION_STATUS, currentRequester, status);
        }
    }
1046226
def curl_couchdb(url, method='GET', base_url=BASE_URL, data=None):
    '''
        
    '''
    (username, password) = get_admin()
    if username is None:
        auth = None
    else:
        auth = (username, password)

    if method == 'PUT':
        req = requests.put('{}{}'.format(base_url, url), auth=auth, data=data)
    elif method == 'DELETE':
        req = requests.delete('{}{}'.format(base_url, url), auth=auth)
    else:
        req = requests.get('{}{}'.format(base_url, url), auth=auth)

    if req.status_code not in [200, 201]:
        raise HTTPError('{}: {}'.format(req.status_code, req.text))
    return req
426898
function validateDoc (doc) {
  let issues = []

  function ignore (field) {
    return IGNORE_WARNINGS[field].indexOf(doc.name) !== -1
  }

  if (!doc.name) {
    issues.push('name missing in document')
  }

  if (!doc.description) {
    issues.push('function "' + doc.name + '": description missing')
  }

  if (!doc.syntax || doc.syntax.length === 0) {
    issues.push('function "' + doc.name + '": syntax missing')
  }

  if (!doc.examples || doc.examples.length === 0) {
    issues.push('function "' + doc.name + '": examples missing')
  }

  if (doc.parameters && doc.parameters.length) {
    doc.parameters.forEach(function (param, index) {
      if (!param.name || !param.name.trim()) {
        issues.push('function "' + doc.name + '": name missing of parameter ' + index + '')
      }
      if (!param.description || !param.description.trim()) {
        issues.push('function "' + doc.name + '": description missing for parameter ' + (param.name || index))
      }
      if (!param.types || !param.types.length) {
        issues.push('function "' + doc.name + '": types missing for parameter ' + (param.name || index))
      }
    })
  } else {
    if (!ignore('parameters')) {
      issues.push('function "' + doc.name + '": parameters missing')
    }
  }

  if (doc.returns) {
    if (!doc.returns.description || !doc.returns.description.trim()) {
      issues.push('function "' + doc.name + '": description missing of returns')
    }
    if (!doc.returns.types || !doc.returns.types.length) {
      issues.push('function "' + doc.name + '": types missing of returns')
    }
  } else {
    if (!ignore('returns')) {
      issues.push('function "' + doc.name + '": returns missing')
    }
  }

  if (!doc.seeAlso || doc.seeAlso.length === 0) {
    if (!ignore('seeAlso')) {
      issues.push('function "' + doc.name + '": seeAlso missing')
    }
  }

  return issues
}
1181610
def _validate_keyschema(self, schema, field, value):
        
        if isinstance(value, Mapping):
            validator = self._get_child_validator(
                document_crumb=field,
                schema_crumb=(field, 'keyschema'),
                schema=dict(((k, schema) for k in value.keys())))
            if not validator(dict(((k, k) for k in value.keys())),
                             normalize=False):
                self._drop_nodes_from_errorpaths(validator._errors,
                                                 [], [2, 4])
                self._error(field, errors.KEYSCHEMA, validator._errors)
1047788
function(db) {
		function tv4_validateResult(data, schema) {
			var tv4 = require('tv4');
			return tv4.validateResult(data, schema);
		}
		return db.query('CREATE SCHEMA IF NOT EXISTS tv4')
			.query('CREATE OR REPLACE FUNCTION tv4.validateResult(data json, schema json) RETURNS json LANGUAGE plv8 VOLATILE AS ' + NoPg._escapeFunction(tv4_validateResult, ["data", "schema"]) );
	}
596823
function validateConfigSchema(config, source = null) {
    validateSchema = validateSchema || ajv.compile(configSchema);

    if (!validateSchema(config)) {
        throw new Error(`ESLint configuration in ${source} is invalid:\n${formatErrors(validateSchema.errors)}`);
    }

    if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
        emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
    }
}
973522
def _validate_data(data, schema, validator_cls):
    
    validator = validator_cls(schema)
    _errors = defaultdict(list)
    for err in validator.iter_errors(data):
        path = err.schema_path

        # Code courtesy: Ruslan Karalkin
        # Looking in error schema path for
        # property that failed validation
        # Schema example:
        # {
        #    "type": "object",
        #    "properties": {
        #        "foo": {"type": "number"},
        #        "bar": {"type": "string"}
        #     }
        #    "required": ["foo", "bar"]
        # }
        #
        # Related err.schema_path examples:
        # ['required'],
        # ['properties', 'foo', 'type']

        if "properties" in path:
            path.remove("properties")
        key = path.popleft()

        # If validation failed by missing property,
        # then parse err.message to find property name
        # as it always first word enclosed in quotes
        if key == "required":
            key = err.message.split("'")[1]

        _errors[key].append(str(err))

    if _errors:
        _raise_exception(
            web.HTTPBadRequest,
            "Request is invalid; There are validation errors.",
            _errors)