问:
Is there any way to solve a ODEs system in Unity the way I need?
I want to "grow" a PreFab in unity using some parameters that are the numerical solution of a ODEs system.
I have two scripts: one that literally grows the prefab and another one that solves an ODE using 4th order Runge-Kutta numerical method.

The code for ODE solution is this one:

```<code>    using System;
    namespace RungeKutta4
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Incrementers to pass into the known solution
                double t = 0.0;
                double T = 1.0;
                double dt = 0.1;

                // Assign the number of elements needed for the arrays
                int n = (int)(((T - t) / dt)) + 1;

                // Initialize the arrays for the time index 's' and estimates 'annualGrowth' at each index 'i'
                double[] annualGrowth = new double[n]; //y
                double[] s = new double[n]; //t

                // RK4 Variables
                double dy1;
                double dy2;
                double dy3;
                double dy4;

                // RK4 Initializations condizioni iniziali
                int i = 0;
                s[i] = 0.0; //t0 = 0
                annualGrowth[i] = 1.0; //y(t0) = y(0) = 1

                // Iterate and implement the Rk4 Algorithm
                while (i < annualGrowth.Length - 1)
                {

                    dy1 = dt * equation(s[i], annualGrowth[i]);
                    dy2 = dt * equation(s[i] + dt / 2, annualGrowth[i] + dy1 / 2);
                    dy3 = dt * equation(s[i] + dt / 2, annualGrowth[i] + dy2 / 2);
                    dy4 = dt * equation(s[i] + dt, annualGrowth[i] + dy3);

                    s[i + 1] = s[i] + dt;
                    annualGrowth[i + 1] = annualGrowth[i] + (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6;

                    double t_rounded = Math.Round(t + dt, 2);

                    if (t_rounded % 1 == 0)
                    {
                       Console.WriteLine(" y(" + t_rounded + ")" + " " .PadRight(10) + annualGrowth[i + 1]);
                    }

                    i++;
                    t += dt; //t = t + dt

                };//End Rk4
                Console.ReadLine();
            }

            // Differential Equation
            public static double equation(double t, double annualGrowth)
            {
                double y_prime;
                double k = 0.1;
                double maxHeight = 5.0;
                return y_prime = k * annualGrowth * (1-(annualGrowth/maxHeight));
            }
        }
    }
</code>```

Then I have the "growing" script in unity:

```<code>    public class Growth : MonoBehaviour
{
    SetupScene setup;
    TimeManager timeManager;
    float currentLenght;
    float currentWidth;
    Genetic geneticInfo;
    bool isMaxLenght;
    bool isMaxWeigth;
    GameObject newInternode;
    float annualLengthGrowth = 0.05f;
    float annualWidthGrowth = 0.01f;
    Vector3 annualGrowth;
    bool hasChild;

    // Start is called before the first frame update
    void Awake()
    {
        annualGrowth = new Vector3(annualWidthGrowth, annualLengthGrowth, annualWidthGrowth);
        setup = GameObject.Find("Setup").GetComponent<SetupScene>();
        timeManager = GameObject.Find("Time Manager").GetComponent<TimeManager>();
        currentLenght = 0f;
        currentWidth = 0f;
        geneticInfo = new Genetic(1);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("ciao, sono nato " + gameObject.name);
        Debug.Log(timeManager.IsYearElapsed + " " + gameObject.name);
        if (timeManager.IsYearElapsed)
        {

            float scaleFactorXZ = 1f;
            float scaleFactorY = 1f;
            if (gameObject.name != "Seed")
            {
                scaleFactorXZ = geneticInfo.InternodeMaxWidtht;
                scaleFactorY = geneticInfo.InternodeMaxLenght;
            }
            currentLenght = (gameObject.transform.lossyScale.y + annualGrowth.y);
            currentWidth = (gameObject.transform.lossyScale.x + annualGrowth.x);

            if(currentWidth > geneticInfo.InternodeMaxWidtht)
            {
                currentWidth = geneticInfo.InternodeMaxWidtht;
                isMaxWeigth = true;
            }

            if(currentLenght > geneticInfo.InternodeMaxLenght)
            {
                currentLenght = geneticInfo.InternodeMaxLenght;
                isMaxLenght = true;
            }

            gameObject.transform.localScale = new Vector3(currentWidth/scaleFactorXZ, currentLenght/scaleFactorY, currentWidth/scaleFactorXZ);

            if (isMaxLenght)
            {

                if (!hasChild && setup.Manager.InternodeNumber < geneticInfo.MaxInternodeNumber)
                {
                    setup.Manager.InternodeNumber++;
                    Debug.Log("nuovo internodo creato");
                    setup.LastInternodePosition = gameObject.transform.position + new Vector3(0f, geneticInfo.InternodeMaxLenght, 0f);
                    newInternode = Instantiate(setup.Prefab, new Vector3(setup.LastInternodePosition.x, setup.LastInternodePosition.y, setup.LastInternodePosition.z), Quaternion.identity);
                    newInternode.transform.localScale = Vector3.zero;
                    newInternode.transform.parent = setup.LastInternode.transform;
                    setup.LastInternode = newInternode;

                    newInternode.AddComponent<Growth>();
                    hasChild = true;
                }

                if (isMaxWeigth)
                {
                    gameObject.GetComponent<Growth>().enabled = false;
                }

            }
        }
    }
}
</code>```

I want to link the numerical solution of ODE script to the value float annualLengthGrowth = 0.05f;in the unity script that is, for now, hardcoded. The problem is that at each update (or timestep) the initial value of ODE system must be the final numerical calculated value of the previous step.

For example, given that at first timestep, the initial value of annualGrowth in ODE script is 1.0, the final calculated value is (for example)  annualGrowthT1 = 2.35f, I have to use this value in Unity script at first time step as annualLengthGrowth. At next time step, the initial value for ODE script should be annualGrowthT1 = 2.35f, then the calculated final value should be (for example) annualGrowthT2 = 3.56f and this value must be used in the second time step in unity script as new  annualLengthGrowth. And so on.

It should be clear thank to this picture:

答:
I tried to put all together but the unity console gives me the error:

error CS0161: 'Growth.Runge.runge(float, float, float, float, Growth.Runge.Function)': not all code paths return a value.

I thin I missed a return somewhere in the code but I don't know where.
Here it is my new code:

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Growth : MonoBehaviour
{
    SetupScene setup; //mi serve per prendere il prefab
    TimeManager timeManager;
    float currentLenght;
    float currentWidth;
    Genetic geneticInfo;
    bool isMaxLenght;  //internodo ha raggiunto la lunghezza massima
    bool isMaxWeigth;
    GameObject newInternode;
    float annualLengthGrowth = Runge.runge(0.0f, 1.0f, 1.0f, .1f, new Runge.Function(Equation.equation)); //0.05f; // per ora lo fissiamo da codice, successivamente verra' calcolato
    float annualWidthGrowth = 0.01f;
    Vector3 annualGrowth;
    bool hasChild;

    // Start is called before the first frame update
    void Awake()
    {
        annualGrowth = new Vector3(annualWidthGrowth, annualLengthGrowth, annualWidthGrowth);
        setup = GameObject.Find("Setup").GetComponent<SetupScene>();
        timeManager = GameObject.Find("Time Manager").GetComponent<TimeManager>();
        currentLenght = 0f;
        currentWidth = 0f;
        geneticInfo = new Genetic(1);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("ciao, sono nato " + gameObject.name);
        Debug.Log(timeManager.IsYearElapsed + " " + gameObject.name);
        if (timeManager.IsYearElapsed)
        {

            //calcolo lunghezza e larghezza corrente
            float scaleFactorXZ = 1f;
            float scaleFactorY = 1f;
            if (gameObject.name != "Seed")
            {
                scaleFactorXZ = geneticInfo.InternodeMaxWidtht;
                scaleFactorY = geneticInfo.InternodeMaxLenght;
            }
            currentLenght = (gameObject.transform.lossyScale.y + annualGrowth.y);
            Debug.Log("Lunghezza corrente internodo = " + currentLenght);
            currentWidth = (gameObject.transform.lossyScale.x + annualGrowth.x);

            if(currentWidth > geneticInfo.InternodeMaxWidtht)
            {
                currentWidth = geneticInfo.InternodeMaxWidtht;
                isMaxWeigth = true;
            }

            if(currentLenght > geneticInfo.InternodeMaxLenght)
            {
                currentLenght = geneticInfo.InternodeMaxLenght;
                isMaxLenght = true;
            }

            gameObject.transform.localScale = new Vector3(currentWidth/scaleFactorXZ, currentLenght/scaleFactorY, currentWidth/scaleFactorXZ);

            if (isMaxLenght)
            {
                //crea nuovo internodo come figlio di quello corrente
                if (!hasChild && setup.Manager.InternodeNumber < geneticInfo.MaxInternodeNumber)
                {
                    setup.Manager.InternodeNumber++;
                    Debug.Log("nuovo internodo creato");
                    setup.LastInternodePosition = gameObject.transform.position + new Vector3(0f, geneticInfo.InternodeMaxLenght, 0f);
                    newInternode = Instantiate(setup.Prefab, new Vector3(setup.LastInternodePosition.x, setup.LastInternodePosition.y, setup.LastInternodePosition.z), Quaternion.identity);
                    newInternode.transform.localScale = Vector3.zero;
                    newInternode.transform.parent = setup.LastInternode.transform;
                    setup.LastInternode = newInternode;
                    //creare nuova classe gestore Gerarchia
                    newInternode.AddComponent<Growth>();
                    hasChild = true;
                }

                if (isMaxWeigth)
                {
                    gameObject.GetComponent<Growth>().enabled = false;
                }

            }
        }
    }

    public class Runge
    {
        //declare a delegate that takes a double and returns
        public delegate float Function(float t, float annualGrowth);

        public static float runge(float a, float b, float value, float step, Function f)
        {
            float t, w, k1, k2, k3, k4;
            t = a;
            w = value;
            for (int i = 0; i < (b - a) / step; i++)
            {
                k1 = step * f(t, w);
                k2 = step * f(t + step / 2f, w + k1 / 2f);
                k3 = step * f(t + step / 2f, w + k2 / 2f);
                k4 = step * f(t + step, w + k3);
                w = w + (k1 + 2f * k2 + 2f * k3 + k4) / 6f;
                t = a + i * step;
                //Console.WriteLine("{0} {1} ", Math.Round(t, 1), w);
            }

        }
    }

    class Equation
    {
        public static float equation(float t, float annualGrowth)
        {
            float y_prime;
            float k = 0.1f; //fattore di crescita, deve essere non hardcodato
            float maxHeight = 5.0f; //altezza max, deve essere non hardcodato
            return y_prime = k * annualGrowth * (1 - (annualGrowth / maxHeight));
        }

    }
}
</code>```

Body:
I want to "grow" a PreFab in unity using some parameters that are the numerical solution of a ODEs system.
I have two scripts: one that literally grows the prefab and another one that solves an ODE using 4th order Runge-Kutta numerical method.

The code for ODE solution is this one:

    using System;
    namespace RungeKutta4
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Incrementers to pass into the known solution
                double t = 0.0;
                double T = 1.0;
                double dt = 0.1;

                // Assign the number of elements needed for the arrays
                int n = (int)(((T - t) / dt)) + 1;

                // Initialize the arrays for the time index 's' and estimates 'annualGrowth' at each index 'i'
                double[] annualGrowth = new double[n]; //y
                double[] s = new double[n]; //t

                // RK4 Variables
                double dy1;
                double dy2;
                double dy3;
                double dy4;

                // RK4 Initializations condizioni iniziali
                int i = 0;
                s[i] = 0.0; //t0 = 0
                annualGrowth[i] = 1.0; //y(t0) = y(0) = 1

                // Iterate and implement the Rk4 Algorithm
                while (i < annualGrowth.Length - 1)
                {

                    dy1 = dt * equation(s[i], annualGrowth[i]);
                    dy2 = dt * equation(s[i] + dt / 2, annualGrowth[i] + dy1 / 2);
                    dy3 = dt * equation(s[i] + dt / 2, annualGrowth[i] + dy2 / 2);
                    dy4 = dt * equation(s[i] + dt, annualGrowth[i] + dy3);

                    s[i + 1] = s[i] + dt;
                    annualGrowth[i + 1] = annualGrowth[i] + (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6;

                    double t_rounded = Math.Round(t + dt, 2);

                    if (t_rounded % 1 == 0)
                    {
                       Console.WriteLine(" y(" + t_rounded + ")" + " " .PadRight(10) + annualGrowth[i + 1]);
                    }

                    i++;
                    t += dt; //t = t + dt

                };//End Rk4
                Console.ReadLine();
            }

            // Differential Equation
            public static double equation(double t, double annualGrowth)
            {
                double y_prime;
                double k = 0.1;
                double maxHeight = 5.0;
                return y_prime = k * annualGrowth * (1-(annualGrowth/maxHeight));
            }
        }
    }

Then I have the "growing" script in unity:

    public class Growth : MonoBehaviour
{
    SetupScene setup;
    TimeManager timeManager;
    float currentLenght;
    float currentWidth;
    Genetic geneticInfo;
    bool isMaxLenght;
    bool isMaxWeigth;
    GameObject newInternode;
    float annualLengthGrowth = 0.05f;
    float annualWidthGrowth = 0.01f;
    Vector3 annualGrowth;
    bool hasChild;

    // Start is called before the first frame update
    void Awake()
    {
        annualGrowth = new Vector3(annualWidthGrowth, annualLengthGrowth, annualWidthGrowth);
        setup = GameObject.Find("Setup").GetComponent<SetupScene>();
        timeManager = GameObject.Find("Time Manager").GetComponent<TimeManager>();
        currentLenght = 0f;
        currentWidth = 0f;
        geneticInfo = new Genetic(1);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("ciao, sono nato " + gameObject.name);
        Debug.Log(timeManager.IsYearElapsed + " " + gameObject.name);
        if (timeManager.IsYearElapsed)
        {

            float scaleFactorXZ = 1f;
            float scaleFactorY = 1f;
            if (gameObject.name != "Seed")
            {
                scaleFactorXZ = geneticInfo.InternodeMaxWidtht;
                scaleFactorY = geneticInfo.InternodeMaxLenght;
            }
            currentLenght = (gameObject.transform.lossyScale.y + annualGrowth.y);
            currentWidth = (gameObject.transform.lossyScale.x + annualGrowth.x);

            if(currentWidth > geneticInfo.InternodeMaxWidtht)
            {
                currentWidth = geneticInfo.InternodeMaxWidtht;
                isMaxWeigth = true;
            }

            if(currentLenght > geneticInfo.InternodeMaxLenght)
            {
                currentLenght = geneticInfo.InternodeMaxLenght;
                isMaxLenght = true;
            }

            gameObject.transform.localScale = new Vector3(currentWidth/scaleFactorXZ, currentLenght/scaleFactorY, currentWidth/scaleFactorXZ);

            if (isMaxLenght)
            {

                if (!hasChild && setup.Manager.InternodeNumber < geneticInfo.MaxInternodeNumber)
                {
                    setup.Manager.InternodeNumber++;
                    Debug.Log("nuovo internodo creato");
                    setup.LastInternodePosition = gameObject.transform.position + new Vector3(0f, geneticInfo.InternodeMaxLenght, 0f);
                    newInternode = Instantiate(setup.Prefab, new Vector3(setup.LastInternodePosition.x, setup.LastInternodePosition.y, setup.LastInternodePosition.z), Quaternion.identity);
                    newInternode.transform.localScale = Vector3.zero;
                    newInternode.transform.parent = setup.LastInternode.transform;
                    setup.LastInternode = newInternode;

                    newInternode.AddComponent<Growth>();
                    hasChild = true;
                }

                if (isMaxWeigth)
                {
                    gameObject.GetComponent<Growth>().enabled = false;
                }

            }
        }
    }
}

I want to link the numerical solution of ODE script to the value float annualLengthGrowth = 0.05f;in the unity script that is, for now, hardcoded. The problem is that at each update (or timestep) the initial value of ODE system must be the final numerical calculated value of the previous step.

For example, given that at first timestep, the initial value of annualGrowth in ODE script is 1.0, the final calculated value is (for example)  annualGrowthT1 = 2.35f, I have to use this value in Unity script at first time step as annualLengthGrowth. At next time step, the initial value for ODE script should be annualGrowthT1 = 2.35f, then the calculated final value should be (for example) annualGrowthT2 = 3.56f and this value must be used in the second time step in unity script as new  annualLengthGrowth. And so on.

It should be clear thank to this picture:

Body:
I tried to put all together but the unity console gives me the error:

error CS0161: 'Growth.Runge.runge(float, float, float, float, Growth.Runge.Function)': not all code paths return a value.

I thin I missed a return somewhere in the code but I don't know where.
Here it is my new code:

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Growth : MonoBehaviour
{
    SetupScene setup; //mi serve per prendere il prefab
    TimeManager timeManager;
    float currentLenght;
    float currentWidth;
    Genetic geneticInfo;
    bool isMaxLenght;  //internodo ha raggiunto la lunghezza massima
    bool isMaxWeigth;
    GameObject newInternode;
    float annualLengthGrowth = Runge.runge(0.0f, 1.0f, 1.0f, .1f, new Runge.Function(Equation.equation)); //0.05f; // per ora lo fissiamo da codice, successivamente verra' calcolato
    float annualWidthGrowth = 0.01f;
    Vector3 annualGrowth;
    bool hasChild;

    // Start is called before the first frame update
    void Awake()
    {
        annualGrowth = new Vector3(annualWidthGrowth, annualLengthGrowth, annualWidthGrowth);
        setup = GameObject.Find("Setup").GetComponent<SetupScene>();
        timeManager = GameObject.Find("Time Manager").GetComponent<TimeManager>();
        currentLenght = 0f;
        currentWidth = 0f;
        geneticInfo = new Genetic(1);
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("ciao, sono nato " + gameObject.name);
        Debug.Log(timeManager.IsYearElapsed + " " + gameObject.name);
        if (timeManager.IsYearElapsed)
        {

            //calcolo lunghezza e larghezza corrente
            float scaleFactorXZ = 1f;
            float scaleFactorY = 1f;
            if (gameObject.name != "Seed")
            {
                scaleFactorXZ = geneticInfo.InternodeMaxWidtht;
                scaleFactorY = geneticInfo.InternodeMaxLenght;
            }
            currentLenght = (gameObject.transform.lossyScale.y + annualGrowth.y);
            Debug.Log("Lunghezza corrente internodo = " + currentLenght);
            currentWidth = (gameObject.transform.lossyScale.x + annualGrowth.x);

            if(currentWidth > geneticInfo.InternodeMaxWidtht)
            {
                currentWidth = geneticInfo.InternodeMaxWidtht;
                isMaxWeigth = true;
            }

            if(currentLenght > geneticInfo.InternodeMaxLenght)
            {
                currentLenght = geneticInfo.InternodeMaxLenght;
                isMaxLenght = true;
            }

            gameObject.transform.localScale = new Vector3(currentWidth/scaleFactorXZ, currentLenght/scaleFactorY, currentWidth/scaleFactorXZ);

            if (isMaxLenght)
            {
                //crea nuovo internodo come figlio di quello corrente
                if (!hasChild && setup.Manager.InternodeNumber < geneticInfo.MaxInternodeNumber)
                {
                    setup.Manager.InternodeNumber++;
                    Debug.Log("nuovo internodo creato");
                    setup.LastInternodePosition = gameObject.transform.position + new Vector3(0f, geneticInfo.InternodeMaxLenght, 0f);
                    newInternode = Instantiate(setup.Prefab, new Vector3(setup.LastInternodePosition.x, setup.LastInternodePosition.y, setup.LastInternodePosition.z), Quaternion.identity);
                    newInternode.transform.localScale = Vector3.zero;
                    newInternode.transform.parent = setup.LastInternode.transform;
                    setup.LastInternode = newInternode;
                    //creare nuova classe gestore Gerarchia
                    newInternode.AddComponent<Growth>();
                    hasChild = true;
                }

                if (isMaxWeigth)
                {
                    gameObject.GetComponent<Growth>().enabled = false;
                }

            }
        }
    }

    public class Runge
    {
        //declare a delegate that takes a double and returns
        public delegate float Function(float t, float annualGrowth);

        public static float runge(float a, float b, float value, float step, Function f)
        {
            float t, w, k1, k2, k3, k4;
            t = a;
            w = value;
            for (int i = 0; i < (b - a) / step; i++)
            {
                k1 = step * f(t, w);
                k2 = step * f(t + step / 2f, w + k1 / 2f);
                k3 = step * f(t + step / 2f, w + k2 / 2f);
                k4 = step * f(t + step, w + k3);
                w = w + (k1 + 2f * k2 + 2f * k3 + k4) / 6f;
                t = a + i * step;
                //Console.WriteLine("{0} {1} ", Math.Round(t, 1), w);
            }

        }
    }

    class Equation
    {
        public static float equation(float t, float annualGrowth)
        {
            float y_prime;
            float k = 0.1f; //fattore di crescita, deve essere non hardcodato
            float maxHeight = 5.0f; //altezza max, deve essere non hardcodato
            return y_prime = k * annualGrowth * (1 - (annualGrowth / maxHeight));
        }

    }
}


来源: stackexchange

问:
Why i am getting "NotImplementedError()" when building a custom optimizer in Tensorflow
I am working on image classification and i am trying to implement a custom optimizer(based on a paper published on ELSEVIER) in Tensorflow,

I tried to modify the code as below: I have some other functions but it is all related with preprocessing and model architecture etc. My optimizer code follows;

```<code>import os
os.environ['TF_KERAS'] = '1'
from tensorflow import keras
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import cv2
import imutils
import matplotlib.pyplot as plt
from os import listdir
from sklearn.metrics import confusion_matrix,classification_report
import logging, warnings
import numpy as np
from tensorflow.python.training import optimizer
from tensorflow.python.ops import math_ops, state_ops, control_flow_ops, variable_scope
from tensorflow.python.framework import ops

class BPVAM(optimizer.Optimizer):
     """Back-propagation algorithm with variable adaptive momentum.

    Variables are updated in two steps:
    1) v(t + 1) = alpha * v(t)- lr * g(t)
    2) w(t + 1) = w(t) + v(t + 1)

    where
        - v(t + 1): delta for update at step t + 1
        - w(t + 1): weights at step t + 1 (after update)
        - g(t): gradients at step t.
        - lr: learning rate
        - alpha: momentum parameter

    In the algorithm alpha is not fixed. It is variable and it is parametrized by:
        alpha(t) = lambda / (1 - beta ^ t)
    """

    def __init__(
            self,
            lr: float = 0.001,
            lam: float = 0.02,
            beta: float = 0.998,
            use_locking: bool = False,
            name: str = 'BPVAM'
    ):
        """
            Args:
                lr: learning rate
                lam: momentum parameter
                beta: momentum parameter
                use_locking:
                name:
        """
        super(BPVAM, self).__init__(use_locking, name)

        self._lr = lr
        self._lambda = lam
        self._beta = beta

        self._lr_tensor = None
        self._lambda_tensor = None
        self._beta_tensor = None

    def _create_slots(self, var_list):
        for v in var_list:
            self._zeros_slot(v, 'v', self._name)
            self._get_or_make_slot(v,
                                   ops.convert_to_tensor(self._beta),
                                   'beta',
                                   self._name)

    def _prepare(self):
        self._lr_tensor = ops.convert_to_tensor(self._lr, name='lr')
        self._lambda_tensor = ops.convert_to_tensor(self._lambda, name='lambda')

    def _apply_dense(self, grad, var):
        lr_t = math_ops.cast(self._lr_tensor, var.dtype.base_dtype)
        lambda_t = math_ops.cast(self._lambda_tensor, var.dtype.base_dtype)

        v = self.get_slot(var, 'v')
        betas = self.get_slot(var, 'beta')

        beta_t = state_ops.assign(betas, betas * betas)

        alpha = lambda_t / (1 - beta_t)

        v_t = state_ops.assign(v, alpha * v - lr_t * grad)

        var_update = state_ops.assign_add(var, v_t, use_locking=self._use_locking)

        return control_flow_ops.group(*[beta_t, v_t, var_update])
</code>```

After i create my optimizer and run;

```<code>myopt = BPVAM()
model.compile(optimizer= myopt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
</code>```

I got this error message;

```<code>Traceback (most recent call last):
  File "/Users/classification.py", line 264, in <module>model.fit(x=X_train,y=y_train, batch_size=32, epochs=50, validation_data=(X_val, y_val))

File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training.py", line 780, in fit steps_name='steps_per_epoch')

File"/Users/venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training_arrays.py", line 157, in model_iteration f = _make_execution_function(model, mode)

 File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training_arrays.py", line 532, in _make_execution_function return model._make_execution_function(mode)

File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training.py", line 2276, in _make_execution_function self._make_train_function()

File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training.py", line 2219, in _make_train_function params=self._collected_trainable_weights, loss=self.total_loss)

File "/Users/ venv/lib/python3.7/site-packages/tensorflow/python/keras/optimizers.py", line 753, in get_updates grads, global_step=self.iterations)

File "/Users/ venv/lib/python3.7/site-packages/tensorflow/python/training/optimizer.py", line 614, in apply_gradients update_ops.append(processor.update_op(self, grad))

File "/Users/venv/lib/python3.7/site-packages/tensorflow/python/training/optimizer.py", line 171, in update_op update_op = optimizer._resource_apply_dense(g, self._v)

File "/Users/venv/lib/python3.7/site-packages/tensorflow/python/training/optimizer.py", line 954, in _resource_apply_dense

raise NotImplementedError()
NotImplementedError
</code>```

I can not understand where the problem is. I am using Tensorflow 1.14.0 version and python 3.7. I created virtual environment and tried other tensorflow and python versions but it still does not work.

答:
In order to use a class that inherits from tensorflow.python.training.optimizer.Optimizer you have to implement at least the following methods:

_apply_dense

_resource_apply_dense

_apply_sparse

Check out the source code of the Optimizer for more information.

Since you try to implement a custom momentum method you might want to subclass MomentumOptimizer directly.

ContentLicense: CC BY-SA 4.0

Body:
I am working on image classification and i am trying to implement a custom optimizer(based on a paper published on ELSEVIER) in Tensorflow,

I tried to modify the code as below: I have some other functions but it is all related with preprocessing and model architecture etc. My optimizer code follows;

import os
os.environ['TF_KERAS'] = '1'
from tensorflow import keras
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.utils import shuffle
import cv2
import imutils
import matplotlib.pyplot as plt
from os import listdir
from sklearn.metrics import confusion_matrix,classification_report
import logging, warnings
import numpy as np
from tensorflow.python.training import optimizer
from tensorflow.python.ops import math_ops, state_ops, control_flow_ops, variable_scope
from tensorflow.python.framework import ops

class BPVAM(optimizer.Optimizer):
     """Back-propagation algorithm with variable adaptive momentum.

    Variables are updated in two steps:
    1) v(t + 1) = alpha * v(t)- lr * g(t)
    2) w(t + 1) = w(t) + v(t + 1)

    where
        - v(t + 1): delta for update at step t + 1
        - w(t + 1): weights at step t + 1 (after update)
        - g(t): gradients at step t.
        - lr: learning rate
        - alpha: momentum parameter

    In the algorithm alpha is not fixed. It is variable and it is parametrized by:
        alpha(t) = lambda / (1 - beta ^ t)
    """

    def __init__(
            self,
            lr: float = 0.001,
            lam: float = 0.02,
            beta: float = 0.998,
            use_locking: bool = False,
            name: str = 'BPVAM'
    ):
        """
            Args:
                lr: learning rate
                lam: momentum parameter
                beta: momentum parameter
                use_locking:
                name:
        """
        super(BPVAM, self).__init__(use_locking, name)

        self._lr = lr
        self._lambda = lam
        self._beta = beta

        self._lr_tensor = None
        self._lambda_tensor = None
        self._beta_tensor = None

    def _create_slots(self, var_list):
        for v in var_list:
            self._zeros_slot(v, 'v', self._name)
            self._get_or_make_slot(v,
                                   ops.convert_to_tensor(self._beta),
                                   'beta',
                                   self._name)

    def _prepare(self):
        self._lr_tensor = ops.convert_to_tensor(self._lr, name='lr')
        self._lambda_tensor = ops.convert_to_tensor(self._lambda, name='lambda')

    def _apply_dense(self, grad, var):
        lr_t = math_ops.cast(self._lr_tensor, var.dtype.base_dtype)
        lambda_t = math_ops.cast(self._lambda_tensor, var.dtype.base_dtype)

        v = self.get_slot(var, 'v')
        betas = self.get_slot(var, 'beta')

        beta_t = state_ops.assign(betas, betas * betas)

        alpha = lambda_t / (1 - beta_t)

        v_t = state_ops.assign(v, alpha * v - lr_t * grad)

        var_update = state_ops.assign_add(var, v_t, use_locking=self._use_locking)

        return control_flow_ops.group(*[beta_t, v_t, var_update])

After i create my optimizer and run;

myopt = BPVAM()
model.compile(optimizer= myopt, loss='sparse_categorical_crossentropy', metrics=['accuracy'])

I got this error message;

Traceback (most recent call last):
  File "/Users/classification.py", line 264, in <module>model.fit(x=X_train,y=y_train, batch_size=32, epochs=50, validation_data=(X_val, y_val))

File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training.py", line 780, in fit steps_name='steps_per_epoch')

File"/Users/venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training_arrays.py", line 157, in model_iteration f = _make_execution_function(model, mode)

 File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training_arrays.py", line 532, in _make_execution_function return model._make_execution_function(mode)

File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training.py", line 2276, in _make_execution_function self._make_train_function()

File"/Users/ venv/lib/python3.7/sitepackages/tensorflow/python/keras/engine/training.py", line 2219, in _make_train_function params=self._collected_trainable_weights, loss=self.total_loss)

File "/Users/ venv/lib/python3.7/site-packages/tensorflow/python/keras/optimizers.py", line 753, in get_updates grads, global_step=self.iterations)

File "/Users/ venv/lib/python3.7/site-packages/tensorflow/python/training/optimizer.py", line 614, in apply_gradients update_ops.append(processor.update_op(self, grad))

File "/Users/venv/lib/python3.7/site-packages/tensorflow/python/training/optimizer.py", line 171, in update_op update_op = optimizer._resource_apply_dense(g, self._v)

File "/Users/venv/lib/python3.7/site-packages/tensorflow/python/training/optimizer.py", line 954, in _resource_apply_dense

raise NotImplementedError()
NotImplementedError

I can not understand where the problem is. I am using Tensorflow 1.14.0 version and python 3.7. I created virtual environment and tried other tensorflow and python versions but it still does not work.


问:
How does one concatenate cell arrays that are part of a cell array in MATLAB?
I have a cell array allData which is Nx1. Each cell contains a structure with a names property (the name is a custom object, but think of it as a cell array of strings if you like). I would like to create a single cell array that contains all of the names. For example, if N=3, so that allData is a 3x1 cell array, then the following would accomplish my goal:

```<code>A = allData{1};
B = allData{2};
C = allData{3};

allNames = [A.names B.names C.names];
</code>```

The problem with this approach is that N is large and changes depending on the input, so I'm hoping that there is a clever way to do this using cellfun, but everything that I've tried fails (e.g. it doesn't work to do allNames = [cellfun(@(x) {x.names}, allData)];).

UPDATE: Thanks to the suggested solutions, I can get everything into one cell array where each cell contains a cell array. My goal here is to concatenate these. More or less, what I have is:

```<code>{A.names B.names C.names}
</code>```

and what I want and cannot seem to get is

```<code>{A.names{1} A.names{2} ... A.names{end} B.names{1} ... B.names{end} ...}
</code>```

SOLUTION:
I needed pieces of each answer below, so here's the solution that worked for me:

from Andrew Lazarus:

allNames = arrayfun(@(x) x.name, [allData{:}], 'UniformOutput', false);

then, from gnovice:

allNames = vertcat(allNames{:});

Thanks to both!!

答:
Try this

```<code> allNames = arrayfun(@(x) x.name, [allData{:}], 'UniformOutput', false)
</code>```

Omit the UniformOutput vararg for straight concatenation. This gives a cell output.

ContentLicense: CC BY-SA 3.0

Body:
I have a cell array allData which is Nx1. Each cell contains a structure with a names property (the name is a custom object, but think of it as a cell array of strings if you like). I would like to create a single cell array that contains all of the names. For example, if N=3, so that allData is a 3x1 cell array, then the following would accomplish my goal:

A = allData{1};
B = allData{2};
C = allData{3};

allNames = [A.names B.names C.names];

The problem with this approach is that N is large and changes depending on the input, so I'm hoping that there is a clever way to do this using cellfun, but everything that I've tried fails (e.g. it doesn't work to do allNames = [cellfun(@(x) {x.names}, allData)];).

UPDATE: Thanks to the suggested solutions, I can get everything into one cell array where each cell contains a cell array. My goal here is to concatenate these. More or less, what I have is:

{A.names B.names C.names}

and what I want and cannot seem to get is

{A.names{1} A.names{2} ... A.names{end} B.names{1} ... B.names{end} ...}

SOLUTION:
I needed pieces of each answer below, so here's the solution that worked for me:

from Andrew Lazarus:

allNames = arrayfun(@(x) x.name, [allData{:}], 'UniformOutput', false);

then, from gnovice:

allNames = vertcat(allNames{:});

Thanks to both!!

Body:
Try this

 allNames = arrayfun(@(x) x.name, [allData{:}], 'UniformOutput', false)

Omit the UniformOutput vararg for straight concatenation. This gives a cell output.


问:
Calculate table each row uniquely in jquery
I am working on a POS system. Here I need to calculate the total for each item uniquely. I have written an onKeyUp function to calculate the amount. It's working perfect for a single row. If I modified added discount 2 for the second product it affects the first row.

Screenshot:

HTML :

```<code><table class="table table-striped table-hover" id="item_table">
   <thead id="thead">
      <tr class="bg-primary">
         <th>#</th>
         <th>Product Name</th>
         <th>Quantity</th>
         <th>Unit Price</th>
         <th>Discount</th>
         <th>Discount 2</th>
         <th>Amount</th>
         <th><i class="fa fa-close"></i></th>
      </tr>
   </thead>
   <tbody id="item_list">
      <tr>
         <td><?php echo $n; ?></td>
         <td><?php echo $product_name; ?></td>
         <td><input type="number" class="form-control" name="quantity[]" id="quantity" value="1" min="1" step="1"></td>
         <td id="sprice"><?php echo $selling_price; ?></td>
         <td id="discount"><?php echo $discount_rate; ?>%</td>
         <td><input type="text" class="form-control" name="discount2" id="discount2"></td>
         <td id="total"><?php echo number_format($total,2,'.', ''); ?></td>
         <td><span><i class="fa fa-trash"></i></span></td>
      </tr>
   </tbody>
</table>
</code>```

Here the PHP code used insert the row for the first time to the table.There is no issue with that. Its working with the one record.

JavaScript :

```<code>//Product Row Calculation
function calculateItemPrice() {
    var sprice = $("#item_table #sprice").text();
    var quantity = $("#item_table #item_list #quantity").val();
    var discount = $("#item_table #discount").text().slice(0, -1);
    var discount2 = $("#item_table #item_list #discount2").val();

    $('tr').each(function() {
        var totalDiscount = ((sprice * quantity) * discount / 100);
        var price = ((((sprice * quantity) - totalDiscount)) - discount2);
        var total = parseFloat(price).toFixed(2);

        $("#total").html(total);
    });
}

$("#item_table").on("keyup", "#quantity", function() {
    calculateItemPrice();
});

$("#item_table").on("keyup", "#discount2", function() {
    calculateItemPrice();
});
</code>```

答:
Try like this:</p>

```<code>//Product Row Calculation
    function calculateItemPrice(sprice,quantity,discount,discount2){
        var totalDiscount = ((sprice * quantity) * discount/100);
        var price = ((((sprice * quantity) - totalDiscount))- discount2);
        var total = parseFloat(price).toFixed(2);

        //alert("Hi");
        return total;
    }

    $("#item_table").on("keyup","#discount2 , #quantity", function() {
        var sprice = $(this).closest('tr').find("#sprice").text();
        var quantity = $(this).closest('tr').find("#quantity").val();
        var discount = $(this).closest('tr').find("#discount").text().slice(0,-1);
        var discount2 = $(this).closest('tr').find("#discount2").val();

        total2 = calculateItemPrice(sprice,quantity,discount,discount2);
        $(this).closest('tr').find('#total').html(total2);
        //alert(discount2);
    });
</code>```

Body:
I am working on a POS system. Here I need to calculate the total for each item uniquely. I have written an onKeyUp function to calculate the amount. It's working perfect for a single row. If I modified added discount 2 for the second product it affects the first row.

Screenshot:

HTML :

         #
         Product Name
         Quantity
         Unit Price
         Discount
         Discount 2
         Amount

         <?php echo $n; ?>
         <?php echo $product_name; ?>
         <input type="number" class="form-control" name="quantity[]" id="quantity" value="1" min="1" step="1">
         <?php echo $selling_price; ?>
         <?php echo $discount_rate; ?>%
         <input type="text" class="form-control" name="discount2" id="discount2">
         <?php echo number_format($total,2,'.', ''); ?>

Here the PHP code used insert the row for the first time to the table.There is no issue with that. Its working with the one record.

JavaScript :

//Product Row Calculation
function calculateItemPrice() {
    var sprice = $("#item_table #sprice").text();
    var quantity = $("#item_table #item_list #quantity").val();
    var discount = $("#item_table #discount").text().slice(0, -1);
    var discount2 = $("#item_table #item_list #discount2").val();

    $('tr').each(function() {
        var totalDiscount = ((sprice * quantity) * discount / 100);
        var price = ((((sprice * quantity) - totalDiscount)) - discount2);
        var total = parseFloat(price).toFixed(2);

        $("#total").html(total);
    });
}

$("#item_table").on("keyup", "#quantity", function() {
    calculateItemPrice();
});

$("#item_table").on("keyup", "#discount2", function() {
    calculateItemPrice();
});

Body:
Try like this:

//Product Row Calculation
    function calculateItemPrice(sprice,quantity,discount,discount2){
        var totalDiscount = ((sprice * quantity) * discount/100);
        var price = ((((sprice * quantity) - totalDiscount))- discount2);
        var total = parseFloat(price).toFixed(2);

        //alert("Hi");
        return total;
    }

    $("#item_table").on("keyup","#discount2 , #quantity", function() {
        var sprice = $(this).closest('tr').find("#sprice").text();
        var quantity = $(this).closest('tr').find("#quantity").val();
        var discount = $(this).closest('tr').find("#discount").text().slice(0,-1);
        var discount2 = $(this).closest('tr').find("#discount2").val();

        total2 = calculateItemPrice(sprice,quantity,discount,discount2);
        $(this).closest('tr').find('#total').html(total2);
        //alert(discount2);
    });


问:
JavaScript function calls are not working inside table dropdown when ReactDOMServer and innerHTML are used
JavaScript functions calls are not working inside the table dropdown which is added to the DOM by innerHTML

```<code>  employeesRetrieval = e => {

    axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {

        let totalActiveEmployees = res.data[0];

        let activeEmployeesAdder = ``;

          totalActiveEmployees.forEach( ele => {

            let role = '';
            if(ele.empRole === 0){
              role = 'Admin';
            }else{
              role = 'Employee';
            }
            activeEmployeesAdder += ReactDOMServer.renderToString(
                                    <tr>
                                      <td>{ele.empId}</td>
                                      <td>{ele.empName}</td>
                                      <td>{ele.empEmail}</td>
                                      <td>{role}</td>
                                      <td className = "editColumn">

                                        <div className="btn-group">
                                          <button className="noCaret" data-toggle="dropdown" title = "Edit">
                                            <MoreVertical className = "editIcon" id = "editIcon"/>
                                          </button>
                                          <ul className="dropdown-menu" role="menu">
                                            <li className = "dropdown-item" role = "button" name = {ele.empId} onSelect = {() => this.showEmployeeUpdateModal('active', ele.empId)}>Edit details</li>
                                            <li className = "dropdown-item" role = "button" name = {ele.empId} onSelect = {() => this.directEmployeeStatusChange('inactive', ele.empId)}>Make inactive</li>
                                          </ul>
                                        </div>

                                      </td>
                                    </tr>
                                  );
          });
          document.getElementById('activeEmployeesLoader').style.display = "none";
          document.getElementById('activeEmployeesTableContent').innerHTML = activeEmployeesAdder;
</code>```

After opening the dropdown:

No response or error is coming after clicking them. I tried changing everything like onClick attributes and changing ul and li to select and option tags. Nothing seems to work for me.

The two functions :

```<code>showEmployeeUpdateModal = (e, id) => {
      console.log('INSIDE THE FUNCTION');
      /*
         SOME LOGIC
      */
    };
</code>```

```<code>directEmployeeStatusChange = (e, id) => {
      console.log('INSIDE THE FUNCTION');
      /*
         SOME LOGIC
      */
    };
</code>```

答:
You are using ReactDOMServer.renderToString on that chunk of code that includes your event listeners.

As the name suggests, renderToString gives you plain HTML, so the event handlers won't work as written.

Have a look at a similar question React.js Serverside rendering and Event Handlers

Body:
JavaScript functions calls are not working inside the table dropdown which is added to the DOM by innerHTML

  employeesRetrieval = e => {

    axios.post('http://localhost:5000/employeesRetrieval')
      .then( res => {

        let totalActiveEmployees = res.data[0];

        let activeEmployeesAdder = ``;

          totalActiveEmployees.forEach( ele => {

            let role = '';
            if(ele.empRole === 0){
              role = 'Admin';
            }else{
              role = 'Employee';
            }
            activeEmployeesAdder += ReactDOMServer.renderToString(

                                      {ele.empId}
                                      {ele.empName}
                                      {ele.empEmail}
                                      {role}

                                          <button className="noCaret" data-toggle="dropdown" title = "Edit">
                                            <MoreVertical className = "editIcon" id = "editIcon"/>
                                          </button>

 this.showEmployeeUpdateModal('active', ele.empId)}>Edit details

 this.directEmployeeStatusChange('inactive', ele.empId)}>Make inactive

                                  );
          });
          document.getElementById('activeEmployeesLoader').style.display = "none";
          document.getElementById('activeEmployeesTableContent').innerHTML = activeEmployeesAdder;

After opening the dropdown:

No response or error is coming after clicking them. I tried changing everything like onClick attributes and changing ul and li to select and option tags. Nothing seems to work for me.

The two functions :

showEmployeeUpdateModal = (e, id) => {
      console.log('INSIDE THE FUNCTION');
      /*
         SOME LOGIC
      */
    };

directEmployeeStatusChange = (e, id) => {
      console.log('INSIDE THE FUNCTION');
      /*
         SOME LOGIC
      */
    };


问:
How do I login with multiple discord bot accounts WITHOUT hardcoding?
I have been trying to get this to work for a bit now, with no avail.

What i have tried is below, what i want to be able to do is have multiple discord bot accounts respond to the same prompts at the same time, without hardcoding it, my best example so far is down below.

EDIT: I know about the client.on error, but this is the best example that has gotten this far I have had

```<code>const auth = require("./tokens.json");
const Discord = require("discord.js");
client = new Discord.Client();
var clients = [];
auth["Tokens"].forEach(element => {
    console.log(clients)
    clients.push(new Discord.Client().login(element));
    console.log(clients)
});
console.log(clients[0])
console.log(clients[1])
console.log(clients[2])

clients.forEach(client => {
    client.on("ready", () => {
        console.log("I am ready!");
        console.log(client.user.id)
    });
});

</code>```

My tokens.json code:

```<code>{
    "Tokens": ["MjIxtokentoken","MjIxtokentokenc","MjIxtokentoken"]
}
</code>```

The output:

```<code>PS E:\test> node app.js
[]
[ Promise { <pending> } ]
[ Promise { <pending> } ]
[ Promise { <pending> }, Promise { <pending> } ]
[ Promise { <pending> }, Promise { <pending> } ]
[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
E:\test\app.js:40
    client.on("ready", () => {
           ^

TypeError: client.on is not a function
    at E:\test\app.js:40:12
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (E:\test\app.js:39:9)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11
</code>```

答:
you can do it in a simple way. At first do a loop on a your tokens and do your job.

This will look likes:

const auth = require('./tokens.json')
const Discord = require('discord.js')

for (const token of auth.Tokens) {
    const client = new Discord.Client()
    client.on('ready', () => {
        console.log('I am ready !')
        console.log(client.user.id)
    })
    client.login(token)
}
```

Body:
I have been trying to get this to work for a bit now, with no avail.

What i have tried is below, what i want to be able to do is have multiple discord bot accounts respond to the same prompts at the same time, without hardcoding it, my best example so far is down below.

EDIT: I know about the client.on error, but this is the best example that has gotten this far I have had

const auth = require("./tokens.json");
const Discord = require("discord.js");
client = new Discord.Client();
var clients = [];
auth["Tokens"].forEach(element => {
    console.log(clients)
    clients.push(new Discord.Client().login(element));
    console.log(clients)
});
console.log(clients[0])
console.log(clients[1])
console.log(clients[2])

clients.forEach(client => {
    client.on("ready", () => {
        console.log("I am ready!");
        console.log(client.user.id)
    });
});

My tokens.json code:

{
    "Tokens": ["MjIxtokentoken","MjIxtokentokenc","MjIxtokentoken"]
}

The output:

PS E:\test> node app.js
[]
[ Promise { <pending> } ]
[ Promise { <pending> } ]
[ Promise { <pending> }, Promise { <pending> } ]
[ Promise { <pending> }, Promise { <pending> } ]
[ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
E:\test\app.js:40
    client.on("ready", () => {
           ^

TypeError: client.on is not a function
    at E:\test\app.js:40:12
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (E:\test\app.js:39:9)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)
    at internal/main/run_main_module.js:17:11


问:
App specific storage or sq lite database for reminder app?
I am trying to develop a reminder app in android studio. The user can create an appointment which will be shown in a recycler view. Every created appointment has a name and a priority. The user can choose if the appointment should also have an alarm. Later on I want to implement the possibility to attach an audio recording, an image from the gallery or a document from the device to the appointment, and the possibility to sort the appointment by date or search by name.

Now to my question, I want to save the appointments locally on my device, but I don’t know what type of data storage is better for my app. I already searched on google, but couldn’t find any concrete answer. After looking through the internet I think the best two options for me are sq lite database or app specific storage in the external storage. Can somebody please help me and tell me which one is best and why for my specific situation?

答: Use ROOM db it is flexible to store data objects and modify them with simple and clean code, on the other hand sqlite needs to write a lot of boiler plate code and even developers recommends to use ROOM DB over sqlite or shared preferences, you can run simple queries and fetch data from the database using ROOM Database, you can also write/read files using FileProviders but it requires user local storage permission which may be denied by few.</p>


问:
How to model these relations in Rails
I currently have the following model structure and relations

```<code>class Fleet < ApplicationRecord
  # properties id, created_at, updated_at

  # A fleet should only consists of the same type, either a fleet or cars or a fleet of trains. Never both
    has_many :cars
    has_many :trains
end

class Car < ApplicationRecord
  # properties id, created_at, updated_at, number_of_gears, is_sports_car

  belongs_to :fleet
end

class Train < ApplicationRecord
  # properties id, created_at, updated_at, number_of_wagons, people_capacity, has_first_calass_section

  belongs_to :fleet
end
</code>```

The problem i have is thata fleet should only consists of the same type, either a fleet of cars or a fleet of trains. Never both.

With the current relations on fleet, it seems error prone to have both has_many associations (or more coming like Airplanes) in terms of integrity and ease of use when calling @fleet._cars-or-trains, i would have to know what i can call.

STI is not an option since the properties are very different on a Car and a Train. There are many more properties, for the sake of simplicity i have shortened them in this example.

What is the right way in Rails to do this?

答:
You could add a model validation to check this:

```<code>class Fleet < ApplicationRecord
  has_many :cars
  has_many :trains

  validates :cars, absence: true, if: -> { trains.any? }
  validates :trains, absence: true, if: -> { cars.any? }
end
</code>```

The above should stop fleets from being saved when they have both cars and trains present. However you can still create cars and trains separately and link them to a fleet.

```<code># assuming a valid fleet exist
fleet = Fleet.create # should save

# you can still create both cars and trains
fleet.cars.create # should save
fleet.trains.create # should save

# however when you retry to save the fleet it fails on the validation
fleet.save # should fail
</code>```

In the above scenario we would like to also fire the fleet validations when creating a car or train. To do this add a validates_associated:

```<code>validates_associated :fleet
</code>```

In both the Car and Train model. This now should withhold the above car and train to be saved.

Note that this answer doesn't prevent anything SQL related and records are still technically allowed in the database. If you don't want this you have to build a trigger that runs AFTER INSERT and AFTER UPDATE. Since this is SQL related I would suggest asking a new question if you have any issues with trigger creation. Mention the database used since the trigger syntax is not the same for all database types (MySQL, SQL Server, ...).

Title: How to model these relations in Rails

Body:
I currently have the following model structure and relations

class Fleet < ApplicationRecord
  # properties id, created_at, updated_at

  # A fleet should only consists of the same type, either a fleet or cars or a fleet of trains. Never both
    has_many :cars
    has_many :trains
end

class Car < ApplicationRecord
  # properties id, created_at, updated_at, number_of_gears, is_sports_car

  belongs_to :fleet
end

class Train < ApplicationRecord
  # properties id, created_at, updated_at, number_of_wagons, people_capacity, has_first_calass_section

  belongs_to :fleet
end

The problem i have is thata fleet should only consists of the same type, either a fleet of cars or a fleet of trains. Never both.

With the current relations on fleet, it seems error prone to have both has_many associations (or more coming like Airplanes) in terms of integrity and ease of use when calling @fleet._cars-or-trains, i would have to know what i can call.

STI is not an option since the properties are very different on a Car and a Train. There are many more properties, for the sake of simplicity i have shortened them in this example.

What is the right way in Rails to do this?

Body:
You could add a model validation to check this:

class Fleet < ApplicationRecord
  has_many :cars
  has_many :trains

  validates :cars, absence: true, if: -> { trains.any? }
  validates :trains, absence: true, if: -> { cars.any? }
end

The above should stop fleets from being saved when they have both cars and trains present. However you can still create cars and trains separately and link them to a fleet.

# assuming a valid fleet exist
fleet = Fleet.create # should save

# you can still create both cars and trains
fleet.cars.create # should save
fleet.trains.create # should save

# however when you retry to save the fleet it fails on the validation
fleet.save # should fail

In the above scenario we would like to also fire the fleet validations when creating a car or train. To do this add a validates_associated:

validates_associated :fleet

In both the Car and Train model. This now should withhold the above car and train to be saved.

Note that this answer doesn't prevent anything SQL related and records are still technically allowed in the database. If you don't want this you have to build a trigger that runs AFTER INSERT and AFTER UPDATE. Since this is SQL related I would suggest asking a new question if you have any issues with trigger creation. Mention the database used since the trigger syntax is not the same for all database types (MySQL, SQL Server, ...).


问:
I have an issue on mysql file 110.err (408GB)
There is a file "110.err" on /opt/lampp/var/mysql consume big storage data I don' know the purpose of this file and what I should do ?Screenshot of size</p>

答:
Download the file, stop the server, delete the file, then restart the server. Truncating the file might be an option to download & review the file (because you cannot use "Notepad" or alike to open 408GB); the last few megabytes should suffice. For example, the last 10.000 lines:</p>

```<code>tail -10000 ./110.err > ./110_mysqld.log
</code>```

Body:
Download the file, stop the server, delete the file, then restart the server. Truncating the file might be an option to download & review the file (because you cannot use "Notepad" or alike to open 408GB); the last few megabytes should suffice. For example, the last 10.000 lines:

tail -10000 ./110.err > ./110_mysqld.log


问:
Print a vector with variable number of elements using sprintf
In the following code, I can print all the elements in the vector item separated by a space as

```<code>item = [123 456 789];
sprintf('%d %d %d', item)

ans =

123 456 789
</code>```

How do I go about doing this without having to enter as many %d as the number of elements in item?

答:
I believe num2str is what you're looking for.

```<code>item=[123 456 789];
num2str(item)

ans =

123  456  789
</code>```

Since you also tagged it sprintf, here's a solution that uses it.

```<code>item=[123 456 789];
str='%d ';
nItem=numel(item);
strAll=repmat(str,1,nItem);

sprintf(strAll(1:end-1),item)

ans =

123 456 789
</code>```

Body:
In the following code, I can print all the elements in the vector item separated by a space as

item = [123 456 789];
sprintf('%d %d %d', item)

ans =

123 456 789

How do I go about doing this without having to enter as many %d as the number of elements in item?

Body:
I believe num2str is what you're looking for.

item=[123 456 789];
num2str(item)

ans =

123  456  789

Since you also tagged it sprintf, here's a solution that uses it.

item=[123 456 789];
str='%d ';
nItem=numel(item);
strAll=repmat(str,1,nItem);

sprintf(strAll(1:end-1),item)

ans =

123 456 789


问:
Is there a way to use "js-yaml" to add one YAML file to another YAML file in nodejs unix environment
I have two YAML files. I want to add the second YAML file inside first YAML file using "js-yaml". Basically my first YAML file continues to grow by adding multiple YAML files.

I have tried to add the new file directly to first YAML file, and it has added, but when I try it again, it is replacing the current data, not adding it:

```<code>try {
  var filename = path.join(__dirname, "first.yaml"),
    contents = fs.readFileSync(filename, "utf8"),
    first = yaml.load(contents);

  var filename2 = path.join(__dirname, "second.yaml"),
    contents2 = fs.readFileSync(filename2, "utf8"),
    second = yaml.load(contents2);

  var fruits = first.fruits ;
  var newfruits = second.fruits;
  first.fruits= newfruits;

  console.log(util.inspect(first, false, 10, true));
  fs.writeFile("first.yaml", yaml.dump(first), "utf8", err => {
    if (err) console.log(err);
</code>```

the above code is replacing fruits always not adding it. I want to stack it when ever I want it to add.

答:
Well, I had a look on you code and there is not much to do to obtain the desired result.

Use:

```<code>first = first + second;
</code>```

or:

```<code>first = second;
</code>```

Body:
I have two YAML files. I want to add the second YAML file inside first YAML file using "js-yaml". Basically my first YAML file continues to grow by adding multiple YAML files.

I have tried to add the new file directly to first YAML file, and it has added, but when I try it again, it is replacing the current data, not adding it:

try {
  var filename = path.join(__dirname, "first.yaml"),
    contents = fs.readFileSync(filename, "utf8"),
    first = yaml.load(contents);

  var filename2 = path.join(__dirname, "second.yaml"),
    contents2 = fs.readFileSync(filename2, "utf8"),
    second = yaml.load(contents2);

  var fruits = first.fruits ;
  var newfruits = second.fruits;
  first.fruits= newfruits;

  console.log(util.inspect(first, false, 10, true));
  fs.writeFile("first.yaml", yaml.dump(first), "utf8", err => {
    if (err) console.log(err);

the above code is replacing fruits always not adding it. I want to stack it when ever I want it to add.

Body:
Well, I had a look on you code and there is not much to do to obtain the desired result.

Use:

first = first + second;

or:

first = second;


问:
Change alignment of particular column - Gridview
I have a Gridview whose items should be left aligned and I have written the code as below. Now I have a column for serial number. Only this column should be center aligned. How can I achieve this? I have done like below. But serial number column is always center aligned.
In short, The first column items of gridview should be center aligned. And the remaining columns should be left aligned.</p>

```<code> <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
 CssClass="gridview_alter"  GridLines="Both"  HorizontalAlign="Right"  CellPadding="4"
 CellSpacing="2" HeaderStyle-Height="60px" HeaderStyle-Font-Bold="true"
 HeaderStyle-Font-Size="Larger" Caption="Information" CaptionAlign="Top"
 OnRowDataBound="GridView2_RowDataBound">
            <Columns>
        <asp:TemplateField HeaderText="SNo"><ItemTemplate >
        <asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
        </ItemTemplate>
        <ItemStyle Width="20px" HorizontalAlign="Center" />
        <HeaderStyle  Width="20px" />
        </asp:TemplateField>

        <asp:BoundField DataField="name" HeaderText="Name" ReadOnly="True"></asp:BoundField>
        <asp:BoundField DataField="count" HeaderText="Total" ReadOnly="True"></asp:BoundField>
            </Columns>
 </asp:GridView>

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridView2.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Center;//serialnum
}

.gridview_alter {
width: 85%;
font-family: Arial !important;
border: 2px solid #d7dedb;
background-color: #ffffff;
}
 .gridview_alter th {
    text-align: center;
    background-color: #ffffff;
}
  .gridview_alter td {
    font-size: 16px;
    color: #000000;
    text-align: left;
}
</code>```

答:
For your remaining two columns [ name, count ], you should also add the ItemStyle-HorizontalAlign and HeaderStyle-HorizontalAlign property as:

```<code><asp:BoundField DataField="name" HeaderText="Name"
        HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" .... />
</code>```

There are ways to do this programmmatically also by catching the RowDataBound event of gridview. I believe the markups should be just fine for setting the alignments.

Body:
I have a Gridview whose items should be left aligned and I have written the code as below. Now I have a column for serial number. Only this column should be center aligned. How can I achieve this? I have done like below. But serial number column is always center aligned.
In short, The first column items of gridview should be center aligned. And the remaining columns should be left aligned.

 <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
 CssClass="gridview_alter"  GridLines="Both"  HorizontalAlign="Right"  CellPadding="4"
 CellSpacing="2" HeaderStyle-Height="60px" HeaderStyle-Font-Bold="true"
 HeaderStyle-Font-Size="Larger" Caption="Information" CaptionAlign="Top"
 OnRowDataBound="GridView2_RowDataBound">
            <Columns>
        <asp:TemplateField HeaderText="SNo"><ItemTemplate >
        <asp:Label ID="lblSRNO" runat="server" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
        </ItemTemplate>
        <ItemStyle Width="20px" HorizontalAlign="Center" />
        <HeaderStyle  Width="20px" />
        </asp:TemplateField>

        <asp:BoundField DataField="name" HeaderText="Name" ReadOnly="True"></asp:BoundField>
        <asp:BoundField DataField="count" HeaderText="Total" ReadOnly="True"></asp:BoundField>
            </Columns>
 </asp:GridView>

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridView2.Columns[0].ItemStyle.HorizontalAlign = HorizontalAlign.Center;//serialnum
}

.gridview_alter {
width: 85%;
font-family: Arial !important;
border: 2px solid #d7dedb;
background-color: #ffffff;
}
 .gridview_alter th {
    text-align: center;
    background-color: #ffffff;
}
  .gridview_alter td {
    font-size: 16px;
    color: #000000;
    text-align: left;
}

Body:
For your remaining two columns [ name, count ], you should also add the ItemStyle-HorizontalAlign and HeaderStyle-HorizontalAlign property as:

<asp:BoundField DataField="name" HeaderText="Name"
        HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" .... />

There are ways to do this programmmatically also by catching the RowDataBound event of gridview. I believe the markups should be just fine for setting the alignments.


问:
Get frame object that function was defined in
Is there any way to programmatically find the frame that a function was defined in? I'm looking for something like a function get_defining_frame that would work like this:

```<code>def foo():
    def bar():
        pass
    return bar

bar = foo()

get_defining_frame(foo) # should be the same as inspect.currentframe()
get_defining_frame(bar) # should be the frame created by the call to foo
</code>```

Thanks!

答:
This is a snippet from an answer I posted on a different topic, but found it very applicable to the question. It goes up the frames to locate the one where the function is defined, or should have been defined in.

The code below was designed to find out if a function has already been defined in a class, module, or in __main__. Before it returns what it finds, it has found the locals dictionary of the object in which the function is declared. So it could be modified to return the locals dict or frame.

The problem this addressed was how to find the scope for a function during class declaration before the function was bound to the class. So o.__self__ or other properties weren't yet assigned. This was part of an implementation for a decorator.

This works on Python 3, but not 2.

```<code>>>> def _find_scope(func):
...     try:
...         owner_qname = '.'.join(func.__qualname__.split('.')[:-1])
...         if len(owner_qname) == 0:
...             module = sys.modules['__main__']
...             if hasattr(module, func.__name__):
...                 return module.__dict__
...             else:
...                 return None
...         i = 0
...         while True:
...             f_locals = sys._getframe(i).f_locals
...             i += 1
...             if ('__qualname__' in f_locals and
...                 f_locals['__qualname__'] == owner_qname):
...                     if func.__name__ in f_locals:
...                         return f_locals
...                     else:
...                         return None
...     except ValueError:
...         return None
</code>```

Body:
Is there any way to programmatically find the frame that a function was defined in? I'm looking for something like a function get_defining_frame that would work like this:

def foo():
    def bar():
        pass
    return bar

bar = foo()

get_defining_frame(foo) # should be the same as inspect.currentframe()
get_defining_frame(bar) # should be the frame created by the call to foo

Thanks!

Body:
This is a snippet from an answer I posted on a different topic, but found it very applicable to the question. It goes up the frames to locate the one where the function is defined, or should have been defined in.

The code below was designed to find out if a function has already been defined in a class, module, or in __main__. Before it returns what it finds, it has found the locals dictionary of the object in which the function is declared. So it could be modified to return the locals dict or frame.

The problem this addressed was how to find the scope for a function during class declaration before the function was bound to the class. So o.__self__ or other properties weren't yet assigned. This was part of an implementation for a decorator.

This works on Python 3, but not 2.

>>> def _find_scope(func):
...     try:
...         owner_qname = '.'.join(func.__qualname__.split('.')[:-1])
...         if len(owner_qname) == 0:
...             module = sys.modules['__main__']
...             if hasattr(module, func.__name__):
...                 return module.__dict__
...             else:
...                 return None
...         i = 0
...         while True:
...             f_locals = sys._getframe(i).f_locals
...             i += 1
...             if ('__qualname__' in f_locals and
...                 f_locals['__qualname__'] == owner_qname):
...                     if func.__name__ in f_locals:
...                         return f_locals
...                     else:
...                         return None
...     except ValueError:
...         return None


问:
How do I use PDO::FETCH_CLASS with namespace?
I'm learning PHP and right now I'm displaying some articles with PDO. I have some issue using PDO::FETCH_CLASS with the usage of namespace.

my folder architecture:

```<code>class/
- Post.php
layout/
-articles/
--articles.php
public/
-index.php (contains my router)
</code>```

Post.php

```<code>namespace App\Articles;

class Post {
    private $id;
    private $name;
    private $content;
    private $date;

    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getContent()
    {
        return $this->content;
    }
    public function getExcerpt()
    {
        $res = $this->content;
        return (strlen($res) > 150) ? substr($res, 0, 150) . '...' : $res;
    }
    public function getDate()
    {
        return $this->date = date('d-m-Y', $this->date);
    }
}
</code>```

data.db contains only four columns: id, name(text), content(text), created_at(int)

The part I have trouble with:

```<code>use App\Articles\Post;

$pdo = new PDO('sqlite:../data.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
try {
    $query = $pdo->query('SELECT * FROM posts');
    $posts = $query->fetchAll(PDO::FETCH_CLASS, 'Post');
} catch (PDOException $e) {
    $error = $e->getMessage();
}
</code>```

I tried different typing instead of 'Postlike

```<code>'App\Articles\'
'App\Articles\Post'
'App\Articles\::POST'
...
</code>```

I can't manage to make it works with namepsace.
It works with a require '../class/Post.php'.

Is there a solution for this problem or should I just use the require ?

答:
hi try to read somting about autoloading classes https://www.php.net/manual/en/language.oop5.autoload.php

if you dont have autoloading in code, simply using

```<code>use App\Articles\Post;
</code>```

does nothing,or as you stated self using require is right solution

Body:
I'm learning PHP and right now I'm displaying some articles with PDO. I have some issue using PDO::FETCH_CLASS with the usage of namespace.

my folder architecture:

class/
- Post.php
layout/
-articles/
--articles.php
public/
-index.php (contains my router)

Post.php

namespace App\Articles;

class Post {
    private $id;
    private $name;
    private $content;
    private $date;

    public function getId()
    {
        return $this->id;
    }
    public function getName()
    {
        return $this->name;
    }
    public function getContent()
    {
        return $this->content;
    }
    public function getExcerpt()
    {
        $res = $this->content;
        return (strlen($res) > 150) ? substr($res, 0, 150) . '...' : $res;
    }
    public function getDate()
    {
        return $this->date = date('d-m-Y', $this->date);
    }
}

data.db contains only four columns: id, name(text), content(text), created_at(int)

The part I have trouble with:

use App\Articles\Post;

$pdo = new PDO('sqlite:../data.db', null, null, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
]);
try {
    $query = $pdo->query('SELECT * FROM posts');
    $posts = $query->fetchAll(PDO::FETCH_CLASS, 'Post');
} catch (PDOException $e) {
    $error = $e->getMessage();
}

I tried different typing instead of 'Postlike

'App\Articles\'
'App\Articles\Post'
'App\Articles\::POST'
...

I can't manage to make it works with namepsace.
It works with a require '../class/Post.php'.

Is there a solution for this problem or should I just use the require ?

Body:
hi try to read somting about autoloading classes https://www.php.net/manual/en/language.oop5.autoload.php

if you dont have autoloading in code, simply using

use App\Articles\Post;

does nothing,or as you stated self using require is right solution


问:
Calculate the standard deviation in R for a specific group of the dependent variable
I am trying to calculate the standard deviation from certain variables for different groups. In my dataset I have a 2 explanatory variables with a 0 or 1 outcome (CH and CH2). I would like to know the difference in the standard deviation of these two groups.

so far I am working with the following command. sample being the dataset and COM being one of the explanatory variables.

```<code>sd(sample$COM, na.rm=TRUE)
</code>```

Is it possible to specify it for CH = 1?
And additionally for CH = 1 or CH2=1?

Thank you in advance and kind regards.

答:
Maybe the tapply function will do what you want:</p>

```<code>tapply(sample$COM, sample$CH, sd)
</code>```

Body:
I am trying to calculate the standard deviation from certain variables for different groups. In my dataset I have a 2 explanatory variables with a 0 or 1 outcome (CH and CH2). I would like to know the difference in the standard deviation of these two groups.

so far I am working with the following command. sample being the dataset and COM being one of the explanatory variables.

sd(sample$COM, na.rm=TRUE)

Is it possible to specify it for CH = 1?
And additionally for CH = 1 or CH2=1?

Thank you in advance and kind regards.

Body:
Maybe the tapply function will do what you want:

tapply(sample$COM, sample$CH, sd)


问:
South ignores change in field default value in Python / Django
Why does South not recognize changes in default field values in Python models?  For example, take this existing model that is migrated with south:

```<code>class MyFamily(models.Model):
    family_size = models.IntegerField(verbose_name="What is your family size?", default=2)
</code>```

Now, I'd like to change the default value from two to four.  However, when schemamigrating the module, South reports:

```<code>python manage.py schemamigration family --auto change_default_from_two_to_four_for_size

Running migrations for family:
- Nothing to migrate.
    - Loading initial data for family.
</code>```

I could manually update the initial migration, and use the SQL to directly update the field, but that's a pain.  Is there a South command I haven't found that recognizes the change in the default?

Thanks!

答:
South won't update the default value for existing columns, because it matters for him only when adding a new column to a non empty table. The django orm will handle writing the new default value to new rows before hitting the database.

If you will work on the database from outside django orm, you have to update it manually.

More explanations south/db.add_column

Body:
Why does South not recognize changes in default field values in Python models?  For example, take this existing model that is migrated with south:

class MyFamily(models.Model):
    family_size = models.IntegerField(verbose_name="What is your family size?", default=2)

Now, I'd like to change the default value from two to four.  However, when schemamigrating the module, South reports:

python manage.py schemamigration family --auto change_default_from_two_to_four_for_size

Running migrations for family:
- Nothing to migrate.
    - Loading initial data for family.

I could manually update the initial migration, and use the SQL to directly update the field, but that's a pain.  Is there a South command I haven't found that recognizes the change in the default?

Thanks!


问:
PHP array_walk doesn't change the array's values
I have this simple code:

```<code>$postCopy = $_POST['adminpanel'];
array_walk($postCopy, function($v, $k) {
    return '';
});
</code>```

I did var_dump for postCopy before and after array_walk execution.
In both var_dump executions, I get the same result:

```<code>array(2) { ["usefulinfo_countryfilescount"]=> string(1) "3" ["strageticoverviews_filesinpagecount"]=> string(1) "3" }
</code>```

So it means that array_walk didn't execute correctly, because if it would- I'd get an array with '' values...

答:
You just forgot to pass argument by reference : </p>

```<code>$postCopy = $_POST['adminpanel'];
array_walk($postCopy, function(&$v, $k) {
    $v = '';
});
</code>```

Body:
I have this simple code:

$postCopy = $_POST['adminpanel'];
array_walk($postCopy, function($v, $k) {
    return '';
});

I did var_dump for postCopy before and after array_walk execution.
In both var_dump executions, I get the same result:

array(2) { ["usefulinfo_countryfilescount"]=> string(1) "3" ["strageticoverviews_filesinpagecount"]=> string(1) "3" }

So it means that array_walk didn't execute correctly, because if it would- I'd get an array with '' values...

Body:
You just forgot to pass argument by reference :

$postCopy = $_POST['adminpanel'];
array_walk($postCopy, function(&$v, $k) {
    $v = '';
});


问:
The view above recyclerview is skipped
I have CardView above RecycleView, but when Page is loaded RecyclerView is  on the top and CardView is skipped. Why can this happen?</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/homeProgress"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:progressTint="@color/colorText"
            android:visibility="visible"/>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/homeMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
            android:padding="10dp"
            android:visibility="gone">

            <androidx.cardview.widget.CardView
                android:id="@+id/firstPlace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorCardView"
                app:cardCornerRadius="10dp"
                android:padding="10dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="10dp">

                        <TextView
                            android:id="@+id/firstPlaceName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="30sp"
                            android:textColor="@color/colorText"/>

                        <TextView
                            android:id="@+id/firstPlaceCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="15sp"
                            android:textColor="@color/colorText"/>

                    </LinearLayout>

                    <ImageView
                        android:id="@+id/firstPlaceImage"
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_alignParentEnd="true"/>

                </RelativeLayout>
            </androidx.cardview.widget.CardView>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/artistsWithImagesRecycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/firstPlace"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:overScrollMode="never"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">

            </androidx.recyclerview.widget.RecyclerView>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>
</code>```

答: align your recyler view to top to bottom of card view</p>

Title: The view above recyclerview is skipped

Body:
I have CardView above RecycleView, but when Page is loaded RecyclerView is  on the top and CardView is skipped. Why can this happen?

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:id="@+id/homeProgress"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            android:progressTint="@color/colorText"
            android:visibility="visible"/>

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/homeMainLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
            android:padding="10dp"
            android:visibility="gone">

            <androidx.cardview.widget.CardView
                android:id="@+id/firstPlace"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/colorCardView"
                app:cardCornerRadius="10dp"
                android:padding="10dp"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="10dp">

                        <TextView
                            android:id="@+id/firstPlaceName"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="30sp"
                            android:textColor="@color/colorText"/>

                        <TextView
                            android:id="@+id/firstPlaceCount"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="15sp"
                            android:textColor="@color/colorText"/>

                    </LinearLayout>

                    <ImageView
                        android:id="@+id/firstPlaceImage"
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_alignParentEnd="true"/>

                </RelativeLayout>
            </androidx.cardview.widget.CardView>

            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/artistsWithImagesRecycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_constraintTop_toBottomOf="@+id/firstPlace"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                android:overScrollMode="never"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager">

            </androidx.recyclerview.widget.RecyclerView>

        </androidx.constraintlayout.widget.ConstraintLayout>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.core.widget.NestedScrollView>


问:
Python Scrapy extract child
I have the following situation:

```<code><div class="question">
    <div class="post-layout">
        <div class="post-text">
            <p> Sample Question </p>
        </div>
    </div>
</div>
</code>```

and

```<code><div class="answer">
    <div class="post-layout">
        <div class="post-text">
            <p> Sample Answer </p>
        </div>
    </div>
</div>
</code>```

I want to extract the text of the question class separately from the answer class.

I tried: response.css('.post-text > p::text').extract() but this extracts the question and answer together.

I tried: response.css('.question > .post-text > p::text').extract() but it doesn't return anything.

I also tried: response.xpath(".//div[@class='question']/div[@class='post-text']/p//text()").extract() but it doesn't return anything.

I am new to Scrapy so maybe I am doing something wrong... any help will be appreciated!!

Thanks!

答:
You are close. The > in your selector asks for a child of what you are selecting. As the
 isn't a direct child of
 it doesn't find it. You can fix this by just removing it

```<code>question = response.css(".question p::text").get()
answer = response.css(".answer p::text").get()
</code>```

Note I use get() instead of extract() just because this is the recommended way to do this now.

Your second attempt doesn't work because you are missing the post-layout class. The correct way to use that approach would be e.g.

```<code>response.css('.question > .post-layout > .post-text > p::text')
</code>```

The xpath equivalents are

```<code>question = response.xpath('//div[@class="question"]//p/text()').get()
answer = response.xpath('//div[@class="answer"]//p/text()').get()
</code>```

Title: Python Scrapy extract child

Body:
I have the following situation:

 Sample Question

and

 Sample Answer

I want to extract the text of the question class separately from the answer class.

I tried: response.css('.post-text > p::text').extract() but this extracts the question and answer together.

I tried: response.css('.question > .post-text > p::text').extract() but it doesn't return anything.

I also tried: response.xpath(".//div[@class='question']/div[@class='post-text']/p//text()").extract() but it doesn't return anything.

I am new to Scrapy so maybe I am doing something wrong... any help will be appreciated!!

Thanks!

Body:
You are close. The > in your selector asks for a child of what you are selecting. As the <p> isn't a direct child of <div class="answer"> it doesn't find it. You can fix this by just removing it

question = response.css(".question p::text").get()
answer = response.css(".answer p::text").get()

Note I use get() instead of extract() just because this is the recommended way to do this now.

Your second attempt doesn't work because you are missing the post-layout class. The correct way to use that approach would be e.g.

response.css('.question > .post-layout > .post-text > p::text')

The xpath equivalents are

question = response.xpath('//div[@class="question"]//p/text()').get()
answer = response.xpath('//div[@class="answer"]//p/text()').get()


答:
From the manual:

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

So you need to change your call to:

array_walk($postCopy, function(&$v, $k) {
  $v = "";
});
```

Note the & in the argument list. The return value of callback is not actually used.

Also, consider using array_map, if you are modifying all elements of an array.

Title: PHP array_walk doesn't change the array's values

Body:
From the manual:

Note:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

So you need to change your call to:

array_walk($postCopy, function(&$v, $k) {
  $v = "";
});

Note the & in the argument list. The return value of callback is not actually used.

Also, consider using array_map, if you are modifying all elements of an array.


问:
phpmyadmin: create a function
i'm trying to create a function in my phpmyadmin - doesnt work .. :/
here's my syntax:

```<code>DELIMITER $$

CREATE FUNCTION fixString(input varchar) RETURNS varchar
BEGIN
  declare output varchar;
  SET output = REPLACE(input,'ö','oe');
  RETURN output;
END $$

DELIMITER ;
</code>```

error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') RETURNS varchar BEGIN declare output varchar; SET output = ' at line 1

any ideas what's wrong?
thanks

答:
You're using VARCHAR, so you have to indicate a max size:

```<code>DELIMITER $$

CREATE FUNCTION fixString(input varchar(15)) RETURNS varchar(15)
BEGIN
  declare output varchar(15);
  SET output = REPLACE(input,'ö','oe');
  RETURN output;
END $$

DELIMITER ;
</code>```

Title: phpmyadmin: create a function

Body:
i'm trying to create a function in my phpmyadmin - doesnt work .. :/
here's my syntax:

DELIMITER $$

CREATE FUNCTION fixString(input varchar) RETURNS varchar
BEGIN
  declare output varchar;
  SET output = REPLACE(input,'ö','oe');
  RETURN output;
END $$

DELIMITER ;

error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') RETURNS varchar BEGIN declare output varchar; SET output = ' at line 1

any ideas what's wrong?
thanks

Body:
You're using VARCHAR, so you have to indicate a max size:

DELIMITER $$

CREATE FUNCTION fixString(input varchar(15)) RETURNS varchar(15)
BEGIN
  declare output varchar(15);
  SET output = REPLACE(input,'ö','oe');
  RETURN output;
END $$

DELIMITER ;