问:
Extending Calcite parser to Adding Custom relational operators
I want to support FOO_GREATER_THAN clause instead of > in my sql parser.
For ex:
select * from people where age FOO_GREATER_THAN 10

I followed https://calcite.apache.org/docs/adapter.html#extending-the-parser and I have added custom fmpp and ftl file, but I am not able to add it.

parserImpls.ftl

```<code>SqlKind regRealtionalOperator() :
SqlKind regRealtionalOperator() :
{
}
{
    <FOO_EQUAL> { return SqlKind.EQUALS; }
|
    <FOO_GREATER_THAN> { return SqlKind.NOT_EQUALS; }
}
</code>```

config.fmpp

```<code># Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to you under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This file is an FMPP (http://fmpp.sourceforge.net/) configuration file to
# allow clients to extend Calcite's SQL parser to support application specific
# SQL statements, literals or data types.
#
# Calcite's parser grammar file (Parser.jj) is written in javacc
# (http://javacc.java.net/) with Freemarker (http://freemarker.org/) variables
# to allow clients to:
#   1. have custom parser implementation class and package name.
#   2. insert new parser method implementations written in javacc to parse
#      custom:
#      a) SQL statements.
#      b) literals.
#      c) data types.
#   3. add new keywords to support custom SQL constructs added as part of (2).
#   4. add import statements needed by inserted custom parser implementations.
#
# Parser template file (Parser.jj) along with this file are packaged as
# part of the calcite-core-<version>.jar under "codegen" directory.

data: {
  parser: {
    # Generated parser implementation package and class name.
    package: "org.apache.calcite.sql.parser.impl",
    class: "SqlParserImpl",

    # List of additional classes and packages to import.
    # Example. "org.apache.calcite.sql.*", "java.util.List".
    imports: [
    ]

    # List of new keywords. Example: "DATABASES", "TABLES". If the keyword is not a reserved
    # keyword add it to 'nonReservedKeywords' section.
    keywords: [
    "FOO_EQUAL"
    "FOO_GREATER_THAN"
    ]

    # List of keywords from "keywords" section that are not reserved.
    nonReservedKeywords: [
        "A"
        "ABSENT"
        "ABSOLUTE"
        "ACTION"
        "ADA"
        "ADD"
        "ADMIN"
        "AFTER"
        "ALWAYS"
        "APPLY"
        "ASC"
        "ASSERTION"
        "ASSIGNMENT"
        "ATTRIBUTE"
        "ATTRIBUTES"
        "BEFORE"
        "BERNOULLI"
        "BREADTH"
        "C"
        "CASCADE"
        "CATALOG"
        "CATALOG_NAME"
        "CENTURY"
        "CHAIN"
        "CHARACTER_SET_CATALOG"
        "CHARACTER_SET_NAME"
        "CHARACTER_SET_SCHEMA"
        "CHARACTERISTICS"
        "CHARACTERS"
        "CLASS_ORIGIN"
        "COBOL"
        "COLLATION"
        "COLLATION_CATALOG"
        "COLLATION_NAME"
        "COLLATION_SCHEMA"
        "COLUMN_NAME"
        "COMMAND_FUNCTION"
        "COMMAND_FUNCTION_CODE"
        "COMMITTED"
        "CONDITION_NUMBER"
        "CONDITIONAL"
        "CONNECTION"
        "CONNECTION_NAME"
        "CONSTRAINT_CATALOG"
        "CONSTRAINT_NAME"
        "CONSTRAINT_SCHEMA"
        "CONSTRAINTS"
        "CONSTRUCTOR"
        "CONTINUE"
        "CURSOR_NAME"
        "DATA"
        "DATABASE"
        "DATETIME_INTERVAL_CODE"
        "DATETIME_INTERVAL_PRECISION"
        "DECADE"
        "DEFAULTS"
        "DEFERRABLE"
        "DEFERRED"
        "DEFINED"
        "DEFINER"
        "DEGREE"
        "DEPTH"
        "DERIVED"
        "DESC"
        "DESCRIPTION"
        "DESCRIPTOR"
        "DIAGNOSTICS"
        "DISPATCH"
        "DOMAIN"
        "DOW"
        "DOY"
        "DYNAMIC_FUNCTION"
        "DYNAMIC_FUNCTION_CODE"
        "ENCODING"
        "EPOCH"
        "ERROR"
        "EXCEPTION"
        "EXCLUDE"
        "EXCLUDING"
        "FINAL"
        "FIRST"
        "FOLLOWING"
        "FORMAT"
        "FORTRAN"
        "FOUND"
        "FRAC_SECOND"
        "G"
        "GENERAL"
        "GENERATED"
        "GEOMETRY"
        "GO"
        "GOTO"
        "GRANTED"
        "HIERARCHY"
        "IGNORE"
        "IMMEDIATE"
        "IMMEDIATELY"
        "IMPLEMENTATION"
        "INCLUDING"
        "INCREMENT"
        "INITIALLY"
        "INPUT"
        "INSTANCE"
        "INSTANTIABLE"
        "INVOKER"
        "ISODOW"
        "ISOYEAR"
        "ISOLATION"
        "JAVA"
        "JSON"
        "K"
        "KEY"
        "KEY_MEMBER"
        "KEY_TYPE"
        "LABEL"
        "LAST"
        "LENGTH"
        "LEVEL"
        "LIBRARY"
        "LOCATOR"
        "M"
        "MAP"
        "MATCHED"
        "MAXVALUE"
        "MICROSECOND"
        "MESSAGE_LENGTH"
        "MESSAGE_OCTET_LENGTH"
        "MESSAGE_TEXT"
        "MILLISECOND"
        "MILLENNIUM"
        "MINVALUE"
        "MORE_"
        "MUMPS"
        "NAME"
        "NAMES"
        "NANOSECOND"
        "NESTING"
        "NORMALIZED"
        "NULLABLE"
        "NULLS"
        "NUMBER"
        "OBJECT"
        "OCTETS"
        "OPTION"
        "OPTIONS"
        "ORDERING"
        "ORDINALITY"
        "OTHERS"
        "OUTPUT"
        "OVERRIDING"
        "PAD"
        "PARAMETER_MODE"
        "PARAMETER_NAME"
        "PARAMETER_ORDINAL_POSITION"
        "PARAMETER_SPECIFIC_CATALOG"
        "PARAMETER_SPECIFIC_NAME"
        "PARAMETER_SPECIFIC_SCHEMA"
        "PARTIAL"
        "PASCAL"
        "PASSING"
        "PASSTHROUGH"
        "PAST"
        "PATH"
        "PLACING"
        "PLAN"
        "PLI"
        "PRECEDING"
        "PRESERVE"
        "PRIOR"
        "PRIVILEGES"
        "PUBLIC"
        "QUARTER"
        "READ"
        "RELATIVE"
        "REPEATABLE"
        "REPLACE"
        "RESPECT"
        "RESTART"
        "RESTRICT"
        "RETURNED_CARDINALITY"
        "RETURNED_LENGTH"
        "RETURNED_OCTET_LENGTH"
        "RETURNED_SQLSTATE"
        "RETURNING"
        "ROLE"
        "ROUTINE"
        "ROUTINE_CATALOG"
        "ROUTINE_NAME"
        "ROUTINE_SCHEMA"
        "ROW_COUNT"
        "SCALAR"
        "SCALE"
        "SCHEMA"
        "SCHEMA_NAME"
        "SCOPE_CATALOGS"
        "SCOPE_NAME"
        "SCOPE_SCHEMA"
        "SECTION"
        "SECURITY"
        "SELF"
        "SEQUENCE"
        "SERIALIZABLE"
        "SERVER"
        "SERVER_NAME"
        "SESSION"
        "SETS"
        "SIMPLE"
        "SIZE"
        "SOURCE"
        "SPACE"
        "SPECIFIC_NAME"
        "SQL_BIGINT"
        "SQL_BINARY"
        "SQL_BIT"
        "SQL_BLOB"
        "SQL_BOOLEAN"
        "SQL_CHAR"
        "SQL_CLOB"
        "SQL_DATE"
        "SQL_DECIMAL"
        "SQL_DOUBLE"
        "SQL_FLOAT"
        "SQL_INTEGER"
        "SQL_INTERVAL_DAY"
        "SQL_INTERVAL_DAY_TO_HOUR"
        "SQL_INTERVAL_DAY_TO_MINUTE"
        "SQL_INTERVAL_DAY_TO_SECOND"
        "SQL_INTERVAL_HOUR"
        "SQL_INTERVAL_HOUR_TO_MINUTE"
        "SQL_INTERVAL_HOUR_TO_SECOND"
        "SQL_INTERVAL_MINUTE"
        "SQL_INTERVAL_MINUTE_TO_SECOND"
        "SQL_INTERVAL_MONTH"
        "SQL_INTERVAL_SECOND"
        "SQL_INTERVAL_YEAR"
        "SQL_INTERVAL_YEAR_TO_MONTH"
        "SQL_LONGVARBINARY"
        "SQL_LONGVARNCHAR"
        "SQL_LONGVARCHAR"
        "SQL_NCHAR"
        "SQL_NCLOB"
        "SQL_NUMERIC"
        "SQL_NVARCHAR"
        "SQL_REAL"
        "SQL_SMALLINT"
        "SQL_TIME"
        "SQL_TIMESTAMP"
        "SQL_TINYINT"
        "SQL_TSI_DAY"
        "SQL_TSI_FRAC_SECOND"
        "SQL_TSI_HOUR"
        "SQL_TSI_MICROSECOND"
        "SQL_TSI_MINUTE"
        "SQL_TSI_MONTH"
        "SQL_TSI_QUARTER"
        "SQL_TSI_SECOND"
        "SQL_TSI_WEEK"
        "SQL_TSI_YEAR"
        "SQL_VARBINARY"
        "SQL_VARCHAR"
        "STATE"
        "STATEMENT"
        "STRUCTURE"
        "STYLE"
        "SUBCLASS_ORIGIN"
        "SUBSTITUTE"
        "TABLE_NAME"
        "TEMPORARY"
        "TIES"
        "TIMESTAMPADD"
        "TIMESTAMPDIFF"
        "TOP_LEVEL_COUNT"
        "TRANSACTION"
        "TRANSACTIONS_ACTIVE"
        "TRANSACTIONS_COMMITTED"
        "TRANSACTIONS_ROLLED_BACK"
        "TRANSFORM"
        "TRANSFORMS"
        "TRIGGER_CATALOG"
        "TRIGGER_NAME"
        "TRIGGER_SCHEMA"
        "TYPE"
        "UNBOUNDED"
        "UNCOMMITTED"
        "UNCONDITIONAL"
        "UNDER"
        "UNNAMED"
        "USAGE"
        "USER_DEFINED_TYPE_CATALOG"
        "USER_DEFINED_TYPE_CODE"
        "USER_DEFINED_TYPE_NAME"
        "USER_DEFINED_TYPE_SCHEMA"
        "UTF8"
        "UTF16"
        "UTF32"
        "VERSION"
        "VIEW"
        "WEEK"
        "WRAPPER"
        "WORK"
        "WRITE"
        "XML"
        "ZONE"
    ]

    # List of additional join types. Each is a method with no arguments.
    # Example: LeftSemiJoin()
    joinTypes: [
    ]

    # List of methods for parsing custom SQL statements.
    # Return type of method implementation should be 'SqlNode'.
    # Example: SqlShowDatabases(), SqlShowTables().
    statementParserMethods: [
    ]

    # List of methods for parsing custom literals.
    # Return type of method implementation should be "SqlNode".
    # Example: ParseJsonLiteral().
    literalParserMethods: [
    ]

    # List of methods for parsing custom data types.
    # Return type of method implementation should be "SqlIdentifier".
    # Example: SqlParseTimeStampZ().
    dataTypeParserMethods: [
    ]

    # List of methods for parsing extensions to "ALTER <scope>" calls.
    # Each must accept arguments "(SqlParserPos pos, String scope)".
    # Example: "SqlUploadJarNode"
    alterStatementParserMethods: [
    ]

    # List of methods for parsing extensions to "CREATE [OR REPLACE]" calls.
    # Each must accept arguments "(SqlParserPos pos, boolean replace)".
    createStatementParserMethods: [
    ]

    # List of methods for parsing extensions to "DROP" calls.
    # Each must accept arguments "(SqlParserPos pos)".
    dropStatementParserMethods: [
    ]

    # List of files in @includes directory that have parser method
    # implementations for parsing custom SQL statements, literals or types
    # given as part of "statementParserMethods", "literalParserMethods" or
    # "dataTypeParserMethods".
    implementationFiles: [
      "parserImpls.ftl"
    ]

    includeCompoundIdentifier: true
    includeBraces: true
    includeAdditionalDeclarations: false
  }
}

freemarkerLinks: {
  includes: includes/
}
</code>```

I am able to see the method regRealtionalOperator present in generated SqlParseImp class in javacc package of the target directory. Also in fmpp of generate-source, the generated Parser.jj also contains by the method.
Still, upon running the above query, SqlPArseException [ Encountered FOO_GREATER_THAN error is being thrown.

答: You've added it as a keyword, but you still need to indicate where this operator can be used in a query. For example, in Parser.jj, you'll see the comp() production which is used wherever a comparison operator is required. Based on where your operator is valid in a query, you'll have to decide how to modify the grammar.

Body:
I want to support FOO_GREATER_THAN clause instead of > in my sql parser.
For ex:
select * from people where age FOO_GREATER_THAN 10

I followed https://calcite.apache.org/docs/adapter.html#extending-the-parser and I have added custom fmpp and ftl file, but I am not able to add it.

parserImpls.ftl

SqlKind regRealtionalOperator() :
SqlKind regRealtionalOperator() :
{
}
{
    <FOO_EQUAL> { return SqlKind.EQUALS; }
|
    <FOO_GREATER_THAN> { return SqlKind.NOT_EQUALS; }
}

config.fmpp

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to you under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This file is an FMPP (http://fmpp.sourceforge.net/) configuration file to
# allow clients to extend Calcite's SQL parser to support application specific
# SQL statements, literals or data types.
#
# Calcite's parser grammar file (Parser.jj) is written in javacc
# (http://javacc.java.net/) with Freemarker (http://freemarker.org/) variables
# to allow clients to:
#   1. have custom parser implementation class and package name.
#   2. insert new parser method implementations written in javacc to parse
#      custom:
#      a) SQL statements.
#      b) literals.
#      c) data types.
#   3. add new keywords to support custom SQL constructs added as part of (2).
#   4. add import statements needed by inserted custom parser implementations.
#
# Parser template file (Parser.jj) along with this file are packaged as
# part of the calcite-core-<version>.jar under "codegen" directory.

data: {
  parser: {
    # Generated parser implementation package and class name.
    package: "org.apache.calcite.sql.parser.impl",
    class: "SqlParserImpl",

    # List of additional classes and packages to import.
    # Example. "org.apache.calcite.sql.*", "java.util.List".
    imports: [
    ]

    # List of new keywords. Example: "DATABASES", "TABLES". If the keyword is not a reserved
    # keyword add it to 'nonReservedKeywords' section.
    keywords: [
    "FOO_EQUAL"
    "FOO_GREATER_THAN"
    ]

    # List of keywords from "keywords" section that are not reserved.
    nonReservedKeywords: [
        "A"
        "ABSENT"
        "ABSOLUTE"
        "ACTION"
        "ADA"
        "ADD"
        "ADMIN"
        "AFTER"
        "ALWAYS"
        "APPLY"
        "ASC"
        "ASSERTION"
        "ASSIGNMENT"
        "ATTRIBUTE"
        "ATTRIBUTES"
        "BEFORE"
        "BERNOULLI"
        "BREADTH"
        "C"
        "CASCADE"
        "CATALOG"
        "CATALOG_NAME"
        "CENTURY"
        "CHAIN"
        "CHARACTER_SET_CATALOG"
        "CHARACTER_SET_NAME"
        "CHARACTER_SET_SCHEMA"
        "CHARACTERISTICS"
        "CHARACTERS"
        "CLASS_ORIGIN"
        "COBOL"
        "COLLATION"
        "COLLATION_CATALOG"
        "COLLATION_NAME"
        "COLLATION_SCHEMA"
        "COLUMN_NAME"
        "COMMAND_FUNCTION"
        "COMMAND_FUNCTION_CODE"
        "COMMITTED"
        "CONDITION_NUMBER"
        "CONDITIONAL"
        "CONNECTION"
        "CONNECTION_NAME"
        "CONSTRAINT_CATALOG"
        "CONSTRAINT_NAME"
        "CONSTRAINT_SCHEMA"
        "CONSTRAINTS"
        "CONSTRUCTOR"
        "CONTINUE"
        "CURSOR_NAME"
        "DATA"
        "DATABASE"
        "DATETIME_INTERVAL_CODE"
        "DATETIME_INTERVAL_PRECISION"
        "DECADE"
        "DEFAULTS"
        "DEFERRABLE"
        "DEFERRED"
        "DEFINED"
        "DEFINER"
        "DEGREE"
        "DEPTH"
        "DERIVED"
        "DESC"
        "DESCRIPTION"
        "DESCRIPTOR"
        "DIAGNOSTICS"
        "DISPATCH"
        "DOMAIN"
        "DOW"
        "DOY"
        "DYNAMIC_FUNCTION"
        "DYNAMIC_FUNCTION_CODE"
        "ENCODING"
        "EPOCH"
        "ERROR"
        "EXCEPTION"
        "EXCLUDE"
        "EXCLUDING"
        "FINAL"
        "FIRST"
        "FOLLOWING"
        "FORMAT"
        "FORTRAN"
        "FOUND"
        "FRAC_SECOND"
        "G"
        "GENERAL"
        "GENERATED"
        "GEOMETRY"
        "GO"
        "GOTO"
        "GRANTED"
        "HIERARCHY"
        "IGNORE"
        "IMMEDIATE"
        "IMMEDIATELY"
        "IMPLEMENTATION"
        "INCLUDING"
        "INCREMENT"
        "INITIALLY"
        "INPUT"
        "INSTANCE"
        "INSTANTIABLE"
        "INVOKER"
        "ISODOW"
        "ISOYEAR"
        "ISOLATION"
        "JAVA"
        "JSON"
        "K"
        "KEY"
        "KEY_MEMBER"
        "KEY_TYPE"
        "LABEL"
        "LAST"
        "LENGTH"
        "LEVEL"
        "LIBRARY"
        "LOCATOR"
        "M"
        "MAP"
        "MATCHED"
        "MAXVALUE"
        "MICROSECOND"
        "MESSAGE_LENGTH"
        "MESSAGE_OCTET_LENGTH"
        "MESSAGE_TEXT"
        "MILLISECOND"
        "MILLENNIUM"
        "MINVALUE"
        "MORE_"
        "MUMPS"
        "NAME"
        "NAMES"
        "NANOSECOND"
        "NESTING"
        "NORMALIZED"
        "NULLABLE"
        "NULLS"
        "NUMBER"
        "OBJECT"
        "OCTETS"
        "OPTION"
        "OPTIONS"
        "ORDERING"
        "ORDINALITY"
        "OTHERS"
        "OUTPUT"
        "OVERRIDING"
        "PAD"
        "PARAMETER_MODE"
        "PARAMETER_NAME"
        "PARAMETER_ORDINAL_POSITION"
        "PARAMETER_SPECIFIC_CATALOG"
        "PARAMETER_SPECIFIC_NAME"
        "PARAMETER_SPECIFIC_SCHEMA"
        "PARTIAL"
        "PASCAL"
        "PASSING"
        "PASSTHROUGH"
        "PAST"
        "PATH"
        "PLACING"
        "PLAN"
        "PLI"
        "PRECEDING"
        "PRESERVE"
        "PRIOR"
        "PRIVILEGES"
        "PUBLIC"
        "QUARTER"
        "READ"
        "RELATIVE"
        "REPEATABLE"
        "REPLACE"
        "RESPECT"
        "RESTART"
        "RESTRICT"
        "RETURNED_CARDINALITY"
        "RETURNED_LENGTH"
        "RETURNED_OCTET_LENGTH"
        "RETURNED_SQLSTATE"
        "RETURNING"
        "ROLE"
        "ROUTINE"
        "ROUTINE_CATALOG"
        "ROUTINE_NAME"
        "ROUTINE_SCHEMA"
        "ROW_COUNT"
        "SCALAR"
        "SCALE"
        "SCHEMA"
        "SCHEMA_NAME"
        "SCOPE_CATALOGS"
        "SCOPE_NAME"
        "SCOPE_SCHEMA"
        "SECTION"
        "SECURITY"
        "SELF"
        "SEQUENCE"
        "SERIALIZABLE"
        "SERVER"
        "SERVER_NAME"
        "SESSION"
        "SETS"
        "SIMPLE"
        "SIZE"
        "SOURCE"
        "SPACE"
        "SPECIFIC_NAME"
        "SQL_BIGINT"
        "SQL_BINARY"
        "SQL_BIT"
        "SQL_BLOB"
        "SQL_BOOLEAN"
        "SQL_CHAR"
        "SQL_CLOB"
        "SQL_DATE"
        "SQL_DECIMAL"
        "SQL_DOUBLE"
        "SQL_FLOAT"
        "SQL_INTEGER"
        "SQL_INTERVAL_DAY"
        "SQL_INTERVAL_DAY_TO_HOUR"
        "SQL_INTERVAL_DAY_TO_MINUTE"
        "SQL_INTERVAL_DAY_TO_SECOND"
        "SQL_INTERVAL_HOUR"
        "SQL_INTERVAL_HOUR_TO_MINUTE"
        "SQL_INTERVAL_HOUR_TO_SECOND"
        "SQL_INTERVAL_MINUTE"
        "SQL_INTERVAL_MINUTE_TO_SECOND"
        "SQL_INTERVAL_MONTH"
        "SQL_INTERVAL_SECOND"
        "SQL_INTERVAL_YEAR"
        "SQL_INTERVAL_YEAR_TO_MONTH"
        "SQL_LONGVARBINARY"
        "SQL_LONGVARNCHAR"
        "SQL_LONGVARCHAR"
        "SQL_NCHAR"
        "SQL_NCLOB"
        "SQL_NUMERIC"
        "SQL_NVARCHAR"
        "SQL_REAL"
        "SQL_SMALLINT"
        "SQL_TIME"
        "SQL_TIMESTAMP"
        "SQL_TINYINT"
        "SQL_TSI_DAY"
        "SQL_TSI_FRAC_SECOND"
        "SQL_TSI_HOUR"
        "SQL_TSI_MICROSECOND"
        "SQL_TSI_MINUTE"
        "SQL_TSI_MONTH"
        "SQL_TSI_QUARTER"
        "SQL_TSI_SECOND"
        "SQL_TSI_WEEK"
        "SQL_TSI_YEAR"
        "SQL_VARBINARY"
        "SQL_VARCHAR"
        "STATE"
        "STATEMENT"
        "STRUCTURE"
        "STYLE"
        "SUBCLASS_ORIGIN"
        "SUBSTITUTE"
        "TABLE_NAME"
        "TEMPORARY"
        "TIES"
        "TIMESTAMPADD"
        "TIMESTAMPDIFF"
        "TOP_LEVEL_COUNT"
        "TRANSACTION"
        "TRANSACTIONS_ACTIVE"
        "TRANSACTIONS_COMMITTED"
        "TRANSACTIONS_ROLLED_BACK"
        "TRANSFORM"
        "TRANSFORMS"
        "TRIGGER_CATALOG"
        "TRIGGER_NAME"
        "TRIGGER_SCHEMA"
        "TYPE"
        "UNBOUNDED"
        "UNCOMMITTED"
        "UNCONDITIONAL"
        "UNDER"
        "UNNAMED"
        "USAGE"
        "USER_DEFINED_TYPE_CATALOG"
        "USER_DEFINED_TYPE_CODE"
        "USER_DEFINED_TYPE_NAME"
        "USER_DEFINED_TYPE_SCHEMA"
        "UTF8"
        "UTF16"
        "UTF32"
        "VERSION"
        "VIEW"
        "WEEK"
        "WRAPPER"
        "WORK"
        "WRITE"
        "XML"
        "ZONE"
    ]

    # List of additional join types. Each is a method with no arguments.
    # Example: LeftSemiJoin()
    joinTypes: [
    ]

    # List of methods for parsing custom SQL statements.
    # Return type of method implementation should be 'SqlNode'.
    # Example: SqlShowDatabases(), SqlShowTables().
    statementParserMethods: [
    ]

    # List of methods for parsing custom literals.
    # Return type of method implementation should be "SqlNode".
    # Example: ParseJsonLiteral().
    literalParserMethods: [
    ]

    # List of methods for parsing custom data types.
    # Return type of method implementation should be "SqlIdentifier".
    # Example: SqlParseTimeStampZ().
    dataTypeParserMethods: [
    ]

    # List of methods for parsing extensions to "ALTER <scope>" calls.
    # Each must accept arguments "(SqlParserPos pos, String scope)".
    # Example: "SqlUploadJarNode"
    alterStatementParserMethods: [
    ]

    # List of methods for parsing extensions to "CREATE [OR REPLACE]" calls.
    # Each must accept arguments "(SqlParserPos pos, boolean replace)".
    createStatementParserMethods: [
    ]

    # List of methods for parsing extensions to "DROP" calls.
    # Each must accept arguments "(SqlParserPos pos)".
    dropStatementParserMethods: [
    ]

    # List of files in @includes directory that have parser method
    # implementations for parsing custom SQL statements, literals or types
    # given as part of "statementParserMethods", "literalParserMethods" or
    # "dataTypeParserMethods".
    implementationFiles: [
      "parserImpls.ftl"
    ]

    includeCompoundIdentifier: true
    includeBraces: true
    includeAdditionalDeclarations: false
  }
}

freemarkerLinks: {
  includes: includes/
}

I am able to see the method regRealtionalOperator present in generated SqlParseImp class in javacc package of the target directory. Also in fmpp of generate-source, the generated Parser.jj also contains by the method.
Still, upon running the above query, SqlPArseException [ Encountered FOO_GREATER_THAN error is being thrown.


来源: stackexchange

问:
How to keep the last, non-missing set of complete observations across multiple columns?
I have a longitudinal data set and would like to extract the latest, non-missing complete set of observations for each variable in the data set where id is a unique identifier, yr is year, and x1 and x2 are variables with missing values. The actual data set has 100s of variables over the course of 60 years.

```<code>data <- data.frame(id=rep(1:3,3)
yr=rep(1:3,times=1, each=3)
x1=c(1,3,7,NA,NA,NA,9,4,10)
x2=c(NA,NA,NA,3,9,6,NA,NA,NA))
</code>```

Below are my expected results. For x1, the latest complete set of observations is year 3. For x2, the latest complete set of observations is year 2.

答:
Using base R

```<code>subset(data, yr %in% names(tail(which(sapply(split(data[c('x1', 'x2')],
        data$yr), function(x) any(colSums(!is.na(x)) == nrow(x)))), 2)))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a longitudinal data set and would like to extract the latest, non-missing complete set of observations for each variable in the data set where id is a unique identifier, yr is year, and x1 and x2 are variables with missing values. The actual data set has 100s of variables over the course of 60 years.

data <- data.frame(id=rep(1:3,3)
yr=rep(1:3,times=1, each=3)
x1=c(1,3,7,NA,NA,NA,9,4,10)
x2=c(NA,NA,NA,3,9,6,NA,NA,NA))

Below are my expected results. For x1, the latest complete set of observations is year 3. For x2, the latest complete set of observations is year 2.

Body:
Using base R

subset(data, yr %in% names(tail(which(sapply(split(data[c('x1', 'x2')],
        data$yr), function(x) any(colSums(!is.na(x)) == nrow(x)))), 2)))


问:
read a text file and remove all occurences of a duplicates
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

```<code>hello i am a businessman  i am also a student
</code>```

output should be:

```<code>hello businessman also student
</code>```

my approach was like this:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}
</code>```

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.

答:
What you need is an implementation of Set interface. Java provides multiple of them:

HashSet: This implementation does not maintain any order

TreeSet: This implementation maintains natural order (Lexicographical comparison for Strings, Increasing order for numbers, etc)

LinkedHashSet: This implementation maintains the order of insertion.

Like others mentioned, this looks like a clear homework problem. So I am not going to code the solution for you. However, I will show you a sample algorithm that can work.

Step 1: Open the file to read words one by one.

Step 2: Declare two sets, one for storing all the words and one for storing the duplicates.

Step 3: Read the words one by one and try inserting into the first set. Java's add method for set returns a boolean stating true or false based on insertion succeeding or failing.

Step 4: Try to insert in first set.

Step 4.1: If insertion passed, this means that the word has never been encountered so far. Move on to the next word and do Step 4 again.

Step 4.2: If insertion fails, that means that the word has already been seen in before and hence we should not have it in the final list. So put in the second list. Move on the next word and do Step 4 again.

Step 5: After finishing all the words, you will have a set of unique words in the first set (Set A) and a set of words that occurred more than once in that paragraph. (Set B).

Step 6: Perform A - B (Set of all words in A but not in B)

Step 7: The result above has all the words that occurred only once.

Note that this is just one kind of algorithm for the solution. There are other solutions using other data structures. (You can use HasMap, where you can map each word to the number of times it occurred and then print all those out that occured only once). Also note that you can implement the solution above using ArrayLists as well. Figure out how these work and you will really learn something.

Body:
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

hello i am a businessman  i am also a student

output should be:

hello businessman also student

my approach was like this:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.


问:
How would I go about turning the characters in a word that a user inputs into an array that contains the letters in the word?
I am trying to code a hangman game in java. Using JOptionPane to ask the user for a word, how would I go about turning the characters in a word that a user inputs into an array that contains the letters in the word?</p>

答:
In Java, the String class is a little bit like a decorated array (the characters are internally stored in an array). So your best bet honestly is just to use String or StringBuilder

But if it needs to be a char[], you can create your array using

```<code>char[] entries = new char[26];
entriesLength = 0;
</code>```

And then when you have another guess

```<code>entries[entriesLength++] = newGuess;
</code>```

Body:
In Java, the String class is a little bit like a decorated array (the characters are internally stored in an array). So your best bet honestly is just to use String or StringBuilder

But if it needs to be a char[], you can create your array using

char[] entries = new char[26];
entriesLength = 0;

And then when you have another guess

entries[entriesLength++] = newGuess;


问:
Why am I getting error at line 1 on Create Table
First time working with MySQL. Using MySQL Workbench with a new instance installed on my Windows 10 desktop. I've created a test test db/schema, and now trying to create a table.

```<code>CREATE TABLE kcplusers (
'user_barcode' varchar(255),
'first_name' varchar(255),
'middle_name' varchar(255),
'last_name' varchar(255),
'address_street' varchar(500),
'city_state' varchar(500),
'zip' varchar(100),
'user_profile' varchar(500),
'birth_date' DATE
);
</code>```

Workbench shows a red x at line 1 and red slashes under the open-parenth (

I get the error:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user_barcode' varchar(255),  'first_name' varchar(255),      'middle_name' varc' at line 2

What am I missing?

答:
Don't use single quotes ' for the fields names, use backticks ` or nothing at all:

```<code>CREATE TABLE kcplusers (
`user_barcode` varchar(255),
`first_name` varchar(255),
`middle_name` varchar(255),
`last_name` varchar(255),
`address_street` varchar(500),
`city_state` varchar(500),
`zip` varchar(100),
`user_profile` varchar(500),
`birth_date` DATE
);
</code>```

Body:
First time working with MySQL. Using MySQL Workbench with a new instance installed on my Windows 10 desktop. I've created a test test db/schema, and now trying to create a table.

CREATE TABLE kcplusers (
'user_barcode' varchar(255),
'first_name' varchar(255),
'middle_name' varchar(255),
'last_name' varchar(255),
'address_street' varchar(500),
'city_state' varchar(500),
'zip' varchar(100),
'user_profile' varchar(500),
'birth_date' DATE
);

Workbench shows a red x at line 1 and red slashes under the open-parenth (

I get the error:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user_barcode' varchar(255),  'first_name' varchar(255),      'middle_name' varc' at line 2

What am I missing?

Body:
Don't use single quotes ' for the fields names, use backticks ` or nothing at all:

CREATE TABLE kcplusers (
`user_barcode` varchar(255),
`first_name` varchar(255),
`middle_name` varchar(255),
`last_name` varchar(255),
`address_street` varchar(500),
`city_state` varchar(500),
`zip` varchar(100),
`user_profile` varchar(500),
`birth_date` DATE
);


问:
React Failed to compile. Module not found: Can't resolve, How to compile with react-router?
I am dealing with an issue on two new projects I have just started and I have it configured the way I have it on another in production and for some reason I can't seem to find the bug here.

I have started my react project with the latest version of create-react-app using: npx create-react-app myapp and for some reason my app does not compile locally with react-router-dom.

Here are my dependencies in my package.json:

```<code>"dependencies": {
    "react": "^16.8.6",
    "react-bootstrap": "^0.32.4",
    "react-dom": "^16.8.6",
    "react-router-dom": "^4.3.1",
    "react-scripts": "3.0.1"
</code>```

I have an index.js file where I am wrapping my <App /> component inside of the <Router /> component that I am importing with BrowserRouter as specified from react-router-dom.

Here are the contents of my index.js file:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();
</code>```

From there my <App /> component implements a custom <Routes /> component that uses Route and Switch from react-router-dom to handle my app's routing needs.

Here are the contents of my <App /> component:

```<code>import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Navbar } from "react-bootstrap";
import Routes from "./Routes.js";
import "./App.css";

class App extends Component {
  render() {
    return (
      <div className="App container">
        <Navbar fluid collapsOnSelect>
          ...... misc navbar code
        </Navbar>
        <Routes />
      </div>
      );
  }
}

export default App;
</code>```

This is what my Routes.js file looks like and how it uses the Route and Switch from react-router-dom:

```<code>import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./containers/Home";

export default () => <Switch>
                       <Route path="/" exact component={ Home } />
                     </Switch>;
</code>```

Here is the { Home } component that I am trying to serve up locally:

```<code>import React, { Component } from "react";
import "./Home.css";

export default class Home extends Component {
  render() {
    return (
      <div className="Home">
        <div className="LandingPage">
          ... random html code
        </div>
      </div>
      );
  }
}
</code>```

And finally here is the error:

What do you think could be the problem here??? Thanks !

UPDATE: Adding File Hierarchy

答:
Ah! So it was with the file hierarchy. Routes.js is in src, so it's looking in src/components, which doesn't exist.

Instead, make it import Home from "../containers/Home";, or restructure the project so that containers is inside src.

Body:
I am dealing with an issue on two new projects I have just started and I have it configured the way I have it on another in production and for some reason I can't seem to find the bug here.

I have started my react project with the latest version of create-react-app using: npx create-react-app myapp and for some reason my app does not compile locally with react-router-dom.

Here are my dependencies in my package.json:

"dependencies": {
    "react": "^16.8.6",
    "react-bootstrap": "^0.32.4",
    "react-dom": "^16.8.6",
    "react-router-dom": "^4.3.1",
    "react-scripts": "3.0.1"

I have an index.js file where I am wrapping my <App /> component inside of the <Router /> component that I am importing with BrowserRouter as specified from react-router-dom.

Here are the contents of my index.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();

From there my <App /> component implements a custom <Routes /> component that uses Route and Switch from react-router-dom to handle my app's routing needs.

Here are the contents of my <App /> component:

import React, { Component } from "react";
import { Link } from "react-router-dom";
import { Navbar } from "react-bootstrap";
import Routes from "./Routes.js";
import "./App.css";

class App extends Component {
  render() {
    return (

        <Navbar fluid collapsOnSelect>
          ...... misc navbar code
        </Navbar>
        <Routes />

      );
  }
}

export default App;

This is what my Routes.js file looks like and how it uses the Route and Switch from react-router-dom:

import React from "react";
import { Route, Switch } from "react-router-dom";
import Home from "./containers/Home";

export default () => <Switch>
                       <Route path="/" exact component={ Home } />
                     </Switch>;

Here is the { Home } component that I am trying to serve up locally:

import React, { Component } from "react";
import "./Home.css";

export default class Home extends Component {
  render() {
    return (

          ... random html code

      );
  }
}

And finally here is the error:

What do you think could be the problem here??? Thanks !

UPDATE: Adding File Hierarchy


问:
Using negative integer range of int (4 bytes) as ids(-2.14 billion to 0) : Any downsides?
I am storing certain entities in my database with integer Ids of size 32 bits thus using the range of -2.14 billion to +2.14 billion.

I have given tried giving some meaning to my ids due to which my Ids, in the positive range, have finished up a bit quickly. I am looking forward to use the negative integer range of -2.14 billion to 0.

Wanted to know, if you could see any downsides of using negative integers as ids, though personally I don't see any downsides.

答: Given than dumb keys are only compared for equality, sign or lack thereof has no impact.</p>

ContentLicense: CC BY-SA 3.0


问:
How to add user to another table after user registration in laravel?
I am developing an e-commerce project in Laravel 5.6 in which I have two tables for users :

Users for passwords and some other stuff and

UserDetails table for storing user address, phone, city, pin code, etc.

While registering a user with storing credentials in the Users table I want to make a column in the UserDetails table with the same user_id that has been generated while adding to Users table.

Below is my migrations :

```<code>Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

Schema::create('user_details', function (Blueprint $table) {
            $table->increments('id');
            $table->string('phone')->nullable();
            $table->string('city')->nullable();
            $table->string('pincode')->nullable();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
</code>```

I had tried to add following in the create function in RegisterController

```<code>protected function create(array $data)
    {
        User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        UserDetails::create([
            'user_id' => Auth::user()->id
        ]);

        return;
    }
</code>```

But it doesn't work and shows

Trying to get property 'id' of non-object".

Help me through this.

答:
You can modify the create function, on app/Http/Controllers/Auth/RegisterController.php,

which is, by default:

```<code>protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}
</code>```

Just change this to

```<code>protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
    UserDetails::create([
        'user_id' => $user->id
    ]);

    return $user;
}
</code>```

Body:
I am developing an e-commerce project in Laravel 5.6 in which I have two tables for users :

Users for passwords and some other stuff and

UserDetails table for storing user address, phone, city, pin code, etc.

While registering a user with storing credentials in the Users table I want to make a column in the UserDetails table with the same user_id that has been generated while adding to Users table.

Below is my migrations :

Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamp('email_verified_at')->nullable();
            $table->rememberToken();
            $table->timestamps();
        });

Schema::create('user_details', function (Blueprint $table) {
            $table->increments('id');
            $table->string('phone')->nullable();
            $table->string('city')->nullable();
            $table->string('pincode')->nullable();
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });

I had tried to add following in the create function in RegisterController

protected function create(array $data)
    {
        User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        UserDetails::create([
            'user_id' => Auth::user()->id
        ]);

        return;
    }

But it doesn't work and shows

Trying to get property 'id' of non-object".

Help me through this.

Body:
You can modify the create function, on app/Http/Controllers/Auth/RegisterController.php,

which is, by default:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
}

Just change this to

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
    ]);
    UserDetails::create([
        'user_id' => $user->id
    ]);

    return $user;
}


问:
Ignoring specified items of StringList
I would like to create a program (learning Delphi) that takes 3 different list (from TEdit)

A list of names

A list of names to ignore when searching first list

A list of names to ignore when searching first list

By taking the 3 TEdit and converting the text to TStringList and seperating (I am so far okay with this).

I want to output the first name (or item) of the first list that is neither on 2nd or 3rd list

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
i, j ,k : integer;
begin

  list := TStringList.Create;
  ignoreListFirst := TStringList.Create;
  ignoreListSecond := TStringList.Create;

  list.Delimiter := ',';
  ignoreListFirst.Delimiter := ',';
  ignoreListSecond.Delimiter := ',';

  list.DelimitedText := EditList.Text;
  ignoreListFirst.DelimitedText := EditIgnoreList1.Text;
  ignoreListSecond.DelimitedText := EditIgnoreList2.Text;

  for k := 0 to list.Count - 1 do
  begin
    for i := 0 to ignoreListFirst.Count - 1 do
    begin
      for j := 0 to ignoreListSecond.Count - 1 do
      begin
        if (list[k] <> ignoreListFirst[i]) and (list[k] <> ignoreListSecond[k]) then

        EditResult.Text := list[k];
        break;

      end;
    end;
  end;

  list.Free;
  ignoreListFirst.Free;
  ignoreListSecond.Free;

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  EditList.Text := 'Katy,Mary,John,Maggie,Carl';
  EditIgnoreList1.Text := 'Katy,Mary,John';
  EditIgnoreList2.Text := 'John,Carl';
end;

</code>```

Tried swapping the loop order to see if I can pinpoint the problem.

first list in last loop give me no errors and produces the name 'Katy' which is yes, the first on the list but ignored.

Swapped the the first list to be first loop. produces 'Mary' which I guess ignored (which I wanted) Katy but not others from what I can see.

In this example (which does not work) I want it to result 'Maggie' which is not on either ignore lists.

Thanks and sorry if I explained this wrong. Learning Delphi.
Do pinpoint any mistakes.

答:
While messing around with debugger and following the suggestions given I came to the answer bellow. </p>

```<code>procedure TForm1.Button1Click(Sender: TObject);
var
  iList, iListFirst ,iListSecond : integer;
  found : boolean;
begin

  list := TStringList.Create;
  ignoreListFirst := TStringList.Create;
  ignoreListSecond := TStringList.Create;

  list.Delimiter := ',';
  ignoreListFirst.Delimiter := ',';
  ignoreListSecond.Delimiter := ',';

  list.DelimitedText := EditList.Text;
  ignoreListFirst.DelimitedText := EditIgnoreList1.Text;
  ignoreListSecond.DelimitedText := EditIgnoreList2.Text;

  for iList := 0 to list.Count - 1 do
  begin
    for iListFirst := 0 to ignoreListFirst.Count - 1 do
    begin
      found := false;
      if list[iList] = ignoreListFirst[iListFirst] then
      begin
        found := true;
        break
      end;
    end;
    if not found then
    begin
      for iListSecond := 0 to ignoreListSecond.Count - 1 do
      begin
        if list[iList] = ignoreListSecond[iListSecond] then
        begin
          found := true;
          break
        end;
      end;
    end;
    if not found then
    begin
      EditResult.Text := list[iList];
      break
    end;
  end;

  list.Free;
  ignoreListFirst.Free;
  ignoreListSecond.Free;

end;
</code>```

Title: Ignoring specified items of StringList

Body:
I would like to create a program (learning Delphi) that takes 3 different list (from TEdit)

A list of names

A list of names to ignore when searching first list

A list of names to ignore when searching first list

By taking the 3 TEdit and converting the text to TStringList and seperating (I am so far okay with this).

I want to output the first name (or item) of the first list that is neither on 2nd or 3rd list

procedure TForm1.Button1Click(Sender: TObject);
var
i, j ,k : integer;
begin

  list := TStringList.Create;
  ignoreListFirst := TStringList.Create;
  ignoreListSecond := TStringList.Create;

  list.Delimiter := ',';
  ignoreListFirst.Delimiter := ',';
  ignoreListSecond.Delimiter := ',';

  list.DelimitedText := EditList.Text;
  ignoreListFirst.DelimitedText := EditIgnoreList1.Text;
  ignoreListSecond.DelimitedText := EditIgnoreList2.Text;

  for k := 0 to list.Count - 1 do
  begin
    for i := 0 to ignoreListFirst.Count - 1 do
    begin
      for j := 0 to ignoreListSecond.Count - 1 do
      begin
        if (list[k] <> ignoreListFirst[i]) and (list[k] <> ignoreListSecond[k]) then

        EditResult.Text := list[k];
        break;

      end;
    end;
  end;

  list.Free;
  ignoreListFirst.Free;
  ignoreListSecond.Free;

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  EditList.Text := 'Katy,Mary,John,Maggie,Carl';
  EditIgnoreList1.Text := 'Katy,Mary,John';
  EditIgnoreList2.Text := 'John,Carl';
end;

Tried swapping the loop order to see if I can pinpoint the problem.

first list in last loop give me no errors and produces the name 'Katy' which is yes, the first on the list but ignored.

Swapped the the first list to be first loop. produces 'Mary' which I guess ignored (which I wanted) Katy but not others from what I can see.

In this example (which does not work) I want it to result 'Maggie' which is not on either ignore lists.

Thanks and sorry if I explained this wrong. Learning Delphi.
Do pinpoint any mistakes.

Body:
While messing around with debugger and following the suggestions given I came to the answer bellow.

procedure TForm1.Button1Click(Sender: TObject);
var
  iList, iListFirst ,iListSecond : integer;
  found : boolean;
begin

  list := TStringList.Create;
  ignoreListFirst := TStringList.Create;
  ignoreListSecond := TStringList.Create;

  list.Delimiter := ',';
  ignoreListFirst.Delimiter := ',';
  ignoreListSecond.Delimiter := ',';

  list.DelimitedText := EditList.Text;
  ignoreListFirst.DelimitedText := EditIgnoreList1.Text;
  ignoreListSecond.DelimitedText := EditIgnoreList2.Text;

  for iList := 0 to list.Count - 1 do
  begin
    for iListFirst := 0 to ignoreListFirst.Count - 1 do
    begin
      found := false;
      if list[iList] = ignoreListFirst[iListFirst] then
      begin
        found := true;
        break
      end;
    end;
    if not found then
    begin
      for iListSecond := 0 to ignoreListSecond.Count - 1 do
      begin
        if list[iList] = ignoreListSecond[iListSecond] then
        begin
          found := true;
          break
        end;
      end;
    end;
    if not found then
    begin
      EditResult.Text := list[iList];
      break
    end;
  end;

  list.Free;
  ignoreListFirst.Free;
  ignoreListSecond.Free;

end;


问:
React web scraping without using a server
There is a way in React to do web scraping without using a server that takes care of this.

I would like to use only React.

I was trying to use casperjs but it seems to give me problems on react when I set it, it can't find the module.

答:
As i understand, web scraping is process of gathering information (not data), from web pages.

Short answer: It is not always possible because of cross site scripting.

Long answer: The problem of gathering usefull information from pages with other domain name is that, server that serves specific domain have to explicitly define that allow you to get information from that server(technically not exactly, but for simplicity it is true). Mostly web servers, try to reduce list of allowed domain names, because this is security issue.


问:
How can I change calcite's default encode character set?
I use driver manager (eg. jdbc:calcite:inline) to get a calcite connection and run sql with it, but calcite's default encode character set(ISO) don't support Chinese characters, I want to find a method to change the encode character set.

I tried the following two sql:

select * from tb where id= '啊'

select * from tb where id= _UTF16'啊'

Firstly,I run a sql(select * from tb where id= '啊') and receive a error
 that is "org.apache.calcite.runtime.CalciteException: Failed to encode '啊' in character set 'ISO-8859-1'".

Secondly, I add a character set to the sql(select * from tb where id= _UTF16'啊'),but I receive another error that is "SqlValidatorException: Cannot apply = to the two different charsets ISO-8859-1 and UTF-16LE".

答: You should set the property calcite.default.charset to whatever character set you want to use. That said, I'm not sure this will solve all your problems. Support for other character sets is really a work in progress. See this discussion on the project mailing list.


问:
"Security aware" action link?
How can I create a "security aware" action link that detects if a user is authorized to click (invoke) the action?

Hide link if user is not allowed to use that action...

Depending from

web.config (authorization) and

[Authorize] attributes on actions

PS

I guess it is  bad practice to mix those 2 in MVC?

答:
In my case, I would like my logic to stay in the controller side. So I removed the dependency on HtmlHelper. The changes are minor, but it might help.

```<code>    protected bool HasActionPermission(string actionName, string controllerName)
    {
        if (string.IsNullOrWhiteSpace(controllerName))
            return false;

        var controller = GetControllerByName(ControllerContext.RequestContext, controllerName);
        var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
        var actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);
        return ActionIsAuthorized(ControllerContext, actionDescriptor);
    }

    private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false; // action does not exist so say yes - should we authorise this?!

        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);

        // run each auth filter until on fails
        // performance could be improved by some caching
        foreach (var filter in FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor))
        {
            var authFilter = filter.Instance as IAuthorizationFilter;

            if (authFilter == null)
                continue;

            authFilter.OnAuthorization(authContext);

            if (authContext.Result != null)
                return false;
        }

        return true;
    }

    private static ControllerBase GetControllerByName(RequestContext context, string controllerName)
    {
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

        IController controller = factory.CreateController(context, controllerName);

        if (controller == null)
        {
            throw new InvalidOperationException(

                String.Format(
                    CultureInfo.CurrentUICulture,
                    "Controller factory {0} controller {1} returned null",
                    factory.GetType(),
                    controllerName));
        }
        return (ControllerBase)controller;
    }
</code>```

ContentLicense: CC BY-SA 2.5

Title: "Security aware" action link?

Body:
In my case, I would like my logic to stay in the controller side. So I removed the dependency on HtmlHelper. The changes are minor, but it might help.

    protected bool HasActionPermission(string actionName, string controllerName)
    {
        if (string.IsNullOrWhiteSpace(controllerName))
            return false;

        var controller = GetControllerByName(ControllerContext.RequestContext, controllerName);
        var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
        var actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);
        return ActionIsAuthorized(ControllerContext, actionDescriptor);
    }

    private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false; // action does not exist so say yes - should we authorise this?!

        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);

        // run each auth filter until on fails
        // performance could be improved by some caching
        foreach (var filter in FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor))
        {
            var authFilter = filter.Instance as IAuthorizationFilter;

            if (authFilter == null)
                continue;

            authFilter.OnAuthorization(authContext);

            if (authContext.Result != null)
                return false;
        }

        return true;
    }

    private static ControllerBase GetControllerByName(RequestContext context, string controllerName)
    {
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

        IController controller = factory.CreateController(context, controllerName);

        if (controller == null)
        {
            throw new InvalidOperationException(

                String.Format(
                    CultureInfo.CurrentUICulture,
                    "Controller factory {0} controller {1} returned null",
                    factory.GetType(),
                    controllerName));
        }
        return (ControllerBase)controller;
    }


问:
How can i check if the function exists in my class
i started using Javascript OOP i'm still beginner,
i created a class and i want to know if the deleteQuote function exists in my class ?

This is my Class code

```<code>class Quote{

deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

var quote = new Quote();
var y = quote.deleteQuote();
console.log(typeof y);
</code>```

Thank you

答:
You can you hasOwnProperty() on the prototype object of Quote

class Quote{

  deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

console.log(Quote.prototype.hasOwnProperty('deleteQuote'));```

Body:
i started using Javascript OOP i'm still beginner,
i created a class and i want to know if the deleteQuote function exists in my class ?

This is my Class code

class Quote{

deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

var quote = new Quote();
var y = quote.deleteQuote();
console.log(typeof y);

Thank you


答:
Your routes.js should be </p>

```<code>import Home from "../containers/Home";
</code>```

<p>You gotta go up one directory to get to where containers is, the way you have it set up looks for containers inside there src </p>

Title: React Failed to compile. Module not found: Can't resolve, How to compile with react-router?

Body:
Your routes.js should be

import Home from "../containers/Home";

You gotta go up one directory to get to where containers is, the way you have it set up looks for containers inside there src


问:
Expanded Tree Cache Full Exception while executing XQuery on a huge number of documents
I am trying to retrieve value of XPath from multiple documents. In my case approximately 800k documents. I am getting and exception called

Expanded Tree cache full.

The same query yields the expected output when there are less documents i.e for 400k documents.

Following is the query used to retrieve value of XPath from collections: collection1 and collection2:

```<code>cts:search(doc(),
  cts:and-query((
    cts:collection-query("collection1"),
    cts:collection-query("collection2")
  ))
)/xpath/text()
</code>```

答:
Please see if the answer here will help you: https://help.marklogic.com/Knowledgebase/Article/View/9/16/resolving-xdmp-expntreecachefull-errors.

When the query needs to actually retrieve elements, values, or otherwise traverse the contents of one of these fragments, the fragment is uncompressed and cached in the expanded tree cache.

So, try rewriting the query to retrieve less number of documents. If you have enough memory, increasing expanded tree cache size may help you also.

Body:
I am trying to retrieve value of XPath from multiple documents. In my case approximately 800k documents. I am getting and exception called

Expanded Tree cache full.

The same query yields the expected output when there are less documents i.e for 400k documents.

Following is the query used to retrieve value of XPath from collections: collection1 and collection2:

cts:search(doc(),
  cts:and-query((
    cts:collection-query("collection1"),
    cts:collection-query("collection2")
  ))
)/xpath/text()


问:
Spring validation : Custom validate @RequestBody based on criteria @RequestParam
I want to validate a requestbody with @Valid annotation.
In the method there is a @RequestParam value.
If this @RequestParam value "min" I want that a field, in requestbody, is mandatory. It's possible with annotations?

```<code>@RequestMapping(method = RequestMethod.POST, value = ProductionResponse.URL, produces = JWSMessageConverter.JWS_MEDIA_TYPE_VALUE)
@ResponseBody
public ResponseEntity<ProductionResponse> richiestaProduzione(@RequestParam("issuerType") String issuerType,
        @RequestParam("issuerCode") String issuerCode, @RequestParam("procedureId") String procedureId,
        @Valid @RequestBody ProductionRequestResource requestBody) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("POST " + ProductionResponse.URL);
  @Valid ProductionRequestResource fff = requestBody;
    requestBody.setProcedureResource(issuerType, issuerCode, procedureId);

    try {
        ProductionResponse response = produzioneService.richiestaProduzione(requestBody);
        return ResponseEntity.ok(response);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.badRequest().body(ProductionResponse.ko(requestBody, e.getMessage(), requestBody.getNun()));
    }
}
</code>```

I want that the field issuerMunicipalityCode in the ProductionRequestResource is mandatory if issuerType is equal to "MIN".

答:
To continue further, here is how you can implement custom validation.

Add a validation to throw an exception when issueType is MIN and municipality code is empty/null.

```<code>@RequestMapping(method = RequestMethod.POST, value = ProductionResponse.URL, produces = JWSMessageConverter.JWS_MEDIA_TYPE_VALUE)
@ResponseBody
public ResponseEntity<ProductionResponse> richiestaProduzione(@RequestParam("issuerType") String issuerType,
        @RequestParam("issuerCode") String issuerCode, @RequestParam("procedureId") String procedureId,
        @RequestBody ProductionRequestResource requestBody) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("POST " + ProductionResponse.URL);

    if("MIN".equals(issuerType) && StringUtils.isEmpty(requestBody.getIssuerMunicipalityCode())) {
        throw new IllegalArgumentException("IssuerMuncipalityCode can't be null when IssuerType is MIN");
    }

    try {
        ProductionResponse response = produzioneService.richiestaProduzione(requestBody);
        return ResponseEntity.ok(response);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.badRequest().body(ProductionResponse.ko(requestBody, e.getMessage(), requestBody.getNun()));
    }
}
</code>```

Implement exception handler to catch the exceptions and build response body based on exception types. InvalidArgumentSuppliedException that was thrown above will be caught by below exception handler. Exception Handler is a best practice to handle exceptions in a separate component.

```<code>@ControllerAdvice
public class ScnSchedulerExceptionHandler {

    @ExceptionHandler(InvalidArgumentSuppliedException.class)
    public final ResponseEntity<Object> handleInvalidArgException(Exception ex) {
        ErrorResponseDTO errorDTO = new ErrorResponseDTO();
        errorDTO.setMessage(ex.getMessage());
        return new ResponseEntity<>(errorDTO, HttpStatus.NOT_ACCEPTABLE);
    }

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex) {
        ErrorResponseDTO errorDTO = new ErrorResponseDTO();
        errorDTO.setMessage("Internal server error occurred.");
        return new ResponseEntity<>(errorDTO, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
</code>```

In the exception handler, wrap the error messages in a pojo object.

```<code>public class ErrorResponseDTO {

    private String errorMessage;

}
</code>```

Body:
I want to validate a requestbody with @Valid annotation.
In the method there is a @RequestParam value.
If this @RequestParam value "min" I want that a field, in requestbody, is mandatory. It's possible with annotations?

@RequestMapping(method = RequestMethod.POST, value = ProductionResponse.URL, produces = JWSMessageConverter.JWS_MEDIA_TYPE_VALUE)
@ResponseBody
public ResponseEntity<ProductionResponse> richiestaProduzione(@RequestParam("issuerType") String issuerType,
        @RequestParam("issuerCode") String issuerCode, @RequestParam("procedureId") String procedureId,
        @Valid @RequestBody ProductionRequestResource requestBody) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("POST " + ProductionResponse.URL);
  @Valid ProductionRequestResource fff = requestBody;
    requestBody.setProcedureResource(issuerType, issuerCode, procedureId);

    try {
        ProductionResponse response = produzioneService.richiestaProduzione(requestBody);
        return ResponseEntity.ok(response);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.badRequest().body(ProductionResponse.ko(requestBody, e.getMessage(), requestBody.getNun()));
    }
}

I want that the field issuerMunicipalityCode in the ProductionRequestResource is mandatory if issuerType is equal to "MIN".

Body:
To continue further, here is how you can implement custom validation.

Add a validation to throw an exception when issueType is MIN and municipality code is empty/null.

@RequestMapping(method = RequestMethod.POST, value = ProductionResponse.URL, produces = JWSMessageConverter.JWS_MEDIA_TYPE_VALUE)
@ResponseBody
public ResponseEntity<ProductionResponse> richiestaProduzione(@RequestParam("issuerType") String issuerType,
        @RequestParam("issuerCode") String issuerCode, @RequestParam("procedureId") String procedureId,
        @RequestBody ProductionRequestResource requestBody) {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("POST " + ProductionResponse.URL);

    if("MIN".equals(issuerType) && StringUtils.isEmpty(requestBody.getIssuerMunicipalityCode())) {
        throw new IllegalArgumentException("IssuerMuncipalityCode can't be null when IssuerType is MIN");
    }

    try {
        ProductionResponse response = produzioneService.richiestaProduzione(requestBody);
        return ResponseEntity.ok(response);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        return ResponseEntity.badRequest().body(ProductionResponse.ko(requestBody, e.getMessage(), requestBody.getNun()));
    }
}

Implement exception handler to catch the exceptions and build response body based on exception types. InvalidArgumentSuppliedException that was thrown above will be caught by below exception handler. Exception Handler is a best practice to handle exceptions in a separate component.

@ControllerAdvice
public class ScnSchedulerExceptionHandler {

    @ExceptionHandler(InvalidArgumentSuppliedException.class)
    public final ResponseEntity<Object> handleInvalidArgException(Exception ex) {
        ErrorResponseDTO errorDTO = new ErrorResponseDTO();
        errorDTO.setMessage(ex.getMessage());
        return new ResponseEntity<>(errorDTO, HttpStatus.NOT_ACCEPTABLE);
    }

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex) {
        ErrorResponseDTO errorDTO = new ErrorResponseDTO();
        errorDTO.setMessage("Internal server error occurred.");
        return new ResponseEntity<>(errorDTO, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

In the exception handler, wrap the error messages in a pojo object.

public class ErrorResponseDTO {

    private String errorMessage;

}