问:
Scala error - Exception in thread "main" java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
I have a requirement where i am reading data from a CSV file and writing data to a Delta table over scala on window OS. My scala code is given below:-

```<code>import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.Logger
import org.apache.spark.sql.SparkSession

object DelataLake_Pipeline {
  def main(args: Array[String]): Unit = {
    val masterConfig = ConfigFactory.load()
    val sourceConfig = masterConfig.getConfig("source-db")
    val logger = Logger("Pipeline")
    println("Printing Step 1")

    val spark = SparkSession
      .builder
      .appName("GPipe")
      .master("local")
      .getOrCreate()

    /**************suppress Logs******************/
    org.slf4j.LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME)
      .asInstanceOf[ch.qos.logback.classic.Logger]
      .setLevel(ch.qos.logback.classic.Level.WARN)

    /*Read data from source file*/
    val sourceTableDF = spark.read.options(Map("inferSchema"->"false","delimiter"->",","header"->"true")).csv(sourceConfig.getString("sourcefile"))

    println("Printing source CSV data")
    sourceTableDF.show()

    /* ***************Create Delta Table*************************/
    println("Start creating delta-table ")

    try {
      sourceTableDF.write.format("delta").mode("overwrite").save("datable")
    } catch {
      case _: Throwable => // Catching all exceptions and not doing anything with them
    }
    println("End creating delta-table")

    /* ***************Read Delta table into a dataframe ********** */
      val df_dd = spark.read.format("delta").load("datable")
      df_dd.show()

    println("printing delta table data")
    spark.stop()
  }
}

</code>```

When i execute above code then i am getting following exception :-

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:793)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1215)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1420)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:601)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:761)
    at org.apache.spark.sql.delta.storage.HadoopFileSystemLogStore.listFrom(HadoopFileSystemLogStore.scala:83)
    at org.apache.spark.sql.delta.storage.DelegatingLogStore.listFrom(DelegatingLogStore.scala:119)
    at org.apache.spark.sql.delta.SnapshotManagement.listFrom(SnapshotManagement.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.listFrom$(SnapshotManagement.scala:61)
    at org.apache.spark.sql.delta.DeltaLog.listFrom(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.getLogSegmentForVersion(SnapshotManagement.scala:95)
    at org.apache.spark.sql.delta.SnapshotManagement.getLogSegmentForVersion$(SnapshotManagement.scala:89)
    at org.apache.spark.sql.delta.DeltaLog.getLogSegmentForVersion(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.$anonfun$updateInternal$1(SnapshotManagement.scala:284)
    at com.databricks.spark.util.DatabricksLogging.recordOperation(DatabricksLogging.scala:77)
    at com.databricks.spark.util.DatabricksLogging.recordOperation$(DatabricksLogging.scala:67)
    at org.apache.spark.sql.delta.DeltaLog.recordOperation(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation(DeltaLogging.scala:112)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation$(DeltaLogging.scala:97)
    at org.apache.spark.sql.delta.DeltaLog.recordDeltaOperation(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.updateInternal(SnapshotManagement.scala:282)
    at org.apache.spark.sql.delta.SnapshotManagement.updateInternal$(SnapshotManagement.scala:281)
    at org.apache.spark.sql.delta.DeltaLog.updateInternal(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.$anonfun$update$1(SnapshotManagement.scala:243)
    at org.apache.spark.sql.delta.DeltaLog.lockInterruptibly(DeltaLog.scala:163)
    at org.apache.spark.sql.delta.SnapshotManagement.update(SnapshotManagement.scala:243)
    at org.apache.spark.sql.delta.SnapshotManagement.update$(SnapshotManagement.scala:239)
    at org.apache.spark.sql.delta.DeltaLog.update(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommit(OptimisticTransaction.scala:749)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommit$(OptimisticTransaction.scala:715)
    at org.apache.spark.sql.delta.OptimisticTransaction.doCommit(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.$anonfun$doCommitRetryIteratively$2(OptimisticTransaction.scala:684)
    at com.databricks.spark.util.DatabricksLogging.recordOperation(DatabricksLogging.scala:77)
    at com.databricks.spark.util.DatabricksLogging.recordOperation$(DatabricksLogging.scala:67)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation(DeltaLogging.scala:112)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation$(DeltaLogging.scala:97)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordDeltaOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.$anonfun$doCommitRetryIteratively$1(OptimisticTransaction.scala:680)
    at org.apache.spark.sql.delta.DeltaLog.lockInterruptibly(DeltaLog.scala:163)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.lockCommitIfEnabled(OptimisticTransaction.scala:659)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommitRetryIteratively(OptimisticTransaction.scala:674)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommitRetryIteratively$(OptimisticTransaction.scala:671)
    at org.apache.spark.sql.delta.OptimisticTransaction.doCommitRetryIteratively(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.liftedTree1$1(OptimisticTransaction.scala:522)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.$anonfun$commit$1(OptimisticTransaction.scala:462)
    at scala.runtime.java8.JFunction0$mcJ$sp.apply(JFunction0$mcJ$sp.scala:17)
    at com.databricks.spark.util.DatabricksLogging.recordOperation(DatabricksLogging.scala:77)
    at com.databricks.spark.util.DatabricksLogging.recordOperation$(DatabricksLogging.scala:67)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation(DeltaLogging.scala:112)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation$(DeltaLogging.scala:97)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordDeltaOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.commit(OptimisticTransaction.scala:459)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.commit$(OptimisticTransaction.scala:457)
    at org.apache.spark.sql.delta.OptimisticTransaction.commit(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.commands.WriteIntoDelta.$anonfun$run$1(WriteIntoDelta.scala:83)
    at org.apache.spark.sql.delta.commands.WriteIntoDelta.$anonfun$run$1$adapted(WriteIntoDelta.scala:78)
    at org.apache.spark.sql.delta.DeltaLog.withNewTransaction(DeltaLog.scala:198)
    at org.apache.spark.sql.delta.commands.WriteIntoDelta.run(WriteIntoDelta.scala:78)
    at org.apache.spark.sql.delta.sources.DeltaDataSource.createRelation(DeltaDataSource.scala:154)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:45)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:75)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:73)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.executeCollect(commands.scala:84)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.$anonfun$applyOrElse$1(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:103)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:163)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:90)
    at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:106)
    at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDownWithPruning$1(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:82)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDownWithPruning(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.org$apache$spark$sql$catalyst$plans$logical$AnalysisHelper$$super$transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning(AnalysisHelper.scala:267)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning$(AnalysisHelper.scala:263)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:457)
    at org.apache.spark.sql.execution.QueryExecution.eagerlyExecuteCommands(QueryExecution.scala:106)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted$lzycompute(QueryExecution.scala:93)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted(QueryExecution.scala:91)
    at org.apache.spark.sql.execution.QueryExecution.assertCommandExecuted(QueryExecution.scala:128)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:848)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:382)
    at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:303)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:239)
    at DelataLake_Pipeline$.writeData(DelataLake_Pipeline.scala:217)
    at DelataLake_Pipeline$.main(DelataLake_Pipeline.scala:189)
    at DelataLake_Pipeline.main(DelataLake_Pipeline.scala)
</code>```

I have properly configured enviroment variables and my Hadoop_Home folder has hadoop.dll winutils.exe files under BIN folder.

Looking forward for your input how to resolve this issue, because of this exception i cannot read data from Delta table and apply transformations.

答:
I had the same problem running scalatest using spark 3.2.1.
I solved it updating wintuils to Hadoop 3.3.1 from this repo

https://github.com/kontext-tech/winutils

Cheers

Body:
I have a requirement where i am reading data from a CSV file and writing data to a Delta table over scala on window OS. My scala code is given below:-

import com.typesafe.config.ConfigFactory
import com.typesafe.scalalogging.Logger
import org.apache.spark.sql.SparkSession

object DelataLake_Pipeline {
  def main(args: Array[String]): Unit = {
    val masterConfig = ConfigFactory.load()
    val sourceConfig = masterConfig.getConfig("source-db")
    val logger = Logger("Pipeline")
    println("Printing Step 1")

    val spark = SparkSession
      .builder
      .appName("GPipe")
      .master("local")
      .getOrCreate()

    /**************suppress Logs******************/
    org.slf4j.LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME)
      .asInstanceOf[ch.qos.logback.classic.Logger]
      .setLevel(ch.qos.logback.classic.Level.WARN)

    /*Read data from source file*/
    val sourceTableDF = spark.read.options(Map("inferSchema"->"false","delimiter"->",","header"->"true")).csv(sourceConfig.getString("sourcefile"))

    println("Printing source CSV data")
    sourceTableDF.show()

    /* ***************Create Delta Table*************************/
    println("Start creating delta-table ")

    try {
      sourceTableDF.write.format("delta").mode("overwrite").save("datable")
    } catch {
      case _: Throwable => // Catching all exceptions and not doing anything with them
    }
    println("End creating delta-table")

    /* ***************Read Delta table into a dataframe ********** */
      val df_dd = spark.read.format("delta").load("datable")
      df_dd.show()

    println("printing delta table data")
    spark.stop()
  }
}

When i execute above code then i am getting following exception :-

Exception in thread "main" java.lang.UnsatisfiedLinkError: org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Ljava/lang/String;I)Z
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:793)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1215)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1420)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:601)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:761)
    at org.apache.spark.sql.delta.storage.HadoopFileSystemLogStore.listFrom(HadoopFileSystemLogStore.scala:83)
    at org.apache.spark.sql.delta.storage.DelegatingLogStore.listFrom(DelegatingLogStore.scala:119)
    at org.apache.spark.sql.delta.SnapshotManagement.listFrom(SnapshotManagement.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.listFrom$(SnapshotManagement.scala:61)
    at org.apache.spark.sql.delta.DeltaLog.listFrom(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.getLogSegmentForVersion(SnapshotManagement.scala:95)
    at org.apache.spark.sql.delta.SnapshotManagement.getLogSegmentForVersion$(SnapshotManagement.scala:89)
    at org.apache.spark.sql.delta.DeltaLog.getLogSegmentForVersion(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.$anonfun$updateInternal$1(SnapshotManagement.scala:284)
    at com.databricks.spark.util.DatabricksLogging.recordOperation(DatabricksLogging.scala:77)
    at com.databricks.spark.util.DatabricksLogging.recordOperation$(DatabricksLogging.scala:67)
    at org.apache.spark.sql.delta.DeltaLog.recordOperation(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation(DeltaLogging.scala:112)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation$(DeltaLogging.scala:97)
    at org.apache.spark.sql.delta.DeltaLog.recordDeltaOperation(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.updateInternal(SnapshotManagement.scala:282)
    at org.apache.spark.sql.delta.SnapshotManagement.updateInternal$(SnapshotManagement.scala:281)
    at org.apache.spark.sql.delta.DeltaLog.updateInternal(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.SnapshotManagement.$anonfun$update$1(SnapshotManagement.scala:243)
    at org.apache.spark.sql.delta.DeltaLog.lockInterruptibly(DeltaLog.scala:163)
    at org.apache.spark.sql.delta.SnapshotManagement.update(SnapshotManagement.scala:243)
    at org.apache.spark.sql.delta.SnapshotManagement.update$(SnapshotManagement.scala:239)
    at org.apache.spark.sql.delta.DeltaLog.update(DeltaLog.scala:62)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommit(OptimisticTransaction.scala:749)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommit$(OptimisticTransaction.scala:715)
    at org.apache.spark.sql.delta.OptimisticTransaction.doCommit(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.$anonfun$doCommitRetryIteratively$2(OptimisticTransaction.scala:684)
    at com.databricks.spark.util.DatabricksLogging.recordOperation(DatabricksLogging.scala:77)
    at com.databricks.spark.util.DatabricksLogging.recordOperation$(DatabricksLogging.scala:67)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation(DeltaLogging.scala:112)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation$(DeltaLogging.scala:97)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordDeltaOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.$anonfun$doCommitRetryIteratively$1(OptimisticTransaction.scala:680)
    at org.apache.spark.sql.delta.DeltaLog.lockInterruptibly(DeltaLog.scala:163)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.lockCommitIfEnabled(OptimisticTransaction.scala:659)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommitRetryIteratively(OptimisticTransaction.scala:674)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.doCommitRetryIteratively$(OptimisticTransaction.scala:671)
    at org.apache.spark.sql.delta.OptimisticTransaction.doCommitRetryIteratively(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.liftedTree1$1(OptimisticTransaction.scala:522)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.$anonfun$commit$1(OptimisticTransaction.scala:462)
    at scala.runtime.java8.JFunction0$mcJ$sp.apply(JFunction0$mcJ$sp.scala:17)
    at com.databricks.spark.util.DatabricksLogging.recordOperation(DatabricksLogging.scala:77)
    at com.databricks.spark.util.DatabricksLogging.recordOperation$(DatabricksLogging.scala:67)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation(DeltaLogging.scala:112)
    at org.apache.spark.sql.delta.metering.DeltaLogging.recordDeltaOperation$(DeltaLogging.scala:97)
    at org.apache.spark.sql.delta.OptimisticTransaction.recordDeltaOperation(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.commit(OptimisticTransaction.scala:459)
    at org.apache.spark.sql.delta.OptimisticTransactionImpl.commit$(OptimisticTransaction.scala:457)
    at org.apache.spark.sql.delta.OptimisticTransaction.commit(OptimisticTransaction.scala:86)
    at org.apache.spark.sql.delta.commands.WriteIntoDelta.$anonfun$run$1(WriteIntoDelta.scala:83)
    at org.apache.spark.sql.delta.commands.WriteIntoDelta.$anonfun$run$1$adapted(WriteIntoDelta.scala:78)
    at org.apache.spark.sql.delta.DeltaLog.withNewTransaction(DeltaLog.scala:198)
    at org.apache.spark.sql.delta.commands.WriteIntoDelta.run(WriteIntoDelta.scala:78)
    at org.apache.spark.sql.delta.sources.DeltaDataSource.createRelation(DeltaDataSource.scala:154)
    at org.apache.spark.sql.execution.datasources.SaveIntoDataSourceCommand.run(SaveIntoDataSourceCommand.scala:45)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:75)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:73)
    at org.apache.spark.sql.execution.command.ExecutedCommandExec.executeCollect(commands.scala:84)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.$anonfun$applyOrElse$1(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$5(SQLExecution.scala:103)
    at org.apache.spark.sql.execution.SQLExecution$.withSQLConfPropagated(SQLExecution.scala:163)
    at org.apache.spark.sql.execution.SQLExecution$.$anonfun$withNewExecutionId$1(SQLExecution.scala:90)
    at org.apache.spark.sql.SparkSession.withActive(SparkSession.scala:775)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:64)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:110)
    at org.apache.spark.sql.execution.QueryExecution$$anonfun$eagerlyExecuteCommands$1.applyOrElse(QueryExecution.scala:106)
    at org.apache.spark.sql.catalyst.trees.TreeNode.$anonfun$transformDownWithPruning$1(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.trees.CurrentOrigin$.withOrigin(TreeNode.scala:82)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDownWithPruning(TreeNode.scala:481)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.org$apache$spark$sql$catalyst$plans$logical$AnalysisHelper$$super$transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning(AnalysisHelper.scala:267)
    at org.apache.spark.sql.catalyst.plans.logical.AnalysisHelper.transformDownWithPruning$(AnalysisHelper.scala:263)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.plans.logical.LogicalPlan.transformDownWithPruning(LogicalPlan.scala:30)
    at org.apache.spark.sql.catalyst.trees.TreeNode.transformDown(TreeNode.scala:457)
    at org.apache.spark.sql.execution.QueryExecution.eagerlyExecuteCommands(QueryExecution.scala:106)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted$lzycompute(QueryExecution.scala:93)
    at org.apache.spark.sql.execution.QueryExecution.commandExecuted(QueryExecution.scala:91)
    at org.apache.spark.sql.execution.QueryExecution.assertCommandExecuted(QueryExecution.scala:128)
    at org.apache.spark.sql.DataFrameWriter.runCommand(DataFrameWriter.scala:848)
    at org.apache.spark.sql.DataFrameWriter.saveToV1Source(DataFrameWriter.scala:382)
    at org.apache.spark.sql.DataFrameWriter.saveInternal(DataFrameWriter.scala:303)
    at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:239)
    at DelataLake_Pipeline$.writeData(DelataLake_Pipeline.scala:217)
    at DelataLake_Pipeline$.main(DelataLake_Pipeline.scala:189)
    at DelataLake_Pipeline.main(DelataLake_Pipeline.scala)

I have properly configured enviroment variables and my Hadoop_Home folder has hadoop.dll winutils.exe files under BIN folder.

Looking forward for your input how to resolve this issue, because of this exception i cannot read data from Delta table and apply transformations.


来源: stackexchange

问:
how to use LIKE with column name
Normally LIKE statement is used to check the pattern like data.

example:

```<code>select * from table1 where name like 'ar%'
</code>```

My problem is to use one column of table with LIKE statement.

example:

```<code>select * from table1, table2 where table1.x is like table2.y%
</code>```

Query above results error . how to use one column data in like query?

答:
This works for me:</p>
```<code>SELECT * FROM `mdl_user` WHERE `firstname` LIKE concat(lastname,'%') AND lastname != ''
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to use LIKE with column name

Body:
Normally LIKE statement is used to check the pattern like data.

example:

select * from table1 where name like 'ar%'

My problem is to use one column of table with LIKE statement.

example:

select * from table1, table2 where table1.x is like table2.y%

Query above results error . how to use one column data in like query?

LastEditorDisplayName: lutz

Body:
This works for me:

SELECT * FROM `mdl_user` WHERE `firstname` LIKE concat(lastname,'%') AND lastname != ''


问:
How come onWSM method does not get invoke when sending messages from RSU?
I'm trying to send messages from RSU to the cars, basically, I want to flood the network, but for some I can not seem to see any message that are received by the car module.

I did try cleaning the project. I tried following the veins example but even that does not work for me.

RSU class

void RSU11p::handleSelfMsg(cMessage* msg) {

    EV << "handleselfmessage in RSU11p" << endl;

    WaveShortMessage* rsu_msg = new WaveShortMessage();

    populateWSM(rsu_msg);
    sendDown(rsu_msg->dup());
    //scheduleAt(simTime() + 1, rsu_msg->dup());
}

```

<p>MyVeinsApp class</p>

<pre class="lang-cpp prettyprint-override"><code>void MyThesisApp::onWSM(WaveShortMessage* wsm)
{
    findHost()->getDisplayString().updateWith("r=16,green");
    EV << "received here from car or RSU?" << endl;

    EV << wsm << endl;

}

</code>```

When I run the simulation, I do not see "received here ..." printed in the console. Which does not make sense to me at all. What I'm doing wrong?

Any help is greatly appreciated. Thank you.

答: Seems you are not invoking handleSelfMessage (). You need to call scheduleAt()  in some method to invoke it.</p>

Body:
I'm trying to send messages from RSU to the cars, basically, I want to flood the network, but for some I can not seem to see any message that are received by the car module.

I did try cleaning the project. I tried following the veins example but even that does not work for me.

RSU class

void RSU11p::handleSelfMsg(cMessage* msg) {

    EV << "handleselfmessage in RSU11p" << endl;

    WaveShortMessage* rsu_msg = new WaveShortMessage();

    populateWSM(rsu_msg);
    sendDown(rsu_msg->dup());
    //scheduleAt(simTime() + 1, rsu_msg->dup());
}

MyVeinsApp class

void MyThesisApp::onWSM(WaveShortMessage* wsm)
{
    findHost()->getDisplayString().updateWith("r=16,green");
    EV << "received here from car or RSU?" << endl;

    EV << wsm << endl;

}

When I run the simulation, I do not see "received here ..." printed in the console. Which does not make sense to me at all. What I'm doing wrong?

Any help is greatly appreciated. Thank you.


问:
Downsampling Wav audio files in datasets
I have taken the LJ Speech dataset from Hugging Face for Automatic Speech Recognition Training.
Link to dataset: https://huggingface.co/datasets/lj_speech
The sampling rate of the audio is 22050 Hz.
I want to convert it into 16000 Hz for the whole dataset.

code and output
lj_data['audio'][0]

output
screenshot of audio file description

答:
Actually, I found out the answer.
Hugging face has some amazing functions, which can resample the file.

```<code>from datasets import load_dataset, load_metric, Audio

#loading data
data = load_dataset("lj_speech")

#resampling training data from 22050Hz to 16000Hz
data['train'] = data['train'].cast_column("audio", Audio(sampling_rate=16_000))
</code>```

To see documentation: https://huggingface.co/docs/datasets/audio_process.html

Results:

Before Resampling
Before Resampling- 22050Hz

After Resampling:
After Resampling - 16000Hz

Body:
Actually, I found out the answer.
Hugging face has some amazing functions, which can resample the file.

from datasets import load_dataset, load_metric, Audio

#loading data
data = load_dataset("lj_speech")

#resampling training data from 22050Hz to 16000Hz
data['train'] = data['train'].cast_column("audio", Audio(sampling_rate=16_000))

To see documentation: https://huggingface.co/docs/datasets/audio_process.html

Results:

Before Resampling
Before Resampling- 22050Hz

After Resampling:
After Resampling - 16000Hz


问:
How to copy sitemap.xml to build folder with React & Webpack?
I have a sitemap.xml file in public folder. When I build the React application, the sitemap.xml file is not present in the dist/build folder.

What Webpack configuration is needed to achieve that? How does robots.txt need to be set up?

答:
Here is the webpack-config for serving a file to build folder witha a custom name

```<code>module: {
    rules: [
        {
            test: /\.(ts|js)x?$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'babel-loader',
                },
            ],
        },
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
        },
        {
            test: /\.(?:ico|gif|png|jpg|jpeg|xml)$/i,
            type: 'asset/resource',
        },
        {
            test: /\.xml/,
            type: 'asset/resource',
            generator: {
                filename: 'sitemap.xml',
            },
        },
        {
            test: /\.txt/,
            type: 'asset/resource',
            generator: {
                filename: 'robots.txt',
            },
        },
        {
            test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
            type: 'asset/inline',
        },
    ],
},
</code>```

Finally make sure you import that file inside your react application or else it will not be served to build folder

OwnerDisplayName: Sharan Balakrishnan

Body:
Here is the webpack-config for serving a file to build folder witha a custom name

module: {
    rules: [
        {
            test: /\.(ts|js)x?$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'babel-loader',
                },
            ],
        },
        {
            test: /\.css$/,
            use: ['style-loader', 'css-loader'],
        },
        {
            test: /\.(?:ico|gif|png|jpg|jpeg|xml)$/i,
            type: 'asset/resource',
        },
        {
            test: /\.xml/,
            type: 'asset/resource',
            generator: {
                filename: 'sitemap.xml',
            },
        },
        {
            test: /\.txt/,
            type: 'asset/resource',
            generator: {
                filename: 'robots.txt',
            },
        },
        {
            test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
            type: 'asset/inline',
        },
    ],
},

Finally make sure you import that file inside your react application or else it will not be served to build folder


问:
How to split a Formik / React form into different columns in a table?
I'm learning ReactJS and using the Formik library for user input.

I've been trying to design a table whose first row (header) contains input fields for each of the columns displayed, but I can't seem to find a way to distribute said fields on their own columns. They all get crammed into the first column of the table.

```<code><table>
  <thead>
    <tr>
      <th scope="col">
        {/* TODO: Fix this form as it currently loads into a single column */}
        <Formik
          initialValues={hobbyInitialValues}
          onSubmit={SubmitHobby}
          validationSchema={ValidateHobby}
        >
          <Form>
            <Field className="selectField" as="select" name="passion">
              <option value="" label="Select Passion" />
              <option value="Low" label="Low" />
              <option value="Medium" label="Medium" />
              <option value="High" label="High" />
            </Field>
            <Field
              className="inputField"
              id="inputHobbyName"
              name="name"
              placeholder="Enter User Hobby"
            />
            <Field
              className="inputField"
              id="inputYear"
              name="year"
              placeholder="Enter Year"
            />
            <button className="submitButton" type="submit">
              Add
            </button>
          </Form>
        </Formik>
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
    </tr>
  </tbody>
</table>
</code>```

Attempting to surround a single field within a  results in this error, as both Formik and React Tables restrict what children can a component have:

Warning: validateDOMNesting(...): <form> cannot appear as a child of
.

How can I achieve the intended result?

EDIT: my issue was solved thanks to Wraithy's answer. Code is now as follows:

```<code><Formik
  initialValues={hobbyInitialValues}
  onSubmit={SubmitHobby}
  validationSchema={ValidateHobby}
>
  <Form>
    <table>
      <thead>
        <tr>
          <th scope="col">
            <Field className="selectField" as="select" name="passion">
              <option value="" label="Select Passion" />
              <option value="Low" label="Low" />
              <option value="Medium" label="Medium" />
              <option value="High" label="High" />
            </Field>
          </th>
          <th scope="col">
            <Field
              className="inputField"
              id="inputHobbyName"
              name="name"
              placeholder="Enter User Hobby"
            />
          </th>
          <th scope="col">
            <Field
              className="inputField"
              id="inputYear"
              name="year"
              placeholder="Enter Year"
            />
          </th>
          <th scope="col">
            <button className="submitButton" type="submit">
              Add
            </button>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th>Column 1</th>
          <th>Column 2</th>
          <th>Column 3</th>
          <th>Column 4</th>
        </tr>
      </tbody>
    </table>
  </Form>
</Formik>
</code>```

答:
You can just wrap your whole Table in <Formik>

```<code> <Formik
          initialValues={hobbyInitialValues}
          onSubmit={SubmitHobby}
          validationSchema={ValidateHobby}
        >
<table>
<!-- table with more columns go there -->
</table>
</Formik>

</code>```

Body:
I'm learning ReactJS and using the Formik library for user input.

I've been trying to design a table whose first row (header) contains input fields for each of the columns displayed, but I can't seem to find a way to distribute said fields on their own columns. They all get crammed into the first column of the table.

        {/* TODO: Fix this form as it currently loads into a single column */}
        <Formik
          initialValues={hobbyInitialValues}
          onSubmit={SubmitHobby}
          validationSchema={ValidateHobby}
        >
          <Form>
            <Field className="selectField" as="select" name="passion">
              <option value="" label="Select Passion" />
              <option value="Low" label="Low" />
              <option value="Medium" label="Medium" />
              <option value="High" label="High" />
            </Field>
            <Field
              className="inputField"
              id="inputHobbyName"
              name="name"
              placeholder="Enter User Hobby"
            />
            <Field
              className="inputField"
              id="inputYear"
              name="year"
              placeholder="Enter Year"
            />
            <button className="submitButton" type="submit">
              Add
            </button>
          </Form>
        </Formik>

      Column 1
      Column 2
      Column 3
      Column 4

Attempting to surround a single field within a  results in this error, as both Formik and React Tables restrict what children can a component have:

Warning: validateDOMNesting(...): <form> cannot appear as a child of
.

How can I achieve the intended result?

EDIT: my issue was solved thanks to Wraithy's answer. Code is now as follows:

<Formik
  initialValues={hobbyInitialValues}
  onSubmit={SubmitHobby}
  validationSchema={ValidateHobby}
>
  <Form>

            <Field className="selectField" as="select" name="passion">
              <option value="" label="Select Passion" />
              <option value="Low" label="Low" />
              <option value="Medium" label="Medium" />
              <option value="High" label="High" />
            </Field>

            <Field
              className="inputField"
              id="inputHobbyName"
              name="name"
              placeholder="Enter User Hobby"
            />

            <Field
              className="inputField"
              id="inputYear"
              name="year"
              placeholder="Enter Year"
            />

            <button className="submitButton" type="submit">
              Add
            </button>

          Column 1
          Column 2
          Column 3
          Column 4

  </Form>
</Formik>

Body:
You can just wrap your whole Table in <Formik>

 <Formik
          initialValues={hobbyInitialValues}
          onSubmit={SubmitHobby}
          validationSchema={ValidateHobby}
        >
<table>
<!-- table with more columns go there -->
</table>
</Formik>


问:
How many phone numbers i can associate with one messaging service in twilio?
i am using twilio messaging service in my webapp. Here, each phone number have its own messaging service. I want to associate all phone numbers to 1 messaging service. Is it possible to send and receive messages on each phone number using 1 messaging service?</p>

答:
Twilio developer evangelist here.

According to this article:

A Twilio Messaging Service can contain up to 400 Twilio message senders by default, including phone numbers, short codes, Alpha Sender ID, and WhatsApp senders.

And if you need more, you can contact support.


问:
How do I get the path of a directory where a file SQL backup is missing?
The task is to track the execution of SQL backups. One of the tracking mechanisms is to browse the directory where the backups are saved and if the file is missing, you can send an email with the full address of the directory where the file is missing. This is what I am trying to implement with Powershell script, but for some reason my script doesn't work and doesn't give me the information I need.

```<code>$list = Get-ChildItem -Path network_path_to_share -Recurse -File | Where-Object {$_.DirectoryName -like '*FULL*' -and $_.LastWriteTime -ge (Get-Date).AddDays(-6)}
$fileExists = Test-Path $list
If ($fileExists)
{
 #Do Nothing
}
Else
{
$list | Select DirectoryName
}
</code>```

Can anyone help?

答:
If you're wanting to check for something that is missing or doesn't exist, you need to start with a known condition, e.g.:  either the server names or expected file or directory names.

If you know that, then you can create a static list (or dynamically query a list from Active Directory for your SQL servers or something (assuming the backup file names correspond to the server names)) and then check the files that were created and output the missing ones for triage.

Here is a modification to your script (essentially the opposite of what you did) that might point you in the right direction:

```<code>## List of expected files
$ExpectedFiles = @(
    'File1.bak',
    'File2.bak',
    'File3.bak',
    'File4.bak'
    '...'
)

## Get a list of created files
$list = Get-ChildItem -Path network_path_to_share -Recurse -File | Where-Object {$_.DirectoryName -like '*FULL*' -and $_.LastWriteTime -ge (Get-Date).AddDays(-6)} | Select -ExpandProperty Name

## Check whether each expected file exists in the array of backups that actually were created
foreach ($file in $ExpectedFiles) {
    if (-not(Test-Path $list)) {
        "$($file) is missing!"
    }
}
</code>```

Body:
The task is to track the execution of SQL backups. One of the tracking mechanisms is to browse the directory where the backups are saved and if the file is missing, you can send an email with the full address of the directory where the file is missing. This is what I am trying to implement with Powershell script, but for some reason my script doesn't work and doesn't give me the information I need.

$list = Get-ChildItem -Path network_path_to_share -Recurse -File | Where-Object {$_.DirectoryName -like '*FULL*' -and $_.LastWriteTime -ge (Get-Date).AddDays(-6)}
$fileExists = Test-Path $list
If ($fileExists)
{
 #Do Nothing
}
Else
{
$list | Select DirectoryName
}

Can anyone help?

Body:
If you're wanting to check for something that is missing or doesn't exist, you need to start with a known condition, e.g.:  either the server names or expected file or directory names.

If you know that, then you can create a static list (or dynamically query a list from Active Directory for your SQL servers or something (assuming the backup file names correspond to the server names)) and then check the files that were created and output the missing ones for triage.

Here is a modification to your script (essentially the opposite of what you did) that might point you in the right direction:

## List of expected files
$ExpectedFiles = @(
    'File1.bak',
    'File2.bak',
    'File3.bak',
    'File4.bak'
    '...'
)

## Get a list of created files
$list = Get-ChildItem -Path network_path_to_share -Recurse -File | Where-Object {$_.DirectoryName -like '*FULL*' -and $_.LastWriteTime -ge (Get-Date).AddDays(-6)} | Select -ExpandProperty Name

## Check whether each expected file exists in the array of backups that actually were created
foreach ($file in $ExpectedFiles) {
    if (-not(Test-Path $list)) {
        "$($file) is missing!"
    }
}


问:
Webpack - any sort of async call stops all the js
I'm running webpack and this is all the js I have in my app.js file:

```<code>import '../styles/index.scss';
console.log('test');
</code>```

The console.log is working in the browser. If now I add any sort of asynchronous call (I tried fetch() and axios) the console is no longer working in the browser and I have NO idea why.

```<code>import '../styles/index.scss';
import axios from 'axios';

console.log('test');

axios.get('http://webcode.me').then(resp => {
    console.log(resp.data);
});
</code>```

答: For anyone getting here using Django, you need to use django-webpack-loader to import the generated bundle: https://github.com/django-webpack/django-webpack-loader</p>

Body:
I'm running webpack and this is all the js I have in my app.js file:

import '../styles/index.scss';
console.log('test');

The console.log is working in the browser. If now I add any sort of asynchronous call (I tried fetch() and axios) the console is no longer working in the browser and I have NO idea why.

import '../styles/index.scss';
import axios from 'axios';

console.log('test');

axios.get('http://webcode.me').then(resp => {
    console.log(resp.data);
});


问:
BigQuery for running count of distinct values with a dynamic date-range
We are trying to make a query where we get the sum of unique customers on a specific year-month + the sum of unique customers on the 364 days before the specific date.

For example:

Our customer-table looks like this:

```<code>| order_date   | customer_unique_id |
| --------     | --------------     |
| 2020-01-01   | tom@email.com      |
| 2020-01-01   | daisy@email.com    |
| 2019-05-02   | tom@email.com      |
</code>```

In this example we have two customers who ordered on 2020-01-01 and one of them already ordered within the 364-days timeframe.

The desired table should look like this:

```<code>| year_month | unique_customers |
| --------   | --------------   |
| 2020-01    | 2                |
</code>```

We tried multiple solutions, such as partitioning and windows, but nothing seem to work correctly. The tricky part is the uniqueness. We want the look 364 days back but want to do a count distinct on the customers based on that whole period and not based on date/year/month because then we would get duplicates. For example, if you partition by date, year or month tom@email.com would be counted twice instead of once.

The goal of this query is to get insight into the order-frequency (orders divided by customers) over a time period from 12 months.

We work with Google BigQuery.

Hope someone can help us out! :)

答:
Here is a way to achieve your desired results. Note that this query does year-month join in a separate query, and joins it with the rolling 364-day-interval query.</p>
```<code>with year_month_distincts as (
    select
        concat(
           cast(extract(year from order_date) as string),
           '-',
           cast(extract(month from order_date) as string)
        ) as year_month,
        count(distinct customer_id) as ym_distincts
    from customer_table
    group by 1
)

select x.order_date, x.ytd_distincts, y.ym_distincts from (
    select
       a. order_date,
       (select
           count(distinct customer_id)
        from customer_table b
        where b.order_date between date_sub(a.order_date, interval 364 day) and a.order_date
       ) as ytd_distincts
    from orders a
    group by 1
) x
join year_month_distincts y on concat(
   cast(extract(year from x.order_date) as string),
   '-',
   cast(extract(month from x.order_date) as string)
) = y.year_month
</code>```

Body:
We are trying to make a query where we get the sum of unique customers on a specific year-month + the sum of unique customers on the 364 days before the specific date.

For example:

Our customer-table looks like this:

| order_date   | customer_unique_id |
| --------     | --------------     |
| 2020-01-01   | tom@email.com      |
| 2020-01-01   | daisy@email.com    |
| 2019-05-02   | tom@email.com      |

In this example we have two customers who ordered on 2020-01-01 and one of them already ordered within the 364-days timeframe.

The desired table should look like this:

| year_month | unique_customers |
| --------   | --------------   |
| 2020-01    | 2                |

We tried multiple solutions, such as partitioning and windows, but nothing seem to work correctly. The tricky part is the uniqueness. We want the look 364 days back but want to do a count distinct on the customers based on that whole period and not based on date/year/month because then we would get duplicates. For example, if you partition by date, year or month tom@email.com would be counted twice instead of once.

The goal of this query is to get insight into the order-frequency (orders divided by customers) over a time period from 12 months.

We work with Google BigQuery.

Hope someone can help us out! :)

Body:
Here is a way to achieve your desired results. Note that this query does year-month join in a separate query, and joins it with the rolling 364-day-interval query.

with year_month_distincts as (
    select
        concat(
           cast(extract(year from order_date) as string),
           '-',
           cast(extract(month from order_date) as string)
        ) as year_month,
        count(distinct customer_id) as ym_distincts
    from customer_table
    group by 1
)

select x.order_date, x.ytd_distincts, y.ym_distincts from (
    select
       a. order_date,
       (select
           count(distinct customer_id)
        from customer_table b
        where b.order_date between date_sub(a.order_date, interval 364 day) and a.order_date
       ) as ytd_distincts
    from orders a
    group by 1
) x
join year_month_distincts y on concat(
   cast(extract(year from x.order_date) as string),
   '-',
   cast(extract(month from x.order_date) as string)
) = y.year_month


问:
PhpMyAdmin not working on localhost
Xampp version:1.7.7 (installed it on external hard drive), operating system: Windows 8,
installed version 4.1.7 of phpMyAdmin and copied config.inc.php from my old version of phpmyadmin to the new phpmyadmin version (4.1.7)

When I type localhost/phpMyAdmin I get the error message:

Object not found!

The requested URL was not found on this server. If you entered the URL
  manually please check your spelling and try again.

If you think this is a server error, please contact the webmaster.
  Error 404 localhost 02/13/14 17:16:55 Apache/2.2.21 (Win32)
  mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8

So I had a look in the xampp localhost welcome page http://pngwebdesign.co.uk/forum/localhost.jpg and in the security link PhpMyAdmin: Could not find the 'config.inc.php' comes up, how can this be recified

Looked in my local phpmyadmin folder and the config.inc.php file is there so I really don't understand why I can't log into localhost/phpMyAdmin

Any help appreciated

答:
Try to navigate below URL .this workes to me

http://localhost/phpmyadmin/index.php

ContentLicense: CC BY-SA 3.0

Title: PhpMyAdmin not working on localhost


问:
Emitting states from a bloc using bloc.emit
I'm building a phone authentication ui (OTP) using firebase_auth library with BLoC pattern (a bit of an overkill for this ui, but the whole project is in BLoC, so). I'm processing the authentication within the BLoC, as such:

```<code>
  @override
  Stream<PhoneAuthState> mapEventToState(PhoneAuthEvent event) async* {
    ....
    else if(event is PhoneNumberSubmittedEvent) yield* _handlePhoneNumberSubmittedEvent(event);
    ....
  }

  Stream<PhoneAuthState> _handlePhoneNumberSubmittedEvent(PhoneNumberSubmittedEvent event) async*{
      yield SendingCodeState();

      await Firebase.initializeApp();
      var firebaseAuth = FirebaseAuth.instance;

      await firebaseAuth.verifyPhoneNumber(
        phoneNumber: _buildPhoneNumber(),
        timeout: Duration(seconds: 0),
        verificationCompleted: (firebaseUser) {},
        codeAutoRetrievalTimeout: (String verificationId) {},

        // Relevant code

        codeSent: (id, [forceResendingToken]) =>
          emit(_codeSentState(id, forceResendingToken)),

        verificationFailed: (error) =>
          emit(_verificationFailedState(error)),
      );
  }

</code>```

Because the results of my _codeSentState and _verificationFailedState functions cannot be yielded from within the handlePhoneNumberSubmittedEvent method, I used emit (which is actually working fine).

However, as I was looking through BLoC docs, I found that emit is @protected, and the docs stating:

[emit] should never be used outside of tests.

So I have three questions:

Why shouldn't emit be used outside of tests?

Is there an alternative to emit? (other than yielding in response to events in mapEventToState)

Is there a way to yield the result of a function that is passed as a parameter to a method/constructor call? (in my case, is there a way to yield the results of _codeSentState and/or _verificationFailedState that are called within firebaseAuth.verifyPhoneNumber.codeSent and firebaseAuth.verifyPhoneNumber.verificationFailed respectively?)

答:
In flutter_bloc version 8.0.0, this issue was resolved. The method mapEventToState was replaced with the more efficient on<Event> to respond to events. on method provides an emitter as a parameter to its callback, which can be used to emit states as needed. In other words, the code I mentioned in OP can now be written as follows

```<code>// constructor
MyBloc() : super(MyInitialState) {
  on<PhoneNumberSubmittedEvent>((event, emit) async {
      emit(SendingCodeState());

      await Firebase.initializeApp();
      var firebaseAuth = FirebaseAuth.instance;

      await firebaseAuth.verifyPhoneNumber(
        phoneNumber: _buildPhoneNumber(),
        timeout: Duration(seconds: 0),
        verificationCompleted: (firebaseUser) {},
        codeAutoRetrievalTimeout: (String verificationId) {},

        codeSent: (id, [forceResendingToken]) =>
          emit(_codeSentState(id, forceResendingToken)),

        verificationFailed: (error) =>
          emit(_verificationFailedState(error)),
      );
  });
}
</code>```

Body:
I'm building a phone authentication ui (OTP) using firebase_auth library with BLoC pattern (a bit of an overkill for this ui, but the whole project is in BLoC, so). I'm processing the authentication within the BLoC, as such:

  @override
  Stream<PhoneAuthState> mapEventToState(PhoneAuthEvent event) async* {
    ....
    else if(event is PhoneNumberSubmittedEvent) yield* _handlePhoneNumberSubmittedEvent(event);
    ....
  }

  Stream<PhoneAuthState> _handlePhoneNumberSubmittedEvent(PhoneNumberSubmittedEvent event) async*{
      yield SendingCodeState();

      await Firebase.initializeApp();
      var firebaseAuth = FirebaseAuth.instance;

      await firebaseAuth.verifyPhoneNumber(
        phoneNumber: _buildPhoneNumber(),
        timeout: Duration(seconds: 0),
        verificationCompleted: (firebaseUser) {},
        codeAutoRetrievalTimeout: (String verificationId) {},

        // Relevant code

        codeSent: (id, [forceResendingToken]) =>
          emit(_codeSentState(id, forceResendingToken)),

        verificationFailed: (error) =>
          emit(_verificationFailedState(error)),
      );
  }

Because the results of my _codeSentState and _verificationFailedState functions cannot be yielded from within the handlePhoneNumberSubmittedEvent method, I used emit (which is actually working fine).

However, as I was looking through BLoC docs, I found that emit is @protected, and the docs stating:

[emit] should never be used outside of tests.

So I have three questions:

Why shouldn't emit be used outside of tests?

Is there an alternative to emit? (other than yielding in response to events in mapEventToState)

Is there a way to yield the result of a function that is passed as a parameter to a method/constructor call? (in my case, is there a way to yield the results of _codeSentState and/or _verificationFailedState that are called within firebaseAuth.verifyPhoneNumber.codeSent and firebaseAuth.verifyPhoneNumber.verificationFailed respectively?)

Body:
In flutter_bloc version 8.0.0, this issue was resolved. The method mapEventToState was replaced with the more efficient on<Event> to respond to events. on method provides an emitter as a parameter to its callback, which can be used to emit states as needed. In other words, the code I mentioned in OP can now be written as follows

// constructor
MyBloc() : super(MyInitialState) {
  on<PhoneNumberSubmittedEvent>((event, emit) async {
      emit(SendingCodeState());

      await Firebase.initializeApp();
      var firebaseAuth = FirebaseAuth.instance;

      await firebaseAuth.verifyPhoneNumber(
        phoneNumber: _buildPhoneNumber(),
        timeout: Duration(seconds: 0),
        verificationCompleted: (firebaseUser) {},
        codeAutoRetrievalTimeout: (String verificationId) {},

        codeSent: (id, [forceResendingToken]) =>
          emit(_codeSentState(id, forceResendingToken)),

        verificationFailed: (error) =>
          emit(_verificationFailedState(error)),
      );
  });
}


问:
CSS Display: inline-block but Stack Divs only if they overlap
I have the following divs below:

.parent {
  padding: 10px;
  background: grey;
}

.child {
  background: green;
  display: block;
  position: relative;
  width: 50px;
}

.stacked {
  left: 0px;
}

.three {
  left: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child stacked">div1</div>
  <div class="child stacked">div2</div>
  <div class="child three">div3</div>
</div></code>```

This looks like the following:

I would like divs 1 and 2 to stack as they do, but since div3 does not collide with the divs above, I'd like it to vertically aline with div 1.

If I switch display to inline or inline-block, it pushes div 2 to the right of div one. and the left values are not accurate to the parant.

The left values of the divs will be dynamically generated so I cannot know if the divs are overlapping or not.

Is this possible?

答:
Try this :
wrap div3 item in another div and give it a class property of flex-container.

```<code>.flex-container {
  align-content: flex-start;
}
</code>```

Ensure the flex direction is horizontal.

Body:
I have the following divs below:

.parent {
  padding: 10px;
  background: grey;
}

.child {
  background: green;
  display: block;
  position: relative;
  width: 50px;
}

.stacked {
  left: 0px;
}

.three {
  left: 200px;
}

div1

div2

div3

This looks like the following:

I would like divs 1 and 2 to stack as they do, but since div3 does not collide with the divs above, I'd like it to vertically aline with div 1.

If I switch display to inline or inline-block, it pushes div 2 to the right of div one. and the left values are not accurate to the parant.

The left values of the divs will be dynamically generated so I cannot know if the divs are overlapping or not.

Is this possible?

Body:
Try this :
wrap div3 item in another div and give it a class property of flex-container.

.flex-container {
  align-content: flex-start;
}

Ensure the flex direction is horizontal.


问:
Fast writing bytearray to file
I use _FileStream.Write(_ByteArray, 0, _ByteArray.Length); to write a bytearray to a file. I noticed that's very slow.
I read a line from a text file, convert it to a bytearray and then need to write it to a new (large > 500 Mb) file. Please some advice to speed up the write process.

答:
If your writing nothing but Byte arrays, have you tried using BinaryWriter's Write method? Writing in bulk would probably also help with the speed. Perhaps you can read each line, convert the string to its bytes, store those bytes for a future write operation (i.e in a List or something), and every so often (after reading x lines) write a chunk to the disk.

BinaryWriter: http://msdn.microsoft.com/en-us/library/ms143302.aspx

Title: Fast writing bytearray to file


问:
Convert written number to number in R
Does anybody know a function to convert a text representation of a number into an actual number, e.g. 'twenty thousand three hundred and five' into 20305. I have written numbers in dataframe rows and want to convert them to numbers.

In package qdap, you can replace numeric represented numbers with words (e.g., 1001 becomes one thousand one), but not the other way around:

```<code>library(qdap)
replace_number("I like 346457 ice cream cones.")
[1] "I like three hundred forty six thousand four hundred fifty seven ice cream cones."
</code>```

答:
I wrote an R package to do this a few years back, https://github.com/fsingletonthorn/words_to_numbers, which works for numbers up to the decillions.

```<code>devtools::install_github("fsingletonthorn/words_to_numbers")

library(wordstonumbers)

example_input <- "twenty thousand three hundred and five"

words_to_numbers(example_input)

[1] "20305"

</code>```

It also works for much more complex cases similar to those included in the qdap example:

```<code>words_to_numbers('I like three hundred forty six thousand four hundred fifty seven ice cream cones.')
[1] "I like 346457 ice cream cones."
</code>```

Title: Convert written number to number in R

Body:
Does anybody know a function to convert a text representation of a number into an actual number, e.g. 'twenty thousand three hundred and five' into 20305. I have written numbers in dataframe rows and want to convert them to numbers.

In package qdap, you can replace numeric represented numbers with words (e.g., 1001 becomes one thousand one), but not the other way around:

library(qdap)
replace_number("I like 346457 ice cream cones.")
[1] "I like three hundred forty six thousand four hundred fifty seven ice cream cones."

Body:
I wrote an R package to do this a few years back, https://github.com/fsingletonthorn/words_to_numbers, which works for numbers up to the decillions.

devtools::install_github("fsingletonthorn/words_to_numbers")

library(wordstonumbers)

example_input <- "twenty thousand three hundred and five"

words_to_numbers(example_input)

[1] "20305"

It also works for much more complex cases similar to those included in the qdap example:

words_to_numbers('I like three hundred forty six thousand four hundred fifty seven ice cream cones.')
[1] "I like 346457 ice cream cones."


问:
Django rest framework override page_size in ViewSet
I am having problem with django rest framework pagination.
I have set pagination in settings like -

```<code>'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1
</code>```

Below is my viewset.

```<code>class HobbyCategoryViewSet(viewsets.ModelViewSet):
    serializer_class = HobbyCategorySerializer
    queryset = UserHobbyCategory.objects.all()
</code>```

I want to set different page size for this viewset. I have tried setting page_size and Paginate_by class variables but list is paginated according to PAGE_SIZE defined in settings. Any idea where I am wrong ?

答:
settings.py

```<code>REST_FRAMEWORK = {
  #'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
  #'PAGE_SIZE':10
}
</code>```

these settings will affect every endpoints  better to remove both settings from settings.py

views.py

```<code>from .pagination import DefaultPagination

class ProductViewSet(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    pagination_class = DefaultPagination
</code>```

pagination.py

```<code>from rest_framework.pagination import PageNumberPagination

class DefaultPagination(PageNumberPagination):
    page_size = 10
</code>```

Body:
I am having problem with django rest framework pagination.
I have set pagination in settings like -

'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 1

Below is my viewset.

class HobbyCategoryViewSet(viewsets.ModelViewSet):
    serializer_class = HobbyCategorySerializer
    queryset = UserHobbyCategory.objects.all()

I want to set different page size for this viewset. I have tried setting page_size and Paginate_by class variables but list is paginated according to PAGE_SIZE defined in settings. Any idea where I am wrong ?

Body:
settings.py

REST_FRAMEWORK = {
  #'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
  #'PAGE_SIZE':10
}

these settings will affect every endpoints  better to remove both settings from settings.py

views.py

from .pagination import DefaultPagination

class ProductViewSet(ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    pagination_class = DefaultPagination

pagination.py

from rest_framework.pagination import PageNumberPagination

class DefaultPagination(PageNumberPagination):
    page_size = 10


答:
Edit: If you really want to align the 3rd div using positioning, then you can do it like so:

.parent {
  padding: 10px;
  background: grey;
  position: relative;
}

.child {
  background: green;
  display: block;
  position: relative;
  width: 50px;
}

.stacked {
  position: relative;
  left: 0px;
}

.three {
  position: absolute;
  left: 200px;
  top: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child stacked">div1</div>
  <div class="child stacked">div2</div>
  <div class="child three">div3</div>
</div></code>```

You can use the column-count property like so:

.parent {
  padding: 10px;
  background: grey;
  column-count: 2;
}

.child {
  background: green;
  display: block;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
</div></code>```

Or you can use flexbox to wrap vertically, like so:

.parent {
  padding: 10px;
  background: grey;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 50px;
}

.child {
  background: green;
  display: block;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
</div></code>```

Here's using grid:

.parent {
  padding: 10px;
  background: grey;
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: 1fr 1fr;
}

.child {
  background: green;
  display: block;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
</div></code>```

Title: CSS Display: inline-block but Stack Divs only if they overlap

Body:
Edit: If you really want to align the 3rd div using positioning, then you can do it like so:

.parent {
  padding: 10px;
  background: grey;
  position: relative;
}

.child {
  background: green;
  display: block;
  position: relative;
  width: 50px;
}

.stacked {
  position: relative;
  left: 0px;
}

.three {
  position: absolute;
  left: 200px;
  top: 10px;
}

<div class="parent">
  <div class="child stacked">div1</div>
  <div class="child stacked">div2</div>
  <div class="child three">div3</div>
</div>

You can use the column-count property like so:

.parent {
  padding: 10px;
  background: grey;
  column-count: 2;
}

.child {
  background: green;
  display: block;
  width: 50px;
}

<div class="parent">
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
</div>

Or you can use flexbox to wrap vertically, like so:

.parent {
  padding: 10px;
  background: grey;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 50px;
}

.child {
  background: green;
  display: block;
  width: 50px;
}

<div class="parent">
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
</div>

Here's using grid:

.parent {
  padding: 10px;
  background: grey;
  display: grid;
  grid-auto-flow: column;
  grid-template-rows: 1fr 1fr;
}

.child {
  background: green;
  display: block;
  width: 50px;
}

<div class="parent">
  <div class="child">div1</div>
  <div class="child">div2</div>
  <div class="child">div3</div>
</div>


问:
Finding Number of pages from the total number of digits used to number the pages
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.

(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).

I tried it by using a while loop but it does not run as it exceeds the execution time.

My C code looks like this:

```<code>#include <stdio.h>

int main() {
    int n, pages = 9;
    scanf("%d", &n);

    if (n <= 9) {
        printf("%d",n);
    }
    else if (n % 2 == 0) {
        printf("Invalid input");
    }
    else {
        while (n < 9) {
            pages++;
            n -= 2;
        }
    }
    return 0;
}
</code>```

Can anyone please help me with this problem?

答:
In your posts body you do not ask a question (apart from "Can somebody help me?", which is not considered a question here). In your comments you ask for the main() function, or the logic, or the pseudo code. Sorry, that is not how StackOverflow is meant to be used.

But finally you ask how to arrive at the needed formula.

With How do I ask and answer homework questions? in mind I will help you with that.

make a table of the simplest case (1,2,3,4,5,6,7,8,9) pages and digits, the same

find the formula for that

check the next complex case (10,11,12,13,14,...99) pages and digits, there is a very simple relation

consider which influence the pages 1...9 have on the formula, think offset

consider the next complex case (100, 101, .... 999)

and proceed to the mentioned limit of 2 billion pages

Body:
I am stuck in a problem where the user inputs the total number of digits used in numbering the pages and the program gives the total number of pages in the book.

(i.e. a book of 10 pages needs 11 digits to number because the numbers 1-9 are written with one digit and the number 10 is written with two digits; an 11 pages book requires 13 digits ...).

I tried it by using a while loop but it does not run as it exceeds the execution time.

My C code looks like this:

#include <stdio.h>

int main() {
    int n, pages = 9;
    scanf("%d", &n);

    if (n <= 9) {
        printf("%d",n);
    }
    else if (n % 2 == 0) {
        printf("Invalid input");
    }
    else {
        while (n < 9) {
            pages++;
            n -= 2;
        }
    }
    return 0;
}

Can anyone please help me with this problem?


问:
Can we create Sitemap for private routes in react application?
I have created a Sitemap.xml file in my react application using react-router-sitemap package from npm.
I'm new to this SEO and Google search console, it got an indexing error in GSC. that's y I created the sitemap.
I've  created sitemap file using the public routes in my site, but I'm not sure if we need to include private routes. I'm almost 100% sure that private routes cannot / shouldn't be crawled by google bots but wanted to make sure.</p>

答: Sitemap shouldn't include private routes. Even if you include them it is of no use.</p>


问:
LINQ vs context.entity.Where()
Are these two blocks exactly the same? Does one have any advantage over the other?</p>

```<code>        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }
</code>```

答:
From Julia Lermans' book Programming Entity Framework:

The MSDN documentation says, “In general, we recommend query syntax
  because it is usually simpler and more readable; however, there is no
  semantic difference between method syntax and query syntax.”*
  Therefore, using one over the other is a matter of style and personal
  choice.

Title: LINQ vs context.entity.Where()

Body:
Are these two blocks exactly the same? Does one have any advantage over the other?

        using (var context = new TRANSITEntities())
        {
            var result = context.Table1.Where(c => c.UserCode == "123");
        }

        using (var context = new TRANSITEntities())
        {
            var result = from c in context.Table1
                         where c.UserCode == "123"
                         select c;
        }


问:
How would I grow <TextInput> height upon text wrapping?
I'm trying to create a <TextInput> that can grow in height when the text wraps to the next line, similar to how Slack's message input grows with the text up to a point.

I have the multiline prop set, so it is wrapping but the docs don't seem to mention any event regarding wrapping, and the only thing I can think of is a really hacky strategy to character count to figure out when to increase height of the input. How would I accomplish this?
https://facebook.github.io/react-native/docs/textinput.html

答:
Just use multiline={true} no need to set height. check the following</p>
```<code><SafeAreaView style={{flex:1, backgroundColor:"#F8F8F9"}}>
        <ScrollView style={{flex:1}}>
            {
                this.state.data && <CommentListView data={this.state.data} onReplyClick={this.onReplyClick}/>
            }
        </ScrollView>
        <View style={{bottom:Platform.OS=="ios" ? this.state.keyboardHeight : 0, flexDirection:"row", alignItems:"flex-end", padding:10}}>
            <TextInput
            multiline={true}
            style={{flex:3, backgroundColor:"#EFEFEF", borderRadius:5, padding:10}}
            value={this.state.comment}
            onChangeText={(text)=> this.setState({comment:text})}
            />
            <TouchableOpacity style={{flex:1}} onPress={()=> this.submit()}>
                <Text style={{padding:13, color:"#fff", textAlign:"center", fontWeight:"bold", backgroundColor:"#00394D", borderWidth:1, borderColor:"#00FFEE", borderRadius:5, overflow: "hidden"}}>Post</Text>
            </TouchableOpacity>
        </View>
    </SafeAreaView>
</code>```

Body:
Just use multiline={true} no need to set height. check the following

<SafeAreaView style={{flex:1, backgroundColor:"#F8F8F9"}}>
        <ScrollView style={{flex:1}}>
            {
                this.state.data && <CommentListView data={this.state.data} onReplyClick={this.onReplyClick}/>
            }
        </ScrollView>
        <View style={{bottom:Platform.OS=="ios" ? this.state.keyboardHeight : 0, flexDirection:"row", alignItems:"flex-end", padding:10}}>
            <TextInput
            multiline={true}
            style={{flex:3, backgroundColor:"#EFEFEF", borderRadius:5, padding:10}}
            value={this.state.comment}
            onChangeText={(text)=> this.setState({comment:text})}
            />
            <TouchableOpacity style={{flex:1}} onPress={()=> this.submit()}>
                <Text style={{padding:13, color:"#fff", textAlign:"center", fontWeight:"bold", backgroundColor:"#00394D", borderWidth:1, borderColor:"#00FFEE", borderRadius:5, overflow: "hidden"}}>Post</Text>
            </TouchableOpacity>
        </View>
    </SafeAreaView>


问:
[Jenkin][MacServer] Jenkin not accessible remotely
I setup Jenkin on Mac-server and able to do build locally for both iOS and Android source code.

I am facing issue while accessing the Jenkin's on remote machine(Same Mac server) from home. Mac-Server is ping-able from Home but Jenkin's is not accessible.

We found out that to able to access the Jenkin's we always need to enable screen sharing. Login to screen sharing is not needed just connecting(IP Address of remote mac server) enables Jenkin's to be accessible.

System Details below

Mac server OS version : macOS Big Sur 11.2.3

Jenkins version: 2.319.2

Jenkins installed via Homebrew

Any support/guidance will be highly appreciated.

答:
Amit, check if the MAC server is not in sleep mode. You can check this under System Preferences->Energy Saver option. Select the first checkbox if it is not selected "Prevent computer from sleeping automatically when the display is off".

This should resolve the connectivity issue with MAC server without the need to use screen sharing.


问:
Dart - Call Named Constructor using super vs class name
```<code>class Person {
  late String name;
  late int age;
  Person();
  Person.ap(this.name, this.age);
}

class Employee extends Person {
  Employee(String name, int age) : super.ap(name, age); // This works

  // This is giving error. The method 'ap' isn't defined in a superclass of 'Employee'.
  Employee(String name, int age) {
    super.ap(name, age);
  }
}
</code>```

What's the difference of calling unnamed constructor using super or inside the parenthesis?

答:
try this, just create a setter function named ap in the Person class

     class Person {
          late String name;
          late int age;
          Person();
          Person.ap(this.name, this.age);

          ap(String name, int age){ //add this
              this.name=name;
              this.age=age;
            }
        }

        class Employee extends Person {

          //here ap is name constructor
          Employee(String name, int age) : super.ap(name, age);

          //here ap is setter function in the person class
          Employee.ap(String name, int age) {
            super.ap(name, age);
          }
        }
```

Body:
class Person {
  late String name;
  late int age;
  Person();
  Person.ap(this.name, this.age);
}

class Employee extends Person {
  Employee(String name, int age) : super.ap(name, age); // This works

  // This is giving error. The method 'ap' isn't defined in a superclass of 'Employee'.
  Employee(String name, int age) {
    super.ap(name, age);
  }
}

What's the difference of calling unnamed constructor using super or inside the parenthesis?


问:
How do you reload an iframe with ReactJS?
My ReactJS component contains an iframe. In response to an event in the outer page, I need to reload the iframe. If the user has navigated to another page in the iframe, I need to reset it to the URL that it had when I first loaded the page. This URL is available in this.props.

I've tried using forceUpdate(). I can see that this causes the render method to run, but the iframe doesn't get reset - presumably because React can't tell that anything has changed.

At the moment I'm appending some random text to the iframe's querystring: this URL change forces React to re-render the iframe. However this feels a bit dirty: the page within the iframe is beyond my control so who knows what this extra querystring value might do?

```<code>resetIframe() {
    console.log("==== resetIframe ====");
    this.forceUpdate();
}

public render() {
    console.log("==== render ====");

    // How can I use just this.props.myUrl, without the Math.random()?
    let iframeUrl = this.props.myUrl + '&random=' + Math.random().toString();

    return <div>
        <button onClick={() => { this.resetIframe(); }}>Reset</button>
        <iframe src={iframeUrl}></iframe>
    </div>
}
</code>```

(I'm using TypeScript too, if that makes a difference.)

答:
```<code>    <iframe key={props.location.key} />
</code>```

use This "Router location Key" each click will get random value, whenever to navigate to here this value will get change then iframe will get the refresh

Body:
My ReactJS component contains an iframe. In response to an event in the outer page, I need to reload the iframe. If the user has navigated to another page in the iframe, I need to reset it to the URL that it had when I first loaded the page. This URL is available in this.props.

I've tried using forceUpdate(). I can see that this causes the render method to run, but the iframe doesn't get reset - presumably because React can't tell that anything has changed.

At the moment I'm appending some random text to the iframe's querystring: this URL change forces React to re-render the iframe. However this feels a bit dirty: the page within the iframe is beyond my control so who knows what this extra querystring value might do?

resetIframe() {
    console.log("==== resetIframe ====");
    this.forceUpdate();
}

public render() {
    console.log("==== render ====");

    // How can I use just this.props.myUrl, without the Math.random()?
    let iframeUrl = this.props.myUrl + '&random=' + Math.random().toString();

    return

        <button onClick={() => { this.resetIframe(); }}>Reset</button>

}

(I'm using TypeScript too, if that makes a difference.)

Body:
    <iframe key={props.location.key} />

use This "Router location Key" each click will get random value, whenever to navigate to here this value will get change then iframe will get the refresh


问:
How can I use gvim to add a carriage return (aka ENTER) to a pattern?
What's the vi/gvim syntax to replace a pattern with a pattern that includes <ENTER>?  I know this is possible but never felt like diving too deep in the documentation to know how to do it.

Something like this:

```<code> :s/\(word\)/\1<ENTER>/
</code>```

But correctly :)

Thanks

答:
```<code>:s/\(word\)/\1\r/
</code>```

Alternatively, use Ctrl+V or Ctrl+Q to quote (escape) the Enter key:

```<code>:s/\(word\)\1^QENTER/
</code>```

Where ^Q is Ctrl+Q and ENTER is the Enter key.

Clarification:  Depending on your installation, either ^Q or ^V should work.  The quoting character differs on some platforms.

(This has the helpful side-effect of inserting the appropriate end-of-line character for whichever platform you're using, eliminating the CR vs. LF vs. CRLF problem.)

OwnerDisplayName: Oscar Reyes

ContentLicense: CC BY-SA 2.5

Body:
What's the vi/gvim syntax to replace a pattern with a pattern that includes <ENTER>?  I know this is possible but never felt like diving too deep in the documentation to know how to do it.

Something like this:

 :s/\(word\)/\1<ENTER>/

But correctly :)

Thanks

LastEditorDisplayName: Chad Birch

Body:
:s/\(word\)/\1\r/

Alternatively, use Ctrl+V or Ctrl+Q to quote (escape) the Enter key:

:s/\(word\)\1^QENTER/

Where ^Q is Ctrl+Q and ENTER is the Enter key.

Clarification:  Depending on your installation, either ^Q or ^V should work.  The quoting character differs on some platforms.

(This has the helpful side-effect of inserting the appropriate end-of-line character for whichever platform you're using, eliminating the CR vs. LF vs. CRLF problem.)

OwnerDisplayName: Adam Liss

LastEditorDisplayName: Adam Liss


问:
Snowflake Replace to joins with group by clause with single join
I have to take the LATEST CLICK as the latest date for that ID where the Event_Type is click. And do the similar thing for Event_Type = 'open'. I have the data like :

Id
Event_Type
SRC_CREATED

1
click
2021-04-10 01:50:08.490

1
click
2021-03-10 02:221:05.115

1
open
2021-06-10 01:12:08.288

1
click
2021-08-10 01:50:08.490

Outcome required :

Id
Event_Type
SRC_CREATED

1
click
2021-08-10 01:50:08.490

1
open
2021-06-10 01:12:08.288

I have used the query mentioned below, which is working fine, but I want to replace the 2 somehow joins used with a single join to fetch both these data. Can anyone think of a workaround query for that?

```<code>CREATE OR REPLACE table CUSTOMER AS
select CONCAT(NVL(ADD1,''),NVL(ADD2,'')) AS ADDRESS,
    CASE
WHEN NVL(GENDER,'')='F' THEN 'Female'
WHEN NVL(GENDER,'')='M' THEN 'Male'
WHEN NVL(GENDER,'')='U' Then 'Other'
ELSE ''
END AS GENDER,
***CLICK AS LAST_CLICK,
OPENS AS LAST_EMAIL_CLICK,***
B.PHONE AS PHONE,
A.SRC_CREATED AS SINCE,
from "HXP_SANDBOX"."BASE_RA_TEST"."IDENTITY" A
inner join "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" B
on A.DIGITALID = B.DIGITALID
***inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) CLICK
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'click'
 group by DIGITALID) C
on A.DIGITALID = C.DIGITALID
inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) OPENS
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'open'
 group by DIGITALID) D
on A.DIGITALID = D.DIGITALID;***
</code>```

答:
You should be able to do the following, where you use a CASE inside the MAX to restrict it to the event types you want.

```<code>CREATE OR REPLACE TABLE CUSTOMER
AS
SELECT CONCAT(NVL(ADD1,''), NVL(ADD2,'')) AS [ADDRESS]
    , CASE
        WHEN NVL(GENDER,'')='F' THEN 'Female'
        WHEN NVL(GENDER,'')='M' THEN 'Male'
        WHEN NVL(GENDER,'')='U' Then 'Other'
        ELSE ''
    END AS GENDER
    , C.CLICK AS LAST_CLICK
    , C.OPENS AS LAST_EMAIL_CLICK
    , B.PHONE AS PHONE
    , A.SRC_CREATED AS SINCE
FROM "HXP_SANDBOX"."BASE_RA_TEST"."IDENTITY" A
INNER JOIN "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" B ON A.DIGITALID = B.DIGITALID
INNER JOIN (
    SELECT DIGITALID
      , MAX(CASE WHEN EVENT_TYPE = 'click' THEN SRC_CREATED ELSE NULL END) CLICK
      , MAX(CASE WHEN EVENT_TYPE = 'open' THEN SRC_CREATED ELSE NULL END) OPENS
    FROM "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
    GROUP BY DIGITALID
) C ON A.DIGITALID = C.DIGITALID;
</code>```

Body:
I have to take the LATEST CLICK as the latest date for that ID where the Event_Type is click. And do the similar thing for Event_Type = 'open'. I have the data like :

Id
Event_Type
SRC_CREATED

1
click
2021-04-10 01:50:08.490

1
click
2021-03-10 02:221:05.115

1
open
2021-06-10 01:12:08.288

1
click
2021-08-10 01:50:08.490

Outcome required :

Id
Event_Type
SRC_CREATED

1
click
2021-08-10 01:50:08.490

1
open
2021-06-10 01:12:08.288

I have used the query mentioned below, which is working fine, but I want to replace the 2 somehow joins used with a single join to fetch both these data. Can anyone think of a workaround query for that?

CREATE OR REPLACE table CUSTOMER AS
select CONCAT(NVL(ADD1,''),NVL(ADD2,'')) AS ADDRESS,
    CASE
WHEN NVL(GENDER,'')='F' THEN 'Female'
WHEN NVL(GENDER,'')='M' THEN 'Male'
WHEN NVL(GENDER,'')='U' Then 'Other'
ELSE ''
END AS GENDER,
***CLICK AS LAST_CLICK,
OPENS AS LAST_EMAIL_CLICK,***
B.PHONE AS PHONE,
A.SRC_CREATED AS SINCE,
from "HXP_SANDBOX"."BASE_RA_TEST"."IDENTITY" A
inner join "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" B
on A.DIGITALID = B.DIGITALID
***inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) CLICK
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'click'
 group by DIGITALID) C
on A.DIGITALID = C.DIGITALID
inner JOIN (SELECT DIGITALID,MAX(SRC_CREATED) OPENS
 from "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
  where EVENT_TYPE = 'open'
 group by DIGITALID) D
on A.DIGITALID = D.DIGITALID;***

Body:
You should be able to do the following, where you use a CASE inside the MAX to restrict it to the event types you want.

CREATE OR REPLACE TABLE CUSTOMER
AS
SELECT CONCAT(NVL(ADD1,''), NVL(ADD2,'')) AS [ADDRESS]
    , CASE
        WHEN NVL(GENDER,'')='F' THEN 'Female'
        WHEN NVL(GENDER,'')='M' THEN 'Male'
        WHEN NVL(GENDER,'')='U' Then 'Other'
        ELSE ''
    END AS GENDER
    , C.CLICK AS LAST_CLICK
    , C.OPENS AS LAST_EMAIL_CLICK
    , B.PHONE AS PHONE
    , A.SRC_CREATED AS SINCE
FROM "HXP_SANDBOX"."BASE_RA_TEST"."IDENTITY" A
INNER JOIN "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" B ON A.DIGITALID = B.DIGITALID
INNER JOIN (
    SELECT DIGITALID
      , MAX(CASE WHEN EVENT_TYPE = 'click' THEN SRC_CREATED ELSE NULL END) CLICK
      , MAX(CASE WHEN EVENT_TYPE = 'open' THEN SRC_CREATED ELSE NULL END) OPENS
    FROM "HXP_SANDBOX"."BASE_RA_TEST"."EMAIL_INTERACTIONS" t
    GROUP BY DIGITALID
) C ON A.DIGITALID = C.DIGITALID;


问:
Listen to real-time changes in Flutter SQFLite Database
I have a fully functional app created in Flutter. It uses sqflite plugin for storing data. I want to have a data change listener, which will update or refresh the data when new data is added or updated. How can I achieve this. I came across a sqflite helper plugin sqlcool but could not figure out a way to use it with my existing database in sqflite. Please help me.

Thanks.

答: You can achieve similar function of listening to sqflite changes by implementing Streams, adapting BloC pattern. You can check this blog post for a sample. One way of achieving this is by updating the Stream paired to sqflite. With this approach, you can use StreamBuilders that can automatically rebuild child widgets when there's change on Stream.</p>


问:
getting empty list even though appending while using recursion
I am trying to print all subsequences of the list "l" in the code but here i want the answer to be stored in "proc" list.But when executing the below code i am getting empty lists of list.I am practising recursion problems.I stuck to understand why i am getting empty lists of list which is "proc" list</p>
```<code>proc = [] #global array
def fun(t,lst,i,n):
    if(i==n):
        print(t)
        proc.append(t) #appending to the global array
        return
    t.append(lst[i])
    fun(t,lst,i+1,n)
    t.pop()
    fun(t,lst,i+1,n)

arr = [6,4,2]
n = len(arr)
l = []
for i in range(n):
    for j in range(i+1,n):
        l.append([i+1,j+1])
fun([],l,0,len(l))
print(proc) #printing the global list proc after executing function```

I want to know why i am getting output as empty lists even though i am appending "t" list to the "proc" list

[[1, 2], [1, 3], [2, 3]]
[[1, 2], [1, 3]]
[[1, 2], [2, 3]]
[[1, 2]]
[[1, 3], [2, 3]]
[[1, 3]]
[[2, 3]]
[]
[[], [], [], [], [], [], [], []]

i want answer to be appended list of t
</code>```

答:
You have fallen prey to one of the classic Python errors.  You are passing [] into the function as t.  You then modify t, and pass t into the recursive call.  That means there is ONLY ONE LIST t.  When you do proc.append(t), you are not grabbing a snapshot of the array.  You are appending multiple references to that one list.  By the time the function ends, t is empty, so your proc has multiple references to an empty list.

The short term fix is to change to

```<code>    proc.append( t.copy() )
</code>```

or

```<code>    proc.append( t[:] )
</code>```

Body:
I am trying to print all subsequences of the list "l" in the code but here i want the answer to be stored in "proc" list.But when executing the below code i am getting empty lists of list.I am practising recursion problems.I stuck to understand why i am getting empty lists of list which is "proc" list

proc = [] #global array
def fun(t,lst,i,n):
    if(i==n):
        print(t)
        proc.append(t) #appending to the global array
        return
    t.append(lst[i])
    fun(t,lst,i+1,n)
    t.pop()
    fun(t,lst,i+1,n)

arr = [6,4,2]
n = len(arr)
l = []
for i in range(n):
    for j in range(i+1,n):
        l.append([i+1,j+1])
fun([],l,0,len(l))
print(proc) #printing the global list proc after executing function```

I want to know why i am getting output as empty lists even though i am appending "t" list to the "proc" list

[[1, 2], [1, 3], [2, 3]]
[[1, 2], [1, 3]]
[[1, 2], [2, 3]]
[[1, 2]]
[[1, 3], [2, 3]]
[[1, 3]]
[[2, 3]]
[]
[[], [], [], [], [], [], [], []]

i want answer to be appended list of t

Body:
You have fallen prey to one of the classic Python errors.  You are passing [] into the function as t.  You then modify t, and pass t into the recursive call.  That means there is ONLY ONE LIST t.  When you do proc.append(t), you are not grabbing a snapshot of the array.  You are appending multiple references to that one list.  By the time the function ends, t is empty, so your proc has multiple references to an empty list.

The short term fix is to change to

    proc.append( t.copy() )

or

    proc.append( t[:] )


问:
torchaudio load audio with specific sampling rate
From documentation, https://pytorch.org/audio/stable/backend.html#torchaudio.backend.sox_io_backend.load it seems there is no parameter for loading audio with a fixed sampling rate which is important for training models.

How to load a pytorch audio tensor with a fixed sampling rate with torchaudio?

答:
Resample can be used from transforms.

```<code>waveform, sample_rate = torchaudio.load('test.wav', normalize=True)
transform = transforms.Resample(sample_rate, sample_rate/10)
waveform = transform(waveform)
</code>```

Body:
Resample can be used from transforms.

waveform, sample_rate = torchaudio.load('test.wav', normalize=True)
transform = transforms.Resample(sample_rate, sample_rate/10)
waveform = transform(waveform)


问:
laravel 7 using as uuid foreign key
I have two tables, in both, I am using UUID to generate an id.
after that, I am trying to use one id as a foreign in the second table. as shown
the migration does accept what I am doing but when I insert data I get this error

```<code>Illuminate/Database/QueryException with message 'SQLSTATE[01000]: Warning: 1265 Data truncated for column 'userId' at row 1
</code>```

her is my first tables:

```<code>       Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('userName')->unique();
            $table->string('email')->unique();
            $table->boolean('isVerified')->default(false);
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
</code>```

the second table with the foreign key

```<code>Schema::create('tableTwo', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->unsignedBigInteger('userId');
            $table->foreign('userId')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
            $table->timestamps();
        });
</code>```

答:
change your code from

```<code>$table->unsignedBigInteger('userId');
</code>```

to

```<code>$table->foreign('userId')
</code>```

if use laravel 8 you can typing like that

```<code>$table->foreignUuid('user_id');
</code>```

Title: laravel 7 using as uuid foreign key

Body:
I have two tables, in both, I am using UUID to generate an id.
after that, I am trying to use one id as a foreign in the second table. as shown
the migration does accept what I am doing but when I insert data I get this error

Illuminate/Database/QueryException with message 'SQLSTATE[01000]: Warning: 1265 Data truncated for column 'userId' at row 1

her is my first tables:

       Schema::create('users', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->string('userName')->unique();
            $table->string('email')->unique();
            $table->boolean('isVerified')->default(false);
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });

the second table with the foreign key

Schema::create('tableTwo', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->unsignedBigInteger('userId');
            $table->foreign('userId')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');
            $table->timestamps();
        });

Body:
change your code from

$table->unsignedBigInteger('userId');

to

$table->foreign('userId')

if use laravel 8 you can typing like that

$table->foreignUuid('user_id');


问:
How do I create a single list of object pairs from two lists in C#?
I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:</p>

```<code>List A
object a1
object a2
object a3

List B
object b1
object b2
object b3

List C (creates pairs)
object c1 (object a1, object b1)
object c2 (object a2, object b2)
object c3 (object a3, object b3)
</code>```

答:
This would do it:

```<code>public static IEnumerable<Tuple<T, U>> CombineWith<T, U>(this IEnumerable<T> first, IEnumerable<U> second)
{
    using (var firstEnumerator = first.GetEnumerator())
    using (var secondEnumerator = second.GetEnumerator())
    {
        bool hasFirst = true;
        bool hasSecond = true;

        while (
            // Only call MoveNext if it didn't fail last time.
            (hasFirst && (hasFirst = firstEnumerator.MoveNext()))
            | // WARNING: Do NOT change to ||.
            (hasSecond && (hasSecond = secondEnumerator.MoveNext()))
            )
        {
            yield return Tuple.Create(
                    hasFirst ? firstEnumerator.Current : default(T),
                    hasSecond ? secondEnumerator.Current : default(U)
                );
        }
    }
}
</code>```

Edit: I vastly prefer Paul's answer.

Body:
I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:

List A
object a1
object a2
object a3

List B
object b1
object b2
object b3

List C (creates pairs)
object c1 (object a1, object b1)
object c2 (object a2, object b2)
object c3 (object a3, object b3)

Body:
This would do it:

public static IEnumerable<Tuple<T, U>> CombineWith<T, U>(this IEnumerable<T> first, IEnumerable<U> second)
{
    using (var firstEnumerator = first.GetEnumerator())
    using (var secondEnumerator = second.GetEnumerator())
    {
        bool hasFirst = true;
        bool hasSecond = true;

        while (
            // Only call MoveNext if it didn't fail last time.
            (hasFirst && (hasFirst = firstEnumerator.MoveNext()))
            | // WARNING: Do NOT change to ||.
            (hasSecond && (hasSecond = secondEnumerator.MoveNext()))
            )
        {
            yield return Tuple.Create(
                    hasFirst ? firstEnumerator.Current : default(T),
                    hasSecond ? secondEnumerator.Current : default(U)
                );
        }
    }
}

Edit: I vastly prefer Paul's answer.


问:
What does the underscore(_) do in for loop Golang?
I am just getting started learning the Golang language!
In for loop, I saw sometimes adding an underscore or without underscore.

Whatever add _ or not, I got the same result.

```<code>package main

import (
    "fmt"
)

func main() {
    doSomething()
    sum := addValues(5, 8)
    fmt.Println("The sum is", sum)

    multiSum, multiCount := addAllValues(4, 7, 9)
    fmt.Println("multisum", multiSum)
    fmt.Println("multiCount", multiCount)
}

func doSomething() {
    fmt.Println("Doing Something")
}

func addValues(value1 int, value2 int) int {
    return value1 + value2
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for _, v := range values {
        total += v
    }
    return total, len(values)
}
</code>```
```<code>func addAllValues(values ...int) (int, int) {
    total := 0
    for v := range values {
        total += v
    }
    return total, len(values)
}
</code>```

All I know is I don't care about the index. Is that all? or there is something more what I have to know??

I really appreciate your help!

答:
For range over slices:

In for v := range values { the v is the index of the element in the slice.

In for _, v := range values { the v is the actual element value.

In for i, v := range values { the i is the index and the v is the element.

In for i, _ := range values { the i is the index of the element in the slice.

You can run this playground example to see the differences.

Range expression                          1st value          2nd value

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
string          s  string type            index    i  int    see below  rune
map             m  map[K]V                key      k  K      m[k]       V
channel         c  chan E, <-chan E       element  e  E
```

For more details see the spec.

Body:
I am just getting started learning the Golang language!
In for loop, I saw sometimes adding an underscore or without underscore.

Whatever add _ or not, I got the same result.

package main

import (
    "fmt"
)

func main() {
    doSomething()
    sum := addValues(5, 8)
    fmt.Println("The sum is", sum)

    multiSum, multiCount := addAllValues(4, 7, 9)
    fmt.Println("multisum", multiSum)
    fmt.Println("multiCount", multiCount)
}

func doSomething() {
    fmt.Println("Doing Something")
}

func addValues(value1 int, value2 int) int {
    return value1 + value2
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for _, v := range values {
        total += v
    }
    return total, len(values)
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for v := range values {
        total += v
    }
    return total, len(values)
}

All I know is I don't care about the index. Is that all? or there is something more what I have to know??

I really appreciate your help!

Body:
For range over slices:

In for v := range values { the v is the index of the element in the slice.

In for _, v := range values { the v is the actual element value.

In for i, v := range values { the i is the index and the v is the element.

In for i, _ := range values { the i is the index of the element in the slice.

You can run this playground example to see the differences.

Range expression                          1st value          2nd value

array or slice  a  [n]E, *[n]E, or []E    index    i  int    a[i]       E
string          s  string type            index    i  int    see below  rune
map             m  map[K]V                key      k  K      m[k]       V
channel         c  chan E, <-chan E       element  e  E

For more details see the spec.