问:
Low accuracy on simple neural network
I’ve been working on building my first neural network from scratch, but the accuracy is very low (~10%).

import math
import numpy as np

####################################################################################################

# In this program, we will create a class that builds a neural network from scratch and use it to identify the images of digits 0-9 imported
# from the sklearn library.

####################################################################################################

# Create the ‘Nnetwork’ class and define its arguments:
# Set the number of neurons/nodes for each layer
# and initialize the weight matrices:

class Nnetwork:

    def __init__(self):
        # Initialize the values of the NN to the parameters passed into the function
        self.no_of_in_nodes = 8 * 8  # Hardcoded for now
        self.no_of_out_nodes = 10  # Right now we are doing 10 because we want to be able to recognize 10 different digits 0-9
        self.no_of_hidden_nodes = math.floor(
            self.no_of_in_nodes * 2 / 3) + self.no_of_out_nodes  # Formula for calculating appropriate amount of hidden nodes
        self.no_of_hidden_layers = 2  # This number will help determining how many nodes per hidden layer there are
        self.learning_rate = .01  # How strongly the weights will change after back propagation

        # Calculate the number of nodes per hidden layer to make life easier.
        # We are assuming that all hidden layers have the same amount of nodes
        self.no_of_nodes_per_hidden_layer = int(self.no_of_hidden_nodes / self.no_of_hidden_layers)
        # print("Number of nodes per hidden layer:", self.no_of_nodes_per_hidden_layer)

        # Initialize the weight matrices of the NN
        # We have 3 weight matrices, two for the hidden layers and one for the output layer because they all differ in size
        self.first_hidden_layer_weights = np.random.rand(self.no_of_in_nodes + 1,
                                                         self.no_of_nodes_per_hidden_layer)  # The +1 here is for the bias weights.
        # The first row of the weight matrix is the bias weights and the following rows are the weights of the input neurons
        # This means that technically every single neuron in the hidden layer will have one bias node connected to it multiplied by a weight
        # But in reality it is just one bias node with a weight going into every single node of the hidden layer. Each of these weights
        # counts as one parameter. E.g. if the input layer had 5 neurons and a bias node, and the output layer has 4 neurons, then the model
        # has 4*(5+1) parameters. 5 weights plus the bias weight for each node, and that for each of the 4 nodes in the output layer.
        # print(self.hidden_layer_weights.shape)

        self.second_hidden_layer_weights = np.random.rand(self.no_of_nodes_per_hidden_layer + 1,
                                                          self.no_of_nodes_per_hidden_layer)

        self.output_layer_weights = np.random.rand(self.no_of_nodes_per_hidden_layer + 1,
                                                   self.no_of_out_nodes)  # The + 1 here is for the bias weights again

        # print(self.output_layer_weights.shape)

        # Initialize node matrices of the NN. These will hold the activation values of the nodes and are initialized to 0
        self.input_layer_nodes = np.zeros((self.no_of_in_nodes + 1, 1))  # + 1 for extra bias node
        self.input_layer_nodes[0, 0] = 1
        # print(self.input_layer_nodes)
        self.first_hidden_layer_nodes = np.zeros(
            (self.no_of_nodes_per_hidden_layer + 1, 1))  # +1 for extra bias node
        self.first_hidden_layer_nodes[0, 0] = 1

        self.second_hidden_layer_nodes = np.zeros(
            (self.no_of_nodes_per_hidden_layer + 1, 1))  # +1 for extra bias node
        self.second_hidden_layer_nodes[0, 0] = 1

        self.output_layer_nodes = np.zeros((self.no_of_out_nodes, 1))

        # print(self.input_layer_nodes.shape)
        # print(self.hidden_layer_nodes.shape)
        # print(self.output_layer_nodes.shape)

    ####################################################################################################

    # This will be our method for training our neural network. It takes an input vector and the desired output (labels)
    def forwardprop(self, input_vector, target_vector):
        # First we need to normalize the input vector, otherwise the tanh function will just return 0s and 1s
        # print(input_vector.shape)

        norm_input = input_vector / np.linalg.norm(input_vector)
        # Let's assume that the input we receive is already in the vector form we need for simplicity.
        self.input_layer_nodes[1:, :] = norm_input  # Initialize the input layer nodes to the input.
        # Index every node starting from 1 instead of 0 since the 0th node is the bias node
        # print(self.input_layer_nodes)

        # ------------------------

        # Now we need to apply all the weights of the input layer to the first hidden layer
        # The way the weights are organized each, row represents all the weights for a single neuron in the input layer. If we take the
        # transpose of this matrix, then each column will represent all the weights going from that specific node of the input layer to the
        # nodes of the next layer (hidden layer).
        # In this case we only have two hidden layers, so I did it by hand, but in the case of many hidden layers we need to loop through
        # them here.
        # We will perform the matrix multiplication, but then we need to normalize the data so that the tanh function can make something
        # useful out of it.

        # ----------------------------
        # Forward propagation from input layer into first hidden layer
        first_hidden_layer_nodes = np.matmul(self.first_hidden_layer_weights.transpose(), self.input_layer_nodes)
        # print(hidden_layer_nodes)

        # This gives us the weighted sum of the activation from the input layer
        # print(hidden_layer_nodes)
        norm_first_hidden_layer_nodes = first_hidden_layer_nodes / np.linalg.norm(first_hidden_layer_nodes)
        # print(norm_hidden_layer_nodes)
        self.first_hidden_layer_nodes[1:, :] = tanh(norm_first_hidden_layer_nodes)  # Larger number give all 1's
        # print(self.hidden_layer_nodes)

        # ----------------------------
        # Forward propagation from first hidden layer into second hidden layer
        second_hidden_layer_nodes = np.matmul(self.second_hidden_layer_weights.transpose(), self.first_hidden_layer_nodes)
        # print(hidden_layer_nodes)

        # This gives us the weighted sum of the activation from the input layer
        # print(hidden_layer_nodes)
        norm_second_hidden_layer_nodes = second_hidden_layer_nodes / np.linalg.norm(second_hidden_layer_nodes)
        # print(norm_hidden_layer_nodes)
        self.second_hidden_layer_nodes[1:, :] = tanh(norm_second_hidden_layer_nodes)  # Larger number give all 1's

        # ----------------------------
        # Forward propagation from second hidden layer into output layer
        output_layer_nodes = np.matmul(self.output_layer_weights.transpose(), self.second_hidden_layer_nodes)
        norm_output_layer_nodes = output_layer_nodes / np.linalg.norm(output_layer_nodes)
        self.output_layer_nodes = tanh(norm_output_layer_nodes)
        # print(self.output_layer_nodes)

        # print('Loss:', self.loss(target_vector))

    ####################################################################################################

    def backprop(self, target, learning_rate):
        """All of these steps are explained in detail in this video: https://www.youtube.com/watch?v=tIeHLnjs5U8"""
        # Backprop would usually contain a loop but since we only have 2 hidden layers we can do it manually for clarity

        # ---------------------------------------------------------------------------------------- #

        # WEIGHT ADJUSTMENT OUTPUT LAYER
        # z is the derivative of the activation of the previous layer multiplied by the weights with the bias added on
        # It is needed for calculating the derivatives of the components of the derivative of the cost function with respect to the weights
        z = np.matmul(self.output_layer_weights.transpose(),
                      self.second_hidden_layer_nodes)

        # print(z.shape)

        # Again normalize for tanh function
        z_norm = z / np.linalg.norm(z)

        # This is the derivative of z with respect to the weights
        hidden_activation = self.second_hidden_layer_nodes  # Doesn't need to be normalized because it already went through norm tanh
        # print(hidden_activation)

        # This is the derivative of the tanh function
        tanh_derivative = 1 - np.square(tanh(z_norm))

        # This is the derivative of the cost with respect to the activation of the current layer
        cost_derivative = 2 * (self.output_layer_nodes - target)

        # The product of all three of these combined should
        # give us the negative gradient meaning the amount which we should adjust the
        # weights to move towards our desired result

        output_layer_gradient = -np.matmul(hidden_activation, np.multiply(tanh_derivative, cost_derivative).transpose())[1:, :]
        # print(output_layer_gradient)

        # After this, we need to add the result to our weight matrix so that the adjustments take effect
        # Do not modify these weights yet as we need them to calculate the activation of the previous layer that minimizes the cost function

        # BIAS WEIGHT ADJUSTMENT OUTPUT LAYER

        bias_weights_output_layer = np.multiply(tanh_derivative, cost_derivative).transpose()

        # ---------------------------------------------------------------------------------------- #

        # WEIGHT ADJUSTMENT SECOND HIDDEN LAYER
        ideal_activation = np.matmul(self.output_layer_weights[1:, :], np.multiply(tanh_derivative, cost_derivative))
        norm_ideal_activation = ideal_activation / np.linalg.norm(ideal_activation)

        z = np.matmul(self.second_hidden_layer_weights.transpose(),
                      self.first_hidden_layer_nodes)  # 0 is our bias here, but we will have a matrix for it in the future

        # Again normalize for tanh function
        z_norm = z / np.linalg.norm(z)

        # This is the derivative of z with respect to the weights
        input_activation = self.first_hidden_layer_nodes

        # print(input_activation)

        # This is the derivative of the sigmoid function
        # sigmoid_derivative = np.exp(-z_norm) / np.square(1 + np.exp(-z_norm))
        # print(sigmoid_derivative.shape)

        # This is the derivative of tanh
        tanh_derivative = 1 - np.square(tanh(z_norm))

        # This is the derivative of the cost with respect to the output layer of this example
        cost_derivative = 2 * (
                self.second_hidden_layer_nodes[1:, :] - norm_ideal_activation)  # We can ignore the bias activation in this case
        # because there is no weight going from the input layer into the bias node
        # print(cost_derivative.shape)

        # The product of all three of these combined should give us the negative gradient meaning the amount which we should adjust the
        # weights to move towards our desired result
        # We want to omit the first row because we will be calculating the change of weights for the bias separately
        second_hidden_layer_gradient = -np.matmul(input_activation, np.multiply(tanh_derivative, cost_derivative).transpose())[1:, :]
        # print(second_hidden_layer_gradient.shape)

        # BIAS WEIGHT ADJUSTMENT SECOND HIDDEN LAYER

        bias_weights_second_hidden_layer = np.multiply(tanh_derivative, cost_derivative).transpose()

        # ---------------------------------------------------------------------------------------- #

        # Here we will calculate the desired activation of the previous layer to minimize the cost function

        ideal_activation = np.matmul(self.second_hidden_layer_weights, np.multiply(tanh_derivative, cost_derivative))
        norm_ideal_activation = ideal_activation / np.linalg.norm(ideal_activation)

        # WEIGHT ADJUSTMENT FIRST HIDDEN
        # Then we need to do the same for the weights between the first hidden layer and the input layer
        # We need to get the derivative of the cost function with respect to the activation of the previous layer so that we can calculate
        # the difference of the activation of that layer and the activation of that layer that would minimize the cost.

        z = np.matmul(self.first_hidden_layer_weights.transpose(),
                      self.input_layer_nodes)  # 0 is out bias here, but we will have a matrix for it in the future

        # Again normalize for tanh function
        z_norm = z / np.linalg.norm(z)

        # This is the derivative of z with respect to the weights
        input_activation = self.input_layer_nodes

        # print(input_activation)

        # This is the derivative of the sigmoid function
        # sigmoid_derivative = np.exp(-z_norm) / np.square(1 + np.exp(-z_norm))
        # print(sigmoid_derivative.shape)

        # This is the derivative of tanh
        tanh_derivative = 1 - np.square(tanh(z_norm))

        # This is the derivative of the cost with respect to the output layer of this example
        cost_derivative = 2 * (
                self.first_hidden_layer_nodes[1:, :] - norm_ideal_activation[1:, :])  # We can ignore the bias activation in this case
        # because there is no weight going from the input layer into the bias node
        # print(cost_derivative.shape)

        # The product of all three of these combined should give us the negative gradient meaning the amount which we should adjust the
        # weights to move towards our desired result
        first_hidden_layer_gradient = -np.matmul(input_activation, np.multiply(tanh_derivative, cost_derivative).transpose())[1:, :]
        # print(hidden_layer_gradient)

        # BIAS WEIGHT ADJUSTMENT OUTPUT LAYER

        bias_weights_first_hidden_layer = np.multiply(tanh_derivative, cost_derivative).transpose()

        # print(self.first_hidden_layer_weights[0])

        # --------------------------------------------------------------------------------------- #

        # Now we can update all weights with their respective new gradients
        self.output_layer_weights[1:, :] = self.output_layer_weights[1:, :] + output_layer_gradient * learning_rate
        self.output_layer_weights[0] = bias_weights_output_layer * learning_rate

        self.second_hidden_layer_weights[1:, :] = self.second_hidden_layer_nodes[1:, :] + second_hidden_layer_gradient * learning_rate
        self.second_hidden_layer_weights[0] = bias_weights_second_hidden_layer * learning_rate

        self.first_hidden_layer_weights[1:, :] = self.first_hidden_layer_weights[1:, :] + first_hidden_layer_gradient * learning_rate
        self.first_hidden_layer_weights[0] = bias_weights_first_hidden_layer * learning_rate
```

It takes 8x8 greyscale images and is supposed to be able to recognize digits from 0-9. I can’t find any obvious mistakes in the math, but I’m sure that I must be making a bad mistake somewhere. I am also a bit confused on when exactly to normalize. I’ve assumed that I need to normalize every input I give to an activation function since very large and very small inputs just result in 0s and 1s. I’ve tried to document my thought process into the code as much as possible through comments. The data set I’m using is from sklearn so I am not worried about that being an issue and I’ve also played around with the learning rate, the test-train split, and the number of hidden layers. Any help would be appreciated.

Thank you.

https://github.com/WallerCodes/FirstNN/blob/main/neuralNetwork.py

Title: Low accuracy on simple neural network

Body:
I’ve been working on building my first neural network from scratch, but the accuracy is very low (~10%).

import math
import numpy as np

####################################################################################################

# In this program, we will create a class that builds a neural network from scratch and use it to identify the images of digits 0-9 imported
# from the sklearn library.

####################################################################################################

# Create the ‘Nnetwork’ class and define its arguments:
# Set the number of neurons/nodes for each layer
# and initialize the weight matrices:

class Nnetwork:

    def __init__(self):
        # Initialize the values of the NN to the parameters passed into the function
        self.no_of_in_nodes = 8 * 8  # Hardcoded for now
        self.no_of_out_nodes = 10  # Right now we are doing 10 because we want to be able to recognize 10 different digits 0-9
        self.no_of_hidden_nodes = math.floor(
            self.no_of_in_nodes * 2 / 3) + self.no_of_out_nodes  # Formula for calculating appropriate amount of hidden nodes
        self.no_of_hidden_layers = 2  # This number will help determining how many nodes per hidden layer there are
        self.learning_rate = .01  # How strongly the weights will change after back propagation

        # Calculate the number of nodes per hidden layer to make life easier.
        # We are assuming that all hidden layers have the same amount of nodes
        self.no_of_nodes_per_hidden_layer = int(self.no_of_hidden_nodes / self.no_of_hidden_layers)
        # print("Number of nodes per hidden layer:", self.no_of_nodes_per_hidden_layer)

        # Initialize the weight matrices of the NN
        # We have 3 weight matrices, two for the hidden layers and one for the output layer because they all differ in size
        self.first_hidden_layer_weights = np.random.rand(self.no_of_in_nodes + 1,
                                                         self.no_of_nodes_per_hidden_layer)  # The +1 here is for the bias weights.
        # The first row of the weight matrix is the bias weights and the following rows are the weights of the input neurons
        # This means that technically every single neuron in the hidden layer will have one bias node connected to it multiplied by a weight
        # But in reality it is just one bias node with a weight going into every single node of the hidden layer. Each of these weights
        # counts as one parameter. E.g. if the input layer had 5 neurons and a bias node, and the output layer has 4 neurons, then the model
        # has 4*(5+1) parameters. 5 weights plus the bias weight for each node, and that for each of the 4 nodes in the output layer.
        # print(self.hidden_layer_weights.shape)

        self.second_hidden_layer_weights = np.random.rand(self.no_of_nodes_per_hidden_layer + 1,
                                                          self.no_of_nodes_per_hidden_layer)

        self.output_layer_weights = np.random.rand(self.no_of_nodes_per_hidden_layer + 1,
                                                   self.no_of_out_nodes)  # The + 1 here is for the bias weights again

        # print(self.output_layer_weights.shape)

        # Initialize node matrices of the NN. These will hold the activation values of the nodes and are initialized to 0
        self.input_layer_nodes = np.zeros((self.no_of_in_nodes + 1, 1))  # + 1 for extra bias node
        self.input_layer_nodes[0, 0] = 1
        # print(self.input_layer_nodes)
        self.first_hidden_layer_nodes = np.zeros(
            (self.no_of_nodes_per_hidden_layer + 1, 1))  # +1 for extra bias node
        self.first_hidden_layer_nodes[0, 0] = 1

        self.second_hidden_layer_nodes = np.zeros(
            (self.no_of_nodes_per_hidden_layer + 1, 1))  # +1 for extra bias node
        self.second_hidden_layer_nodes[0, 0] = 1

        self.output_layer_nodes = np.zeros((self.no_of_out_nodes, 1))

        # print(self.input_layer_nodes.shape)
        # print(self.hidden_layer_nodes.shape)
        # print(self.output_layer_nodes.shape)

    ####################################################################################################

    # This will be our method for training our neural network. It takes an input vector and the desired output (labels)
    def forwardprop(self, input_vector, target_vector):
        # First we need to normalize the input vector, otherwise the tanh function will just return 0s and 1s
        # print(input_vector.shape)

        norm_input = input_vector / np.linalg.norm(input_vector)
        # Let's assume that the input we receive is already in the vector form we need for simplicity.
        self.input_layer_nodes[1:, :] = norm_input  # Initialize the input layer nodes to the input.
        # Index every node starting from 1 instead of 0 since the 0th node is the bias node
        # print(self.input_layer_nodes)

        # ------------------------

        # Now we need to apply all the weights of the input layer to the first hidden layer
        # The way the weights are organized each, row represents all the weights for a single neuron in the input layer. If we take the
        # transpose of this matrix, then each column will represent all the weights going from that specific node of the input layer to the
        # nodes of the next layer (hidden layer).
        # In this case we only have two hidden layers, so I did it by hand, but in the case of many hidden layers we need to loop through
        # them here.
        # We will perform the matrix multiplication, but then we need to normalize the data so that the tanh function can make something
        # useful out of it.

        # ----------------------------
        # Forward propagation from input layer into first hidden layer
        first_hidden_layer_nodes = np.matmul(self.first_hidden_layer_weights.transpose(), self.input_layer_nodes)
        # print(hidden_layer_nodes)

        # This gives us the weighted sum of the activation from the input layer
        # print(hidden_layer_nodes)
        norm_first_hidden_layer_nodes = first_hidden_layer_nodes / np.linalg.norm(first_hidden_layer_nodes)
        # print(norm_hidden_layer_nodes)
        self.first_hidden_layer_nodes[1:, :] = tanh(norm_first_hidden_layer_nodes)  # Larger number give all 1's
        # print(self.hidden_layer_nodes)

        # ----------------------------
        # Forward propagation from first hidden layer into second hidden layer
        second_hidden_layer_nodes = np.matmul(self.second_hidden_layer_weights.transpose(), self.first_hidden_layer_nodes)
        # print(hidden_layer_nodes)

        # This gives us the weighted sum of the activation from the input layer
        # print(hidden_layer_nodes)
        norm_second_hidden_layer_nodes = second_hidden_layer_nodes / np.linalg.norm(second_hidden_layer_nodes)
        # print(norm_hidden_layer_nodes)
        self.second_hidden_layer_nodes[1:, :] = tanh(norm_second_hidden_layer_nodes)  # Larger number give all 1's

        # ----------------------------
        # Forward propagation from second hidden layer into output layer
        output_layer_nodes = np.matmul(self.output_layer_weights.transpose(), self.second_hidden_layer_nodes)
        norm_output_layer_nodes = output_layer_nodes / np.linalg.norm(output_layer_nodes)
        self.output_layer_nodes = tanh(norm_output_layer_nodes)
        # print(self.output_layer_nodes)

        # print('Loss:', self.loss(target_vector))

    ####################################################################################################

    def backprop(self, target, learning_rate):
        """All of these steps are explained in detail in this video: https://www.youtube.com/watch?v=tIeHLnjs5U8"""
        # Backprop would usually contain a loop but since we only have 2 hidden layers we can do it manually for clarity

        # ---------------------------------------------------------------------------------------- #

        # WEIGHT ADJUSTMENT OUTPUT LAYER
        # z is the derivative of the activation of the previous layer multiplied by the weights with the bias added on
        # It is needed for calculating the derivatives of the components of the derivative of the cost function with respect to the weights
        z = np.matmul(self.output_layer_weights.transpose(),
                      self.second_hidden_layer_nodes)

        # print(z.shape)

        # Again normalize for tanh function
        z_norm = z / np.linalg.norm(z)

        # This is the derivative of z with respect to the weights
        hidden_activation = self.second_hidden_layer_nodes  # Doesn't need to be normalized because it already went through norm tanh
        # print(hidden_activation)

        # This is the derivative of the tanh function
        tanh_derivative = 1 - np.square(tanh(z_norm))

        # This is the derivative of the cost with respect to the activation of the current layer
        cost_derivative = 2 * (self.output_layer_nodes - target)

        # The product of all three of these combined should
        # give us the negative gradient meaning the amount which we should adjust the
        # weights to move towards our desired result

        output_layer_gradient = -np.matmul(hidden_activation, np.multiply(tanh_derivative, cost_derivative).transpose())[1:, :]
        # print(output_layer_gradient)

        # After this, we need to add the result to our weight matrix so that the adjustments take effect
        # Do not modify these weights yet as we need them to calculate the activation of the previous layer that minimizes the cost function

        # BIAS WEIGHT ADJUSTMENT OUTPUT LAYER

        bias_weights_output_layer = np.multiply(tanh_derivative, cost_derivative).transpose()

        # ---------------------------------------------------------------------------------------- #

        # WEIGHT ADJUSTMENT SECOND HIDDEN LAYER
        ideal_activation = np.matmul(self.output_layer_weights[1:, :], np.multiply(tanh_derivative, cost_derivative))
        norm_ideal_activation = ideal_activation / np.linalg.norm(ideal_activation)

        z = np.matmul(self.second_hidden_layer_weights.transpose(),
                      self.first_hidden_layer_nodes)  # 0 is our bias here, but we will have a matrix for it in the future

        # Again normalize for tanh function
        z_norm = z / np.linalg.norm(z)

        # This is the derivative of z with respect to the weights
        input_activation = self.first_hidden_layer_nodes

        # print(input_activation)

        # This is the derivative of the sigmoid function
        # sigmoid_derivative = np.exp(-z_norm) / np.square(1 + np.exp(-z_norm))
        # print(sigmoid_derivative.shape)

        # This is the derivative of tanh
        tanh_derivative = 1 - np.square(tanh(z_norm))

        # This is the derivative of the cost with respect to the output layer of this example
        cost_derivative = 2 * (
                self.second_hidden_layer_nodes[1:, :] - norm_ideal_activation)  # We can ignore the bias activation in this case
        # because there is no weight going from the input layer into the bias node
        # print(cost_derivative.shape)

        # The product of all three of these combined should give us the negative gradient meaning the amount which we should adjust the
        # weights to move towards our desired result
        # We want to omit the first row because we will be calculating the change of weights for the bias separately
        second_hidden_layer_gradient = -np.matmul(input_activation, np.multiply(tanh_derivative, cost_derivative).transpose())[1:, :]
        # print(second_hidden_layer_gradient.shape)

        # BIAS WEIGHT ADJUSTMENT SECOND HIDDEN LAYER

        bias_weights_second_hidden_layer = np.multiply(tanh_derivative, cost_derivative).transpose()

        # ---------------------------------------------------------------------------------------- #

        # Here we will calculate the desired activation of the previous layer to minimize the cost function

        ideal_activation = np.matmul(self.second_hidden_layer_weights, np.multiply(tanh_derivative, cost_derivative))
        norm_ideal_activation = ideal_activation / np.linalg.norm(ideal_activation)

        # WEIGHT ADJUSTMENT FIRST HIDDEN
        # Then we need to do the same for the weights between the first hidden layer and the input layer
        # We need to get the derivative of the cost function with respect to the activation of the previous layer so that we can calculate
        # the difference of the activation of that layer and the activation of that layer that would minimize the cost.

        z = np.matmul(self.first_hidden_layer_weights.transpose(),
                      self.input_layer_nodes)  # 0 is out bias here, but we will have a matrix for it in the future

        # Again normalize for tanh function
        z_norm = z / np.linalg.norm(z)

        # This is the derivative of z with respect to the weights
        input_activation = self.input_layer_nodes

        # print(input_activation)

        # This is the derivative of the sigmoid function
        # sigmoid_derivative = np.exp(-z_norm) / np.square(1 + np.exp(-z_norm))
        # print(sigmoid_derivative.shape)

        # This is the derivative of tanh
        tanh_derivative = 1 - np.square(tanh(z_norm))

        # This is the derivative of the cost with respect to the output layer of this example
        cost_derivative = 2 * (
                self.first_hidden_layer_nodes[1:, :] - norm_ideal_activation[1:, :])  # We can ignore the bias activation in this case
        # because there is no weight going from the input layer into the bias node
        # print(cost_derivative.shape)

        # The product of all three of these combined should give us the negative gradient meaning the amount which we should adjust the
        # weights to move towards our desired result
        first_hidden_layer_gradient = -np.matmul(input_activation, np.multiply(tanh_derivative, cost_derivative).transpose())[1:, :]
        # print(hidden_layer_gradient)

        # BIAS WEIGHT ADJUSTMENT OUTPUT LAYER

        bias_weights_first_hidden_layer = np.multiply(tanh_derivative, cost_derivative).transpose()

        # print(self.first_hidden_layer_weights[0])

        # --------------------------------------------------------------------------------------- #

        # Now we can update all weights with their respective new gradients
        self.output_layer_weights[1:, :] = self.output_layer_weights[1:, :] + output_layer_gradient * learning_rate
        self.output_layer_weights[0] = bias_weights_output_layer * learning_rate

        self.second_hidden_layer_weights[1:, :] = self.second_hidden_layer_nodes[1:, :] + second_hidden_layer_gradient * learning_rate
        self.second_hidden_layer_weights[0] = bias_weights_second_hidden_layer * learning_rate

        self.first_hidden_layer_weights[1:, :] = self.first_hidden_layer_weights[1:, :] + first_hidden_layer_gradient * learning_rate
        self.first_hidden_layer_weights[0] = bias_weights_first_hidden_layer * learning_rate

It takes 8x8 greyscale images and is supposed to be able to recognize digits from 0-9. I can’t find any obvious mistakes in the math, but I’m sure that I must be making a bad mistake somewhere. I am also a bit confused on when exactly to normalize. I’ve assumed that I need to normalize every input I give to an activation function since very large and very small inputs just result in 0s and 1s. I’ve tried to document my thought process into the code as much as possible through comments. The data set I’m using is from sklearn so I am not worried about that being an issue and I’ve also played around with the learning rate, the test-train split, and the number of hidden layers. Any help would be appreciated.

Thank you.

https://github.com/WallerCodes/FirstNN/blob/main/neuralNetwork.py


来源: stackexchange

问:
React TreeView JSON Data
Is there a way to create a TreeView navigation using React?

my data is returned as:

```<code>[{
    "make" : "BMW",
    "year" : "2020",
    "type" : "used"
 },
 {
    "make" : "BMW",
    "year" : "2022",
    "type" : "new"
 },
 {
   "make" : "lexus",
   "year" : "2022",
   "type" : "used"
 },
 {
   "make" : "lexus",
   "year" : "2022",
   "type" : "used"
 }
</code>```

I want the tree to look like

```<code> used
      2022
         bmw
         lexus
   new
       2022
          BMW
</code>```

I can't change the output format, so it has be done in the response object.

ContentLicense: CC BY-SA 4.0

Title: React TreeView JSON Data

Body:
Is there a way to create a TreeView navigation using React?

my data is returned as:

[{
    "make" : "BMW",
    "year" : "2020",
    "type" : "used"
 },
 {
    "make" : "BMW",
    "year" : "2022",
    "type" : "new"
 },
 {
   "make" : "lexus",
   "year" : "2022",
   "type" : "used"
 },
 {
   "make" : "lexus",
   "year" : "2022",
   "type" : "used"
 }

I want the tree to look like

 used
      2022
         bmw
         lexus
   new
       2022
          BMW

I can't change the output format, so it has be done in the response object.


问:
How to use archiveArtifacts in Jenkins using Artifactory
I'm at a lost on how I can publish artifacts to Artifactory and have the artifacts shown in Jenkins, as links to the artifacts. From Jenkins pipeline, I know how to manipulate the artifacts (upload/download/delete) to/from Artifactory using the JFrog CLI. However, that does not make the artifacts visible in the build's output page (shown as "Last Successful Artifacs"). I also know that archiveArtifacts is used to make that happens, but archiveArtifacts will store the artifacts in the controller, not Artifactory. I've seen this video here: https://www.youtube.com/watch?v=u6LF-T-daS4, where Amazon S3 can be used in place of the controller for storing artifacts. That's exactly what I needed to do, except that I need to use Artifactory instead of Amazon S3. Can someone with the knowledge help me to connect the dots? Documentation/sample pipeline scripts/videos and the likes would be very helpful.</p>


问:
How to close Binance popup screen
I am trying to get data from Binance with Selenium lib. but I have a problem when site is open there is going to be a 'screen says welcome to binance spot' and there is close button on it but I cant find it with xpath method and css selector. How can I fix this. If you help me I appriciate. This is my codeThis is popup

I tried to close it to continue my process

Title: How to close Binance popup screen


问:
Assist with bash loop using files
I'd like some help with this script I'm working on to utilize the AWS CLI. My goal is to get a list of instances base on tags. So far I have what want. However, I'd like some help with interating not only through my initial file, but again through another file.

Here's what I've tried, it's not pretty but it does the job for me. I need some assistance finishing it:

```<code>FILENAME="aws_regions.txt"
AWSREGIONS=$(cat $FILENAME)

for region in $AWSREGIONS
do
    echo "\nListing hosts in region:'$region'..."
    aws ec2 describe-instances --filters "Name=tag:name,Values=test" --output text --query 'Reservations[].Instances[].[InstanceId, PrivateIpAddress, Tags[?Key==`Name`].Value[] | [0]]' --region $region --profile default

done
</code>```

I would like to run this through a list of profiles I have saved in a text file. How would I do so? I'm not sure how I would replace --profile default with the list in the file.

Title: Assist with bash loop using files

Body:
I'd like some help with this script I'm working on to utilize the AWS CLI. My goal is to get a list of instances base on tags. So far I have what want. However, I'd like some help with interating not only through my initial file, but again through another file.

Here's what I've tried, it's not pretty but it does the job for me. I need some assistance finishing it:

FILENAME="aws_regions.txt"
AWSREGIONS=$(cat $FILENAME)

for region in $AWSREGIONS
do
    echo "\nListing hosts in region:'$region'..."
    aws ec2 describe-instances --filters "Name=tag:name,Values=test" --output text --query 'Reservations[].Instances[].[InstanceId, PrivateIpAddress, Tags[?Key==`Name`].Value[] | [0]]' --region $region --profile default

done

I would like to run this through a list of profiles I have saved in a text file. How would I do so? I'm not sure how I would replace --profile default with the list in the file.


问:
React - Blank page after building and deploying app to IIS
After I built and deployed my React App (initally built with Create-React-App) on IIS server, Chrome shows a blank page, 304 OK, and no errors as seen here: https://imgur.com/a/W2JunFc

How to resolve this?

When I Debug the app after deploying, I see that the debugger hits all my breakpoints in App.tsx (where my routes are) but not in any of route components.

I don't even know how to debug this issue because it is not throwing any errors.

I set "private": false, "homepage": "." in package.json.
I installed URL Rewrite module and added the below web.config file to the App's public folder so that the app works with React Router, but it made no difference:

```<code><?xml version="1.0"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="React Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>
</code>```

Body:
After I built and deployed my React App (initally built with Create-React-App) on IIS server, Chrome shows a blank page, 304 OK, and no errors as seen here: https://imgur.com/a/W2JunFc

How to resolve this?

When I Debug the app after deploying, I see that the debugger hits all my breakpoints in App.tsx (where my routes are) but not in any of route components.

I don't even know how to debug this issue because it is not throwing any errors.

I set "private": false, "homepage": "." in package.json.
I installed URL Rewrite module and added the below web.config file to the App's public folder so that the app works with React Router, but it made no difference:

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="React Routes" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>


问:
What can i do to decrease the completing time and make my code go faster at this little program(A program that prints narcissistic numbers))
```<code>#include <stdio.h>
#include <math.h>
#include <time.h>
int main(void){
    clock_t start=clock();
    for(int i=1;i<=11;i++){
        long long multi=(long long)pow(10,i-1);
        long long control_multi=(long long)pow(10,i);
        for(long long a=1*multi;a<=control_multi;a++){
            long long armstrong_copy=0;
            for(long long a_copy=a;a_copy;a_copy/=10){
                armstrong_copy+=(long long)pow(a_copy%10,i);
            }
            if(a==armstrong_copy){
                printf("%lld\n",a);
            }
        }
    }
    clock_t end=clock();

    printf("%f",(double )(end-start)/CLOCKS_PER_SEC);
}
</code>```

It takes 15 minutes to run and complete this program and I dont know how to decrease it to seconds and this program supposed to print narcissistic numbers up to and including the numbers that have 10 digits

Body:
#include <stdio.h>
#include <math.h>
#include <time.h>
int main(void){
    clock_t start=clock();
    for(int i=1;i<=11;i++){
        long long multi=(long long)pow(10,i-1);
        long long control_multi=(long long)pow(10,i);
        for(long long a=1*multi;a<=control_multi;a++){
            long long armstrong_copy=0;
            for(long long a_copy=a;a_copy;a_copy/=10){
                armstrong_copy+=(long long)pow(a_copy%10,i);
            }
            if(a==armstrong_copy){
                printf("%lld\n",a);
            }
        }
    }
    clock_t end=clock();

    printf("%f",(double )(end-start)/CLOCKS_PER_SEC);
}

It takes 15 minutes to run and complete this program and I dont know how to decrease it to seconds and this program supposed to print narcissistic numbers up to and including the numbers that have 10 digits


问:
Task Scheduler with Anaconda Python
I'm trying to use the Windows Task Scheduler to run a Python file but it seems to fail on anything more complex than command to save to a text file.

I have a python file that I'm able to run from the command prompt. When I move it to be scheduled, it fails. I've stripped back a file to only set a variable and save that value and other messages out to a text file and it runs. But as soon as I add something as simple as simple as import pandas as pd, it fails.

This is the first time I've tried this with this particular laptop. So maybe there's a configuration missing?

Removed all code except:

```<code>with open('SES Automation Status.txt', 'a') as f:
    f.write('\n Imported Packages')
</code>```

This works. Setting variables and printing the value out to the same file will also work. Anything more complex fails and it looks like it fails on the validation prior to running as if I put an import package instruction prior to one of the write to files that was running before, the whole thing fails.

Have tried running Task Scheduler in Admin and also have run with highest privleges selected. enter image description here. Doesn't work.

If tried invoking both the Anaconda prompt python location and another instance of python on the system in task scheduler and neither work. 0x2331 is the error code I receive on the non-Anaconda instance.

Title: Task Scheduler with Anaconda Python

Body:
I'm trying to use the Windows Task Scheduler to run a Python file but it seems to fail on anything more complex than command to save to a text file.

I have a python file that I'm able to run from the command prompt. When I move it to be scheduled, it fails. I've stripped back a file to only set a variable and save that value and other messages out to a text file and it runs. But as soon as I add something as simple as simple as import pandas as pd, it fails.

This is the first time I've tried this with this particular laptop. So maybe there's a configuration missing?

Removed all code except:

with open('SES Automation Status.txt', 'a') as f:
    f.write('\n Imported Packages')

This works. Setting variables and printing the value out to the same file will also work. Anything more complex fails and it looks like it fails on the validation prior to running as if I put an import package instruction prior to one of the write to files that was running before, the whole thing fails.

Have tried running Task Scheduler in Admin and also have run with highest privleges selected. enter image description here. Doesn't work.

If tried invoking both the Anaconda prompt python location and another instance of python on the system in task scheduler and neither work. 0x2331 is the error code I receive on the non-Anaconda instance.


问:
Python Unittest for function with input file and output file
I have a python function which I would like to make an automated test system for it. My function required an input file and will generate output file. I generated lots of test input and output files but its annoying to chech test files one by ones manually. Is there a way to do it in a completely automated way?

I used the following code for checking each test file but it's not automated.

```<code>import unittest
from mask import load
import io

class TestInterval(unittest.TestCase):
    def testinterval(self):
        input_path = "test10.txt.gz"
        output_path = "test_run.txt"
        column_name = "PCT"
        min_percent = 0.85
        max_depth = 100
        test_out = "test10_out.txt"
        load(column_name, input_path, output_path, min_percent, max_depth)
        self.assertListEqual(
            list(io.open(test_out)),
            list(io.open(output_path)))

if __name__ == '__main__':
    unittest.main()
</code>```

Body:
I have a python function which I would like to make an automated test system for it. My function required an input file and will generate output file. I generated lots of test input and output files but its annoying to chech test files one by ones manually. Is there a way to do it in a completely automated way?

I used the following code for checking each test file but it's not automated.

import unittest
from mask import load
import io

class TestInterval(unittest.TestCase):
    def testinterval(self):
        input_path = "test10.txt.gz"
        output_path = "test_run.txt"
        column_name = "PCT"
        min_percent = 0.85
        max_depth = 100
        test_out = "test10_out.txt"
        load(column_name, input_path, output_path, min_percent, max_depth)
        self.assertListEqual(
            list(io.open(test_out)),
            list(io.open(output_path)))

if __name__ == '__main__':
    unittest.main()


问:
Packages are not uploaded to the emulator on Android Studio
FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:validateSigningDebug'.
java.util.concurrent.ExecutionException: com.android.builder.utils.SynchronizedFile$ActionExecutionException: java.io.IOException: com.android.ide.common.signing.KeytoolException: Failed to create keystore.

Try:
Run with --stacktrace option to get the stack trace.

Run with --info or --debug option to get more log output.

Run with --scan to get full insights.

Get more help at https://help.gradle.org

BUILD FAILED in 25s
Exception: Gradle task assembleDebug failed with exit code 1text

I want a solution to upload and apply the flatter program on the emulator


问:
Different AIC results using base R (step/add1/drop1) in oppose to broom:: glance
I am reading this short paper:

https://pages.pomona.edu/~jsh04747/courses/math158/multlin4.pdf)

And following the examples on the mtcars dataset, I get different AIC results when comparing to glance from broom package.

Here is what I am talking about:

```<code>library(tidyverse)
library(broom)
df <- mtcars[,c(1,3:7)]
attach(df)
# Using stepwise backward in Base R:
step(lm(mpg~disp+hp+drat+wt+qsec),direction = "backward")
# AIC = 63.89, mpg ~ drat + wt + qsec

# Using glance() from broom:
glance(lm(mpg~disp+hp+drat+wt+qsec))
# AIC = 158

</code>```

I have a feeling I lack some formal theoretical knowledge about the formula but would love to get some help, because these are big differences...

I am aware of stepwise/back/for ward yielding different results depending on who got in the model first*

Body:
I am reading this short paper:

https://pages.pomona.edu/~jsh04747/courses/math158/multlin4.pdf)

And following the examples on the mtcars dataset, I get different AIC results when comparing to glance from broom package.

Here is what I am talking about:

library(tidyverse)
library(broom)
df <- mtcars[,c(1,3:7)]
attach(df)
# Using stepwise backward in Base R:
step(lm(mpg~disp+hp+drat+wt+qsec),direction = "backward")
# AIC = 63.89, mpg ~ drat + wt + qsec

# Using glance() from broom:
glance(lm(mpg~disp+hp+drat+wt+qsec))
# AIC = 158

I have a feeling I lack some formal theoretical knowledge about the formula but would love to get some help, because these are big differences...

I am aware of stepwise/back/for ward yielding different results depending on who got in the model first*


问:
No 'Access-Control-Allow-Origin' header is present on the requested resource
I'm having a struggle met CORS, after many attempts. I have tried the following; @CrossOrigin() in the controllers, added .cors() in filterchain, added a corsconfiurationsource in my securityconfig. Also if I dont write the whole url at the fetch function in React it goes to localhost:3000 instead of :8080 even though proxy is setup in package.json and works with other Get methods.

And now I am getting the following error when fetching a post method from React:

'Access to fetch at 'http://localhost:8080/like/liked' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'

So this is how my code looks like right now(Spring as backend & React as frontend) :

SecurityConfig.java

```<code>@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authz) -> authz
                        .antMatchers("/**/*.{js,html,css}").permitAll()
                        .antMatchers("/", "/user", "/").permitAll()
                        .anyRequest().authenticated()

                )
                .csrf((csrf) -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                )
                .cors()
                .and()
                .oauth2Login();
        return http.build();
    }

    @Bean
    public RequestCache refererRequestCache() {
        return new HttpSessionRequestCache() {
            @Override
            public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
                String referrer = request.getHeader("referer");
                if (referrer != null) {
                    request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST",
                            new SimpleSavedRequest(referrer));
                }
            }
        };
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
/*
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
*/
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
            configuration.addAllowedOrigin("*");
            configuration.addAllowedHeader("*");
            configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
</code>```

LikedController

```<code>@RestController
@RequestMapping("/like")
public class LikedController {
    @Autowired
    LikedService likedService = new LikedService();
    @Autowired
    NuserService nuserService = new NuserService();

    @PostMapping("/liked")
    public ResponseEntity<?> AddLikeToUser(@AuthenticationPrincipal OAuth2User ouser, @RequestBody Liked like)
    {
        if(like == null || ouser == null)
        {
            return ResponseEntity.ok().body("Something went wrong.");
        }
        else
        {
            Nuser user = nuserService.getuserbyemail(ouser.getAttribute("email"));
            like.setUser(user);
            like.setLiked_date(LocalDate.now());
            likedService.addLike(like);
            return ResponseEntity.ok().body("Person has been successfully liked");

        }
    }
</code>```

Date.js where I fetch the post method.

```<code>const Date = () => {
    const globalcontext = useContext(AppContext);
    const [cookies] = useCookies(['XRSF-TOKEN']);
    const [loading, setloading] = useState(false);
    const [error, seterror] = useState(false);
    const [users, setusers] = useState([]);

    useEffect(() => {
        setloading(true);
        fetch("/user/allotherusers", {credentials: "include"})
            .then(response => response.text())
            .then(body => {
                if (body === "") {
                    return <Navigate to="/"/>
                } else {
                    setusers(JSON.parse(body));
                }
                setloading(false);
            });
    }, [])

    const userlist = users.map(user => {
        return (
            <div key={user.id}>
                <p> {user.firstname}</p>
                <button onClick={() => like(user, false)}>Like</button>
            </div>
        )
    });

    const like =  async (likeduser, superlike) => {
        const likemodel =
            {
                likeduser: likeduser,
                superlike: superlike

            }

         await fetch("http://localhost:8080/like/liked", {
            method: "POST",
            headers: {
                'X-XSRF-TOKEN': cookies['XRSF-TOKEN'],
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
             credentials: 'include',
             body: JSON.stringify(likemodel)

        });
    };

    return (
        <div>
            {userlist}
        </div>
    );

}
export default Date;
</code>```

Package.json

```<code>"proxy": "http://localhost:8080",
</code>```

Body:
I'm having a struggle met CORS, after many attempts. I have tried the following; @CrossOrigin() in the controllers, added .cors() in filterchain, added a corsconfiurationsource in my securityconfig. Also if I dont write the whole url at the fetch function in React it goes to localhost:3000 instead of :8080 even though proxy is setup in package.json and works with other Get methods.

And now I am getting the following error when fetching a post method from React:

'Access to fetch at 'http://localhost:8080/like/liked' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'

So this is how my code looks like right now(Spring as backend & React as frontend) :

SecurityConfig.java

@EnableWebSecurity
@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests((authz) -> authz
                        .antMatchers("/**/*.{js,html,css}").permitAll()
                        .antMatchers("/", "/user", "/").permitAll()
                        .anyRequest().authenticated()

                )
                .csrf((csrf) -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                )
                .cors()
                .and()
                .oauth2Login();
        return http.build();
    }

    @Bean
    public RequestCache refererRequestCache() {
        return new HttpSessionRequestCache() {
            @Override
            public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
                String referrer = request.getHeader("referer");
                if (referrer != null) {
                    request.getSession().setAttribute("SPRING_SECURITY_SAVED_REQUEST",
                            new SimpleSavedRequest(referrer));
                }
            }
        };
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
/*
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
*/
        configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        //the below three lines will add the relevant CORS response headers
            configuration.addAllowedOrigin("*");
            configuration.addAllowedHeader("*");
            configuration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

LikedController

@RestController
@RequestMapping("/like")
public class LikedController {
    @Autowired
    LikedService likedService = new LikedService();
    @Autowired
    NuserService nuserService = new NuserService();

    @PostMapping("/liked")
    public ResponseEntity<?> AddLikeToUser(@AuthenticationPrincipal OAuth2User ouser, @RequestBody Liked like)
    {
        if(like == null || ouser == null)
        {
            return ResponseEntity.ok().body("Something went wrong.");
        }
        else
        {
            Nuser user = nuserService.getuserbyemail(ouser.getAttribute("email"));
            like.setUser(user);
            like.setLiked_date(LocalDate.now());
            likedService.addLike(like);
            return ResponseEntity.ok().body("Person has been successfully liked");

        }
    }

Date.js where I fetch the post method.

const Date = () => {
    const globalcontext = useContext(AppContext);
    const [cookies] = useCookies(['XRSF-TOKEN']);
    const [loading, setloading] = useState(false);
    const [error, seterror] = useState(false);
    const [users, setusers] = useState([]);

    useEffect(() => {
        setloading(true);
        fetch("/user/allotherusers", {credentials: "include"})
            .then(response => response.text())
            .then(body => {
                if (body === "") {
                    return <Navigate to="/"/>
                } else {
                    setusers(JSON.parse(body));
                }
                setloading(false);
            });
    }, [])

    const userlist = users.map(user => {
        return (

 {user.firstname}

                <button onClick={() => like(user, false)}>Like</button>

        )
    });

    const like =  async (likeduser, superlike) => {
        const likemodel =
            {
                likeduser: likeduser,
                superlike: superlike

            }

         await fetch("http://localhost:8080/like/liked", {
            method: "POST",
            headers: {
                'X-XSRF-TOKEN': cookies['XRSF-TOKEN'],
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
             credentials: 'include',
             body: JSON.stringify(likemodel)

        });
    };

    return (

            {userlist}

    );

}
export default Date;

Package.json

"proxy": "http://localhost:8080",


问:
Memcache and Memcached not working on PHPUnit test
I have configured my PHP to have Memcache/Memcached installed and enabled.

Typing php -m shows me both extensions:

```<code>% php -m | grep memcache
memcache
memcached
</code>```

With php -i | grep memcache I also have the two extensions loaded.

```<code>% php -i | grep memcache
memcache
memcache support => enabled
memcache.allow_failover => 1 => 1
memcache.chunk_size => 32768 => 32768
memcache.compress_threshold => 20000 => 20000
memcache.default_port => 11211 => 11211
memcache.hash_function => crc32 => crc32
memcache.hash_strategy => consistent => consistent
memcache.lock_timeout => 15 => 15
memcache.max_failover_attempts => 20 => 20
memcache.prefix_host_key => Off => Off
memcache.prefix_host_key_remove_subdomain => Off => Off
memcache.prefix_host_key_remove_www => On => On
memcache.prefix_static_key => no value => no value
memcache.protocol => ascii => ascii
memcache.redundancy => 1 => 1
memcache.session_prefix_host_key => Off => Off
memcache.session_prefix_host_key_remove_subdomain => Off => Off
memcache.session_prefix_host_key_remove_www => On => On
memcache.session_prefix_static_key => no value => no value
memcache.session_redundancy => 2 => 2
memcache.session_save_path => no value => no value
memcached
memcached support => enabled
libmemcached version => 1.0.18
memcached.compression_factor => 1.3 => 1.3
memcached.compression_threshold => 2000 => 2000
memcached.compression_type => fastlz => fastlz
memcached.default_binary_protocol => Off => Off
memcached.default_connect_timeout => 0 => 0
memcached.default_consistent_hash => Off => Off
memcached.serializer => igbinary => igbinary
memcached.sess_binary_protocol => On => On
memcached.sess_connect_timeout => 0 => 0
memcached.sess_consistent_hash => On => On
memcached.sess_consistent_hash_type => ketama => ketama
memcached.sess_lock_expire => 0 => 0
memcached.sess_lock_max_wait => not set => not set
memcached.sess_lock_retries => 5 => 5
memcached.sess_lock_wait => not set => not set
memcached.sess_lock_wait_max => 150 => 150
memcached.sess_lock_wait_min => 150 => 150
memcached.sess_locking => On => On
memcached.sess_number_of_replicas => 0 => 0
memcached.sess_persistent => Off => Off
memcached.sess_prefix => memc.sess.key. => memc.sess.key.
memcached.sess_randomize_replica_read => Off => Off
memcached.sess_remove_failed_servers => Off => Off
memcached.sess_sasl_password => no value => no value
memcached.sess_sasl_username => no value => no value
memcached.sess_server_failure_limit => 0 => 0
memcached.store_retry_count => 2 => 2
Registered save handlers => files user memcached memcache
</code>```

But even thought when running PHPUnit and trying to get Memcache / Memcached classes I receive a Class not found error.

The problem is that some tests rely on retrieving data from an API which is cached, so the tests fails without reason.

I installed both extensions correctly, made sure it's working on CLI.
When running phpunit it should work properly and the classes should be found.

Should I make any special setup for having these two extensions enabled on PHPUnit?

Body:
I have configured my PHP to have Memcache/Memcached installed and enabled.

Typing php -m shows me both extensions:

% php -m | grep memcache
memcache
memcached

With php -i | grep memcache I also have the two extensions loaded.

% php -i | grep memcache
memcache
memcache support => enabled
memcache.allow_failover => 1 => 1
memcache.chunk_size => 32768 => 32768
memcache.compress_threshold => 20000 => 20000
memcache.default_port => 11211 => 11211
memcache.hash_function => crc32 => crc32
memcache.hash_strategy => consistent => consistent
memcache.lock_timeout => 15 => 15
memcache.max_failover_attempts => 20 => 20
memcache.prefix_host_key => Off => Off
memcache.prefix_host_key_remove_subdomain => Off => Off
memcache.prefix_host_key_remove_www => On => On
memcache.prefix_static_key => no value => no value
memcache.protocol => ascii => ascii
memcache.redundancy => 1 => 1
memcache.session_prefix_host_key => Off => Off
memcache.session_prefix_host_key_remove_subdomain => Off => Off
memcache.session_prefix_host_key_remove_www => On => On
memcache.session_prefix_static_key => no value => no value
memcache.session_redundancy => 2 => 2
memcache.session_save_path => no value => no value
memcached
memcached support => enabled
libmemcached version => 1.0.18
memcached.compression_factor => 1.3 => 1.3
memcached.compression_threshold => 2000 => 2000
memcached.compression_type => fastlz => fastlz
memcached.default_binary_protocol => Off => Off
memcached.default_connect_timeout => 0 => 0
memcached.default_consistent_hash => Off => Off
memcached.serializer => igbinary => igbinary
memcached.sess_binary_protocol => On => On
memcached.sess_connect_timeout => 0 => 0
memcached.sess_consistent_hash => On => On
memcached.sess_consistent_hash_type => ketama => ketama
memcached.sess_lock_expire => 0 => 0
memcached.sess_lock_max_wait => not set => not set
memcached.sess_lock_retries => 5 => 5
memcached.sess_lock_wait => not set => not set
memcached.sess_lock_wait_max => 150 => 150
memcached.sess_lock_wait_min => 150 => 150
memcached.sess_locking => On => On
memcached.sess_number_of_replicas => 0 => 0
memcached.sess_persistent => Off => Off
memcached.sess_prefix => memc.sess.key. => memc.sess.key.
memcached.sess_randomize_replica_read => Off => Off
memcached.sess_remove_failed_servers => Off => Off
memcached.sess_sasl_password => no value => no value
memcached.sess_sasl_username => no value => no value
memcached.sess_server_failure_limit => 0 => 0
memcached.store_retry_count => 2 => 2
Registered save handlers => files user memcached memcache

But even thought when running PHPUnit and trying to get Memcache / Memcached classes I receive a Class not found error.

The problem is that some tests rely on retrieving data from an API which is cached, so the tests fails without reason.

I installed both extensions correctly, made sure it's working on CLI.
When running phpunit it should work properly and the classes should be found.

Should I make any special setup for having these two extensions enabled on PHPUnit?


问:
Edit List in a NavigationStack
I want to edit my List, which is in a NavigationStack. The Items in the List are NavigationLinks.

I saw how to remove Items from a List, but not how, when the List is in a NavigationStack.

```<code>import SwiftUI

struct Title: Identifiable, Hashable {
    var id = UUID()
    let name:  String
}

struct NewsView: View {
    let newsTitle: [Title] = [
        .init(name: "Personelle Änderungen"),
        .init(name: "Neuigkeit 2"),
        .init(name: "Neuigkeit 3"),
        .init(name: "Neuigkeit 4")
    ]

    @State var path: [Title] = []

    var body: some View {
        NavigationStack(path: $path){
            List(newsTitle){ title in
                NavigationLink(title.name, value: title)
            }
            .navigationDestination(for: Title.self, destination: { title in
                Text(title.name)
                    .navigationTitle(title.name)
                    .navigationBarTitleDisplayMode(.inline)

            })
            .navigationTitle("News")
            .toolbar {
                Button {

                } label: {
                    Text("Bearbeiten")
                }

            }
        }
    }
}

struct NewsView_Previews: PreviewProvider {
    static var previews: some View {
        NewsView()
    }
}
</code>```

Title: Edit List in a NavigationStack

Body:
I want to edit my List, which is in a NavigationStack. The Items in the List are NavigationLinks.

I saw how to remove Items from a List, but not how, when the List is in a NavigationStack.

import SwiftUI

struct Title: Identifiable, Hashable {
    var id = UUID()
    let name:  String
}

struct NewsView: View {
    let newsTitle: [Title] = [
        .init(name: "Personelle Änderungen"),
        .init(name: "Neuigkeit 2"),
        .init(name: "Neuigkeit 3"),
        .init(name: "Neuigkeit 4")
    ]

    @State var path: [Title] = []

    var body: some View {
        NavigationStack(path: $path){
            List(newsTitle){ title in
                NavigationLink(title.name, value: title)
            }
            .navigationDestination(for: Title.self, destination: { title in
                Text(title.name)
                    .navigationTitle(title.name)
                    .navigationBarTitleDisplayMode(.inline)

            })
            .navigationTitle("News")
            .toolbar {
                Button {

                } label: {
                    Text("Bearbeiten")
                }

            }
        }
    }
}

struct NewsView_Previews: PreviewProvider {
    static var previews: some View {
        NewsView()
    }
}


问:
ignore "blank" (unfilled) row with jackson csv
I can't find a way to ignore "blank" lines in a CSV. I use quotes because I'm talking about lines that look like '','','','','' or ,,,,,, Here is a CSV (blank lines could be random):

```<code>id,name,age
1,alex,22
3,tiff,42
,,
,,
4,john,24
</code>```

What I expect is output list of POJO will contain only these data

```<code>1,alex,22
3,tiff,42
4,john,24
</code>```

Here is similar questions that I've been reading, but different to this in particular: JACKSON :: SKIP_EMPTY_LINES

Have tried out multiple approaches didn't find any csv mapper feature inbuilt. Am i missing something?

Body:
I can't find a way to ignore "blank" lines in a CSV. I use quotes because I'm talking about lines that look like '','','','','' or ,,,,,, Here is a CSV (blank lines could be random):

id,name,age
1,alex,22
3,tiff,42
,,
,,
4,john,24

What I expect is output list of POJO will contain only these data

1,alex,22
3,tiff,42
4,john,24

Here is similar questions that I've been reading, but different to this in particular: JACKSON :: SKIP_EMPTY_LINES

Have tried out multiple approaches didn't find any csv mapper feature inbuilt. Am i missing something?


问:
Docker compose rolling release without swarm/stack
What should I do to achieve sequential update of my containers without using swarm/stack?

I'm using docker-compose.yml file kinda this

```<code>---
services:
  myservice:
    image: myrepo/myimage:latest
    deploy:
      replicas: 5
      update_config:
        parallelism: 1
        delay: 10s
</code>```

I've started with docker compose up -d command and can see in docker ps 5 containers running from myimage:latest image.
Then I edit Dockerfile of myimage, build it with tag myrepo/myimage:latest and successfully push to my repo.
Аfter that I'm issuing docker compose pull && docker compose up -d hoping my containers will restart one-by-one with interval of 10 seconds according with this official page:
https://docs.docker.com/compose/compose-file/deploy/#update_config
But instead of this all 5 replicas restarting at the same time.

My config:

```<code>$ docker --version
Docker version 20.10.21, build baeda1f
$ docker compose version
Docker Compose version v2.14.0
$ cat /etc/*release | grep PRETTY
PRETTY_NAME="Ubuntu 20.04.5 LTS"
</code>```

Body:
What should I do to achieve sequential update of my containers without using swarm/stack?

I'm using docker-compose.yml file kinda this

---
services:
  myservice:
    image: myrepo/myimage:latest
    deploy:
      replicas: 5
      update_config:
        parallelism: 1
        delay: 10s

I've started with docker compose up -d command and can see in docker ps 5 containers running from myimage:latest image.
Then I edit Dockerfile of myimage, build it with tag myrepo/myimage:latest and successfully push to my repo.
Аfter that I'm issuing docker compose pull && docker compose up -d hoping my containers will restart one-by-one with interval of 10 seconds according with this official page:
https://docs.docker.com/compose/compose-file/deploy/#update_config
But instead of this all 5 replicas restarting at the same time.

My config:

$ docker --version
Docker version 20.10.21, build baeda1f
$ docker compose version
Docker Compose version v2.14.0
$ cat /etc/*release | grep PRETTY
PRETTY_NAME="Ubuntu 20.04.5 LTS"


问:
How to filter a table using multiple dropdowns in javascript?
I have a table populated using a php file from another site and I want to filter what displays based on 3 dropdown select inputs. The options within the dropdown inputs come from a php file on another site as well. I'm wondering how I can get the table to display only the values corresponding to the dropdown filters. I need to use Javascript and NOT Jquery. Here is the code: JSFiddle

All the other solutions on here are either in JQuery or just don't work for what I need.

Click the fiddle link above to see the whole program where I grab the info from external php to understand where the data came from, but here is where I make the table:

```<code>const visitsURL = 'https://www.randyconnolly.com/funwebdev/services/visits/visits.php?continent=EU&month=1&limit=100';
    const visitsList = document.querySelector('#visitsBody');
    fetch(visitsURL)
        .then( response => response.json() )
        .then( data => {
            data.forEach( v => {
                const row = document.createElement('tr');          //Creates row element
                const tdId = document.createElement('td');         //Makes td elements to store info
                const tdDate = document.createElement('td');
                const tdCountry = document.createElement('td');
                const tdBrowser = document.createElement('td');
                const tdOs = document.createElement('td');

                tdId.innerText = v.id;                            //Sets each td to respective info from php
                tdDate.innerText = v.visit_date;
                tdCountry.innerText = v.country;
                tdBrowser.innerText = v.browser;
                tdOs.innerText = v.operatingSystem;

                row.appendChild(tdId);                            //Adds each td to the row
                row.appendChild(tdDate);
                row.appendChild(tdCountry);
                row.appendChild(tdBrowser);
                row.appendChild(tdOs);
                visitsList.appendChild(row);                     //Adds row to table
            });
        })
        .catch( error => { console.error(error) } );
</code>```

Here is the HTML for the filters and table:

```<code><div class="filters mdl-shadow--2dp">
    Filter
    <select id="filterCountry">
        <option value="0">All Countries</option>
    </select>
    <select id="filterBrowser">
        <option value="0">All Browsers</option>
    </select>
    <select id="filterOS">
        <option value="0">All Operating System</option>
    </select>
</div>

<table class="mdl-data-table  ">
  <thead>
    <tr>
      <th >Id</th>
      <th class="mdl-data-table__cell--non-numeric">Date</th>
      <th class="mdl-data-table__cell--non-numeric">Country</th>
      <th class="mdl-data-table__cell--non-numeric">Browser</th>
      <th class="mdl-data-table__cell--non-numeric">OS</th>
    </tr>
  </thead>
  <tbody id="visitsBody">

  </tbody>
</table>
</code>```

Body:
I have a table populated using a php file from another site and I want to filter what displays based on 3 dropdown select inputs. The options within the dropdown inputs come from a php file on another site as well. I'm wondering how I can get the table to display only the values corresponding to the dropdown filters. I need to use Javascript and NOT Jquery. Here is the code: JSFiddle

All the other solutions on here are either in JQuery or just don't work for what I need.

Click the fiddle link above to see the whole program where I grab the info from external php to understand where the data came from, but here is where I make the table:

const visitsURL = 'https://www.randyconnolly.com/funwebdev/services/visits/visits.php?continent=EU&month=1&limit=100';
    const visitsList = document.querySelector('#visitsBody');
    fetch(visitsURL)
        .then( response => response.json() )
        .then( data => {
            data.forEach( v => {
                const row = document.createElement('tr');          //Creates row element
                const tdId = document.createElement('td');         //Makes td elements to store info
                const tdDate = document.createElement('td');
                const tdCountry = document.createElement('td');
                const tdBrowser = document.createElement('td');
                const tdOs = document.createElement('td');

                tdId.innerText = v.id;                            //Sets each td to respective info from php
                tdDate.innerText = v.visit_date;
                tdCountry.innerText = v.country;
                tdBrowser.innerText = v.browser;
                tdOs.innerText = v.operatingSystem;

                row.appendChild(tdId);                            //Adds each td to the row
                row.appendChild(tdDate);
                row.appendChild(tdCountry);
                row.appendChild(tdBrowser);
                row.appendChild(tdOs);
                visitsList.appendChild(row);                     //Adds row to table
            });
        })
        .catch( error => { console.error(error) } );

Here is the HTML for the filters and table:

    Filter
    <select id="filterCountry">
        <option value="0">All Countries</option>
    </select>
    <select id="filterBrowser">
        <option value="0">All Browsers</option>
    </select>
    <select id="filterOS">
        <option value="0">All Operating System</option>
    </select>

      Id
      Date
      Country
      Browser
      OS


问:
PY exe file is not working, what could be the problem?
i have a code that connects to my BLE device, get some info and then exports it in CSV.
It works fine (I get a csv updated with the data from ble device) with no errors but after i try to make an exe file out of it i get the following reply (in cmd).

Could someone help me please figure out what the issue is and how i can fix it?

```<code>c:\IDE\output\bleeeeeak>bleeeeeak.exe --debug=all
Traceback (most recent call last):
  File "bleeeeeak.py", line 48, in <module>
  File "asyncio\runners.py", line 190, in run
  File "asyncio\runners.py", line 118, in run
  File "asyncio\base_events.py", line 650, in run_until_complete
  File "bleeeeeak.py", line 39, in main
  File "bleak\__init__.py", line 433, in __aenter__
  File "bleak\__init__.py", line 471, in connect
  File "bleak\backends\winrt\client.py", line 244, in connect
bleak.exc.BleakDeviceNotFoundError: Device with address C4:BD:00:6B:11:25 was not found.
[12636] Failed to execute script 'bleeeeeak' due to unhandled exception!
</code>```

The device is on but the exe file doesn't see it :(.

The code is:

```<code>import pandas as pd
import asyncio
from bleak import BleakClient
import csv
from pathlib import Path
import logging
from csv import writer
import sys
import os

ADDRESS = "C4:BD:00:6B:11:25"
UUID = "00002a63-0000-1000-8000-00805f9b34fb"
from bleak import BleakClient
logger = logging.getLogger(__name__)
output_numbers1=pd.DataFrame(columns=['Column1'])
FILE_PATH=Path(r"C:\Users\maimo\Desktop\UnrealProjects\MyProject3\Saved\power.csv")

if not FILE_PATH.exists():
    with open(FILE_PATH, 'w', newline='') as f:
        pd.DataFrame(columns=['Column1']).to_csv(f)
        f.close()

def notification_handler(sender, data):
    """Simple notification handler which prints the data received."""
    global output_numbers1
    output_numbers = list(data)
    output_numbers_df=pd.DataFrame({'Column1':output_numbers[2]}, index=[0])
    output_numbers1=pd.concat([output_numbers1,output_numbers_df], ignore_index = True)

    with open(r"C:\Users\maimo\Desktop\UnrealProjects\MyProject3\Saved\power.csv", 'a', newline='') as f:
       output_numbers1.tail(1).to_csv(f, header=False)
       f.close()

async def main(address):
    async with BleakClient(address) as client:
        await client.start_notify(UUID, notification_handler)
        await asyncio.sleep(120.0)
        await client.stop_notify(UUID)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.run(main(ADDRESS))

</code>```

Body:
i have a code that connects to my BLE device, get some info and then exports it in CSV.
It works fine (I get a csv updated with the data from ble device) with no errors but after i try to make an exe file out of it i get the following reply (in cmd).

Could someone help me please figure out what the issue is and how i can fix it?

c:\IDE\output\bleeeeeak>bleeeeeak.exe --debug=all
Traceback (most recent call last):
  File "bleeeeeak.py", line 48, in <module>
  File "asyncio\runners.py", line 190, in run
  File "asyncio\runners.py", line 118, in run
  File "asyncio\base_events.py", line 650, in run_until_complete
  File "bleeeeeak.py", line 39, in main
  File "bleak\__init__.py", line 433, in __aenter__
  File "bleak\__init__.py", line 471, in connect
  File "bleak\backends\winrt\client.py", line 244, in connect
bleak.exc.BleakDeviceNotFoundError: Device with address C4:BD:00:6B:11:25 was not found.
[12636] Failed to execute script 'bleeeeeak' due to unhandled exception!

The device is on but the exe file doesn't see it :(.

The code is:

import pandas as pd
import asyncio
from bleak import BleakClient
import csv
from pathlib import Path
import logging
from csv import writer
import sys
import os

ADDRESS = "C4:BD:00:6B:11:25"
UUID = "00002a63-0000-1000-8000-00805f9b34fb"
from bleak import BleakClient
logger = logging.getLogger(__name__)
output_numbers1=pd.DataFrame(columns=['Column1'])
FILE_PATH=Path(r"C:\Users\maimo\Desktop\UnrealProjects\MyProject3\Saved\power.csv")

if not FILE_PATH.exists():
    with open(FILE_PATH, 'w', newline='') as f:
        pd.DataFrame(columns=['Column1']).to_csv(f)
        f.close()

def notification_handler(sender, data):
    """Simple notification handler which prints the data received."""
    global output_numbers1
    output_numbers = list(data)
    output_numbers_df=pd.DataFrame({'Column1':output_numbers[2]}, index=[0])
    output_numbers1=pd.concat([output_numbers1,output_numbers_df], ignore_index = True)

    with open(r"C:\Users\maimo\Desktop\UnrealProjects\MyProject3\Saved\power.csv", 'a', newline='') as f:
       output_numbers1.tail(1).to_csv(f, header=False)
       f.close()

async def main(address):
    async with BleakClient(address) as client:
        await client.start_notify(UUID, notification_handler)
        await asyncio.sleep(120.0)
        await client.stop_notify(UUID)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.run(main(ADDRESS))


问:
Queues & exchanges declared using code not reflected in rabbitmq management portal
I am using .NET client for RabbitMQ. Exchange, Queues & messages published to an declared exchange are not showing in RabbitMQ management portal. Rabbitmqctl command is also not returning declared exchanges, queues. I have referred sample code from RabbitMQ official documentation. What am i missing ? Using docker to run RammitMQ.

docker run -d --hostname rabbitmq --name rabbitmq -p 15672:15672 -p 5672:5672 rabbitmq:3.11-management.

RabbitMQ management plugin is also enabled

Exchange, Queues & messages published to an declared exchange are not showing in RabbitMQ management portal. Rabbitmqctl command is also not returning declared exchanges, queues. I have referred sample code from RabbitMQ official documentation. What am i missing ?

Expecting: Declared exchange, queues to be listed in management portal as well.


问:
Is there a way to optimise the time taken for uploading multipart data in a django + react app?
I have an app that has a django rest framework backend and a react frontend. As usual the user has an option to edit the details he has initially submitted. The details also contain a profile picture of the user. The update view works fine, but what I have noticed in the network tab is, if the user tries to update his profile it takes upt 5-8s and sometimes 27s for the react frontend to receive a response from backend.

Question

Is there any way to reduce this time or any performance optimisation method?

I am also posting my code incase I am doing something wrong.

react part

```<code>export const editTeacherDetail = async (detailsData, photo) => {
  console.log("detailsData before in main api = ", detailsData);
  console.log("photo before in main api = ", photo);

  let formData = new FormData();
  formData.append("name", detailsData.name.toUpperCase());
  formData.append("state", detailsData.state);
  formData.append("adhaar_number", detailsData.adhaar_number);
  formData.append("current_profession", detailsData.current_profession);
  formData.append("phone", detailsData.phone);
  formData.append("location", detailsData.location.toUpperCase());
  formData.append("full_address", detailsData.full_address.toUpperCase());
  formData.append("date_of_birth", detailsData.date_of_birth);
  formData.append("gender", detailsData.gender.toUpperCase());
  formData.append("name_of_school", detailsData.name_of_school.toUpperCase());
  formData.append("experience", detailsData.experience);
  formData.append("teach_for_no_days", detailsData.teach_for_no_days);
  formData.append("subject", detailsData.subject.toUpperCase());
  formData.append("teach_class", detailsData.teach_class);
  formData.append("home_tuition", detailsData.home_tuition);
  formData.append("fees", detailsData.fees);
  formData.append("home_tuition_fees", detailsData.home_tuition_fees);
  formData.append("shift", detailsData.shift.toUpperCase());
  formData.append("board", detailsData.board.toUpperCase());

  if (typeof photo !== "string") {
    formData.append("profile_photo", photo);
  }

  try {
    console.log("formData = ", formData);

    let response = await axiosInstance.put(`/teacher/edit-detail/`, formData);
    console.log(response);
    return response;
  } catch (error) {
    if (error.response) {
      ToastNotification(
        "We are facing some problems. Please try again later",
        "error"
      );
      return error.response;
    } else if (error.request) {
      console.error(error.request);
      return error.request;
    } else {
      console.error(error);
    }
  }
};

</code>```

django part

```<code>@api_view(['PUT'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def edit_teacher_detail(request):

   data = request.data

   if data is not None:

     queryset = TeacherDetail.objects.get(user = request.user)

     serializer = TeacherDetailUpdateSerializer(instance=queryset, data = data)

     try:
       if serializer.is_valid():
         serializer.save()
         return Response({'message':"details edited"} ,status=status.HTTP_200_OK)
       else:
         print(serializer._errors)
         return Response({'message': serializer._errors}, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
       print(e)
       return Response({"message": str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

   else:
      return Response({'message':'no query recieved'}, status=status.HTTP_400_BAD_REQUEST)
</code>```

profile model

```<code>def profile_upload_to(instance,filename):
    id = instance.id
    user = instance.user.id
    return f'teacher-profile-picture/{filename}'.format(filename=filename)

class TeacherDetail(models.Model):

    STATE_CHOICES = (
        ("AN", "Andaman and Nicobar"),
        ("AP", "Andhra Pradesh"),
        ...
    )

    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)

    is_verified = models.BooleanField(default=False)

    user = models.OneToOneField(CustomUser, on_delete=models.SET_NULL, null=True, blank=True)

    name= models.CharField(max_length=100, null=True, blank=True)

    email = models.EmailField(null=True, blank=True)

    profile_photo = models.ImageField(upload_to = profile_upload_to, null=True, blank=True)

    adhaar_number = models.CharField(max_length=200, null=True, blank=True)

    phone = models.CharField(max_length=10, null=True, blank=True)

    current_profession = models.CharField(max_length= 20, null=True, blank=True)

    location = models.CharField(max_length=100, null=True, blank=True)

    state = models.CharField(max_length=200, choices=STATE_CHOICES, null=True, blank=True)

    full_address = models.CharField(max_length=500, null=True, blank=True)

    date_of_birth = models.DateField( null=True, blank=True)

    name_of_school = models.CharField(max_length=200, null=True, blank=True)

    experience = models.IntegerField( null=True, blank=True)

    teach_for_no_days = models.IntegerField( null=True, blank=True)

    shift = models.CharField(max_length=20 ,null=True, blank=True)

    subject = models.CharField(max_length=300, null=True, blank=True)

    teach_class = models.CharField(max_length=100 ,null=True, blank=True)

    board = models.CharField(max_length=25,null=True, blank=True)

    gender = models.CharField(max_length=8 ,null=True, blank=True)

    fees = models.IntegerField(null=True, blank=True, default=0)

    fac = models.IntegerField(null=True, blank=True, default=0)

    home_tuition = models.BooleanField(default=False)

    home_tuition_fees = models.IntegerField(null=True, blank=True, default=0)

    hfac = models.IntegerField(null=True, blank=True, default=0)

    home_tuition_students = models.ManyToManyField(CustomUser, blank=True, related_name='home_tuition_students')

    general_tuition_students = models.ManyToManyField(CustomUser, blank=True, related_name='general_tuition_students')

    date_created = models.DateTimeField(auto_now_add=True, editable= False)
</code>```

serialiser used in the update view

```<code>class GetTeacherInfoEditSerializer(serializers.ModelSerializer):
  class Meta:
    model = TeacherDetail
    exclude = ['id','date_created','user','home_tuition_students','general_tuition_students']
</code>```

Body:
I have an app that has a django rest framework backend and a react frontend. As usual the user has an option to edit the details he has initially submitted. The details also contain a profile picture of the user. The update view works fine, but what I have noticed in the network tab is, if the user tries to update his profile it takes upt 5-8s and sometimes 27s for the react frontend to receive a response from backend.

Question

Is there any way to reduce this time or any performance optimisation method?

I am also posting my code incase I am doing something wrong.

react part

export const editTeacherDetail = async (detailsData, photo) => {
  console.log("detailsData before in main api = ", detailsData);
  console.log("photo before in main api = ", photo);

  let formData = new FormData();
  formData.append("name", detailsData.name.toUpperCase());
  formData.append("state", detailsData.state);
  formData.append("adhaar_number", detailsData.adhaar_number);
  formData.append("current_profession", detailsData.current_profession);
  formData.append("phone", detailsData.phone);
  formData.append("location", detailsData.location.toUpperCase());
  formData.append("full_address", detailsData.full_address.toUpperCase());
  formData.append("date_of_birth", detailsData.date_of_birth);
  formData.append("gender", detailsData.gender.toUpperCase());
  formData.append("name_of_school", detailsData.name_of_school.toUpperCase());
  formData.append("experience", detailsData.experience);
  formData.append("teach_for_no_days", detailsData.teach_for_no_days);
  formData.append("subject", detailsData.subject.toUpperCase());
  formData.append("teach_class", detailsData.teach_class);
  formData.append("home_tuition", detailsData.home_tuition);
  formData.append("fees", detailsData.fees);
  formData.append("home_tuition_fees", detailsData.home_tuition_fees);
  formData.append("shift", detailsData.shift.toUpperCase());
  formData.append("board", detailsData.board.toUpperCase());

  if (typeof photo !== "string") {
    formData.append("profile_photo", photo);
  }

  try {
    console.log("formData = ", formData);

    let response = await axiosInstance.put(`/teacher/edit-detail/`, formData);
    console.log(response);
    return response;
  } catch (error) {
    if (error.response) {
      ToastNotification(
        "We are facing some problems. Please try again later",
        "error"
      );
      return error.response;
    } else if (error.request) {
      console.error(error.request);
      return error.request;
    } else {
      console.error(error);
    }
  }
};

django part

@api_view(['PUT'])
@permission_classes([IsAuthenticated])
@parser_classes([MultiPartParser, FormParser])
def edit_teacher_detail(request):

   data = request.data

   if data is not None:

     queryset = TeacherDetail.objects.get(user = request.user)

     serializer = TeacherDetailUpdateSerializer(instance=queryset, data = data)

     try:
       if serializer.is_valid():
         serializer.save()
         return Response({'message':"details edited"} ,status=status.HTTP_200_OK)
       else:
         print(serializer._errors)
         return Response({'message': serializer._errors}, status=status.HTTP_400_BAD_REQUEST)
     except Exception as e:
       print(e)
       return Response({"message": str(e)},status=status.HTTP_500_INTERNAL_SERVER_ERROR)

   else:
      return Response({'message':'no query recieved'}, status=status.HTTP_400_BAD_REQUEST)

profile model

def profile_upload_to(instance,filename):
    id = instance.id
    user = instance.user.id
    return f'teacher-profile-picture/{filename}'.format(filename=filename)

class TeacherDetail(models.Model):

    STATE_CHOICES = (
        ("AN", "Andaman and Nicobar"),
        ("AP", "Andhra Pradesh"),
        ...
    )

    id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)

    is_verified = models.BooleanField(default=False)

    user = models.OneToOneField(CustomUser, on_delete=models.SET_NULL, null=True, blank=True)

    name= models.CharField(max_length=100, null=True, blank=True)

    email = models.EmailField(null=True, blank=True)

    profile_photo = models.ImageField(upload_to = profile_upload_to, null=True, blank=True)

    adhaar_number = models.CharField(max_length=200, null=True, blank=True)

    phone = models.CharField(max_length=10, null=True, blank=True)

    current_profession = models.CharField(max_length= 20, null=True, blank=True)

    location = models.CharField(max_length=100, null=True, blank=True)

    state = models.CharField(max_length=200, choices=STATE_CHOICES, null=True, blank=True)

    full_address = models.CharField(max_length=500, null=True, blank=True)

    date_of_birth = models.DateField( null=True, blank=True)

    name_of_school = models.CharField(max_length=200, null=True, blank=True)

    experience = models.IntegerField( null=True, blank=True)

    teach_for_no_days = models.IntegerField( null=True, blank=True)

    shift = models.CharField(max_length=20 ,null=True, blank=True)

    subject = models.CharField(max_length=300, null=True, blank=True)

    teach_class = models.CharField(max_length=100 ,null=True, blank=True)

    board = models.CharField(max_length=25,null=True, blank=True)

    gender = models.CharField(max_length=8 ,null=True, blank=True)

    fees = models.IntegerField(null=True, blank=True, default=0)

    fac = models.IntegerField(null=True, blank=True, default=0)

    home_tuition = models.BooleanField(default=False)

    home_tuition_fees = models.IntegerField(null=True, blank=True, default=0)

    hfac = models.IntegerField(null=True, blank=True, default=0)

    home_tuition_students = models.ManyToManyField(CustomUser, blank=True, related_name='home_tuition_students')

    general_tuition_students = models.ManyToManyField(CustomUser, blank=True, related_name='general_tuition_students')

    date_created = models.DateTimeField(auto_now_add=True, editable= False)

serialiser used in the update view

class GetTeacherInfoEditSerializer(serializers.ModelSerializer):
  class Meta:
    model = TeacherDetail
    exclude = ['id','date_created','user','home_tuition_students','general_tuition_students']


问:
Any idea What is this? - marked words with 2 colors
Use Arch Linux,

I don't know what is due,

Any idea where to look for.

Visual Code assigns double color to the same word

I'm still looking within the configurations that create this problem


问:
When will Custom Resource Providers get out of public preview
Since 2019 Custom Resource Providers are still in public preview, this prevents partners and organizations to put bigger investments in creating additional services on the platform as the service capability might be removed, changed or never be supported.

Is there any outlook by when the service might be released/published? If not at least some sort of roadmap, what is missing to get it there?

I've checked the documentation and GitHub Issues, but there is not much movement on the CustomServiceProvider portion of Azure.