问:
Flink data type does not match when add time attributes by table source
I tried to add a table source with event time attribute according to flink doc. My codes like:

```<code>class SISSourceTable
    extends StreamTableSource[Row]
    with DefinedRowtimeAttributes
    with FlinkCal
    with FlinkTypeTags {
  private[this] val profileProp = ConfigurationManager.loadBusinessProperty
  val topic: String = ...
  val schemas = Seq(
    (TsCol, SQLTimestamp),
    (DCol, StringTag),
    (CCol, StringTag),
    (RCol, StringTag)
  )

  override def getProducedDataType: DataType = DataTypes.ROW(extractFields(schemas): _*)

  override def getTableSchema: TableSchema =
    new TableSchema.Builder()
      .fields(extractFieldNames(schemas), extractFieldDataTypes(schemas))
      .build()

  override def getRowtimeAttributeDescriptors: util.List[RowtimeAttributeDescriptor] =
    Collections.singletonList(
      new RowtimeAttributeDescriptor(
        TsCol,
        new ExistingField(TsCol),
        new AscendingTimestamps
      )
    )

  override def getDataStream(execEnv: StreamExecutionEnvironment): DataStream[Row] = {
    val windowTime: Int = profileProp.getProperty("xxx", "300").toInt
    val source = prepareSource(topic)
    val colsToCheck = List(RCol, CCol, DCol)

    execEnv
      .addSource(source)
      .map(new MapFunction[String, Map[String, String]]() {
        override def map(value: String): Map[String, String] = ...
      })
      .map(new MapFunction[Map[String, String], Row]() {
        override def map(value: Map[String, String]): Row = {
          Row.of(new Timestamp(value(TsCol).toLong * 1000), value(DCol), value(CCol), value(RCol))
        }
      })
      .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor[Row](Time.seconds(windowTime)) {
        override def extractTimestamp(element: Row): Long = element.getField(0).asInstanceOf[Timestamp].getTime
      })
  }
}
</code>```

The source I get in getDataStream method is a Kafka string source. And there's a TsCol which I extracted from each kafka record. I want to use the TsCol as event time. However the TsCol is a 10 digits timestamp with string data type, so I need to transform it to 13 digits Long data type. When I tried to use 13 digits Long data as rowtime, I got exception said rowtime can only be extract from a SQL_TIMESTAMP column. So I tranformed the ts col to a java.sql.Timestamp in the end. When I registered above Source Table and run the flink. I got following exception:

```<code>org.apache.flink.table.api.TableException: TableSource of type com.mob.mobeye.flink.table.source.StayInStoreSourceTable returned a DataStream of data type ROW<`t` TIMESTAMP(3), `mac` STRING, `c` STRING, `r` STRING> that does not match with the data type ROW<`t` TIMESTAMP(3), `mac` STRING, `c` STRING, `r` STRING> declared by the TableSource.getProducedDataType() method. Please validate the implementation of the TableSource.
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecTableSourceScan.translateToPlanInternal(StreamExecTableSourceScan.scala:113)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecTableSourceScan.translateToPlanInternal(StreamExecTableSourceScan.scala:55)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecTableSourceScan.translateToPlan(StreamExecTableSourceScan.scala:55)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecExchange.translateToPlanInternal(StreamExecExchange.scala:84)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecExchange.translateToPlanInternal(StreamExecExchange.scala:44)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecExchange.translateToPlan(StreamExecExchange.scala:44)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecGroupWindowAggregate.translateToPlanInternal(StreamExecGroupWindowAggregate.scala:140)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecGroupWindowAggregate.translateToPlanInternal(StreamExecGroupWindowAggregate.scala:55)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecGroupWindowAggregate.translateToPlan(StreamExecGroupWindowAggregate.scala:55)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:97)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlan(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:97)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlan(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToTransformation(StreamExecSink.scala:185)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToPlanInternal(StreamExecSink.scala:133)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToPlanInternal(StreamExecSink.scala:50)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToPlan(StreamExecSink.scala:50)
    at org.apache.flink.table.planner.delegation.StreamPlanner.$anonfun$translateToPlan$1(StreamPlanner.scala:61)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:233)
    at scala.collection.Iterator.foreach(Iterator.scala:937)
    at scala.collection.Iterator.foreach$(Iterator.scala:937)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
    at scala.collection.IterableLike.foreach(IterableLike.scala:70)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
    at scala.collection.TraversableLike.map(TraversableLike.scala:233)
    at scala.collection.TraversableLike.map$(TraversableLike.scala:226)
    at scala.collection.AbstractTraversable.map(Traversable.scala:104)
    at org.apache.flink.table.planner.delegation.StreamPlanner.translateToPlan(StreamPlanner.scala:60)
    at org.apache.flink.table.planner.delegation.PlannerBase.translate(PlannerBase.scala:149)
    at org.apache.flink.table.api.internal.TableEnvironmentImpl.translate(TableEnvironmentImpl.java:439)
    at org.apache.flink.table.api.internal.TableEnvironmentImpl.insertInto(TableEnvironmentImpl.java:327)
    at org.apache.flink.table.api.internal.TableImpl.insertInto(TableImpl.java:411)
</code>```

I'm so confused that why the

ROW<t TIMESTAMP(3), mac STRING, c STRING, r STRING>

does not match with the data type

ROW<t TIMESTAMP(3), mac STRING, c STRING, r STRING>

I got similar error in another place where I replaced TIMESTAMP as Long and it worked. But here, I need column t to be extracted as rowtime, so it has to be of type TIMESTAMP(3). I greatly appreciate that someone can help with the problem.

答:
What flink version are you using? If I am not mistaken you are using a version <1.9.2. Is that correct?

If it is so the exception message is not very helpful as it has a bug that was fixed in https://issues.apache.org/jira/browse/FLINK-15726. Before that actually the same type was printed twice.

There are a couple of problems with your implementation. The type mismatch is most probably because you produce a GenericTypeInformation returned by the map operator in

```<code>      .map(new MapFunction[Map[String, String], Row]() {
        override def map(value: Map[String, String]): Row = {
          Row.of(new Timestamp(value(TsCol).toLong * 1000), value(DCol), value(CCol), value(RCol))
        }
      })
</code>```

Try changing it to

```<code>      .map(new MapFunction[Map[String, String], Row]() {
        override def map(value: Map[String, String]): Row = {
          Row.of(new Timestamp(value(TsCol).toLong * 1000), value(DCol), value(CCol), value(RCol))
        }
      }).returns(Types.ROW(Types.SQL_TIMESTAMP, Types.STRING, Types.STRING, Types.STRING))
</code>```

Secondly you don't need to assign the timestamps and watermarks within the TableSource. They will be assigned automatically based on the information provided through DefinedRowtimeAttributes.

Body:
I tried to add a table source with event time attribute according to flink doc. My codes like:

class SISSourceTable
    extends StreamTableSource[Row]
    with DefinedRowtimeAttributes
    with FlinkCal
    with FlinkTypeTags {
  private[this] val profileProp = ConfigurationManager.loadBusinessProperty
  val topic: String = ...
  val schemas = Seq(
    (TsCol, SQLTimestamp),
    (DCol, StringTag),
    (CCol, StringTag),
    (RCol, StringTag)
  )

  override def getProducedDataType: DataType = DataTypes.ROW(extractFields(schemas): _*)

  override def getTableSchema: TableSchema =
    new TableSchema.Builder()
      .fields(extractFieldNames(schemas), extractFieldDataTypes(schemas))
      .build()

  override def getRowtimeAttributeDescriptors: util.List[RowtimeAttributeDescriptor] =
    Collections.singletonList(
      new RowtimeAttributeDescriptor(
        TsCol,
        new ExistingField(TsCol),
        new AscendingTimestamps
      )
    )

  override def getDataStream(execEnv: StreamExecutionEnvironment): DataStream[Row] = {
    val windowTime: Int = profileProp.getProperty("xxx", "300").toInt
    val source = prepareSource(topic)
    val colsToCheck = List(RCol, CCol, DCol)

    execEnv
      .addSource(source)
      .map(new MapFunction[String, Map[String, String]]() {
        override def map(value: String): Map[String, String] = ...
      })
      .map(new MapFunction[Map[String, String], Row]() {
        override def map(value: Map[String, String]): Row = {
          Row.of(new Timestamp(value(TsCol).toLong * 1000), value(DCol), value(CCol), value(RCol))
        }
      })
      .assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor[Row](Time.seconds(windowTime)) {
        override def extractTimestamp(element: Row): Long = element.getField(0).asInstanceOf[Timestamp].getTime
      })
  }
}

The source I get in getDataStream method is a Kafka string source. And there's a TsCol which I extracted from each kafka record. I want to use the TsCol as event time. However the TsCol is a 10 digits timestamp with string data type, so I need to transform it to 13 digits Long data type. When I tried to use 13 digits Long data as rowtime, I got exception said rowtime can only be extract from a SQL_TIMESTAMP column. So I tranformed the ts col to a java.sql.Timestamp in the end. When I registered above Source Table and run the flink. I got following exception:

org.apache.flink.table.api.TableException: TableSource of type com.mob.mobeye.flink.table.source.StayInStoreSourceTable returned a DataStream of data type ROW<`t` TIMESTAMP(3), `mac` STRING, `c` STRING, `r` STRING> that does not match with the data type ROW<`t` TIMESTAMP(3), `mac` STRING, `c` STRING, `r` STRING> declared by the TableSource.getProducedDataType() method. Please validate the implementation of the TableSource.
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecTableSourceScan.translateToPlanInternal(StreamExecTableSourceScan.scala:113)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecTableSourceScan.translateToPlanInternal(StreamExecTableSourceScan.scala:55)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecTableSourceScan.translateToPlan(StreamExecTableSourceScan.scala:55)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecExchange.translateToPlanInternal(StreamExecExchange.scala:84)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecExchange.translateToPlanInternal(StreamExecExchange.scala:44)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecExchange.translateToPlan(StreamExecExchange.scala:44)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecGroupWindowAggregate.translateToPlanInternal(StreamExecGroupWindowAggregate.scala:140)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecGroupWindowAggregate.translateToPlanInternal(StreamExecGroupWindowAggregate.scala:55)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecGroupWindowAggregate.translateToPlan(StreamExecGroupWindowAggregate.scala:55)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:97)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlan(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:97)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlanInternal(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecLookupJoin.translateToPlan(StreamExecLookupJoin.scala:40)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:86)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlanInternal(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecCalc.translateToPlan(StreamExecCalc.scala:46)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToTransformation(StreamExecSink.scala:185)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToPlanInternal(StreamExecSink.scala:133)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToPlanInternal(StreamExecSink.scala:50)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan(ExecNode.scala:54)
    at org.apache.flink.table.planner.plan.nodes.exec.ExecNode.translateToPlan$(ExecNode.scala:52)
    at org.apache.flink.table.planner.plan.nodes.physical.stream.StreamExecSink.translateToPlan(StreamExecSink.scala:50)
    at org.apache.flink.table.planner.delegation.StreamPlanner.$anonfun$translateToPlan$1(StreamPlanner.scala:61)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:233)
    at scala.collection.Iterator.foreach(Iterator.scala:937)
    at scala.collection.Iterator.foreach$(Iterator.scala:937)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1425)
    at scala.collection.IterableLike.foreach(IterableLike.scala:70)
    at scala.collection.IterableLike.foreach$(IterableLike.scala:69)
    at scala.collection.AbstractIterable.foreach(Iterable.scala:54)
    at scala.collection.TraversableLike.map(TraversableLike.scala:233)
    at scala.collection.TraversableLike.map$(TraversableLike.scala:226)
    at scala.collection.AbstractTraversable.map(Traversable.scala:104)
    at org.apache.flink.table.planner.delegation.StreamPlanner.translateToPlan(StreamPlanner.scala:60)
    at org.apache.flink.table.planner.delegation.PlannerBase.translate(PlannerBase.scala:149)
    at org.apache.flink.table.api.internal.TableEnvironmentImpl.translate(TableEnvironmentImpl.java:439)
    at org.apache.flink.table.api.internal.TableEnvironmentImpl.insertInto(TableEnvironmentImpl.java:327)
    at org.apache.flink.table.api.internal.TableImpl.insertInto(TableImpl.java:411)

I'm so confused that why the

ROW<t TIMESTAMP(3), mac STRING, c STRING, r STRING>

does not match with the data type

ROW<t TIMESTAMP(3), mac STRING, c STRING, r STRING>

I got similar error in another place where I replaced TIMESTAMP as Long and it worked. But here, I need column t to be extracted as rowtime, so it has to be of type TIMESTAMP(3). I greatly appreciate that someone can help with the problem.

Body:
What flink version are you using? If I am not mistaken you are using a version <1.9.2. Is that correct?

If it is so the exception message is not very helpful as it has a bug that was fixed in https://issues.apache.org/jira/browse/FLINK-15726. Before that actually the same type was printed twice.

There are a couple of problems with your implementation. The type mismatch is most probably because you produce a GenericTypeInformation returned by the map operator in

      .map(new MapFunction[Map[String, String], Row]() {
        override def map(value: Map[String, String]): Row = {
          Row.of(new Timestamp(value(TsCol).toLong * 1000), value(DCol), value(CCol), value(RCol))
        }
      })

Try changing it to

      .map(new MapFunction[Map[String, String], Row]() {
        override def map(value: Map[String, String]): Row = {
          Row.of(new Timestamp(value(TsCol).toLong * 1000), value(DCol), value(CCol), value(RCol))
        }
      }).returns(Types.ROW(Types.SQL_TIMESTAMP, Types.STRING, Types.STRING, Types.STRING))

Secondly you don't need to assign the timestamps and watermarks within the TableSource. They will be assigned automatically based on the information provided through DefinedRowtimeAttributes.


来源: stackexchange

问:
Skipping NA rows in index column
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3
</code>```

At the moment I'm doing it as:

```<code>i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)
</code>```

but that gives me

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5
</code>```

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

答:
No need for looping or iterating:

```<code>df$ID <- ifelse(df$VarA == TRUE, TRUE, NA)
</code>```

Should give you the desired result.

Or, maybe I missunderstood and you want to remove rows with NA in VarA:

```<code>df[!is.na(df$VarA), ]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Skipping NA rows in index column

Body:
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3

At the moment I'm doing it as:

i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)

but that gives me

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

Body:
No need for looping or iterating:

df$ID <- ifelse(df$VarA == TRUE, TRUE, NA)

Should give you the desired result.

Or, maybe I missunderstood and you want to remove rows with NA in VarA:

df[!is.na(df$VarA), ]


问:
How to call an async function synchronized without blocking the main thread?
I wrote a simple console application to test ConfigureAwait(false) for fixing the problem of calling an async function in a synchronized way. This is how I simulate an event and trying to call an async function in a sync way.

 public static class Test2
    {
        private static EventHandler<int> _somethingEvent;

        public static void Run()
        {
            _somethingEvent += OnSomething;
            _somethingEvent(null, 10);
            Console.WriteLine("fetch some other resources");
            Console.ReadLine();
        }

        private static void OnSomething(object sender, int e)
        {
            Console.WriteLine($"passed value : {e}");
            FakeAsync().Wait();
        }

        private static async Task FakeAsync()
        {
            await Task.Delay(2000).ConfigureAwait(false);
            Console.WriteLine($"task completed");
        }
    }
```

<p>the output of the code is like this:</p>

<pre class="lang-sh prettyprint-override"><code>passed value : 10
task completed
fetch some other resources
</code>```

And when I change the OnSomething function to async void like this:

private static async void OnSomething(object sender, int e)
{
    Console.WriteLine($"passed value : {e}");
    await FakeAsync();
}
```

<p>The output will change to this:</p>

<pre class="lang-sh prettyprint-override"><code>passed value : 10
fetch some other resources
task completed
</code>```

You can see fetch some other resources is occurred before task completed section and this is my desired result.

My question is how can I achieve the same result by calling the async function synchronized like the first signature  I wrote for the OnSomething function?

How could I use ConfigureAwait(false) to help me in this situation? Or maybe I am not using it properly.

答:
I wrote a simple console application to test ConfigureAwait(false) for fixing the problem of calling an async function in a synchronized way.

There's a couple of problems with this.

ConfigureAwait(false) is not a "fix" for the "problem" of calling an asynchronous function synchronously. It is one possible hack that works in some situations, but it's not generally recommended because you have to use ConfigureAwait(false) everywhere in the entire transitive closure of that function - including second- and third-party calls - and if you just miss one, there is still the possibility of a deadlock. The best solution for the problem of calling an asynchronous function from a synchronous function is to change the calling function to be asynchronous (go "async all the way"). Sometimes this isn't possible and you need a hack, but there is no hack that works in every scenario.

The deadlock issue you're trying to avoid has two ingredients: blocking a thread on a task, and a single-threaded context. Console applications do not have a single-threaded context, so in a Console application it's as though all your code uses ConfigureAwait(false) everywhere.

My question is how can I achieve the same result by calling the async function synchronized like the first signature I wrote for the OnSomething function?

The calling code will either block on the asynchronous code (e.g., Wait), or it will not (e.g., await). You can't block on the asynchronous code and continue executing. The calling thread must either continue executing or block; it can't do both.

Body:
I wrote a simple console application to test ConfigureAwait(false) for fixing the problem of calling an async function in a synchronized way. This is how I simulate an event and trying to call an async function in a sync way.

 public static class Test2
    {
        private static EventHandler<int> _somethingEvent;

        public static void Run()
        {
            _somethingEvent += OnSomething;
            _somethingEvent(null, 10);
            Console.WriteLine("fetch some other resources");
            Console.ReadLine();
        }

        private static void OnSomething(object sender, int e)
        {
            Console.WriteLine($"passed value : {e}");
            FakeAsync().Wait();
        }

        private static async Task FakeAsync()
        {
            await Task.Delay(2000).ConfigureAwait(false);
            Console.WriteLine($"task completed");
        }
    }

the output of the code is like this:

passed value : 10
task completed
fetch some other resources

And when I change the OnSomething function to async void like this:

private static async void OnSomething(object sender, int e)
{
    Console.WriteLine($"passed value : {e}");
    await FakeAsync();
}

The output will change to this:

passed value : 10
fetch some other resources
task completed

You can see fetch some other resources is occurred before task completed section and this is my desired result.

My question is how can I achieve the same result by calling the async function synchronized like the first signature  I wrote for the OnSomething function?

How could I use ConfigureAwait(false) to help me in this situation? Or maybe I am not using it properly.


问:
Data preparation for association rules algorithm (apriori)
I need help with my data preparation for a project I am working on.
I have 2 columns csv file, one contains the Order number, the second contains the items purchased.

Here's a sample of what I have:

```<code>1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K
</code>```

I need to transform it to:

```<code>1 A B C
2 A D
3 F G K
</code>```

(this is just a sample I made.. I have 70k rows)
Any help would be amazing. SQL / Python / excel are the tools I know how to work with. So if it possible, the answer within one of them would be the best.
Thanks!

答: You can use ROW_NUMBER () OVER (PARTITION BY NUMBER ORDER BY LETTER) (inner query), then using sub queries you can select the letters as columns.

Body:
I need help with my data preparation for a project I am working on.
I have 2 columns csv file, one contains the Order number, the second contains the items purchased.

Here's a sample of what I have:

1 A
1 B
1 C
2 A
2 D
3 F
3 G
3 K

I need to transform it to:

1 A B C
2 A D
3 F G K

(this is just a sample I made.. I have 70k rows)
Any help would be amazing. SQL / Python / excel are the tools I know how to work with. So if it possible, the answer within one of them would be the best.
Thanks!


问:
Element height and width change detection in Angular 2
I was looking for a solution, but nothing found (only articles about (window:resize), but it is not I am looking for).

How to detect element size change in Angular 2?

```<code><div #myElement (sizeChanged)="callback()" />
</code>```

I want to use some CSS animations and detect element's height and width changes.

答:
For angular users,
     You can easily apply this code....

Html

```<code><div (resized)="onResized($event)"></div>
</code>```

Angular

```<code>import { Component } from '@angular/core';

// Import the resized event model
import { ResizedEvent } from 'angular-resize-event';

@Component({...})
class MyComponent {
  width: number;
  height: number;

  onResized(event: ResizedEvent) {
    this.width = event.newWidth;
    this.height = event.newHeight;
  }
}
</code>```

Remember you have to install node module and import it to your app.module.ts file.

Check this link for more:
    https://www.npmjs.com/package/angular-resize-event

ContentLicense: CC BY-SA 3.0

Body:
I was looking for a solution, but nothing found (only articles about (window:resize), but it is not I am looking for).

How to detect element size change in Angular 2?

I want to use some CSS animations and detect element's height and width changes.

Body:
For angular users,
     You can easily apply this code....

Html

<div (resized)="onResized($event)"></div>

Angular

import { Component } from '@angular/core';

// Import the resized event model
import { ResizedEvent } from 'angular-resize-event';

@Component({...})
class MyComponent {
  width: number;
  height: number;

  onResized(event: ResizedEvent) {
    this.width = event.newWidth;
    this.height = event.newHeight;
  }
}

Remember you have to install node module and import it to your app.module.ts file.

Check this link for more:
    https://www.npmjs.com/package/angular-resize-event


问:
No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator
I am trying to consume an API using Retrofit and Jackson to deserialize. I am getting the onFailure error No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator.

答:
I had a similar issue (using Jackson, lombok, gradle) and a POJO without no args constructor - the solution was to add

```<code>lombok.anyConstructor.addConstructorProperties=true
</code>```

to the lombok.config file

Body:
I had a similar issue (using Jackson, lombok, gradle) and a POJO without no args constructor - the solution was to add

lombok.anyConstructor.addConstructorProperties=true

to the lombok.config file


问:
Cannot export component from module even if imported and declared Angular 8
I am working on an app where I have a SharedUiModule containing all the components (and services) that will be used in other parts of the app.

Now I want to export from the SharedUiModule my ModalComponent (renamed PopupComponent) so I can reuse it in other modules by importing the SharedUiModule.

Problem is, in SharedUiModule, even after importing the PopupComponent and declaring it, when I want to export it I have the following alert : "Cannot export PopupComponent from SharedUiModule as it is neither declared nor imported in it". Spent few hours searching on the internet but couldn't find any similar issue.

My IDE is Intellij. Here is what my SharedUiModule looks like :

```<code>import {CommonModule} from '@angular/common';
import {MatDialogModule, MatFormFieldModule, MatIconModule, MatListModule} from "@angular/material";
import {PopupComponent} from "./popup/popup.component";

@NgModule({
  imports: [
    CommonModule,
    MatListModule,
    MatIconModule,
    MatFormFieldModule,
    MatDialogModule,
  ],
  declarations: [
    PopupComponent
  ],
  exports: [
    PopupComponent <= "Cannot export PopupComponent from SharedUiModule as it is neither declared nor imported in it"
  ],
  entryComponents: [PopupComponent]
})
export class SharedUiModule {}
</code>```

答:
A work mate told me to try to export the component the same way I imported the component and it works ! Now I don't understand why this way works while the exports properties should do the job (my work mate doesn't have any explanation too)</p>

```<code>import {PopupComponent} from "./popup/popup.component";
export {PopupComponent};
</code>```

Body:
I am working on an app where I have a SharedUiModule containing all the components (and services) that will be used in other parts of the app.

Now I want to export from the SharedUiModule my ModalComponent (renamed PopupComponent) so I can reuse it in other modules by importing the SharedUiModule.

Problem is, in SharedUiModule, even after importing the PopupComponent and declaring it, when I want to export it I have the following alert : "Cannot export PopupComponent from SharedUiModule as it is neither declared nor imported in it". Spent few hours searching on the internet but couldn't find any similar issue.

My IDE is Intellij. Here is what my SharedUiModule looks like :

import {CommonModule} from '@angular/common';
import {MatDialogModule, MatFormFieldModule, MatIconModule, MatListModule} from "@angular/material";
import {PopupComponent} from "./popup/popup.component";

@NgModule({
  imports: [
    CommonModule,
    MatListModule,
    MatIconModule,
    MatFormFieldModule,
    MatDialogModule,
  ],
  declarations: [
    PopupComponent
  ],
  exports: [
    PopupComponent <= "Cannot export PopupComponent from SharedUiModule as it is neither declared nor imported in it"
  ],
  entryComponents: [PopupComponent]
})
export class SharedUiModule {}

Body:
A work mate told me to try to export the component the same way I imported the component and it works ! Now I don't understand why this way works while the exports properties should do the job (my work mate doesn't have any explanation too)

import {PopupComponent} from "./popup/popup.component";
export {PopupComponent};


问:
PostgreSQL parallel queries using SPI possible?
I am using PostgreSQL's Server Programming Interface (SPI) to build my postgres extension and execute my query. Please see this detailed example, or the following simple code sample:

```<code>int ret = SPI_exec("SELECT * FROM ....", 0);
</code>```

We know that PostgreSQL has parallel query support feature, where a query is executed in parallel using multiple processors. Since the SPI interface hides quite some complexity (communication/locks/cursors/etc), I was wondering whether executing a query in this way limits this parallel query feature in some way or not? Obviously, if it does indeed pose a limit, then maybe it is not worth making use of.

答:
The specific usage in your example does not inhibit parallelism, as can be seen by running SELECT execq('select count(*) from pgbench_accounts', 0); and observing the plan via auto_explain.  (I had run pgbench -i -s20, so there 2e6 rows).

Other SPI method, like those involving cursors, will inhibit parallelization.

Body:
I am using PostgreSQL's Server Programming Interface (SPI) to build my postgres extension and execute my query. Please see this detailed example, or the following simple code sample:

int ret = SPI_exec("SELECT * FROM ....", 0);

We know that PostgreSQL has parallel query support feature, where a query is executed in parallel using multiple processors. Since the SPI interface hides quite some complexity (communication/locks/cursors/etc), I was wondering whether executing a query in this way limits this parallel query feature in some way or not? Obviously, if it does indeed pose a limit, then maybe it is not worth making use of.


问:
java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment
I am trying to move from one fragment to another.. It shows following error during fragment transaction-

```<code>    java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2{41a57218 #3 id=0x1020002}
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)
</code>```

Below are the classes.I have used following code for fragment transaction

```<code>Fragment fragment = new PhotosFragment2();

                        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                        fragmentTransaction.replace(android.R.id.content, fragment);
                        fragmentTransaction.commit();
</code>```

PhotosFragment.java

```<code>   public class PhotosFragment extends Fragment {
        private FragmentActivity myContext;
        @Override
        public void onAttach(Activity activity) {
            myContext = (FragmentActivity) activity;
            super.onAttach(activity);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.photos, container, false);

            rootView.setVerticalScrollBarEnabled(false);
            int[] mThumbIds = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4, R.drawable.album8,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album12, R.drawable.album10,
            };

            int[] mThumbIds2 = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
            };

            CustomGridSingle2 adapter = new CustomGridSingle2(myContext, mThumbIds);
            GridView grid = (GridView)rootView.findViewById(R.id.gridView);
            final ImageView img= (ImageView)rootView.findViewById(R.id.imageView7);
            grid.setFocusable(false);

            grid.setAdapter(adapter);
    grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fragment fragment = new PhotosFragment2();

            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(android.R.id.content, fragment);
            fragmentTransaction.commit();
        }
    });
            CustomGridSingle2 adapter2 = new CustomGridSingle2(myContext, mThumbIds2);
            GridView grid2 = (GridView)rootView.findViewById(R.id.gridView2);
            grid2.setFocusable(false);
            grid2.setAdapter(adapter2);
            grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Fragment fragment = new PhotosFragment2();

                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(android.R.id.content, fragment);
                    fragmentTransaction.commit();
                }
            });

            return rootView;
        }

    }
</code>```

PhotosFragment2.java

```<code>public class PhotosFragment2 extends Fragment {
    private FragmentActivity myContext;
    @Override
    public void onAttach(Activity activity) {
        myContext = (FragmentActivity) activity;
        super.onAttach(activity);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.photos2, container, false);
        myContext.getActionBar().hide();
        return rootView;
    }
}
</code>```

Activity xml file

```<code><android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/left_drawer_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bgmenu"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/profilelayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:paddingTop="10dp">

            <ImageView
                android:id="@+id/drawer_profile_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_alignLeft="@+id/drawer_profile_background"
                android:layout_alignRight="@+id/drawer_profile_background"
                android:layout_alignTop="@+id/drawer_profile_background"
                android:layout_marginBottom="7.667dp"
                android:layout_marginLeft="6.5dp"
                android:layout_marginRight="8.3dp"
                android:layout_marginTop="7.667dp"
                android:scaleType="centerCrop"></ImageView>

            <ImageView
                android:id="@+id/drawer_profile_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:scaleType="centerCrop"
                android:src="@drawable/profileblock">

            </ImageView>

            <ImageView
                android:id="@+id/settingicon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_marginLeft="-15dp"
                android:layout_toRightOf="@+id/drawer_profile_background"
                android:background="@drawable/settings" />

            <textview
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/drawer_profile_background"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="5dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceListItemSmall"
                android:textColor="@android:color/white" />

        </RelativeLayout>

        <ListView
            android:id="@+id/list_slidermenu"
            style="@style/buttonStyle"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="30dp"
            android:layout_weight="2"
            android:cacheColorHint="@android:color/transparent"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="1dp"
            android:listSelector="@android:color/transparent"
            android:scrollbars="none" />

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>
</code>```

答: Make sure the fragment id you are calling is in the class listed in setcontent in onCreate method. For my case, I was editing the layout from linear to constraint. So as not to mess with the working code, I made another layout but messed an id in the process so that what was on oncreate was the edited layout but the fragment being called was from the old layout. Apparently, in the new layout I gave it a different id name. Search the id of your fragment using ctrl+shift+f and see if the search results point to the layout you specified in the oncreate method. Goodluck.</p>

Body:
I am trying to move from one fragment to another.. It shows following error during fragment transaction-

    java.lang.IllegalArgumentException: No view found for id 0x1020002 (android:id/content) for fragment PhotosFragment2{41a57218 #3 id=0x1020002}
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:153)
            at android.app.ActivityThread.main(ActivityThread.java:5086)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
            at dalvik.system.NativeStart.main(Native Method)

Below are the classes.I have used following code for fragment transaction

Fragment fragment = new PhotosFragment2();

                        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                        fragmentTransaction.replace(android.R.id.content, fragment);
                        fragmentTransaction.commit();

PhotosFragment.java

   public class PhotosFragment extends Fragment {
        private FragmentActivity myContext;
        @Override
        public void onAttach(Activity activity) {
            myContext = (FragmentActivity) activity;
            super.onAttach(activity);
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.photos, container, false);

            rootView.setVerticalScrollBarEnabled(false);
            int[] mThumbIds = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4, R.drawable.album8,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album12, R.drawable.album10,
            };

            int[] mThumbIds2 = {
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
                    R.drawable.album8, R.drawable.album3,
                    R.drawable.album4,
                    R.drawable.album6, R.drawable.album7,
                    R.drawable.album9, R.drawable.album10,
                    R.drawable.album11, R.drawable.album12, R.drawable.album8,
            };

            CustomGridSingle2 adapter = new CustomGridSingle2(myContext, mThumbIds);
            GridView grid = (GridView)rootView.findViewById(R.id.gridView);
            final ImageView img= (ImageView)rootView.findViewById(R.id.imageView7);
            grid.setFocusable(false);

            grid.setAdapter(adapter);
    grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Fragment fragment = new PhotosFragment2();

            FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
            fragmentTransaction.replace(android.R.id.content, fragment);
            fragmentTransaction.commit();
        }
    });
            CustomGridSingle2 adapter2 = new CustomGridSingle2(myContext, mThumbIds2);
            GridView grid2 = (GridView)rootView.findViewById(R.id.gridView2);
            grid2.setFocusable(false);
            grid2.setAdapter(adapter2);
            grid2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Fragment fragment = new PhotosFragment2();

                    FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                    fragmentTransaction.replace(android.R.id.content, fragment);
                    fragmentTransaction.commit();
                }
            });

            return rootView;
        }

    }

PhotosFragment2.java

public class PhotosFragment2 extends Fragment {
    private FragmentActivity myContext;
    @Override
    public void onAttach(Activity activity) {
        myContext = (FragmentActivity) activity;
        super.onAttach(activity);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View rootView = inflater.inflate(R.layout.photos2, container, false);
        myContext.getActionBar().hide();
        return rootView;
    }
}

Activity xml file

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:id="@+id/left_drawer_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/bgmenu"
        android:orientation="vertical">

        <RelativeLayout
            android:id="@+id/profilelayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"
            android:paddingTop="10dp">

            <ImageView
                android:id="@+id/drawer_profile_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_alignLeft="@+id/drawer_profile_background"
                android:layout_alignRight="@+id/drawer_profile_background"
                android:layout_alignTop="@+id/drawer_profile_background"
                android:layout_marginBottom="7.667dp"
                android:layout_marginLeft="6.5dp"
                android:layout_marginRight="8.3dp"
                android:layout_marginTop="7.667dp"
                android:scaleType="centerCrop"></ImageView>

            <ImageView
                android:id="@+id/drawer_profile_background"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:scaleType="centerCrop"
                android:src="@drawable/profileblock">

            </ImageView>

            <ImageView
                android:id="@+id/settingicon"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/drawer_profile_background"
                android:layout_marginLeft="-15dp"
                android:layout_toRightOf="@+id/drawer_profile_background"
                android:background="@drawable/settings" />

            <textview
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/drawer_profile_background"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="5dp"
                android:text="Name"
                android:textAppearance="?android:attr/textAppearanceListItemSmall"
                android:textColor="@android:color/white" />

        </RelativeLayout>

        <ListView
            android:id="@+id/list_slidermenu"
            style="@style/buttonStyle"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_marginTop="30dp"
            android:layout_weight="2"
            android:cacheColorHint="@android:color/transparent"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="1dp"
            android:listSelector="@android:color/transparent"
            android:scrollbars="none" />

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>


问:
Set background of preference according to the position
I am developing an app where I am using Preference (androidx.preference.Preference).
I am using PreferenceCategory and adding Preerence to it at runtime.

My requirement is that the first, middle and last preferences in PreferenceCategory should have different backgrounds and layouts. I am using following code for this :

```<code>public static class SettingsFragment extends PreferenceFragmentCompat {
    Activity activity = null;
    String TAG = "SettingsFragment";
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (Activity) getActivity();
    }

    @Override
    public void onResume() {
        super.onResume();
        PreferenceCategory category = findPreference("MyPreference");
        category.setLayoutResource(R.layout.preference_group_layout);
        MyAdapter myAdapter = new MyAdapter(category);
        for(int i=0;i<10;i++) {
            Preference preference = new Preference(activity);
            preference.setKey("P" + i);
            preference.setLayoutResource(R.layout.preference_layout);
            category.addPreference(preference);
            Log.d(TAG,"" + category.getPreferenceCount());
            myAdapter.notifyDataSetChanged();
        }

    }
}

class MyAdapter extends PreferenceGroupAdapter {
    String TAG = "MyAdapter";
    public MyAdapter(PreferenceGroup preferenceGroup) {
        super(preferenceGroup);
    }

    @Override
    public int getItemCount() {
        return super.getItemCount();
    }

    @Override
    public Preference getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @NonNull
    @Override
    public PreferenceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.d(TAG,"onCreateViewHolder called");
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull PreferenceViewHolder holder, int position) {
        Log.d(TAG,"onBindViewHolder called");
        super.onBindViewHolder(holder, position);
    }
}
</code>```

But This is not showing my Prefrence in layout. I searched on internet about this but I didn't find any similar example. How can I add Preference and set their layout according to their positions.

答:
PreferenceGroupAdapter object has the preference data but adapter is not linked with the fragment means, adapter is not being used so do this via overriding onCreateAdapter in your PreferenceFragmentCompat and return your adapter object as:

```<code>public class SettingsFragment extends PreferenceFragmentCompat {
    Activity activity = null;
    String TAG = "SettingsFragment";

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = getActivity();
    }

    // Add this with modified logic
    @Override
    protected RecyclerView.Adapter onCreateAdapter(PreferenceScreen preferenceScreen) {
        PreferenceCategory category = findPreference("MyPreference");
        category.setLayoutResource(R.layout.preference_group_layout);
        MyAdapter myAdapter = new MyAdapter(category);
        final int tot = 10;
        final int middle = tot / 2;
        for (int i = 1; i <= tot; i++) {
            Preference preference = new Preference(activity);
            preference.setKey("P" + i);
            int layout = R.layout.preference_layout;
            switch (i) {
                case 1:
                    layout = R.layout.preference_layout_first;
                    break;
                case middle:
                    layout = R.layout.preference_layout_middle;
                    break;
                case tot: // last
                    layout = R.layout.preference_layout_last;
                    break;
            }
            preference.setLayoutResource(layout);
            category.addPreference(preference);
            Log.d(TAG, "" + category.getPreferenceCount());
            myAdapter.notifyDataSetChanged();
        }
        return myAdapter;
    }
}
</code>```

Body:
I am developing an app where I am using Preference (androidx.preference.Preference).
I am using PreferenceCategory and adding Preerence to it at runtime.

My requirement is that the first, middle and last preferences in PreferenceCategory should have different backgrounds and layouts. I am using following code for this :

public static class SettingsFragment extends PreferenceFragmentCompat {
    Activity activity = null;
    String TAG = "SettingsFragment";
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = (Activity) getActivity();
    }

    @Override
    public void onResume() {
        super.onResume();
        PreferenceCategory category = findPreference("MyPreference");
        category.setLayoutResource(R.layout.preference_group_layout);
        MyAdapter myAdapter = new MyAdapter(category);
        for(int i=0;i<10;i++) {
            Preference preference = new Preference(activity);
            preference.setKey("P" + i);
            preference.setLayoutResource(R.layout.preference_layout);
            category.addPreference(preference);
            Log.d(TAG,"" + category.getPreferenceCount());
            myAdapter.notifyDataSetChanged();
        }

    }
}

class MyAdapter extends PreferenceGroupAdapter {
    String TAG = "MyAdapter";
    public MyAdapter(PreferenceGroup preferenceGroup) {
        super(preferenceGroup);
    }

    @Override
    public int getItemCount() {
        return super.getItemCount();
    }

    @Override
    public Preference getItem(int position) {
        return super.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    @NonNull
    @Override
    public PreferenceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        Log.d(TAG,"onCreateViewHolder called");
        return super.onCreateViewHolder(parent, viewType);
    }

    @Override
    public void onBindViewHolder(@NonNull PreferenceViewHolder holder, int position) {
        Log.d(TAG,"onBindViewHolder called");
        super.onBindViewHolder(holder, position);
    }
}

But This is not showing my Prefrence in layout. I searched on internet about this but I didn't find any similar example. How can I add Preference and set their layout according to their positions.

Body:
PreferenceGroupAdapter object has the preference data but adapter is not linked with the fragment means, adapter is not being used so do this via overriding onCreateAdapter in your PreferenceFragmentCompat and return your adapter object as:

public class SettingsFragment extends PreferenceFragmentCompat {
    Activity activity = null;
    String TAG = "SettingsFragment";

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity = getActivity();
    }

    // Add this with modified logic
    @Override
    protected RecyclerView.Adapter onCreateAdapter(PreferenceScreen preferenceScreen) {
        PreferenceCategory category = findPreference("MyPreference");
        category.setLayoutResource(R.layout.preference_group_layout);
        MyAdapter myAdapter = new MyAdapter(category);
        final int tot = 10;
        final int middle = tot / 2;
        for (int i = 1; i <= tot; i++) {
            Preference preference = new Preference(activity);
            preference.setKey("P" + i);
            int layout = R.layout.preference_layout;
            switch (i) {
                case 1:
                    layout = R.layout.preference_layout_first;
                    break;
                case middle:
                    layout = R.layout.preference_layout_middle;
                    break;
                case tot: // last
                    layout = R.layout.preference_layout_last;
                    break;
            }
            preference.setLayoutResource(layout);
            category.addPreference(preference);
            Log.d(TAG, "" + category.getPreferenceCount());
            myAdapter.notifyDataSetChanged();
        }
        return myAdapter;
    }
}


问:
how to fix the error "error creating bean with name...."
when I run my application there is the following error displayed:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pamdaBatchConfigurer': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getJobRepository' defined in com.orange.pamda.config.PamdaBatchConfigurer: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.repository.JobRepository]: Circular reference involving containing bean 'pamdaBatchConfigurer' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getJobRepository' threw exception; nested exception is java.lang.IllegalArgumentException: DatabaseType not found for product name: [MariaDB]
      at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
      at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
      at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
      at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
      at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4685)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5146)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
      at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
      at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
      at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
      at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
      at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
      at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:343)
      at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474)

here is my file "pamdabatchconfigurer.java":

```<code>    package com.orange.pamda.config;

import java.util.Date;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;

import com.orange.pamda.config.batch.listener.SendFileAfterExportListener;
import com.orange.pamda.worker.config.CatalogueExporterJobConfiguration;
import com.orange.pamda.worker.config.CatalogueImporterJobConfiguration;
import com.orange.pamda.worker.config.CommonJobConfiguration;
import com.orange.pamda.worker.config.DataExporterJobConfiguration;
import com.orange.pamda.worker.config.HierarchyValidatorJobConfiguration;
import com.orange.pamda.worker.config.JobBuilderFactory;
import com.orange.pamda.worker.config.KoalaExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingImporterJobConfiguration;
import com.orange.pamda.worker.config.OrphanExporterJobConfiguration;
import com.orange.pamda.worker.config.ReleaseJobConfiguration;
import com.orange.pamda.worker.config.SummaryExporterJobConfiguration;

@Configuration
@EnableBatchProcessing(modular = true)
@Import({ CommonJobConfiguration.class, CatalogueExporterJobConfiguration.class,
        CatalogueImporterJobConfiguration.class, DataExporterJobConfiguration.class,
        HierarchyValidatorJobConfiguration.class, KoalaExporterJobConfiguration.class,
        MappingExporterJobConfiguration.class, MappingImporterJobConfiguration.class,
        OrphanExporterJobConfiguration.class, ReleaseJobConfiguration.class, SummaryExporterJobConfiguration.class })
public class PamdaBatchConfigurer implements BatchConfigurer {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private DataSource dataSource;

    @Override
    @Bean
    public JobRepository getJobRepository() throws Exception {
        JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
        jobRepositoryFactoryBean.setDataSource(dataSource);
        jobRepositoryFactoryBean.setTransactionManager(transactionManager);
        jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_DEFAULT");
        jobRepositoryFactoryBean.afterPropertiesSet();
        return jobRepositoryFactoryBean.getObject();
    }

    @Override
    public PlatformTransactionManager getTransactionManager() throws Exception {
        return transactionManager;
    }

    @Override
    @Bean
    public JobLauncher getJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(getJobRepository());
        // jobLauncher.setTaskExecutor(getTaskExecutor());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    @Override
    @Bean
    public JobExplorer getJobExplorer() throws Exception {
        JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
        jobExplorerFactoryBean.setDataSource(dataSource);
        jobExplorerFactoryBean.afterPropertiesSet();
        return jobExplorerFactoryBean.getObject();
    }

    // @Bean
    // public TaskExecutor getTaskExecutor() {
    // SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new
    // SimpleAsyncTaskExecutor();
    // simpleAsyncTaskExecutor.setConcurrencyLimit(1000); // no throttle
    // return simpleAsyncTaskExecutor;
    // }

    @Bean
    public JobBuilderFactory getJobBuilderFactory() throws Exception {
        return new JobBuilderFactory(getJobRepository(), sendFileAfterExportListener());
    }

    @Bean
    public StepBuilderFactory getStepBuilderFactory() throws Exception {
        return new StepBuilderFactory(getJobRepository(), transactionManager);
    }

    @Bean
    public SendFileAfterExportListener sendFileAfterExportListener() {
        return new SendFileAfterExportListener();
    }

    @PostConstruct
    @Transactional
    public void init() throws Exception {
        JobExplorer jobExplorer = getJobExplorer();
        JobRepository jobRepository = getJobRepository();
        for (String jobName : jobExplorer.getJobNames()) {
            Set<JobExecution> runningJobExecutions = jobExplorer.findRunningJobExecutions(jobName);
            for (JobExecution runningJobExecution : runningJobExecutions) {
                runningJobExecution.setExitStatus(ExitStatus.UNKNOWN);
                runningJobExecution.setEndTime(new Date());
                jobRepository.update(runningJobExecution);
            }
        }
    }

}
</code>```

I really do not know where this error comes from can someone help me please?

答:
Most important part of the stacktrace: DatabaseType not found for product name: [MariaDB]

Look here: https://github.com/spring-projects/spring-framework/issues/22344

Similar issues:

DatabaseType not found for product name: [Impala]

Spring batch --- DatabaseType not found for product name: [Informix Dynamic Server]

Body:
when I run my application there is the following error displayed:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pamdaBatchConfigurer': Invocation of init method failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getJobRepository' defined in com.orange.pamda.config.PamdaBatchConfigurer: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.batch.core.repository.JobRepository]: Circular reference involving containing bean 'pamdaBatchConfigurer' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getJobRepository' threw exception; nested exception is java.lang.IllegalArgumentException: DatabaseType not found for product name: [MariaDB]
      at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
      at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
      at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
      at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
      at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
      at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
      at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:443)
      at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:325)
      at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
      at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4685)
      at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5146)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
      at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
      at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
      at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384)
      at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374)
      at java.util.concurrent.FutureTask.run(FutureTask.java:266)
      at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75)
      at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:134)
      at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909)
      at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930)
      at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
      at org.apache.catalina.startup.Catalina.start(Catalina.java:633)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:498)
      at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:343)
      at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:474)

here is my file "pamdabatchconfigurer.java":

    package com.orange.pamda.config;

import java.util.Date;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.configuration.annotation.BatchConfigurer;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.explore.JobExplorer;
import org.springframework.batch.core.explore.support.JobExplorerFactoryBean;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;

import com.orange.pamda.config.batch.listener.SendFileAfterExportListener;
import com.orange.pamda.worker.config.CatalogueExporterJobConfiguration;
import com.orange.pamda.worker.config.CatalogueImporterJobConfiguration;
import com.orange.pamda.worker.config.CommonJobConfiguration;
import com.orange.pamda.worker.config.DataExporterJobConfiguration;
import com.orange.pamda.worker.config.HierarchyValidatorJobConfiguration;
import com.orange.pamda.worker.config.JobBuilderFactory;
import com.orange.pamda.worker.config.KoalaExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingExporterJobConfiguration;
import com.orange.pamda.worker.config.MappingImporterJobConfiguration;
import com.orange.pamda.worker.config.OrphanExporterJobConfiguration;
import com.orange.pamda.worker.config.ReleaseJobConfiguration;
import com.orange.pamda.worker.config.SummaryExporterJobConfiguration;

@Configuration
@EnableBatchProcessing(modular = true)
@Import({ CommonJobConfiguration.class, CatalogueExporterJobConfiguration.class,
        CatalogueImporterJobConfiguration.class, DataExporterJobConfiguration.class,
        HierarchyValidatorJobConfiguration.class, KoalaExporterJobConfiguration.class,
        MappingExporterJobConfiguration.class, MappingImporterJobConfiguration.class,
        OrphanExporterJobConfiguration.class, ReleaseJobConfiguration.class, SummaryExporterJobConfiguration.class })
public class PamdaBatchConfigurer implements BatchConfigurer {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private DataSource dataSource;

    @Override
    @Bean
    public JobRepository getJobRepository() throws Exception {
        JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
        jobRepositoryFactoryBean.setDataSource(dataSource);
        jobRepositoryFactoryBean.setTransactionManager(transactionManager);
        jobRepositoryFactoryBean.setIsolationLevelForCreate("ISOLATION_DEFAULT");
        jobRepositoryFactoryBean.afterPropertiesSet();
        return jobRepositoryFactoryBean.getObject();
    }

    @Override
    public PlatformTransactionManager getTransactionManager() throws Exception {
        return transactionManager;
    }

    @Override
    @Bean
    public JobLauncher getJobLauncher() throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        jobLauncher.setJobRepository(getJobRepository());
        // jobLauncher.setTaskExecutor(getTaskExecutor());
        jobLauncher.afterPropertiesSet();
        return jobLauncher;
    }

    @Override
    @Bean
    public JobExplorer getJobExplorer() throws Exception {
        JobExplorerFactoryBean jobExplorerFactoryBean = new JobExplorerFactoryBean();
        jobExplorerFactoryBean.setDataSource(dataSource);
        jobExplorerFactoryBean.afterPropertiesSet();
        return jobExplorerFactoryBean.getObject();
    }

    // @Bean
    // public TaskExecutor getTaskExecutor() {
    // SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new
    // SimpleAsyncTaskExecutor();
    // simpleAsyncTaskExecutor.setConcurrencyLimit(1000); // no throttle
    // return simpleAsyncTaskExecutor;
    // }

    @Bean
    public JobBuilderFactory getJobBuilderFactory() throws Exception {
        return new JobBuilderFactory(getJobRepository(), sendFileAfterExportListener());
    }

    @Bean
    public StepBuilderFactory getStepBuilderFactory() throws Exception {
        return new StepBuilderFactory(getJobRepository(), transactionManager);
    }

    @Bean
    public SendFileAfterExportListener sendFileAfterExportListener() {
        return new SendFileAfterExportListener();
    }

    @PostConstruct
    @Transactional
    public void init() throws Exception {
        JobExplorer jobExplorer = getJobExplorer();
        JobRepository jobRepository = getJobRepository();
        for (String jobName : jobExplorer.getJobNames()) {
            Set<JobExecution> runningJobExecutions = jobExplorer.findRunningJobExecutions(jobName);
            for (JobExecution runningJobExecution : runningJobExecutions) {
                runningJobExecution.setExitStatus(ExitStatus.UNKNOWN);
                runningJobExecution.setEndTime(new Date());
                jobRepository.update(runningJobExecution);
            }
        }
    }

}

I really do not know where this error comes from can someone help me please?


问:
Copy a db2 schema to db2 with all tables and rename the schema?
How just to copy a db2 schema with all tables and rename the schema?

windows, db2 v9.7.0.1, I am trying the command db2 "call sysproc.admin_copy_schema('P1ADM549','H1ADM549','DDL',NULL,NULL,NULL,'ERRORS','ERRORT')" but i get

SQLCODE: -601, SQLSTATE: 42710 - The name of the object to be created
  is identical to the existing

答:
With db2move utility it's easy, in your cause:

```<code>db2move source_db COPY -sn P1ADM549 -co TARGET_DB target MODE DDL_ONLY SCHEMA_MAP "((P1ADM549,H1ADM549))" [ user userid using password ] # If it's same database it isn't mandatory.
</code>```

https://www.ibm.com/support/knowledgecenter/SSEPGG_11.1.0/com.ibm.db2.luw.admin.dbobj.doc/doc/t0022655.html

Body:
With db2move utility it's easy, in your cause:

db2move source_db COPY -sn P1ADM549 -co TARGET_DB target MODE DDL_ONLY SCHEMA_MAP "((P1ADM549,H1ADM549))" [ user userid using password ] # If it's same database it isn't mandatory.

https://www.ibm.com/support/knowledgecenter/SSEPGG_11.1.0/com.ibm.db2.luw.admin.dbobj.doc/doc/t0022655.html


问:
Git commit opens blank text file, for what?
In all the Git tutorials I've read they say that you can do:

```<code>git init
git add .
git commit
</code>```

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

答:
The git commit command will open up the editor specified in the EDITOR environment variable so you can enter a commit comment.  On a Linux or BSD system, this should be vi by default, although any editor should work.

Just enter your comments and save the file.

OwnerDisplayName: Alex

LastEditorDisplayName: Baishampayan Ghose

Body:
In all the Git tutorials I've read they say that you can do:

git init
git add .
git commit

When I do that I get a big text file opened up. None of the tutorials seem to address this, so I don't know what to do with the file or what to put in it if anything.

OwnerDisplayName: Ben Collins

ContentLicense: CC BY-SA 2.5


问:
Wait for application window loading
Hi I am working with an automatisation of certain app like obs. What I am trying to do is launch obs and wait for it to load its window is there a way to check if the window has shown ?

Tried this but the process start instantly it does not take in concideration if the app has shown its window

```<code>Process[] obs = Process.GetProcessesByName("obs64");
while (obs.Count() == 0 && firefox.Count() == 0){
    Thread.Sleep(1000);
    obs = Process.GetProcessesByName("obs64");
}
</code>```

答:
Found a way by using the MainWindowHandle</p>

```<code>
Process obsProcess = Process.Start("C:\\Program Files (x86)\\obs-studio\\bin\\64bit\\OBS.exe");
while (obsProcess.MainWindowHandle == IntPtr.Zero) Thread.Sleep(1000);
</code>```

Title: Wait for application window loading

Body:
Hi I am working with an automatisation of certain app like obs. What I am trying to do is launch obs and wait for it to load its window is there a way to check if the window has shown ?

Tried this but the process start instantly it does not take in concideration if the app has shown its window

Process[] obs = Process.GetProcessesByName("obs64");
while (obs.Count() == 0 && firefox.Count() == 0){
    Thread.Sleep(1000);
    obs = Process.GetProcessesByName("obs64");
}

Body:
Found a way by using the MainWindowHandle

Process obsProcess = Process.Start("C:\\Program Files (x86)\\obs-studio\\bin\\64bit\\OBS.exe");
while (obsProcess.MainWindowHandle == IntPtr.Zero) Thread.Sleep(1000);