问:
error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'
Am getting this error and multiple others about binding like this
:7:21 - error NG8001: 'app-custom-datepicker' is not a known element
the issue is i a have imported all the required modules in the app.module.ts file.
This has occured after moving components and services generated with angular 8 to angular 14.
Although i have cleaned this components and services one by one i cannot figure out where the error is coming from or the reason the app cannot build.


来源: stackexchange

问:
The local variable 'xlist' referenced before assignment is the issue in the python code. This is a facial emotion detection code using SVM algorithm
```<code>import math
import pickle
from xml.etree.ElementPath import prepare_predicate

import numpy as np
import cv2
#Import required modules
import cv2
import dlib

import imutils
import glob
import csv

from imutils import face_utils
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
# from sklearn.svm import LinearSVC
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
import matplotlib.pyplot as plt
from itertools import cycle
from scipy import interp
from sklearn.multiclass import OneVsRestClassifier, OneVsOneClassifier

from sklearn.svm import SVC
import pickle

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("D:\\study folder\\msc project SVM\\Emotion-Recognition-From-Facial-Expressions-master\\shape_predictor_68_face_landmarks.dat") #Or set this to whatever you named the downloaded file
clf = OneVsRestClassifier(SVC(kernel='linear', probability=True, tol=1e-3))
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))

def get_landmark_positions(img):
    detections = detector(img, 1)
    for k, d in enumerate(detections):  # For all detected face instances individually
        shape = predictor(img, d)  # Draw Facial Landmarks with the predictor class
        shape2 = face_utils.shape_to_np(shape)
        ch = cv2.convexHull(shape2[48:68])
        M = cv2.moments(shape2[48:68])
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        sum = 0
        for p in ch:
            i, j = p[0]
            v = (j - cY) / (i - cX)
            if ((i - cX) != 0):
                sum = sum + v

        xlist = []
        ylist = []
        (x, y, w, h) = cv2.boundingRect(np.array([shape2[48:68]]))
        roi = img[y:y + h, x:x + w]

        win_size = (64, 128)

        img = cv2.resize(img, win_size)
        # img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        d = cv2.HOGDescriptor()
        hog = d.compute(img)

        hog = hog.transpose()[0]
        hog = np.asarray(hog)

        for i in range(1, 68):  # Store X and Y coordinates in two lists
            # if(i >= 49 and i <= 68):
            #     print(shape.part(i))
            xlist.append(float(shape.part(i).x))
            ylist.append(float(shape.part(i).y))
    return xlist, ylist, hog,sum
def get_features(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # convert to grayscale
    clahe_image = clahe.apply(gray)
    xlist, ylist, hog, sum = get_landmark_positions(clahe_image)
    features2 = []
    features2.extend(hog)

cap = cv2.VideoCapture(0)
filename = 'D:\\study folder\\msc project SVM\\Emotion-Recognition-From-Facial-Expressions-master\\finalized_model.sav'

face_cascade = cv2.CascadeClassifier('D:\\study folder\\msc project SVM\\Emotion-Recognition-From-Facial-Expressions-master\\haarcascade_frontalface_default.xml')

clf = pickle.load(open(filename, 'rb'))
classes = ["HAPPY", "CONTEMPT", "ANGER", "DISGUST", "FEAR", "SADNESS", "SURPRISE", "NEUTRAL"]

while(True):
    _, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y+h, x:x+w]
    crop_img = frame
    if len(faces) == 0:
        crop_img = frame
    else:
        crop_img = frame[y:y + h, x:x + w]

    win_size = (64, 128)

    feat = get_features(crop_img)
    proba = clf.predict_proba([feat])
    pred_value = clf.predict([feat])[0]
    print(proba)
    print(math.floor((proba[0][
        0]*1000000))/10000)

    if(pred_value == 0):
        cv2.putText(frame, 'Happy: ' + str(math.floor((proba[0][0]*1000000))/10000) + '%', (30, 60),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'Happy: ' + str(math.floor((proba[0][0] * 1000000)) / 10000) + '%', (30, 60),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    if (pred_value == 2):
         cv2.putText(frame, 'ANGER: ' + str(math.floor((proba[0][1]*1000000))/10000), (30, 100),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'ANGER: ' + str(math.floor((proba[0][1] * 1000000)) / 10000), (30, 100),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)
    if (pred_value == 3):
        cv2.putText(frame, 'DISGUST: ' + str(math.floor((proba[0][2]*1000000))/10000), (30, 140),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'DISGUST: ' + str(math.floor((proba[0][2] * 1000000)) / 10000), (30, 140),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)
    if(pred_value == 4):
        cv2.putText(frame, 'FEAR: ' + str(math.floor((proba[0][3]*1000000))/10000), (30, 180),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'FEAR: ' + str(math.floor((proba[0][3] * 1000000)) / 10000), (30, 180),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    if (pred_value == 5):
        cv2.putText(frame, 'SADNESS: ' + str(math.floor((proba[0][4]*1000000))/10000), (30, 220),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'SADNESS: ' + str(math.floor((proba[0][4] * 1000000)) / 10000), (30, 220),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)
    if(pred_value == 6):
        cv2.putText(frame, 'SURPRISE: ' + str(math.floor((proba[0][5]*1000000))/10000), (30, 260),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'SURPRISE: ' + str(math.floor((proba[0][5] * 1000000)) / 10000), (30, 260),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    if (pred_value == 7):
        cv2.putText(frame, 'NEUTRAL: ' + str(math.floor((proba[0][6]*1000000))/10000), (30, 300),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'NEUTRAL: ' + str(math.floor((proba[0][6] * 1000000)) / 10000), (30, 300),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    cv2.imshow('frame',frame)
    key = cv2.waitKey(1)

    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()
</code>```
```<code>  Message=local variable 'xlist' referenced before assignment
  Source=D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py
  StackTrace:
  File "D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py", line 74, in get_landmark_positions
    return xlist, ylist, hog,sum
  File "D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py", line 78, in get_features
    xlist, ylist, hog, sum = get_landmark_positions(clahe_image)
  File "D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py", line 109, in <module> (Current frame)
    feat = get_features(crop_img)
</code>```

The local variable 'xlist' referenced before assignment is the issue in the python code. This is a facial emotion detection code using SVM algorithm.

ContentLicense: CC BY-SA 4.0

Body:
import math
import pickle
from xml.etree.ElementPath import prepare_predicate

import numpy as np
import cv2
#Import required modules
import cv2
import dlib

import imutils
import glob
import csv

from imutils import face_utils
from sklearn import datasets
from sklearn.multiclass import OneVsRestClassifier
# from sklearn.svm import LinearSVC
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix,classification_report
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
import matplotlib.pyplot as plt
from itertools import cycle
from scipy import interp
from sklearn.multiclass import OneVsRestClassifier, OneVsOneClassifier

from sklearn.svm import SVC
import pickle

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("D:\\study folder\\msc project SVM\\Emotion-Recognition-From-Facial-Expressions-master\\shape_predictor_68_face_landmarks.dat") #Or set this to whatever you named the downloaded file
clf = OneVsRestClassifier(SVC(kernel='linear', probability=True, tol=1e-3))
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))

def get_landmark_positions(img):
    detections = detector(img, 1)
    for k, d in enumerate(detections):  # For all detected face instances individually
        shape = predictor(img, d)  # Draw Facial Landmarks with the predictor class
        shape2 = face_utils.shape_to_np(shape)
        ch = cv2.convexHull(shape2[48:68])
        M = cv2.moments(shape2[48:68])
        cX = int(M["m10"] / M["m00"])
        cY = int(M["m01"] / M["m00"])
        sum = 0
        for p in ch:
            i, j = p[0]
            v = (j - cY) / (i - cX)
            if ((i - cX) != 0):
                sum = sum + v

        xlist = []
        ylist = []
        (x, y, w, h) = cv2.boundingRect(np.array([shape2[48:68]]))
        roi = img[y:y + h, x:x + w]

        win_size = (64, 128)

        img = cv2.resize(img, win_size)
        # img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        d = cv2.HOGDescriptor()
        hog = d.compute(img)

        hog = hog.transpose()[0]
        hog = np.asarray(hog)

        for i in range(1, 68):  # Store X and Y coordinates in two lists
            # if(i >= 49 and i <= 68):
            #     print(shape.part(i))
            xlist.append(float(shape.part(i).x))
            ylist.append(float(shape.part(i).y))
    return xlist, ylist, hog,sum
def get_features(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # convert to grayscale
    clahe_image = clahe.apply(gray)
    xlist, ylist, hog, sum = get_landmark_positions(clahe_image)
    features2 = []
    features2.extend(hog)

cap = cv2.VideoCapture(0)
filename = 'D:\\study folder\\msc project SVM\\Emotion-Recognition-From-Facial-Expressions-master\\finalized_model.sav'

face_cascade = cv2.CascadeClassifier('D:\\study folder\\msc project SVM\\Emotion-Recognition-From-Facial-Expressions-master\\haarcascade_frontalface_default.xml')

clf = pickle.load(open(filename, 'rb'))
classes = ["HAPPY", "CONTEMPT", "ANGER", "DISGUST", "FEAR", "SADNESS", "SURPRISE", "NEUTRAL"]

while(True):
    _, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
        roi_gray = gray[y:y+h, x:x+w]
        roi_color = frame[y:y+h, x:x+w]
    crop_img = frame
    if len(faces) == 0:
        crop_img = frame
    else:
        crop_img = frame[y:y + h, x:x + w]

    win_size = (64, 128)

    feat = get_features(crop_img)
    proba = clf.predict_proba([feat])
    pred_value = clf.predict([feat])[0]
    print(proba)
    print(math.floor((proba[0][
        0]*1000000))/10000)

    if(pred_value == 0):
        cv2.putText(frame, 'Happy: ' + str(math.floor((proba[0][0]*1000000))/10000) + '%', (30, 60),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'Happy: ' + str(math.floor((proba[0][0] * 1000000)) / 10000) + '%', (30, 60),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    if (pred_value == 2):
         cv2.putText(frame, 'ANGER: ' + str(math.floor((proba[0][1]*1000000))/10000), (30, 100),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'ANGER: ' + str(math.floor((proba[0][1] * 1000000)) / 10000), (30, 100),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)
    if (pred_value == 3):
        cv2.putText(frame, 'DISGUST: ' + str(math.floor((proba[0][2]*1000000))/10000), (30, 140),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'DISGUST: ' + str(math.floor((proba[0][2] * 1000000)) / 10000), (30, 140),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)
    if(pred_value == 4):
        cv2.putText(frame, 'FEAR: ' + str(math.floor((proba[0][3]*1000000))/10000), (30, 180),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'FEAR: ' + str(math.floor((proba[0][3] * 1000000)) / 10000), (30, 180),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    if (pred_value == 5):
        cv2.putText(frame, 'SADNESS: ' + str(math.floor((proba[0][4]*1000000))/10000), (30, 220),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'SADNESS: ' + str(math.floor((proba[0][4] * 1000000)) / 10000), (30, 220),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)
    if(pred_value == 6):
        cv2.putText(frame, 'SURPRISE: ' + str(math.floor((proba[0][5]*1000000))/10000), (30, 260),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'SURPRISE: ' + str(math.floor((proba[0][5] * 1000000)) / 10000), (30, 260),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    if (pred_value == 7):
        cv2.putText(frame, 'NEUTRAL: ' + str(math.floor((proba[0][6]*1000000))/10000), (30, 300),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2, cv2.LINE_AA)
    else:
        cv2.putText(frame, 'NEUTRAL: ' + str(math.floor((proba[0][6] * 1000000)) / 10000), (30, 300),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2, cv2.LINE_AA)

    cv2.imshow('frame',frame)
    key = cv2.waitKey(1)

    if key == 27:
        break

cap.release()
cv2.destroyAllWindows()

  Message=local variable 'xlist' referenced before assignment
  Source=D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py
  StackTrace:
  File "D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py", line 74, in get_landmark_positions
    return xlist, ylist, hog,sum
  File "D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py", line 78, in get_features
    xlist, ylist, hog, sum = get_landmark_positions(clahe_image)
  File "D:\study folder\msc project SVM\Emotion-Recognition-From-Facial-Expressions-master\live.py", line 109, in <module> (Current frame)
    feat = get_features(crop_img)

The local variable 'xlist' referenced before assignment is the issue in the python code. This is a facial emotion detection code using SVM algorithm.


问:
ObjectWriter print json double with precision
Giving the following code:

```<code>ArrayList<ActionOutput> res = manager.getRes();
ObjectWriter objectWriter = objectMapper.writer();
objectWriter = objectWriter.withDefaultPrettyPrinter();
objectWriter.writeValue(new File(args[1]), res);
</code>```

Let's say a member from ActionOutput is a list of objects, and that object contains a double instance variable.

I want to print in a file that double with precision at .00 (13.2 -> 13.20, 14.23423 -> 14.23).

How can I configure my objectWriter to write my JSON file this way?

Body:
Giving the following code:

ArrayList<ActionOutput> res = manager.getRes();
ObjectWriter objectWriter = objectMapper.writer();
objectWriter = objectWriter.withDefaultPrettyPrinter();
objectWriter.writeValue(new File(args[1]), res);

Let's say a member from ActionOutput is a list of objects, and that object contains a double instance variable.

I want to print in a file that double with precision at .00 (13.2 -> 13.20, 14.23423 -> 14.23).

How can I configure my objectWriter to write my JSON file this way?


问:
I can't edit grid template area with my JavaScript
i can't edit my grid template area throught my javascript
i write code to make code update the node map and this part of code is to evaluate node map to grid template area but i couldnt figure it out how to solve this problem can some help me please

createMap() {
        let gridTemplate = []
        let str = ``
        this.map.forEach(xLayer => {
            let row = xLayer.map(a => {
                //convert a to [a.name, a.position] if a is not blank space
                a = (a == '.') ? '.' : `[${a[0]}, ${a[1]}]`
                return a
            })

            str += `"${row.join(' ')}"`
            gridTemplate.push(row.join(' '))
        })
        document.getElementById("viewer").style.gridTemplateAreas = `
        "${gridTemplate[0]}"
        "${gridTemplate[1]}"
        "${gridTemplate[2]}"
        "${gridTemplate[3]}"
        "${gridTemplate[4]}"
        "${gridTemplate[5]}"
        "${gridTemplate[6]}"
        "${gridTemplate[7]}"
        "${gridTemplate[8]}"
        "${gridTemplate[9]}"
        "${gridTemplate[10]}"
        "${gridTemplate[11]}"
        "${gridTemplate[12]}"
        "${gridTemplate[13]}"
        "${gridTemplate[14]}"
        `
        console.log(document.getElementById("viewer").style.gridTemplateAreas)
        //
    console.log(gridTemplate)
    //alot of
}
```

i try decrease the line of grid template, but it work when line is lower than 5

Body:
i can't edit my grid template area throught my javascript
i write code to make code update the node map and this part of code is to evaluate node map to grid template area but i couldnt figure it out how to solve this problem can some help me please

createMap() {
        let gridTemplate = []
        let str = ``
        this.map.forEach(xLayer => {
            let row = xLayer.map(a => {
                //convert a to [a.name, a.position] if a is not blank space
                a = (a == '.') ? '.' : `[${a[0]}, ${a[1]}]`
                return a
            })

            str += `"${row.join(' ')}"`
            gridTemplate.push(row.join(' '))
        })
        document.getElementById("viewer").style.gridTemplateAreas = `
        "${gridTemplate[0]}"
        "${gridTemplate[1]}"
        "${gridTemplate[2]}"
        "${gridTemplate[3]}"
        "${gridTemplate[4]}"
        "${gridTemplate[5]}"
        "${gridTemplate[6]}"
        "${gridTemplate[7]}"
        "${gridTemplate[8]}"
        "${gridTemplate[9]}"
        "${gridTemplate[10]}"
        "${gridTemplate[11]}"
        "${gridTemplate[12]}"
        "${gridTemplate[13]}"
        "${gridTemplate[14]}"
        `
        console.log(document.getElementById("viewer").style.gridTemplateAreas)
        //
    console.log(gridTemplate)
    //alot of
}

i try decrease the line of grid template, but it work when line is lower than 5


问:
Expose filter in views not working for anonymous user in Drupal 9
In a page views when I use exposed filter for any fields no results are showing. Without filter results are displaying.
It's in Drupal 9. Please help me on this.

I create a view in drupal 9.
Create a filter using exposed the title field.
No results are showing in row with filter.
Results are showing without exposed filter.
But it should work with filters. I am facing this issue first time.


问:
how to compare 2 distribution with log-liklihood ratio with compare_distributions(d1, d2)
I want to compare power law distribution with log-normal using likelihood ratio test.I use power law package and use the code below with continuous data set of one variable.According to clauset et al.(2009) If this p-value is small ( p < 0.1) then it is unlikely that the observed sign is a chance result of fluctuations and the sign is a reliable indicator of which model is the better fit to the data. If p is large on the other hand, the sign is not reliable and the test does not favor either model over the other.But in case of my data, the p-value is smaller than 0.1, hence the sign is a reliable indicator of which model is the better fit.by using the below code I got 500 rows with 2 column of x and ratio. but the sign of ratio is both positive and negative. So, I don;t know using the below code, which one is the log likelihood ratio to infer from that. An screen of output is attached.
the code is :

```<code>m1 = conpl$new(data) m1$setXmin(estimate_xmin(m1))

########################################################
##Exponential #
#######################################################
m2 = conlnorm$new(data) m2$setXmin(m1$getXmin()) est2 = estimate_pars(m2) m2$setPars(est2$pars)

########################################################
##Vuong's test #
########################################################
comp = compare_distributions(m1, m2)
</code>```

Body:
I want to compare power law distribution with log-normal using likelihood ratio test.I use power law package and use the code below with continuous data set of one variable.According to clauset et al.(2009) If this p-value is small ( p < 0.1) then it is unlikely that the observed sign is a chance result of fluctuations and the sign is a reliable indicator of which model is the better fit to the data. If p is large on the other hand, the sign is not reliable and the test does not favor either model over the other.But in case of my data, the p-value is smaller than 0.1, hence the sign is a reliable indicator of which model is the better fit.by using the below code I got 500 rows with 2 column of x and ratio. but the sign of ratio is both positive and negative. So, I don;t know using the below code, which one is the log likelihood ratio to infer from that. An screen of output is attached.
the code is :

m1 = conpl$new(data) m1$setXmin(estimate_xmin(m1))

########################################################
##Exponential #
#######################################################
m2 = conlnorm$new(data) m2$setXmin(m1$getXmin()) est2 = estimate_pars(m2) m2$setPars(est2$pars)

########################################################
##Vuong's test #
########################################################
comp = compare_distributions(m1, m2)


问:
how to set best kernel size on conv2D
how to setup conv2d layey to get good filter results? I have tried to setup the conv2d layer as below. but the filter results are not good so I don't get good results when training.

```<code>X Data:

    [[  0.   0.   0.   0.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]
     [ 46.  35.   1.   0.   0.   0.]
     [  2.  48. 106. 143.  72.   0.]
     [ 82.  75. 135. 147. 152.  19.]
     [100.  89. 130. 140. 148. 131.]
     [ 19.  45.  69. 121. 130. 132.]
     [  0.   0.   0.  94. 113.   0.]
     [  0.   0.   0.  66.  79.   0.]
     [  0.   0.  38.  84.   0.   0.]
     [  0.   0.  26.  59.   0.   0.]
     [  2.  51.  68.  65.   0.   0.]
     [ 14.  68.  76.  38.   0.   0.]
     [ 65.  80. 101.  46.   0.   0.]
     [ 52.  64.  90.  62.   0.   0.]
     [ 14.  33.  33.   6.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]]

    X Data Shape: (19, 6)
Y Data :
[3.22531]
X Data Shape: (1,)
</code>```

below is my conv2d layer:

```<code>img_width, img_height, img_num_channels = 19, 6, 1

input_shape = (img_width, img_height, img_num_channels)

model = Sequential()
model.add(Conv2D(128, kernel_size=(5, 5), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(1, 1)))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
</code>```

Title: how to set best kernel size on conv2D

Body:
how to setup conv2d layey to get good filter results? I have tried to setup the conv2d layer as below. but the filter results are not good so I don't get good results when training.

X Data:

    [[  0.   0.   0.   0.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]
     [ 46.  35.   1.   0.   0.   0.]
     [  2.  48. 106. 143.  72.   0.]
     [ 82.  75. 135. 147. 152.  19.]
     [100.  89. 130. 140. 148. 131.]
     [ 19.  45.  69. 121. 130. 132.]
     [  0.   0.   0.  94. 113.   0.]
     [  0.   0.   0.  66.  79.   0.]
     [  0.   0.  38.  84.   0.   0.]
     [  0.   0.  26.  59.   0.   0.]
     [  2.  51.  68.  65.   0.   0.]
     [ 14.  68.  76.  38.   0.   0.]
     [ 65.  80. 101.  46.   0.   0.]
     [ 52.  64.  90.  62.   0.   0.]
     [ 14.  33.  33.   6.   0.   0.]
     [  0.   0.   0.   0.   0.   0.]]

    X Data Shape: (19, 6)
Y Data :
[3.22531]
X Data Shape: (1,)

below is my conv2d layer:

img_width, img_height, img_num_channels = 19, 6, 1

input_shape = (img_width, img_height, img_num_channels)

model = Sequential()
model.add(Conv2D(128, kernel_size=(5, 5), activation='relu', input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(1, 1)))

model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(1, activation='sigmoid'))


问:
How to check nulleable value in where clause for join table contains DefaultIfEmpty extention in LINQ
I am using the Linq query to fetch the result from Database. For left join, I am using the DefaultIfEmpty extension. But while using the where clause for the left join table It is getting a null exception. So tried to use the below code but it's not working. returning empty results. If the rcs table is empty It is affecting the remaining joins.</p>
```<code>from r in _db.TableA
join rcs in _db.TableB.AsNoTracking() on r.ID equals rcs.ID into rrcs
from rcs in rrcs.DefaultIfEmpty()
where r.Id = 1 && rcs?.isvaleexist = false
select new classprop {r.id}

</code>```

Body:
I am using the Linq query to fetch the result from Database. For left join, I am using the DefaultIfEmpty extension. But while using the where clause for the left join table It is getting a null exception. So tried to use the below code but it's not working. returning empty results. If the rcs table is empty It is affecting the remaining joins.

from r in _db.TableA
join rcs in _db.TableB.AsNoTracking() on r.ID equals rcs.ID into rrcs
from rcs in rrcs.DefaultIfEmpty()
where r.Id = 1 && rcs?.isvaleexist = false
select new classprop {r.id}


问:
What's the difference between Solr queries "* AND a OR b" and "a OR b"?
In our application that uses Solr as its backend for search, we have two ways of doing an OR search. Either we type "a OR b" directly into the search box, or we use a filter tool to input the terms, which transforms the query into "* AND a OR b".

In theory, this should give the same results. In practice, it doesn't always give the same results.

Looking at the parsed query using the debug option, I see a subtle difference:

The first query results in +(+((content_all:a)^1.0) ((content_all:b)^1.0)) ()

The second query results in +(((content_all:a)^1.0) ((content_all:b)^1.0)) ()

As you can see, a + is missing in the second query, and I think that's why it gives less results than the first.

Trying different things, I've come to the conclusion that the second part of the query is essentially ignored. If I type "* AND a" I get the same amount of results as the second query, and the parsed query is +(+((content_all:a)^1.0)) ()

Does anyone have an idea as to what's going on? I'm using Dismax.


问:
Setting LocalDateTime precision when using @CreationTimestamp/@UpdateTimestamp in hibernate (Spring-Data-JPA)
I have a bunch of failing test due to comparisons and a mismatch of precision between LocalDateTime and what MySQL support. The code is creating LocalDateTime within microsecond precision, where as MySQL only supports up to nanosecond precision.

I have an entity as such:

```<code>@AllArgsConstructor
@Data
@MappedSuperclass
@NoArgsConstructor
@SuperBuilder
@Table("my_table")
public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @CreationTimestamp
    @Column(updatable = false)
    private LocalDateTime created;

    @UpdateTimestamp
    @Column(name = "last_update")
    private LocalDateTime updated;
}
</code>```

With corresponding table:

```<code>CREATE TABLE `my_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `created` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  `name` varchar(128) DEFAULT NULL,
  `last_update` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  PRIMARY KEY (`id`)
);
</code>```

When I use my repository to save an Entity within a test, the test fails.

```<code>@Autowired
Repository<MyEntity, Id> aSpringDataRepository;

@Test
public void myTest() {

   // given
   MyEntity = new MyEntity();
   myEntity.setName("Foo Bar");

   // when
   aSpringDataRepository.save(myEntity);

   // then
   MyEntity myEntityFromDatabase = aSpringDataRepository.findById(myEntity.getId());
   assertThat(myEntity).isEqualTo(myEntityFromDatabase) //it fails here
}
</code>```

With

```<code>myEntity.created == "2022-12-09T13:09:52.125720132"
myEntity.updated == "2022-12-09T13:09:52.125760760"
</code>```

And

```<code>myEntityFromDatabase.created == "2022-12-09T13:09:52.125720"
myEntityFromDatabase.updated == "2022-12-09T13:09:52.125761"
</code>```

I can see it's a precision issue. Unfortunately MySQL only supports nonasecond, so I can't change the schema. I could also update my test to be the following, but I think it's just a bit hacky.

```<code>@Autowired
Repository<MyEntity, Id> aSpringDataRepository;

@Test
public void myTest() {

   // given
   MyEntity = new MyEntity();
   myEntity.setName("Foo Bar");

   // when
   aSpringDataRepository.save(myEntity);

   // then
   MyEntity myEntityFromDatabase = aSpringDataRepository.findById(myEntity.getId());
   myEntity.setCreated(myEntityFromDatabase.getCreated());
   myEntity.setUpdated(myEntityFromDatabase.getUpdated());
   assertThat(myEntity).isEqualTo(myEntityFromDatabase) //now it passes

}
</code>```

Is there a way, presumably via annotations, where I can force the precision of these values? Or is this just an irritating quirk I'm going to have to lump?

Body:
I have a bunch of failing test due to comparisons and a mismatch of precision between LocalDateTime and what MySQL support. The code is creating LocalDateTime within microsecond precision, where as MySQL only supports up to nanosecond precision.

I have an entity as such:

@AllArgsConstructor
@Data
@MappedSuperclass
@NoArgsConstructor
@SuperBuilder
@Table("my_table")
public class MyEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @CreationTimestamp
    @Column(updatable = false)
    private LocalDateTime created;

    @UpdateTimestamp
    @Column(name = "last_update")
    private LocalDateTime updated;
}

With corresponding table:

CREATE TABLE `my_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `created` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
  `name` varchar(128) DEFAULT NULL,
  `last_update` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
  PRIMARY KEY (`id`)
);

When I use my repository to save an Entity within a test, the test fails.

@Autowired
Repository<MyEntity, Id> aSpringDataRepository;

@Test
public void myTest() {

   // given
   MyEntity = new MyEntity();
   myEntity.setName("Foo Bar");

   // when
   aSpringDataRepository.save(myEntity);

   // then
   MyEntity myEntityFromDatabase = aSpringDataRepository.findById(myEntity.getId());
   assertThat(myEntity).isEqualTo(myEntityFromDatabase) //it fails here
}

With

myEntity.created == "2022-12-09T13:09:52.125720132"
myEntity.updated == "2022-12-09T13:09:52.125760760"

And

myEntityFromDatabase.created == "2022-12-09T13:09:52.125720"
myEntityFromDatabase.updated == "2022-12-09T13:09:52.125761"

I can see it's a precision issue. Unfortunately MySQL only supports nonasecond, so I can't change the schema. I could also update my test to be the following, but I think it's just a bit hacky.

@Autowired
Repository<MyEntity, Id> aSpringDataRepository;

@Test
public void myTest() {

   // given
   MyEntity = new MyEntity();
   myEntity.setName("Foo Bar");

   // when
   aSpringDataRepository.save(myEntity);

   // then
   MyEntity myEntityFromDatabase = aSpringDataRepository.findById(myEntity.getId());
   myEntity.setCreated(myEntityFromDatabase.getCreated());
   myEntity.setUpdated(myEntityFromDatabase.getUpdated());
   assertThat(myEntity).isEqualTo(myEntityFromDatabase) //now it passes

}

Is there a way, presumably via annotations, where I can force the precision of these values? Or is this just an irritating quirk I'm going to have to lump?


问:
Excel VBA UserForm Code Stops Running After Cell Change
I am using a UserForm to fill in two cells with data selected from a list box. The list box is populated from a table on another sheet.

Currently the code will update the value in B2 and then stops executing, before B3 is edited. I can't see what is causing the code to stop at this point.

Here is the code for the UserForm, which is activated by a double click event.

```<code>Private Sub UserForm_Initialize()

Dim sh As Worksheet
Set sh = Sheets("Table")

User_List.List = sh.Range("A1:B10").Value
User_List.ColumnWidths = "85;135"

End Sub

Private Sub OK_Button_Click()

Range("B2").Value = User_List.List(User_List.ListIndex, 0)
Range("B3").Value = User_List.List(User_List.ListIndex, 1)

Unload Me

End Sub
</code>```

Body:
I am using a UserForm to fill in two cells with data selected from a list box. The list box is populated from a table on another sheet.

Currently the code will update the value in B2 and then stops executing, before B3 is edited. I can't see what is causing the code to stop at this point.

Here is the code for the UserForm, which is activated by a double click event.

Private Sub UserForm_Initialize()

Dim sh As Worksheet
Set sh = Sheets("Table")

User_List.List = sh.Range("A1:B10").Value
User_List.ColumnWidths = "85;135"

End Sub

Private Sub OK_Button_Click()

Range("B2").Value = User_List.List(User_List.ListIndex, 0)
Range("B3").Value = User_List.List(User_List.ListIndex, 1)

Unload Me

End Sub


问:
Dynatrace api/v2/metrics response missing Metric Latency
I have a requirement where I need to know the latency of every metric and based on that I can write the logic to get the metrics. I went through the document and found api/v2/metrics provides the metric latency in the response as per the doc https://www.dynatrace.com/support/help/dynatrace-api/environment-api/metric-v2/get-all-metrics but somehow this is missing in the response.

Can anyone help me with this?


问:
React-intl defineMessage type assertion
We use enums for hooks to ingest in our messages files. It looks like this:

```<code>import { defineMessages } from 'react-intl';

export enum SettingsMessages {
  Settings = 'app.views.settings.title',
}

export default defineMessages({
  settings: {
    id: 'app.views.settings.title',
    defaultMessage: 'Settings',
  },
});
</code>```

It works well but I'd like to enforce the following things with typescript:

The messages object is exactly that structure. No more, no less

There is a 1:1 relationship between the enum values and the id keys in the object. I'd like TypeScript to throw an error if the enum value is not located in the object and vice versa. Also it'd be nice if it threw an error if there is a message id that is not in the enum.

Essentially since there are two sources of truth for this, I'd like to make it a bit safer against typos and forgetting to add it as these files get pretty large. Removing the enums is out of the question

Any help is appreciated

Title: React-intl defineMessage type assertion

Body:
We use enums for hooks to ingest in our messages files. It looks like this:

import { defineMessages } from 'react-intl';

export enum SettingsMessages {
  Settings = 'app.views.settings.title',
}

export default defineMessages({
  settings: {
    id: 'app.views.settings.title',
    defaultMessage: 'Settings',
  },
});

It works well but I'd like to enforce the following things with typescript:

The messages object is exactly that structure. No more, no less

There is a 1:1 relationship between the enum values and the id keys in the object. I'd like TypeScript to throw an error if the enum value is not located in the object and vice versa. Also it'd be nice if it threw an error if there is a message id that is not in the enum.

Essentially since there are two sources of truth for this, I'd like to make it a bit safer against typos and forgetting to add it as these files get pretty large. Removing the enums is out of the question

Any help is appreciated


问:
Can I change the confiiguration inside an msbuild target?
In my projects I want to switch to Release mode every time someone wants to pack wit the following command

```<code>dotnet build "project.csproj"
</code>```

I have tried to use the following <Target> in my Directory.Build.props

```<code><Target Name="ChangeToReleaseOnPack" BeforeTargets="Pack">
    <Warning Text="You have packed with Release mode"/>
    <PropertyGroup>
        <Configuration>Release</Configuration>
    </PropertyGroup>
</Target>
</code>```

where afterwards the conditions for the Configuration are evaluated, e.g.:

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)'=='Debug|x64' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>false</Optimize>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <WarningLevel>4</WarningLevel>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    <ErrorReport>prompt</ErrorReport>
</PropertyGroup>
</code>```

When now building with dotnet pack I can see the warning text, when I'm building with dotnet build I can see no warning which lets me assume that at least the target is hit. But obviously the configuration was not changed.

I can see this also on the size of the output package, it differs.

Is there any experience out there with the same problem?

Body:
In my projects I want to switch to Release mode every time someone wants to pack wit the following command

dotnet build "project.csproj"

I have tried to use the following <Target> in my Directory.Build.props

<Target Name="ChangeToReleaseOnPack" BeforeTargets="Pack">
    <Warning Text="You have packed with Release mode"/>
    <PropertyGroup>
        <Configuration>Release</Configuration>
    </PropertyGroup>
</Target>

where afterwards the conditions for the Configuration are evaluated, e.g.:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)'=='Debug|x64' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>false</Optimize>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <WarningLevel>4</WarningLevel>
    <UseVSHostingProcess>false</UseVSHostingProcess>
    <TreatWarningsAsErrors>false</TreatWarningsAsErrors>
    <ErrorReport>prompt</ErrorReport>
</PropertyGroup>

When now building with dotnet pack I can see the warning text, when I'm building with dotnet build I can see no warning which lets me assume that at least the target is hit. But obviously the configuration was not changed.

I can see this also on the size of the output package, it differs.

Is there any experience out there with the same problem?


问:
draft-js convert to html to display on page
I'm looking for some help on how to convert a string of html like below to draftjs and convert back to html to display on a page as html without a rich text editor or WYSIWYG:

```<code>const htmlString = `<p>hello world</p>
   <ul>
     <li>hello</li>
     <li>world</li>
   <ul>
   <p>this is my string</p>`
</code>```

I have used draft-js method convertFromHtml which results in this:

```<code>{
    "contentBlocks": [
        {
            "key": "f9aci",
            "type": "unstyled",
            "text": "hello world  ",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        },
        {
            "key": "boi9l",
            "type": "unordered-list-item",
            "text": "hello ",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        },
        {
            "key": "fbf9j",
            "type": "unordered-list-item",
            "text": "world  ",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        },
        {
            "key": "ejvm",
            "type": "unstyled",
            "text": "this is my string",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        }
    ],
    "entityMap": {}
}
</code>```

i have tried using convertToRaw and then ConvertFromRaw with no avail just getting errors

Invariant Violation: invalid RawDraftContentState

My ultimate goal is to convert to draftjs for the server but when i receive the data to be able to convert back and display as html.

Body:
I'm looking for some help on how to convert a string of html like below to draftjs and convert back to html to display on a page as html without a rich text editor or WYSIWYG:

const htmlString = `
hello world

hello

world

this is my string
`

I have used draft-js method convertFromHtml which results in this:

{
    "contentBlocks": [
        {
            "key": "f9aci",
            "type": "unstyled",
            "text": "hello world  ",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        },
        {
            "key": "boi9l",
            "type": "unordered-list-item",
            "text": "hello ",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        },
        {
            "key": "fbf9j",
            "type": "unordered-list-item",
            "text": "world  ",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        },
        {
            "key": "ejvm",
            "type": "unstyled",
            "text": "this is my string",
            "characterList": [
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                },
                {
                    "style": [],
                    "entity": null
                }
            ],
            "depth": 0,
            "data": {}
        }
    ],
    "entityMap": {}
}

i have tried using convertToRaw and then ConvertFromRaw with no avail just getting errors

Invariant Violation: invalid RawDraftContentState

My ultimate goal is to convert to draftjs for the server but when i receive the data to be able to convert back and display as html.


问:
Add checkbox to Woocommerce gateway description
I need to add a required checkbox to the cheque gateway description on the Woocommerce checkout page if the order amount is greater than 200. I ave this:

```<code>add_filter( 'woocommerce_gateway_description',  'change_payment_gateway_description', 25, 2 );

function change_payment_gateway_description( $description, $gateway_id) {

global $woocommerce;
$total = WC()->cart->total; $minimum_amount = 200;

if( 'cheque' === $gateway_id && $total >=  $minimum_amount) {

    $description = '<p>My text</p><label class="custom-one woocommerce-form__label woocommerce-form__label-for-checkbox checkbox"><input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="custom_one"><span>I agree. *</span></label>';
}
return $description;
}
add_action('woocommerce_checkout_process',     'custom_checkbox_checkout_validation');
function custom_checkbox_checkout_validation() {
global $woocommerce;
$total = WC()->cart->total; $minimum_amount = 200;

$field_id = 'custom_one';

if( ! isset( $_POST[$field_id] ) || empty( $_POST[$field_id] && 'cheque' === $gateway_id && $total >= $minimum_amount ) )
    wc_add_notice( __("Please agree.","woocommerce"), "error" );
}
</code>```

It works, but the validation error message that should be displayed when the checkbox is NOT ticked is not working: It is always displayed when trying to place an order, regardless of whether the order amount is less than 200 or even if another gateway like COD is used. What do I need to change?

Body:
I need to add a required checkbox to the cheque gateway description on the Woocommerce checkout page if the order amount is greater than 200. I ave this:

add_filter( 'woocommerce_gateway_description',  'change_payment_gateway_description', 25, 2 );

function change_payment_gateway_description( $description, $gateway_id) {

global $woocommerce;
$total = WC()->cart->total; $minimum_amount = 200;

if( 'cheque' === $gateway_id && $total >=  $minimum_amount) {

    $description = '
My text
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" name="custom_one">I agree. *';
}
return $description;
}
add_action('woocommerce_checkout_process',     'custom_checkbox_checkout_validation');
function custom_checkbox_checkout_validation() {
global $woocommerce;
$total = WC()->cart->total; $minimum_amount = 200;

$field_id = 'custom_one';

if( ! isset( $_POST[$field_id] ) || empty( $_POST[$field_id] && 'cheque' === $gateway_id && $total >= $minimum_amount ) )
    wc_add_notice( __("Please agree.","woocommerce"), "error" );
}

It works, but the validation error message that should be displayed when the checkbox is NOT ticked is not working: It is always displayed when trying to place an order, regardless of whether the order amount is less than 200 or even if another gateway like COD is used. What do I need to change?


问:
Cant figure out whats wrong with my syntax - python Codevue practice - very basic beginner level
I'm not sure where I am going wrong with my code here are the instructions from codevue. It automatically starts with with the top portion up to print(line), then I fill the rest of the code out myself.

Input:
Each test case will pass this value to your code through stdin ("Standard In")

Output:
Each test case's Output value will be compared to what your code writes to stdout ("Standard Out").

If your program's output matches the Expected Output, the test case will pass and be shown in green in the output panel.

If your program's output does NOT math the Expected Output for a test case, the result will be displayed in red in the output panel.

Test 1
Test Input
"Test Case 3"
Expected Output
"Try writing code to pass all 3 tests"

Test 2
Test Input
"This is Test case 2"
Expected Output
"This is the expected Output. Try changing the code to write this to STDOUT for this case."

Test 3
Test Input
"This is the input for Test 1"
Expected Output
"This is the input for Test 1"

My syntax below here starting after print(line) call.

`

```<code>import sys

# This entire script will be run once for each Test Input.
# The Input for each test will be passed through the filelike object
# `sys.stdin` (STDIN).

# This provides a single line from the Test Input for each iteration.
for line in sys.stdin:
    # You'll want to write some code to pass all of the tests.
    # if "2" in line:
    #   print("This is the expected Output. Try changing the code to write this to STDOUT for this case.")

    # This writes `line` to STDOUT.
    print(line)
    x = input()

    if(x == "Test Case 3"):
        print("Try writing code to pass all 3 tests")
    elif(x == "This is Test case 2"):
        print("This is the expected Output. Try changing the code to write this to STDOUT for this case.")
    else:
        print("This is the input for Test 1")
</code>```

`

if else branches to execute one print function for three different input values.

Body:
I'm not sure where I am going wrong with my code here are the instructions from codevue. It automatically starts with with the top portion up to print(line), then I fill the rest of the code out myself.

Input:
Each test case will pass this value to your code through stdin ("Standard In")

Output:
Each test case's Output value will be compared to what your code writes to stdout ("Standard Out").

If your program's output matches the Expected Output, the test case will pass and be shown in green in the output panel.

If your program's output does NOT math the Expected Output for a test case, the result will be displayed in red in the output panel.

Test 1
Test Input
"Test Case 3"
Expected Output
"Try writing code to pass all 3 tests"

Test 2
Test Input
"This is Test case 2"
Expected Output
"This is the expected Output. Try changing the code to write this to STDOUT for this case."

Test 3
Test Input
"This is the input for Test 1"
Expected Output
"This is the input for Test 1"

My syntax below here starting after print(line) call.

`

import sys

# This entire script will be run once for each Test Input.
# The Input for each test will be passed through the filelike object
# `sys.stdin` (STDIN).

# This provides a single line from the Test Input for each iteration.
for line in sys.stdin:
    # You'll want to write some code to pass all of the tests.
    # if "2" in line:
    #   print("This is the expected Output. Try changing the code to write this to STDOUT for this case.")

    # This writes `line` to STDOUT.
    print(line)
    x = input()

    if(x == "Test Case 3"):
        print("Try writing code to pass all 3 tests")
    elif(x == "This is Test case 2"):
        print("This is the expected Output. Try changing the code to write this to STDOUT for this case.")
    else:
        print("This is the input for Test 1")

`

if else branches to execute one print function for three different input values.


问:
How to isolate one value of a returned object from firebase
I'm wondering how to isolate one value coming from an object in firebase - I have a document that I am using the following code to grab all objects under a folder -

```<code>async function ListImageData()
{
  const querySnapshot = await getDocs(collection(db, "users", "userUID2", "images"));
  querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", (doc.data()));
  });
}
</code>```

When I run the function, I get the following message in the browser console ^
Im wondering how to only get the blue value, and potentially separate it from other values in the future like tags ect.
Thanks!

Body:
I'm wondering how to isolate one value coming from an object in firebase - I have a document that I am using the following code to grab all objects under a folder -

async function ListImageData()
{
  const querySnapshot = await getDocs(collection(db, "users", "userUID2", "images"));
  querySnapshot.forEach((doc) => {
    console.log(doc.id, " => ", (doc.data()));
  });
}

When I run the function, I get the following message in the browser console ^
Im wondering how to only get the blue value, and potentially separate it from other values in the future like tags ect.
Thanks!


问:
Excel array formulas work for me but not for file recipient
I created an excel model recently which uses some array formulas - vlookups and sumproducts mostly. On my end, everything works, but when I send it to my colleague who uses the model, the array formulas just throw value errors.

I'm using the latest version of excel, so I didn't use curly brackets. My first guess was that my colleague had an older version of excel. Curly brackets and ctrl+shift+enter don't help. Even after an excel update on their end, though, they still get the same error on the exact same file that works for me.

Does anyone have any idea as to what's going on?


问:
Get Start Date of the Occurrence that is being accepted from a recurring appointment
I am trying to forward appointments from one email account to another.

I managed this for a single appointment.

For recurring appointments, when I accept, instead of the occurrence date, it gets the first date of the series.

Option Explicit
Private WithEvents newAppt As Items

Private Sub Application_Startup()
Dim objNS As NameSpace
  Set objNS = Application.Session
  Set newAppt = objNS.GetDefaultFolder(olFolderCalendar).Items
  Set objNS = Nothing
End Sub

Private Sub newAppt_ItemChange(ByVal Item As Object)

Dim I As Boolean 'control parameter to avoid unexpected duplications
i = True
Dim fwdAppt As Object
Set fwdAppt = Application.CreateItem(olAppointmentItem)

Debug.Print Item.RecurrenceState

If (Item.ResponseStatus = olResponseAccepted And Item.RequiredAttendees <> "email@domain.com") Then 'condition to avoid infinite loop
    With fwdAppt
        If (i = True) Then
            .Recipients.Add "email@domain.com"
            .MeetingStatus = olMeeting
            .subject = Item.subject
            .Start = Item.Start
            .End = Item.End
            .Duration = Item.Duration
            .Location = Item.Location
            .Body = "Required: " & Chr(13) & Item.RequiredAttendees & Chr(13) & Chr(13) & "Optional: " & Chr(13) & Item.OptionalAttendees & Chr(13) & Chr(13) & "Body: " & Item.Body
            .Send
            .Delete 'delete the forwarded appointment item to keep only the original in the calendar
            i = False
        End If
    End With
End If
End Sub
```

Debug.Print Item.RecurrenceState returns '1' which means the appointment is a master appointment, even when I open and accept a specific occurrence and select to open just that occurrence instead of the series.

Body:
I am trying to forward appointments from one email account to another.

I managed this for a single appointment.

For recurring appointments, when I accept, instead of the occurrence date, it gets the first date of the series.

Option Explicit
Private WithEvents newAppt As Items

Private Sub Application_Startup()
Dim objNS As NameSpace
  Set objNS = Application.Session
  Set newAppt = objNS.GetDefaultFolder(olFolderCalendar).Items
  Set objNS = Nothing
End Sub

Private Sub newAppt_ItemChange(ByVal Item As Object)

Dim I As Boolean 'control parameter to avoid unexpected duplications
i = True
Dim fwdAppt As Object
Set fwdAppt = Application.CreateItem(olAppointmentItem)

Debug.Print Item.RecurrenceState

If (Item.ResponseStatus = olResponseAccepted And Item.RequiredAttendees <> "email@domain.com") Then 'condition to avoid infinite loop
    With fwdAppt
        If (i = True) Then
            .Recipients.Add "email@domain.com"
            .MeetingStatus = olMeeting
            .subject = Item.subject
            .Start = Item.Start
            .End = Item.End
            .Duration = Item.Duration
            .Location = Item.Location
            .Body = "Required: " & Chr(13) & Item.RequiredAttendees & Chr(13) & Chr(13) & "Optional: " & Chr(13) & Item.OptionalAttendees & Chr(13) & Chr(13) & "Body: " & Item.Body
            .Send
            .Delete 'delete the forwarded appointment item to keep only the original in the calendar
            i = False
        End If
    End With
End If
End Sub

Debug.Print Item.RecurrenceState returns '1' which means the appointment is a master appointment, even when I open and accept a specific occurrence and select to open just that occurrence instead of the series.


问:
SwiftUI: Use Canvas (DragGesture) inside ScrollView
I want to add an image and canvas with DragGesture above in ScrollView, so I can zoom image and draw above it.

```<code>GeometryReader { proxy in
    ZStack {
        Image(uiImage: UIImage(named: "beach.jpg")!)
            .resizable()
            .scaledToFit()
            .frame(
                width: (UIScreen.main.bounds.width - 32)
            )
            .readSize { newSize in
                print("Image size: \(newSize)")
                canvasSize = newSize
            }

        canvas
            .readSize { newSize in
                print("Canvas size: \(newSize)")
                canvasSize = newSize
            }
            .background(Color.red.opacity(0.3))

        if let resultImageData = viewModel.resultImageData {
            Image(uiImage: UIImage(data: resultImageData)!)
                .resizable()
                .aspectRatio(contentMode: .fit)
        }
    }
    .fixedSize(horizontal: false, vertical: true)
    .padding(.top)
    .padding(.horizontal, 16)
    .modifier(
        ImageModifier(
            contentSize: CGSize(width: proxy.size.width, height: proxy.size.height),
            disabled: $disabled
        )
    )
}
</code>```

The ScrollView wrapper is inside ImageModifier:

```<code>ScrollView([.horizontal, .vertical], showsIndicators: false) {
    content
        .frame(width: contentSize.width * currentScale, height: contentSize.height * currentScale, alignment: .center)
        .modifier(PinchToZoom(minScale: min, maxScale: max, scale: $currentScale))
        .introspectScrollView { scrollView in
            scrollView.panGestureRecognizer.minimumNumberOfTouches = 2
        }
}
</code>```

But unfortunately even when I set minimum touches for ScrollView = 2, or set .allowsHitTesting(false), or set .scrollDisabled(true) for ScrollView I can't touch my canvas.

Did anybody made drag gestures for view inside ScrollView work with SwiftUI? Thanks

Body:
I want to add an image and canvas with DragGesture above in ScrollView, so I can zoom image and draw above it.

GeometryReader { proxy in
    ZStack {
        Image(uiImage: UIImage(named: "beach.jpg")!)
            .resizable()
            .scaledToFit()
            .frame(
                width: (UIScreen.main.bounds.width - 32)
            )
            .readSize { newSize in
                print("Image size: \(newSize)")
                canvasSize = newSize
            }

        canvas
            .readSize { newSize in
                print("Canvas size: \(newSize)")
                canvasSize = newSize
            }
            .background(Color.red.opacity(0.3))

        if let resultImageData = viewModel.resultImageData {
            Image(uiImage: UIImage(data: resultImageData)!)
                .resizable()
                .aspectRatio(contentMode: .fit)
        }
    }
    .fixedSize(horizontal: false, vertical: true)
    .padding(.top)
    .padding(.horizontal, 16)
    .modifier(
        ImageModifier(
            contentSize: CGSize(width: proxy.size.width, height: proxy.size.height),
            disabled: $disabled
        )
    )
}

The ScrollView wrapper is inside ImageModifier:

ScrollView([.horizontal, .vertical], showsIndicators: false) {
    content
        .frame(width: contentSize.width * currentScale, height: contentSize.height * currentScale, alignment: .center)
        .modifier(PinchToZoom(minScale: min, maxScale: max, scale: $currentScale))
        .introspectScrollView { scrollView in
            scrollView.panGestureRecognizer.minimumNumberOfTouches = 2
        }
}

But unfortunately even when I set minimum touches for ScrollView = 2, or set .allowsHitTesting(false), or set .scrollDisabled(true) for ScrollView I can't touch my canvas.

Did anybody made drag gestures for view inside ScrollView work with SwiftUI? Thanks


问:
RANKX Breaks with Rank Filter within Matrix Category
PBI Example

My dataset is records of losses by wtg by alarm.  I need to show the top 5 wtg's in each alarm by losses.  I also need to build charts for each of the top 10 alarms which show those 5 wtgs' losses.

enter image description here

These matrices are the same.  The only difference is that I've filtered the one on the right to only return the top 5 based on losses in that category.  Why aren't the top level categories still ranked in the same way when this filter is applied?

I've tried various things to try and exclude filters like Allselected, Allexcept, and in this example I tried creating a variable with All / Inscope.  The results are all the same.

Original Attempt- Works w/out filter -

```<code>Rank by Alarm = RANKX(ALL(Table[Alarm_Issue]),CALCULATE(SUM(Table[MWhLosses_Technical])))
</code>```

Rank w/ Variable - Works w/out filter:
below

I would very much appreciate some help!

```<code>Rank by Alarm w Variable =
var Issue Rank = RANKX( ALLSELECTED (TABLE [alarm_issue]), CALCULATE(SUM(TABLE[MWhLosses_Technical])))
var Result =
if(isinscope(Table [Alarm_Issue]),IssueRank)
Return
Result
</code>```

Body:
PBI Example

My dataset is records of losses by wtg by alarm.  I need to show the top 5 wtg's in each alarm by losses.  I also need to build charts for each of the top 10 alarms which show those 5 wtgs' losses.

enter image description here

These matrices are the same.  The only difference is that I've filtered the one on the right to only return the top 5 based on losses in that category.  Why aren't the top level categories still ranked in the same way when this filter is applied?

I've tried various things to try and exclude filters like Allselected, Allexcept, and in this example I tried creating a variable with All / Inscope.  The results are all the same.

Original Attempt- Works w/out filter -

Rank by Alarm = RANKX(ALL(Table[Alarm_Issue]),CALCULATE(SUM(Table[MWhLosses_Technical])))

Rank w/ Variable - Works w/out filter:
below

I would very much appreciate some help!

Rank by Alarm w Variable =
var Issue Rank = RANKX( ALLSELECTED (TABLE [alarm_issue]), CALCULATE(SUM(TABLE[MWhLosses_Technical])))
var Result =
if(isinscope(Table [Alarm_Issue]),IssueRank)
Return
Result


问:
Issues with using H5py dataset in PyTorch
I'm trying to use a h5py dataset in PyTorch with this model this model, but I'm running into issues.
I've used a function like this to create datasets for Tensorflow before without issue.
I'd normally load the dataset using the following functions:

```<code>def create_hdf5_generator(db_path, batch_size):
    db = h5py.File(db_path)
    db_size = db['data'].shape[0]

    while True:  # loop through the dataset indefinitely
        for i in np.arange(0, db_size, batch_size):
            images = db['data'][i:i+batch_size]
            labels = db['labels'][i:i+batch_size]
            yield images, labels
training_data = create_hdf5_generator(training_path, batch_size=batch_size)
training_samples, training_labels = next(training_data)
</code>```

This, however, doesn't seem to work for the Pytorch DataLoader.
I then tried to use the class shown here https://vict0rs.ch/2021/06/15/pytorch-h5/ but I kept getting a "KeyError: Unable to open object (object 'trajectory_0' doesn't exist)" error as I'm presuming my h5py file is organized differently than the author's.

```<code>import torch
from torch.utils.data import Dataset
import h5py

class H5Dataset(Dataset):
    def __init__(self, h5_paths, limit=-1):
        self.limit = limit
        self.h5_paths = h5_paths
        self._archives = [h5py.File(h5_path, "r") for h5_path in self.h5_paths]
        self.indices = {}
        idx = 0
        for a, archive in enumerate(self.archives):
            for i in range(len(archive)):
                self.indices[idx] = (a, i)
                idx += 1

        self._archives = None

    @property
    def archives(self):
        if self._archives is None: # lazy loading here!
            self._archives = [h5py.File(h5_path, "r") for h5_path in self.h5_paths]
        return self._archives

    def __getitem__(self, index):
        a, i = self.indices[index]
        archive = self.archives[a]
        dataset = archive[f"trajectory_{i}"]
        data = torch.from_numpy(dataset[:])
        labels = dict(dataset.attrs)

        return {"data": data, "labels": labels}

    def __len__(self):
        if self.limit > 0:
            return min([len(self.indices), self.limit])
        return len(self.indices)

dataloader = DataLoader(H5Dataset(['E:/.../_training.h5py']), num_workers=0) # example loading of dataset
</code>```

I then tried to re-write the function to work with how my h5py is organized - replacing the __getitem__ definition with the following (the commented-out is part of the original function):

```<code>        def __getitem__(self, index):

            # a, i = self.indices[index]
            # archive = self.archives[a]
            # dataset = archive[f"trajectory_{i}"]
            # data = torch.from_numpy(dataset[:])
            # labels = dict(dataset.attrs)

            db = h5py.File(self.h5_paths[0])
            db_size = db['data'].shape[0]
            while True:  # loop through the dataset indefinitely
                for i in np.arange(0, db_size, batch_size):
                    data = db['data'][i:i + batch_size]
                    labels = db['labels'][i:i + batch_size]

dataloader = DataLoader(H5Dataset(['E:/.../_training.h5py']), num_workers=0) # example loading of dataset
</code>```

This seems to load the data, but training becomes stuck at 0/2 batches in the first epoch - which is interesting as there should be more than 2 batches.

 0%|          | 0/2 [00:00<?, ?it/s]epoch 0

What is going wrong? I'd be appreciative of any guidance or solutions.

Body:
I'm trying to use a h5py dataset in PyTorch with this model this model, but I'm running into issues.
I've used a function like this to create datasets for Tensorflow before without issue.
I'd normally load the dataset using the following functions:

def create_hdf5_generator(db_path, batch_size):
    db = h5py.File(db_path)
    db_size = db['data'].shape[0]

    while True:  # loop through the dataset indefinitely
        for i in np.arange(0, db_size, batch_size):
            images = db['data'][i:i+batch_size]
            labels = db['labels'][i:i+batch_size]
            yield images, labels
training_data = create_hdf5_generator(training_path, batch_size=batch_size)
training_samples, training_labels = next(training_data)

This, however, doesn't seem to work for the Pytorch DataLoader.
I then tried to use the class shown here https://vict0rs.ch/2021/06/15/pytorch-h5/ but I kept getting a "KeyError: Unable to open object (object 'trajectory_0' doesn't exist)" error as I'm presuming my h5py file is organized differently than the author's.

import torch
from torch.utils.data import Dataset
import h5py

class H5Dataset(Dataset):
    def __init__(self, h5_paths, limit=-1):
        self.limit = limit
        self.h5_paths = h5_paths
        self._archives = [h5py.File(h5_path, "r") for h5_path in self.h5_paths]
        self.indices = {}
        idx = 0
        for a, archive in enumerate(self.archives):
            for i in range(len(archive)):
                self.indices[idx] = (a, i)
                idx += 1

        self._archives = None

    @property
    def archives(self):
        if self._archives is None: # lazy loading here!
            self._archives = [h5py.File(h5_path, "r") for h5_path in self.h5_paths]
        return self._archives

    def __getitem__(self, index):
        a, i = self.indices[index]
        archive = self.archives[a]
        dataset = archive[f"trajectory_{i}"]
        data = torch.from_numpy(dataset[:])
        labels = dict(dataset.attrs)

        return {"data": data, "labels": labels}

    def __len__(self):
        if self.limit > 0:
            return min([len(self.indices), self.limit])
        return len(self.indices)

dataloader = DataLoader(H5Dataset(['E:/.../_training.h5py']), num_workers=0) # example loading of dataset

I then tried to re-write the function to work with how my h5py is organized - replacing the __getitem__ definition with the following (the commented-out is part of the original function):

        def __getitem__(self, index):

            # a, i = self.indices[index]
            # archive = self.archives[a]
            # dataset = archive[f"trajectory_{i}"]
            # data = torch.from_numpy(dataset[:])
            # labels = dict(dataset.attrs)

            db = h5py.File(self.h5_paths[0])
            db_size = db['data'].shape[0]
            while True:  # loop through the dataset indefinitely
                for i in np.arange(0, db_size, batch_size):
                    data = db['data'][i:i + batch_size]
                    labels = db['labels'][i:i + batch_size]

dataloader = DataLoader(H5Dataset(['E:/.../_training.h5py']), num_workers=0) # example loading of dataset

This seems to load the data, but training becomes stuck at 0/2 batches in the first epoch - which is interesting as there should be more than 2 batches.

 0%|          | 0/2 [00:00<?, ?it/s]epoch 0

What is going wrong? I'd be appreciative of any guidance or solutions.


问:
Mocha.js: how could I separate test and application files in different folders?
Here is my folder structure:

```<code>|-src
 |- mySrc.ts
|-tests
 |- testFolder1
  |- test1.test.ts
</code>```

I tried to run the command mocha -n loader=ts-node/esm 'tests/**/*.ts', but I get the following error SyntaxError: Cannot use import statement outside a module. How could I separate my test and application source folders?

Body:
Here is my folder structure:

|-src
 |- mySrc.ts
|-tests
 |- testFolder1
  |- test1.test.ts

I tried to run the command mocha -n loader=ts-node/esm 'tests/**/*.ts', but I get the following error SyntaxError: Cannot use import statement outside a module. How could I separate my test and application source folders?


问:
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
I sporadically get this error using Python 3.10 in Windows. I've tried installing 3.7.8 to get around the error (based on prior posts) but it persists.

It can happen with any module, including os. For example, I can perform the command os.chdir() successfully but then when I try os.listdir() I get the error message.

This works:

file_loc = r"C:\Temp1\Registry\R2_XML_Files"  # source directory for Registry
os.chdir(file_loc)
```
<p>But then when I run</p>
<pre class="lang-py prettyprint-override"><code>os.listdir(file_loc)
</code>```

The error is

>>> os.listdir(file_loc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
```
<p>I've also tried using the pathlib module to troubleshoot Windows path issues with</p>
<pre class="lang-py prettyprint-override"><code>file_loc = pathlib.PureWindowsPath ("C:/Temp1/Registry/R2_XML_Files")
</code>```

but I still get the error

I've also tried not changing the directory but this code also fails:

file_loc = r"C:\Temp1\Registry\R2_XML_Files"  # source directory for Registry

os.listdir(file_loc)
```
<pre class="lang-py prettyprint-override"><code>>>> os.listdir(file_loc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
>>>
</code>```

On a related note, I've also noticed when using the following code, I get a similar error, but only every 4 days. It runs for 3 days, then throws the same OSError. I can prevent the error by preemptively re-creating (in Windows) the folder "c:/Temp1/Covid"

dir_name = r"c:/Temp1/Covid"
extension = ".zip"

os.chdir(dir_name)
for item in os.listdir(dir_name): # loop through items in dir
    if item.endswith(extension): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        zip_ref = zipfile.ZipFile(file_name) # create zipfile object
        zip_ref.extractall(dir_name) # extract file to dir
        zip_ref.close() # close file
        os.remove(file_name)
```

Is there some Windows metadata that allows Windows to see and rename folders but does not allow Python to do so?

Have also run into the problem trying to pip install some modules.

I work for a hospital and have escalated to IT Security and no one seems to be able to figure out why this is occurring. The error also occurs for my colleagues and it is a huge hassle trying to keep Python stable. Starting over with a new install and new virtual environments sometimes works but sometimes doesn't.

Thanks very much.

Body:
I sporadically get this error using Python 3.10 in Windows. I've tried installing 3.7.8 to get around the error (based on prior posts) but it persists.

It can happen with any module, including os. For example, I can perform the command os.chdir() successfully but then when I try os.listdir() I get the error message.

This works:

file_loc = r"C:\Temp1\Registry\R2_XML_Files"  # source directory for Registry
os.chdir(file_loc)

But then when I run

os.listdir(file_loc)

The error is

>>> os.listdir(file_loc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'

I've also tried using the pathlib module to troubleshoot Windows path issues with

file_loc = pathlib.PureWindowsPath ("C:/Temp1/Registry/R2_XML_Files")

but I still get the error

I've also tried not changing the directory but this code also fails:

file_loc = r"C:\Temp1\Registry\R2_XML_Files"  # source directory for Registry

os.listdir(file_loc)

>>> os.listdir(file_loc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [WinError 87] The parameter is incorrect: 'C:\\Temp1\\Registry\\R2_XML_Files'
>>>

On a related note, I've also noticed when using the following code, I get a similar error, but only every 4 days. It runs for 3 days, then throws the same OSError. I can prevent the error by preemptively re-creating (in Windows) the folder "c:/Temp1/Covid"

dir_name = r"c:/Temp1/Covid"
extension = ".zip"

os.chdir(dir_name)
for item in os.listdir(dir_name): # loop through items in dir
    if item.endswith(extension): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        zip_ref = zipfile.ZipFile(file_name) # create zipfile object
        zip_ref.extractall(dir_name) # extract file to dir
        zip_ref.close() # close file
        os.remove(file_name)

Is there some Windows metadata that allows Windows to see and rename folders but does not allow Python to do so?

Have also run into the problem trying to pip install some modules.

I work for a hospital and have escalated to IT Security and no one seems to be able to figure out why this is occurring. The error also occurs for my colleagues and it is a huge hassle trying to keep Python stable. Starting over with a new install and new virtual environments sometimes works but sometimes doesn't.

Thanks very much.


问:
state after useEffect has the same reference for multiple components
I'm currently trying to parse an init state to multiple components. but parsing the state equals to the same state for all components even thou the logging in the useEffect logs out correctly .
There are some array and or object references that JS holds even though I create new copies of objects.

export default function App() {
  return (

My component

      <MyComponent id={"component-1"} initContent={"component-1-content"} />
      <MyComponent id={"component-2"} initContent={"component-2-content"} />

  );
}

```
<p>The components them self takes in the init content but since the render function is dependent on an array of object I need to parse the content before displaying the value</p>
<pre class="lang-js prettyprint-override"><code>
import { useEffect, useState } from "react";

type OBJECT_TYPE = {
  text: string;
  children: {
    text: string;
  }[];
};
const EMPTY_OBJECT: OBJECT_TYPE = {
  text: "",
  children: [
    {
      text: ""
    }
  ]
};
export const MyComponent = ({
  id,
  initContent
}: {
  id: string;
  initContent: string;
}) => {
  const [contentObject, setContent] = useState<[OBJECT_TYPE] | undefined>();
  useEffect(() => {
    const newContent = { ...EMPTY_OBJECT }; // copy the object
    newContent.children[0].text = initContent;
    console.log(newContent.children[0].text); // logs out correctly

    setContent([newContent]);
  }, [initContent]);
  if (!contentObject) return null;
  return <div>{contentObject[0].children[0].text}</div>; // Wrong render
};

</code>```

As you can see here, the renders does not output the correct state

I know there is something about JS array reference or something, but given the state in the useEffects logs out the correct content I'm not sure what is happening. I know I can use JSON.parse(json.stringify(newContent)) to make sure there is no lagging reference, but I want to know whats it happening, and how this could be solved more cleanly.

link to sandbox

Body:
I'm currently trying to parse an init state to multiple components. but parsing the state equals to the same state for all components even thou the logging in the useEffect logs out correctly .
There are some array and or object references that JS holds even though I create new copies of objects.

export default function App() {
  return (

My component

      <MyComponent id={"component-1"} initContent={"component-1-content"} />
      <MyComponent id={"component-2"} initContent={"component-2-content"} />

  );
}

The components them self takes in the init content but since the render function is dependent on an array of object I need to parse the content before displaying the value

import { useEffect, useState } from "react";

type OBJECT_TYPE = {
  text: string;
  children: {
    text: string;
  }[];
};
const EMPTY_OBJECT: OBJECT_TYPE = {
  text: "",
  children: [
    {
      text: ""
    }
  ]
};
export const MyComponent = ({
  id,
  initContent
}: {
  id: string;
  initContent: string;
}) => {
  const [contentObject, setContent] = useState<[OBJECT_TYPE] | undefined>();
  useEffect(() => {
    const newContent = { ...EMPTY_OBJECT }; // copy the object
    newContent.children[0].text = initContent;
    console.log(newContent.children[0].text); // logs out correctly

    setContent([newContent]);
  }, [initContent]);
  if (!contentObject) return null;
  return
{contentObject[0].children[0].text}
; // Wrong render
};

As you can see here, the renders does not output the correct state

I know there is something about JS array reference or something, but given the state in the useEffects logs out the correct content I'm not sure what is happening. I know I can use JSON.parse(json.stringify(newContent)) to make sure there is no lagging reference, but I want to know whats it happening, and how this could be solved more cleanly.

link to sandbox


问:
pyLDAvis tsne multidimensional scaling error
I've implemented a scikit learn LDA model and then rendered it using PyLDAvis which works good with other multidimensional scaling methods but when using tsne it gives me Value Error as follows:

scikit learn model:

```<code>#Create document word matrix (previously lemmatized and stemmatized)
vectorizer = CountVectorizer(analyzer='word',
                             min_df=10,                        # minimum reqd occurences of a word
                             stop_words=stopwords,             # remove stop words
                             lowercase=True,                   # convert all words to lowercase
                             token_pattern='[a-zA-Z0-9]{3,}',  # num chars > 3
                             # max_features=50000,             # max number of uniq words
                            )

data_vectorized = vectorizer.fit_transform(data_lemmatized)
# Build LDA Model
lda_model = LatentDirichletAllocation(n_components=3,
                                      max_iter=10,
                                      learning_method='online',
                                      random_state=100,
                                      batch_size=128,
                                      evaluate_every = -1,
                                      n_jobs = -1
                                     )
lda_output = lda_model.fit_transform(data_vectorized)
</code>```

pyLDAvis:

pyLDAvis.enable_notebook()
panel = pyLDAvis.sklearn.prepare(lda_model, data_vectorized, vectorizer, mds="tsne")
panel
```
```ValueError: perplexity must be less than n_samples
```

Body:
I've implemented a scikit learn LDA model and then rendered it using PyLDAvis which works good with other multidimensional scaling methods but when using tsne it gives me Value Error as follows:

scikit learn model:

#Create document word matrix (previously lemmatized and stemmatized)
vectorizer = CountVectorizer(analyzer='word',
                             min_df=10,                        # minimum reqd occurences of a word
                             stop_words=stopwords,             # remove stop words
                             lowercase=True,                   # convert all words to lowercase
                             token_pattern='[a-zA-Z0-9]{3,}',  # num chars > 3
                             # max_features=50000,             # max number of uniq words
                            )

data_vectorized = vectorizer.fit_transform(data_lemmatized)
# Build LDA Model
lda_model = LatentDirichletAllocation(n_components=3,
                                      max_iter=10,
                                      learning_method='online',
                                      random_state=100,
                                      batch_size=128,
                                      evaluate_every = -1,
                                      n_jobs = -1
                                     )
lda_output = lda_model.fit_transform(data_vectorized)

pyLDAvis:

pyLDAvis.enable_notebook()
panel = pyLDAvis.sklearn.prepare(lda_model, data_vectorized, vectorizer, mds="tsne")
panel

ValueError: perplexity must be less than n_samples


问:
How to handle error in Program.cs in asp.net core web app
I have a multitenant application that I'm restricting access to specific tenants. The code to authorize a user from specific tenants works fine and for those without access I'm throwing a SecurityTokenInvalidIssuerException. The problem is I don't know how to capture this error because the code is executed at the start of Program.cs and prior to the app.build. How do I gracefully handle this error? ...right now it's just crashing the app.

Program.cs

```<code>var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
//builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
//    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration);

// Restrict users to specific belonging to specific tenants
UserValidator user = new UserValidator();
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters.IssuerValidator = user.ValidateSpecificIssuers;
});
</code>```

UserValidator.cs

```<code>public class UserValidator
{
    public string ValidateSpecificIssuers(string issuer, SecurityToken securityToken,
                                          TokenValidationParameters validationParameters)
    {
        var validIssuers = GetAcceptedTenantIds()
                             .Select(tid => $"https://login.microsoftonline.com/{tid}/v2.0");
        if (validIssuers.Contains(issuer))
        {
            return issuer;
        }
        else
        {
            throw new SecurityTokenInvalidIssuerException("The sign-in user's account does not belong to one of the tenants that this Web App accepts users from.");
        }
    }
    private string[] GetAcceptedTenantIds()
    {
        // If you are an ISV who wants to make the Web app available only to certain customers who
        // are paying for the service, you might want to fetch this list of accepted tenant ids from
        // a database.
        // Here for simplicity we just return a hard-coded list of TenantIds.
        var config = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json").Build();

        var acceptedTenants = config.GetSection("Tenants").GetChildren();
        string[] tenants = new string[acceptedTenants.Count()];
        int i = 0;
        foreach (var acceptedTenant in acceptedTenants)
        {
            tenants[i] = acceptedTenant.GetValue<string>("TenantId");
        i++;
        }

        return tenants;
    }
}
</code>```

Body:
I have a multitenant application that I'm restricting access to specific tenants. The code to authorize a user from specific tenants works fine and for those without access I'm throwing a SecurityTokenInvalidIssuerException. The problem is I don't know how to capture this error because the code is executed at the start of Program.cs and prior to the app.build. How do I gracefully handle this error? ...right now it's just crashing the app.

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
//builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
//    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration);

// Restrict users to specific belonging to specific tenants
UserValidator user = new UserValidator();
builder.Services.Configure<OpenIdConnectOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
    options.TokenValidationParameters.IssuerValidator = user.ValidateSpecificIssuers;
});

UserValidator.cs

public class UserValidator
{
    public string ValidateSpecificIssuers(string issuer, SecurityToken securityToken,
                                          TokenValidationParameters validationParameters)
    {
        var validIssuers = GetAcceptedTenantIds()
                             .Select(tid => $"https://login.microsoftonline.com/{tid}/v2.0");
        if (validIssuers.Contains(issuer))
        {
            return issuer;
        }
        else
        {
            throw new SecurityTokenInvalidIssuerException("The sign-in user's account does not belong to one of the tenants that this Web App accepts users from.");
        }
    }
    private string[] GetAcceptedTenantIds()
    {
        // If you are an ISV who wants to make the Web app available only to certain customers who
        // are paying for the service, you might want to fetch this list of accepted tenant ids from
        // a database.
        // Here for simplicity we just return a hard-coded list of TenantIds.
        var config = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json").Build();

        var acceptedTenants = config.GetSection("Tenants").GetChildren();
        string[] tenants = new string[acceptedTenants.Count()];
        int i = 0;
        foreach (var acceptedTenant in acceptedTenants)
        {
            tenants[i] = acceptedTenant.GetValue<string>("TenantId");
        i++;
        }

        return tenants;
    }
}