问:
Keras with Tensorflow backend does not use GPU
I have installed Keras with the TensorFlow backend following these instructions:

```<code>library(keras)
install_keras(tensorflow = "gpu")
</code>```

The installation went smoothly and I had no error message.

If I type:

```<code>k = backend()
sess = k$get_session()
sess$list_devices()
</code>```

As far as I understand the output, my GPU seems to be recognized:

```<code>[[1]]
_DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 3277741456357329757)

[[2]]
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 14524037525637335634)

[[3]]
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 5788527260077506513)
</code>```

My .profile file looks like this:

```<code>export CUDA_HOME=${CUDA_PATH}
export PATH="${CUDA_PATH}/bin:$PATH"
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${CUDA_PATH}/lib64/
</code>```

I can also list all the Nvidia related packages:

```<code>[ben@Solgaleo ~]$ pacman -Qs nvidia*
local/cuda 10.2.89-3
    NVIDIA's GPU programming toolkit
local/cudnn 7.6.5.32-3
    NVIDIA CUDA Deep Neural Network library
local/lib32-nvidia-utils 440.59-1
    NVIDIA drivers utilities (32-bit)
local/libvdpau 1.3-1
    Nvidia VDPAU library
local/libxnvctrl 440.59-1
    NVIDIA NV-CONTROL X extension
local/nvidia 440.59-8
    NVIDIA drivers for linux
local/nvidia-settings 440.59-1
    Tool for configuring the NVIDIA graphics driver
local/nvidia-utils 440.59-1
    NVIDIA drivers utilities
local/nvtop 1.0.0-2
    An htop like monitoring tool for NVIDIA GPUs
local/opencl-nvidia 440.59-1
    OpenCL implemention for NVIDIA
</code>```

But when I build a Keras model, some library files are not found:

```<code>library(keras)
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y
# reshape
x_train <- array_reshape(x_train, c(nrow(x_train), 784))
x_test <- array_reshape(x_test, c(nrow(x_test), 784))
# rescale
x_train <- x_train / 255
x_test <- x_test / 255
y_train <- to_categorical(y_train, 10)
y_test <- to_categorical(y_test, 10)
model <- keras_model_sequential()
model %>%
  layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>%
  layer_dropout(rate = 0.4) %>%
  layer_dense(units = 128, activation = 'relu') %>%
  layer_dropout(rate = 0.3) %>%
  layer_dense(units = 10, activation = 'softmax')
</code>```

Here is the error message:

```<code>2020-02-18 13:45:23.530693: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2020-02-18 13:45:23.609674: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-02-18 13:45:23.610276: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:
name: GeForce RTX 2070 SUPER major: 7 minor: 5 memoryClockRate(GHz): 1.77
pciBusID: 0000:09:00.0
2020-02-18 13:45:23.610420: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcudart.so.10.0'; dlerror: libcudart.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610508: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcublas.so.10.0'; dlerror: libcublas.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610597: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcufft.so.10.0'; dlerror: libcufft.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610680: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcurand.so.10.0'; dlerror: libcurand.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610761: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcusolver.so.10.0'; dlerror: libcusolver.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610842: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcusparse.so.10.0'; dlerror: libcusparse.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.646497: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-02-18 13:45:23.646508: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1641] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
2020-02-18 13:45:23.647124: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-02-18 13:45:23.669292: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3794460000 Hz
2020-02-18 13:45:23.670124: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x559b541a72c0 executing computations on platform Host. Devices:
2020-02-18 13:45:23.670138: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): Host, Default Version
2020-02-18 13:45:23.670530: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1159] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-02-18 13:45:23.670542: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1165]
2020-02-18 13:45:23.982097: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-02-18 13:45:23.982507: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x559b5423b030 executing computations on platform CUDA. Devices:
2020-02-18 13:45:23.982529: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): GeForce RTX 2070 SUPER, Compute Capability 7.5
</code>```

And indeed, libcudart.so.10.0 (for instance) cannot be found, because it's not there:

```<code>[ben@Solgaleo ~]$ ll /opt/cuda/lib64/libcudart.so*
lrwxrwxrwx 1 root root   20 Dec 31 09:07 /opt/cuda/lib64/libcudart.so -> libcudart.so.10.2.89
lrwxrwxrwx 1 root root   20 Dec 31 09:07 /opt/cuda/lib64/libcudart.so.10 -> libcudart.so.10.2.89
lrwxrwxrwx 1 root root   20 Dec 31 09:07 /opt/cuda/lib64/libcudart.so.10.2 -> libcudart.so.10.2.89
-rwxr-xr-x 1 root root 498K Dec 31 09:07 /opt/cuda/lib64/libcudart.so.10.2.89
</code>```

So TensorFlow is looking for version 10.0, while I have the 10.2 installed.

And when training my model, only the CPU is used.

What did I mess up with Keras/TensorFlow installation? How can I fix this?

Edit: Here are the versions of Keras and TensorFlow R packages:

```<code>keras_2.2.5.0
tensorflow_2.0.0
</code>```

答:
Adding an a partial answer ti the question based on the comments we discussed (as some of the errors I have no idea how to resolve, but maybe someone can add to this).

On the original question it looks like tensorflow can only see the CPU:
CPU : _DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 3277741456357329757)

Tensorflow versions are not CUDA version agnostic so you need to ensure they are compatible. TF 2.0 is expecting CUDA 10.0 so you need to always double check. You can upgrade to tf 2.1 and downgrade CUDA to 10.1 by using install_tensorflow(version = "2.1.0") in R and using yaourt cuda-10.1 in arch linux to get the right version of CUDA with all dependencies.

Since CUDA 10.0 you need to install TensorRT dependencies as well to use some acceleration properties (that tensorflow is using); for this you need to download the TensorRT package from NVidia developer downloads (account needed) and install using AUR repository.

On the progbar error, I am not 100% sure as I haven't seen it before, but looks like it could be related to tensorboard, so please make sure you have an appropriate version of this installed as well.

Body:
I have installed Keras with the TensorFlow backend following these instructions:

library(keras)
install_keras(tensorflow = "gpu")

The installation went smoothly and I had no error message.

If I type:

k = backend()
sess = k$get_session()
sess$list_devices()

As far as I understand the output, my GPU seems to be recognized:

[[1]]
_DeviceAttributes(/job:localhost/replica:0/task:0/device:CPU:0, CPU, 268435456, 3277741456357329757)

[[2]]
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_CPU:0, XLA_CPU, 17179869184, 14524037525637335634)

[[3]]
_DeviceAttributes(/job:localhost/replica:0/task:0/device:XLA_GPU:0, XLA_GPU, 17179869184, 5788527260077506513)

My .profile file looks like this:

export CUDA_HOME=${CUDA_PATH}
export PATH="${CUDA_PATH}/bin:$PATH"
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:${CUDA_PATH}/lib64/

I can also list all the Nvidia related packages:

[ben@Solgaleo ~]$ pacman -Qs nvidia*
local/cuda 10.2.89-3
    NVIDIA's GPU programming toolkit
local/cudnn 7.6.5.32-3
    NVIDIA CUDA Deep Neural Network library
local/lib32-nvidia-utils 440.59-1
    NVIDIA drivers utilities (32-bit)
local/libvdpau 1.3-1
    Nvidia VDPAU library
local/libxnvctrl 440.59-1
    NVIDIA NV-CONTROL X extension
local/nvidia 440.59-8
    NVIDIA drivers for linux
local/nvidia-settings 440.59-1
    Tool for configuring the NVIDIA graphics driver
local/nvidia-utils 440.59-1
    NVIDIA drivers utilities
local/nvtop 1.0.0-2
    An htop like monitoring tool for NVIDIA GPUs
local/opencl-nvidia 440.59-1
    OpenCL implemention for NVIDIA

But when I build a Keras model, some library files are not found:

library(keras)
mnist <- dataset_mnist()
x_train <- mnist$train$x
y_train <- mnist$train$y
x_test <- mnist$test$x
y_test <- mnist$test$y
# reshape
x_train <- array_reshape(x_train, c(nrow(x_train), 784))
x_test <- array_reshape(x_test, c(nrow(x_test), 784))
# rescale
x_train <- x_train / 255
x_test <- x_test / 255
y_train <- to_categorical(y_train, 10)
y_test <- to_categorical(y_test, 10)
model <- keras_model_sequential()
model %>%
  layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>%
  layer_dropout(rate = 0.4) %>%
  layer_dense(units = 128, activation = 'relu') %>%
  layer_dropout(rate = 0.3) %>%
  layer_dense(units = 10, activation = 'softmax')

Here is the error message:

2020-02-18 13:45:23.530693: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2020-02-18 13:45:23.609674: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-02-18 13:45:23.610276: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1618] Found device 0 with properties:
name: GeForce RTX 2070 SUPER major: 7 minor: 5 memoryClockRate(GHz): 1.77
pciBusID: 0000:09:00.0
2020-02-18 13:45:23.610420: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcudart.so.10.0'; dlerror: libcudart.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610508: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcublas.so.10.0'; dlerror: libcublas.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610597: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcufft.so.10.0'; dlerror: libcufft.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610680: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcurand.so.10.0'; dlerror: libcurand.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610761: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcusolver.so.10.0'; dlerror: libcusolver.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.610842: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libcusparse.so.10.0'; dlerror: libcusparse.so.10.0: cannot open shared object file: No such file or directory; LD_LIBRARY_PATH: /usr/lib64/R/lib::/opt/cuda/lib64/:::/lib:/usr/lib/jvm/java-7-openjdk/jre/lib/amd64/server::/opt/cuda/lib64/
2020-02-18 13:45:23.646497: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-02-18 13:45:23.646508: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1641] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform.
Skipping registering GPU devices...
2020-02-18 13:45:23.647124: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-02-18 13:45:23.669292: I tensorflow/core/platform/profile_utils/cpu_utils.cc:94] CPU Frequency: 3794460000 Hz
2020-02-18 13:45:23.670124: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x559b541a72c0 executing computations on platform Host. Devices:
2020-02-18 13:45:23.670138: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): Host, Default Version
2020-02-18 13:45:23.670530: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1159] Device interconnect StreamExecutor with strength 1 edge matrix:
2020-02-18 13:45:23.670542: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1165]
2020-02-18 13:45:23.982097: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:1006] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-02-18 13:45:23.982507: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x559b5423b030 executing computations on platform CUDA. Devices:
2020-02-18 13:45:23.982529: I tensorflow/compiler/xla/service/service.cc:175]   StreamExecutor device (0): GeForce RTX 2070 SUPER, Compute Capability 7.5

And indeed, libcudart.so.10.0 (for instance) cannot be found, because it's not there:

[ben@Solgaleo ~]$ ll /opt/cuda/lib64/libcudart.so*
lrwxrwxrwx 1 root root   20 Dec 31 09:07 /opt/cuda/lib64/libcudart.so -> libcudart.so.10.2.89
lrwxrwxrwx 1 root root   20 Dec 31 09:07 /opt/cuda/lib64/libcudart.so.10 -> libcudart.so.10.2.89
lrwxrwxrwx 1 root root   20 Dec 31 09:07 /opt/cuda/lib64/libcudart.so.10.2 -> libcudart.so.10.2.89
-rwxr-xr-x 1 root root 498K Dec 31 09:07 /opt/cuda/lib64/libcudart.so.10.2.89

So TensorFlow is looking for version 10.0, while I have the 10.2 installed.

And when training my model, only the CPU is used.

What did I mess up with Keras/TensorFlow installation? How can I fix this?

Edit: Here are the versions of Keras and TensorFlow R packages:

keras_2.2.5.0
tensorflow_2.0.0


来源: stackexchange

问:
XAML WebView binding to HTML source not working
I have a XAML page layout defined that includes a WebView populated from an HTML string:

```<code><WebView HorizontalOptions="Fill" VerticalOptions="FillAndExpand">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Flag.Description}" />
<!--    <HtmlWebViewSource Html="<html><body><p>The HTML string.</p></body></html>" />-->
    </WebView.Source>
</WebView>
</code>```

When I hard code the string into the XAML it displays correctly, but it will not bind to the Flag.Description string. The XAML includes a couple of labels that bind correctly but I can't find any reason why the WebView source isn't binding correctly.

答:
```<code>public HtmlWebViewSource Description { get { var webView = "html content";return
 new HtmlWebViewSource { Html = webView };} }
<WebView
  HorizontalOptions="Fill"
  VerticalOptions="FillAndExpand"
  Source="{Binding Description}" />
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a XAML page layout defined that includes a WebView populated from an HTML string:

<WebView HorizontalOptions="Fill" VerticalOptions="FillAndExpand">
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding Flag.Description}" />

    </WebView.Source>
</WebView>

When I hard code the string into the XAML it displays correctly, but it will not bind to the Flag.Description string. The XAML includes a couple of labels that bind correctly but I can't find any reason why the WebView source isn't binding correctly.

ContentLicense: CC BY-SA 4.0


问:
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter when using DiffUtil
Below is an adapter class for loading all book items in recycler view. Used DiffUtils so that the whole list doesn't get notified.

```<code>
class BooksAdapter(var mContext: Context) : RecyclerView.Adapter<BooksAdapter.BooksViewHolder>() {

    var books: List<BookTable> = ArrayList()
        set(value) {
            val result = DiffUtil.calculateDiff(BookListDiffCallBacks(ArrayList(value), ArrayList(books)))
            field = value
            result.dispatchUpdatesTo(this)
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BooksViewHolder {
        val binding = DataBindingUtil.inflate<ItemBookBinding>(LayoutInflater.from(mContext), R.layout.item_book, parent, false)
        return BooksViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return books.size
    }

    override fun onBindViewHolder(holder: BooksViewHolder, position: Int) {
        holder.setData(books[position])
    }

    inner class BooksViewHolder(var binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root) {
        fun setData(bookTable: BookTable) {
            binding.book = bookTable
        }
    }
}

</code>```

My DiffUtil class is as below. I have extended DiffUtil class and checked if items are same or not , if not then DiffUtil will handle updatin

```<code>class BookListDiffCallBacks(var oldBooks: ArrayList<BookTable>, var newBooks: ArrayList<BookTable>) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition].bookId == newBooks[newItemPosition].bookId
    }

    override fun getOldListSize(): Int {
        return oldBooks.size
    }

    override fun getNewListSize(): Int {
        return newBooks.size
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition] == newBooks[newItemPosition]// == means structural equality checks in kotlin
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}
</code>```

Model class

```<code>

@Entity(
    tableName = "book_table"//,
//    foreignKeys = [ForeignKey(entity = CategoryTable::class, parentColumns = arrayOf("categoryId"), childColumns = arrayOf("categoryId"), onDelete = ForeignKey.CASCADE)]
)
class BookTable : BaseObservable() {

    @Bindable
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "bookId")
    var bookId: Int = 0
        set(value) {
            field = value
            notifyPropertyChanged(BR.bookId)
        }

    @Bindable
    var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }

    @Bindable
    var categoryId: Int? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.categoryId)
        }

    override fun equals(other: Any?): Boolean {

        if (other === this) return true // means same reference
        if (other !is BookTable) return false// is not of same class

        // other is now Booktable instance as above condition false if you remove that condition then it will show error in below condition
        // as it has passed above condition means it is of type BookTable
        return (bookId == other.bookId
                && categoryId == other.categoryId
                && name == other.name)

    }

    override fun hashCode(): Int {
        var result = bookId
        result = 31 * result + (name?.hashCode() ?: 0)
        result = 31 * result + (categoryId ?: 0)
        return result
    }

}

</code>```

My app gets crash and I am getting this error:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionBooksViewHolder

I have implemented DiffUtil class so that whole recycleview view items don't get notified.

Reference: https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/DiffUtil

答:
Your parameters to the BookListDiffCallBacks constructor are backwards:

```<code>val result = DiffUtil.calculateDiff(BookListDiffCallBacks(ArrayList(value), ArrayList(books)))
</code>```

You're passing new, old, but the constructor expects old, new.

Body:
Below is an adapter class for loading all book items in recycler view. Used DiffUtils so that the whole list doesn't get notified.

class BooksAdapter(var mContext: Context) : RecyclerView.Adapter<BooksAdapter.BooksViewHolder>() {

    var books: List<BookTable> = ArrayList()
        set(value) {
            val result = DiffUtil.calculateDiff(BookListDiffCallBacks(ArrayList(value), ArrayList(books)))
            field = value
            result.dispatchUpdatesTo(this)
        }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BooksViewHolder {
        val binding = DataBindingUtil.inflate<ItemBookBinding>(LayoutInflater.from(mContext), R.layout.item_book, parent, false)
        return BooksViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return books.size
    }

    override fun onBindViewHolder(holder: BooksViewHolder, position: Int) {
        holder.setData(books[position])
    }

    inner class BooksViewHolder(var binding: ItemBookBinding) : RecyclerView.ViewHolder(binding.root) {
        fun setData(bookTable: BookTable) {
            binding.book = bookTable
        }
    }
}

My DiffUtil class is as below. I have extended DiffUtil class and checked if items are same or not , if not then DiffUtil will handle updatin

class BookListDiffCallBacks(var oldBooks: ArrayList<BookTable>, var newBooks: ArrayList<BookTable>) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition].bookId == newBooks[newItemPosition].bookId
    }

    override fun getOldListSize(): Int {
        return oldBooks.size
    }

    override fun getNewListSize(): Int {
        return newBooks.size
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldBooks[oldItemPosition] == newBooks[newItemPosition]// == means structural equality checks in kotlin
    }

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}

Model class

@Entity(
    tableName = "book_table"//,
//    foreignKeys = [ForeignKey(entity = CategoryTable::class, parentColumns = arrayOf("categoryId"), childColumns = arrayOf("categoryId"), onDelete = ForeignKey.CASCADE)]
)
class BookTable : BaseObservable() {

    @Bindable
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "bookId")
    var bookId: Int = 0
        set(value) {
            field = value
            notifyPropertyChanged(BR.bookId)
        }

    @Bindable
    var name: String? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.name)
        }

    @Bindable
    var categoryId: Int? = null
        set(value) {
            field = value
            notifyPropertyChanged(BR.categoryId)
        }

    override fun equals(other: Any?): Boolean {

        if (other === this) return true // means same reference
        if (other !is BookTable) return false// is not of same class

        // other is now Booktable instance as above condition false if you remove that condition then it will show error in below condition
        // as it has passed above condition means it is of type BookTable
        return (bookId == other.bookId
                && categoryId == other.categoryId
                && name == other.name)

    }

    override fun hashCode(): Int {
        var result = bookId
        result = 31 * result + (name?.hashCode() ?: 0)
        result = 31 * result + (categoryId ?: 0)
        return result
    }

}

My app gets crash and I am getting this error:

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionBooksViewHolder

I have implemented DiffUtil class so that whole recycleview view items don't get notified.

Reference: https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/DiffUtil

Body:
Your parameters to the BookListDiffCallBacks constructor are backwards:

val result = DiffUtil.calculateDiff(BookListDiffCallBacks(ArrayList(value), ArrayList(books)))

You're passing new, old, but the constructor expects old, new.


问:
Emailvalidator (require("email-validator") stopped working
I am doing email validation in my Signup form and all of a sudden it doesn't work anymore. I didn't change the signup.js file so it is a bit strange. I started working on the login.js file today so maybe there is some 'interference', but I don't have any idea where to look fist to be honest.

So here is the signup.js, where I put the emailvalidation that doesn't work anymore in bold.

```<code>import React, { Component } from 'react';
import { Text, StyleSheet, TouchableOpacity, Image, TextInput, View } from 'react-native';
import firebase from 'react-native-firebase';
var validator = require("email-validator");

export default class loginComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {firstName: ''};
    this.state = {lastName: ''};
    this.state = {email: ''};
    this.state = {password: ''};
    this.state = {emailValidated: false};
    this.state = {errorMessage: null};
  }

  handleSignUp = () => {
    firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then(() => this.props.navigation.navigate('Main'))
      .catch(error => this.setState({ errorMessage: error.message }))
  }

  render() {

  function renderEmailValidationState(emailInput) {

      if(validator.validate(emailInput)) {
        return false;
      } else {
        return true;
    }
    }

    return (
      <View style={styles.container}>
       <View style={styles.logoContainer} >
        <Image source={require('./assets/logo.png')} style={styles.logo}></Image>
        <Text style={styles.slush}>
           Lenen of huren, {"\n"}   bij de buren!
        </Text>
       </View>
       <View style={styles.formContainer}>

       <View style={styles.inputTextFieldContainer}>
       {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>
          }
       <TextInput
          style={styles.inputTextField}
          placeholder="Enter you first name"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(firstName) => this.setState({firstName})}
        />
        <TextInput
          style={styles.inputTextField}
          placeholder="Enter you last name"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(lastName) => this.setState({lastName})}
        />
        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your e-mail"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(email) => this.setState({email})}
        />

        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your password"
          value={this.state.password}
          backgroundColor="white"
          onChangeText={(password) => this.setState({password})}
        />
        <TouchableOpacity
        disabled= {renderEmailValidationState(this.state.email)}
        style={styles.buttonContainer}
        onPress={this.handleSignUp}
        >

          <View>
            <Text style={styles.buttonText}>Sign up!</Text>
          </View>
        </TouchableOpacity>

        <Text style={styles.plainText}>
          Already a user?
        </Text>
        <TouchableOpacity
        style={styles.buttonContainer}
        onPress={() => this.props.navigation.navigate('Login')}
        >
          <View>
            <Text style={styles.buttonText}>Login!</Text>
          </View>
        </TouchableOpacity>
      </View>
      </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 2,
   padding:10,
   backgroundColor:'#c6f1e7',
   alignItems: 'stretch',
   justifyContent: 'space-around'
   },
  logoContainer: {
    padding: 10,
    height: 250,
    justifyContent: 'center' ,
    alignItems: 'center'
  },

  logo: {
    width: 250,
    height: 250
  },
  slush: {
    fontSize: 20,
    color: '#59616e',
    fontFamily: 'Raleway-Regular'
  },
  formContainer: {
    flex:1,
    padding: 10,
  },
  inputTextFieldContainer: {
    padding: 100,
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 30
  },
  inputTextField: {
    padding: 10,
    height: 40,
    width: 300,
    marginBottom: 10,
    fontSize: 16,
    fontFamily: 'Raleway-Regular',
  },
  buttonContainer: {
    padding: 10,
    marginBottom: 20,
    width: 300,
    alignItems: 'center',
    backgroundColor: '#acdcd7',

  },
  buttonText: {
    padding: 1,
    fontSize: 16,
    color: '#59616e',
    fontFamily: 'Raleway-Regular',
  },
  plainText: {
    padding: 1,
    fontSize: 16,
    marginBottom: 5,
    fontFamily: 'Raleway-Regular',
    color: '#59616e'
  },
});
</code>```

And this is the login.js, but that is work in progress.

```<code>import React, { Component } from 'react';
import { Text, StyleSheet, TouchableOpacity, Image, TextInput, View } from 'react-native';
import firebase from 'react-native-firebase';
var validator = require("email-validator");

export default class loginComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {email: ''};
    this.state = {password: ''};
    this.state = {emailValidated: false};
    this.state = {errorMessage: null};
  }

  render() {

  function renderEmailValidationState(emailInput) {
      if(validator.validate(emailInput)) {
        return false;
      } else {
        return true;
    }
    }
    return (
      <View style={styles.container}>
      <View style={styles.logoContainer}>
        <Image source={require('./assets/logo.png')} style={styles.logo}></Image>
        <Text style={styles.slush}>
           Huren bij de buren!
        </Text>
       </View>
      <View style={styles.formContainer}>
       <View style={styles.inputTextFieldContainer}>
       {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>
          }
        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your e-mail"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(email) => this.setState({email})}
        />

        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your password"
          value={this.state.password}
          backgroundColor="white"
          onChangeText={(password) => this.setState({password})}
        />
        <TouchableOpacity
        **disabled= {renderEmailValidationState(this.state.email)}**
        style={styles.buttonContainer}
        onPress={this.handleSignUp}
        >
          <View>
            <Text style={styles.buttonText}>Sign up!</Text>
          </View>
        </TouchableOpacity>
        <Text style={styles.plainText}>
          Don't have an account?
        </Text>
        <TouchableOpacity
        style={styles.buttonContainer}
        onPress={() => this.props.navigation.navigate('SignUp')}
        >
          <View>
            <Text style={styles.buttonText}>Register!</Text>
          </View>
        </TouchableOpacity>
      </View>
      </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 2,
   padding:10,
   backgroundColor:'#c6f1e7',
   alignItems: 'stretch',
   justifyContent: 'space-around'
   },
  logoContainer: {
    padding: 10,
    height: 350,
    justifyContent: 'center' ,
    alignItems: 'center'
  },

  logo: {
    width: 250,
    height: 250
  },
  slush: {
    fontSize: 25,
    color: '#59616e',
    fontFamily: 'Raleway-Regular'
  },
  formContainer: {
    flex:1,
    padding: 10,
  },
  inputTextFieldContainer: {
    padding: 100,
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 30
  },
  inputTextField: {
    padding: 10,
    height: 40,
    width: 300,
    marginBottom: 10,
    fontSize: 16,
    fontFamily: 'Raleway-Regular',
  },
  buttonContainer: {
    padding: 10,
    marginBottom: 20,
    width: 300,
    alignItems: 'center',
    backgroundColor: '#acdcd7',

  },
  buttonText: {
    padding: 1,
    fontSize: 16,
    color: '#59616e',
    fontFamily: 'Raleway-Regular',
  },
  plainText: {
    padding: 1,
    fontSize: 16,
    marginBottom: 5,
    fontFamily: 'Raleway-Regular',
    color: '#59616e'
  },
});
</code>```

Can anyone point me in the good direction?

Thanks a lot!

Tim

答:
try this npm i raysk-vali

instead of email-validator.

usage:

const { isEmail } = require("raysk-vali");

isEmail("abc@example.com") // return true
isEmail("abcexample.com") // return false
```

for more checkout the documentation : https://www.npmjs.com/package/raysk-vali.

Body:
I am doing email validation in my Signup form and all of a sudden it doesn't work anymore. I didn't change the signup.js file so it is a bit strange. I started working on the login.js file today so maybe there is some 'interference', but I don't have any idea where to look fist to be honest.

So here is the signup.js, where I put the emailvalidation that doesn't work anymore in bold.

import React, { Component } from 'react';
import { Text, StyleSheet, TouchableOpacity, Image, TextInput, View } from 'react-native';
import firebase from 'react-native-firebase';
var validator = require("email-validator");

export default class loginComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {firstName: ''};
    this.state = {lastName: ''};
    this.state = {email: ''};
    this.state = {password: ''};
    this.state = {emailValidated: false};
    this.state = {errorMessage: null};
  }

  handleSignUp = () => {
    firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then(() => this.props.navigation.navigate('Main'))
      .catch(error => this.setState({ errorMessage: error.message }))
  }

  render() {

  function renderEmailValidationState(emailInput) {

      if(validator.validate(emailInput)) {
        return false;
      } else {
        return true;
    }
    }

    return (
      <View style={styles.container}>
       <View style={styles.logoContainer} >
        <Image source={require('./assets/logo.png')} style={styles.logo}></Image>
        <Text style={styles.slush}>
           Lenen of huren, {"\n"}   bij de buren!
        </Text>
       </View>
       <View style={styles.formContainer}>

       <View style={styles.inputTextFieldContainer}>
       {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>
          }
       <TextInput
          style={styles.inputTextField}
          placeholder="Enter you first name"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(firstName) => this.setState({firstName})}
        />
        <TextInput
          style={styles.inputTextField}
          placeholder="Enter you last name"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(lastName) => this.setState({lastName})}
        />
        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your e-mail"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(email) => this.setState({email})}
        />

        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your password"
          value={this.state.password}
          backgroundColor="white"
          onChangeText={(password) => this.setState({password})}
        />
        <TouchableOpacity
        disabled= {renderEmailValidationState(this.state.email)}
        style={styles.buttonContainer}
        onPress={this.handleSignUp}
        >

          <View>
            <Text style={styles.buttonText}>Sign up!</Text>
          </View>
        </TouchableOpacity>

        <Text style={styles.plainText}>
          Already a user?
        </Text>
        <TouchableOpacity
        style={styles.buttonContainer}
        onPress={() => this.props.navigation.navigate('Login')}
        >
          <View>
            <Text style={styles.buttonText}>Login!</Text>
          </View>
        </TouchableOpacity>
      </View>
      </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 2,
   padding:10,
   backgroundColor:'#c6f1e7',
   alignItems: 'stretch',
   justifyContent: 'space-around'
   },
  logoContainer: {
    padding: 10,
    height: 250,
    justifyContent: 'center' ,
    alignItems: 'center'
  },

  logo: {
    width: 250,
    height: 250
  },
  slush: {
    fontSize: 20,
    color: '#59616e',
    fontFamily: 'Raleway-Regular'
  },
  formContainer: {
    flex:1,
    padding: 10,
  },
  inputTextFieldContainer: {
    padding: 100,
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 30
  },
  inputTextField: {
    padding: 10,
    height: 40,
    width: 300,
    marginBottom: 10,
    fontSize: 16,
    fontFamily: 'Raleway-Regular',
  },
  buttonContainer: {
    padding: 10,
    marginBottom: 20,
    width: 300,
    alignItems: 'center',
    backgroundColor: '#acdcd7',

  },
  buttonText: {
    padding: 1,
    fontSize: 16,
    color: '#59616e',
    fontFamily: 'Raleway-Regular',
  },
  plainText: {
    padding: 1,
    fontSize: 16,
    marginBottom: 5,
    fontFamily: 'Raleway-Regular',
    color: '#59616e'
  },
});

And this is the login.js, but that is work in progress.

import React, { Component } from 'react';
import { Text, StyleSheet, TouchableOpacity, Image, TextInput, View } from 'react-native';
import firebase from 'react-native-firebase';
var validator = require("email-validator");

export default class loginComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {email: ''};
    this.state = {password: ''};
    this.state = {emailValidated: false};
    this.state = {errorMessage: null};
  }

  render() {

  function renderEmailValidationState(emailInput) {
      if(validator.validate(emailInput)) {
        return false;
      } else {
        return true;
    }
    }
    return (
      <View style={styles.container}>
      <View style={styles.logoContainer}>
        <Image source={require('./assets/logo.png')} style={styles.logo}></Image>
        <Text style={styles.slush}>
           Huren bij de buren!
        </Text>
       </View>
      <View style={styles.formContainer}>
       <View style={styles.inputTextFieldContainer}>
       {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>
          }
        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your e-mail"
          value={this.state.text}
          backgroundColor="white"
          onChangeText={(email) => this.setState({email})}
        />

        <TextInput
          style={styles.inputTextField}
          placeholder="Enter your password"
          value={this.state.password}
          backgroundColor="white"
          onChangeText={(password) => this.setState({password})}
        />
        <TouchableOpacity
        **disabled= {renderEmailValidationState(this.state.email)}**
        style={styles.buttonContainer}
        onPress={this.handleSignUp}
        >
          <View>
            <Text style={styles.buttonText}>Sign up!</Text>
          </View>
        </TouchableOpacity>
        <Text style={styles.plainText}>
          Don't have an account?
        </Text>
        <TouchableOpacity
        style={styles.buttonContainer}
        onPress={() => this.props.navigation.navigate('SignUp')}
        >
          <View>
            <Text style={styles.buttonText}>Register!</Text>
          </View>
        </TouchableOpacity>
      </View>
      </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
   flex: 2,
   padding:10,
   backgroundColor:'#c6f1e7',
   alignItems: 'stretch',
   justifyContent: 'space-around'
   },
  logoContainer: {
    padding: 10,
    height: 350,
    justifyContent: 'center' ,
    alignItems: 'center'
  },

  logo: {
    width: 250,
    height: 250
  },
  slush: {
    fontSize: 25,
    color: '#59616e',
    fontFamily: 'Raleway-Regular'
  },
  formContainer: {
    flex:1,
    padding: 10,
  },
  inputTextFieldContainer: {
    padding: 100,
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 30
  },
  inputTextField: {
    padding: 10,
    height: 40,
    width: 300,
    marginBottom: 10,
    fontSize: 16,
    fontFamily: 'Raleway-Regular',
  },
  buttonContainer: {
    padding: 10,
    marginBottom: 20,
    width: 300,
    alignItems: 'center',
    backgroundColor: '#acdcd7',

  },
  buttonText: {
    padding: 1,
    fontSize: 16,
    color: '#59616e',
    fontFamily: 'Raleway-Regular',
  },
  plainText: {
    padding: 1,
    fontSize: 16,
    marginBottom: 5,
    fontFamily: 'Raleway-Regular',
    color: '#59616e'
  },
});

Can anyone point me in the good direction?

Thanks a lot!

Tim

Body:
try this npm i raysk-vali

instead of email-validator.

usage:

const { isEmail } = require("raysk-vali");

isEmail("abc@example.com") // return true
isEmail("abcexample.com") // return false

for more checkout the documentation : https://www.npmjs.com/package/raysk-vali.


问:
How can i make flat button size as it's child size
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

```<code>        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),
</code>```

and this is the photo
photo

答:
Your question is confusing to me, I am not sure whether you want your button as big as the parent's child (as you stated in the title), or if you want it as big as the Text child (as you stated in the description of your question).

If what you want is the button to be as big as the parent, consider using LayoutBuilder and SizedBox to make the button as big as the available surrounding space. You can do something like this:

  LayoutBuilder(
    builder: (context, constraints) {
      return SizedBox(
        height: constraints.maxHeight,
        width: constraints.maxWidth,
        child: FlatButton(
          ...
        )
      )
    }
  )
```

If you want the button to be as big as its child, I believe you don't need to worry about anything other than providing the proper Text widget. FlatButton will figure out its size accordingly.

Body:
i want to make button size like it's text child size
i will attach  example photo , and i'll attach the code that i write

this is my code :

        Expanded(
        child: FlatButton(
          minWidth: double.infinity,
          height: 20,
          child: FlatButton(
            onPressed: (){},
            color: Colors.grey,
           shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10) ,
            ),
            child: Text(
              'SHOP' ,
              style: TextStyle(
                color: Colors.blueAccent,
                fontWeight: FontWeight.bold ,
                fontSize: 16 ,
              ),

and this is the photo
photo

Body:
Your question is confusing to me, I am not sure whether you want your button as big as the parent's child (as you stated in the title), or if you want it as big as the Text child (as you stated in the description of your question).

If what you want is the button to be as big as the parent, consider using LayoutBuilder and SizedBox to make the button as big as the available surrounding space. You can do something like this:

  LayoutBuilder(
    builder: (context, constraints) {
      return SizedBox(
        height: constraints.maxHeight,
        width: constraints.maxWidth,
        child: FlatButton(
          ...
        )
      )
    }
  )

If you want the button to be as big as its child, I believe you don't need to worry about anything other than providing the proper Text widget. FlatButton will figure out its size accordingly.


问:
Using Typescript types to ensure that all action types are handled by a reducer
I've attempted to create a kind of pattern-matching in typescript, particularly here for creating Redux reducers.

I'd really like to be able to specify ahead of time that a reducer must handle all actions of a particular type. I've tried to do that by creating an object which is keyed by action type, with values which are reducers. The typings for this mapping looks like:

export interface IReduxAction<T> {
    type: T;
}

interface IReducer<S, A> {
    (state: S, action: A): S;
}

export type IActionReducerMapping<S, A extends IReduxAction<string>> = Record<A['type'], IReducer<S, A>>;
```

<p>This does most of what I was planning; any mapping created for a given action type must implement all of the types of action. The problem is that, with how I've set up the typings, the reducers in the mapping aren't able to infer the exact type of their action. For instance:</p>

<pre class="lang-js prettyprint-override"><code>interface IUser {
    id: number;
    name: string;
    age: number;
}

interface IUserState {
    [id: number]: IUser;
}

interface IAddUserAction {
    type: 'ADD_USER';
    payload: IUser;
}

interface ISetUserNameAction {
    type: 'SET_USER_NAME';
    payload: {
        id: IUser['id'];
        name: IUser['name'];
    }
}

type UserAction = IAddUserAction | ISetUserNameAction;

const mapping: IActionReducerMapping<IUserState, UserAction> = {
    // here action is only aware of the properties on UserAction
    // ideally it'd know that it has access to the properties of
    // IAddUserAction
    'ADD_USER': (state, action) => ({
        ...state,
        [action.payload.id]: action.payload,
    }),

    'SET_USER_NAME': (state, action) => ({
        ...state,
        [action.payload.id]: {
            ...state[action.payload.id],
            name: action.payload.name,
        }
    }),
};
</code>```

The problem is that the action in each reducer is only the union type UserAction, and so age, for instance, is not accessible. Is there a way to setup typings with this sort of pattern such that:

I can ensure that all action types are handled, one way or another

I can setup reducers which know the type of the action they are given

答:
You can solve the problem with the action not having the correct type by using a custom mapped type that maps over all the types (A['type']) and uses the Extract conditional type to get the correct action type for each type name.

```<code>
export type IActionReducerMapping<S, A extends IReduxAction<string>> = {
    [K in A['type']]: IReducer<S, Extract<A, { type: K }>>
};
</code>```

Playground Link

Body:
I've attempted to create a kind of pattern-matching in typescript, particularly here for creating Redux reducers.

I'd really like to be able to specify ahead of time that a reducer must handle all actions of a particular type. I've tried to do that by creating an object which is keyed by action type, with values which are reducers. The typings for this mapping looks like:

export interface IReduxAction<T> {
    type: T;
}

interface IReducer<S, A> {
    (state: S, action: A): S;
}

export type IActionReducerMapping<S, A extends IReduxAction<string>> = Record<A['type'], IReducer<S, A>>;

This does most of what I was planning; any mapping created for a given action type must implement all of the types of action. The problem is that, with how I've set up the typings, the reducers in the mapping aren't able to infer the exact type of their action. For instance:

interface IUser {
    id: number;
    name: string;
    age: number;
}

interface IUserState {
    [id: number]: IUser;
}

interface IAddUserAction {
    type: 'ADD_USER';
    payload: IUser;
}

interface ISetUserNameAction {
    type: 'SET_USER_NAME';
    payload: {
        id: IUser['id'];
        name: IUser['name'];
    }
}

type UserAction = IAddUserAction | ISetUserNameAction;

const mapping: IActionReducerMapping<IUserState, UserAction> = {
    // here action is only aware of the properties on UserAction
    // ideally it'd know that it has access to the properties of
    // IAddUserAction
    'ADD_USER': (state, action) => ({
        ...state,
        [action.payload.id]: action.payload,
    }),

    'SET_USER_NAME': (state, action) => ({
        ...state,
        [action.payload.id]: {
            ...state[action.payload.id],
            name: action.payload.name,
        }
    }),
};

The problem is that the action in each reducer is only the union type UserAction, and so age, for instance, is not accessible. Is there a way to setup typings with this sort of pattern such that:

I can ensure that all action types are handled, one way or another

I can setup reducers which know the type of the action they are given

Body:
You can solve the problem with the action not having the correct type by using a custom mapped type that maps over all the types (A['type']) and uses the Extract conditional type to get the correct action type for each type name.

export type IActionReducerMapping<S, A extends IReduxAction<string>> = {
    [K in A['type']]: IReducer<S, Extract<A, { type: K }>>
};

<a href="https://www.typescriptlang.org/play/?ssl=11&ssc=3&pln=8&pc=1#code/KYDwDg9gTgLgBASwHY2FAZgQwMbDgSQCVgATAVxAEFsYEIkAeAFQD44BvAKDh7hgE8wwAFxwmAbk4BfTp2SoMOPEVJlcUBgGUANHEpsuvOAAoAzjEypROuDlr1RlAJTXJMzqEiw+g5dXtIxOTqALKYYGDIAOZaupRwoKhIJKYEQRT+dIzmUNEsbAC8HNy8ANoA0ohIeqUA5AJCtQC6TaIqwWixcACiIDBQdgyUuuw+QqKVUvnSkrLyaFi4BACqpmjFRggkokhkALYARmiSRkiYeyJwOdEnvJhRl7uHx9JzKAtKK2tQmhaoG2Utjt9kcoK0vi93PNFEt8JQSCRVmhMvQATwGpdapQACLYgD6y003UItVuPDAmH4ABsIJhthCoG43gpFspNMAYEioAA5c7AFHVQy8DGiWpEpgEomEPHcyghbqkkrkyk0umiIVGHhAhl1LbNMmas4XNpcupG4D6pVwGTuDFwLkCuBFOEIh00LJwAA+BHZnO+vIuAtm2Ho5jge3CkSQUTaAvSoUj0QY+C5v0swF0boChTRcCxuMlxNqojMfwztnd9CcTrYxg1moAdE3zOntFajKU7FkGxTqbSSA2tuCu-Qeyr+22jFInG2rWLuhLCcSZXKFSWW6hdCOkNWCrX60Ymw2Nxn22Vt2O+3TByRwQfNTwjyfO5WkJfVQOh5OH4a+aIL72H4Nua34PjIU4zjMQA" rel="nofollow noreferrer">Playground Link


问:
How to send json in response at Get Endpoint Odoo v11
Currently trying to call  a odoo controller which return json data as per my exception.

```<code>@http.route('/web/update_order_webhook', type='http', csrf=False, auth="public")
def update_order_webhook(self, **kwargs):
    return Response(json.dumps({"yes":"i am json"}),content_type='application/json;charset=utf-8',status=200)
</code>```

When I tried to call this end point

```<code>import requests

url = "http://159.89.197.219:8069/web/update_order_webhook"

headers = {
    'content-type': "application/json"
    }

response = requests.request("GET", url, headers=headers)

print(response.text)
</code>```

I get Request Body

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Invalid JSON data: ''</p>
</code>```

And Request Header at my calling end point

```<code>content-length →137
content-type →text/html
date →Thu, 11 Jan 2018 20:32:53 GMT
server →Werkzeug/0.13 Python/3.5.2
</code>```

that clearly mean that I am not getting json response data from my odoo endpoint.
As per last answer I had update my code

```<code>@http.route('/web/update_order_webhook', type='json', auth="public", website=True)
    def update_order_webhook(self, **kwargs):
         return json.dumps({"yes":"i am json"})
</code>```

But now I got new error while I called my endpoint

```<code>Bad Request
<function Binary.update_order_webhook at 0x7efd82ac8510>, /web/update_order_webhook: Function declared as capable of handling request of type 'json' but called with a request of type 'http'
</code>```

答:
Yes. ODOO HTTP GET METHOD 100% WORKS, JUST FOLLOW MY GUIDANCE.

Controller should be  type='json', not type='http'

"Hussain Ali" Absolute right on his Qustation, as solution with GET method I wrote below for ODOO

Note: I had given you solution with my sample code, you had to correct parameters as I had explain below.

```<code>import requests

url = "https://dev-expert.snippetbucket.com/api/get_user_information/"

headers = {
    'content-type': "application/json",
    'user-token': "02BXD2AGqVH-TEJASTANK-gg92DwntD8f1p0tb",
    'cache-control': "no-cache",
    }
payload = "{\"params\": {}}"
response = requests.request("GET", url, data=payload, headers=headers)

print(response.text)
</code>```

This solution absolute 100% works, Just data=payload need to add, that's works with odoo, latest versionn 13.0 as well. As of version 14 not release so can't say.

Solution works with odoo community and enterprise version as well.

Special Note:
Story behind seen, odoo type='json' in controller does not mean http json request. type='json' its json-rpc.

Regards,
Tejas - SnippetBucket.com

Body:
Currently trying to call  a odoo controller which return json data as per my exception.

@http.route('/web/update_order_webhook', type='http', csrf=False, auth="public")
def update_order_webhook(self, **kwargs):
    return Response(json.dumps({"yes":"i am json"}),content_type='application/json;charset=utf-8',status=200)

When I tried to call this end point

import requests

url = "http://159.89.197.219:8069/web/update_order_webhook"

headers = {
    'content-type': "application/json"
    }

response = requests.request("GET", url, headers=headers)

print(response.text)

I get Request Body

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>

Bad Request

Invalid JSON data: ''

And Request Header at my calling end point

content-length →137
content-type →text/html
date →Thu, 11 Jan 2018 20:32:53 GMT
server →Werkzeug/0.13 Python/3.5.2

that clearly mean that I am not getting json response data from my odoo endpoint.
As per last answer I had update my code

@http.route('/web/update_order_webhook', type='json', auth="public", website=True)
    def update_order_webhook(self, **kwargs):
         return json.dumps({"yes":"i am json"})

But now I got new error while I called my endpoint

Bad Request
<function Binary.update_order_webhook at 0x7efd82ac8510>, /web/update_order_webhook: Function declared as capable of handling request of type 'json' but called with a request of type 'http'

Body:
Yes. ODOO HTTP GET METHOD 100% WORKS, JUST FOLLOW MY GUIDANCE.

Controller should be  type='json', not type='http'

"Hussain Ali" Absolute right on his Qustation, as solution with GET method I wrote below for ODOO

Note: I had given you solution with my sample code, you had to correct parameters as I had explain below.

import requests

url = "https://dev-expert.snippetbucket.com/api/get_user_information/"

headers = {
    'content-type': "application/json",
    'user-token': "02BXD2AGqVH-TEJASTANK-gg92DwntD8f1p0tb",
    'cache-control': "no-cache",
    }
payload = "{\"params\": {}}"
response = requests.request("GET", url, data=payload, headers=headers)

print(response.text)

This solution absolute 100% works, Just data=payload need to add, that's works with odoo, latest versionn 13.0 as well. As of version 14 not release so can't say.

Solution works with odoo community and enterprise version as well.

Special Note:
Story behind seen, odoo type='json' in controller does not mean http json request. type='json' its json-rpc.

Regards,
Tejas - SnippetBucket.com


问:
backtracking depth first search algorithm in pseudocode
```<code>boolean backtrackDFS(v)  {
   If  (SolutionFound(v))  return true;
   Mark vertex v as reached.
   for (each unreached vertex u adjacenct from v)
        if (backtrakDFS(u)) return true;
   Unmark vertex v;
   return false;
}
</code>```

Here why Unmark vertex v is needed?
and why is it safe to add such line as hence v becomes unreached again, would it result in revisit?

答:
I don't think it's needed. It's usually just good practice to undo what you do, and leave things as they were when you found them.

For example, including that line would allow you to search using the same function more than once without a separate operation to clear the marks.

Body:
boolean backtrackDFS(v)  {
   If  (SolutionFound(v))  return true;
   Mark vertex v as reached.
   for (each unreached vertex u adjacenct from v)
        if (backtrakDFS(u)) return true;
   Unmark vertex v;
   return false;
}

Here why Unmark vertex v is needed?
and why is it safe to add such line as hence v becomes unreached again, would it result in revisit?


问:
Java - Math.asin() only returns 0
I've been struggling with Math.asin() for a while.

System.out.println(Math.toDegrees(Math.asin(1 / 2)));
```

This very simple line of code pretty much sums up my desperation: The result should be 30°, however, I only get 0.0 as a result. Its not just these numbers, no matter which numbers I use, the result is 0.0.
My question is, is this a known bug of Java, or am I missing something?

Bonus Information:
I need asin() to calculate the angle between the centerpoints of two objects in my game.

答:
You’re doing integer division, please add a decimal point in the end of each number like this:</p>

```<code>System.out.println(Math.toDegrees(Math.asin(1.0/2.0)))
</code>```

Title: Java - Math.asin() only returns 0

Body:
I've been struggling with Math.asin() for a while.

System.out.println(Math.toDegrees(Math.asin(1 / 2)));

This very simple line of code pretty much sums up my desperation: The result should be 30°, however, I only get 0.0 as a result. Its not just these numbers, no matter which numbers I use, the result is 0.0.
My question is, is this a known bug of Java, or am I missing something?

Bonus Information:
I need asin() to calculate the angle between the centerpoints of two objects in my game.

Body:
You’re doing integer division, please add a decimal point in the end of each number like this:

System.out.println(Math.toDegrees(Math.asin(1.0/2.0)))


问:
How to Show Notifications when get close to Beacon even if the app is closed?
I have created a mini App that helps me playing with beacons.

-what i have done so far-

So until now, I have successfully connected my App to the beacon, made 2 texts, so when I'm in the app and get in the beacon's range, the texts are changing so I can see that, move 2m away or turning the beacon upside down so it simulates Out of range, and it will show the message that I'm not in the range anymore.

So far so good, I have also successfully made the app to show notifications when I get close to the beacon, and when I click the notification to open a second activity.

-the problem-

Now, I want to show a notification when I get in the beacon's range, and the app is closed (not in the background). And after, when I click on that Notification to open my app / open App Google Play's Page if not installed.

I have searched on the internet but I haven't found anything conclusive.

If you guys know anything, or have you accomplished this task, it would be great if you can help with it.
If you need more info like, my activities code I can upload it, but I considered unimportant.

Thanks!

答:
You could create a BoradcastReceiver that intercept the android.intent.action.BOOT_COMPLETED.

In that way, you can launch a part of your app when you turn on the device.
There, you can use a Service or something that can manage the interactions with Beacons.
(BTW, i never worked with Beacons, i don't know what are the policies that you must follow).

If you don't need to launch the app when the device is turned on, anyway you can use a simple Service

Here the link to the documentation of receivers documentation.


问:
How to configure browserstack with protractor and mocha
so I am trying to figure out how to config more correctly with mobile and aswell with desktop. Before I explain my issue, I am using this code:

```<code>let SpecReporter = require('mochawesome').SpecReporter;

exports.config = {

    "browserstackUser": "helloworld",
    "browserstackKey": "123456789",

    multiCapabilities: [

        //{
        //  browserName: 'Android',
        //  device: 'Google Pixel 4 XL',
        //  os_version: '10.0',
        //  real_mobile: "true",
        //  project: "Selenium-Test",
        //  build: "Build T-Hour",
        //  name: "Pixel 4 XL Android - Happy Flow"
        //},

        {
            browserName: 'Chrome',
            device: 'Samsung Galaxy S9 Plus',
            os_version: '9.0',
            real_mobile: "true",
            project: "Selenium-Test",
            build: "Build T-Hour",
            name: "Samsung Galaxy S9 Plus Chrome - Happy Flow"
        }

    ],

    maxSessions: 1,

    mochaOpts: {
        reporter: "mochawesome",
        timeout: 60000,
    },

    suites: {
        all: 'pagesMobile/*.js',
    },

    framework: 'mocha',

};
</code>```

As you can see I have different multiCapabilities where I can add on different browsers whenever I want to test.

However my issue is that I do feel like I am doing it incorrectly because I have entered browserName : Chrome to test on however it still does Samsung browser instead and I am not sure what I am doing wrong anymore.

I do feel like I have set it up incorrectly and I am here asking what I am doing wrong that it doesn't want to run Chrome as a browser from Mobile and also if there is someone that is willing to tell me what I can improve aswell.

答: BrowserStack currently supports only the Chrome Browser on Android and the Safari Browser on iOS real mobile devices. So, your tests on the Samsung Mobile devices should execute on the Chrome Browser by default.</p>

Body:
so I am trying to figure out how to config more correctly with mobile and aswell with desktop. Before I explain my issue, I am using this code:

let SpecReporter = require('mochawesome').SpecReporter;

exports.config = {

    "browserstackUser": "helloworld",
    "browserstackKey": "123456789",

    multiCapabilities: [

        //{
        //  browserName: 'Android',
        //  device: 'Google Pixel 4 XL',
        //  os_version: '10.0',
        //  real_mobile: "true",
        //  project: "Selenium-Test",
        //  build: "Build T-Hour",
        //  name: "Pixel 4 XL Android - Happy Flow"
        //},

        {
            browserName: 'Chrome',
            device: 'Samsung Galaxy S9 Plus',
            os_version: '9.0',
            real_mobile: "true",
            project: "Selenium-Test",
            build: "Build T-Hour",
            name: "Samsung Galaxy S9 Plus Chrome - Happy Flow"
        }

    ],

    maxSessions: 1,

    mochaOpts: {
        reporter: "mochawesome",
        timeout: 60000,
    },

    suites: {
        all: 'pagesMobile/*.js',
    },

    framework: 'mocha',

};

As you can see I have different multiCapabilities where I can add on different browsers whenever I want to test.

However my issue is that I do feel like I am doing it incorrectly because I have entered browserName : Chrome to test on however it still does Samsung browser instead and I am not sure what I am doing wrong anymore.

I do feel like I have set it up incorrectly and I am here asking what I am doing wrong that it doesn't want to run Chrome as a browser from Mobile and also if there is someone that is willing to tell me what I can improve aswell.


问:
How to show react variable values in loop in table td tag
i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

```<code>let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })
</code>```

My td code is:

```<code><tr>
  <td className="font-weight-medium"> <img className="logo" src={jessica} alt="pam-logo" /> </td>
  <td>jessicajames@gmail.com </td>
  <td>(012)-876789876</td>
  <td>Family Physician</td>
  <td>23145655</td>
  <td>Mountain view,Ave</td>
  <td><Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/></td>
</tr>
</code>```

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

答:
Your axios call should ordinarily be in an initialization stage, such as by employing useEffect or componentDidMount, depending on the style of your component.

Then you set the data using your response, e.g.

```<code>setData(response.data);
</code>```

or

```<code>this.setState({"myData": response.data});
</code>```

and in your render, you use that data loop to generate the rows, something along the lines of:

```<code>const { myData } = this.state;
myData.map((datum, index) => {
   <tr key={index}>
     <td>{datum.provider.firstName}</td>
     ...
   </tr>
});
</code>```

Body:
i use axios to get values, now i want to display the values in td tag in a loop how to execute it.

my code is :

let apiUrl = "http://api_url_here";
axios.get(apiUrl, {headers: headers})
  .then((response) => {
    console.log(response.data[0].provider.firstName);
    //console.log(token);[0]
  })

My td code is:

  jessicajames@gmail.com
  (012)-876789876
  Family Physician
  23145655
  Mountain view,Ave
  <Icon icon={editIcon} width="20px"/>  <Icon icon={deleteIcon} width="20px"/>

I need that response.data[0].provider.firstName in 1st td and correspondingly the same for all and it should be in loop to get next iteration.

Body:
Your axios call should ordinarily be in an initialization stage, such as by employing useEffect or componentDidMount, depending on the style of your component.

Then you set the data using your response, e.g.

setData(response.data);

or

this.setState({"myData": response.data});

and in your render, you use that data loop to generate the rows, something along the lines of:

const { myData } = this.state;
myData.map((datum, index) => {
   <tr key={index}>
     <td>{datum.provider.firstName}</td>
     ...
   </tr>
});


问:
Set a variable equal to null if it is not included in an array?
If I have something like,

```<code>const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']
</code>```

Is it possible to make anotherProperty = null?

答:
You can use Array.prototype.reduce

let properties = [
  'someProperty',
  'anotherProperty',
  'thirdProperty'
]

const includeProperties = ['someProperty', 'thirdProperty'];

let object = properties.reduce((acc, val) => {

  if (includeProperties.indexOf(val) === -1)
    acc[val] = null;
  else
    acc[val] = 'some value';

  return acc;
}, {});

console.log(object);```

Body:
If I have something like,

const {
  someProperty,
  anotherProperty,
  thirdProperty
} = someObject;

const includeProperties = ['someProperty', 'thirdProperty']

Is it possible to make anotherProperty = null?


问:
Can we use Selenium or any other jars to get network response and validate
I have a requirement here that I need to verify the network response values using selenium & java.

It would be great if there is any code that could help me out.

The action that I want to perform (which is needed to be automated) is

load the application https://www.ancestry.com

press F12 and go to network tab when application is loading

select a respective network containing b/ss

click on it and get the values in the query parameters

I have highlighted them in the below image

Note: I need to perform this action for every click event that happen after the application is loaded.

Is this possible in selenium

This is the code that I tried to get the values recorded am I doing it right please help

```<code>public static void main(String[] args) throws IOException {
    System.setProperty("webdriver.chrome.driver",
            new File(".").getCanonicalPath() + "\\WebDriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.ancestry.com");
    //capture(driver);
    driver.quit();
}

public static void capture(WebDriver driver) throws IOException {
    OutputStream logfile = new FileOutputStream(new File(new
    File(".").getCanonicalPath() + "\\log.txt"), true);
    PrintStream printlog = new PrintStream(logfile);
    LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);
    for (LogEntry entry : logs) {
        if (entry.toString().contains("\"type\":\"Img\""))
            System.out.println(entry.toString());

        printlog.append(new Date(entry.getTimestamp()) + " " + entry.toString() + " "
                + System.getProperty("line.separator"));
        printlog.append(System.getProperty("line.separator"));
        printlog.append(System.getProperty("line.separator"));
    }
    printlog.close();
}
</code>```

答:
We can get all the network logs using browser mob proxy

```<code>private static BrowserMobProxy proxy = new BrowserMobProxyServer();
public webLib(String browser) {
        logReport.logMethodStart("Launch Application");
        Proxy seleniumProxy = null;
        proxy.start();
        seleniumProxy = ClientUtil.createSeleniumProxy(proxy);

        if (browser.equalsIgnoreCase("chrome")) {
            try {
                System.setProperty("webdriver.chrome.driver",
                        new File(".").getCanonicalFile() + seperator + "WebDriver" + seperator + "chromeDriver.exe");
            } catch (IOException e) {
                e.printStackTrace();
            }

            ChromeOptions options = new ChromeOptions();

            options.setCapability(CapabilityType.PROXY, seleniumProxy);
            options.setAcceptInsecureCerts(true);
            options.addArguments("--ignore-certificate-errors");
            options.addArguments("--disable-popup-blocking");
            options.addArguments("--no-sandbox");
            options.addArguments("--no-sandbox");

            driver = new ChromeDriver(options);
        } else if (browser.equalsIgnoreCase("firefox")) {

        }

        driver.manage().deleteAllCookies();
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        if (driver != null) {
            logReport.logStep(Status.PASS, "Browser launched successfully", driver);
        }

    }
</code>```

You can reffer the following site
https://www.swtestacademy.com/webdriver-browsermob-proxy/

Body:
I have a requirement here that I need to verify the network response values using selenium & java.

It would be great if there is any code that could help me out.

The action that I want to perform (which is needed to be automated) is

load the application https://www.ancestry.com

press F12 and go to network tab when application is loading

select a respective network containing b/ss

click on it and get the values in the query parameters

I have highlighted them in the below image

Note: I need to perform this action for every click event that happen after the application is loaded.

Is this possible in selenium

This is the code that I tried to get the values recorded am I doing it right please help

public static void main(String[] args) throws IOException {
    System.setProperty("webdriver.chrome.driver",
            new File(".").getCanonicalPath() + "\\WebDriver\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.ancestry.com");
    //capture(driver);
    driver.quit();
}

public static void capture(WebDriver driver) throws IOException {
    OutputStream logfile = new FileOutputStream(new File(new
    File(".").getCanonicalPath() + "\\log.txt"), true);
    PrintStream printlog = new PrintStream(logfile);
    LogEntries logs = driver.manage().logs().get(LogType.PERFORMANCE);
    for (LogEntry entry : logs) {
        if (entry.toString().contains("\"type\":\"Img\""))
            System.out.println(entry.toString());

        printlog.append(new Date(entry.getTimestamp()) + " " + entry.toString() + " "
                + System.getProperty("line.separator"));
        printlog.append(System.getProperty("line.separator"));
        printlog.append(System.getProperty("line.separator"));
    }
    printlog.close();
}

Body:
We can get all the network logs using browser mob proxy

private static BrowserMobProxy proxy = new BrowserMobProxyServer();
public webLib(String browser) {
        logReport.logMethodStart("Launch Application");
        Proxy seleniumProxy = null;
        proxy.start();
        seleniumProxy = ClientUtil.createSeleniumProxy(proxy);

        if (browser.equalsIgnoreCase("chrome")) {
            try {
                System.setProperty("webdriver.chrome.driver",
                        new File(".").getCanonicalFile() + seperator + "WebDriver" + seperator + "chromeDriver.exe");
            } catch (IOException e) {
                e.printStackTrace();
            }

            ChromeOptions options = new ChromeOptions();

            options.setCapability(CapabilityType.PROXY, seleniumProxy);
            options.setAcceptInsecureCerts(true);
            options.addArguments("--ignore-certificate-errors");
            options.addArguments("--disable-popup-blocking");
            options.addArguments("--no-sandbox");
            options.addArguments("--no-sandbox");

            driver = new ChromeDriver(options);
        } else if (browser.equalsIgnoreCase("firefox")) {

        }

        driver.manage().deleteAllCookies();
        driver.manage().window().maximize();
        driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        if (driver != null) {
            logReport.logStep(Status.PASS, "Browser launched successfully", driver);
        }

    }

You can reffer the following site
https://www.swtestacademy.com/webdriver-browsermob-proxy/


问:
Approach for associated model searching with Elasticsearch [Ruby, ActiveRecord, elasticsearch-model]
I have a question about choosing the best approach in case of searching in Elasticsearch.

I have Ruby off Rails API, with ActiveRecord, together with Elasticsearch ( elasticsearch-model gem).

It's a simple API which returns projects (Project AR model), where I set up indexes:

```<code>mapping dynamic: false do
indexes :created_at, type: 'date'
end
</code>```

Then I simply make a search on Elasticsearch and return AR relations directly from the controller. It's working perfectly.

Now I am trying to add categories to projects, as categories has_many projects, and projects belongs_to categories. I am wondering about two things:

How now should I make a query to get projects from specific categories, should I reimplement it to return result = Category.search(...) and return result.jobs, or still seeking by projects, but searching by category_id?

How to combine Category and Project in Elasticsearch to make possible to search for projects from a specific category, and from various multiple categories? Merge mappings?

Thanks in advance!

答:
My first though here is that you're use case is very simple. You don't need Elasticsearch at all. You can simplify and use just ActiveRecord, select by SQL and return records. You don't need any of the features provided by Elasticsearch for your use case, you're just creating more work for yourself by doing so.

However, I'll assume your developing iteratively and your usage will get significantly more complex. Justifying the use of Elasticsearch.

Relational and Non-Relational Data

ActiveRecord is a ORM for relational data. Typicalhttps://www.elastic.co/guide/en/elasticsearch/reference/current/documents-indices.htmlly it sits on top of a Structured Query Language powered relational database. It supports relations (associations in Rails parlance) really well.

Elasticsearch is a non relational document store, storing information as JSON in an inverted index. This allows for very quick full-text search (amongst other uses). It doesn't support relations between documents very well. It is designed to not relate data! It wants you to not store relations and to instead repeat data constantly, the opposite of the SQL approach. This is called denormalization, more on this below.

These are very different ways of think about data storage! That doesn't mean they don't play well together. They can work well together if used correctly. However, they take different ways of thinking. It's important to have a good grasp of the fundamentals behind each in order to make sound judgements on how to use them, in my opinion.

Elasticsearch has great documentation. I recommend you spend a couple hours reading up on it.

How does  Elasticsearch do associations?

You care about a basic has-many association in your question, so how does Elastic handle these? What are the options?

There are 4 major options. I think you should denormalize your data here.

I think you want to return all projects from certain categories. So you should create a index which contains a document per category. Each category should have within it a complete list of it's projects. You can then query for a category and return all it's projects.

This is one approach. Your use case is so simple that it feels like overkill to me, you could solve this using any of the 4 major options for Elasticsearch linked above. Or ideally by not using Elasticsearch at all.

If you provide more detail on your use case, I'd be able to discuss more what approach you could use.

Body:
I have a question about choosing the best approach in case of searching in Elasticsearch.

I have Ruby off Rails API, with ActiveRecord, together with Elasticsearch ( elasticsearch-model gem).

It's a simple API which returns projects (Project AR model), where I set up indexes:

mapping dynamic: false do
indexes :created_at, type: 'date'
end

Then I simply make a search on Elasticsearch and return AR relations directly from the controller. It's working perfectly.

Now I am trying to add categories to projects, as categories has_many projects, and projects belongs_to categories. I am wondering about two things:

How now should I make a query to get projects from specific categories, should I reimplement it to return result = Category.search(...) and return result.jobs, or still seeking by projects, but searching by category_id?

How to combine Category and Project in Elasticsearch to make possible to search for projects from a specific category, and from various multiple categories? Merge mappings?

Thanks in advance!


问:
nodemailer multiple recipients different context
I am trying to implement a method to send emails to multiple recipients but also I want to pass to the html template the user attribute which will have the name of the recipient. (I AM USING NODEMAILER as a nodejs module)

My code in this stage is like this:

```<code>SellerMatched: function (fromUser, offer, cb) {

        var maillist  = [];
        var users = [];

        for (var i=0; i<fromUser.length; i++)
        {
            maillist[i]=fromUser[i].email;
            users[i] = fromUser[i].Name;
        }

        maillist.toString();
        users.toString();

        mail.sendMail({
            from: 'Website Support <help@domain.com>',
            to: maillist,
            subject: 'Seller Matched',
            template: 'SellerMatch',
            context: {
                user: users,
                username: offer.owner.username,
                OfferName: offer.name,
                category: offer.category
            }
        }, cb);
    }
</code>```

and the html have those attributes: It's something like this:

```<code>...

Hi {{user}},

A offer is uploaded that matched your preference.
Offer detail:
Name : {{OfferName}}
By: {{username}}
Category: {{category}}

....
</code>```

This is working properly, emails are sent to the recipients but in the attribute Hi {{user}}, I want to show only the name of recipient because now it shows the array of all recipients.

Thanks

答:
Right now you are sending one Email to a list of recipients. I guess what you want to do is send one Email to each recipient in the list so you can set the greeting per recipient.

```<code>SellerMatched: function (fromUser, offer, cb) {

    for (var i=0; i<fromUser.length; i++)
    {
        mail.sendMail({
            from: 'Website Support <help@domain.com>',
            to: fromUser[i].email,
            subject: 'Seller Matched',
            template: 'SellerMatch',
            context: {
                user: fromUser[i].Name,
                username: offer.owner.username,
                OfferName: offer.name,
                category: offer.category
            }
        }, cb);
    }
}
</code>```

Body:
I am trying to implement a method to send emails to multiple recipients but also I want to pass to the html template the user attribute which will have the name of the recipient. (I AM USING NODEMAILER as a nodejs module)

My code in this stage is like this:

SellerMatched: function (fromUser, offer, cb) {

        var maillist  = [];
        var users = [];

        for (var i=0; i<fromUser.length; i++)
        {
            maillist[i]=fromUser[i].email;
            users[i] = fromUser[i].Name;
        }

        maillist.toString();
        users.toString();

        mail.sendMail({
            from: 'Website Support <help@domain.com>',
            to: maillist,
            subject: 'Seller Matched',
            template: 'SellerMatch',
            context: {
                user: users,
                username: offer.owner.username,
                OfferName: offer.name,
                category: offer.category
            }
        }, cb);
    }

and the html have those attributes: It's something like this:

...

Hi {{user}},

A offer is uploaded that matched your preference.
Offer detail:
Name : {{OfferName}}
By: {{username}}
Category: {{category}}

....

This is working properly, emails are sent to the recipients but in the attribute Hi {{user}}, I want to show only the name of recipient because now it shows the array of all recipients.

Thanks

Body:
Right now you are sending one Email to a list of recipients. I guess what you want to do is send one Email to each recipient in the list so you can set the greeting per recipient.

SellerMatched: function (fromUser, offer, cb) {

    for (var i=0; i<fromUser.length; i++)
    {
        mail.sendMail({
            from: 'Website Support <help@domain.com>',
            to: fromUser[i].email,
            subject: 'Seller Matched',
            template: 'SellerMatch',
            context: {
                user: fromUser[i].Name,
                username: offer.owner.username,
                OfferName: offer.name,
                category: offer.category
            }
        }, cb);
    }
}


问:
How to compare date if one column has start and end date
The column has a start and end date

```<code>month_name
23 March, 2018 - 23 April, 2018
</code>```

23 March, 2018 is the start date and 23 April, 2018 is the end date

How can I use them as to the start date and end date to query?

答:
```<code>set @fromto='23 March, 2018 - 23 April, 2018';
select
  str_to_date(left(@fromto,locate('-',@fromto)-1),'%d %M,%Y') datefrom,
  str_to_date(right(@fromto,length(@fromto)-locate('-',@fromto)),'%d %M,%Y') dateto;
</code>```

output:

```<code>+------------+------------+
| datefrom   | dateto     |
+------------+------------+
| 2018-03-23 | 2018-04-23 |
+------------+------------+
</code>```

short explanation:

set @fromto - defines a variable, which is used as input for this example

locate('-',@fromto)  - this will find the length of the part in @fromto before the '-', the -1 is needed because where only want the part before the '-'

length(@fromto)-locate('-',@fromto) - this will find the length of the part in @fromto after the '-'

str_to_date(...)  - see STR_TO_DATE

Body:
The column has a start and end date

month_name
23 March, 2018 - 23 April, 2018

23 March, 2018 is the start date and 23 April, 2018 is the end date

How can I use them as to the start date and end date to query?

Body:
set @fromto='23 March, 2018 - 23 April, 2018';
select
  str_to_date(left(@fromto,locate('-',@fromto)-1),'%d %M,%Y') datefrom,
  str_to_date(right(@fromto,length(@fromto)-locate('-',@fromto)),'%d %M,%Y') dateto;

output:

+------------+------------+
| datefrom   | dateto     |
+------------+------------+
| 2018-03-23 | 2018-04-23 |
+------------+------------+

short explanation:

set @fromto - defines a variable, which is used as input for this example

locate('-',@fromto)  - this will find the length of the part in @fromto before the '-', the -1 is needed because where only want the part before the '-'

length(@fromto)-locate('-',@fromto) - this will find the length of the part in @fromto after the '-'

str_to_date(...)  - see STR_TO_DATE


问:
django how to see sql query when running tests?
One of my django application unit test fails with

```<code>DatabaseError: ORA-00942: table or view does not exist
</code>```

I would like to see actual SQL query that caused this error. Do you know how to achieve that?

答:
Another option is to use CaptureQueriesContext (tested with pytest).

from django.db import connection
from django.test.utils import CaptureQueriesContext

def test_foo():
    with CaptureQueriesContext(connection) as ctx:
        # code that runs SQL queries
        print(ctx.captured_queries)
```

Sources:

https://blog.ploetzli.ch/2019/showing-sql-queries-with-pytest-and-django/

How to force django to print each executed sql query

Body:
One of my django application unit test fails with

DatabaseError: ORA-00942: table or view does not exist

I would like to see actual SQL query that caused this error. Do you know how to achieve that?

Body:
Another option is to use CaptureQueriesContext (tested with pytest).

from django.db import connection
from django.test.utils import CaptureQueriesContext

def test_foo():
    with CaptureQueriesContext(connection) as ctx:
        # code that runs SQL queries
        print(ctx.captured_queries)

Sources:

https://blog.ploetzli.ch/2019/showing-sql-queries-with-pytest-and-django/

How to force django to print each executed sql query


问:
Select row id that has unique value provided
I have a table called category in which a user can store the value of a spending category. Here food and sports is one combination and they have the same cat_id in the database.

```<code>cat_id  spending_category
1       food
1       sport
2       food
2       sport
2       movie
3       food
3       movie
</code>```

I want to query this table and find out if there is already an existing category combination of only food and sport. if yes return that id.i want to used that id to tag the similar id, which means I should get 1 here. not 2 because id 2 is a combination of food, sport and movie.

答:
```<code>SELECT cat_id
FROM category
GROUP BY cat_id
HAVING SUM(spending_category = 'food') + SUM(spending_category = 'sport') = COUNT(*)
</code>```

The conditions in the SUM() functions return 1 or 0. Just compare it to the number of entries in each group.

cat_id 2 would have 3 entries, therefore it would not be returned.

Body:
I have a table called category in which a user can store the value of a spending category. Here food and sports is one combination and they have the same cat_id in the database.

cat_id  spending_category
1       food
1       sport
2       food
2       sport
2       movie
3       food
3       movie

I want to query this table and find out if there is already an existing category combination of only food and sport. if yes return that id.i want to used that id to tag the similar id, which means I should get 1 here. not 2 because id 2 is a combination of food, sport and movie.

Body:
SELECT cat_id
FROM category
GROUP BY cat_id
HAVING SUM(spending_category = 'food') + SUM(spending_category = 'sport') = COUNT(*)

The conditions in the SUM() functions return 1 or 0. Just compare it to the number of entries in each group.

cat_id 2 would have 3 entries, therefore it would not be returned.


问:
DocuSign - Embedded Signing in a native application
I would like to know if it is possible to use signatures embedded in a native Windows-based application to make face-to-face signing possible.

I have seen that it is possible to use this for a web application but is it possible for an application running under Windows?

If so, what APIs should be used?

答:
Yes, by using a web view component. The signing ceremony itself is hosted by DocuSign and displayed using a browser-like window in your app. For Windows, WebView2 or similar.

APIs will be the same as for any other DocuSign embedded signing application:

Authentication to obtain an access token. Probably implicit grant or perhaps a different grant if used in conjunction with a secure server component.

Send the envelope using Envelopes:create

Obtain a URL for the signing ceremony via EnvelopeViews:recipientView.

See the curl example, workflow 1.


问:
What project would you recommend me to get up to speed with C++
I know that C++ is a very complex language that takes many years of practice to master.

Taking that into account do you know of a small project (around a 1k of loc) that tests all of C++ major features (inheritance, pointers, memory management, etc).

The thing is I'm a Java/Python programmer and I really want to learn C++ so I've been studying C++ for a while but haven't tested anything of what I've learned beyond small exercises.

I want to take all of that knowledge and put into practice.

答:
An interactive world:
A matrix where each position can be a Void or a Being.
A Being is something with a few attributes: age, Time left, gender, neigbor connections, etc. Capable a few interactions: fights, having sex and kids, friendships, etc. Some have special Skills, depending on their fathers (inherited trades)... like ability to kill, ability to make food,, etc...
Possible outcomes of those interactions and skills are changes on the self attributes, or creating offspring (when possible), or change neigbor attributes.

At each iteration, print the matrix as symbols/numbers on the console (depending on the attributes, etc), starting from a Biblical iteration 0 (initial conditions of your choice... you're God here).

Now you got some real-life pattern simulator, and learned something about inheritance, polimorfism, virtual functions, instantiation of classes, etc.

OwnerDisplayName: climatewarrior

ContentLicense: CC BY-SA 2.5


问:
Easier way to serialize C# class as XML text
While trying to answer another question, I was serializing a C# object to an XML string.  It was surprisingly hard; this was the shortest code snippet I could come up with:

```<code>var yourList = new List<int>() { 1, 2, 3 };
var ms = new MemoryStream();
var xtw = new XmlTextWriter(ms, Encoding.UTF8);
var xs = new XmlSerializer(yourList.GetType());
xs.Serialize(xtw, yourList);
var encoding = new UTF8Encoding();
string xmlEncodedList = encoding.GetString(ms.GetBuffer());
</code>```

The result is okay:

```<code><?xml version="1.0" encoding="utf-8"?>
<ArrayOfInt
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <int>1</int>
    <int>2</int>
    <int>3</int>
</ArrayOfInt>
</code>```

But the snippet is more complicated than I think it should be.  I can't believe you have to know about encoding and MemoryStream for this simple task.

Is there a shorter way to serialize an object to an XML string?

答:
Simply if you want to use UTF8 encoding then do it like this

```<code>public class StringWriterUtf8 : System.IO.StringWriter
{
    public override Encoding Encoding
    {
        get
        {
            return Encoding.UTF8;
        }
    }

}
</code>```

and then use StringWriterUtf8 insread of StringWriter like this

```<code>        using (StringWriterUtf8 textWriter = new StringWriterUtf8())
        {

            serializer.Serialize(textWriter, tr, ns);

            xmlText = textWriter.ToString();
        }
</code>```

Body:
While trying to answer another question, I was serializing a C# object to an XML string.  It was surprisingly hard; this was the shortest code snippet I could come up with:

var yourList = new List<int>() { 1, 2, 3 };
var ms = new MemoryStream();
var xtw = new XmlTextWriter(ms, Encoding.UTF8);
var xs = new XmlSerializer(yourList.GetType());
xs.Serialize(xtw, yourList);
var encoding = new UTF8Encoding();
string xmlEncodedList = encoding.GetString(ms.GetBuffer());

The result is okay:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfInt
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <int>1</int>
    <int>2</int>
    <int>3</int>
</ArrayOfInt>

But the snippet is more complicated than I think it should be.  I can't believe you have to know about encoding and MemoryStream for this simple task.

Is there a shorter way to serialize an object to an XML string?

Body:
Simply if you want to use UTF8 encoding then do it like this

public class StringWriterUtf8 : System.IO.StringWriter
{
    public override Encoding Encoding
    {
        get
        {
            return Encoding.UTF8;
        }
    }

}

and then use StringWriterUtf8 insread of StringWriter like this

        using (StringWriterUtf8 textWriter = new StringWriterUtf8())
        {

            serializer.Serialize(textWriter, tr, ns);

            xmlText = textWriter.ToString();
        }


问:
How to match new-line character using regex
I'm trying to match the special characters and the breaks using a regex to cleanse the string so that I'm left with only the following string 'All release related activities' extracted from the following line:

```<code>{"Well":"\n\n\t\n\t\n\n\t\n\tAll release related activities\n\n\t"}
</code>```

I've tried the regex ^{.Well":" and I'm able to match till  the first colon appears. How do I match the \n characters in the string?

答:
Try:

```<code>/":"(?:\\[nt])*(.*)}"$/
</code>```

See Regex Demo

":" Matches ":".

(?:\\[nt])* Matches 0 or more occurrences of either \n or \t.

(.*) Matches 0 or more characters in Capture Group 1 until:

}"$ Matches }" followed by the end of the string.

The string you are looking for is in Capture Group 1.

Body:
I'm trying to match the special characters and the breaks using a regex to cleanse the string so that I'm left with only the following string 'All release related activities' extracted from the following line:

{"Well":"\n\n\t\n\t\n\n\t\n\tAll release related activities\n\n\t"}

I've tried the regex ^{.Well":" and I'm able to match till  the first colon appears. How do I match the \n characters in the string?

Body:
Try:

/":"(?:\\[nt])*(.*)}"$/

See Regex Demo

":" Matches ":".

(?:\\[nt])* Matches 0 or more occurrences of either \n or \t.

(.*) Matches 0 or more characters in Capture Group 1 until:

}"$ Matches }" followed by the end of the string.

The string you are looking for is in Capture Group 1.