答:
I finally found the solution (sort of). It's enough to change keras to tensorflow.keras.

Revised Code

```<code># Based on examples from "Deep Learning with Python" by François Chollet:
## Constants, modules:
VERSION = 2

import os
#U: from keras import models
#U: from keras import layers
from tensorflow.keras import models
from tensorflow.keras import layers

import matplotlib.pyplot as plt
import pylab

## Loading data:
from keras.datasets import imdb

(x_train, y_train), (x_test, y_test) = \
    imdb.load_data(num_words=10000)

from keras.preprocessing import sequence

x_train = sequence.pad_sequences(x_train, maxlen=500)
x_test = sequence.pad_sequences(x_test, maxlen=500)

## Dictionary with models' hyperparameters:
MODELS_ALL = [
    # GRU:
    {"no": 1,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 2,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 3,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 4,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 5,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 6,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 7,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 8,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    # LSTM:
    {"no": 9,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 10,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 11,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 12,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 13,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 14,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 15,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 16,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},
]

MODELS_GRU_RECCURENT = [
    # GRU:
    {"no": 3,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 4,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 7,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 8,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},
]

MODELS = MODELS_ALL   # "MODELS = MODELS_ALL" or "MODELS = MODELS_GRU_RECCURENT"

## Adding name:
for model_dict in MODELS:
    model_dict["name"] = f"{model_dict['layer_type']}"
    model_dict["name"] += f"_d{model_dict['dropout']}" if model_dict['dropout'] is not None else f"_dN"
    model_dict["name"] += f"_rd{model_dict['recurrent_dropout']}" if model_dict['recurrent_dropout'] is not None else f"_rdN"
    model_dict["name"] += f"_{model_dict['optimizer']}"

## Fucntion - defing and training model:
def train_model(model_dict):
    """Defines and trains a model, outputs history."""

    ## Defining:
    model = models.Sequential()
    model.add(layers.Embedding(10000, 32))

    recurrent_layer_kwargs = dict()
    if model_dict["dropout"] is not None:
        recurrent_layer_kwargs["dropout"] = model_dict["dropout"]
    if model_dict["recurrent_dropout"] is not None:
        recurrent_layer_kwargs["recurrent_dropout"] = model_dict["recurrent_dropout"]

    if model_dict["layer_type"] == 'GRU':
        model.add(layers.GRU(32, **recurrent_layer_kwargs))
    elif model_dict["layer_type"] == 'LSTM':
        model.add(layers.LSTM(32, **recurrent_layer_kwargs))
    else:
        raise ValueError("Wrong model_dict['layer_type'] value...")
    model.add(layers.Dense(1, activation='sigmoid'))

    ## Compiling:
    model.compile(
        optimizer=model_dict["optimizer"],
        loss='binary_crossentropy',
        metrics=['accuracy'])

    ## Training:
    history = model.fit(x_train, y_train,
                        epochs=20,
                        batch_size=64,
                        validation_split=0.2)

    return history

## Multi-model graphs' parameters:
graph_all_nrow = 4
graph_all_ncol = 4
graph_all_figsize = (20, 20)

assert graph_all_nrow * graph_all_nrow >= len(MODELS)

# fig and axes of multi-model graphs:
graph_all_loss_fig, graph_all_loss_axs = plt.subplots(graph_all_nrow, graph_all_ncol, figsize=graph_all_figsize)
graph_all_acc_fig, graph_all_acc_axs = plt.subplots(graph_all_nrow, graph_all_ncol, figsize=graph_all_figsize)

## Loop trough all models:
for i, model_dict in enumerate(MODELS):
    history = train_model(model_dict)

    ## Metrics extraction:
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']

    epochs = range(1, len(loss) + 1)

    ## Single-model graph - loss:
    graph_loss_fname = fr"{os.path.basename(__file__).replace('.py', '')}"
    graph_loss_fname += fr"_v{VERSION}_{model_dict['no']}_{model_dict['name']}_loss_graph.png"

    graph_loss_fig, graph_loss_ax = plt.subplots()
    graph_loss_ax.plot(epochs, loss, 'bo', label='Training loss')
    graph_loss_ax.plot(epochs, val_loss, 'b', label='Validation loss')
    graph_loss_ax.legend()
    graph_loss_fig.suptitle("Training and validation loss")
    graph_loss_fig.savefig(graph_loss_fname)
    pylab.close(graph_loss_fig)

    ## Single-model graph - accuracy:
    graph_acc_fname = fr"{os.path.basename(__file__).replace('.py', '')}"
    graph_acc_fname += fr"_v{VERSION}_{model_dict['no']}_{model_dict['name']}_acc_graph.png"

    graph_acc_fig, graph_acc_ax = plt.subplots()
    graph_acc_ax.plot(epochs, acc, 'bo', label='Training accuracy')
    graph_acc_ax.plot(epochs, val_acc, 'b', label='Validation accuracy')
    graph_acc_ax.legend()
    graph_acc_fig.suptitle("Training and validation acc")
    graph_acc_fig.savefig(graph_acc_fname)
    pylab.close(graph_acc_fig)

    ## Position of axes on multi-model graph:
    i_row = i // graph_all_ncol
    i_col = i % graph_all_ncol

    ## Adding model metrics to multi-model graph - loss:
    graph_all_loss_axs[i_row, i_col].plot(epochs, loss, 'bo', label='Training loss')
    graph_all_loss_axs[i_row, i_col].plot(epochs, val_loss, 'b', label='Validation loss')
    graph_all_loss_axs[i_row, i_col].set_title(fr"{model_dict['no']}. {model_dict['name']}")

    ## Adding model metrics to multi-model graph - accuracy:
    graph_all_acc_axs[i_row, i_col].plot(epochs, acc, 'bo', label='Training acc')
    graph_all_acc_axs[i_row, i_col].plot(epochs, val_acc, 'b', label='Validation acc')
    graph_all_acc_axs[i_row, i_col].set_title(fr"{model_dict['no']}. {model_dict['name']}")

graph_all_loss_fig.suptitle(f"Loss - binary crossentropy [v{VERSION}]")
graph_all_acc_fig.suptitle(f"Accuracy [v{VERSION}]")

## Saving multi-model graphs:
graph_all_loss_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_loss_graph.png", dpi=400)
graph_all_acc_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_acc_graph.png", dpi=400)

## Saving multi-model graphs (SMALL):
graph_all_loss_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_loss_graph_SMALL.png", dpi=150)
graph_all_acc_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_acc_graph_SMALL.png", dpi=150)
</code>```

Results

Graphs analogous to those in question: Loss - binary crossentropy, Accuracy

More on keras vs tensorflow.keras

As written in François Chollet's tweets (found here: https://stackoverflow.com/a/54117754) instead of stand-alone keras there will be tensorflow.keras (that is Keras as official API to TensorFlow) from now on. (I'm not completely sure if I'm 100% correct, feel free to correct me.)

I think it's better just to use tensorflow.keras instead of keras in future projects.

Title: Keras - GRU layer with recurrent dropout - loss: 'nan', accuracy: 0

Body:
Problem description

I am going through "Deep Learning in Python" by François Chollet (publisher webpage, notebooks on github). Replicating examples from Chapter 6 I encountered problems with (I believe) GRU layer with recurrent dropout.

The code in which I had first observed those errors is quite long, so I decided to stick to the simplest problem, which could replicate the error: classifying IMDB reviews into "positive" and "negative" categories.

When I use a GRU layer with recurrent dropout training loss (after couple of batches of first epoch) takes "value" of nan, while training accuracy (from the start of second epoch) takes the value of 0.

   64/12000 [..............................] - ETA: 3:05 - loss: 0.6930 - accuracy: 0.4844
  128/12000 [..............................] - ETA: 2:09 - loss: 0.6926 - accuracy: 0.4766
  192/12000 [..............................] - ETA: 1:50 - loss: 0.6910 - accuracy: 0.5573
(...)
 3136/12000 [======>.......................] - ETA: 59s - loss: 0.6870 - accuracy: 0.5635
 3200/12000 [=======>......................] - ETA: 58s - loss: 0.6862 - accuracy: 0.5650
 3264/12000 [=======>......................] - ETA: 58s - loss: 0.6860 - accuracy: 0.5650
 3328/12000 [=======>......................] - ETA: 57s - loss: nan - accuracy: 0.5667
 3392/12000 [=======>......................] - ETA: 57s - loss: nan - accuracy: 0.5560
 3456/12000 [=======>......................] - ETA: 56s - loss: nan - accuracy: 0.5457
(...)
11840/12000 [============================>.] - ETA: 1s - loss: nan - accuracy: 0.1593
11904/12000 [============================>.] - ETA: 0s - loss: nan - accuracy: 0.1584
11968/12000 [============================>.] - ETA: 0s - loss: nan - accuracy: 0.1576
12000/12000 [==============================] - 83s 7ms/step - loss: nan - accuracy: 0.1572 - val_loss: nan - val_accuracy: 0.0000e+00
Epoch 2/20

   64/12000 [..............................] - ETA: 1:16 - loss: nan - accuracy: 0.0000e+00
  128/12000 [..............................] - ETA: 1:15 - loss: nan - accuracy: 0.0000e+00
  192/12000 [..............................] - ETA: 1:16 - loss: nan - accuracy: 0.0000e+00
(...)
11840/12000 [============================>.] - ETA: 1s - loss: nan - accuracy: 0.0000e+00
11904/12000 [============================>.] - ETA: 0s - loss: nan - accuracy: 0.0000e+00
11968/12000 [============================>.] - ETA: 0s - loss: nan - accuracy: 0.0000e+00
12000/12000 [==============================] - 82s 7ms/step - loss: nan - accuracy: 0.0000e+00 - val_loss: nan - val_accuracy: 0.0000e+00
Epoch 3/20

   64/12000 [..............................] - ETA: 1:18 - loss: nan - accuracy: 0.0000e+00
  128/12000 [..............................] - ETA: 1:18 - loss: nan - accuracy: 0.0000e+00
  192/12000 [..............................] - ETA: 1:16 - loss: nan - accuracy: 0.0000e+00
(...)

Localizing the problem

To find out the solution I wrote the code presented below, which goes through several models (GRU/LSTM, {no dropout, only "normal" dropout, only recurrent dropout, "normal" and recurrent dropout, rmsprop/adam}) and presents loss and accuracy of all those models. (It also creates smaller, separate graphs for each model.)

# Based on examples from "Deep Learning with Python" by François Chollet:
## Constants, modules:
VERSION = 2

import os
from keras import models
from keras import layers
import matplotlib.pyplot as plt
import pylab

## Loading data:
from keras.datasets import imdb
(x_train, y_train), (x_test, y_test) = \
    imdb.load_data(num_words=10000)

from keras.preprocessing import sequence
x_train = sequence.pad_sequences(x_train, maxlen=500)
x_test = sequence.pad_sequences(x_test, maxlen=500)

## Dictionary with models' hyperparameters:
MODELS = [
    # GRU:
    {"no": 1,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 2,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 3,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 4,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 5,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 6,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 7,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 8,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    # LSTM:
    {"no": 9,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 10,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 11,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 12,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 13,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 14,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 15,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 16,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},
]

## Adding name:
for model_dict in MODELS:
    model_dict["name"] = f"{model_dict['layer_type']}"
    model_dict["name"] += f"_d{model_dict['dropout']}" if model_dict['dropout'] is not None else f"_dN"
    model_dict["name"] += f"_rd{model_dict['recurrent_dropout']}" if model_dict['recurrent_dropout'] is not None else f"_rdN"
    model_dict["name"] += f"_{model_dict['optimizer']}"

## Fucntion - defing and training model:
def train_model(model_dict):
    """Defines and trains a model, outputs history."""

    ## Defining:
    model = models.Sequential()
    model.add(layers.Embedding(10000, 32))

    recurrent_layer_kwargs = dict()
    if model_dict["dropout"] is not None:
        recurrent_layer_kwargs["dropout"] = model_dict["dropout"]
    if model_dict["recurrent_dropout"] is not None:
        recurrent_layer_kwargs["recurrent_dropout"] = model_dict["recurrent_dropout"]

    if model_dict["layer_type"] == 'GRU':
        model.add(layers.GRU(32, **recurrent_layer_kwargs))
    elif model_dict["layer_type"] == 'LSTM':
        model.add(layers.LSTM(32, **recurrent_layer_kwargs))
    else:
        raise ValueError("Wrong model_dict['layer_type'] value...")
    model.add(layers.Dense(1, activation='sigmoid'))

    ## Compiling:
    model.compile(
        optimizer=model_dict["optimizer"],
        loss='binary_crossentropy',
        metrics=['accuracy'])

    ## Training:
    history = model.fit(x_train, y_train,
                        epochs=20,
                        batch_size=64,
                        validation_split=0.2)

    return history

## Multi-model graphs' parameters:
graph_all_nrow = 4
graph_all_ncol = 4
graph_all_figsize = (20, 20)

assert graph_all_nrow * graph_all_nrow >= len(MODELS)

## Figs and axes of multi-model graphs:
graph_all_loss_fig, graph_all_loss_axs = plt.subplots(graph_all_nrow, graph_all_ncol, figsize=graph_all_figsize)
graph_all_acc_fig, graph_all_acc_axs = plt.subplots(graph_all_nrow, graph_all_ncol, figsize=graph_all_figsize)

## Loop trough all models:
for i, model_dict in enumerate(MODELS):
    history = train_model(model_dict)

    ## Metrics extraction:
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']

    epochs = range(1, len(loss) + 1)

    ## Single-model grph - loss:
    graph_loss_fname = fr"{os.path.basename(__file__).replace('.py', '')}"
    graph_loss_fname += fr"_v{VERSION}_{model_dict['no']}_{model_dict['name']}_loss_graph.png"

    graph_loss_fig, graph_loss_ax = plt.subplots()
    graph_loss_ax.plot(epochs, loss, 'bo', label='Training loss')
    graph_loss_ax.plot(epochs, val_loss, 'b', label='Validation loss')
    graph_loss_ax.legend()
    graph_loss_fig.suptitle("Training and validation loss")
    graph_loss_fig.savefig(graph_loss_fname)
    pylab.close(graph_loss_fig)

    ## Single-model grph - accuracy:
    graph_acc_fname = fr"{os.path.basename(__file__).replace('.py', '')}"
    graph_acc_fname += fr"_v{VERSION}_{model_dict['no']}_{model_dict['name']}_acc_graph.png"

    graph_acc_fig, graph_acc_ax = plt.subplots()
    graph_acc_ax.plot(epochs, acc, 'bo', label='Training accuracy')
    graph_acc_ax.plot(epochs, val_acc, 'b', label='Validation accuracy')
    graph_acc_ax.legend()
    graph_acc_fig.suptitle("Training and validation acc")
    graph_acc_fig.savefig(graph_acc_fname)
    pylab.close(graph_acc_fig)

    ## Position of axes on multi-model graph:
    i_row = i // graph_all_ncol
    i_col = i % graph_all_ncol

    ## Adding model metrics to multi-model graph - loss:
    graph_all_loss_axs[i_row, i_col].plot(epochs, loss, 'bo', label='Training loss')
    graph_all_loss_axs[i_row, i_col].plot(epochs, val_loss, 'b', label='Validation loss')
    graph_all_loss_axs[i_row, i_col].set_title(fr"{model_dict['no']}. {model_dict['name']}")

    ## Adding model metrics to multi-model graph - accuracy:
    graph_all_acc_axs[i_row, i_col].plot(epochs, acc, 'bo', label='Training acc')
    graph_all_acc_axs[i_row, i_col].plot(epochs, val_acc, 'b', label='Validation acc')
    graph_all_acc_axs[i_row, i_col].set_title(fr"{model_dict['no']}. {model_dict['name']}")

## Saving multi-model graphs:
# Output files are quite big (8000x8000 PNG), you may want to decrease DPI.
graph_all_loss_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_loss_graph.png", dpi=400)
graph_all_acc_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_acc_graph.png", dpi=400)

Please find two main graphs below: Loss - binary crossentropy, Accuracy (I am not allowed te embed images in post due to low reputation).

I have also obtained similarly strange problems in regression model - the MAE was in range of several thousands - in the problem where $y$ range was maybe of several tens. (I decided not to include this model here, because it would make this question even longer.)

Versions of modules and libraries, hardware

Modules:

Keras                    2.3.1
Keras-Applications       1.0.8
Keras-Preprocessing      1.1.0
matplotlib               3.1.3
tensorflow-estimator     1.14.0
tensorflow-gpu           2.1.0
tensorflow-gpu-estimator 2.1.0

keras.json file:

{
    "floatx": "float32",
    "epsilon": 1e-07,
    "backend": "tensorflow",
    "image_data_format": "channels_last"
}

CUDA - I have CUDA 10.0 and CUDA 10.1 installed on my system.

CUDnn - I have three versions: cudnn-10.0 v7.4.2.24, cudnn-10.0 v7.6.4.38, cudnn-9.0 v7.4.2.24

GPU: Nvidia GTX 1050Ti 4gb

Windows 10 Home

Questions

Do you know what may be the reason of this behavior?

Is it possible that this is caused by multiple CUDA and CUDnn installations? Before observing the problem I have trained several models (both from book and my own ones) and the seemed to behave mor or less as expected, while having 2 CUDA and 2 CUDnn versions (those above without cudnn-10.0 v7.6.4.38) installed.

Is there any official/good source of adequate combinations of keras, tensorflow, CUDA, CUDnn (and  other relevant things e.g. maybe Visual Studio)? I cannot really find any authoritative and up-to-date source.

I hope I've described everything clearly enough. If you have any questions, please ask.

Body:
I finally found the solution (sort of). It's enough to change keras to tensorflow.keras.

Revised Code

# Based on examples from "Deep Learning with Python" by François Chollet:
## Constants, modules:
VERSION = 2

import os
#U: from keras import models
#U: from keras import layers
from tensorflow.keras import models
from tensorflow.keras import layers

import matplotlib.pyplot as plt
import pylab

## Loading data:
from keras.datasets import imdb

(x_train, y_train), (x_test, y_test) = \
    imdb.load_data(num_words=10000)

from keras.preprocessing import sequence

x_train = sequence.pad_sequences(x_train, maxlen=500)
x_test = sequence.pad_sequences(x_test, maxlen=500)

## Dictionary with models' hyperparameters:
MODELS_ALL = [
    # GRU:
    {"no": 1,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 2,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 3,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 4,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 5,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 6,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 7,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 8,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    # LSTM:
    {"no": 9,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 10,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 11,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 12,
     "layer_type": "LSTM",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 13,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": None},

    {"no": 14,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": None},

    {"no": 15,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 16,
     "layer_type": "LSTM",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},
]

MODELS_GRU_RECCURENT = [
    # GRU:
    {"no": 3,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 4,
     "layer_type": "GRU",
     "optimizer": "rmsprop",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},

    {"no": 7,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": None,
     "recurrent_dropout": 0.3},

    {"no": 8,
     "layer_type": "GRU",
     "optimizer": "adam",
     "dropout": 0.3,
     "recurrent_dropout": 0.3},
]

MODELS = MODELS_ALL   # "MODELS = MODELS_ALL" or "MODELS = MODELS_GRU_RECCURENT"

## Adding name:
for model_dict in MODELS:
    model_dict["name"] = f"{model_dict['layer_type']}"
    model_dict["name"] += f"_d{model_dict['dropout']}" if model_dict['dropout'] is not None else f"_dN"
    model_dict["name"] += f"_rd{model_dict['recurrent_dropout']}" if model_dict['recurrent_dropout'] is not None else f"_rdN"
    model_dict["name"] += f"_{model_dict['optimizer']}"

## Fucntion - defing and training model:
def train_model(model_dict):
    """Defines and trains a model, outputs history."""

    ## Defining:
    model = models.Sequential()
    model.add(layers.Embedding(10000, 32))

    recurrent_layer_kwargs = dict()
    if model_dict["dropout"] is not None:
        recurrent_layer_kwargs["dropout"] = model_dict["dropout"]
    if model_dict["recurrent_dropout"] is not None:
        recurrent_layer_kwargs["recurrent_dropout"] = model_dict["recurrent_dropout"]

    if model_dict["layer_type"] == 'GRU':
        model.add(layers.GRU(32, **recurrent_layer_kwargs))
    elif model_dict["layer_type"] == 'LSTM':
        model.add(layers.LSTM(32, **recurrent_layer_kwargs))
    else:
        raise ValueError("Wrong model_dict['layer_type'] value...")
    model.add(layers.Dense(1, activation='sigmoid'))

    ## Compiling:
    model.compile(
        optimizer=model_dict["optimizer"],
        loss='binary_crossentropy',
        metrics=['accuracy'])

    ## Training:
    history = model.fit(x_train, y_train,
                        epochs=20,
                        batch_size=64,
                        validation_split=0.2)

    return history

## Multi-model graphs' parameters:
graph_all_nrow = 4
graph_all_ncol = 4
graph_all_figsize = (20, 20)

assert graph_all_nrow * graph_all_nrow >= len(MODELS)

# fig and axes of multi-model graphs:
graph_all_loss_fig, graph_all_loss_axs = plt.subplots(graph_all_nrow, graph_all_ncol, figsize=graph_all_figsize)
graph_all_acc_fig, graph_all_acc_axs = plt.subplots(graph_all_nrow, graph_all_ncol, figsize=graph_all_figsize)

## Loop trough all models:
for i, model_dict in enumerate(MODELS):
    history = train_model(model_dict)

    ## Metrics extraction:
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    acc = history.history['accuracy']
    val_acc = history.history['val_accuracy']

    epochs = range(1, len(loss) + 1)

    ## Single-model graph - loss:
    graph_loss_fname = fr"{os.path.basename(__file__).replace('.py', '')}"
    graph_loss_fname += fr"_v{VERSION}_{model_dict['no']}_{model_dict['name']}_loss_graph.png"

    graph_loss_fig, graph_loss_ax = plt.subplots()
    graph_loss_ax.plot(epochs, loss, 'bo', label='Training loss')
    graph_loss_ax.plot(epochs, val_loss, 'b', label='Validation loss')
    graph_loss_ax.legend()
    graph_loss_fig.suptitle("Training and validation loss")
    graph_loss_fig.savefig(graph_loss_fname)
    pylab.close(graph_loss_fig)

    ## Single-model graph - accuracy:
    graph_acc_fname = fr"{os.path.basename(__file__).replace('.py', '')}"
    graph_acc_fname += fr"_v{VERSION}_{model_dict['no']}_{model_dict['name']}_acc_graph.png"

    graph_acc_fig, graph_acc_ax = plt.subplots()
    graph_acc_ax.plot(epochs, acc, 'bo', label='Training accuracy')
    graph_acc_ax.plot(epochs, val_acc, 'b', label='Validation accuracy')
    graph_acc_ax.legend()
    graph_acc_fig.suptitle("Training and validation acc")
    graph_acc_fig.savefig(graph_acc_fname)
    pylab.close(graph_acc_fig)

    ## Position of axes on multi-model graph:
    i_row = i // graph_all_ncol
    i_col = i % graph_all_ncol

    ## Adding model metrics to multi-model graph - loss:
    graph_all_loss_axs[i_row, i_col].plot(epochs, loss, 'bo', label='Training loss')
    graph_all_loss_axs[i_row, i_col].plot(epochs, val_loss, 'b', label='Validation loss')
    graph_all_loss_axs[i_row, i_col].set_title(fr"{model_dict['no']}. {model_dict['name']}")

    ## Adding model metrics to multi-model graph - accuracy:
    graph_all_acc_axs[i_row, i_col].plot(epochs, acc, 'bo', label='Training acc')
    graph_all_acc_axs[i_row, i_col].plot(epochs, val_acc, 'b', label='Validation acc')
    graph_all_acc_axs[i_row, i_col].set_title(fr"{model_dict['no']}. {model_dict['name']}")

graph_all_loss_fig.suptitle(f"Loss - binary crossentropy [v{VERSION}]")
graph_all_acc_fig.suptitle(f"Accuracy [v{VERSION}]")

## Saving multi-model graphs:
graph_all_loss_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_loss_graph.png", dpi=400)
graph_all_acc_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_acc_graph.png", dpi=400)

## Saving multi-model graphs (SMALL):
graph_all_loss_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_loss_graph_SMALL.png", dpi=150)
graph_all_acc_fig.savefig(fr"{os.path.basename(__file__).replace('.py', '')}_ALL_v{VERSION}_acc_graph_SMALL.png", dpi=150)

Results

Graphs analogous to those in question: Loss - binary crossentropy, Accuracy

More on keras vs tensorflow.keras

As written in François Chollet's tweets (found here: https://stackoverflow.com/a/54117754) instead of stand-alone keras there will be tensorflow.keras (that is Keras as official API to TensorFlow) from now on. (I'm not completely sure if I'm 100% correct, feel free to correct me.)

I think it's better just to use tensorflow.keras instead of keras in future projects.


来源: stackexchange

问:
How to use a proved lemma in Coq
As elementary as it seems, I can't solve the following problem. There's this inductive type for even naturals and a proven lemma expressing that adding two even numbers yields an even number.

```<code>Inductive even : nat -> Prop :=
| O_even : even 0
| plus_2_even : forall n:nat, even n -> even (S (S n)).

Lemma lm_even1: forall n p:nat, even n -> even p -> even (n + p).
</code>```

I'd like to prove the special case that n + 2 is even:

```<code>Lemma lm_even2: forall n: nat, even n -> even (n + 2).
</code>```

The more general lm_even1 would come handy here but I keep failing with my efforts using apply, rewrite etc. to express that lm_even2 is the same statement with "p = 2". Help would be appreciated.

答:
You might get a better answer if you show us what you've tried (explicitly). There's a short proof with just apply and one or two other basic tactics, but maybe you have a misunderstanding somewhere. Fixing that misunderstanding would be more helpful for you in the long term.

We should start by introducing all the premises. There's a good reason for this that I'll discuss below.

```<code>Lemma lm_even2: forall n: nat, even n -> even (n + 2).
Proof.
  intros.
</code>```

Now the proof state is

```<code>1 subgoal
n : nat
H : even n
______________________________________(1/1)
even (n + 2)
</code>```

Now we're in a position to apply lm_even1.. apply term. attempts to unify the type of term with the goal, possibly filling in arguments to term from left to right (if it's some kind of function).

So, for example, apply lm_even1. would first try to unify with the full type

```<code>forall n p : nat, even n -> even p -> even (n + p)
</code>```

Then it'll try with some variable to be determined as the first argument (of type nat):

```<code>forall p : nat, even ?n -> even p -> even (?n + p)
</code>```

Then the same for p: even ?n -> even ?p -> even (?n + ?p). Next, since this is still a function type, it can continue by filling in the argument of type even ?n with some unknown variable: even ?p -> even (?n + ?p) and finally, even (?n + ?p).

The only one of those that could match the goal is the last one: even (?n + ?p) with ?n = n and ?p = 2. If we hadn't introduced the variables, this wouldn't work at all because none of the other types match the original goal.

```<code>Lemma lm_even2: forall n: nat, even n -> even (n + 2).
Proof.
  intros.
  apply lm_even1.
</code>```

Now the proof state is

```<code>2 subgoals
n : nat
H : even n
______________________________________(1/2)
even n
______________________________________(2/2)
even 2
</code>```

So we have two goals: even n and even 2. Both should be fairly easy to reach using the premises and the definition of even.

ContentLicense: CC BY-SA 4.0

Title: How to use a proved lemma in Coq

Body:
As elementary as it seems, I can't solve the following problem. There's this inductive type for even naturals and a proven lemma expressing that adding two even numbers yields an even number.

Inductive even : nat -> Prop :=
| O_even : even 0
| plus_2_even : forall n:nat, even n -> even (S (S n)).

Lemma lm_even1: forall n p:nat, even n -> even p -> even (n + p).

I'd like to prove the special case that n + 2 is even:

Lemma lm_even2: forall n: nat, even n -> even (n + 2).

The more general lm_even1 would come handy here but I keep failing with my efforts using apply, rewrite etc. to express that lm_even2 is the same statement with "p = 2". Help would be appreciated.

Body:
You might get a better answer if you show us what you've tried (explicitly). There's a short proof with just apply and one or two other basic tactics, but maybe you have a misunderstanding somewhere. Fixing that misunderstanding would be more helpful for you in the long term.

We should start by introducing all the premises. There's a good reason for this that I'll discuss below.

Lemma lm_even2: forall n: nat, even n -> even (n + 2).
Proof.
  intros.

Now the proof state is

1 subgoal
n : nat
H : even n
______________________________________(1/1)
even (n + 2)

Now we're in a position to apply lm_even1.. apply term. attempts to unify the type of term with the goal, possibly filling in arguments to term from left to right (if it's some kind of function).

So, for example, apply lm_even1. would first try to unify with the full type

forall n p : nat, even n -> even p -> even (n + p)

Then it'll try with some variable to be determined as the first argument (of type nat):

forall p : nat, even ?n -> even p -> even (?n + p)

Then the same for p: even ?n -> even ?p -> even (?n + ?p). Next, since this is still a function type, it can continue by filling in the argument of type even ?n with some unknown variable: even ?p -> even (?n + ?p) and finally, even (?n + ?p).

The only one of those that could match the goal is the last one: even (?n + ?p) with ?n = n and ?p = 2. If we hadn't introduced the variables, this wouldn't work at all because none of the other types match the original goal.

Lemma lm_even2: forall n: nat, even n -> even (n + 2).
Proof.
  intros.
  apply lm_even1.

Now the proof state is

2 subgoals
n : nat
H : even n
______________________________________(1/2)
even n
______________________________________(2/2)
even 2

So we have two goals: even n and even 2. Both should be fairly easy to reach using the premises and the definition of even.


问:
How is atomic rule ensured when using default (read commited) isolation mode?
An important property of transaction is atomicity.

The default mode is read commited. This prevents dirty reads. But we have problem of repeatable reads and phantom rows.

How is atomic rule ensured when using default (read commited) isolation mode?

Example- in tran1 I read value from table1. While tran1 is still running, I start tran2 and update the same value in table1. So tran1 has got stale value.

答:
Read committed isolation mode does not prevent updates of the rows you have read in your transaction while your transaction is still open.

If you want to prevent this, then you'll need to set the isolation level to REPEATABLE READ (or SERIALIZABLE).
Or you can set the READ_COMMITTED_SNAPSHOT  option of your database to ON.


问:
Checking whether a list value is within a range
I have created a list of numbers in fav_numbers. The user will be prompted to enter 2 values: starting range and ending range. The program will check if the list of numbers will fall into the range that the user has inputted. If the numbers in the list fall within the range, the list will be printed out.
The thing is I'm not sure how to check if the individual numbers in the list are within the range.
I am a beginner to python so what would be the most straightforward way to do this, preferably using loops?</p>

```<code>start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))

#find favourite numbers
def find_favourite_numbers(start_range,end_range):
    fav_numbers = [70, 105, 140]
    for start_range and end_range in range(fav_numbers):
    if fav_numbers[0,1,2] >= start_range and fav_number <= end_range:
        print(fav_numbers)
    else:
        print("favourite numbers not in range")

    print(fav_numbers)

    return fav_numbers

#Do not remove the next line
find_favourite_numbers(start_range,end_range)
</code>```

答:
One suggestion would be to make a separate function which tests whether all the numbers are in range, and returns a True or False value, as this makes it a bit tidier.  Inside the fav_numbers_are_in_range function is the loop that you were asking about, but if it finds a number out of range, then it just returns from the function so it does not execute the whole loop.

```<code>start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))

# test if favourite numbers are in rage
def fav_numbers_are_in_range(fav_numbers, start_range, end_range):
    for number in fav_numbers:
        if number < start_range or number > end_range:
            return False
    return True

#find favourite numbers
def find_favourite_numbers(start_range,end_range):
    fav_numbers = [70, 105, 140]
    if fav_numbers_are_in_range(fav_numbers, start_range, end_range):
        print("fav numbers are in range ", fav_numbers)
        return fav_numbers
    else:
        print("not all favourite numbers are in range")
        return None

find_favourite_numbers(start_range,end_range)
</code>```

Body:
I have created a list of numbers in fav_numbers. The user will be prompted to enter 2 values: starting range and ending range. The program will check if the list of numbers will fall into the range that the user has inputted. If the numbers in the list fall within the range, the list will be printed out.
The thing is I'm not sure how to check if the individual numbers in the list are within the range.
I am a beginner to python so what would be the most straightforward way to do this, preferably using loops?

start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))

#find favourite numbers
def find_favourite_numbers(start_range,end_range):
    fav_numbers = [70, 105, 140]
    for start_range and end_range in range(fav_numbers):
    if fav_numbers[0,1,2] >= start_range and fav_number <= end_range:
        print(fav_numbers)
    else:
        print("favourite numbers not in range")

    print(fav_numbers)

    return fav_numbers

#Do not remove the next line
find_favourite_numbers(start_range,end_range)

Body:
One suggestion would be to make a separate function which tests whether all the numbers are in range, and returns a True or False value, as this makes it a bit tidier.  Inside the fav_numbers_are_in_range function is the loop that you were asking about, but if it finds a number out of range, then it just returns from the function so it does not execute the whole loop.

start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))

# test if favourite numbers are in rage
def fav_numbers_are_in_range(fav_numbers, start_range, end_range):
    for number in fav_numbers:
        if number < start_range or number > end_range:
            return False
    return True

#find favourite numbers
def find_favourite_numbers(start_range,end_range):
    fav_numbers = [70, 105, 140]
    if fav_numbers_are_in_range(fav_numbers, start_range, end_range):
        print("fav numbers are in range ", fav_numbers)
        return fav_numbers
    else:
        print("not all favourite numbers are in range")
        return None

find_favourite_numbers(start_range,end_range)


问:
Java XML Document XPath with Disable Escaping
Currently, I need to get the element of XML without escaping.

For example:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Message>
      <Header>H001</Header>
      <Body>
            <Item>ABC&ABC"</Item>
      </Body>
</Message>
</code>```

I need to get the value of "Item" element via XPath.
However, it is escaped automatically.

My Result = ABC&ABC"

Expected = ABC&ABC"

How can I get the expected value?

答: XPath will always return the values of nodes that result from XML parsing. The string value of the Item element in your XML, after parsing, is ABC&ABC", so that's what XPath gives you. If you want ABC&amp;ABC&quot; then you will have to reverse the action of the XML parser - this is known as serialization. Parsing "unescapes" entity and character references (it turns & into &). Serialization escapes special characters such as "&" (it turns & into &).

Body:
Currently, I need to get the element of XML without escaping.

For example:

<?xml version="1.0" encoding="UTF-8"?>
<Message>
      H001

            <Item>ABC&amp;ABC&quot;</Item>

</Message>

I need to get the value of "Item" element via XPath.
However, it is escaped automatically.

My Result = ABC&ABC"

Expected = ABC&amp;ABC&quot;

How can I get the expected value?

Body: XPath will always return the values of nodes that result from XML parsing. The string value of the Item element in your XML, after parsing, is ABC&amp;ABC&quot;, so that's what XPath gives you. If you want ABC&amp;amp;ABC&amp;quot; then you will have to reverse the action of the XML parser - this is known as serialization. Parsing "unescapes" entity and character references (it turns &amp; into &). Serialization escapes special characters such as "&" (it turns & into &amp;).


问:
Generic collection support in WCF
Does WCF support generic collections?
I looked at the proxy object, and it seems to generate object array from a generic list collection.

Thanks

答:
WCF does support generic collections. Over the wire it is transfered as an array of objects (this is the standard way of sending lists/arrays/etc), but WCF does the serialization/deserialization for you, so as far as your client/server are concerned, the collections are generic.

Edit: a caveat is, of course, that the collection has to be serializable. Also, take  a look at this if you asking your question because your custom collection is being treated as an T[] on the client.

OwnerDisplayName: Jeremy Thomson

ContentLicense: CC BY-SA 2.5

Title: Generic collection support in WCF

LastEditorDisplayName: Daniel Auger

OwnerDisplayName: siz

LastEditorDisplayName: siz


问:
Keyboard hides TextField in a PageView
I have a quite complex screen with a page view and a FutureBuilder. In the Pagebuilder I also have a TextFormField, when I now click into the text field the keyboard opens like expected. But it then hides the textfield and a button below the text field.
I already searched for solutions, things i tried:

setting resizeToAvoidBottomInset to true

putting the outer column or the pageview into a SingleChildScrollView

adding some padding (in the size of the keyboard) to the bottom

Any other ideas?

I only have ONE Scaffold.

答:
Have you tried this?

You should wrap your page with SingleChildScrollView so that you get scrolling in the case when your content grows bigger than the device height because of introduction of keyboard.

Soution

1)Use of WidgetsBindingObserver mixin

2)Adding scrollController to SingleChildScrollView

3)Listening the event of presence of keyboard using didChangeMetrics and scrolling as per the need.

```<code>class _SignInState extends State<SignIn> with WidgetsBindingObserver{

ScrollController _scrollController = new ScrollController();

void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    _scrollController.jumpTo(200); //as per your need
  }
</code>```

Inside Scaffold widget adding controller to SingleChildScrollView

```<code>  body: SingleChildScrollView(
        controller: _scrollController,
    )
</code>```

Title: Keyboard hides TextField in a PageView

Body:
Have you tried this?

You should wrap your page with SingleChildScrollView so that you get scrolling in the case when your content grows bigger than the device height because of introduction of keyboard.

Soution

1)Use of WidgetsBindingObserver mixin

2)Adding scrollController to SingleChildScrollView

3)Listening the event of presence of keyboard using didChangeMetrics and scrolling as per the need.

class _SignInState extends State<SignIn> with WidgetsBindingObserver{

ScrollController _scrollController = new ScrollController();

void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    _scrollController.jumpTo(200); //as per your need
  }

Inside Scaffold widget adding controller to SingleChildScrollView

  body: SingleChildScrollView(
        controller: _scrollController,
    )


问:
Determine if a path is local Flutter
I am trying to play an audio by using package audioplayer but I cannot always know if a path is a local file or not. Therefore, I wonder what is the best way to determine if a path is local in Flutter?</p>

答:
Both File and Directory classes of dart:io library has isAbsolute method, which checks if a File or Directory path is absolute or not.

final file = File('foo/bar');
print(file.isAbsolute);
```

Title: Determine if a path is local Flutter


问:
How make a request in the browser to a DELETE http method in ASP.NET (.NET FRAMEWORK)
In laravel or some express.js libs add middleware to check if a field is given called _Method which will override the actual http method of the http request on arrival of the server, because the browser only supports POST and GET.

Does ASP.NET (.NET Framework) contain a build-in middleware like those I just mentioned, I couldn't find anything online.

If so, how do I use it or do you know such an atricle.

If not, how can I create such a middleware myself.

I could not create one myself, because the HttpRequest in the HttpContext is readonly and the HttpMethod in the HttpRequest is readonly aswell.

Or is the only choice to use preventDefault() and/or ajax to send (for example) a DELETE request via javascript?

答:
After some digging, I found that later in the chain of ASP.NET the HttpContext Changes into HttpContextBase. This context contains GetHttpMethodOverride().

I looked the Method up on github, because it's open source and ASP.NET does contain a middleware such as mentioned.

You can override the actual http method using the key X-HTTP-Method-Override in either the Header, Form or Query string and the actual http method must be POST for the middleware to even consider a http method override.


问:
Trying to segment characters using opencv - Contour problem
My code is detecting another box when there is no letter!

```<code># Create sort_contours() function to grab the contour of each digit from left to right
def sort_contours(cnts,reverse = False):
    i = 0
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts

cont, _  = cv2.findContours(thre_mor, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# creat a copy version "test_roi" of plat_image to draw bounding box
test_roi = plate_image.copy()

# Initialize a list which will be used to append charater image
crop_characters = []

# define standard width and height of character
digit_w, digit_h = 40, 80 #40,80

for c in sort_contours(cont):
    (x, y, w, h) = cv2.boundingRect(c)
    ratio = h/w
    if 1<=ratio<=2.5: # Only select contour with defined ratio
        if h/plate_image.shape[0]>=0.4: # Select contour which has the height larger than 50% of the plate
            # Draw bounding box arroung digit number
            cv2.rectangle(test_roi, (x, y), (x + w, y + h), (0, 255,0), 2)

            # Sperate number and gibe prediction
            curr_num = thre_mor[y:y+h,x:x+w]
            curr_num = cv2.resize(curr_num, dsize=(digit_w, digit_h))
            _, curr_num = cv2.threshold(curr_num, 220, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
            crop_characters.append(curr_num)

print("Detect {} letters...".format(len(crop_characters)))
fig = plt.figure(figsize=(10,6))
plt.axis(False)
plt.imshow(test_roi)
</code>```

The image it is this:

With this binary image:

This is the result:

Do you see the last 5? The goal it is avoid this.

Why this is happening?

The way I procces the image it is:

```<code>gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(7,7),0)
binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thre_mor = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel3)
</code>```

Grayscale

Blur

Binarization

Segmentation

I think it's because of the contour, how could I remove the contour better?

答:
When segmenting characters by binarisation, finding alien blobs is the rule rather than the exception.

You can get rid of many of them by simple size/area/aspect ratio… criteria. In the given case, you can use the fact that they go alongside the edges of the image, or that they are shifted up wrt the other characters.

Anyway, there can be blobs that resist to any form of by-feature rejection just for the reason that they look like characters.

The next level of filtering is recognition proper, which will tell you if the blob has the shape of a known character (this is font dependent).

Last but not least, you can even have blobs taking the appearance of legit characters and being in-line with the string. Then there is nothing you can do.

Body:
My code is detecting another box when there is no letter!

# Create sort_contours() function to grab the contour of each digit from left to right
def sort_contours(cnts,reverse = False):
    i = 0
    boundingBoxes = [cv2.boundingRect(c) for c in cnts]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts

cont, _  = cv2.findContours(thre_mor, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# creat a copy version "test_roi" of plat_image to draw bounding box
test_roi = plate_image.copy()

# Initialize a list which will be used to append charater image
crop_characters = []

# define standard width and height of character
digit_w, digit_h = 40, 80 #40,80

for c in sort_contours(cont):
    (x, y, w, h) = cv2.boundingRect(c)
    ratio = h/w
    if 1<=ratio<=2.5: # Only select contour with defined ratio
        if h/plate_image.shape[0]>=0.4: # Select contour which has the height larger than 50% of the plate
            # Draw bounding box arroung digit number
            cv2.rectangle(test_roi, (x, y), (x + w, y + h), (0, 255,0), 2)

            # Sperate number and gibe prediction
            curr_num = thre_mor[y:y+h,x:x+w]
            curr_num = cv2.resize(curr_num, dsize=(digit_w, digit_h))
            _, curr_num = cv2.threshold(curr_num, 220, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
            crop_characters.append(curr_num)

print("Detect {} letters...".format(len(crop_characters)))
fig = plt.figure(figsize=(10,6))
plt.axis(False)
plt.imshow(test_roi)

The image it is this:

With this binary image:

This is the result:

Do you see the last 5? The goal it is avoid this.

Why this is happening?

The way I procces the image it is:

gray = cv2.cvtColor(plate_image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(7,7),0)
binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
kernel3 = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
thre_mor = cv2.morphologyEx(binary, cv2.MORPH_DILATE, kernel3)

Grayscale

Blur

Binarization

Segmentation

I think it's because of the contour, how could I remove the contour better?


问:
How to set only Date in DataTable Column of Type DateTime WEB
Hi All,

My Question is simple but please keep in mind I'm not binding it to any grid or any of ASP.NET control I have my own grid control and I want to keep it as a DateTime Column for sorting purpose.

I'm creating DataTable With Column Type DateTime.

```<code>DataTable data = new DataTable();
data.Columns.Add("Invoice Date", typeof(DateTime));
DataRow dr = data.NewRow();
dr[0] = DateTime.Now;

//Adding filled row to the DataTable object
dataTable.Rows.Add(dr);
</code>```

When the Value is shown on ASP.NET page
it is show something like this:

```<code>"2/28/2011 12:00:00 AM"
</code>```

I have 2 columns like this, In 1 column I want to show just date and in other column i want to show date as "Dec 2011", these formats can be achieved if i use DataColumn with type string but in that case sorting is not working properly.

Please help.

Thanks.

答:
First of all take only date part

```<code>dr[0] = DateTime.Now.Date;
</code>```

Second make use of

DateTime.ToShortDateString

```<code>    <asp:Label ID="Label1" runat="server" Text='<%#
((DateTime)Eval("ItemValue")).ToShortDateString() %>'></asp:Label>
</code>```

method to when binding value

EDIT

Not Sure but you can check this answer may help you to resolve your issue : Is it possible to format a date column of a datatable?

ContentLicense: CC BY-SA 3.0

Body:
Hi All,

My Question is simple but please keep in mind I'm not binding it to any grid or any of ASP.NET control I have my own grid control and I want to keep it as a DateTime Column for sorting purpose.

I'm creating DataTable With Column Type DateTime.

DataTable data = new DataTable();
data.Columns.Add("Invoice Date", typeof(DateTime));
DataRow dr = data.NewRow();
dr[0] = DateTime.Now;

//Adding filled row to the DataTable object
dataTable.Rows.Add(dr);

When the Value is shown on ASP.NET page
it is show something like this:

"2/28/2011 12:00:00 AM"

I have 2 columns like this, In 1 column I want to show just date and in other column i want to show date as "Dec 2011", these formats can be achieved if i use DataColumn with type string but in that case sorting is not working properly.

Please help.

Thanks.

Body:
First of all take only date part

dr[0] = DateTime.Now.Date;

Second make use of

DateTime.ToShortDateString

    <asp:Label ID="Label1" runat="server" Text='<%#
((DateTime)Eval("ItemValue")).ToShortDateString() %>'></asp:Label>

method to when binding value

EDIT

Not Sure but you can check this answer may help you to resolve your issue : Is it possible to format a date column of a datatable?


问:
Is the namespace created when free variables are used?
```<code>x = 2
def my_func():
    print(x)
    print(dir())

my_func()
</code>```

The output by the statement print(dir()) is an empty list []. Was the local namespace created but didn't contain any name or it wasn't created at all?

答:
The x is part of the global in your case you can check it by

```<code>x = 2
def my_func():
    print(x)
    print(locals())
    print(globals())

my_func()
</code>```

The print(locals())
Output

```<code>{}
</code>```

and the print(globals())
Output

```<code>{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x004FC230>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/leeron.arad/Documents/test-proj/venv/t.py', '__cached__': None, 'x': 2, 'my_func': <function my_func at 0x0058E978>}
</code>```

In the globals dict you can see the 'x': 2 that get printed in the my_func scope.

The x values is not created in the function it's only from the global scope.

Body:
x = 2
def my_func():
    print(x)
    print(dir())

my_func()

The output by the statement print(dir()) is an empty list []. Was the local namespace created but didn't contain any name or it wasn't created at all?

Body:
The x is part of the global in your case you can check it by

x = 2
def my_func():
    print(x)
    print(locals())
    print(globals())

my_func()

The print(locals())
Output

{}

and the print(globals())
Output

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x004FC230>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:/Users/leeron.arad/Documents/test-proj/venv/t.py', '__cached__': None, 'x': 2, 'my_func': <function my_func at 0x0058E978>}

In the globals dict you can see the 'x': 2 that get printed in the my_func scope.

The x values is not created in the function it's only from the global scope.


问:
2D array conversion (an integer to a string)
I am writing a game code. The board of this game is 10x10 size. In the beginning, I wrote this board as a two-dimensional integer array. Now I have to replace some places on the board with letters. It will change with letters according to the coordinates entered by the player.</p>

```<code>private static int[][] board = new int[10][10]; //board

StringBuilder sb = new StringBuilder();
    for (int[] array : board) {
        sb.append('\n').append(Arrays.toString(array));
    }
    String new = sb.toString(); //I tried to convert this way

if (new[x][y].equals("r")){
    new[x][y] = "d"; //I'm getting an error in this part.
}
</code>```

答:
Try using 2D String array, by copying data from the 2D int array.</p>

```<code>int[][] board = new int[10][10]; //board

//Converting int array to String array
String[][] s = new String[board.length][];
for(int i = 0; i < board.length; i++){
    s[i] = new String[board[i].length];
    for(int j=0; j<board[i].length; j++){
        s[i][j] = Integer.toString(board[i][j]);
    }
}

if (s[x][y].equals("r")){
    s[x][y] = "d";
}
</code>```

Body:
I am writing a game code. The board of this game is 10x10 size. In the beginning, I wrote this board as a two-dimensional integer array. Now I have to replace some places on the board with letters. It will change with letters according to the coordinates entered by the player.

private static int[][] board = new int[10][10]; //board

StringBuilder sb = new StringBuilder();
    for (int[] array : board) {
        sb.append('\n').append(Arrays.toString(array));
    }
    String new = sb.toString(); //I tried to convert this way

if (new[x][y].equals("r")){
    new[x][y] = "d"; //I'm getting an error in this part.
}

Body:
Try using 2D String array, by copying data from the 2D int array.

int[][] board = new int[10][10]; //board

//Converting int array to String array
String[][] s = new String[board.length][];
for(int i = 0; i < board.length; i++){
    s[i] = new String[board[i].length];
    for(int j=0; j<board[i].length; j++){
        s[i][j] = Integer.toString(board[i][j]);
    }
}

if (s[x][y].equals("r")){
    s[x][y] = "d";
}


问:
Terminate pod after did not find correct file
I tried to set up pod which use init container to create file. If the file does not exist it should terminate immediately. Here is my yaml file

```<code>apiVersion: v1
kind: Pod
metadata:
  name: init-test-pod4
spec:
  volumes:
  - name: my-pvc
    persistentVolumeClaim:
      claimName: mypvc
  containers:
  - name: myapp-container
    image: alpine
    command: ['sh', '-c', 'if [ **-f /workdir2/test.txt** ]; then exit 0; fi']
    volumeMounts:
    - name: mypvc
      mountPath: /workdir
  initContainers:
  - name: init-service
    image: busybox:1.28
    command: ['sh', '-c', '**mkdir /workdir; echo>/workdir/test.txt**']
    volumeMounts:
    - name: my-pvc
      mountPath: /workdir
</code>```

After i create yaml file i see this output.

```<code>init-test-pod4   0/1     Completed   1          11s
init-test-pod4   0/1     CrashLoopBackOff   1          22s
init-test-pod4   0/1     Completed          2          24s
init-test-pod4   0/1     CrashLoopBackOff   2          36s
init-test-pod4   0/1     Completed          3          51s
init-test-pod4   0/1     CrashLoopBackOff   3          61s
init-test-pod4   0/1     Completed          4          99s
init-test-pod4   0/1     CrashLoopBackOff   4          111s
</code>```

How to change the command which terminate the pod immediately after it did not find right file ?

答:
Default restartPolicy for a Kubernetes pod is always. Init-Container keeps restart when a given task fails. To prevent this, explicitly we should mention restartPolicy: Never in pod's manifest. But still, it won't be terminated. The init-container state will be moved to Completed.

```<code>apiVersion: v1
kind: Pod
metadata:
  name: init-test-pod4
spec:
  restartPolicy: Never
  volumes:
  - name: my-pvc
    emptyDir: {}
  containers:
  - name: myapp-container
    image: alpine
    command: ['sh', '-c', 'if [ **-f /workdir2/test.txt** ]; then exit 0; fi']
    volumeMounts:
    - name: my-pvc
      mountPath: /workdir
  initContainers:
  - name: init-service
    image: busybox:1.28
    command: ['sh', '-c', '**mkdir /workdir; echo>/workdir/test.txt**']
    volumeMounts:
    - name: my-pvc
      mountPath: /workdir
</code>```

```<code>kubectl get po init-test-pod4
NAME             READY   STATUS      RESTARTS   AGE
init-test-pod4   0/1     Completed   0          10m
</code>```

Body:
I tried to set up pod which use init container to create file. If the file does not exist it should terminate immediately. Here is my yaml file

apiVersion: v1
kind: Pod
metadata:
  name: init-test-pod4
spec:
  volumes:
  - name: my-pvc
    persistentVolumeClaim:
      claimName: mypvc
  containers:
  - name: myapp-container
    image: alpine
    command: ['sh', '-c', 'if [ **-f /workdir2/test.txt** ]; then exit 0; fi']
    volumeMounts:
    - name: mypvc
      mountPath: /workdir
  initContainers:
  - name: init-service
    image: busybox:1.28
    command: ['sh', '-c', '**mkdir /workdir; echo>/workdir/test.txt**']
    volumeMounts:
    - name: my-pvc
      mountPath: /workdir

After i create yaml file i see this output.

init-test-pod4   0/1     Completed   1          11s
init-test-pod4   0/1     CrashLoopBackOff   1          22s
init-test-pod4   0/1     Completed          2          24s
init-test-pod4   0/1     CrashLoopBackOff   2          36s
init-test-pod4   0/1     Completed          3          51s
init-test-pod4   0/1     CrashLoopBackOff   3          61s
init-test-pod4   0/1     Completed          4          99s
init-test-pod4   0/1     CrashLoopBackOff   4          111s

How to change the command which terminate the pod immediately after it did not find right file ?

Body:
Default restartPolicy for a Kubernetes pod is always. Init-Container keeps restart when a given task fails. To prevent this, explicitly we should mention restartPolicy: Never in pod's manifest. But still, it won't be terminated. The init-container state will be moved to Completed.

apiVersion: v1
kind: Pod
metadata:
  name: init-test-pod4
spec:
  restartPolicy: Never
  volumes:
  - name: my-pvc
    emptyDir: {}
  containers:
  - name: myapp-container
    image: alpine
    command: ['sh', '-c', 'if [ **-f /workdir2/test.txt** ]; then exit 0; fi']
    volumeMounts:
    - name: my-pvc
      mountPath: /workdir
  initContainers:
  - name: init-service
    image: busybox:1.28
    command: ['sh', '-c', '**mkdir /workdir; echo>/workdir/test.txt**']
    volumeMounts:
    - name: my-pvc
      mountPath: /workdir

kubectl get po init-test-pod4
NAME             READY   STATUS      RESTARTS   AGE
init-test-pod4   0/1     Completed   0          10m


问:
How to run a JavaScript .js file from an AJAX callback using native JavaScript?
I need to include and run the following from an AJAX callback (native JavaScript, no libraries):

```<code><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</code>```

So the following works on all web browsers that I tested, except (of course) IE11:

```<code>var scrt = document.createElement("script");
scrt.setAttribute('async', '');
scrt.setAttribute('src', 'https://platform.twitter.com/widgets.js');
scrt.setAttribute('charset', 'utf-8');
document.body.appendChild(scrt);
</code>```

IE shows no errors but the script from widgets.js is not executed.

So is there another way to do it that works with IE?

答:
Try this code to check if (when) twttr is available (loaded):

```<code>function checkTwitter() {
    if (!twttr.widgets) {
        setTimeout(checkTwitter.bind(this), 100);
    } else {
        // init:
        twttr.widgets.load();
    }
}
setTimeout(checkTwitter.bind(this), 100);
</code>```

See twitter initialization

P.S.: I'm not sure if you have to write 'twttr.widgets' or 'window.twttr.widgets'

Body:
I need to include and run the following from an AJAX callback (native JavaScript, no libraries):

So the following works on all web browsers that I tested, except (of course) IE11:

var scrt = document.createElement("script");
scrt.setAttribute('async', '');
scrt.setAttribute('src', 'https://platform.twitter.com/widgets.js');
scrt.setAttribute('charset', 'utf-8');
document.body.appendChild(scrt);

IE shows no errors but the script from widgets.js is not executed.

So is there another way to do it that works with IE?

Body:
Try this code to check if (when) twttr is available (loaded):

function checkTwitter() {
    if (!twttr.widgets) {
        setTimeout(checkTwitter.bind(this), 100);
    } else {
        // init:
        twttr.widgets.load();
    }
}
setTimeout(checkTwitter.bind(this), 100);

See twitter initialization

P.S.: I'm not sure if you have to write 'twttr.widgets' or 'window.twttr.widgets'


问:
Passing Array to Spark Lit function
Let's say I have a numpy array a that contains the numbers 1-10:

[1 2 3 4 5 6 7 8 9 10]

I also have a Spark dataframe to which I want to add my numpy array a. I figure that a column of literals will do the job. This doesn't work:

```<code>df = df.withColumn("NewColumn", F.lit(a))
</code>```

Unsupported literal type class java.util.ArrayList

But this works:

```<code>df = df.withColumn("NewColumn", F.lit(a[0]))
</code>```

How to do it?

Example DF before:

col1

a b c d e f g h i j

Expected result:

col1
NewColumn

a b c d e f g h i j
1 2 3 4 5 6 7 8 9 10

答:
In scala API, we can use "typedLit" function to add the Array or map values in the column.

// Ref : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

Here is the sample code to add an Array or Map as a column value.

```<code>import org.apache.spark.sql.functions.typedLit

val df1 = Seq((1, 0), (2, 3)).toDF("a", "b")

df1.withColumn("seq", typedLit(Seq(1,2,3)))
    .withColumn("map", typedLit(Map(1 -> 2)))
    .show(truncate=false)
</code>```

// Output

```<code>+---+---+---------+--------+
|a  |b  |seq      |map     |
+---+---+---------+--------+
|1  |0  |[1, 2, 3]|[1 -> 2]|
|2  |3  |[1, 2, 3]|[1 -> 2]|
+---+---+---------+--------+
</code>```

I hope this helps.

Title: Passing Array to Spark Lit function

Body:
Let's say I have a numpy array a that contains the numbers 1-10:

[1 2 3 4 5 6 7 8 9 10]

I also have a Spark dataframe to which I want to add my numpy array a. I figure that a column of literals will do the job. This doesn't work:

df = df.withColumn("NewColumn", F.lit(a))

Unsupported literal type class java.util.ArrayList

But this works:

df = df.withColumn("NewColumn", F.lit(a[0]))

How to do it?

Example DF before:

col1

a b c d e f g h i j

Expected result:

col1
NewColumn

a b c d e f g h i j
1 2 3 4 5 6 7 8 9 10

Body:
In scala API, we can use "typedLit" function to add the Array or map values in the column.

// Ref : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

Here is the sample code to add an Array or Map as a column value.

import org.apache.spark.sql.functions.typedLit

val df1 = Seq((1, 0), (2, 3)).toDF("a", "b")

df1.withColumn("seq", typedLit(Seq(1,2,3)))
    .withColumn("map", typedLit(Map(1 -> 2)))
    .show(truncate=false)

// Output

+---+---+---------+--------+
|a  |b  |seq      |map     |
+---+---+---------+--------+
|1  |0  |[1, 2, 3]|[1 -> 2]|
|2  |3  |[1, 2, 3]|[1 -> 2]|
+---+---+---------+--------+

I hope this helps.


问:
php mongo aggregate - loop through an array php
I am getting an array from mongo aggregate in PHP.

I am not able to read the array data in a loop. When I read the array it just gives me empty values.

I want data of communityId and branchcity. I am attaching my array and PHP code I am not able to find what am doing wrong.

My array is:

```<code>Array
(

[result] => Array (

[0] => Array (

        [libraryId] => LIB1002
        [communityId] => COM1
        [match_case] => Array (

        [0] => Array (

                [libraryId] => LIB1002
                [libraryName] => Oval Box
                [branchCity] => BRAN1002

                )
               )
        )
    [1] => Array (

        [libraryId] => LIB1003
        [match_case] => Array (
            [0] => Array (
                [libraryId] => LIB1003
                [libraryName] => House Keeping
                [branchCity] => BRAN1003
                )
            )
        )
    )
</code>```

[ok] => 1

PHP code

```<code>foreach ($library_selectdetails as $doc )

{

   echo $doc['libraryId'];

   echo $doc['match_case']['branchCity'];

}
</code>```

答:
To get the values, you have to use the key results. As communityId is missing from the second array, you could check for the key first.

```<code>foreach ($library_selectdetails["result"] as $doc) {
    if (array_key_exists("communityId", $doc)) {
        echo $doc["communityId"] . PHP_EOL;
    }
    echo $doc['match_case']['branchCity'] . PHP_EOL;
}
</code>```

See a Php demo

Body:
I am getting an array from mongo aggregate in PHP.

I am not able to read the array data in a loop. When I read the array it just gives me empty values.

I want data of communityId and branchcity. I am attaching my array and PHP code I am not able to find what am doing wrong.

My array is:

Array
(

[result] => Array (

[0] => Array (

        [libraryId] => LIB1002
        [communityId] => COM1
        [match_case] => Array (

        [0] => Array (

                [libraryId] => LIB1002
                [libraryName] => Oval Box
                [branchCity] => BRAN1002

                )
               )
        )
    [1] => Array (

        [libraryId] => LIB1003
        [match_case] => Array (
            [0] => Array (
                [libraryId] => LIB1003
                [libraryName] => House Keeping
                [branchCity] => BRAN1003
                )
            )
        )
    )

[ok] => 1

PHP code

foreach ($library_selectdetails as $doc )

{

   echo $doc['libraryId'];

   echo $doc['match_case']['branchCity'];

}

Body:
To get the values, you have to use the key results. As communityId is missing from the second array, you could check for the key first.

foreach ($library_selectdetails["result"] as $doc) {
    if (array_key_exists("communityId", $doc)) {
        echo $doc["communityId"] . PHP_EOL;
    }
    echo $doc['match_case']['branchCity'] . PHP_EOL;
}

See a Php demo


问:
how to update records after drag and drop
I am using react-sortable-hoc to drag/drop and reorder items. When I do this though I want to update the database (node.js and mongodb).

Firstly, I have changed it to be a functional component which is why my syntax looks a bit different to the example.

```<code>const onSortEnd = ({ oldIndex, newIndex }) => {

    setItems((items) => arrayMove(items, oldIndex, newIndex));

    const newArray = arrayMove(items, oldIndex, newIndex);

    async function makePatchRequest() {
      const config = {
        method: "patch",
        url: "http://localhost:8000/api/admin/faq/order",
        headers: { Authorization: "Bearer " + auth.token },
        data: {
          order: newArray,
        },
      };

      let res = await axios(config, { order: newArray });

    }
    makePatchRequest();
  };
</code>```

I am sending the new array to the backend with everything in the order after the drag and drop. The issue is that I don't really know what to do with it on the backend. Do I need to delete all records and then loop over the array and insert new records? I initially wanted to loop over the records and update them but it isn't actually doing anything, probably because the code is wrong or my logic is wrong because all it is doing is overwriting with the exact same data because all that has changed is the order of the array, not the actual id or _id in the array.

```<code>exports.faqSort = async (req, res) => {
  const { order } = req.body;
  console.log(order);

  await order.map((o) => {
    Faq.update({ _id: o._id }, { $set: { id: o.id } });
  });
};
</code>```

This is the array when the page loads:

```<code>[
  {
    _id: '5ed273049b268308302cb1fb',
    question: 'question 1',
    answer: 'answer 1',
    id: 1,
    __v: 0
  },
  {
    _id: '5ed273439b268308302cb1fd',
    question: 'question 2',
    answer: 'answer 2',
    id: 2,
    __v: 0
  },
  {
    _id: '5ed276129b268308302cb1ff',
    question: 'quesiton 3',
    answer: 'answer 3',
    id: 3,
    __v: 0
  }
]
</code>```

And this is the new array I send to the backend

```<code>[
  {
    _id: '5ed276129b268308302cb1ff',
    question: 'quesiton 3',
    answer: 'answer 3',
    order: 3,
    __v: 0
  },
  {
    _id: '5ed273049b268308302cb1fb',
    question: 'question 1',
    answer: 'answer 1',
    order: 1,
    __v: 0
  },
  {
    _id: '5ed273439b268308302cb1fd',
    question: 'question 2',
    answer: 'answer 2',
    order: 2,
    __v: 0
  }
]
</code>```

答:
Simplest and safest way I think would just be to use "order" key in the objects held by the array. You could just keep the array in any order, instead using the "order" key to handle, well, the order.

You can always manipulate your array with the built-in sort() method, or query this the "order" key in Mongoose.

Basically, don't use the array's order, but your own instead.

Body:
I am using react-sortable-hoc to drag/drop and reorder items. When I do this though I want to update the database (node.js and mongodb).

Firstly, I have changed it to be a functional component which is why my syntax looks a bit different to the example.

const onSortEnd = ({ oldIndex, newIndex }) => {

    setItems((items) => arrayMove(items, oldIndex, newIndex));

    const newArray = arrayMove(items, oldIndex, newIndex);

    async function makePatchRequest() {
      const config = {
        method: "patch",
        url: "http://localhost:8000/api/admin/faq/order",
        headers: { Authorization: "Bearer " + auth.token },
        data: {
          order: newArray,
        },
      };

      let res = await axios(config, { order: newArray });

    }
    makePatchRequest();
  };

I am sending the new array to the backend with everything in the order after the drag and drop. The issue is that I don't really know what to do with it on the backend. Do I need to delete all records and then loop over the array and insert new records? I initially wanted to loop over the records and update them but it isn't actually doing anything, probably because the code is wrong or my logic is wrong because all it is doing is overwriting with the exact same data because all that has changed is the order of the array, not the actual id or _id in the array.

exports.faqSort = async (req, res) => {
  const { order } = req.body;
  console.log(order);

  await order.map((o) => {
    Faq.update({ _id: o._id }, { $set: { id: o.id } });
  });
};

This is the array when the page loads:

[
  {
    _id: '5ed273049b268308302cb1fb',
    question: 'question 1',
    answer: 'answer 1',
    id: 1,
    __v: 0
  },
  {
    _id: '5ed273439b268308302cb1fd',
    question: 'question 2',
    answer: 'answer 2',
    id: 2,
    __v: 0
  },
  {
    _id: '5ed276129b268308302cb1ff',
    question: 'quesiton 3',
    answer: 'answer 3',
    id: 3,
    __v: 0
  }
]

And this is the new array I send to the backend

[
  {
    _id: '5ed276129b268308302cb1ff',
    question: 'quesiton 3',
    answer: 'answer 3',
    order: 3,
    __v: 0
  },
  {
    _id: '5ed273049b268308302cb1fb',
    question: 'question 1',
    answer: 'answer 1',
    order: 1,
    __v: 0
  },
  {
    _id: '5ed273439b268308302cb1fd',
    question: 'question 2',
    answer: 'answer 2',
    order: 2,
    __v: 0
  }
]


问:
how to validate enter button?
i had a functionality that in text box after entering a value when i pressed enter the value was validated.
Now i wanted to perform similar task by using enter button.
I had created an event for button click but not able to understand how to perform enter action.

i am sending code:

```<code><Button x:Name="BtnCancel" Content="CANCEL" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Center" Click="PlayerSwipeBtn_Click" Width="110" Height="55"  Margin="303,6,113,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" />
                <Button x:Name="BtnEntername" Content="Enter" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Stretch"  Width="110" Height="55"  Margin="113,6,303,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" Click="BtnEntername_Click" />

Xaml.cs code:
private void PlayerSwipeBtn_Click(object sender, RoutedEventArgs e)
        {
            Button btnAction = (Button)sender;
            ACTION = btnAction.Tag.ToString();
            if (ACTION == PLAYER_ACTIONS_CODE.CANCEL)
                this.DialogResult = false;
            else
                this.DialogResult = true;
        }
</code>```

what to do for enter button to validate entry.

答:
Below might help you. KeyCode for enter key is "13", you can modify and perform your logic to the below code.</p>

```<code> <script type="text/javascript" language="javascript">
 function clickButton(e)
         {
            var bt = document.getElementById('buttonid');
            if (typeof bt == 'object')
            {
                if(navigator.appName.indexOf("Netscape")>(-1))
                {
                    if (e.keyCode == 13)
                    {
                           //Enter Key Pressed
                            return false;
                    }
                }
                if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
                {
                    if (event.keyCode == 13)
                    {
                           //Enter Key Pressed
                            return false;
                    }
                }
            }
         }

    </script>
</code>```

Title: how to validate enter button?

Body:
i had a functionality that in text box after entering a value when i pressed enter the value was validated.
Now i wanted to perform similar task by using enter button.
I had created an event for button click but not able to understand how to perform enter action.

i am sending code:

<Button x:Name="BtnCancel" Content="CANCEL" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Center" Click="PlayerSwipeBtn_Click" Width="110" Height="55"  Margin="303,6,113,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" />
                <Button x:Name="BtnEntername" Content="Enter" Style="{StaticResource ButtonStyle10}"  VerticalAlignment="Stretch"  Width="110" Height="55"  Margin="113,6,303,4" HorizontalAlignment="Center"  Grid.Row="2" Grid.RowSpan="2" Click="BtnEntername_Click" />

Xaml.cs code:
private void PlayerSwipeBtn_Click(object sender, RoutedEventArgs e)
        {
            Button btnAction = (Button)sender;
            ACTION = btnAction.Tag.ToString();
            if (ACTION == PLAYER_ACTIONS_CODE.CANCEL)
                this.DialogResult = false;
            else
                this.DialogResult = true;
        }

what to do for enter button to validate entry.

Body:
Below might help you. KeyCode for enter key is "13", you can modify and perform your logic to the below code.

 <script type="text/javascript" language="javascript">
 function clickButton(e)
         {
            var bt = document.getElementById('buttonid');
            if (typeof bt == 'object')
            {
                if(navigator.appName.indexOf("Netscape")>(-1))
                {
                    if (e.keyCode == 13)
                    {
                           //Enter Key Pressed
                            return false;
                    }
                }
                if (navigator.appName.indexOf("Microsoft Internet Explorer")>(-1))
                {
                    if (event.keyCode == 13)
                    {
                           //Enter Key Pressed
                            return false;
                    }
                }
            }
         }

    </script>


问:
How to refine the use of stepVeriifer in this test?
I am using Flux from Reactor (projectreactor.io) to create a reactive stream.

In my stream generation method (connect()), I will put out in a number of message of type X, then at last near the end of the operation, I will emit a message of type Y and then call complete() of the flux stream.

The number of message X is unknown at the time of test. It could be more or less depending on the duration the test is run.

Here is my test condition at the moment:

```<code>var connectStream = service.connect();
StepVerifier.create(connectStream)
  .recordWith(ArrayList::new)
  .thenConsumeWhile(x -> true)
  .verifyComplete();
</code>```

It allows me to test the stream is closed by the server side.

My question is more of 'How to do it' nature: How can I ensure that there are more than 1 message of X and they are all followed a single message Y?

答:
Given you want "one or more" messages of type X, then exactly one of type Y:

```<code>StepVerifier.create(new Main().getFlux())
        .expectNextMatches(x -> x.equals("X"))
        .thenConsumeWhile(x -> x.equals("X"))
        .expectNextMatches(x -> x.equals("Y"))
        .verifyComplete();
</code>```

So:

```<code>Flux.just("X", "X", "X", "Y"); //Passes
Flux.just("X", "X", "X", "Y", "Y"); //Fails
Flux.just("Y"); //Fails
</code>```

In this trivial example you could of course just use expectNext() in place of expectNextMatches() - I use the latter as you say you want to test for types rather than values, so I suspect it's likely you'll need that predicate rather than a fixed value.

Body:
I am using Flux from Reactor (projectreactor.io) to create a reactive stream.

In my stream generation method (connect()), I will put out in a number of message of type X, then at last near the end of the operation, I will emit a message of type Y and then call complete() of the flux stream.

The number of message X is unknown at the time of test. It could be more or less depending on the duration the test is run.

Here is my test condition at the moment:

var connectStream = service.connect();
StepVerifier.create(connectStream)
  .recordWith(ArrayList::new)
  .thenConsumeWhile(x -> true)
  .verifyComplete();

It allows me to test the stream is closed by the server side.

My question is more of 'How to do it' nature: How can I ensure that there are more than 1 message of X and they are all followed a single message Y?

Body:
Given you want "one or more" messages of type X, then exactly one of type Y:

StepVerifier.create(new Main().getFlux())
        .expectNextMatches(x -> x.equals("X"))
        .thenConsumeWhile(x -> x.equals("X"))
        .expectNextMatches(x -> x.equals("Y"))
        .verifyComplete();

So:

Flux.just("X", "X", "X", "Y"); //Passes
Flux.just("X", "X", "X", "Y", "Y"); //Fails
Flux.just("Y"); //Fails

In this trivial example you could of course just use expectNext() in place of expectNextMatches() - I use the latter as you say you want to test for types rather than values, so I suspect it's likely you'll need that predicate rather than a fixed value.


问:
Python video has no sound when sent from whatsapp
I have a specific problem while sending my videos from Whatsapp on an iPhone (everything else works: android, web app on windows and mac). Below you can see my code, every time I send my video from the Whatsapp app on iPhone it appears to be without sound on iPhone devices, I will note that if I send the same video through drive for an example it's working fine.

I will add as well that regular mp4 videos do transfer with sound.
Thanks :)

```<code>with codecs.open(self.fileName + '.txt', 'r', encoding='utf8') as stampFile:
  for line in stampFile:
      if self.stop:
          return
      self.counter += 1
      time = line.split(";")
      currStart = timeClass.calculateTimeToSec(time[0])
      currEnd = timeClass.calculateTimeToSec(time[1])
      currStart = max(currStart, 0)
      currEnd = max(currEnd, 0)
      if currEnd <= currStart:
          return
      clip = VideoFileClip(self.mediaFilePath)
      if currStart >= clip.duration:
          return
      currStart = min(currStart, clip.duration - 1)
      currEnd = min(currEnd, clip.duration)
      clip = clip.subclip(currStart, min(currEnd, clip.duration))
      path = self.dirName + "\\BBrief-Clips" + "/BBrief-" + str(self.counter) + "-" + self.mediaFileName
        #threading.Thread(target=lambda: clip.write_videofile(path, codec='libx264')).start()
        clip.write_videofile(path, codec='libx264')
        if prevClip is None:
            prevClip = clip
            clip = fadeout(clip, 1)
        else:
            clip = clip.set_start(prevClip.end)
            clip = fadein(clip, 1)
            clip = fadeout(clip, 1)
            prevClip = clip
        clips.append(clip)
        duration += currStart - currEnd

    path = self.dirName + "\\Singel-BBrief" + "/BBrief-" + self.mediaFileName
    CompositeVideoClip(clips).write_videofile(path, codec='libx264')
    T.sleep(1)
    self.counter += 1
    for clip in clips:
        clip.close()
</code>```

答:
I managed to solve this solution by changing the output file to be MOV.</p>

```<code>path = self.dirName + "mediaFileName"[:-4]+".MOV"
    CompositeVideoClip(clips).write_videofile(path, codec='libx264')
</code>```

Body:
I have a specific problem while sending my videos from Whatsapp on an iPhone (everything else works: android, web app on windows and mac). Below you can see my code, every time I send my video from the Whatsapp app on iPhone it appears to be without sound on iPhone devices, I will note that if I send the same video through drive for an example it's working fine.

I will add as well that regular mp4 videos do transfer with sound.
Thanks :)

with codecs.open(self.fileName + '.txt', 'r', encoding='utf8') as stampFile:
  for line in stampFile:
      if self.stop:
          return
      self.counter += 1
      time = line.split(";")
      currStart = timeClass.calculateTimeToSec(time[0])
      currEnd = timeClass.calculateTimeToSec(time[1])
      currStart = max(currStart, 0)
      currEnd = max(currEnd, 0)
      if currEnd <= currStart:
          return
      clip = VideoFileClip(self.mediaFilePath)
      if currStart >= clip.duration:
          return
      currStart = min(currStart, clip.duration - 1)
      currEnd = min(currEnd, clip.duration)
      clip = clip.subclip(currStart, min(currEnd, clip.duration))
      path = self.dirName + "\\BBrief-Clips" + "/BBrief-" + str(self.counter) + "-" + self.mediaFileName
        #threading.Thread(target=lambda: clip.write_videofile(path, codec='libx264')).start()
        clip.write_videofile(path, codec='libx264')
        if prevClip is None:
            prevClip = clip
            clip = fadeout(clip, 1)
        else:
            clip = clip.set_start(prevClip.end)
            clip = fadein(clip, 1)
            clip = fadeout(clip, 1)
            prevClip = clip
        clips.append(clip)
        duration += currStart - currEnd

    path = self.dirName + "\\Singel-BBrief" + "/BBrief-" + self.mediaFileName
    CompositeVideoClip(clips).write_videofile(path, codec='libx264')
    T.sleep(1)
    self.counter += 1
    for clip in clips:
        clip.close()

Body:
I managed to solve this solution by changing the output file to be MOV.

path = self.dirName + "mediaFileName"[:-4]+".MOV"
    CompositeVideoClip(clips).write_videofile(path, codec='libx264')