问:
How to capture pods' IP addresses in Kubernetes Audit log?
I need to log Pods' IP addresses for forensics purposes, ideally via the Kubernetes Audit log.

For testing purposes, I created the following audit config file:

```<code>apiVersion: audit.k8s.io/v1

kind: Policy
  - "RequestReceived"

rules:
  # Log pod changes at RequestResponse level
  - level: RequestResponse
    resources:
    - group: ""
      resources: ["pods"]
    namespaces: ["default"]
</code>```

After creating a pod and waiting for a few seconds, I see three events are written to the log (see below), but no podIP.
I could get the podIP to appear in the log by issuing a kubectl get pods -o wide command - this produces a log entry for a list verb with the IP address in the response. However, I want to find a way to produce the required log data without doing a list.
Thanks

```<code>{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "auditID": "89a167ed-eedb-4376-9032-c673f252c15c",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/default/pods?fieldManager=kubectl-create\u0026fieldValidation=Strict",
  "verb": "create",
  "user": {
    "username": "kubernetes-admin",
    "groups": [
      "system:masters",
      "system:authenticated"
    ]
  },
  "sourceIPs": [
    "172.18.0.1"
  ],
  "userAgent": "kubectl/v1.25.0 (linux/amd64) kubernetes/a866cbe",
  "objectRef": {
    "resource": "pods",
    "namespace": "default",
    "name": "nginx",
    "apiVersion": "v1"
  },
  "responseStatus": {
    "metadata": {},
    "code": 201
  },
  "requestObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "creationTimestamp": null,
      "labels": {
        "run": "nginx"
      }
    },
    "spec": {
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "enableServiceLinks": true
    },
    "status": {}
  },
  "responseObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "uid": "9523d148-ac73-426a-bd9e-0574ddefd6d8",
      "resourceVersion": "495",
      "creationTimestamp": "2022-12-06T00:13:14Z",
      "labels": {
        "run": "nginx"
      },
      "managedFields": [
        {
          "manager": "kubectl-create",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:metadata": {
              "f:labels": {
                ".": {},
                "f:run": {}
              }
            },
            "f:spec": {
              "f:containers": {
                "k:{\"name\":\"nginx\"}": {
                  ".": {},
                  "f:image": {},
                  "f:imagePullPolicy": {},
                  "f:name": {},
                  "f:resources": {},
                  "f:terminationMessagePath": {},
                  "f:terminationMessagePolicy": {}
                }
              },
              "f:dnsPolicy": {},
              "f:enableServiceLinks": {},
              "f:restartPolicy": {},
              "f:schedulerName": {},
              "f:securityContext": {},
              "f:terminationGracePeriodSeconds": {}
            }
          }
        }
      ]
    },
    "spec": {
      "volumes": [
        {
          "name": "kube-api-access-656v4",
          "projected": {
            "sources": [
              {
                "serviceAccountToken": {
                  "expirationSeconds": 3607,
                  "path": "token"
                }
              },
              {
                "configMap": {
                  "name": "kube-root-ca.crt",
                  "items": [
                    {
                      "key": "ca.crt",
                      "path": "ca.crt"
                    }
                  ]
                }
              },
              {
                "downwardAPI": {
                  "items": [
                    {
                      "path": "namespace",
                      "fieldRef": {
                        "apiVersion": "v1",
                        "fieldPath": "metadata.namespace"
                      }
                    }
                  ]
                }
              }
            ],
            "defaultMode": 420
          }
        }
      ],
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "volumeMounts": [
            {
              "name": "kube-api-access-656v4",
              "readOnly": true,
              "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
            }
          ],
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "serviceAccountName": "default",
      "serviceAccount": "default",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "tolerations": [
        {
          "key": "node.kubernetes.io/not-ready",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        },
        {
          "key": "node.kubernetes.io/unreachable",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        }
      ],
      "priority": 0,
      "enableServiceLinks": true,
      "preemptionPolicy": "PreemptLowerPriority"
    },
    "status": {
      "phase": "Pending",
      "qosClass": "BestEffort"
    }
  },
  "requestReceivedTimestamp": "2022-12-06T00:13:14.254928Z",
  "stageTimestamp": "2022-12-06T00:13:14.257236Z",
  "annotations": {
    "authorization.k8s.io/decision": "allow",
    "authorization.k8s.io/reason": "",
    "pod-security.kubernetes.io/enforce-policy": "privileged:latest"
  }
}
{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "auditID": "897bcbc9-0b74-4ad9-ac6b-63dbba5560ef",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/default/pods/nginx",
  "verb": "get",
  "user": {
    "username": "system:node:audited-cluster-worker",
    "groups": [
      "system:nodes",
      "system:authenticated"
    ]
  },
  "sourceIPs": [
    "fc00:f853:ccd:e793::3"
  ],
  "userAgent": "kubelet/v1.25.0 (linux/amd64) kubernetes/a866cbe",
  "objectRef": {
    "resource": "pods",
    "namespace": "default",
    "name": "nginx",
    "apiVersion": "v1"
  },
  "responseStatus": {
    "metadata": {},
    "code": 200
  },
  "responseObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "uid": "9523d148-ac73-426a-bd9e-0574ddefd6d8",
      "resourceVersion": "511",
      "creationTimestamp": "2022-12-06T00:13:14Z",
      "labels": {
        "run": "nginx"
      },
      "managedFields": [
        {
          "manager": "kube-scheduler",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:status": {
              "f:conditions": {
                ".": {},
                "k:{\"type\":\"PodScheduled\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                }
              }
            }
          },
          "subresource": "status"
        },
        {
          "manager": "kubectl-create",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:metadata": {
              "f:labels": {
                ".": {},
                "f:run": {}
              }
            },
            "f:spec": {
              "f:containers": {
                "k:{\"name\":\"nginx\"}": {
                  ".": {},
                  "f:image": {},
                  "f:imagePullPolicy": {},
                  "f:name": {},
                  "f:resources": {},
                  "f:terminationMessagePath": {},
                  "f:terminationMessagePolicy": {}
                }
              },
              "f:dnsPolicy": {},
              "f:enableServiceLinks": {},
              "f:restartPolicy": {},
              "f:schedulerName": {},
              "f:securityContext": {},
              "f:terminationGracePeriodSeconds": {}
            }
          }
        }
      ]
    },
    "spec": {
      "volumes": [
        {
          "name": "kube-api-access-656v4",
          "projected": {
            "sources": [
              {
                "serviceAccountToken": {
                  "expirationSeconds": 3607,
                  "path": "token"
                }
              },
              {
                "configMap": {
                  "name": "kube-root-ca.crt",
                  "items": [
                    {
                      "key": "ca.crt",
                      "path": "ca.crt"
                    }
                  ]
                }
              },
              {
                "downwardAPI": {
                  "items": [
                    {
                      "path": "namespace",
                      "fieldRef": {
                        "apiVersion": "v1",
                        "fieldPath": "metadata.namespace"
                      }
                    }
                  ]
                }
              }
            ],
            "defaultMode": 420
          }
        }
      ],
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "volumeMounts": [
            {
              "name": "kube-api-access-656v4",
              "readOnly": true,
              "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
            }
          ],
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "serviceAccountName": "default",
      "serviceAccount": "default",
      "nodeName": "audited-cluster-worker",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "tolerations": [
        {
          "key": "node.kubernetes.io/not-ready",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        },
        {
          "key": "node.kubernetes.io/unreachable",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        }
      ],
      "priority": 0,
      "enableServiceLinks": true,
      "preemptionPolicy": "PreemptLowerPriority"
    },
    "status": {
      "phase": "Pending",
      "conditions": [
        {
          "type": "PodScheduled",
          "status": "True",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z"
        }
      ],
      "qosClass": "BestEffort"
    }
  },
  "requestReceivedTimestamp": "2022-12-06T00:13:20.873927Z",
  "stageTimestamp": "2022-12-06T00:13:20.877592Z",
  "annotations": {
    "authorization.k8s.io/decision": "allow",
    "authorization.k8s.io/reason": ""
  }
}
{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "auditID": "2707f57a-62f1-4a10-9efe-5506b9c3b5af",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/default/pods/nginx",
  "verb": "get",
  "user": {
    "username": "system:node:audited-cluster-worker",
    "groups": [
      "system:nodes",
      "system:authenticated"
    ]
  },
  "sourceIPs": [
    "fc00:f853:ccd:e793::3"
  ],
  "userAgent": "kubelet/v1.25.0 (linux/amd64) kubernetes/a866cbe",
  "objectRef": {
    "resource": "pods",
    "namespace": "default",
    "name": "nginx",
    "apiVersion": "v1"
  },
  "responseStatus": {
    "metadata": {},
    "code": 200
  },
  "responseObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "uid": "9523d148-ac73-426a-bd9e-0574ddefd6d8",
      "resourceVersion": "513",
      "creationTimestamp": "2022-12-06T00:13:14Z",
      "labels": {
        "run": "nginx"
      },
      "managedFields": [
        {
          "manager": "kube-scheduler",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:status": {
              "f:conditions": {
                ".": {},
                "k:{\"type\":\"PodScheduled\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                }
              }
            }
          },
          "subresource": "status"
        },
        {
          "manager": "kubectl-create",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:metadata": {
              "f:labels": {
                ".": {},
                "f:run": {}
              }
            },
            "f:spec": {
              "f:containers": {
                "k:{\"name\":\"nginx\"}": {
                  ".": {},
                  "f:image": {},
                  "f:imagePullPolicy": {},
                  "f:name": {},
                  "f:resources": {},
                  "f:terminationMessagePath": {},
                  "f:terminationMessagePolicy": {}
                }
              },
              "f:dnsPolicy": {},
              "f:enableServiceLinks": {},
              "f:restartPolicy": {},
              "f:schedulerName": {},
              "f:securityContext": {},
              "f:terminationGracePeriodSeconds": {}
            }
          }
        },
        {
          "manager": "kubelet",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:20Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:status": {
              "f:conditions": {
                "k:{\"type\":\"ContainersReady\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                },
                "k:{\"type\":\"Initialized\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:status": {},
                  "f:type": {}
                },
                "k:{\"type\":\"Ready\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                }
              },
              "f:containerStatuses": {},
              "f:hostIP": {},
              "f:startTime": {}
            }
          },
          "subresource": "status"
        }
      ]
    },
    "spec": {
      "volumes": [
        {
          "name": "kube-api-access-656v4",
          "projected": {
            "sources": [
              {
                "serviceAccountToken": {
                  "expirationSeconds": 3607,
                  "path": "token"
                }
              },
              {
                "configMap": {
                  "name": "kube-root-ca.crt",
                  "items": [
                    {
                      "key": "ca.crt",
                      "path": "ca.crt"
                    }
                  ]
                }
              },
              {
                "downwardAPI": {
                  "items": [
                    {
                      "path": "namespace",
                      "fieldRef": {
                        "apiVersion": "v1",
                        "fieldPath": "metadata.namespace"
                      }
                    }
                  ]
                }
              }
            ],
            "defaultMode": 420
          }
        }
      ],
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "volumeMounts": [
            {
              "name": "kube-api-access-656v4",
              "readOnly": true,
              "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
            }
          ],
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "serviceAccountName": "default",
      "serviceAccount": "default",
      "nodeName": "audited-cluster-worker",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "tolerations": [
        {
          "key": "node.kubernetes.io/not-ready",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        },
        {
          "key": "node.kubernetes.io/unreachable",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        }
      ],
      "priority": 0,
      "enableServiceLinks": true,
      "preemptionPolicy": "PreemptLowerPriority"
    },
    "status": {
      "phase": "Pending",
      "conditions": [
        {
          "type": "Initialized",
          "status": "True",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z"
        },
        {
          "type": "Ready",
          "status": "False",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z",
          "reason": "ContainersNotReady",
          "message": "containers with unready status: [nginx]"
        },
        {
          "type": "ContainersReady",
          "status": "False",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z",
          "reason": "ContainersNotReady",
          "message": "containers with unready status: [nginx]"
        },
        {
          "type": "PodScheduled",
          "status": "True",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z"
        }
      ],
      "hostIP": "172.18.0.3",
      "startTime": "2022-12-06T00:13:20Z",
      "containerStatuses": [
        {
          "name": "nginx",
          "state": {
            "waiting": {
              "reason": "ContainerCreating"
            }
          },
          "lastState": {},
          "ready": false,
          "restartCount": 0,
          "image": "nginx",
          "imageID": "",
          "started": false
        }
      ],
      "qosClass": "BestEffort"
    }
  },
  "requestReceivedTimestamp": "2022-12-06T00:13:31.124669Z",
  "stageTimestamp": "2022-12-06T00:13:31.125661Z",
  "annotations": {
    "authorization.k8s.io/decision": "allow",
    "authorization.k8s.io/reason": ""
  }
}

</code>```

Body:
I need to log Pods' IP addresses for forensics purposes, ideally via the Kubernetes Audit log.

For testing purposes, I created the following audit config file:

apiVersion: audit.k8s.io/v1

kind: Policy
  - "RequestReceived"

rules:
  # Log pod changes at RequestResponse level
  - level: RequestResponse
    resources:
    - group: ""
      resources: ["pods"]
    namespaces: ["default"]

After creating a pod and waiting for a few seconds, I see three events are written to the log (see below), but no podIP.
I could get the podIP to appear in the log by issuing a kubectl get pods -o wide command - this produces a log entry for a list verb with the IP address in the response. However, I want to find a way to produce the required log data without doing a list.
Thanks

{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "auditID": "89a167ed-eedb-4376-9032-c673f252c15c",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/default/pods?fieldManager=kubectl-create\u0026fieldValidation=Strict",
  "verb": "create",
  "user": {
    "username": "kubernetes-admin",
    "groups": [
      "system:masters",
      "system:authenticated"
    ]
  },
  "sourceIPs": [
    "172.18.0.1"
  ],
  "userAgent": "kubectl/v1.25.0 (linux/amd64) kubernetes/a866cbe",
  "objectRef": {
    "resource": "pods",
    "namespace": "default",
    "name": "nginx",
    "apiVersion": "v1"
  },
  "responseStatus": {
    "metadata": {},
    "code": 201
  },
  "requestObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "creationTimestamp": null,
      "labels": {
        "run": "nginx"
      }
    },
    "spec": {
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "enableServiceLinks": true
    },
    "status": {}
  },
  "responseObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "uid": "9523d148-ac73-426a-bd9e-0574ddefd6d8",
      "resourceVersion": "495",
      "creationTimestamp": "2022-12-06T00:13:14Z",
      "labels": {
        "run": "nginx"
      },
      "managedFields": [
        {
          "manager": "kubectl-create",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:metadata": {
              "f:labels": {
                ".": {},
                "f:run": {}
              }
            },
            "f:spec": {
              "f:containers": {
                "k:{\"name\":\"nginx\"}": {
                  ".": {},
                  "f:image": {},
                  "f:imagePullPolicy": {},
                  "f:name": {},
                  "f:resources": {},
                  "f:terminationMessagePath": {},
                  "f:terminationMessagePolicy": {}
                }
              },
              "f:dnsPolicy": {},
              "f:enableServiceLinks": {},
              "f:restartPolicy": {},
              "f:schedulerName": {},
              "f:securityContext": {},
              "f:terminationGracePeriodSeconds": {}
            }
          }
        }
      ]
    },
    "spec": {
      "volumes": [
        {
          "name": "kube-api-access-656v4",
          "projected": {
            "sources": [
              {
                "serviceAccountToken": {
                  "expirationSeconds": 3607,
                  "path": "token"
                }
              },
              {
                "configMap": {
                  "name": "kube-root-ca.crt",
                  "items": [
                    {
                      "key": "ca.crt",
                      "path": "ca.crt"
                    }
                  ]
                }
              },
              {
                "downwardAPI": {
                  "items": [
                    {
                      "path": "namespace",
                      "fieldRef": {
                        "apiVersion": "v1",
                        "fieldPath": "metadata.namespace"
                      }
                    }
                  ]
                }
              }
            ],
            "defaultMode": 420
          }
        }
      ],
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "volumeMounts": [
            {
              "name": "kube-api-access-656v4",
              "readOnly": true,
              "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
            }
          ],
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "serviceAccountName": "default",
      "serviceAccount": "default",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "tolerations": [
        {
          "key": "node.kubernetes.io/not-ready",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        },
        {
          "key": "node.kubernetes.io/unreachable",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        }
      ],
      "priority": 0,
      "enableServiceLinks": true,
      "preemptionPolicy": "PreemptLowerPriority"
    },
    "status": {
      "phase": "Pending",
      "qosClass": "BestEffort"
    }
  },
  "requestReceivedTimestamp": "2022-12-06T00:13:14.254928Z",
  "stageTimestamp": "2022-12-06T00:13:14.257236Z",
  "annotations": {
    "authorization.k8s.io/decision": "allow",
    "authorization.k8s.io/reason": "",
    "pod-security.kubernetes.io/enforce-policy": "privileged:latest"
  }
}
{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "auditID": "897bcbc9-0b74-4ad9-ac6b-63dbba5560ef",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/default/pods/nginx",
  "verb": "get",
  "user": {
    "username": "system:node:audited-cluster-worker",
    "groups": [
      "system:nodes",
      "system:authenticated"
    ]
  },
  "sourceIPs": [
    "fc00:f853:ccd:e793::3"
  ],
  "userAgent": "kubelet/v1.25.0 (linux/amd64) kubernetes/a866cbe",
  "objectRef": {
    "resource": "pods",
    "namespace": "default",
    "name": "nginx",
    "apiVersion": "v1"
  },
  "responseStatus": {
    "metadata": {},
    "code": 200
  },
  "responseObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "uid": "9523d148-ac73-426a-bd9e-0574ddefd6d8",
      "resourceVersion": "511",
      "creationTimestamp": "2022-12-06T00:13:14Z",
      "labels": {
        "run": "nginx"
      },
      "managedFields": [
        {
          "manager": "kube-scheduler",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:status": {
              "f:conditions": {
                ".": {},
                "k:{\"type\":\"PodScheduled\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                }
              }
            }
          },
          "subresource": "status"
        },
        {
          "manager": "kubectl-create",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:metadata": {
              "f:labels": {
                ".": {},
                "f:run": {}
              }
            },
            "f:spec": {
              "f:containers": {
                "k:{\"name\":\"nginx\"}": {
                  ".": {},
                  "f:image": {},
                  "f:imagePullPolicy": {},
                  "f:name": {},
                  "f:resources": {},
                  "f:terminationMessagePath": {},
                  "f:terminationMessagePolicy": {}
                }
              },
              "f:dnsPolicy": {},
              "f:enableServiceLinks": {},
              "f:restartPolicy": {},
              "f:schedulerName": {},
              "f:securityContext": {},
              "f:terminationGracePeriodSeconds": {}
            }
          }
        }
      ]
    },
    "spec": {
      "volumes": [
        {
          "name": "kube-api-access-656v4",
          "projected": {
            "sources": [
              {
                "serviceAccountToken": {
                  "expirationSeconds": 3607,
                  "path": "token"
                }
              },
              {
                "configMap": {
                  "name": "kube-root-ca.crt",
                  "items": [
                    {
                      "key": "ca.crt",
                      "path": "ca.crt"
                    }
                  ]
                }
              },
              {
                "downwardAPI": {
                  "items": [
                    {
                      "path": "namespace",
                      "fieldRef": {
                        "apiVersion": "v1",
                        "fieldPath": "metadata.namespace"
                      }
                    }
                  ]
                }
              }
            ],
            "defaultMode": 420
          }
        }
      ],
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "volumeMounts": [
            {
              "name": "kube-api-access-656v4",
              "readOnly": true,
              "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
            }
          ],
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "serviceAccountName": "default",
      "serviceAccount": "default",
      "nodeName": "audited-cluster-worker",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "tolerations": [
        {
          "key": "node.kubernetes.io/not-ready",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        },
        {
          "key": "node.kubernetes.io/unreachable",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        }
      ],
      "priority": 0,
      "enableServiceLinks": true,
      "preemptionPolicy": "PreemptLowerPriority"
    },
    "status": {
      "phase": "Pending",
      "conditions": [
        {
          "type": "PodScheduled",
          "status": "True",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z"
        }
      ],
      "qosClass": "BestEffort"
    }
  },
  "requestReceivedTimestamp": "2022-12-06T00:13:20.873927Z",
  "stageTimestamp": "2022-12-06T00:13:20.877592Z",
  "annotations": {
    "authorization.k8s.io/decision": "allow",
    "authorization.k8s.io/reason": ""
  }
}
{
  "kind": "Event",
  "apiVersion": "audit.k8s.io/v1",
  "level": "RequestResponse",
  "auditID": "2707f57a-62f1-4a10-9efe-5506b9c3b5af",
  "stage": "ResponseComplete",
  "requestURI": "/api/v1/namespaces/default/pods/nginx",
  "verb": "get",
  "user": {
    "username": "system:node:audited-cluster-worker",
    "groups": [
      "system:nodes",
      "system:authenticated"
    ]
  },
  "sourceIPs": [
    "fc00:f853:ccd:e793::3"
  ],
  "userAgent": "kubelet/v1.25.0 (linux/amd64) kubernetes/a866cbe",
  "objectRef": {
    "resource": "pods",
    "namespace": "default",
    "name": "nginx",
    "apiVersion": "v1"
  },
  "responseStatus": {
    "metadata": {},
    "code": 200
  },
  "responseObject": {
    "kind": "Pod",
    "apiVersion": "v1",
    "metadata": {
      "name": "nginx",
      "namespace": "default",
      "uid": "9523d148-ac73-426a-bd9e-0574ddefd6d8",
      "resourceVersion": "513",
      "creationTimestamp": "2022-12-06T00:13:14Z",
      "labels": {
        "run": "nginx"
      },
      "managedFields": [
        {
          "manager": "kube-scheduler",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:status": {
              "f:conditions": {
                ".": {},
                "k:{\"type\":\"PodScheduled\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                }
              }
            }
          },
          "subresource": "status"
        },
        {
          "manager": "kubectl-create",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:14Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:metadata": {
              "f:labels": {
                ".": {},
                "f:run": {}
              }
            },
            "f:spec": {
              "f:containers": {
                "k:{\"name\":\"nginx\"}": {
                  ".": {},
                  "f:image": {},
                  "f:imagePullPolicy": {},
                  "f:name": {},
                  "f:resources": {},
                  "f:terminationMessagePath": {},
                  "f:terminationMessagePolicy": {}
                }
              },
              "f:dnsPolicy": {},
              "f:enableServiceLinks": {},
              "f:restartPolicy": {},
              "f:schedulerName": {},
              "f:securityContext": {},
              "f:terminationGracePeriodSeconds": {}
            }
          }
        },
        {
          "manager": "kubelet",
          "operation": "Update",
          "apiVersion": "v1",
          "time": "2022-12-06T00:13:20Z",
          "fieldsType": "FieldsV1",
          "fieldsV1": {
            "f:status": {
              "f:conditions": {
                "k:{\"type\":\"ContainersReady\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                },
                "k:{\"type\":\"Initialized\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:status": {},
                  "f:type": {}
                },
                "k:{\"type\":\"Ready\"}": {
                  ".": {},
                  "f:lastProbeTime": {},
                  "f:lastTransitionTime": {},
                  "f:message": {},
                  "f:reason": {},
                  "f:status": {},
                  "f:type": {}
                }
              },
              "f:containerStatuses": {},
              "f:hostIP": {},
              "f:startTime": {}
            }
          },
          "subresource": "status"
        }
      ]
    },
    "spec": {
      "volumes": [
        {
          "name": "kube-api-access-656v4",
          "projected": {
            "sources": [
              {
                "serviceAccountToken": {
                  "expirationSeconds": 3607,
                  "path": "token"
                }
              },
              {
                "configMap": {
                  "name": "kube-root-ca.crt",
                  "items": [
                    {
                      "key": "ca.crt",
                      "path": "ca.crt"
                    }
                  ]
                }
              },
              {
                "downwardAPI": {
                  "items": [
                    {
                      "path": "namespace",
                      "fieldRef": {
                        "apiVersion": "v1",
                        "fieldPath": "metadata.namespace"
                      }
                    }
                  ]
                }
              }
            ],
            "defaultMode": 420
          }
        }
      ],
      "containers": [
        {
          "name": "nginx",
          "image": "nginx",
          "resources": {},
          "volumeMounts": [
            {
              "name": "kube-api-access-656v4",
              "readOnly": true,
              "mountPath": "/var/run/secrets/kubernetes.io/serviceaccount"
            }
          ],
          "terminationMessagePath": "/dev/termination-log",
          "terminationMessagePolicy": "File",
          "imagePullPolicy": "Always"
        }
      ],
      "restartPolicy": "Always",
      "terminationGracePeriodSeconds": 30,
      "dnsPolicy": "ClusterFirst",
      "serviceAccountName": "default",
      "serviceAccount": "default",
      "nodeName": "audited-cluster-worker",
      "securityContext": {},
      "schedulerName": "default-scheduler",
      "tolerations": [
        {
          "key": "node.kubernetes.io/not-ready",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        },
        {
          "key": "node.kubernetes.io/unreachable",
          "operator": "Exists",
          "effect": "NoExecute",
          "tolerationSeconds": 300
        }
      ],
      "priority": 0,
      "enableServiceLinks": true,
      "preemptionPolicy": "PreemptLowerPriority"
    },
    "status": {
      "phase": "Pending",
      "conditions": [
        {
          "type": "Initialized",
          "status": "True",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z"
        },
        {
          "type": "Ready",
          "status": "False",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z",
          "reason": "ContainersNotReady",
          "message": "containers with unready status: [nginx]"
        },
        {
          "type": "ContainersReady",
          "status": "False",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z",
          "reason": "ContainersNotReady",
          "message": "containers with unready status: [nginx]"
        },
        {
          "type": "PodScheduled",
          "status": "True",
          "lastProbeTime": null,
          "lastTransitionTime": "2022-12-06T00:13:20Z"
        }
      ],
      "hostIP": "172.18.0.3",
      "startTime": "2022-12-06T00:13:20Z",
      "containerStatuses": [
        {
          "name": "nginx",
          "state": {
            "waiting": {
              "reason": "ContainerCreating"
            }
          },
          "lastState": {},
          "ready": false,
          "restartCount": 0,
          "image": "nginx",
          "imageID": "",
          "started": false
        }
      ],
      "qosClass": "BestEffort"
    }
  },
  "requestReceivedTimestamp": "2022-12-06T00:13:31.124669Z",
  "stageTimestamp": "2022-12-06T00:13:31.125661Z",
  "annotations": {
    "authorization.k8s.io/decision": "allow",
    "authorization.k8s.io/reason": ""
  }
}


来源: stackexchange

问:
explain old, new, and default values in mysql trigger
```<code>CREATE TABLE city (id INT, countrycode INT, population INT);
CREATE TABLE country (code INT, population INT);

CREATE TRIGGER diff_pop_ai
AFTER INSERT
ON city
FOR EACH ROW
UPDATE country
SET population = population + NEW.population
WHERE country.code = NEW.countrycode;

CREATE TRIGGER diff_pop_au
AFTER UPDATE
ON city
FOR EACH ROW
UPDATE country
SET population = population - OLD.population + NEW.population
WHERE country.code = NEW.countrycode;

INSERT INTO country VALUES (1,0), (2,0);

INSERT INTO city VALUES (1,1,100);
INSERT INTO city VALUES (2,2,200);
INSERT INTO city VALUES (3,1,300);
SELECT * FROM city;
SELECT * FROM country;
</code>```

enter image description here

```<code>+------+------------+
| code | population |
+------+------------+
|    1 |        400 |
+------+------------+
|    2 |        200 |
+------+------------+

UPDATE city SET population = 400 WHERE id = 2;
UPDATE city SET population = 500 WHERE id = 3;
SELECT * FROM city;
SELECT * FROM country;
</code>```

enter image description here

can anyone explain me the value (population, old.population, new.population). I can't tell the difference, especially the population variable

```<code>+------+------------+
| code | population |
+------+------------+
| 1    | 600        |
+------+------------+
| 2    | 400        |
+------+------------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
CREATE TABLE city (id INT, countrycode INT, population INT);
CREATE TABLE country (code INT, population INT);

CREATE TRIGGER diff_pop_ai
AFTER INSERT
ON city
FOR EACH ROW
UPDATE country
SET population = population + NEW.population
WHERE country.code = NEW.countrycode;

CREATE TRIGGER diff_pop_au
AFTER UPDATE
ON city
FOR EACH ROW
UPDATE country
SET population = population - OLD.population + NEW.population
WHERE country.code = NEW.countrycode;

INSERT INTO country VALUES (1,0), (2,0);

INSERT INTO city VALUES (1,1,100);
INSERT INTO city VALUES (2,2,200);
INSERT INTO city VALUES (3,1,300);
SELECT * FROM city;
SELECT * FROM country;

enter image description here

+------+------------+
| code | population |
+------+------------+
|    1 |        400 |
+------+------------+
|    2 |        200 |
+------+------------+

UPDATE city SET population = 400 WHERE id = 2;
UPDATE city SET population = 500 WHERE id = 3;
SELECT * FROM city;
SELECT * FROM country;

enter image description here

can anyone explain me the value (population, old.population, new.population). I can't tell the difference, especially the population variable

+------+------------+
| code | population |
+------+------------+
| 1    | 600        |
+------+------------+
| 2    | 400        |
+------+------------+


问:
Which imagick ini file is being used by php 8.0.25?
I have an AWS EC2 instance running Amazon Linux 2. My /etc/php.d/ directory contains two imagick ini files. 20-imagick.ini reads extension=imagick and 40-imagick.ini reads extension=imagick.so

If I run the command "php -m | grep imagick" I receive the following - PHP Warning:  Module "imagick" is already loaded in Unknown on line 0

How do I determine which ini file is the correct one? How do I remove the other one?

I wanted to confirm imagick was installed.


问:
RuntimeError: Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [1, 4]
I am beginning to learn how to develop CNN models using PyTorch, and I am currently working on a local dataset that has feature size of 1x4 and a binary label. I am also implementing K-Fold Cross Validation in the process. I have been able to develop a previous CNN model with a different dataset and procedure, but I am currently receiving and error in the code. I would appreciate your help, as I have been stuck in this error for a few days now.

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In [34], line 12
      9 test_loader = DataLoader(dataset, sampler=test_sampler)
     11 for epoch in range(num_epochs):
---> 12     train_loss,train_correct = train_epoch(model,train_loader,criterion,optimizer)
     13     test_loss,test_correct = test_epoch(model,test_loader,criterion)
     15     train_loss = train_loss/len(train_loader.sampler)

Cell In [33], line 11, in train_epoch(model, dataloader, loss_fn, optimizer)
      9 #Forward Pass
     10 print(features)
---> 11 output=model(features)
     12 loss=loss_fn(output,labels)
     14 #Backward Pass

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\module.py:1480, in Module._call_impl(self, *args, **kwargs)
   1475 # If we don't have any hooks, we want to skip the rest of the logic in
   1476 # this function, and just call forward.
   1477 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1478         or _global_backward_pre_hooks or _global_backward_hooks
   1479         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1480     return forward_call(*args, **kwargs)
   1481 # Do not call functions when jit is used
   1482 full_backward_hooks, non_full_backward_hooks = [], []

Cell In [31], line 14, in ConvNet.forward(self, x)
     12 def forward(self,x):
     13     print(x)
---> 14     print(self.conv1(x))
     15     x = F.relu(F.max_pool2d(self.conv1(x), kernel_size=2))
     16     x = F.relu(F.max_pool2d(self.conv2(x), kernel_size=2))

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\module.py:1480, in Module._call_impl(self, *args, **kwargs)
   1475 # If we don't have any hooks, we want to skip the rest of the logic in
   1476 # this function, and just call forward.
   1477 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1478         or _global_backward_pre_hooks or _global_backward_hooks
   1479         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1480     return forward_call(*args, **kwargs)
   1481 # Do not call functions when jit is used
   1482 full_backward_hooks, non_full_backward_hooks = [], []

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\conv.py:463, in Conv2d.forward(self, input)
    462 def forward(self, input: Tensor) -> Tensor:
--> 463     return self._conv_forward(input, self.weight, self.bias)

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\conv.py:459, in Conv2d._conv_forward(self, input, weight, bias)
    455 if self.padding_mode != 'zeros':
    456     return F.conv2d(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
    457                     weight, bias, self.stride,
    458                     _pair(0), self.dilation, self.groups)
--> 459 return F.conv2d(input, weight, bias, self.stride,
    460                 self.padding, self.dilation, self.groups)

RuntimeError: Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [1, 4]
</code>```

This is my current code for your reference.

```<code>## Importing Packages

import torch
import torch.nn as nn #To use neural network related functions (creating layers,)
import torch.nn.functional as F #To use certain activation functions
from torch.utils.data import Dataset, DataLoader, random_split, SubsetRandomSampler, TensorDataset, ConcatDataset
import torchvision #To use certain datasets (MNIST, CIFAR10), apply transformations to datasets
from torchvision import datasets, transforms
import numpy as np
from sklearn.model_selection import KFold, train_test_split
import pandas as pd

## Importing the Dataset

raw_dataset = pd.read_excel(r'C:\Users\Family\Desktop\Nottingham\Year 4\FYP\Software\Datasets\Original\CEA Classification Dataset.xlsx', sheet_name='Sheet1')
dataset = raw_dataset.drop(columns=raw_dataset.columns[0])
X = dataset.drop('Target',axis=1)
y = dataset['Target'].values
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state=42)

train_data = TensorDataset(torch.tensor(X_train.values,dtype=torch.float32), torch.tensor(y_train,dtype=torch.float32))
test_data = TensorDataset(torch.tensor(X_test.values,dtype=torch.float32), torch.tensor(y_test,dtype=torch.float32))

dataset = ConcatDataset([train_data,test_data])

## Creating Convolutional Model

# Creating Model class
class ConvNet(nn.Module):
    def __init__(self,h1=96):
        super(ConvNet,self).__init__()
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2)
        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2)
        self.drop1 = nn.Dropout2d(p=0.5)
        self.fc1 = nn.Linear(32*7*7,h1)
        self.drop2 = nn.Dropout2d(p=0.1)
        self.fc2 = nn.Linear(h1,2)

    def forward(self,x):
        print(x)
        print(self.conv1(x))
        x = F.relu(F.max_pool2d(self.conv1(x), kernel_size=2))
        x = F.relu(F.max_pool2d(self.conv2(x), kernel_size=2))
        x = self.drop1(x)
        x = x.view(x.size(0),-1)
        x = F.relu(self.fc1(x))
        x = self.drop2(x)
        x = self.fc2(x)
        return x

## Defining Hyper-parameters, K Fold, and Model configuration

# Hyper-parameters
num_epochs = 4
learning_rate = 0.001
batch_size=128

# K Fold
k = 10
splits = KFold(n_splits=k, shuffle=True, random_state=42)
foldperf={}

# Model, Loss Function, Optimizer
model = ConvNet()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

## Training & Testing Loop Functions

def train_epoch(model,dataloader,loss_fn,optimizer):
    train_loss,train_correct = 0.0, 0
    model.train() #Sets the mode to train (Helpful when using layers such as DropOut and BatchNorm)

    for features,labels in dataloader:
        #Zero grad
        optimizer.zero_grad()

        #Forward Pass
        print(features)
        output=model(features)
        loss=loss_fn(output,labels)

        #Backward Pass
        loss.backward()
        optimizer.step()

        train_loss += loss.item()*features.size(0)
        print(loss.item,features.size(0))
        scores, predictions = torch.max(output.data,1) # 1 is to create a 1 dimensional tensor with max values from each row

        train_correct += (predictions==labels).sum().item()

        return train_loss, train_correct

def test_epoch(model,dataloader,loss_fn):
    test_loss, test_correct = 0.0, 0
    model.eval()

    for features, labels in dataloader:
        output = model(features)
        loss = loss_fn(output,labels)
        test_loss += loss.item()*features.size(0)
        scores, predictions = torch.max(output.data,1)
        test_correct += (predictions==labels).sum().item()

        return test_loss, test_correct

history = {'train_loss': [], 'test_loss': [], 'train_acc': [], 'test_acc': []}

for fold, (train_idx,test_idx) in enumerate(splits.split(np.arange(len(dataset)))):
    print('Fold {}'.format(fold+1))

    train_sampler = SubsetRandomSampler(train_idx)
    test_sampler = SubsetRandomSampler(test_idx)
    train_loader = DataLoader(dataset, sampler=train_sampler)
    test_loader = DataLoader(dataset, sampler=test_sampler)

    for epoch in range(num_epochs):
        train_loss,train_correct = train_epoch(model,train_loader,criterion,optimizer)
        test_loss,test_correct = test_epoch(model,test_loader,criterion)

        train_loss = train_loss/len(train_loader.sampler)
        train_acc = train_correct//len(train_loader.sampler)*100

        test_loss = test_loss/len(test_loader.sampler)
        test_acc = test_correct//len(test_loader.sampler)*100

        print("Epoch:{}/{} AVG Training Loss: {:.3f} AVG Test Loss: {:.3f} AVG Training Acc: {:.2f}% AVG Test Acc: {:.2f}%"
             .format(epoch+1, num_epochs, train_loss, test_loss, train_acc, test_acc))

        history['train_loss'.append(train_loss)]
        history['test_loss'.append(test_loss)]
        history['train_acc'.append(train_acc)]
        history['test_acc'.append(test_acc)]
</code>```

Thank you for your help.

Body:
I am beginning to learn how to develop CNN models using PyTorch, and I am currently working on a local dataset that has feature size of 1x4 and a binary label. I am also implementing K-Fold Cross Validation in the process. I have been able to develop a previous CNN model with a different dataset and procedure, but I am currently receiving and error in the code. I would appreciate your help, as I have been stuck in this error for a few days now.

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In [34], line 12
      9 test_loader = DataLoader(dataset, sampler=test_sampler)
     11 for epoch in range(num_epochs):
---> 12     train_loss,train_correct = train_epoch(model,train_loader,criterion,optimizer)
     13     test_loss,test_correct = test_epoch(model,test_loader,criterion)
     15     train_loss = train_loss/len(train_loader.sampler)

Cell In [33], line 11, in train_epoch(model, dataloader, loss_fn, optimizer)
      9 #Forward Pass
     10 print(features)
---> 11 output=model(features)
     12 loss=loss_fn(output,labels)
     14 #Backward Pass

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\module.py:1480, in Module._call_impl(self, *args, **kwargs)
   1475 # If we don't have any hooks, we want to skip the rest of the logic in
   1476 # this function, and just call forward.
   1477 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1478         or _global_backward_pre_hooks or _global_backward_hooks
   1479         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1480     return forward_call(*args, **kwargs)
   1481 # Do not call functions when jit is used
   1482 full_backward_hooks, non_full_backward_hooks = [], []

Cell In [31], line 14, in ConvNet.forward(self, x)
     12 def forward(self,x):
     13     print(x)
---> 14     print(self.conv1(x))
     15     x = F.relu(F.max_pool2d(self.conv1(x), kernel_size=2))
     16     x = F.relu(F.max_pool2d(self.conv2(x), kernel_size=2))

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\module.py:1480, in Module._call_impl(self, *args, **kwargs)
   1475 # If we don't have any hooks, we want to skip the rest of the logic in
   1476 # this function, and just call forward.
   1477 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1478         or _global_backward_pre_hooks or _global_backward_hooks
   1479         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1480     return forward_call(*args, **kwargs)
   1481 # Do not call functions when jit is used
   1482 full_backward_hooks, non_full_backward_hooks = [], []

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\conv.py:463, in Conv2d.forward(self, input)
    462 def forward(self, input: Tensor) -> Tensor:
--> 463     return self._conv_forward(input, self.weight, self.bias)

File ~\Anaconda\Installation\envs\FYP\lib\site-packages\torch\nn\modules\conv.py:459, in Conv2d._conv_forward(self, input, weight, bias)
    455 if self.padding_mode != 'zeros':
    456     return F.conv2d(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
    457                     weight, bias, self.stride,
    458                     _pair(0), self.dilation, self.groups)
--> 459 return F.conv2d(input, weight, bias, self.stride,
    460                 self.padding, self.dilation, self.groups)

RuntimeError: Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [1, 4]

This is my current code for your reference.

## Importing Packages

import torch
import torch.nn as nn #To use neural network related functions (creating layers,)
import torch.nn.functional as F #To use certain activation functions
from torch.utils.data import Dataset, DataLoader, random_split, SubsetRandomSampler, TensorDataset, ConcatDataset
import torchvision #To use certain datasets (MNIST, CIFAR10), apply transformations to datasets
from torchvision import datasets, transforms
import numpy as np
from sklearn.model_selection import KFold, train_test_split
import pandas as pd

## Importing the Dataset

raw_dataset = pd.read_excel(r'C:\Users\Family\Desktop\Nottingham\Year 4\FYP\Software\Datasets\Original\CEA Classification Dataset.xlsx', sheet_name='Sheet1')
dataset = raw_dataset.drop(columns=raw_dataset.columns[0])
X = dataset.drop('Target',axis=1)
y = dataset['Target'].values
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state=42)

train_data = TensorDataset(torch.tensor(X_train.values,dtype=torch.float32), torch.tensor(y_train,dtype=torch.float32))
test_data = TensorDataset(torch.tensor(X_test.values,dtype=torch.float32), torch.tensor(y_test,dtype=torch.float32))

dataset = ConcatDataset([train_data,test_data])

## Creating Convolutional Model

# Creating Model class
class ConvNet(nn.Module):
    def __init__(self,h1=96):
        super(ConvNet,self).__init__()
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=2)
        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=2)
        self.drop1 = nn.Dropout2d(p=0.5)
        self.fc1 = nn.Linear(32*7*7,h1)
        self.drop2 = nn.Dropout2d(p=0.1)
        self.fc2 = nn.Linear(h1,2)

    def forward(self,x):
        print(x)
        print(self.conv1(x))
        x = F.relu(F.max_pool2d(self.conv1(x), kernel_size=2))
        x = F.relu(F.max_pool2d(self.conv2(x), kernel_size=2))
        x = self.drop1(x)
        x = x.view(x.size(0),-1)
        x = F.relu(self.fc1(x))
        x = self.drop2(x)
        x = self.fc2(x)
        return x

## Defining Hyper-parameters, K Fold, and Model configuration

# Hyper-parameters
num_epochs = 4
learning_rate = 0.001
batch_size=128

# K Fold
k = 10
splits = KFold(n_splits=k, shuffle=True, random_state=42)
foldperf={}

# Model, Loss Function, Optimizer
model = ConvNet()
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)

## Training & Testing Loop Functions

def train_epoch(model,dataloader,loss_fn,optimizer):
    train_loss,train_correct = 0.0, 0
    model.train() #Sets the mode to train (Helpful when using layers such as DropOut and BatchNorm)

    for features,labels in dataloader:
        #Zero grad
        optimizer.zero_grad()

        #Forward Pass
        print(features)
        output=model(features)
        loss=loss_fn(output,labels)

        #Backward Pass
        loss.backward()
        optimizer.step()

        train_loss += loss.item()*features.size(0)
        print(loss.item,features.size(0))
        scores, predictions = torch.max(output.data,1) # 1 is to create a 1 dimensional tensor with max values from each row

        train_correct += (predictions==labels).sum().item()

        return train_loss, train_correct

def test_epoch(model,dataloader,loss_fn):
    test_loss, test_correct = 0.0, 0
    model.eval()

    for features, labels in dataloader:
        output = model(features)
        loss = loss_fn(output,labels)
        test_loss += loss.item()*features.size(0)
        scores, predictions = torch.max(output.data,1)
        test_correct += (predictions==labels).sum().item()

        return test_loss, test_correct

history = {'train_loss': [], 'test_loss': [], 'train_acc': [], 'test_acc': []}

for fold, (train_idx,test_idx) in enumerate(splits.split(np.arange(len(dataset)))):
    print('Fold {}'.format(fold+1))

    train_sampler = SubsetRandomSampler(train_idx)
    test_sampler = SubsetRandomSampler(test_idx)
    train_loader = DataLoader(dataset, sampler=train_sampler)
    test_loader = DataLoader(dataset, sampler=test_sampler)

    for epoch in range(num_epochs):
        train_loss,train_correct = train_epoch(model,train_loader,criterion,optimizer)
        test_loss,test_correct = test_epoch(model,test_loader,criterion)

        train_loss = train_loss/len(train_loader.sampler)
        train_acc = train_correct//len(train_loader.sampler)*100

        test_loss = test_loss/len(test_loader.sampler)
        test_acc = test_correct//len(test_loader.sampler)*100

        print("Epoch:{}/{} AVG Training Loss: {:.3f} AVG Test Loss: {:.3f} AVG Training Acc: {:.2f}% AVG Test Acc: {:.2f}%"
             .format(epoch+1, num_epochs, train_loss, test_loss, train_acc, test_acc))

        history['train_loss'.append(train_loss)]
        history['test_loss'.append(test_loss)]
        history['train_acc'.append(train_acc)]
        history['test_acc'.append(test_acc)]

Thank you for your help.


问:
Issues with RTSP video in browser using Streamedian
I have a system where I need to be able to view 4 rtsp feeds with a web browser in and amongst other web content.  The feeds are coming from "Amcrest ProHD 1080P PTZ Camera Outdoor, 2MP Outdoor Vandal Dome IP PoE Camera" units.  All of the connectivity is wired within the same intranet.  I'm viewing the cameras on Insignia Amazon Fire TVs, and I'm not getting the results that I expected.

In order to get it working, I installed streamedian on my Windows machine and got that configured properly.  I didn't change much about the default configuration of the proxy server except the port number it was using the serve the feeds on.  On the browser side, I included the necessary JavaScript files (again, only changing the port numbers) and made my call to load the players.  Currently, that code looks like this:

```<code>var playerOptions = {
    socket: 'ws://192.168.1.253:8080/ws/',
    redirectNativeMediaErrors: true,
    bufferDuration: 5,
    continuousFileLength: 5000,
    eventFileLength: 5000,
    errorHandler: function (err) {
        console.log(err.message);
    },
};

setTimeout(function () {
    player1 = Streamedian.player("p1", playerOptions);
    player2 = Streamedian.player("p2", playerOptions);
    player3 = Streamedian.player("p3", playerOptions);
    player4 = Streamedian.player("p4", playerOptions);
}, 100);
</code>```

Each of the players look like this in the HTML:

```<code><video id="p1" controls autoplay>
    <source src="rtsp://path.to.camera" type="application/x-rtsp">
</video>
</code>```

The players do load, and appear to be attempting to start the stream.  However, they quickly start buffering and never come out of it to start showing anything resembling a live feed.  Any ideas on what I can do to try to get this running?  Am I even heading down a valid path to get where I need to be?

I'm not worried about rewind, or anything in the past.  This is purely for live streaming and only needs to show "now".  Saving anything more than necessary is not required in order to meet the needs.
I've tried dropping the frame rate to 4fps.  It didn't seem to help.
The Windows machine has average power at best.  I've opened Task Manager while the streams are running, but nothing appears to be pegged out.  Am I just running an under-powered machine for what I'm asking it to do?
Are the browsers in the TV, or the TV itself, just not capable of getting it done and processing that much information?  I've tried viewing the pages on my laptop as well (separate from the Windows server, and plenty powerful), but the results do not improve.
Should I be trying something else on my server side?  I came across iSpyConnect this evening as I was searching for other (preferably free) options, but I can't tell for sure if it will get me what I need.  I've also started looking at signboard applications for the TVs, but they all have a cost associated with them that I'd like to avoid if at all possible.

If anyone has any thoughts, ideas, comments, suggestions or questions about what I have in place, please let me know so that I can try to get something up and running within the facility.

Thanks!

Body:
I have a system where I need to be able to view 4 rtsp feeds with a web browser in and amongst other web content.  The feeds are coming from "Amcrest ProHD 1080P PTZ Camera Outdoor, 2MP Outdoor Vandal Dome IP PoE Camera" units.  All of the connectivity is wired within the same intranet.  I'm viewing the cameras on Insignia Amazon Fire TVs, and I'm not getting the results that I expected.

In order to get it working, I installed streamedian on my Windows machine and got that configured properly.  I didn't change much about the default configuration of the proxy server except the port number it was using the serve the feeds on.  On the browser side, I included the necessary JavaScript files (again, only changing the port numbers) and made my call to load the players.  Currently, that code looks like this:

var playerOptions = {
    socket: 'ws://192.168.1.253:8080/ws/',
    redirectNativeMediaErrors: true,
    bufferDuration: 5,
    continuousFileLength: 5000,
    eventFileLength: 5000,
    errorHandler: function (err) {
        console.log(err.message);
    },
};

setTimeout(function () {
    player1 = Streamedian.player("p1", playerOptions);
    player2 = Streamedian.player("p2", playerOptions);
    player3 = Streamedian.player("p3", playerOptions);
    player4 = Streamedian.player("p4", playerOptions);
}, 100);

Each of the players look like this in the HTML:

<video id="p1" controls autoplay>
    <source src="rtsp://path.to.camera" type="application/x-rtsp">
</video>

The players do load, and appear to be attempting to start the stream.  However, they quickly start buffering and never come out of it to start showing anything resembling a live feed.  Any ideas on what I can do to try to get this running?  Am I even heading down a valid path to get where I need to be?

I'm not worried about rewind, or anything in the past.  This is purely for live streaming and only needs to show "now".  Saving anything more than necessary is not required in order to meet the needs.
I've tried dropping the frame rate to 4fps.  It didn't seem to help.
The Windows machine has average power at best.  I've opened Task Manager while the streams are running, but nothing appears to be pegged out.  Am I just running an under-powered machine for what I'm asking it to do?
Are the browsers in the TV, or the TV itself, just not capable of getting it done and processing that much information?  I've tried viewing the pages on my laptop as well (separate from the Windows server, and plenty powerful), but the results do not improve.
Should I be trying something else on my server side?  I came across iSpyConnect this evening as I was searching for other (preferably free) options, but I can't tell for sure if it will get me what I need.  I've also started looking at signboard applications for the TVs, but they all have a cost associated with them that I'd like to avoid if at all possible.

If anyone has any thoughts, ideas, comments, suggestions or questions about what I have in place, please let me know so that I can try to get something up and running within the facility.

Thanks!


问:
Hosting an Excel application in the cloud
I have an Excel application with VBA that pulls data from various online sources.

How could I migrate that to a cloud platform?

I’ve looked at Azure and AWS but would ideally not want to refactor the application.


问:
How to use env data in CronJob?
Hi to make it short i use parts of the example from Gribesh Dhakal
How nodejs reads and writes .env files？

so the highest voted answer.

I write the CronJob * * * * * in the .env file - this is working

but if i do

const time1 = process.env.cron2 //cron2 is the key in .env file console.log(time1) //shows the value like it should const job2 = new CronJob(time1, () => { ... }); job2.start()

The CronJob works with any '* * * * *' combination but with time1 .. i get this error.

throw new Error(Field value (${value}) is out of range);  Error: Field value (12) is out of range

can anyone help?

Title: How to use env data in CronJob?


问:
How to handle async operation that we would like to cancel
I have an async operation that should run only if a user is connected, and should stop as soon as the user disconnect. For better understanding, I call the function in the example fetchUserDataAndCacheIt even though there is distinct services in charge of fetching and caching.

```<code>Future fetchUserDataAndCacheIt() async {
    ....
}
</code>```

The problem is, if the user disconnect during fetchUserDataAndCacheIt is running, the cached data will not be valid, as it will be data of a user not connected anymore. Worse, if fetchUserDataAndCacheIt takes a really long time to run (20 seconds), the user have the time to disconnect, an other user can connect on the same machine, then have access to the previous user data trough cache, since fetchUserDataAndCacheIt will end running after the second user connect.

From what I can tell, you cannot cancel a future in dart.
https://github.com/dart-lang/sdk/issues/42855

You could use a completer but it would not solve the problem mentioned above.

For now, what I found is to check whether the user is connected before caching inside the fetchUserDataAndCacheIt function, but I feel like doing that kind of check each time I want to cache any kind of data is going to make the code unmaintainable in the long run.

I hacknowledge this this can only occur in specific cases where the Future take a long time to run, but I cannot just hope the connection of my users to be fast enough for it to never happen.

Body:
I have an async operation that should run only if a user is connected, and should stop as soon as the user disconnect. For better understanding, I call the function in the example fetchUserDataAndCacheIt even though there is distinct services in charge of fetching and caching.

Future fetchUserDataAndCacheIt() async {
    ....
}

The problem is, if the user disconnect during fetchUserDataAndCacheIt is running, the cached data will not be valid, as it will be data of a user not connected anymore. Worse, if fetchUserDataAndCacheIt takes a really long time to run (20 seconds), the user have the time to disconnect, an other user can connect on the same machine, then have access to the previous user data trough cache, since fetchUserDataAndCacheIt will end running after the second user connect.

From what I can tell, you cannot cancel a future in dart.
https://github.com/dart-lang/sdk/issues/42855

You could use a completer but it would not solve the problem mentioned above.

For now, what I found is to check whether the user is connected before caching inside the fetchUserDataAndCacheIt function, but I feel like doing that kind of check each time I want to cache any kind of data is going to make the code unmaintainable in the long run.

I hacknowledge this this can only occur in specific cases where the Future take a long time to run, but I cannot just hope the connection of my users to be fast enough for it to never happen.


问:
How to prevent duplicate calendar events from Apps Script?
I'm very new to this! I can trying to move the information from google sheets over to google calendar automatically. Unfortunately, when I run the script there are duplication on the events. Please help!

```<code>function createCalendarEvent() {
  let communityCalendar = CalendarApp.getCalendarById("calendarid");
  let sheet = SpreadsheetApp.getActiveSheet();

  let schedule = sheet.getDataRange().getValues();
  schedule.splice(0, 2);

  schedule.forEach(function(entry) {
    communityCalendar.createEvent(entry[4], entry[0], entry[1]);
  });
}
</code>```

I am hoping to remove the duplication.

Also, if there is a way to add additional description.
For some reason, I cannot add an extra entry without it bugging. For example, I want to add location but the entry will not let me.

Body:
I'm very new to this! I can trying to move the information from google sheets over to google calendar automatically. Unfortunately, when I run the script there are duplication on the events. Please help!

function createCalendarEvent() {
  let communityCalendar = CalendarApp.getCalendarById("calendarid");
  let sheet = SpreadsheetApp.getActiveSheet();

  let schedule = sheet.getDataRange().getValues();
  schedule.splice(0, 2);

  schedule.forEach(function(entry) {
    communityCalendar.createEvent(entry[4], entry[0], entry[1]);
  });
}

I am hoping to remove the duplication.

Also, if there is a way to add additional description.
For some reason, I cannot add an extra entry without it bugging. For example, I want to add location but the entry will not let me.


问:
How can i get the ip address(or hostname) of the requester in jenkins
Is there any way to get the ip address of the requester who trigger the build in jenkins? it would be very good if the ip_addr(or hostname) of the requester can pass to jenkins server automatically as one of build parameter

The reason why i want to know it is

I am trying to setup Jenkins server in private network which assigns static ip address for every user.

have plan to service it without login to improve the user experience.

i need to monitor statistic data that who/how many user use it

Thanks in advance.

i did googling to get the way of it. But couldn't find it.. alsmost answers are for getting ip address of the node not for requester..


问:
Deferencing memory from ctypes in Python when using windows API
I am using PySide2 to build a GUI in python that requires calling Windows API using ctypes. I have done some C++ and am familiar with memory allocation / deallocation, but am not confident in the context of calling C from python.

I have a couple of use-cases I would like to double check (minimum examples below), as really don't want to miss a possible memory leak. Any help would be much appreciated to ensure my understanding is correct.

1) Pointer to structure managed by Windows / Qt

```<code>class NCCALCSIZE_PARAMS(Structure):
    _fields_ = [("rgrc", RECT * 3), ("lppos", POINTER(PWINDOWPOS))]

LPNCCALCSIZE_PARAMS = POINTER(NCCALCSIZE_PARAMS)

rect = cast(msg.lParam, LPNCCALCSIZE_PARAMS).contents.rgrc[0]
rect.left += thickness
</code>```

NCCALCSIZE_PARAMS is a structure managed by Windows Qt to calculate window size. I think the memory for this will be managed on the Qt / C++ side, and so there is no need to de-reference the block the POINTER points to, so I can just let it go out of scope? for rect = cast(), I believe this is also a pointer to the same memory address, so I can also let it go out of scope.

2) Passing initialised ctypes structure by reference

```<code>class MARGINS(ctypes.Structure):
    _fields_ = [("cxLeftWidth", c_int),
                ("cxRightWidth", c_int),
                ("cyTopHeight", c_int),
                ("cyBottomHeight", c_int)
                ]

margins = MARGINS(1, 1, 1, 1)
dwm.DwmExtendFrameIntoClientArea(msg.hWnd, ctypes.byref(margins))
</code>```

In this instance, a class is initialised on the python side as a ctypes structure. A reference to it is passed to a windows dll. Because the reference is passed straight to the function, and the structure was initialised on the python side, there is no need to deallocate memory?

3)  Using ctypes from_address()

```<code>def nativeEvent(self, event, message):
    msg = MSG.from_address(message.__int__())
    return QtWidgets.QWidget.nativeEvent(self, event, message)
</code>```

This is used to handle internal windows messages, which are structures containing information about the window. message is passed to Qt's nativeEvent after use, and so windows / C++ should handle the memory release. It is read into python with ctyes MSG class using ctyes from_adress() function. I believe ctypes from_address() just returns a python instance of whatever is at that address, and so in this case there is also no need to dellocate memory?

Body:
I am using PySide2 to build a GUI in python that requires calling Windows API using ctypes. I have done some C++ and am familiar with memory allocation / deallocation, but am not confident in the context of calling C from python.

I have a couple of use-cases I would like to double check (minimum examples below), as really don't want to miss a possible memory leak. Any help would be much appreciated to ensure my understanding is correct.

1) Pointer to structure managed by Windows / Qt

class NCCALCSIZE_PARAMS(Structure):
    _fields_ = [("rgrc", RECT * 3), ("lppos", POINTER(PWINDOWPOS))]

LPNCCALCSIZE_PARAMS = POINTER(NCCALCSIZE_PARAMS)

rect = cast(msg.lParam, LPNCCALCSIZE_PARAMS).contents.rgrc[0]
rect.left += thickness

NCCALCSIZE_PARAMS is a structure managed by Windows Qt to calculate window size. I think the memory for this will be managed on the Qt / C++ side, and so there is no need to de-reference the block the POINTER points to, so I can just let it go out of scope? for rect = cast(), I believe this is also a pointer to the same memory address, so I can also let it go out of scope.

2) Passing initialised ctypes structure by reference

class MARGINS(ctypes.Structure):
    _fields_ = [("cxLeftWidth", c_int),
                ("cxRightWidth", c_int),
                ("cyTopHeight", c_int),
                ("cyBottomHeight", c_int)
                ]

margins = MARGINS(1, 1, 1, 1)
dwm.DwmExtendFrameIntoClientArea(msg.hWnd, ctypes.byref(margins))

In this instance, a class is initialised on the python side as a ctypes structure. A reference to it is passed to a windows dll. Because the reference is passed straight to the function, and the structure was initialised on the python side, there is no need to deallocate memory?

3)  Using ctypes from_address()

def nativeEvent(self, event, message):
    msg = MSG.from_address(message.__int__())
    return QtWidgets.QWidget.nativeEvent(self, event, message)

This is used to handle internal windows messages, which are structures containing information about the window. message is passed to Qt's nativeEvent after use, and so windows / C++ should handle the memory release. It is read into python with ctyes MSG class using ctyes from_adress() function. I believe ctypes from_address() just returns a python instance of whatever is at that address, and so in this case there is also no need to dellocate memory?


问:
Clustering with constraint such that each cluster shares a common categorical value
I am trying to write a program that collects interests and availability from users and clusters them into groups based on similar interests and matching availability.

For example, four users could have the following availability and interests:

User 1:

Availability: Monday, Tuesday, Wednesday

Interest: Movies, Hiking

User 2:

Availability: Monday, Wednesday, Friday

Interest: Movies, Music

User 3:

Availability: Tuesday, Thursday, Saturday

Interest: Sports, Hiking

User 4:

Availability: Thursday, Friday

Interest: Hiking

Then the program could group the users into two clusters:

Cluster 1: User 1, User 2

Cluster 2: User 3, User 4

Since both User 1 and User 2 have the interest "movies" and at least one matching day of availability (Monday), they are placed in the same cluster. Similarly, Users 3 and 4 would be matched in a separate cluster

I am looking for suggestions on how to implement such a clustering algorithm. How can I ensure that each cluster has at least one common day of availability? Ideally, each cluster would share a maximal amount of interests and days of availability. Any other tips or suggestions would be greatly appreciated.


问:
I'm making delete buttons, and when I click them, they delete all of of the divs my JavaScript created
I'm using JavaScript to make divs when the user clicks a button. This part is working fine. It creates a form with two buttons, make, and delete shot. Make doesn't work right now- I'm just building out the front end. The delete shot button should just delete it's parent div and everything in it- but clicking any of the delete buttons deletes all of the divs! Sorry if I'm not explaining this well.

Here is my HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./app.js" defer></script>
</head>
<body>
    <h1>Calypso</h1>
    <p>Use Calypso to make storyboards: </p>
    <div class="newShot"></div>
    <button class="newShotButton">New Shot</button>
    <button
</body>
</html>
</code>```

And here is my JavaScript:

```<code>let container = document.querySelector(".newShot")
let btn = document.querySelector(".newShotButton")
let shotListArray = []; //holds all of the shot objects

class shotObject {
    constructor (number) {
        this.name = ("shot" + number);
        this.htmlContent =`
            <form class="shot${number}"
                <fieldset>
                    <legend>Shot ${number}:</legend>
                    <label for="fname">Enter Shot Description:</label><br>
                    <textarea id="fname" name="fname"> </textarea><br>
                    <input type="submit" value="Make">
                    <input type="submit" value="Delete shot" class="shot${number}DeleteButton">
                    <script>
                        let deleteShot${number} = document.getElementByClass('shot${number}');
                        shot${number}DeleteButton.addEventListener ("click", deleteShot${number}.remove());
                    </script>
                </fieldset>
            </form>
        `
    }
}

function createNewShot(){
    let newShot = new shotObject (shotListArray.length + 1);
    shotListArray.push(newShot);
    let arrayLength = shotListArray.length
    container.insertAdjacentHTML("beforeend", shotListArray[arrayLength-1].htmlContent);
}

btn.addEventListener("click", createNewShot);
</code>```
```<code>
</code>```

I just want the delete buttons to work as expected. I'm a little confused because when I look at the live server, I can see the class names are correct in the  tags for each of the buttons.

Body:
I'm using JavaScript to make divs when the user clicks a button. This part is working fine. It creates a form with two buttons, make, and delete shot. Make doesn't work right now- I'm just building out the front end. The delete shot button should just delete it's parent div and everything in it- but clicking any of the delete buttons deletes all of the divs! Sorry if I'm not explaining this well.

Here is my HTML:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

Calypso

Use Calypso to make storyboards:

    <button class="newShotButton">New Shot</button>
    <button

And here is my JavaScript:

let container = document.querySelector(".newShot")
let btn = document.querySelector(".newShotButton")
let shotListArray = []; //holds all of the shot objects

class shotObject {
    constructor (number) {
        this.name = ("shot" + number);
        this.htmlContent =`
            <form class="shot${number}"
                <fieldset>
                    <legend>Shot ${number}:</legend>
                    Enter Shot Description:

                    <textarea id="fname" name="fname"> </textarea>

                    <input type="submit" value="Make">
                    <input type="submit" value="Delete shot" class="shot${number}DeleteButton">

                </fieldset>
            </form>
        `
    }
}

function createNewShot(){
    let newShot = new shotObject (shotListArray.length + 1);
    shotListArray.push(newShot);
    let arrayLength = shotListArray.length
    container.insertAdjacentHTML("beforeend", shotListArray[arrayLength-1].htmlContent);
}

btn.addEventListener("click", createNewShot);

I just want the delete buttons to work as expected. I'm a little confused because when I look at the live server, I can see the class names are correct in the  tags for each of the buttons.


问:
Flume use regex to only include certain data with multiple regex statments
Sample Data:

```<code>ID  DATE READING    FLAG
1   2012-06-01  10  0
2   2012-06-01  10.5    0
3   2012-06-01  8.5 0
</code>```

I have a regex command to get the timestamp and send the data to directories biased on their
date:

```<code>agent1.sources.source1.interceptors = interceptor1
agent1.sources.source1.interceptors.interceptor1.type = regex_extractor
agent1.sources.source1.interceptors.interceptor1.regex = ([0-9][0-9][0-9][0-9]-[0-9][0-2]-[0-3][0-9])

</code>```

I then use sterilizers to timestamp and can set the correct directory. /yyyy/mm/dd

Now I also want to use a second regex interceptor to only show the data in the 3rd column (Reading) of the tab separated file. I can do this in the terminal with grep running a regex command using -o, but can not seem to figure it out in flume.

The desired output of the second regex command would be

```<code>10
10.5
8.5
</code>```

Also I am not sure if regex is best for this, but to my knowledge flume does not have a header filter.

Any help or suggestions is much appreciated

Body:
Sample Data:

ID  DATE READING    FLAG
1   2012-06-01  10  0
2   2012-06-01  10.5    0
3   2012-06-01  8.5 0

I have a regex command to get the timestamp and send the data to directories biased on their
date:

agent1.sources.source1.interceptors = interceptor1
agent1.sources.source1.interceptors.interceptor1.type = regex_extractor
agent1.sources.source1.interceptors.interceptor1.regex = ([0-9][0-9][0-9][0-9]-[0-9][0-2]-[0-3][0-9])

I then use sterilizers to timestamp and can set the correct directory. /yyyy/mm/dd

Now I also want to use a second regex interceptor to only show the data in the 3rd column (Reading) of the tab separated file. I can do this in the terminal with grep running a regex command using -o, but can not seem to figure it out in flume.

The desired output of the second regex command would be

10
10.5
8.5

Also I am not sure if regex is best for this, but to my knowledge flume does not have a header filter.

Any help or suggestions is much appreciated


问:
Can I import some Typescript types from apexchart library?
I'm using Apexcharts with React + Typescript. Can I somehow use i.e. ApexAxisChartSeries type from  Apexcharts library to use it in my typescript code? Something like this:</p>
```<code>const getSeriesNames = (series: ApexAxisChartSeries): string[] => {
...
</code>```

Body:
I'm using Apexcharts with React + Typescript. Can I somehow use i.e. ApexAxisChartSeries type from  Apexcharts library to use it in my typescript code? Something like this:

const getSeriesNames = (series: ApexAxisChartSeries): string[] => {
...


问:
How to update options selected in generate react component command?
Command I ran:
npx generate-react-cli component MyComponent

There are options to choose from for styles and tests, etc.
I would like to update those choices.

I tried clearing npx cache using the command: npx clear-npx-cache hoping that would remove these choices from it, but apparently not.


问:
Checking external private errors
I have a package which does some error checking for specific error types.  One of the errors is from an external package, its fields are all unexported as well as the relevant creation func, so I cant instantiate it in my test, like below.

```<code>type Error struct {
    message string
    condition bool
}

func (e *Error) IsCondition() bool {
    return e.condition
}

func NewError(message string) *Error {
    return &Error{message: message}
}

func newErrorWithCondition(message string, condition bool) *Error {
    return &Error{message: message, condition: condition}
}
</code>```

I want to implement a test in my package that checks if the error has the condition set or, as a different path is executed in each case but have no way of instantiating it?  Is there a way I can test this?

Im testing something thats like,

```<code>func HandleErr(err error) error {
    var specificError Error

    switch {
    case errors.As(err, &specificError):
        return something
    default:
        return another thing
    }
}
</code>```

Title: Checking external private errors

Body:
I have a package which does some error checking for specific error types.  One of the errors is from an external package, its fields are all unexported as well as the relevant creation func, so I cant instantiate it in my test, like below.

type Error struct {
    message string
    condition bool
}

func (e *Error) IsCondition() bool {
    return e.condition
}

func NewError(message string) *Error {
    return &Error{message: message}
}

func newErrorWithCondition(message string, condition bool) *Error {
    return &Error{message: message, condition: condition}
}

I want to implement a test in my package that checks if the error has the condition set or, as a different path is executed in each case but have no way of instantiating it?  Is there a way I can test this?

Im testing something thats like,

func HandleErr(err error) error {
    var specificError Error

    switch {
    case errors.As(err, &specificError):
        return something
    default:
        return another thing
    }
}


问:
easyExcel version 2. X conflicts with poi 3.9
What to do if the easyExcel 2. X version conflicts with the poi 3.9 version? The poi version cannot be changed. What version of easyExcel can be changed

Find the easyExcel version corresponding to poi3.9


问:
Unable to change cursor when PointerEvent is a stylus in MouseRegion flutter

MouseRegion(
    cursor: SystemMouseCursors.precise,
    onHover: (event) {
        print("Event: ${event.kind}, ${event.localPosition}");
    }
    onError: (event) {
        print("onExit");
    }
    child: ...
)
```

When using a mouse, the cursor is changed, and both onEnter and onExit functions are called. But when using a pen tablet (xp-pen or wacom) the pointer event is detected as PointerDeviceKind.stylus in onHover function, but the cursor is not changed, neither is onEnter or onExit is called.

Body:
MouseRegion(
    cursor: SystemMouseCursors.precise,
    onHover: (event) {
        print("Event: ${event.kind}, ${event.localPosition}");
    }
    onError: (event) {
        print("onExit");
    }
    child: ...
)

When using a mouse, the cursor is changed, and both onEnter and onExit functions are called. But when using a pen tablet (xp-pen or wacom) the pointer event is detected as PointerDeviceKind.stylus in onHover function, but the cursor is not changed, neither is onEnter or onExit is called.


问:
How to delete particular datas from BigQuery Using Python
I'm trying to delete some particular data from BigQuery using service account through python. I have listed possible steps to do this:

connect to the bigquery using service account

read the data

filter out the data--- I want to filter out the data using columns "plan_from" and "plan_to." In the bigquery, these columns are in the date formats. When I am reading it on python, its showing object format. I want to filter date based on dates. Then I will move to step 4.

then drop it

```<code>here is the sample code:

import os
import pandas as pd
from google.cloud import bigquery

#step 1 Connect to the bigquery
os.environ['XXX_OP_CREDENTIALS'] = 'pathways to get service account json file in my local system'
key_path = os.environ["XXX_OP_CREDENTIALS"]
BQ_CLIENT = bigquery.Client.from_service_account_json(key_path)

#step 2  Read the data

query= '''SELECT * FROM datalake.DATASET.tablename'''
df=BQ_CLIENT.query(query).result().to_dataframe()

#step3 filter the data

filtered_df = df[(df.plan_from == '2022-11-14') & (df.plan_from == '2022-11-21')
                  & (df.plan_from == '2022-11-28') & (df.plan_from== '2022-12-05')
                  & (df.plan_to == '2022-12-15') & (df.plan_to == '2022-12-08')
                                  & (df.plan_to == '2022-12-01')
                                  & (df.plan_to == '2022-11-24')]

It's throwing an error empty dataframe. How can filter out the data and drop it? Can you please help. Thanks
</code>```

Body:
I'm trying to delete some particular data from BigQuery using service account through python. I have listed possible steps to do this:

connect to the bigquery using service account

read the data

filter out the data--- I want to filter out the data using columns "plan_from" and "plan_to." In the bigquery, these columns are in the date formats. When I am reading it on python, its showing object format. I want to filter date based on dates. Then I will move to step 4.

then drop it

here is the sample code:

import os
import pandas as pd
from google.cloud import bigquery

#step 1 Connect to the bigquery
os.environ['XXX_OP_CREDENTIALS'] = 'pathways to get service account json file in my local system'
key_path = os.environ["XXX_OP_CREDENTIALS"]
BQ_CLIENT = bigquery.Client.from_service_account_json(key_path)

#step 2  Read the data

query= '''SELECT * FROM datalake.DATASET.tablename'''
df=BQ_CLIENT.query(query).result().to_dataframe()

#step3 filter the data

filtered_df = df[(df.plan_from == '2022-11-14') & (df.plan_from == '2022-11-21')
                  & (df.plan_from == '2022-11-28') & (df.plan_from== '2022-12-05')
                  & (df.plan_to == '2022-12-15') & (df.plan_to == '2022-12-08')
                                  & (df.plan_to == '2022-12-01')
                                  & (df.plan_to == '2022-11-24')]

It's throwing an error empty dataframe. How can filter out the data and drop it? Can you please help. Thanks


问:
How to embed a video stream that uses MPEG-DASH protocol to my website?
```<code>This post is written with the google translator because I only know Spanish
</code>```

For a long time I have seen that in the different websites that provide the service of watching television online for free I see that they use JwPlayer but I do not see the way to use it for streams, I have only found the way to use it with normal .mp4 videos etc, not with streams Is there another free or open source alternative that I can use? I have to say that this is my first project as a web programmer, I only know basic html and css but could you help me

```<code></code>```
```<code>I tried different ways, embed scripts but none managed to work, they only worked for the protocol (HLS) and not for (MPEG-DASH) and its similarities
</code>```

Body:
This post is written with the google translator because I only know Spanish

For a long time I have seen that in the different websites that provide the service of watching television online for free I see that they use JwPlayer but I do not see the way to use it for streams, I have only found the way to use it with normal .mp4 videos etc, not with streams Is there another free or open source alternative that I can use? I have to say that this is my first project as a web programmer, I only know basic html and css but could you help me

I tried different ways, embed scripts but none managed to work, they only worked for the protocol (HLS) and not for (MPEG-DASH) and its similarities