问:
Cannot copy from a TensorFlowLite tensor (Identity_1) with shape [1, 3087, 2] to a Java object with shape [1, 3087]
I'm trying to run a YoloV4 model on Android that's been converted to .tflite. My input shape seems to be fine [1, 224, 224, 4] but the app crashes on my output shape. I'm using code from a Udacity course on tflite.

I get the above error when I run the following code:

```<code>class TFLiteObjectDetectionAPIModel private constructor() : Classifier {
override val statString: String
    get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
private var isModelQuantized: Boolean = false
// Config values.
private var inputSize: Int = 0
// Pre-allocated buffers.
private val labels = Vector<String>()
private var intValues: IntArray? = null
// outputLocations: array of shape [Batchsize, NUM_DETECTIONS,4]
// contains the location of detected boxes
private var outputLocations: Array<Array<FloatArray>>? = null
// outputClasses: array of shape [Batchsize, NUM_DETECTIONS]
// contains the classes of detected boxes
private var outputClasses: Array<FloatArray>? = null
// outputScores: array of shape [Batchsize, NUM_DETECTIONS]
// contains the scores of detected boxes
private var outputScores: Array<FloatArray>? = null
// numDetections: array of shape [Batchsize]
// contains the number of detected boxes
private var numDetections: FloatArray? = null

private var imgData: ByteBuffer? = null

private var tfLite: Interpreter? = null

override fun recognizeImage(bitmap: Bitmap): List<Classifier.Recognition> {
    // Log this method so that it can be analyzed with systrace.
    Trace.beginSection("recognizeImage")

    Trace.beginSection("preprocessBitmap")
    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    bitmap.getPixels(intValues, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)

    imgData!!.rewind()
    for (i in 0 until inputSize) {
        for (j in 0 until inputSize) {
            val pixelValue = intValues!![i * inputSize + j]
            if (isModelQuantized) {
                // Quantized model
                imgData!!.put((pixelValue shr 16 and 0xFF).toByte())
                imgData!!.put((pixelValue shr 8 and 0xFF).toByte())
                imgData!!.put((pixelValue and 0xFF).toByte())
            } else { // Float model
                imgData!!.putFloat(((pixelValue shr 16 and 0xFF) - IMAGE_MEAN) / IMAGE_STD)
                imgData!!.putFloat(((pixelValue shr 8 and 0xFF) - IMAGE_MEAN) / IMAGE_STD)
                imgData!!.putFloat(((pixelValue and 0xFF) - IMAGE_MEAN) / IMAGE_STD)
            }
        }
    }
    Trace.endSection() // preprocessBitmap

    // Copy the input data into TensorFlow.
    Trace.beginSection("feed")
    outputLocations = Array(1) { Array(NUM_DETECTIONS) { FloatArray(4) } }
    outputClasses = Array(1) { FloatArray(NUM_DETECTIONS) }
    outputScores = Array(1) { FloatArray(NUM_DETECTIONS) }
    numDetections = FloatArray(1)

    val inputArray = arrayOf<Any>(imgData!!)
    val outputMap = ArrayMap<Int, Any>()
    outputMap[0] = outputLocations!!
    outputMap[1] = outputClasses!!
    outputMap[2] = outputScores!!
    outputMap[3] = numDetections!!
    Trace.endSection()

    // Run the inference call.
    Trace.beginSection("run")
    tfLite!!.runForMultipleInputsOutputs(inputArray, outputMap)
    Trace.endSection()

    // Show the best detections.
    // after scaling them back to the input size.
    val recognitions = ArrayList<Classifier.Recognition>(NUM_DETECTIONS)
    for (i in 0 until NUM_DETECTIONS) {
        val detection = RectF(
                outputLocations!![0][i][1] * inputSize,
                outputLocations!![0][i][0] * inputSize,
                outputLocations!![0][i][3] * inputSize,
                outputLocations!![0][i][2] * inputSize)
        // SSD Mobilenet V1 Model assumes class 0 is background class
        // in label file and class labels start from 1 to number_of_classes+1,
        // while outputClasses correspond to class index from 0 to number_of_classes
        val labelOffset = 1
        recognitions.add(
                Classifier.Recognition(
                        "" + i,
                        labels[outputClasses!![0][i].toInt() + labelOffset],
                        outputScores!![0][i],
                        detection))
    }
    Trace.endSection() // "recognizeImage"
    return recognitions
}

override fun enableStatLogging(debug: Boolean) {
    //Not implemented
}

override fun close() {
    //Not needed.
}

override fun setNumThreads(numThreads: Int) {
    if (tfLite != null) tfLite!!.setNumThreads(numThreads)
}

override fun setUseNNAPI(isChecked: Boolean) {
    if (tfLite != null) tfLite!!.setUseNNAPI(isChecked)
}

companion object {

    // Only return this many results.
    private const val NUM_DETECTIONS = 3087
    // Float model
    private const val IMAGE_MEAN = 128.0f
    private const val IMAGE_STD = 128.0f

    /** Memory-map the model file in Assets.  */
    @Throws(IOException::class)
    private fun loadModelFile(assets: AssetManager, modelFilename: String): MappedByteBuffer {
        val fileDescriptor = assets.openFd(modelFilename)
        val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
        val fileChannel = inputStream.channel
        val startOffset = fileDescriptor.startOffset
        val declaredLength = fileDescriptor.declaredLength
        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
    }

    /**
     * Initializes a native TensorFlow session for classifying images.
     *
     * @param assetManager The asset manager to be used to load assets.
     * @param modelFilename The filepath of the model GraphDef protocol buffer.
     * @param labelFilename The filepath of label file for classes.
     * @param inputSize The size of image input
     * @param isQuantized Boolean representing model is quantized or not
     */
    @Throws(IOException::class)
    fun create(
            assetManager: AssetManager,
            modelFilename: String,
            labelFilename: String,
            inputSize: Int,
            isQuantized: Boolean): Classifier {
        val d = TFLiteObjectDetectionAPIModel()

        val labelsInput: InputStream?
        val actualFilename = labelFilename.split("file:///android_asset/".toRegex())
                .dropLastWhile { it.isEmpty() }.toTypedArray()[1]
        labelsInput = assetManager.open(actualFilename)
        val br: BufferedReader?
        br = BufferedReader(InputStreamReader(labelsInput!!))
        while (br.readLine()?.let { d.labels.add(it) } != null);
        br.close()

        d.inputSize = inputSize

        try {
            val options = Interpreter.Options()
            options.setNumThreads(4)
            d.tfLite = Interpreter(loadModelFile(assetManager, modelFilename), options)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

        d.isModelQuantized = isQuantized
        // Pre-allocate buffers.
        val numBytesPerChannel: Int = if (isQuantized) {
            1 // Quantized
        } else {
            4 // Floating point
        }
        d.imgData = ByteBuffer.allocateDirect(1 * d.inputSize * d.inputSize * 3 * numBytesPerChannel)
        d.imgData!!.order(ByteOrder.nativeOrder())
        d.intValues = IntArray(d.inputSize * d.inputSize)

        d.outputLocations = Array(1) { Array(NUM_DETECTIONS) { FloatArray(2) } }
        d.outputClasses = Array(1) { FloatArray(NUM_DETECTIONS) }
        d.outputScores = Array(1) { FloatArray(NUM_DETECTIONS) }
        d.numDetections = FloatArray(1)
        return d
    }
}
</code>```

When I change the outputLocation to

```<code>outputLocations = Array(1) { Array(NUM_DETECTIONS) { FloatArray(2) } }
</code>```

I get the following error Cannot copy from a TensorFlowLite tensor (Identity) with shape [1, 3087, 4] to a Java object with shape [1, 3087, 2]

What is Identity and Identity_1? I've looked at my model on Netron and can see both but I'm not sure how to understand the model.

Can anyone help? Is there anything else I can change or is my model just not suitable for mobile platforms?

答:
Cannot copy from a TensorFlowLite tensor (Identity) with shape [1, 25200, 8] to a Java object with shape [1, 80, 80, 255].
I have encountered similar problems and haven't found a solution yet</p>

Body:
I'm trying to run a YoloV4 model on Android that's been converted to .tflite. My input shape seems to be fine [1, 224, 224, 4] but the app crashes on my output shape. I'm using code from a Udacity course on tflite.

I get the above error when I run the following code:

class TFLiteObjectDetectionAPIModel private constructor() : Classifier {
override val statString: String
    get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates.
private var isModelQuantized: Boolean = false
// Config values.
private var inputSize: Int = 0
// Pre-allocated buffers.
private val labels = Vector<String>()
private var intValues: IntArray? = null
// outputLocations: array of shape [Batchsize, NUM_DETECTIONS,4]
// contains the location of detected boxes
private var outputLocations: Array<Array<FloatArray>>? = null
// outputClasses: array of shape [Batchsize, NUM_DETECTIONS]
// contains the classes of detected boxes
private var outputClasses: Array<FloatArray>? = null
// outputScores: array of shape [Batchsize, NUM_DETECTIONS]
// contains the scores of detected boxes
private var outputScores: Array<FloatArray>? = null
// numDetections: array of shape [Batchsize]
// contains the number of detected boxes
private var numDetections: FloatArray? = null

private var imgData: ByteBuffer? = null

private var tfLite: Interpreter? = null

override fun recognizeImage(bitmap: Bitmap): List<Classifier.Recognition> {
    // Log this method so that it can be analyzed with systrace.
    Trace.beginSection("recognizeImage")

    Trace.beginSection("preprocessBitmap")
    // Preprocess the image data from 0-255 int to normalized float based
    // on the provided parameters.
    bitmap.getPixels(intValues, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)

    imgData!!.rewind()
    for (i in 0 until inputSize) {
        for (j in 0 until inputSize) {
            val pixelValue = intValues!![i * inputSize + j]
            if (isModelQuantized) {
                // Quantized model
                imgData!!.put((pixelValue shr 16 and 0xFF).toByte())
                imgData!!.put((pixelValue shr 8 and 0xFF).toByte())
                imgData!!.put((pixelValue and 0xFF).toByte())
            } else { // Float model
                imgData!!.putFloat(((pixelValue shr 16 and 0xFF) - IMAGE_MEAN) / IMAGE_STD)
                imgData!!.putFloat(((pixelValue shr 8 and 0xFF) - IMAGE_MEAN) / IMAGE_STD)
                imgData!!.putFloat(((pixelValue and 0xFF) - IMAGE_MEAN) / IMAGE_STD)
            }
        }
    }
    Trace.endSection() // preprocessBitmap

    // Copy the input data into TensorFlow.
    Trace.beginSection("feed")
    outputLocations = Array(1) { Array(NUM_DETECTIONS) { FloatArray(4) } }
    outputClasses = Array(1) { FloatArray(NUM_DETECTIONS) }
    outputScores = Array(1) { FloatArray(NUM_DETECTIONS) }
    numDetections = FloatArray(1)

    val inputArray = arrayOf<Any>(imgData!!)
    val outputMap = ArrayMap<Int, Any>()
    outputMap[0] = outputLocations!!
    outputMap[1] = outputClasses!!
    outputMap[2] = outputScores!!
    outputMap[3] = numDetections!!
    Trace.endSection()

    // Run the inference call.
    Trace.beginSection("run")
    tfLite!!.runForMultipleInputsOutputs(inputArray, outputMap)
    Trace.endSection()

    // Show the best detections.
    // after scaling them back to the input size.
    val recognitions = ArrayList<Classifier.Recognition>(NUM_DETECTIONS)
    for (i in 0 until NUM_DETECTIONS) {
        val detection = RectF(
                outputLocations!![0][i][1] * inputSize,
                outputLocations!![0][i][0] * inputSize,
                outputLocations!![0][i][3] * inputSize,
                outputLocations!![0][i][2] * inputSize)
        // SSD Mobilenet V1 Model assumes class 0 is background class
        // in label file and class labels start from 1 to number_of_classes+1,
        // while outputClasses correspond to class index from 0 to number_of_classes
        val labelOffset = 1
        recognitions.add(
                Classifier.Recognition(
                        "" + i,
                        labels[outputClasses!![0][i].toInt() + labelOffset],
                        outputScores!![0][i],
                        detection))
    }
    Trace.endSection() // "recognizeImage"
    return recognitions
}

override fun enableStatLogging(debug: Boolean) {
    //Not implemented
}

override fun close() {
    //Not needed.
}

override fun setNumThreads(numThreads: Int) {
    if (tfLite != null) tfLite!!.setNumThreads(numThreads)
}

override fun setUseNNAPI(isChecked: Boolean) {
    if (tfLite != null) tfLite!!.setUseNNAPI(isChecked)
}

companion object {

    // Only return this many results.
    private const val NUM_DETECTIONS = 3087
    // Float model
    private const val IMAGE_MEAN = 128.0f
    private const val IMAGE_STD = 128.0f

    /** Memory-map the model file in Assets.  */
    @Throws(IOException::class)
    private fun loadModelFile(assets: AssetManager, modelFilename: String): MappedByteBuffer {
        val fileDescriptor = assets.openFd(modelFilename)
        val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
        val fileChannel = inputStream.channel
        val startOffset = fileDescriptor.startOffset
        val declaredLength = fileDescriptor.declaredLength
        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
    }

    /**
     * Initializes a native TensorFlow session for classifying images.
     *
     * @param assetManager The asset manager to be used to load assets.
     * @param modelFilename The filepath of the model GraphDef protocol buffer.
     * @param labelFilename The filepath of label file for classes.
     * @param inputSize The size of image input
     * @param isQuantized Boolean representing model is quantized or not
     */
    @Throws(IOException::class)
    fun create(
            assetManager: AssetManager,
            modelFilename: String,
            labelFilename: String,
            inputSize: Int,
            isQuantized: Boolean): Classifier {
        val d = TFLiteObjectDetectionAPIModel()

        val labelsInput: InputStream?
        val actualFilename = labelFilename.split("file:///android_asset/".toRegex())
                .dropLastWhile { it.isEmpty() }.toTypedArray()[1]
        labelsInput = assetManager.open(actualFilename)
        val br: BufferedReader?
        br = BufferedReader(InputStreamReader(labelsInput!!))
        while (br.readLine()?.let { d.labels.add(it) } != null);
        br.close()

        d.inputSize = inputSize

        try {
            val options = Interpreter.Options()
            options.setNumThreads(4)
            d.tfLite = Interpreter(loadModelFile(assetManager, modelFilename), options)
        } catch (e: Exception) {
            throw RuntimeException(e)
        }

        d.isModelQuantized = isQuantized
        // Pre-allocate buffers.
        val numBytesPerChannel: Int = if (isQuantized) {
            1 // Quantized
        } else {
            4 // Floating point
        }
        d.imgData = ByteBuffer.allocateDirect(1 * d.inputSize * d.inputSize * 3 * numBytesPerChannel)
        d.imgData!!.order(ByteOrder.nativeOrder())
        d.intValues = IntArray(d.inputSize * d.inputSize)

        d.outputLocations = Array(1) { Array(NUM_DETECTIONS) { FloatArray(2) } }
        d.outputClasses = Array(1) { FloatArray(NUM_DETECTIONS) }
        d.outputScores = Array(1) { FloatArray(NUM_DETECTIONS) }
        d.numDetections = FloatArray(1)
        return d
    }
}

When I change the outputLocation to

outputLocations = Array(1) { Array(NUM_DETECTIONS) { FloatArray(2) } }

I get the following error Cannot copy from a TensorFlowLite tensor (Identity) with shape [1, 3087, 4] to a Java object with shape [1, 3087, 2]

What is Identity and Identity_1? I've looked at my model on Netron and can see both but I'm not sure how to understand the model.

Can anyone help? Is there anything else I can change or is my model just not suitable for mobile platforms?


来源: stackexchange

问:
Setting up a React application and NodeJS backend in Kubernetes?
I am trying to setup a sample React application wired to a NodeJS backend as two pods in Kubernetes. This is the (mostly) the default CRA and NodeJS application with Express i.e. npx create-react-app my_app.

Both application runs fine locally through yarn start and npm app.js respectively. The React application uses a proxy defined in package.json to communicate with the NodeJS back-end.

React package.json

```<code>...
  "proxy": "http://localhost:3001/"
...
</code>```

React Dockerfile

```<code>FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn
COPY . .
CMD [ "yarn", "start" ]
</code>```

NodeJS Dockerfile

```<code>FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD [ "node", "app.js" ]
</code>```

ui-deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-ui
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-ui
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-ui
    spec:
      containers:
      -
        name: sample-ui
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi
</code>```

server-deployment

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-server
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-server
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-server
    spec:
      containers:
      -
        name: sample-server
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3001
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi
</code>```

ui-service

```<code>apiVersion: v1
kind: Service
metadata:
  name: sample-ui
  namespace: my_namespace
  labels: {app: sample-ui}
spec:
  type: LoadBalancer
  selector:
    component: sample-ui
  ports:
  - name: listen
    protocol: TCP
    port: 3000
</code>```

server-service

```<code>apiVersion: v1
kind: Service
metadata:
  name: sample-server
  namespace: my_namespace
  labels: {app: sample-server}
spec:
  selector:
    component: sample-server
  ports:
  - name: listen
    protocol: TCP
    port: 3001
</code>```

Both services run fine on my system.

get svc

```<code>sample-server            ClusterIP      10.19.255.171   <none>           3001/TCP                     26m
sample-ui                LoadBalancer   10.19.242.42    34.82.235.125    3000:31074/TCP               26m
</code>```

However, my deployment for the CRA crashes multiple time despite indicating it is still running.

get pods

```<code>sample-server-598776c5fc-55jsz                     1/1     Running     0          42m
sample-ui-c75ccb746-qppk2                          1/1     Running     4          2m38s
</code>```

I suspect that my React Dockerfile is improperly configured but I'm not sure how to write it to work with a NodeJS backend in kubernetes.

a) How can I setup my Dockerfile for my CRA such that it will run in a pod?

b) How can I setup my docker services and pods such that they communicate?

答:
You will have to use come API gateway in front of your server or you can use ambassador from kubernetes.

Then you can get your client connected to server.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to setup a sample React application wired to a NodeJS backend as two pods in Kubernetes. This is the (mostly) the default CRA and NodeJS application with Express i.e. npx create-react-app my_app.

Both application runs fine locally through yarn start and npm app.js respectively. The React application uses a proxy defined in package.json to communicate with the NodeJS back-end.

React package.json

...
  "proxy": "http://localhost:3001/"
...

React Dockerfile

FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN yarn
COPY . .
CMD [ "yarn", "start" ]

NodeJS Dockerfile

FROM node:10
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3001
CMD [ "node", "app.js" ]

ui-deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-ui
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-ui
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-ui
    spec:
      containers:
      -
        name: sample-ui
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi

server-deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
    name: sample-server
    namespace: my_namespace
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my_namespace
      component: sample-server
  template:
    metadata:
      labels:
        app: my_namespace
        component: sample-server
    spec:
      containers:
      -
        name: sample-server
        image: xxx
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3001
          name: http
          protocol: TCP
        resources:
          limits:
            cpu: 100m
            memory: 128Mi
          requests:
            cpu: 100m
            memory: 128Mi

ui-service

apiVersion: v1
kind: Service
metadata:
  name: sample-ui
  namespace: my_namespace
  labels: {app: sample-ui}
spec:
  type: LoadBalancer
  selector:
    component: sample-ui
  ports:
  - name: listen
    protocol: TCP
    port: 3000

server-service

apiVersion: v1
kind: Service
metadata:
  name: sample-server
  namespace: my_namespace
  labels: {app: sample-server}
spec:
  selector:
    component: sample-server
  ports:
  - name: listen
    protocol: TCP
    port: 3001

Both services run fine on my system.

get svc

sample-server            ClusterIP      10.19.255.171   <none>           3001/TCP                     26m
sample-ui                LoadBalancer   10.19.242.42    34.82.235.125    3000:31074/TCP               26m

However, my deployment for the CRA crashes multiple time despite indicating it is still running.

get pods

sample-server-598776c5fc-55jsz                     1/1     Running     0          42m
sample-ui-c75ccb746-qppk2                          1/1     Running     4          2m38s

I suspect that my React Dockerfile is improperly configured but I'm not sure how to write it to work with a NodeJS backend in kubernetes.

a) How can I setup my Dockerfile for my CRA such that it will run in a pod?

b) How can I setup my docker services and pods such that they communicate?


问:
Sending mails everyday using schedulers in Laravel
I am not receiving any email. Please help me out. I have changed the environment properly.

```<code>use App\User;
use App\Mail\NotifyEmail;

class Notify extends Command
{
    protected $signature = 'notify:email';
    protected $description = 'Send an email to all the users everyday';
    public function handle()
    {
        $emails = User::pluck('email')->toArray();
        $data = ['title' => 'programming' , 'body' => 'php'];
        foreach($emails as $email){
            Mail::To($email) ->send(new NotifyEmail($data));
        }
    }
}

</code>```

My kernel.php has :

```<code>$schedule->command('notify:email') ->daily();
</code>```

App\Mail\NotifyEmail.php :

```<code>class NotifyEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $details;
    public function __construct($data)
    {
        $this -> details = $data;
    }

    public function build()
    {
        return $this->view('mail', compact(varname: 'details'));
    }
}
</code>```

mail.blade.php contains {{$details['title']}} and {{$details['body']}}.

答: If it is a Queueable, you will need a separate process to run the queue continuously. Without that process, the queue entries just stack up and never get processed. See the Laravel Queue documentation https://laravel.com/docs/9.x/queues#running-the-queue-worker about running queues and/or run artisan queue:work</p>

Body:
I am not receiving any email. Please help me out. I have changed the environment properly.

use App\User;
use App\Mail\NotifyEmail;

class Notify extends Command
{
    protected $signature = 'notify:email';
    protected $description = 'Send an email to all the users everyday';
    public function handle()
    {
        $emails = User::pluck('email')->toArray();
        $data = ['title' => 'programming' , 'body' => 'php'];
        foreach($emails as $email){
            Mail::To($email) ->send(new NotifyEmail($data));
        }
    }
}

My kernel.php has :

$schedule->command('notify:email') ->daily();

App\Mail\NotifyEmail.php :

class NotifyEmail extends Mailable
{
    use Queueable, SerializesModels;
    public $details;
    public function __construct($data)
    {
        $this -> details = $data;
    }

    public function build()
    {
        return $this->view('mail', compact(varname: 'details'));
    }
}

mail.blade.php contains {{$details['title']}} and {{$details['body']}}.


问:
AWS Cloudfront and ELB Security Groups
does anyone know how to add your cloudfront distro into the security group inbound rules for an ELB?

We have a cloudfront distro setup for a new site which has a whitelisted set of security group rules for its origin.  I cant see how to configure the security group to allow requests from the cloudfront distro...

any ideas?

答:
Beginning February 2022, you should use AWS Managed Prefix List. They are a list of IPs managed by AWS, and kept up to date by them, that you can use in your route tables and security groups.

Be advised, the Amazon CloudFront managed prefix list counts as 55 rules in a security group. The default quota is 60 rules, leaving room for only 5 additional rules in a security group. You should request a quota increase for this quota. It counts as 55 routes in a route table. The default quota is 50 routes, so you must request a quota increase before you can add the prefix list to a route table.

ContentLicense: CC BY-SA 3.0

Title: AWS Cloudfront and ELB Security Groups


问:
How to POST the json payload data inside a telegram chat using the bot API?
I only get the text "1111" mentioned in the url as the output inside telegram chat and not the json data written inside the code.</p>
```<code>import requests
from requests.structures import CaseInsensitiveDict

url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage? chat_id=@alerttest&text=1111"

headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"

data = """
    {
     "stocks": "SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO"
     }
      """"

     resp = requests.post(url, headers=headers, data=data)

     print(resp.status_code)
</code>```
<p>     </p>

答:
You are probably confused about the working of HTTP methods and Telegram API methods.

First step: Telegram sendMessage works with POST HTTP method.

It requires the text parameter, passed as GET parameter: otherwise you'll send an empty message.

This means, that if you're willing to include the JSON payload as text message you have to include your JSON attribute's values into the Telegram sendMessage text parameter, otherwise you won't be able to see that into the final message.

Body:
I only get the text "1111" mentioned in the url as the output inside telegram chat and not the json data written inside the code.

import requests
from requests.structures import CaseInsensitiveDict

url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage? chat_id=@alerttest&text=1111"

headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"

data = """
    {
     "stocks": "SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO"
     }
      """"

     resp = requests.post(url, headers=headers, data=data)

     print(resp.status_code)


问:
why numpy.array is built-in?
According to https://docs.python.org/3/library/functions.html,
the "built-in function" means a python-innate function such as print or sum.

However, type(numpy.array) results in builtin_function_or_method even though the numpy module is not python-innate.

Why does it happen?

答:
Because builtin_function_or_method is not really testing if it is a built in (which is rather a bit ambiguous term). Rather, it tests if a function or method was written in C.

From the official document:

types.BuiltinFunctionType

types.BuiltinMethodType

The type of built-in functions like len() or sys.exit(), and methods of built-in classes. (Here, the term “built-in” means “written in C”.)

Title: why numpy.array is built-in?


问:
Spring: re-initialized a bean
This is my Spring bean in the configuration class that creates a gRPC ManagedChannel:

```<code>@Configuration
public class CockroachDbConfig {

 @Bean
 public ManagedChannel getManagedChannel() {
    return ManagedChannelBuilder.forTarget(CR_GRPC_SERVER)
        .usePlaintext()
        .build();
   }
 }
</code>```

The controller method is provided below:

```<code>@RestController
public class DBProxyController {

    @Autowired
    private DBProxyService dbProxyService;

    @RequestMapping(value = "/", method = RequestMethod.POST,
        consumes = APPLICATION_JSON_VALUE,
        produces = APPLICATION_JSON_VALUE
    )
    @SuppressWarnings("BlockingMethodInNonBlockingContext")
    public Mono<Void> handleRequest(@RequestBody String requestBody, ServerHttpResponse serverHttpResponse, ServerHttpRequest request)  {

        org.springframework.http.HttpHeaders headers = request.getHeaders();

        Map<String, String> responseMap = dbProxyService.processRequest(requestBody, headers);

        String response = responseMap.get(X_AMZN_RESPONSE);

        if (response.equalsIgnoreCase("{}")) {
            LOGGER.info("We are ot able to sucessfully process the request and reutning an empty response");
        }

        return serverHttpResponse.writeWith(strToDataBuffer(response));
    }
}
</code>```

The service class is:

```<code>@Service
public class DBProxyService {

    public Map<String, String> processRequest(final String requestBody, final org.springframework.http.HttpHeaders headers)  {

        ManagedChannel customManagedChannel = (new CockroachDbConfig()).getManagedChannel();

        switch (action) {

            case GETITEM:
            {

                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }
            case PUTITEM:
            {
                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }

        }

    }

}
</code>```

For each request, I create a new ManagedChannel in the service method processRequest and shut it down using the method called shutdownManagedChannel.

Earlier, I try to use the @Autowired for the managed channel as below:

```<code>@Service
public class DBProxyService {

    @Autowired
    private ManagedChannel customManagedChannel;

    public Map<String, String> processRequest(final String requestBody, final org.springframework.http.HttpHeaders headers)  {

        switch (action) {

            case GETITEM:
            {

                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }
            case PUTITEM:
            {
                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }

        }

    }

}
</code>```

This was not successful as I shut down the channel after the completion of each request and I guess need to figure out a way to re-initialize the bean for each call.

So, how to I re-initialize the ManagedChannel for each request when the app is running?

Thanks.

答:
A simple solution, not relying too much on the framework would be to inject a bean of type Supplier<ManagedChannel> (or any other functional interface type that works for your use case).

@Bean
public Suuplier<ManagedChannel> getManagedChannel() {
  return () -> ManagedChannelBuilder.forTarget(CR_GRPC_SERVER)
      .usePlaintext()
      .build();
}
```

And then use the get method to re-instantiate a new channel whenever you need it.

Otherwise, you could work with the scope Prototype that recreates the bean in some circumstances instead of treating it as a singleton (documentation). Be aware that injecting prototype beans in singleton beans require you to do some configuration gymnastic, as stated in the point 1.5.3 of the documentation.

Title: Spring: re-initialized a bean

Body:
This is my Spring bean in the configuration class that creates a gRPC ManagedChannel:

@Configuration
public class CockroachDbConfig {

 @Bean
 public ManagedChannel getManagedChannel() {
    return ManagedChannelBuilder.forTarget(CR_GRPC_SERVER)
        .usePlaintext()
        .build();
   }
 }

The controller method is provided below:

@RestController
public class DBProxyController {

    @Autowired
    private DBProxyService dbProxyService;

    @RequestMapping(value = "/", method = RequestMethod.POST,
        consumes = APPLICATION_JSON_VALUE,
        produces = APPLICATION_JSON_VALUE
    )
    @SuppressWarnings("BlockingMethodInNonBlockingContext")
    public Mono<Void> handleRequest(@RequestBody String requestBody, ServerHttpResponse serverHttpResponse, ServerHttpRequest request)  {

        org.springframework.http.HttpHeaders headers = request.getHeaders();

        Map<String, String> responseMap = dbProxyService.processRequest(requestBody, headers);

        String response = responseMap.get(X_AMZN_RESPONSE);

        if (response.equalsIgnoreCase("{}")) {
            LOGGER.info("We are ot able to sucessfully process the request and reutning an empty response");
        }

        return serverHttpResponse.writeWith(strToDataBuffer(response));
    }
}

The service class is:

@Service
public class DBProxyService {

    public Map<String, String> processRequest(final String requestBody, final org.springframework.http.HttpHeaders headers)  {

        ManagedChannel customManagedChannel = (new CockroachDbConfig()).getManagedChannel();

        switch (action) {

            case GETITEM:
            {

                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }
            case PUTITEM:
            {
                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }

        }

    }

}

For each request, I create a new ManagedChannel in the service method processRequest and shut it down using the method called shutdownManagedChannel.

Earlier, I try to use the @Autowired for the managed channel as below:

@Service
public class DBProxyService {

    @Autowired
    private ManagedChannel customManagedChannel;

    public Map<String, String> processRequest(final String requestBody, final org.springframework.http.HttpHeaders headers)  {

        switch (action) {

            case GETITEM:
            {

                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }
            case PUTITEM:
            {
                // some code
                ProtoService.shutdownManagedChannel(customManagedChannel);
            }

        }

    }

}

This was not successful as I shut down the channel after the completion of each request and I guess need to figure out a way to re-initialize the bean for each call.

So, how to I re-initialize the ManagedChannel for each request when the app is running?

Thanks.

Body:
A simple solution, not relying too much on the framework would be to inject a bean of type Supplier<ManagedChannel> (or any other functional interface type that works for your use case).

@Bean
public Suuplier<ManagedChannel> getManagedChannel() {
  return () -> ManagedChannelBuilder.forTarget(CR_GRPC_SERVER)
      .usePlaintext()
      .build();
}

And then use the get method to re-instantiate a new channel whenever you need it.

Otherwise, you could work with the scope Prototype that recreates the bean in some circumstances instead of treating it as a singleton (documentation). Be aware that injecting prototype beans in singleton beans require you to do some configuration gymnastic, as stated in the point 1.5.3 of the documentation.


问:
Ant Design: remove the divider line between table rows
When making a Table in Ant Design, there are always gray divider lines between each row. Is there a way to style these divider lines or completely remove them from the table?</p>

答:
if you are using css-modules in your Nextjs application, you can override table styles like this:

in them component file:

```<code>import classes from './Comp.module.css';
function Comp(props){
  ...
  return (
    <Table
       ...
       className={classes.customTable}
   />
  )
}
</code>```

and in the Comp.module.css file:

```<code>.customTable .ant-table-tbody > tr > td{
    border: none
}
</code>```

Body:
if you are using css-modules in your Nextjs application, you can override table styles like this:

in them component file:

import classes from './Comp.module.css';
function Comp(props){
  ...
  return (
    <Table
       ...
       className={classes.customTable}
   />
  )
}

and in the Comp.module.css file:

.customTable .ant-table-tbody > tr > td{
    border: none
}


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
use update() method of dict:</p>

```<code>d.update((k,s.index(k)) for k in d.iterkeys())
</code>```

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
use update() method of dict:

d.update((k,s.index(k)) for k in d.iterkeys())


问:
How to send special characters via mail from a shell script?
I have a script that runs on cron that outputs some text which we send to the 'mail' program. The general line is like this:

```<code>./command.sh | mail -s "My Subject" destination@address.com -- -F "Sender Name" -f sender@address.com
</code>```

The problem is that the text generated by the script has some special characters - é, ã, ç - since it is not in english. When the e-mail is received, each character is replaced by ??.

Now I understand that this is most likely due to the encoding that is not set correctly. What is the easiest way to fix this?

答:
I'm a bit late but none of the previous solutions worked for me.

Locating mail command (CentOS)

```<code># locate mail | grep -v www | grep -v yum | grep -v share
# ls -l /bin/mail
lrwxrwxrwx. 1 root root 22 jul 21  2016 /bin/mail -> /etc/alternatives/mail
# ls -l /etc/alternatives/mail
lrwxrwxrwx. 1 root root 10 jul 21  2016 /etc/alternatives/mail -> /bin/mailx
# ls -l /bin/mailx
-rwxr-xr-x. 1 root root 390744 dic 16  2014 /bin/mailx
</code>```

So mail command is in fact mailx. This helped with the search that finally took me to this answer at Unix&Linux Stackexchange that states:

Mailx expects input text to be in Unix format, with lines separated by newline (^J, \n) characters only. Non-Unix text files that use carriage return (^M, \r) characters in addition will be treated as binary data; to send such files as text, strip these characters e. g. by tr -d '\015'

From man page and:

If there are other control characters in the file they will result on mailx treating the data as binary and will then attach it instead of using it as the body. The following will strip all special characters and place the contents of the file into the message body

So the solution is using tr command to remove those special characters. Something like this:

```<code>./command.sh \
| tr -cd "[:print:]\n" \
| mail -s "My Subject" destination@address.com -- -F "Sender Name" -f sender@address.com
</code>```

I've used this solution with my command

```<code>grep -v "pattern" $file \
| grep -v "another pattern" \
| ... several greps more ... \
| tr -cd "[:print:]\n" \
| mail -s "$subject" -a $file -r '$sender' $destination_email
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a script that runs on cron that outputs some text which we send to the 'mail' program. The general line is like this:

./command.sh | mail -s "My Subject" destination@address.com -- -F "Sender Name" -f sender@address.com

The problem is that the text generated by the script has some special characters - é, ã, ç - since it is not in english. When the e-mail is received, each character is replaced by ??.

Now I understand that this is most likely due to the encoding that is not set correctly. What is the easiest way to fix this?

Body:
I'm a bit late but none of the previous solutions worked for me.

Locating mail command (CentOS)

# locate mail | grep -v www | grep -v yum | grep -v share
# ls -l /bin/mail
lrwxrwxrwx. 1 root root 22 jul 21  2016 /bin/mail -> /etc/alternatives/mail
# ls -l /etc/alternatives/mail
lrwxrwxrwx. 1 root root 10 jul 21  2016 /etc/alternatives/mail -> /bin/mailx
# ls -l /bin/mailx
-rwxr-xr-x. 1 root root 390744 dic 16  2014 /bin/mailx

So mail command is in fact mailx. This helped with the search that finally took me to this answer at Unix&Linux Stackexchange that states:

Mailx expects input text to be in Unix format, with lines separated by newline (^J, \n) characters only. Non-Unix text files that use carriage return (^M, \r) characters in addition will be treated as binary data; to send such files as text, strip these characters e. g. by tr -d '\015'

From man page and:

If there are other control characters in the file they will result on mailx treating the data as binary and will then attach it instead of using it as the body. The following will strip all special characters and place the contents of the file into the message body

So the solution is using tr command to remove those special characters. Something like this:

./command.sh \
| tr -cd "[:print:]\n" \
| mail -s "My Subject" destination@address.com -- -F "Sender Name" -f sender@address.com

I've used this solution with my command

grep -v "pattern" $file \
| grep -v "another pattern" \
| ... several greps more ... \
| tr -cd "[:print:]\n" \
| mail -s "$subject" -a $file -r '$sender' $destination_email


问:
double quote coin flip
```<code>import random
input("You tossed a coin. Select 0 or 1\n" )
random_side = random.randint(0, 1)
if random_side == 1:
  print("Heads")
else:
  print("Tails")
</code>```

when I use double quote in 1(if random_side == "1":). It gives me same output not random outcome.

答:
A much simpler way to choose heads or tails would be random.choice(). See below:

```<code>from random import choice
print(choice(['heads', 'tails'])) # Or assign this to a variable
</code>```

Please read up on the random modules.

Title: double quote coin flip

Body:
import random
input("You tossed a coin. Select 0 or 1\n" )
random_side = random.randint(0, 1)
if random_side == 1:
  print("Heads")
else:
  print("Tails")

when I use double quote in 1(if random_side == "1":). It gives me same output not random outcome.

Body:
A much simpler way to choose heads or tails would be random.choice(). See below:

from random import choice
print(choice(['heads', 'tails'])) # Or assign this to a variable

Please read up on the random modules.


问:
How do I make .gitlab-ci.yml execute different ansible playbooks in different folders/subfolders?
I just started learning about NetDevOps.

All the examples containing demos of GitLAb + Ansible show how to execute "deploy.yml" from Ansible from the .gitlab-ci.yml.

However, when I see a general network equipment based Ansible tutorial the author executes different Ansible cookbook .yml files, for example sites.yml from the root, deploy.yml from another subfolder, interfaces.yml from another subfolder.

Can someone give me an example of how I would execute the different Ansible playbook .yml files on demand?

I.e. - When it detects changes in .yml in a folder, run that .yml file under that folder?

答:
You can use in your GitLab job complex rules like if, changes, and exists, in the same rule.

The rule evaluates to true only when all included keywords evaluate to true.

For example:

docker build:
 script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
 rules:
   - if: '$VAR == "string value"'
     changes:  # Include the job and set to when:manual if any of the follow paths match a modified file.
       - Dockerfile
       - docker/scripts/*
     when: manual
     allow_failure: true
```

In your case, keep when: manual and changes: *.yml in order to trigger the job manually, if yml Ansible playbook are changed.

Body:
You can use in your GitLab job complex rules like if, changes, and exists, in the same rule.

The rule evaluates to true only when all included keywords evaluate to true.

For example:

docker build:
 script: docker build -t my-image:$CI_COMMIT_REF_SLUG .
 rules:
   - if: '$VAR == "string value"'
     changes:  # Include the job and set to when:manual if any of the follow paths match a modified file.
       - Dockerfile
       - docker/scripts/*
     when: manual
     allow_failure: true

In your case, keep when: manual and changes: *.yml in order to trigger the job manually, if yml Ansible playbook are changed.


问:
Passing images between screens in flutterwith pushNamed
I am using onGenerate route for my flutter app, when I try to pass an image as an argument using push named I default to error page without any error message!!

Home Screen

the car has already been initialized in the home screen as final AssetImage car_image;

onTap: () {Navigator.of(context).pushNamed('/details', arguments: DetailScreen(data:data ,image: car.car_image));},

DetailScreen

class DetailScreen extends StatelessWidget {

```<code>final AssetImage image;
DetailScreen({Key key, this.image, this.data}) : super(key: key);```

```

答:
Hope this can help someone in future.
Prefer using named routes as passing arguments through them is much more defined and easy.
In your case define the Details route in your main dart file
DetailsScreen.routeName: (ctx) => DetailsScreen(),
after which from the screen that you are routing from pass the arguments that you need to the Details screen,after that accept the arguments using the
ModalRoute.of(context)!.settings.arguments as Map<String, dynamic> method,retrieve the data and you are good to go.</p>

Body:
I am using onGenerate route for my flutter app, when I try to pass an image as an argument using push named I default to error page without any error message!!

Home Screen

the car has already been initialized in the home screen as final AssetImage car_image;

onTap: () {Navigator.of(context).pushNamed('/details', arguments: DetailScreen(data:data ,image: car.car_image));},

DetailScreen

class DetailScreen extends StatelessWidget {

final AssetImage image;
DetailScreen({Key key, this.image, this.data}) : super(key: key);```


问:
How to solve Matplotlib and Dataframe confusion?

import pandas as pd
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image

app_root = Tk()

#Setting it up
img = ImageTk.PhotoImage(Image.open("predictsodapng.png"))

#Displaying it
imglabel = Label(app_root, image=img).grid(row=0, column=0)

app_root.title("Predict Soda")
app_root.geometry("800x600")

app_root.mainloop()

def show_entry_fields():
    print("Bit Diameter as cms: %s\nWell Name: %s" % (float(e1.get()), e2.get()))

master = tk.Tk()
tk.Label(master,
         text="Bit Diameter as cms").grid(row=0)
tk.Label(master,
         text="Well Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

e1_float = 0.0          # Storage for results on exit
e2_string = ""          # Storage for results on exit

def get_float( entry ):
    """ Converts the characters in an Entry to a float,
        returns 0.0 if not a valid float"""
    try:
        return float( entry.get() )
    except ValueError:
        return 0.0

def save_and_quit():
    global e1_float, e2_string
    e1_float = get_float( e1 )
    e2_string = e2.get()
    print( type( 'e1'),  'e1', type(e1), e1 )   # Prints to see what happens.
    print( type( e1.get()), e1.get(), type(e1_float), e1_float )
    master.destroy()

tk.Button(master,
          text='Save & Quit',
          command=save_and_quit).grid(row=3,
                                      column=0,
                                      sticky=tk.W,
                                      pady=4)
tk.Button(master,
          text='Show', command=show_entry_fields).grid(row=3,
                                                       column=1,
                                                       sticky=tk.W,
                                                       pady=4)

tk.mainloop()

from tkinter import filedialog

app_root_r = Tk()

file = filedialog.askopenfilename()

if file:
        try:
            filename = r"{}".format(file)
            df = pd.read_excel(file)
        except ValueError:
            label.config(text="File could not be opened")
        except FileNotFoundError:
            label.config(text="File Not Found")

data = df.loc[df['WELL'] == e2_string ][['DEPTH_MD', 'CALIPER', 'GR', 'LITHOLOGY', 'SHALLOW', 'DEEP']]

e1_float = e1_float * 30/100 + e1_float

df.loc[(df.GR < 30.0000) & (df.CALIPER > e1_float) & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'
df.loc[(df.GR > 100.0000) , "LITHOLOGY"] = '3'
df.LITHOLOGY.fillna('2', inplace=True)

df.to_excel(file)

df = pd.read_excel(file)

app_root_r.mainloop()

lithology_numbers = {1: {'lith':'Trona', 'lith_num':1, 'hatch': '+', 'color':'aqua'},
                 2: {'lith':'Shale, Claystone', 'lith_num':2, 'hatch':'-.', 'color':'black'},
                 3: {'lith':'Tuff', 'lith_num':3, 'hatch':'o', 'color':'orange'}}
df_lith = pd.DataFrame.from_dict(lithology_numbers, orient='index')
df_lith.index.name = 'LITHOLOGY'
df_lith

y = [0, 1]
x = [1, 1]

from matplotlib import pyplot as plt

fig, axes = plt.subplots(ncols=4,nrows=3, sharex=True, sharey=True,
                         figsize=(10,5), subplot_kw={'xticks': [], 'yticks': []})

for ax, key in zip(axes.flat, lithology_numbers.keys()):
    ax.plot(x, y)
    ax.fill_betweenx(y, 0, 1, facecolor=lithology_numbers[key]['color'], hatch=lithology_numbers[key]['hatch'])
    ax.set_xlim(0, 0.1)
    ax.set_ylim(0, 1)
    ax.set_title(str(lithology_numbers[key]['lith']))

plt.tight_layout()
plt.show()

def makeplot(well, top_depth, bottom_depth):
    fig, ax = plt.subplots(figsize=(15,10))

    ax1 = plt.subplot2grid((1,5), (0,0), rowspan=1, colspan = 1)
    ax5 = ax1.twiny()
    ax2 = plt.subplot2grid((1,5), (0,1), rowspan=1, colspan = 1, sharey = ax1)
    ax3 = ax2.twiny() #Twins the y-axis for the density track with the neutron track
    ax4 = plt.subplot2grid((1,5), (0,3), rowspan=1, colspan = 1, sharey = ax1)
    ax6 = plt.subplot2grid((1,5), (0,2), rowspan=1, colspan = 1, sharey = ax1)
    ax7 = ax6.twiny()

    ax10 = ax1.twiny()
    ax10.xaxis.set_visible(False)
    ax11 = ax2.twiny()
    ax11.xaxis.set_visible(False)
    ax13 = ax4.twiny()
    ax13.xaxis.set_visible(False)
    ax14 = ax6.twiny()
    ax14.xaxis.set_visible(False)

    # Gamma Ray track
    ax1.plot(well["GR"], well['DEPTH_MD'], color = "green", linewidth = 0.5)
    ax1.set_xlabel("Gamma")
    ax1.xaxis.label.set_color("green")
    ax1.set_xlim(0, 200)
    ax1.set_ylabel("Depth (m)")
    ax1.tick_params(axis='x', colors="green")
    ax1.spines["top"].set_edgecolor("green")
    ax1.title.set_color('green')
    ax1.set_xticks([0, 50, 100, 150, 200])

    # Caliper track
    ax2.plot(well["CALIPER"], well['DEPTH_MD'], color = "red", linewidth = 0.5)
    ax2.set_xlabel("Caliper")
    ax2.set_xlim(0, 50)
    ax2.xaxis.label.set_color("red")
    ax2.tick_params(axis='x', colors="red")
    ax2.spines["top"].set_edgecolor("red")
    ax2.set_xticks([0, 10, 20, 30, 40, 50])

  # Resistivity track placed ontop of density track(SHALLOW)
    ax6.plot(well["SHALLOW"], well['DEPTH_MD'], color = "blue", linewidth = 0.5)
    ax6.set_xlabel('Resistivity')
    ax6.xaxis.label.set_color("blue")
    ax6.set_xlim(0, 15)
    ax6.tick_params(axis='x', colors="blue")
    ax6.spines["top"].set_position(("axes", 1.08))
    ax6.spines["top"].set_visible(True)
    ax6.spines["top"].set_edgecolor("blue")
    ax6.set_xticks([0, 1, 2, 15])

  # Resistivity (deep)
    ax7.plot(well["DEEP"], well['DEPTH_MD'], color = "blue", linewidth = 0.5)
    ax7.xaxis.label.set_color("blue")
    ax7.tick_params(axis='x', colors="blue")
    ax7.spines["top"].set_position(("axes", 1.08))
    ax7.spines["top"].set_visible(True)
    ax7.spines["top"].set_edgecolor("blue")
    ax7.set_xticks([1, 2, 15])

    # Lithology track
    ax4.plot(well["LITHOLOGY"], well['DEPTH_MD'], color = "black", linewidth = 0.5)
    ax4.set_xlabel("Lithology")
    ax4.xaxis.label.set_color("black")
    ax4.set_xlim(0,1)
    ax4.tick_params(axis='x', colors="black")
    ax4.spines["top"].set_edgecolor("black")

    for key in lithology_numbers.keys():
        color = lithology_numbers[key]['color']
        hatch = lithology_numbers[key]['hatch']
        ax4.fill_betweenx(well['DEPTH_MD'], 0, well['LITHOLOGY'], where=(well['LITHOLOGY']==key),
                         facecolor=color, hatch=hatch)

    ax4.set_xticks([0, 1])

    for ax in [ax1, ax2, ax4, ax6]:
        ax.set_ylim(bottom_depth, top_depth)
        ax.grid(which='major', color='lightgrey', linestyle='-')
        ax.xaxis.set_ticks_position("top")
        ax.xaxis.set_label_position("top")
        ax.spines["top"].set_position(("axes", 1.02))

    for ax in [ax2, ax3, ax4, ax6]:
        plt.setp(ax.get_yticklabels(), visible = False)

    plt.tight_layout()
    fig.subplots_adjust(wspace = 0.15)

    for key in lithology_numbers.keys():
     color = lithology_numbers[key]['color']
     hatch = lithology_numbers[key]['hatch']
     ax4.fill_betweenx(well['DEPTH_MD'], 0, well['LITHOLOGY'],
                      where=(well['LITHOLOGY']==key),
                      facecolor=color, hatch=hatch)

makeplot(data, 230,330)

plt.savefig("input.jpg")

from PIL import ImageTk, Image

root = Tk()

img = ImageTk.PhotoImage(Image.open("input.jpg"))

l=Label(image=img)

l.pack()

root.mainloop()

```

I have these codes, in order to make comparison and plot. And also Im trying to create an interface using tkinter. I use the LITHOLOGY column for drawing after printing. On the other hand, tkinter uses the first version of this printed excel file instead of the current one(you can see in the first picture). However, when I run the same codes again, i.e. run the same for the second time, you can see the result in second picture(this shows how my output should be). There is no problem as the LITHOLOGY column is already printed to the excel file when i run it for the second time. I want to eliminate this problem. I have to draw the data directly from the dataframe, but when I replace the well[LITHOLOGY] with df[LITHOLOGY], it only shows the values instead of drawing and painting as you can see in the third figure. How can I solve it? Thanks.

答:
Your problem is the order you do your operations.  Look at what you do:

```<code>df = pd.read_excel(file)
...
data = df.loc[df['WELL'] == e2_string ][['DEPTH_MD', 'CALIPER', 'GR', 'LITHOLOGY', 'SHALLOW', 'DEEP']]
...
df.loc[(df.GR < 30.0000) & (df.CALIPER > e1_float) & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'
df.loc[(df.GR > 100.0000) , "LITHOLOGY"] = '3'
df.LITHOLOGY.fillna('2', inplace=True)

df.to_excel(file)
...
makeplot(data, 230, 330)
</code>```

Your complaint is that the plot is plotting your data WITHOUT yourLITHOLOGY column.  That happens because you asked it to do that: you extract the data  dataframe before you fill in the LITHOLOGY column in your df, so data doesn't get any of the modified data.

The obvious solution is to move the data = ... line AFTER you setup the LITHOLOGY column.  Right?

Body:
import pandas as pd
import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image

app_root = Tk()

#Setting it up
img = ImageTk.PhotoImage(Image.open("predictsodapng.png"))

#Displaying it
imglabel = Label(app_root, image=img).grid(row=0, column=0)

app_root.title("Predict Soda")
app_root.geometry("800x600")

app_root.mainloop()

def show_entry_fields():
    print("Bit Diameter as cms: %s\nWell Name: %s" % (float(e1.get()), e2.get()))

master = tk.Tk()
tk.Label(master,
         text="Bit Diameter as cms").grid(row=0)
tk.Label(master,
         text="Well Name").grid(row=1)

e1 = tk.Entry(master)
e2 = tk.Entry(master)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

e1_float = 0.0          # Storage for results on exit
e2_string = ""          # Storage for results on exit

def get_float( entry ):
    """ Converts the characters in an Entry to a float,
        returns 0.0 if not a valid float"""
    try:
        return float( entry.get() )
    except ValueError:
        return 0.0

def save_and_quit():
    global e1_float, e2_string
    e1_float = get_float( e1 )
    e2_string = e2.get()
    print( type( 'e1'),  'e1', type(e1), e1 )   # Prints to see what happens.
    print( type( e1.get()), e1.get(), type(e1_float), e1_float )
    master.destroy()

tk.Button(master,
          text='Save & Quit',
          command=save_and_quit).grid(row=3,
                                      column=0,
                                      sticky=tk.W,
                                      pady=4)
tk.Button(master,
          text='Show', command=show_entry_fields).grid(row=3,
                                                       column=1,
                                                       sticky=tk.W,
                                                       pady=4)

tk.mainloop()

from tkinter import filedialog

app_root_r = Tk()

file = filedialog.askopenfilename()

if file:
        try:
            filename = r"{}".format(file)
            df = pd.read_excel(file)
        except ValueError:
            label.config(text="File could not be opened")
        except FileNotFoundError:
            label.config(text="File Not Found")

data = df.loc[df['WELL'] == e2_string ][['DEPTH_MD', 'CALIPER', 'GR', 'LITHOLOGY', 'SHALLOW', 'DEEP']]

e1_float = e1_float * 30/100 + e1_float

df.loc[(df.GR < 30.0000) & (df.CALIPER > e1_float) & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'
df.loc[(df.GR > 100.0000) , "LITHOLOGY"] = '3'
df.LITHOLOGY.fillna('2', inplace=True)

df.to_excel(file)

df = pd.read_excel(file)

app_root_r.mainloop()

lithology_numbers = {1: {'lith':'Trona', 'lith_num':1, 'hatch': '+', 'color':'aqua'},
                 2: {'lith':'Shale, Claystone', 'lith_num':2, 'hatch':'-.', 'color':'black'},
                 3: {'lith':'Tuff', 'lith_num':3, 'hatch':'o', 'color':'orange'}}
df_lith = pd.DataFrame.from_dict(lithology_numbers, orient='index')
df_lith.index.name = 'LITHOLOGY'
df_lith

y = [0, 1]
x = [1, 1]

from matplotlib import pyplot as plt

fig, axes = plt.subplots(ncols=4,nrows=3, sharex=True, sharey=True,
                         figsize=(10,5), subplot_kw={'xticks': [], 'yticks': []})

for ax, key in zip(axes.flat, lithology_numbers.keys()):
    ax.plot(x, y)
    ax.fill_betweenx(y, 0, 1, facecolor=lithology_numbers[key]['color'], hatch=lithology_numbers[key]['hatch'])
    ax.set_xlim(0, 0.1)
    ax.set_ylim(0, 1)
    ax.set_title(str(lithology_numbers[key]['lith']))

plt.tight_layout()
plt.show()

def makeplot(well, top_depth, bottom_depth):
    fig, ax = plt.subplots(figsize=(15,10))

    ax1 = plt.subplot2grid((1,5), (0,0), rowspan=1, colspan = 1)
    ax5 = ax1.twiny()
    ax2 = plt.subplot2grid((1,5), (0,1), rowspan=1, colspan = 1, sharey = ax1)
    ax3 = ax2.twiny() #Twins the y-axis for the density track with the neutron track
    ax4 = plt.subplot2grid((1,5), (0,3), rowspan=1, colspan = 1, sharey = ax1)
    ax6 = plt.subplot2grid((1,5), (0,2), rowspan=1, colspan = 1, sharey = ax1)
    ax7 = ax6.twiny()

    ax10 = ax1.twiny()
    ax10.xaxis.set_visible(False)
    ax11 = ax2.twiny()
    ax11.xaxis.set_visible(False)
    ax13 = ax4.twiny()
    ax13.xaxis.set_visible(False)
    ax14 = ax6.twiny()
    ax14.xaxis.set_visible(False)

    # Gamma Ray track
    ax1.plot(well["GR"], well['DEPTH_MD'], color = "green", linewidth = 0.5)
    ax1.set_xlabel("Gamma")
    ax1.xaxis.label.set_color("green")
    ax1.set_xlim(0, 200)
    ax1.set_ylabel("Depth (m)")
    ax1.tick_params(axis='x', colors="green")
    ax1.spines["top"].set_edgecolor("green")
    ax1.title.set_color('green')
    ax1.set_xticks([0, 50, 100, 150, 200])

    # Caliper track
    ax2.plot(well["CALIPER"], well['DEPTH_MD'], color = "red", linewidth = 0.5)
    ax2.set_xlabel("Caliper")
    ax2.set_xlim(0, 50)
    ax2.xaxis.label.set_color("red")
    ax2.tick_params(axis='x', colors="red")
    ax2.spines["top"].set_edgecolor("red")
    ax2.set_xticks([0, 10, 20, 30, 40, 50])

  # Resistivity track placed ontop of density track(SHALLOW)
    ax6.plot(well["SHALLOW"], well['DEPTH_MD'], color = "blue", linewidth = 0.5)
    ax6.set_xlabel('Resistivity')
    ax6.xaxis.label.set_color("blue")
    ax6.set_xlim(0, 15)
    ax6.tick_params(axis='x', colors="blue")
    ax6.spines["top"].set_position(("axes", 1.08))
    ax6.spines["top"].set_visible(True)
    ax6.spines["top"].set_edgecolor("blue")
    ax6.set_xticks([0, 1, 2, 15])

  # Resistivity (deep)
    ax7.plot(well["DEEP"], well['DEPTH_MD'], color = "blue", linewidth = 0.5)
    ax7.xaxis.label.set_color("blue")
    ax7.tick_params(axis='x', colors="blue")
    ax7.spines["top"].set_position(("axes", 1.08))
    ax7.spines["top"].set_visible(True)
    ax7.spines["top"].set_edgecolor("blue")
    ax7.set_xticks([1, 2, 15])

    # Lithology track
    ax4.plot(well["LITHOLOGY"], well['DEPTH_MD'], color = "black", linewidth = 0.5)
    ax4.set_xlabel("Lithology")
    ax4.xaxis.label.set_color("black")
    ax4.set_xlim(0,1)
    ax4.tick_params(axis='x', colors="black")
    ax4.spines["top"].set_edgecolor("black")

    for key in lithology_numbers.keys():
        color = lithology_numbers[key]['color']
        hatch = lithology_numbers[key]['hatch']
        ax4.fill_betweenx(well['DEPTH_MD'], 0, well['LITHOLOGY'], where=(well['LITHOLOGY']==key),
                         facecolor=color, hatch=hatch)

    ax4.set_xticks([0, 1])

    for ax in [ax1, ax2, ax4, ax6]:
        ax.set_ylim(bottom_depth, top_depth)
        ax.grid(which='major', color='lightgrey', linestyle='-')
        ax.xaxis.set_ticks_position("top")
        ax.xaxis.set_label_position("top")
        ax.spines["top"].set_position(("axes", 1.02))

    for ax in [ax2, ax3, ax4, ax6]:
        plt.setp(ax.get_yticklabels(), visible = False)

    plt.tight_layout()
    fig.subplots_adjust(wspace = 0.15)

    for key in lithology_numbers.keys():
     color = lithology_numbers[key]['color']
     hatch = lithology_numbers[key]['hatch']
     ax4.fill_betweenx(well['DEPTH_MD'], 0, well['LITHOLOGY'],
                      where=(well['LITHOLOGY']==key),
                      facecolor=color, hatch=hatch)

makeplot(data, 230,330)

plt.savefig("input.jpg")

from PIL import ImageTk, Image

root = Tk()

img = ImageTk.PhotoImage(Image.open("input.jpg"))

l=Label(image=img)

l.pack()

root.mainloop()

I have these codes, in order to make comparison and plot. And also Im trying to create an interface using tkinter. I use the LITHOLOGY column for drawing after printing. On the other hand, tkinter uses the first version of this printed excel file instead of the current one(you can see in the first picture). However, when I run the same codes again, i.e. run the same for the second time, you can see the result in second picture(this shows how my output should be). There is no problem as the LITHOLOGY column is already printed to the excel file when i run it for the second time. I want to eliminate this problem. I have to draw the data directly from the dataframe, but when I replace the well[LITHOLOGY] with df[LITHOLOGY], it only shows the values instead of drawing and painting as you can see in the third figure. How can I solve it? Thanks.

Body:
Your problem is the order you do your operations.  Look at what you do:

df = pd.read_excel(file)
...
data = df.loc[df['WELL'] == e2_string ][['DEPTH_MD', 'CALIPER', 'GR', 'LITHOLOGY', 'SHALLOW', 'DEEP']]
...
df.loc[(df.GR < 30.0000) & (df.CALIPER > e1_float) & (df.SHALLOW > 2.60000)  , "LITHOLOGY"] = '1'
df.loc[(df.GR > 100.0000) , "LITHOLOGY"] = '3'
df.LITHOLOGY.fillna('2', inplace=True)

df.to_excel(file)
...
makeplot(data, 230, 330)

Your complaint is that the plot is plotting your data WITHOUT yourLITHOLOGY column.  That happens because you asked it to do that: you extract the data  dataframe before you fill in the LITHOLOGY column in your df, so data doesn't get any of the modified data.

The obvious solution is to move the data = ... line AFTER you setup the LITHOLOGY column.  Right?


问:
What is the advantage of a single-function-class over a function?
I have often encountered classes with the following structure:

```<code>class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};
</code>```

So classes with only one public member function that are also only run once.
Is there any advantage in any case over a single free function foo(A a, B b)?
The latter option is easier to call, potentially has less header dependencies and also has  much less boilerplate in the header.

答:
Classes introduce a new dynamic to your program -> Better readability, security, moudularity, re-usability....
functions are used to organize code into blocks.</p>

Body:
I have often encountered classes with the following structure:

class FooAlgorithm {
  public:
    FooAlgorithm(A a, B b);
    void run();
  private:
    A _a;
    B _b;
};

So classes with only one public member function that are also only run once.
Is there any advantage in any case over a single free function foo(A a, B b)?
The latter option is easier to call, potentially has less header dependencies and also has  much less boilerplate in the header.


问:
PDO::__construct(): send of 108 bytes failed with errno=32 Broken pipe
When I log into my command line mysql I can no longer access any PHP application that requires a database connection.  This happens every time.  The steps to cause the issue on my localhost:

```<code>Command line:
mysql -u root (no password for localhost)
mysql>
</code>```

I do not execute or do anything at this point.  I load up any page that requires a database connection using root:

```<code>PDO::__construct(): send of 108 bytes failed with errno=32 Broken pipe
</code>```

If I exit mysql the pages come back but another issue comes up when attempting to load two pages at the same time (in browser tabs) it will cause one of them to break until the page loads, then I can refresh

```<code>My.cnf:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

wait_timeout=5000
max_allowed_packet=100m
max_user_connections=1000
</code>```

答:
For "Send of X bytes failed with errno=32 Broken pipe", most responses around the internet would advise you to increase wait_timeout for your connections.
This didn't work for us.

But after struggling for some time, we sort of wildly guessed that it is maybe max_allowed_packet that needs to be increased.
And indeed, lifting it up to 500M did a good job.

Only after it already worked, we found that other people have similar experience (e.g. https://www.somacon.com/p574.php )

Body:
When I log into my command line mysql I can no longer access any PHP application that requires a database connection.  This happens every time.  The steps to cause the issue on my localhost:

Command line:
mysql -u root (no password for localhost)
mysql>

I do not execute or do anything at this point.  I load up any page that requires a database connection using root:

PDO::__construct(): send of 108 bytes failed with errno=32 Broken pipe

If I exit mysql the pages come back but another issue comes up when attempting to load two pages at the same time (in browser tabs) it will cause one of them to break until the page loads, then I can refresh

My.cnf:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

wait_timeout=5000
max_allowed_packet=100m
max_user_connections=1000


问:
Show and hide a JavaScript snippet using a Google Tag Manager (GTM) custom event on a single page application (SPA)?
I am trying to setup Google Tag Manager (GTM) on my single page application (SPA).

I am pushing a custom datalayer event for each page view that looks like this:

```<code>window.dataLayer.push({
    event: 'customPageView',
    path: path,
    pageUrl: window.location.href,
    pageTitle: document.title,
    pageReferrer: pageReferrer,
    requiresAuth: requiresAuth,
    cid: getCid(),
  });
</code>```

And I am using the requiresAuth value to conditionally show a JavaScript snippet from Zoho Desk. When the Zoho Desk JavaScript snippet is present it should display a floating help icon on the page for the user to interact with.

I only want the snippet to load on internal pages where requiresAuth = true. All of the login pages have requiresAuth = false and I do not want the snippet to load there.

Inside GTM I have a Tag that fires when the customPageView event has requiresAuth = true. Here is a screenshot of the Trigger:

When first visiting the app it seems to work fine.

The login page does not show the floating Zoho Desk icon because on that page requiresAuth = false.

After logging in the floating Zoho Desk icon appears because all of those pages have requiresAuth = true.

But then I logout and get redirected back to the login page and the Zoho Desk icon is still showing. It does not disapear until I refresh the page.

It should have disappeared as soon as I was redirected to the login page because it has requiresAuth = false.

How do I fix this?

When debugging with GTM Preview feature everything looks correct -  yet it still doesn't work.

Zoho Desk Tag on login page first visit:

Zoho Desk Tag on internal page visits:

Zoho Desk Tag on login page after I logout:

As you can see from the screenshots above, the tag is firing and not firing correctly. Yet I can still see the Zoho Desk icon after logging out (unless I refresh the page, then it correctly disapears).

答:
I assume your auth pages are also part of the SPA so there is no actual page reload before/after auth. In that case, the Zoho Desk Script/Icon will remain loaded after it was first triggered by "Custom Page View - requiresAuth = true" even if the tag does not fire again.

If you are just concerned about the visual aspect, I would recommend to create a new tag which automatically hides the icon on requiresAuth = false pages.

1. HTML - Zoho Desk - Load/Show

Tag Logic: Check if Zoho Desk Icon Element already exists (aka Script was already loaded), if yes: make sure it is visible (e.g. style.display = "block"), if no: load script

Trigger:  Custom Page View - requiresAuth = true

2. HTML - Zoho Desk - Hide

Tag Logic: Check if Zoho Desk Icon Element exists (aka Script was already loaded), if yes: hide it (e.g. style.display = "none")

Trigger:  Custom Page View - requiresAuth = false

Body:
I am trying to setup Google Tag Manager (GTM) on my single page application (SPA).

I am pushing a custom datalayer event for each page view that looks like this:

window.dataLayer.push({
    event: 'customPageView',
    path: path,
    pageUrl: window.location.href,
    pageTitle: document.title,
    pageReferrer: pageReferrer,
    requiresAuth: requiresAuth,
    cid: getCid(),
  });

And I am using the requiresAuth value to conditionally show a JavaScript snippet from Zoho Desk. When the Zoho Desk JavaScript snippet is present it should display a floating help icon on the page for the user to interact with.

I only want the snippet to load on internal pages where requiresAuth = true. All of the login pages have requiresAuth = false and I do not want the snippet to load there.

Inside GTM I have a Tag that fires when the customPageView event has requiresAuth = true. Here is a screenshot of the Trigger:

When first visiting the app it seems to work fine.

The login page does not show the floating Zoho Desk icon because on that page requiresAuth = false.

After logging in the floating Zoho Desk icon appears because all of those pages have requiresAuth = true.

But then I logout and get redirected back to the login page and the Zoho Desk icon is still showing. It does not disapear until I refresh the page.

It should have disappeared as soon as I was redirected to the login page because it has requiresAuth = false.

How do I fix this?

When debugging with GTM Preview feature everything looks correct -  yet it still doesn't work.

Zoho Desk Tag on login page first visit:

Zoho Desk Tag on internal page visits:

Zoho Desk Tag on login page after I logout:

As you can see from the screenshots above, the tag is firing and not firing correctly. Yet I can still see the Zoho Desk icon after logging out (unless I refresh the page, then it correctly disapears).


问:
Function containing ifelse not working in dplyr, works fine outside
I'd like to write a function with two inputs (x and y) to create some mutated variables in a very large dataframe. Specifically, if x=y then return x, and if x!=y then draw 1 sample from a sequence of x to y.

The function works fine when I test it outside of my datafarme, but throws an error when I try to use it within mutate. I've tried both ifelse and if_else versions.

```<code>library(dplyr)

smx <- function(x,y){ #Function to allow sampling if length>1
  if_else(x==y,x,sample(seq(x,y,1),1))}
  #ifelse(x==y,x,sample(seq(x,y,1),1))} #Have also tried this with ifelse, doesn't work

smx(0,0) #This works
smx(0,5) #This works

#Create dummy data frame
df <- as.data.frame(cbind(c(rep(0,5)),c(seq(0,4,1))))
colnames(df) <- c("varA","varB")

df

#This doesn't work
df1 <- df %>% mutate(
  VarC = smx(varA,varB)
)
</code>```

Ideally, my output should include a third column (VarC) in which the first row is equal to 0 (because varA=varB) and the remaining rows are a random sample between a sequence from varA to varB.

I have set up my data frame so that varA is always be smaller than varB, but I'm not certain. Appreciate any help on a clean solution to this problem!

答:
The function is not working because it is not vectorized. First, you'll need to vectorized your function, in order to make it work inside mutate.

You can do that as follows:

```<code>vectorized_fun <- Vectorize(your_fun)
</code>```

Your code will look like this:

```<code>smx_v <- Vectorize(smx)

#This works
df1 <- df %>%
  mutate(VarC = smx_v(varA,varB)
)
</code>```

Body:
I'd like to write a function with two inputs (x and y) to create some mutated variables in a very large dataframe. Specifically, if x=y then return x, and if x!=y then draw 1 sample from a sequence of x to y.

The function works fine when I test it outside of my datafarme, but throws an error when I try to use it within mutate. I've tried both ifelse and if_else versions.

library(dplyr)

smx <- function(x,y){ #Function to allow sampling if length>1
  if_else(x==y,x,sample(seq(x,y,1),1))}
  #ifelse(x==y,x,sample(seq(x,y,1),1))} #Have also tried this with ifelse, doesn't work

smx(0,0) #This works
smx(0,5) #This works

#Create dummy data frame
df <- as.data.frame(cbind(c(rep(0,5)),c(seq(0,4,1))))
colnames(df) <- c("varA","varB")

df

#This doesn't work
df1 <- df %>% mutate(
  VarC = smx(varA,varB)
)

Ideally, my output should include a third column (VarC) in which the first row is equal to 0 (because varA=varB) and the remaining rows are a random sample between a sequence from varA to varB.

I have set up my data frame so that varA is always be smaller than varB, but I'm not certain. Appreciate any help on a clean solution to this problem!

Body:
The function is not working because it is not vectorized. First, you'll need to vectorized your function, in order to make it work inside mutate.

You can do that as follows:

vectorized_fun <- Vectorize(your_fun)

Your code will look like this:

smx_v <- Vectorize(smx)

#This works
df1 <- df %>%
  mutate(VarC = smx_v(varA,varB)
)


问:
Is it safe to pass a prop object to `ref()` for it to be modified?
In Vue 3, can I create a ref from a prop that is an object to modify in my component?

```<code><template>
  <button @click.prevent="increment">You've clicked me {{ countObj.count }} times</button>
</template>

<script>
import { defineComponent, ref } from 'vue'

export default defineComponent({
  props: {
    startingCount: {
      type: Object,
      default: () => ({
        count: 0
      })
    }
  },

  setup (props) {
    const countObj = ref(props.startingCount)
    const increment = () => {
      countObj.value.count++
    }

    return {
      countObj,
      increment,
    }
  }
})
</script>
</code>```

Would my prop also be modified when modifying countObj?

答:
The short answer is YES! Both the prop startingCount and countObj will be modified.

What's more interesting, is that if the parent component passes a reactive object for startingCount prop then the reactive on parent will reactively change too! See it live

But this is considered a bad practice. You shouldn't modify props directly.
From docs:

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent's state, which can make your app's data flow harder to understand.

In order to perform a mutation to the parent component you can emit an event.

Read more about One-way data flow including the use case of Mutating Object / Array Props.

In your case, in order to fix the prop mutation problem replace this:

const countObj = ref(props.startingCount)

with:

const countObj = ref({ count: props.startingCount.count })

Body:
In Vue 3, can I create a ref from a prop that is an object to modify in my component?

<template>
  <button @click.prevent="increment">You've clicked me {{ countObj.count }} times</button>
</template>

Would my prop also be modified when modifying countObj?


问:
SetTimout in react export function
What is the right way to add setTimeout in this function?
Next js WP headless CMS</p>
```<code>export async function getStaticProps() {
      const allPosts = await getAllPosts();
      return {
        props: {
          allPosts
        }
      };
    }
</code>```

答:
This might get what you want</p>
```<code>export async function getStaticProps() {
    return setTimeout( async () => {

        // executes this block of code after the timeout(2 seconds)
        const allPosts = await getAllPosts();
        return {
            props: {
                allPosts
            }
        };
    }, 2000) //2 seconds (2 * 1000)
}
</code>```

Title: SetTimout in react export function

Body:
What is the right way to add setTimeout in this function?
Next js WP headless CMS

export async function getStaticProps() {
      const allPosts = await getAllPosts();
      return {
        props: {
          allPosts
        }
      };
    }

Body:
This might get what you want

export async function getStaticProps() {
    return setTimeout( async () => {

        // executes this block of code after the timeout(2 seconds)
        const allPosts = await getAllPosts();
        return {
            props: {
                allPosts
            }
        };
    }, 2000) //2 seconds (2 * 1000)
}


问:
Access member variables based on ENUM (no runtime decision)
My goal is to speed up my code by removing the runtime decision making of if-statements. Here's a simple example:

```<code>enum E
{
    E_A,
    E_B
};

class Example:
{
public:
    void DoSomething(E var)
    {
        if (var == E_A) {
            // Do stuff with a
        } else if (var == E_B) {
            // Do stuff with b
        }
    }

private:
    set<int> a;
    set<int> b;
}
</code>```

I've split the above DoSomething() function into 2.

```<code>void DoSomething(E::E_A var) {
    // Do stuff with a
}

void DoSomething(E::E_B var) {
    // Do stuff with b
}
</code>```

The problem is I have to rewrite the same code twice... We could use an inbetween function:

```<code>void DoSomething(E_A var) {
    InBetween(a);
}

void DoSomething(E_B var) {
    InBetween(b);
}

void InBetween(set<int> s)
{
    // Do something with s
}

set<int> a;
set<int> b;
</code>```

However I was wondering if there's a way to achieve what I want with just a single DoSomething()? I want the code to have minimal runtime so please avoid solutions like storing storing a and b inside a map and looking up based on key.

Or please suggest me some areas to look into. Thanks in advance!

答:
You can make DoSomething template (and var template parameter). Then you can apply Constexpr If (since C++17), which performs dispatch at compile-time. E.g.

```<code>template <E var>
void DoSomething()
{
    if constexpr (var == E_A) {
        // Do stuff with a
    } else if constexpr (var == E_B) {
        // Do stuff with b
    }
}
</code>```

Then call it as

```<code>a_Example.DoSomething<E::E_A>();
a_Example.DoSomething<E::E_B>();
</code>```

Body:
My goal is to speed up my code by removing the runtime decision making of if-statements. Here's a simple example:

enum E
{
    E_A,
    E_B
};

class Example:
{
public:
    void DoSomething(E var)
    {
        if (var == E_A) {
            // Do stuff with a
        } else if (var == E_B) {
            // Do stuff with b
        }
    }

private:
    set<int> a;
    set<int> b;
}

I've split the above DoSomething() function into 2.

void DoSomething(E::E_A var) {
    // Do stuff with a
}

void DoSomething(E::E_B var) {
    // Do stuff with b
}

The problem is I have to rewrite the same code twice... We could use an inbetween function:

void DoSomething(E_A var) {
    InBetween(a);
}

void DoSomething(E_B var) {
    InBetween(b);
}

void InBetween(set<int> s)
{
    // Do something with s
}

set<int> a;
set<int> b;

However I was wondering if there's a way to achieve what I want with just a single DoSomething()? I want the code to have minimal runtime so please avoid solutions like storing storing a and b inside a map and looking up based on key.

Or please suggest me some areas to look into. Thanks in advance!

Body:
You can make DoSomething template (and var template parameter). Then you can apply Constexpr If (since C++17), which performs dispatch at compile-time. E.g.

template <E var>
void DoSomething()
{
    if constexpr (var == E_A) {
        // Do stuff with a
    } else if constexpr (var == E_B) {
        // Do stuff with b
    }
}

Then call it as

a_Example.DoSomething<E::E_A>();
a_Example.DoSomething<E::E_B>();


问:
Trying to access design metadata without viewer, but have a problem of getting sqllite file
I am trying to use the api service as in the below link, and trying to get metadata by using derivative urn.

https://forge.autodesk.com/en/docs/model-derivative/v2/reference/http/urn-manifest-derivativeurn-GET/

However, the data returning from the service is broken as in below. What can be the problem?

答:
If you look at the documentation example, it returns chunked partial content body.
For metadata, please use these 2 APIs:

https://forge.autodesk.com/en/docs/model-derivative/v2/reference/http/urn-metadata-GET/

https://forge.autodesk.com/en/docs/model-derivative/v2/reference/http/urn-metadata-guid-GET/


问:
attempt to index nil with "WaitForChild"
i am making a game right now and i want enemies that spawn to have a health bar + player base.
All i have been giving this function to has a humanoid. but it will not stop saying attempt to index nil with wait for child at line 16. (This is a module script located in replicated)</p>
```<code> local Players = game:GetService("Players")
 local health = {}

function health.Setup(model)
    local newHealthBar = script.HealthGui:Clone()
    newHealthBar.Adornee = model:WaitForChild("Head")
    newHealthBar.Parent = Players.LocalPlayer.PlayerGui
   health.UpdateHealth()
    model.Humanoid.HealthChanged:Connect(function()
        health:UpdateHealth(newHealthBar, model)
    end)
end

function health.UpdateHealth(gui, model)
    local humanoid = model:WaitForChild("Humanoid")

    if humanoid and gui then
        local percent = humanoid.Health / humanoid.MaxHealth
        gui.CurrentHealth.Size = UDim2.new(percent, 0, 0.5, 0)
        if humanoid.Health <= 0 then
            gui.Title.Text = model.Name .. "Has died"
        else
            gui.Title.Text = "Health:" .. humanoid.Health .. "/" .. humanoid.MaxHealth
        end
    end
end

return health
</code>```

答:
In health.Setup you call health.UpdateHealth() so in health.UpdateHealth gui and model are nil values.

That's why local humanoid = model:WaitForChild("Humanoid") is causing the observed error.

If you don't provide any arguments to a function all its parameters are nil. nil values may not be indexed as in model:WaitForChild("Humanoid") which is syntactic sugar for model["WaitForChild"](model, "Humanoid") where model["WaitForChild"] is the indexing operation.

Body:
i am making a game right now and i want enemies that spawn to have a health bar + player base.
All i have been giving this function to has a humanoid. but it will not stop saying attempt to index nil with wait for child at line 16. (This is a module script located in replicated)

 local Players = game:GetService("Players")
 local health = {}

function health.Setup(model)
    local newHealthBar = script.HealthGui:Clone()
    newHealthBar.Adornee = model:WaitForChild("Head")
    newHealthBar.Parent = Players.LocalPlayer.PlayerGui
   health.UpdateHealth()
    model.Humanoid.HealthChanged:Connect(function()
        health:UpdateHealth(newHealthBar, model)
    end)
end

function health.UpdateHealth(gui, model)
    local humanoid = model:WaitForChild("Humanoid")

    if humanoid and gui then
        local percent = humanoid.Health / humanoid.MaxHealth
        gui.CurrentHealth.Size = UDim2.new(percent, 0, 0.5, 0)
        if humanoid.Health <= 0 then
            gui.Title.Text = model.Name .. "Has died"
        else
            gui.Title.Text = "Health:" .. humanoid.Health .. "/" .. humanoid.MaxHealth
        end
    end
end

return health


问:
What is the problem with this flutter code. Im trying to read the data from firebase
```<code>Future<Object?> GetData() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("litre");

// Get the data once
  DatabaseEvent event = await ref.once();

// Print the data of the snapshot
  print(event.snapshot.value);
  return event.snapshot.value;
}
</code>```

Code is here I want to get the value of "litre" tag and then print it into Text() function.
Firebase json is here =>

```<code>{
    "litre": "16"
}
</code>```

And I expected to see "16" but I facing Instance of 'Future'

答:
GetData is an async function, so using it in a Text() widget will throw an exception because it is not string.

You can use FutureBuilder to build the Text() widget.

Example:

```<code>Otherwidgets,
FutureBuilder(
          future: GetData(),
          builder: (context, snapshot) => Text(snapshot.data.toString()),
        ),
</code>```

Body:
Future<Object?> GetData() async {
  FirebaseDatabase database = FirebaseDatabase.instance;

  DatabaseReference ref = FirebaseDatabase.instance.ref("litre");

// Get the data once
  DatabaseEvent event = await ref.once();

// Print the data of the snapshot
  print(event.snapshot.value);
  return event.snapshot.value;
}

Code is here I want to get the value of "litre" tag and then print it into Text() function.
Firebase json is here =>

{
    "litre": "16"
}

And I expected to see "16" but I facing Instance of 'Future'

Body:
GetData is an async function, so using it in a Text() widget will throw an exception because it is not string.

You can use FutureBuilder to build the Text() widget.

Example:

Otherwidgets,
FutureBuilder(
          future: GetData(),
          builder: (context, snapshot) => Text(snapshot.data.toString()),
        ),


问:
Make element selected/active (like when you using tab)
I am trying to make element lets say button active on page open. By active I mean when u pressing tab buttons elements, tabs and stuff us getting active one after one. But how can I achieve that element is selected defaulty on page start.</p>

答:
All HTML elements have a Boolean attribute autofocus. It does not only work on form elements such as buttons, input fields, dropdowns, but also on focussable elements like
.

Body: All HTML elements have a Boolean attribute autofocus. It does not only work on form elements such as buttons, input fields, dropdowns, but also on focussable elements like <div contenteditable="true">.


问:
List categories of a Blog with Angular ngFor directive
I just want to list the categories of a Blog in Angular. When I use ngFor, It shows a list of the categories but is bringing in some repeated ones, like if it were bringing all the blogs and not just the categories that some of them share. Hope I was clear on this question.

This is my html:

```<code><aside class="categories">
     <h2 class="aside-title">Categorias</h2>

     <ul *ngFor="let data of datas; index as i">
        <li class="nav-elipse-blue"><a [routerLink]="['/pagina',datas.category]" title="Blog CSS
        articles">{{ data.category.name }}</a></li>
     </ul>

</aside>

</code>```

答:
You have to remove first the duplicates from an array and after that you have to use *ngFor.

You can remove duplicates in different ways:

Using Set

```<code>let data = ['A', 'B', 'A', 'C', 'B'];
let uniqueData = [...new Set(data)];
</code>```

Using forEach() and include() :

```<code> let data = ['A', 'B', 'A', 'C', 'B'];

 let uniqueData = [];
 data.forEach((c) => {
    if (!uniqueData.includes(c)) {
    uniqueData.push(c);
  }
 });
</code>```

There are other methods but these are more understandable.

After that in your HTML

```<code>     <ul *ngFor="let data of uniqueData">
        <li>{{category}}</li>
     </ul>
</code>```

Body:
I just want to list the categories of a Blog in Angular. When I use ngFor, It shows a list of the categories but is bringing in some repeated ones, like if it were bringing all the blogs and not just the categories that some of them share. Hope I was clear on this question.

This is my html:

Categorias

{{ data.category.name }}

Body:
You have to remove first the duplicates from an array and after that you have to use *ngFor.

You can remove duplicates in different ways:

Using Set

let data = ['A', 'B', 'A', 'C', 'B'];
let uniqueData = [...new Set(data)];

Using forEach() and include() :

 let data = ['A', 'B', 'A', 'C', 'B'];

 let uniqueData = [];
 data.forEach((c) => {
    if (!uniqueData.includes(c)) {
    uniqueData.push(c);
  }
 });

There are other methods but these are more understandable.

After that in your HTML

     <ul *ngFor="let data of uniqueData">
        <li>{{category}}</li>
     </ul>


问:
Django: TemplateSyntaxError-Could not parse the remainder
My template gets a queryset named qs.value sent from the views.py, I can display the value using {{qs.value}} anywhere in the template, but using it in an if statement raises an error.

```<code>    {% if {{qs.value}} > 0 %}
             <!--do something-->
             <h3 class="text-success">{{qs.value}}</h3>

    {% else %}
            <!--do something else-->
            <a href=""><button class="btn btn-primary">Else</button></a>

 {% endif %}
</code>```

The error:

```<code>Could not parse the remainder: '{{qs.value}}' from '{{qs.value}}'
</code>```

What am I doing wrong?

答: {{ }} are used to get the string representation of the variable/fuction. {% %} are used to make some code working. Both can read variables/functions as they are passed with context without any additional {{/{% inside them because they process given arguments directly.

Body:
My template gets a queryset named qs.value sent from the views.py, I can display the value using {{qs.value}} anywhere in the template, but using it in an if statement raises an error.

    {% if {{qs.value}} > 0 %}

{{qs.value}}

    {% else %}

            <button class="btn btn-primary">Else</button>

 {% endif %}

The error:

Could not parse the remainder: '{{qs.value}}' from '{{qs.value}}'

What am I doing wrong?


答:
The issue here comes from seq: when using this function inside dplyr verb, you need to make sure the length of input is 1, which isn't the case here.

Using rowwise() solves the problem:

```<code>smx <- function(x,y){
  ifelse(x==y,x,sample(seq(x,y,1),1))
}

df <- as.data.frame(cbind(c(rep(0,5)),c(seq(0,4,1))))
colnames(df) <- c("varA","varB")

df %>%
  rowwise() %>%
  mutate(VarC = smx(varA, varB))
</code>```

Output:

```<code># A tibble: 5 x 3
# Rowwise:
   varA  varB  VarC
  <dbl> <dbl> <dbl>
1     0     0     0
2     0     1     1
3     0     2     1
4     0     3     2
5     0     4     0
</code>```

Title: Function containing ifelse not working in dplyr, works fine outside

Body:
The issue here comes from seq: when using this function inside dplyr verb, you need to make sure the length of input is 1, which isn't the case here.

Using rowwise() solves the problem:

smx <- function(x,y){
  ifelse(x==y,x,sample(seq(x,y,1),1))
}

df <- as.data.frame(cbind(c(rep(0,5)),c(seq(0,4,1))))
colnames(df) <- c("varA","varB")

df %>%
  rowwise() %>%
  mutate(VarC = smx(varA, varB))

Output:

# A tibble: 5 x 3
# Rowwise:
   varA  varB  VarC
  <dbl> <dbl> <dbl>
1     0     0     0
2     0     1     1
3     0     2     1
4     0     3     2
5     0     4     0


问:
Delete All Data with SQLite delete syntax?
I've made a button that removes all the objects in my array, which is shown in my tableView. Then it reloads data and the tableview is empty. But how can I delete all the data from my SQLite database as well, and not just the array? Now the data occurs when I restart. I have tried this:

Button void:

```<code>   - (void) deleteAllButton_Clicked:(id)sender {

     [appDelegate removeAllBooks:nil];
     [self.tableView reloadData];

    }
</code>```

Appdelegate void:

```<code>-(void) removeAllBooks:(Book *)bookObj {
 //Delete it from the database.
 [bookObj deleteAllBooks];

 //Remove it from the array.
 [bookArray removeAllObjects];
}
</code>```

Delete syntax in Book.m

```<code>- (void) deleteAllBooks {
 if(deleteStmt == nil) {
  const char *sql = "WHAT DO I HAVE TO DO TO DELETE ALL THE ROWS?";
  if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
   NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
 }

 //When binding parameters, index starts from 1 and not zero.
 sqlite3_bind_int(deleteStmt, 1, bookID);

 if (SQLITE_DONE != sqlite3_step(deleteStmt))
  NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));

 sqlite3_reset(deleteStmt);
}
</code>```

答:
If you have a standard primary id column (and you should) you can do

```<code>DELETE FROM tablename WHERE id > -1;
</code>```

And this will delete all rows in the table since there is no id less than 0.

Body:
I've made a button that removes all the objects in my array, which is shown in my tableView. Then it reloads data and the tableview is empty. But how can I delete all the data from my SQLite database as well, and not just the array? Now the data occurs when I restart. I have tried this:

Button void:

   - (void) deleteAllButton_Clicked:(id)sender {

     [appDelegate removeAllBooks:nil];
     [self.tableView reloadData];

    }

Appdelegate void:

-(void) removeAllBooks:(Book *)bookObj {
 //Delete it from the database.
 [bookObj deleteAllBooks];

 //Remove it from the array.
 [bookArray removeAllObjects];
}

Delete syntax in Book.m

- (void) deleteAllBooks {
 if(deleteStmt == nil) {
  const char *sql = "WHAT DO I HAVE TO DO TO DELETE ALL THE ROWS?";
  if(sqlite3_prepare_v2(database, sql, -1, &deleteStmt, NULL) != SQLITE_OK)
   NSAssert1(0, @"Error while creating delete statement. '%s'", sqlite3_errmsg(database));
 }

 //When binding parameters, index starts from 1 and not zero.
 sqlite3_bind_int(deleteStmt, 1, bookID);

 if (SQLITE_DONE != sqlite3_step(deleteStmt))
  NSAssert1(0, @"Error while deleting. '%s'", sqlite3_errmsg(database));

 sqlite3_reset(deleteStmt);
}

Body:
If you have a standard primary id column (and you should) you can do

DELETE FROM tablename WHERE id > -1;

And this will delete all rows in the table since there is no id less than 0.