Go through a Contribution and validate each table
1461
def validate_contribution(the_con):
    
    passing = True
    for dtype in list(the_con.tables.keys()):
        print("validating {}".format(dtype))
        fail = validate_table(the_con, dtype)
        if fail:
            passing = False
        print('--')
1223373
private function checkValidity()
    {

        if (!is_writable($this->rssFile)) {
            $this->valid = false;
            return;
        }

        $stmt = $this->db->prepare('SELECT CREATED FROM ' . $this->table . ' ORDER BY CREATED DESC LIMIT 1');
        $stmt->execute();
        $res = $stmt->fetchAll();

        if (count($res) == 0) {
            $this->valid = false;
            return;
        }

        $latestInput = strtotime($res[0]->CREATED);

        $rssCreated = filemtime($this->rssFile);

        if ($latestInput > $rssCreated) {
            $this->valid = false;
        } else {
            $this->valid = true;
        }
    }
1351986
def validate(self):
        """"""
        required = ['token', 'content']
        valid_data = {
            'exp_record': (['type', 'format'], 'record',
                'Exporting record but content is not record'),
            'imp_record': (['type', 'overwriteBehavior', 'data', 'format'],
                'record', 'Importing record but content is not record'),
            'metadata': (['format'], 'metadata',
                'Requesting metadata but content != metadata'),
            'exp_file': (['action', 'record', 'field'], 'file',
                'Exporting file but content is not file'),
            'imp_file': (['action', 'record', 'field'], 'file',
                'Importing file but content is not file'),
            'del_file': (['action', 'record', 'field'], 'file',
                'Deleteing file but content is not file'),
            'exp_event': (['format'], 'event',
                'Exporting events but content is not event'),
            'exp_arm': (['format'], 'arm',
                'Exporting arms but content is not arm'),
            'exp_fem': (['format'], 'formEventMapping',
                'Exporting form-event mappings but content != formEventMapping'),
            'exp_user': (['format'], 'user',
                'Exporting users but content is not user'),
            'exp_survey_participant_list': (['instrument'], 'participantList',
                'Exporting Survey Participant List but content != participantList'),
            'version': (['format'], 'version',
                'Requesting version but content != version')
        }
        extra, req_content, err_msg = valid_data[self.type]
        required.extend(extra)
        required = set(required)
        pl_keys = set(self.payload.keys())
        # if req is not subset of payload keys, this call is wrong
        if not set(required) <= pl_keys:
            # what is not in pl_keys?
            not_pre = required - pl_keys
            raise RCAPIError("Required keys: %s" % ', '.join(not_pre))
        # Check content, raise with err_msg if not good
        try:
            if self.payload['content'] != req_content:
                raise RCAPIError(err_msg)
        except KeyError:
            raise RCAPIError('content not in payload')
1302363
def run_validators(self, values):
        """"""
        for val in values:
            super(CommaSepFloatField, self).run_validators(val)
117163
function processTablesKeys(){
				var tablesKeys = [];

				module.tables.forEach(function(table){
					tablesKeys.push({
						value: table.get('id'),
						text: table.get('name'),
					});
				});

				module.tablesKeys = tablesKeys;
			}
1322939
def db_check(name,
             table=None,
             **connection_args):
    '''
    
    '''
    ret = []
    if table is None:
        # we need to check all tables
        tables = db_tables(name, **connection_args)
        for table in tables:
            log.info('Checking table \'%s\' in db \'%s\'..', name, table)
            ret.append(__check_table(name, table, **connection_args))
    else:
        log.info('Checking table \'%s\' in db \'%s\'..', name, table)
        ret = __check_table(name, table, **connection_args)
    return ret
335743
def all(*validators):
    """"""
    def validate_all(fields):
        for validator in validators:
            errors = validator(fields)
            if errors:
                return errors

    validate_all.__doc__ = " and ".join(validator.__doc__ for validator in validators)
    return validate_all
22409
def validate(self):
        """"""
        if not self.recipe:
            raise workflows.Error("Invalid recipe: No recipe defined")

        # Without a 'start' node nothing would happen
        if "start" not in self.recipe:
            raise workflows.Error('Invalid recipe: "start" node missing')
        if not self.recipe["start"]:
            raise workflows.Error('Invalid recipe: "start" node empty')
        if not all(
            isinstance(x, (list, tuple)) and len(x) == 2 for x in self.recipe["start"]
        ):
            raise workflows.Error('Invalid recipe: "start" node invalid')
        if any(x[0] == "start" for x in self.recipe["start"]):
            raise workflows.Error('Invalid recipe: "start" node points to itself')

        # Check that 'error' node points to regular nodes only
        if "error" in self.recipe and isinstance(
            self.recipe["error"], (list, tuple, basestring)
        ):
            if "start" in self.recipe["error"]:
                raise workflows.Error(
                    'Invalid recipe: "error" node points to "start" node'
                )
            if "error" in self.recipe["error"]:
                raise workflows.Error('Invalid recipe: "error" node points to itself')

        # All other nodes must be numeric
        nodes = list(
            filter(
                lambda x: not isinstance(x, int) and x not in ("start", "error"),
                self.recipe,
            )
        )
        if nodes:
            raise workflows.Error('Invalid recipe: Node "%s" is not numeric' % nodes[0])

        # Detect cycles
        touched_nodes = set(["start", "error"])

        def flatten_links(struct):
            """Take an output/error link object, list or dictionary and return flat list of linked nodes."""
            if struct is None:
                return []
            if isinstance(struct, int):
                return [struct]
            if isinstance(struct, list):
                if not all(isinstance(x, int) for x in struct):
                    raise workflows.Error(
                        "Invalid recipe: Invalid link in recipe (%s)" % str(struct)
                    )
                return struct
            if isinstance(struct, dict):
                joined_list = []
                for sub_list in struct.values():
                    joined_list += flatten_links(sub_list)
                return joined_list
            raise workflows.Error(
                "Invalid recipe: Invalid link in recipe (%s)" % str(struct)
            )

        def find_cycles(path):
            """Depth-First-Search helper function to identify cycles."""
            if path[-1] not in self.recipe:
                raise workflows.Error(
                    'Invalid recipe: Node "%s" is referenced via "%s" but missing'
                    % (str(path[-1]), str(path[:-1]))
                )
            touched_nodes.add(path[-1])
            node = self.recipe[path[-1]]
            for outgoing in ("output", "error"):
                if outgoing in node:
                    references = flatten_links(node[outgoing])
                    for n in references:
                        if n in path:
                            raise workflows.Error(
                                "Invalid recipe: Recipe contains cycle (%s -> %s)"
                                % (str(path), str(n))
                            )
                        find_cycles(path + [n])

        for link in self.recipe["start"]:
            find_cycles(["start", link[0]])
        if "error" in self.recipe:
            if isinstance(self.recipe["error"], (list, tuple)):
                for link in self.recipe["error"]:
                    find_cycles(["error", link])
            else:
                find_cycles(["error", self.recipe["error"]])

        # Test recipe for unreferenced nodes
        for node in self.recipe:
            if node not in touched_nodes:
                raise workflows.Error(
                    'Invalid recipe: Recipe contains unreferenced node "%s"' % str(node)
                )
740651
@Override
    protected void validate(List<TableInfo> tableInfos)
    {
        List listTables = r.db(databaseName).tableList().run(connection);

        for (TableInfo tableInfo : tableInfos)
        {
            try
            {
                if (!listTables.contains(tableInfo.getTableName()))
                {
                    throw new SchemaGenerationException("Table: " + tableInfo.getTableName() + " does not exist ");
                }
            }
            catch (Exception e)
            {
                logger.error("Error while validating tables, Caused by: " + e.getMessage());
                throw new KunderaException("Error while validating tables, Caused by: " + e.getMessage());
            }
        }
    }
569063
private void validateTable(TableDefinition tableDef) {
        for (String optName : tableDef.getOptionNames()) {
            String optValue = tableDef.getOption(optName);
            switch (optName) {
            case CommonDefs.OPT_AGING_FIELD:
                validateTableOptionAgingField(tableDef, optValue);
                break;
            case CommonDefs.OPT_RETENTION_AGE:
                validateTableOptionRetentionAge(tableDef, optValue);
                break;
            case CommonDefs.OPT_SHARDING_FIELD:
                validateTableOptionShardingField(tableDef, optValue);
                break;
            case CommonDefs.OPT_SHARDING_GRANULARITY:
                validateTableOptionShardingGranularity(tableDef, optValue);
                break;
            case CommonDefs.OPT_SHARDING_START:
                validateTableOptionShardingStart(tableDef, optValue);
                break;
            case CommonDefs.OPT_AGING_CHECK_FREQ:
                validateTableOptionAgingCheckFrequency(tableDef, optValue);
                break;
            default:
                Utils.require(false, "Unknown option for SpiderService table: " + optName);
            }
        }
        
        for (FieldDefinition fieldDef : tableDef.getFieldDefinitions()) {
            validateField(fieldDef);
        }
        
        if (tableDef.getOption(CommonDefs.OPT_AGING_FIELD) != null &&
            tableDef.getOption(CommonDefs.OPT_AGING_CHECK_FREQ) == null) {
            String agingCheckFreq = tableDef.getAppDef().getOption(CommonDefs.OPT_AGING_CHECK_FREQ);
            if (Utils.isEmpty(agingCheckFreq)) {
                agingCheckFreq = "1 DAY";
            }
            tableDef.setOption(CommonDefs.OPT_AGING_CHECK_FREQ, agingCheckFreq);
        }
    }
1323475
def ensure_table(self, cls):
        """"""
        coll_name = cls.get_table_name()
        try:
            db = self.mongo_client.get_default_database()
            db.create_collection(coll_name)
        except CollectionInvalid:
            pass  # Expected if collection already exists

        # Make sure we have indexes
        coll = self.get_collection(coll_name)
        for idx_name in cls.index_names():
            coll.ensure_index(idx_name)
952763
protected function checkColumnsValidity(): void
    {
        $this->getAttribute('columns')->map(function (TableListColumn $column) {
            $this->checkSortableColumnHasAttribute($column);
            $isSearchable = in_array(
                $column->getAttribute('attribute'),
                $this->getAttribute('searchableColumns')->pluck('attribute')->toArray()
            );
            if ($isSearchable) {
                $this->checkSearchableColumnHasAttribute($column);
                $this->checkSearchedAttributeDoesExistInRelatedTable($column);
            }
        });
    }
812437
def validate(self, data, schema):
        '''
        '''
        try:
            return schema(data)
        except MultipleInvalid as ie:
            errors = []
            for error in ie.errors:
                if error.path:
                    field = '.'.join(str(p) for p in error.path)
                    path = error.path
                    value = data
                    while path:
                        attr = path.pop(0)
                        try:
                            if isinstance(value, (list, tuple)):
                                attr = int(attr)
                            value = value[attr]
                        except Exception:
                            value = None

                    txt = safe_unicode(error).replace('for dictionary value', '')
                    txt = txt.strip()
                    if isinstance(error, RequiredFieldInvalid):
                        msg = '[{0}] {1}'
                    else:
                        msg = '[{0}] {1}: {2}'
                    try:
                        msg = msg.format(field, txt, str(value))
                    except Exception:
                        msg = '[{0}] {1}'.format(field, txt)

                else:
                    msg = str(error)
                errors.append(msg)
            msg = '\n- '.join(['Validation error:'] + errors)
            raise HarvestValidationError(msg)
480372
function validateSchema(schema) {
  let errors = [];

  schema.forEach((page, index) => {
    if (!['Page', 'Result'].includes(page.type)) {
      errors = [
        ...errors,
        {
          path: ['schema', index],
          error: 'Top-level element is of invalid type. Must be Page or Result',
        },
      ];
    }

    errors = [
      ...errors,
      ...validatePage(page, ['schema', index]),
    ];
  });

  return errors;
}
117987
public function checkRequiredTables() {
        if ($this->requiredTables) {
            $this->out(sprintf('The following tables are required: <info>%s</info>', implode(', ', $this->requiredTables)));
            $this->out('<success>Checking tables...</success>');

            $tables = $this->db->listSources();
            $missing = array();

            foreach ($this->requiredTables as $table) {
                if (!in_array($this->db->config['prefix'] . $table, $tables)) {
                    $missing[] = $table;
                }
            }

            if ($missing) {
                $this->err(sprintf('<error>Missing tables %s; can not proceed</error>', implode(', ', $missing)));
                return false;
            }
        }

        $this->out('<success>Table status good, proceeding...</success>');
        return true;
    }
811328
def validate(self) :
        """"""
        self._store.validate()
        for pField in self.collection.arangoPrivates :
            self.collection.validatePrivate(pField, getattr(self, pField))
408006
private function check_tables() {
		$tab = new AdminStoreTables();
		$tab::init($this);
		$force = $this->force_create_table;
		if ($tab::exists($force)) {
			if (!$force)
				$tab::upgrade();
			$tab::deinit();
			return;
		}
		$tab::install($this->expiration);
		$tab::deinit();
	}