问:
How to extract common function
I have some function that occurs in 4 places (custom hooks) so I want to extract it and save in some /common directory in some file to reuse it in these 4 places. Here is one of my 4 custom hooks with this repeated function:

```<code>export function useMyHook({changeColumnSorting}) {

const [filters, setFilters] = useState();

function handleOnColumnSortChange(columnName, order) {
        changeColumnSorting?.(columnName, order);
        const newFilters = {
            ...filters,
            sorting: { [columnName]: order },
        };
        setFilters(newFilters);
    }

return {
        sorting: filters.sorting,
        filters,
        handleOnColumnSortChange
}
</code>```

columnName and order are unknown, passed from some third party table where handleOnColumnSortChange is one of parameters (here in some other component useMyHook is used):

```<code>
const { handleOnColumnSortChange} =
        useMyHook({
            changeColumnSorting
        });

<Table
 handleOnColumnSortChange={handleOnColumnSortChange}
/>
</code>```

How to extract this function in some file and return this function in all my 4 hooks?

Params are mixed, some params are given from external Table and some variables used in this function are declared in this particular hook... That's the problem

My attempt:

extracted function:

```<code>export function handleOnColumnSortChange(
    columnName: string,
    order: any,
    changeColumnSorting: any,
    filters: any,
    setFilters: (data: any) => void
) {
    changeColumnSorting?.(columnName, order);
    const newFilters = {
        ...filters,
        sorting: { [columnName]: order },
    };
    setFilters(newFilters);
}
</code>```

but what next?
the first 2 params are undefined, I tried to create some const with similar name like my common function and return it in my hook:

Title: How to extract common function

Body:
I have some function that occurs in 4 places (custom hooks) so I want to extract it and save in some /common directory in some file to reuse it in these 4 places. Here is one of my 4 custom hooks with this repeated function:

export function useMyHook({changeColumnSorting}) {

const [filters, setFilters] = useState();

function handleOnColumnSortChange(columnName, order) {
        changeColumnSorting?.(columnName, order);
        const newFilters = {
            ...filters,
            sorting: { [columnName]: order },
        };
        setFilters(newFilters);
    }

return {
        sorting: filters.sorting,
        filters,
        handleOnColumnSortChange
}

columnName and order are unknown, passed from some third party table where handleOnColumnSortChange is one of parameters (here in some other component useMyHook is used):

const { handleOnColumnSortChange} =
        useMyHook({
            changeColumnSorting
        });

How to extract this function in some file and return this function in all my 4 hooks?

Params are mixed, some params are given from external Table and some variables used in this function are declared in this particular hook... That's the problem

My attempt:

extracted function:

export function handleOnColumnSortChange(
    columnName: string,
    order: any,
    changeColumnSorting: any,
    filters: any,
    setFilters: (data: any) => void
) {
    changeColumnSorting?.(columnName, order);
    const newFilters = {
        ...filters,
        sorting: { [columnName]: order },
    };
    setFilters(newFilters);
}

but what next?
the first 2 params are undefined, I tried to create some const with similar name like my common function and return it in my hook:


来源: stackexchange

问:
How in Calendar to display current data according to day instead of displaying the current date
please I greatly need your help on how can I, in "CALENDAR", set different datas for each day and display it when the day is clicked. I have checked everywhere and you guys are my last resource. All documentation & example I got are related to "How to get the date selected from the datepicker ". And almost all of them sets the current date as default date in the datepicker.

How can I display current data instead of displaying the current date.

For example,

when one click on:

▪28 Dec (it should display) -> "coding is great"

▪29 Dec-> "reading is good"

▪30 Dec-> "stackoverflow comunity is the best"

Etc...

Pls, help!

Thanks in advance.

I tried to store in onDateSet a data for a particular day, but it is not working. I am New to coding

ContentLicense: CC BY-SA 4.0


问:
How to draw on an JLabel and Save / Edit the Drawing
can anyone give me a Hint how to draw on a JLabel and Save this Drawing. I Want to Load and Edit the Drawing later.

Here is my GUI:

MY GUI

The Picture has German Subtitles,
Its an JLabel in a JScrollPane

Thank you

Justin

I Hope that u can give me an Programm Code Example.

Thanks,


问:
Granting AWS Config cross-account S3 access
I would like to centralize the AWS Config logs from the different AWS Accounts in a single S3 Bucket in one AWS Account.

I've configured the S3 Bucket exactly with the policy indicated at this link: https://docs.aws.amazon.com/config/latest/developerguide/s3-bucket-policy.html and I've assigned to AWS Config an IAM Role with exactly the policy indicated at the link: https://docs.aws.amazon.com/config/latest/developerguide/iamrole-permissions.html

Nevertheless, I'm still not able to make it working; The error I get is:
AWS Config cannot save your settings because of one of the following: The IAM role is updating in the system. Wait a moment and try again. AWS Config doesn't have sufficient permissions to send configuration information to the specified S3 bucket. Update the role or bucket permissions and try again.

And, from the Cloudtrail logs, I get:
Insufficient delivery policy to s3 bucket: clim8-logs-aws-config, unable to write to bucket, provided s3 key prefix is 'null', provided kms key is 'null'.

The even weird thing is that from the AWS Config present in the AWS Account where the S3 Bucket is located, everything works perfectly, so I guess that's just something due to the cross-account.

I've tried to find out some more indications in the AWS Docs, but I couldn't find anything.

Any hint on what I could have missed?

Thanks!


问:
Anytime I deploy a gltf or hdr for threejd file on GitHub it get deleted and considered as junk when vercel start deploying the site
Anytime I deploy a gltf or hdr for threejd file on GitHub it get deleted and considered as junk when vercel start deploying the site

I tried creating a new folder for the files but still the same


问:
NASM - Selecting multiple values to output different string lengths
I'm trying to use run length encoding to output multiple, different length, strings.  I can output one string, but as soon as I try to modify the code so that multiple strings are output I only get errors.   This code below works as expected and allows me to change the values in rle or movement successfully to control the start point and lenght of the string.   What I want to do is to be able to read multiple values from rle and then use these to output strings of different lengths.  However if I add more than one value to rle (such as rle, dw 2,7,0) I get no output.  Likewise if I dont have the zero (such as rle dw 2) I get no output.  This code is part of a larger bit of code, all of which works, and this is just the essential part where my issue exists.

```<code>section .text

global _start

_start:

    mov     ecx, stars          ; load the output data string into ecx
    mov     edx, dword[rle]     ; define string output length (initially 2)
    mov     eax, 0x4            ; set output type as sys_write
    inc     ecx                 ; move along one position (so go from B not A)
    inc     ecx                 ; move along one position (so go from C not B)
    mov     ebx, dword[movement] ; get the value from movement (1 the first time)
    add     edx, ebx            ; add 1 (ebx via movement) to 2 (edx from rle) >> 3
    mov     ebx, 1               ; now set ebx for printing
    int     80h

section .data

    stars db "ABCDE",0
    rle dw 2,0;
    movement dw 1,0,-1,0;

segment .bss
</code>```

I've tried all types of different rle data.  Only where I have the initial length (2) followed by a zero terminator does it work successfully (outputs CDE in this example).

What I was expecting was that if I added more comma seperated values into rle, I would be able to point at them and then use those values to control my output length.

Body:
I'm trying to use run length encoding to output multiple, different length, strings.  I can output one string, but as soon as I try to modify the code so that multiple strings are output I only get errors.   This code below works as expected and allows me to change the values in rle or movement successfully to control the start point and lenght of the string.   What I want to do is to be able to read multiple values from rle and then use these to output strings of different lengths.  However if I add more than one value to rle (such as rle, dw 2,7,0) I get no output.  Likewise if I dont have the zero (such as rle dw 2) I get no output.  This code is part of a larger bit of code, all of which works, and this is just the essential part where my issue exists.

section .text

global _start

_start:

    mov     ecx, stars          ; load the output data string into ecx
    mov     edx, dword[rle]     ; define string output length (initially 2)
    mov     eax, 0x4            ; set output type as sys_write
    inc     ecx                 ; move along one position (so go from B not A)
    inc     ecx                 ; move along one position (so go from C not B)
    mov     ebx, dword[movement] ; get the value from movement (1 the first time)
    add     edx, ebx            ; add 1 (ebx via movement) to 2 (edx from rle) >> 3
    mov     ebx, 1               ; now set ebx for printing
    int     80h

section .data

    stars db "ABCDE",0
    rle dw 2,0;
    movement dw 1,0,-1,0;

segment .bss

I've tried all types of different rle data.  Only where I have the initial length (2) followed by a zero terminator does it work successfully (outputs CDE in this example).

What I was expecting was that if I added more comma seperated values into rle, I would be able to point at them and then use those values to control my output length.


问:
Redirect a webhooks to another domain name
My payment provider is accepting only one domain which we'll call domainaccepted.com.

I need to redirect payments provider webhooks answers and its data from:

https://www.domainaccepted.com/index.php?option=com_virtuemart&view=vmplg&task=pluginNotification&pm=26 - KNOWING THAT "DOMAINACCEPTED.COM" Does not USE VIRTUEMART OR HAVE IT ON THE SERVER.

TO NEW DOMAIN NAME

https://www.newdomain.com/index.php?option=com_virtuemart&view=vmplg&task=pluginNotification&pm=26 - THAT CONTAINS VIRTUEMART TO TREAT ORDERS.

How doing that simply if possible using .htaccess.

I precise the redirection need to contain data sent from first URL to the NEW URL (such as a post value) to change orders as "accepted", "refunded" -etc.. status.

How can I do that?


问:
Throws an error while closing drawer while keyboard is open
Whenever my keyboard is open and I try to close the Drawer - EndDrawer it throws this error. The error doesn't occur if the keyboard is not focused.

```<code>======== Exception caught by widgets library =======================================================
The following assertion was thrown building StreamBuilder<List<SearchFieldListItem<dynamic>?>?>(dirty, state: _StreamBuilderBaseState<List<SearchFieldListItem<dynamic>?>?, AsyncSnapshot<List<SearchFieldListItem<dynamic>?>?>>#75ea8):
This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
</code>```

Note: There is SearchField inside the drawer.

It shouldn't throw an error.

This is the code

```<code>    appBar:AppBar(title:Text('XYZ')),
    endDrawer: Drawer(
      child: ListView(

        children: [
          Padding(
            padding:EdgeInsets.all(10),
            child: SizedBox(
              child: const DrawerHeader(
                child: Text('Filter'),
              ),
            ),
          ),
            Padding(
              padding: EdgeInsets.all(10),
              child: Container(

                child: SearchField<Model>(
                  onSuggestionTap: (buyerValue) {},
                  ,
                ),
              ),
            ),
        ],
      ),
    ),
    body: Container(
        )
    ),
</code>```

Body:
Whenever my keyboard is open and I try to close the Drawer - EndDrawer it throws this error. The error doesn't occur if the keyboard is not focused.

======== Exception caught by widgets library =======================================================
The following assertion was thrown building StreamBuilder<List<SearchFieldListItem<dynamic>?>?>(dirty, state: _StreamBuilderBaseState<List<SearchFieldListItem<dynamic>?>?, AsyncSnapshot<List<SearchFieldListItem<dynamic>?>?>>#75ea8):
This widget has been unmounted, so the State no longer has a context (and should be considered defunct).

Note: There is SearchField inside the drawer.

It shouldn't throw an error.

This is the code

    appBar:AppBar(title:Text('XYZ')),
    endDrawer: Drawer(
      child: ListView(

        children: [
          Padding(
            padding:EdgeInsets.all(10),
            child: SizedBox(
              child: const DrawerHeader(
                child: Text('Filter'),
              ),
            ),
          ),
            Padding(
              padding: EdgeInsets.all(10),
              child: Container(

                child: SearchField<Model>(
                  onSuggestionTap: (buyerValue) {},
                  ,
                ),
              ),
            ),
        ],
      ),
    ),
    body: Container(
        )
    ),


问:
how to add 24 hour to a specific date-time in bash
I am trying to add 24 hours to a date-time string using bash, but the result is weird.

That is okay:

```<code>$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00"
2016-01-01 21:00:00
</code>```

Then trying to increase the date a little bit, but the result is completely wrong:

```<code>$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00 + 1 day"
2016-01-02 20:00:00  <- expected: 2016-01-02 21:00:00

$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00 + 24 hours"
2015-12-31 22:00:00  <- expected: 2016-01-02 21:00:00

$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00 + 5 mins"
2016-01-01 16:01:00  <- expected: 2016-01-01 21:05:00
</code>```

What is wrong with my command?

--- UPDATE ---

This is my current timezone settings:

```<code>$ timedatectl
               Local time: Mon 2022-12-26 23:58:14 WET
           Universal time: Mon 2022-12-26 23:58:14 UTC
                 RTC time: Mon 2022-12-26 23:58:14
                Time zone: Atlantic/Canary (WET, +0000)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no

$ cat /etc/timezone
Atlantic/Canary
</code>```

--- SOLUTION ---

Thanks for your help I was able to figure out the correct command.

Solution 1:
adding time zone info "Z" to the end of my date-time string solved the problem

```<code>date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00Z + 24 hours"
</code>```

Solution 2:
Convert the date-time string to epoch, then add 24 hours to the value. Finally convert the new epoch back to string

```<code>date -d "@$(($(date "+%s") + 60 * 60 * 24))" +"%Y-%m-%d %H:%M:%S"
</code>```

Body:
I am trying to add 24 hours to a date-time string using bash, but the result is weird.

That is okay:

$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00"
2016-01-01 21:00:00

Then trying to increase the date a little bit, but the result is completely wrong:

$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00 + 1 day"
2016-01-02 20:00:00  <- expected: 2016-01-02 21:00:00

$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00 + 24 hours"
2015-12-31 22:00:00  <- expected: 2016-01-02 21:00:00

$ date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00 + 5 mins"
2016-01-01 16:01:00  <- expected: 2016-01-01 21:05:00

What is wrong with my command?

--- UPDATE ---

This is my current timezone settings:

$ timedatectl
               Local time: Mon 2022-12-26 23:58:14 WET
           Universal time: Mon 2022-12-26 23:58:14 UTC
                 RTC time: Mon 2022-12-26 23:58:14
                Time zone: Atlantic/Canary (WET, +0000)
System clock synchronized: yes
              NTP service: active
          RTC in local TZ: no

$ cat /etc/timezone
Atlantic/Canary

--- SOLUTION ---

Thanks for your help I was able to figure out the correct command.

Solution 1:
adding time zone info "Z" to the end of my date-time string solved the problem

date +"%Y-%m-%d %H:%M:%S" -d "2016-01-01 21:00:00Z + 24 hours"

Solution 2:
Convert the date-time string to epoch, then add 24 hours to the value. Finally convert the new epoch back to string

date -d "@$(($(date "+%s") + 60 * 60 * 24))" +"%Y-%m-%d %H:%M:%S"


问:
Tensorflow misclassification problem. All cases are assigned to one class
I would like to build a tensorflow model to categorize loans for credit risk.
Unfortunately, I have a problem cause my model puts all cases into one class.
I don't know if it comes from the definition of metadata in specify_feature_usages function.
Maybe this part should be done in another way? But how to do that?
Does this come from imbalanced training data? 1.113 for risk cases and 2.220 cases for others.
Data source used in the project credit_data.h5.

confusion matrix

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import pprint as pp
import math
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, f1_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras import Sequential
from tensorflow.keras.layers import DenseFeatures, Dense, Activation
import tensorflow as tf
from tensorflow import keras
from IPython.display import display
import matplotlib.pyplot as plt
sns.set(style='darkgrid')
print('TensorFlow version: ' + tf.__version__)

# credit_data = pd.read_csv('german_credit_data.csv')
# credit_data.to_hdf('credit_data.h5', key='df', mode='w')
credit_data = pd.read_hdf('credit_data.h5', 'df')
display(credit_data)

data = credit_data.copy()
# Name of the label column.
label = 'Risk'
id_column = 'CustomerID'
data[label].value_counts().to_frame().T

data.info()

train = 2/3
test = 1 - train
label_lst = [label]
train_data, test_data = train_test_split(data, test_size=test, random_state=0, stratify=data[label_lst])
print(f"Train data shape: {train_data.shape}")
print(f"Test data shape: {test_data.shape}")
train_data[label].value_counts().to_frame().T

label_new = label + '_target'
train_data[label_new] = train_data[label].apply(lambda x: 1 if x == 'Risk' else 0)
train_data.drop(label, axis=1, inplace=True)

test_data[label_new] = test_data[label].apply(lambda x: 1 if x == 'Risk' else 0)
test_data.drop(label, axis=1, inplace=True)

print("Training dataset")
display(train_data.agg({label_new : ['sum', 'count']}))
print("Test dataset")
display(test_data.agg({label_new : ['sum', 'count']}))

label = label_new
id_column = 'CustomerID'

### Define continuous list
numericFeatures  = ['LoanDuration','LoanAmount','InstallmentPercent','CurrentResidenceDuration','Age','ExistingCreditsCount','Dependents']
### Define the categorical list
objectFeatures = ['CheckingStatus','CreditHistory','LoanPurpose','ExistingSavings','EmploymentDuration','Sex',
'OthersOnLoan','OwnsProperty','InstallmentPlans','Housing','Job','Telephone','ForeignWorker']

# Target column name.
TARGET_COLUMN_NAME = label
# Numeric feature names.
NUMERIC_FEATURE_NAMES = numericFeatures
# Categorical features and their vocabulary lists.
CATEGORICAL_FEATURE_NAMES = objectFeatures

print(TARGET_COLUMN_NAME)
print(NUMERIC_FEATURE_NAMES)
print(CATEGORICAL_FEATURE_NAMES)

def specify_feature_usages(df, label):
    feature_usages = list()
    feature_names = list()

    for feature_name in NUMERIC_FEATURE_NAMES:

        mean = df[feature_name].mean()
        std = df[feature_name].std()

        def zscore(x):
            x = tf.dtypes.cast(x, tf.float32)
            return (x - mean)/std

        feature_usage = tf.feature_column.numeric_column(key=feature_name, normalizer_fn=zscore)
        feature_usages.append(feature_usage)
        feature_names.append(feature_name)

    for feature_name in CATEGORICAL_FEATURE_NAMES:

        aggregate = df.groupby(feature_name)[label].agg(['sum','count'])
        aggregate['share'] = aggregate['sum'] / aggregate['count']
        aggregate.sort_values('share', ascending=False, inplace=True)
        vocabulary = aggregate.index.values.tolist()

        feature_usage = tf.feature_column.indicator_column(
            tf.feature_column.categorical_column_with_vocabulary_list(
            key=feature_name, vocabulary_list=vocabulary, default_value=0
        ))
        feature_usages.append(feature_usage)
        feature_names.append(feature_name)

    return feature_usages, feature_names

feature_columns, feature_names = specify_feature_usages(train_data, label)
l_inputs = len(feature_names)
l_outputs = len([label])
print('inputs={inputs}, output={output}'.format(inputs=l_inputs,output=l_outputs))
pp.pprint(feature_columns)

# A utility method to create a tf.data dataset from a Pandas Dataframe
def df_to_dataset(dataframe, target_cols, shuffle=True):
    dataframe = dataframe.copy()
    total_rows = dataframe.shape[0]
    batch_size = int(total_rows/10)
    labels = dataframe[target_cols]
    features = dataframe.drop(target_cols, axis=1)
    ds = tf.data.Dataset.from_tensor_slices((dict(features), labels))
    if shuffle:
        ds = ds.shuffle(buffer_size=len(features))
        ds = ds.batch(batch_size)
    return ds

# Convert the dataset into a TensorFlow dataset.
train_dataset = df_to_dataset(train_data, label, True)
test_dataset = df_to_dataset(test_data, label, True)

model = Sequential()
model.add(DenseFeatures(feature_columns))
model.add(Dense(24, activation=tf.nn.sigmoid))
model.add(Dense(12, activation=tf.nn.sigmoid))
model.add(Dense(6, activation=tf.nn.sigmoid))
model.add(Dense(l_outputs, activation=tf.nn.softmax))

METRICS = [
      keras.metrics.BinaryAccuracy(name='accuracy'),
      keras.metrics.Precision(name='precision'),
      keras.metrics.Recall(name='recall'),
      keras.metrics.AUC(name='auc')
]

model.compile(optimizer=keras.optimizers.Adam(),
              loss=keras.losses.BinaryCrossentropy(),
              metrics=METRICS)

model.fit(train_dataset, verbose=0)

# evaluate the model
print("Training dataset")
scores = model.evaluate(train_dataset, verbose=0)
scores_metrics = zip(model.metrics_names, scores)
for m, s in list(scores_metrics):
    print(m, s)

print("Test dataset")
scores = model.evaluate(test_dataset, verbose=0)
scores_metrics = zip(model.metrics_names, scores)
for m, s in list(scores_metrics):
    print(m, s)

y_predicted = model.predict(test_dataset)

df_hist = pd.DataFrame(y_predicted)
df_hist.columns = ["Risk_prediction"]
sns.histplot(data=df_hist, x="Risk_prediction", bins=10)
plt.show()

y_predicted = np.where(y_predicted > 0.5, 1, 0)
y_actual = test_data[label]
matrix = confusion_matrix(y_actual, y_predicted, labels=[1,0])
report = classification_report(y_actual, y_predicted)
print(matrix)
print(report)
```

I would appreciate for all advices how to fix model classification.

Body:
I would like to build a tensorflow model to categorize loans for credit risk.
Unfortunately, I have a problem cause my model puts all cases into one class.
I don't know if it comes from the definition of metadata in specify_feature_usages function.
Maybe this part should be done in another way? But how to do that?
Does this come from imbalanced training data? 1.113 for risk cases and 2.220 cases for others.
Data source used in the project credit_data.h5.

confusion matrix

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import pprint as pp
import math
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, f1_score, confusion_matrix, classification_report
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras import Sequential
from tensorflow.keras.layers import DenseFeatures, Dense, Activation
import tensorflow as tf
from tensorflow import keras
from IPython.display import display
import matplotlib.pyplot as plt
sns.set(style='darkgrid')
print('TensorFlow version: ' + tf.__version__)

# credit_data = pd.read_csv('german_credit_data.csv')
# credit_data.to_hdf('credit_data.h5', key='df', mode='w')
credit_data = pd.read_hdf('credit_data.h5', 'df')
display(credit_data)

data = credit_data.copy()
# Name of the label column.
label = 'Risk'
id_column = 'CustomerID'
data[label].value_counts().to_frame().T

data.info()

train = 2/3
test = 1 - train
label_lst = [label]
train_data, test_data = train_test_split(data, test_size=test, random_state=0, stratify=data[label_lst])
print(f"Train data shape: {train_data.shape}")
print(f"Test data shape: {test_data.shape}")
train_data[label].value_counts().to_frame().T

label_new = label + '_target'
train_data[label_new] = train_data[label].apply(lambda x: 1 if x == 'Risk' else 0)
train_data.drop(label, axis=1, inplace=True)

test_data[label_new] = test_data[label].apply(lambda x: 1 if x == 'Risk' else 0)
test_data.drop(label, axis=1, inplace=True)

print("Training dataset")
display(train_data.agg({label_new : ['sum', 'count']}))
print("Test dataset")
display(test_data.agg({label_new : ['sum', 'count']}))

label = label_new
id_column = 'CustomerID'

### Define continuous list
numericFeatures  = ['LoanDuration','LoanAmount','InstallmentPercent','CurrentResidenceDuration','Age','ExistingCreditsCount','Dependents']
### Define the categorical list
objectFeatures = ['CheckingStatus','CreditHistory','LoanPurpose','ExistingSavings','EmploymentDuration','Sex',
'OthersOnLoan','OwnsProperty','InstallmentPlans','Housing','Job','Telephone','ForeignWorker']

# Target column name.
TARGET_COLUMN_NAME = label
# Numeric feature names.
NUMERIC_FEATURE_NAMES = numericFeatures
# Categorical features and their vocabulary lists.
CATEGORICAL_FEATURE_NAMES = objectFeatures

print(TARGET_COLUMN_NAME)
print(NUMERIC_FEATURE_NAMES)
print(CATEGORICAL_FEATURE_NAMES)

def specify_feature_usages(df, label):
    feature_usages = list()
    feature_names = list()

    for feature_name in NUMERIC_FEATURE_NAMES:

        mean = df[feature_name].mean()
        std = df[feature_name].std()

        def zscore(x):
            x = tf.dtypes.cast(x, tf.float32)
            return (x - mean)/std

        feature_usage = tf.feature_column.numeric_column(key=feature_name, normalizer_fn=zscore)
        feature_usages.append(feature_usage)
        feature_names.append(feature_name)

    for feature_name in CATEGORICAL_FEATURE_NAMES:

        aggregate = df.groupby(feature_name)[label].agg(['sum','count'])
        aggregate['share'] = aggregate['sum'] / aggregate['count']
        aggregate.sort_values('share', ascending=False, inplace=True)
        vocabulary = aggregate.index.values.tolist()

        feature_usage = tf.feature_column.indicator_column(
            tf.feature_column.categorical_column_with_vocabulary_list(
            key=feature_name, vocabulary_list=vocabulary, default_value=0
        ))
        feature_usages.append(feature_usage)
        feature_names.append(feature_name)

    return feature_usages, feature_names

feature_columns, feature_names = specify_feature_usages(train_data, label)
l_inputs = len(feature_names)
l_outputs = len([label])
print('inputs={inputs}, output={output}'.format(inputs=l_inputs,output=l_outputs))
pp.pprint(feature_columns)

# A utility method to create a tf.data dataset from a Pandas Dataframe
def df_to_dataset(dataframe, target_cols, shuffle=True):
    dataframe = dataframe.copy()
    total_rows = dataframe.shape[0]
    batch_size = int(total_rows/10)
    labels = dataframe[target_cols]
    features = dataframe.drop(target_cols, axis=1)
    ds = tf.data.Dataset.from_tensor_slices((dict(features), labels))
    if shuffle:
        ds = ds.shuffle(buffer_size=len(features))
        ds = ds.batch(batch_size)
    return ds

# Convert the dataset into a TensorFlow dataset.
train_dataset = df_to_dataset(train_data, label, True)
test_dataset = df_to_dataset(test_data, label, True)

model = Sequential()
model.add(DenseFeatures(feature_columns))
model.add(Dense(24, activation=tf.nn.sigmoid))
model.add(Dense(12, activation=tf.nn.sigmoid))
model.add(Dense(6, activation=tf.nn.sigmoid))
model.add(Dense(l_outputs, activation=tf.nn.softmax))

METRICS = [
      keras.metrics.BinaryAccuracy(name='accuracy'),
      keras.metrics.Precision(name='precision'),
      keras.metrics.Recall(name='recall'),
      keras.metrics.AUC(name='auc')
]

model.compile(optimizer=keras.optimizers.Adam(),
              loss=keras.losses.BinaryCrossentropy(),
              metrics=METRICS)

model.fit(train_dataset, verbose=0)

# evaluate the model
print("Training dataset")
scores = model.evaluate(train_dataset, verbose=0)
scores_metrics = zip(model.metrics_names, scores)
for m, s in list(scores_metrics):
    print(m, s)

print("Test dataset")
scores = model.evaluate(test_dataset, verbose=0)
scores_metrics = zip(model.metrics_names, scores)
for m, s in list(scores_metrics):
    print(m, s)

y_predicted = model.predict(test_dataset)

df_hist = pd.DataFrame(y_predicted)
df_hist.columns = ["Risk_prediction"]
sns.histplot(data=df_hist, x="Risk_prediction", bins=10)
plt.show()

y_predicted = np.where(y_predicted > 0.5, 1, 0)
y_actual = test_data[label]
matrix = confusion_matrix(y_actual, y_predicted, labels=[1,0])
report = classification_report(y_actual, y_predicted)
print(matrix)
print(report)

I would appreciate for all advices how to fix model classification.


问:
How to use BinanceAPI candlesticks with MondoDB timeseries?
I'm trying to implement simple multi charts ui.

I watched MongoDB presentation for financial timeseries with candlesticks.
As I understand timeseries works as flat structure, and I should put there ticks.

timeseries: {
timeField: "time",
metaField: "symbol",
granularity: "seconds",
},

But BinanceAPI provides with candlesticks data, like open close hight low for different time periods 1H 4H 1D.
Or if I fetch ticks, I receive only the last ticks for multi pairs.

What kind of solutions could be there?

Should I fetch those candlesticks and convert it to ticks then put as timeseries.
Or is there any other solutions?


问:
Issues with minikube and building pods
I am trying to run a microservice spring boot application on Kubernetes(minikube). I create the Dockerfile and the images accordantly. I set the deployment.yml file and then I try to run the cluster with the kubectl command. But, I have always ImagePullBackOff on Status.

```<code>NAME                                           READY   STATUS             RESTARTS   AGE
pod/account-service-app-5c6f75d987-ml8j9       0/1     ImagePullBackOff   0          12m
pod/api-gateway-app-744477d8f8-47jg8           0/1     ImagePullBackOff   0          12m
pod/customer-service-app-677966df99-j8fsb      0/1     ImagePullBackOff   0          12m
pod/discovery-service-0                        0/1     ImagePullBackOff   0          29m
pod/notification-service-app-f6d9cf6d6-jlgsq   0/1     ImagePullBackOff   0          12m
pod/transaction-service-app-5b9c6b54cd-6f2cg   0/1     ImagePullBackOff   0          12m

</code>```

If there is any explanation regarding this issue. When I type describe of a pod. Then I see this:

```<code>Controlled By:  ReplicaSet/account-service-app-5c6f75d987
Containers:
  account-service-app:
    Container ID:
    Image:          renosbardis/accounts-service:0.0.1
    Image ID:
    Port:           8081/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       ErrImagePull
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-4rs8l (ro)
</code>```

Does any help please?

Title: Issues with minikube and building pods

Body:
I am trying to run a microservice spring boot application on Kubernetes(minikube). I create the Dockerfile and the images accordantly. I set the deployment.yml file and then I try to run the cluster with the kubectl command. But, I have always ImagePullBackOff on Status.

NAME                                           READY   STATUS             RESTARTS   AGE
pod/account-service-app-5c6f75d987-ml8j9       0/1     ImagePullBackOff   0          12m
pod/api-gateway-app-744477d8f8-47jg8           0/1     ImagePullBackOff   0          12m
pod/customer-service-app-677966df99-j8fsb      0/1     ImagePullBackOff   0          12m
pod/discovery-service-0                        0/1     ImagePullBackOff   0          29m
pod/notification-service-app-f6d9cf6d6-jlgsq   0/1     ImagePullBackOff   0          12m
pod/transaction-service-app-5b9c6b54cd-6f2cg   0/1     ImagePullBackOff   0          12m

If there is any explanation regarding this issue. When I type describe of a pod. Then I see this:

Controlled By:  ReplicaSet/account-service-app-5c6f75d987
Containers:
  account-service-app:
    Container ID:
    Image:          renosbardis/accounts-service:0.0.1
    Image ID:
    Port:           8081/TCP
    Host Port:      0/TCP
    State:          Waiting
      Reason:       ErrImagePull
    Ready:          False
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-4rs8l (ro)

Does any help please?


问:
How to Aquire Audio in Python, and save to sequential .wav files , but without loosing a sample?
So I got this special project were I need to acquire 8 audio-chanels
And save in a new sequential file every minutes or so (date_time.wav) or similar.
For manual analysis,

Phase 2 of the project , I would analyze signals directly in python
(compare Phases, amplitude, and do FFTs, ext)

I think that Sounddevice and Numpy would give me all I need :)

But I'm a newby in python, Linux and programing, please pardon my ignorance.

I got a Beringher USB Umc1820
Flowing this : https://python-sounddevice.readthedocs.io/en/0.4.5/usage.html#recording
I've manage to record 8 tracks successfully:

```<code>import sounddevice as sd
from scipy.io.wavfile import write
import numpy as np

#How to record   https://python-sounddevice.readthedocs.io/en/0.4.5/usage.html#recording
fs = 44100  # Sample rate
seconds = 10

#To list available devices :    python3 -m sounddevice    3=beringher usb umc1820
sd.default.device = 3
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=8)
sd.wait()
write('record_sound_device.wav', fs, myrecording)

</code>```

But now I fear That If I simply loop this around
I might loose samples while the wav file is saved, also , the first few samples in the wave file are always garbage.

There must be a way to aquire audio continuously , and concurrently save .wav files ?

Asyncio seems to point in the direction I need ,

https://docs.python.org/3/library/asyncio.html#module-asyncio

But with My basic python knowledge, I'm completely lost :(

Body:
So I got this special project were I need to acquire 8 audio-chanels
And save in a new sequential file every minutes or so (date_time.wav) or similar.
For manual analysis,

Phase 2 of the project , I would analyze signals directly in python
(compare Phases, amplitude, and do FFTs, ext)

I think that Sounddevice and Numpy would give me all I need :)

But I'm a newby in python, Linux and programing, please pardon my ignorance.

I got a Beringher USB Umc1820
Flowing this : https://python-sounddevice.readthedocs.io/en/0.4.5/usage.html#recording
I've manage to record 8 tracks successfully:

import sounddevice as sd
from scipy.io.wavfile import write
import numpy as np

#How to record   https://python-sounddevice.readthedocs.io/en/0.4.5/usage.html#recording
fs = 44100  # Sample rate
seconds = 10

#To list available devices :    python3 -m sounddevice    3=beringher usb umc1820
sd.default.device = 3
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=8)
sd.wait()
write('record_sound_device.wav', fs, myrecording)

But now I fear That If I simply loop this around
I might loose samples while the wav file is saved, also , the first few samples in the wave file are always garbage.

There must be a way to aquire audio continuously , and concurrently save .wav files ?

Asyncio seems to point in the direction I need ,

https://docs.python.org/3/library/asyncio.html#module-asyncio

But with My basic python knowledge, I'm completely lost :(


问:
How to use AJAX Calls With The WordPress Rewrite API (after watching this video)
The problem is — I got the JSON response but without any interaction on page and from base of local site-name (\\firstwp.test — that was working fine before I start the experiment of using AJAX).

After watching the video about using AJAX Calls With The WordPress Rewrite API, I add this pretty simple code to the \wp-includes\functions.php:

```<code>add_action( 'init', function () {
    add_rewrite_tag( '%filter_id%', '([0-9]+)' );
    add_rewrite_rule( "filter/([0-9]+)/?", 'index.php?filter_id=$matches[1]', 'top' );
});

add_action( 'template_redirect', function () {
    global $wp_query;

    $filtered_posts = "some wp query...";

    if ( !empty( $filtered_posts ) )
    {
        $response = "some data from query...";
        wp_send_json_success( $response );
    }
});
</code>```

I was thinking to be able to use this code by adding \filter\1 to the url.
But I immediately received a JSON response from the base name of the site without any parameters and additions.
I'm just taking my first steps in WordPress and don't understand how it works there, although I've been using the "standard" AJAX features as XMLHttpRequest for a long time.

Body:
The problem is — I got the JSON response but without any interaction on page and from base of local site-name (\\firstwp.test — that was working fine before I start the experiment of using AJAX).

After watching the video about using AJAX Calls With The WordPress Rewrite API, I add this pretty simple code to the \wp-includes\functions.php:

add_action( 'init', function () {
    add_rewrite_tag( '%filter_id%', '([0-9]+)' );
    add_rewrite_rule( "filter/([0-9]+)/?", 'index.php?filter_id=$matches[1]', 'top' );
});

add_action( 'template_redirect', function () {
    global $wp_query;

    $filtered_posts = "some wp query...";

    if ( !empty( $filtered_posts ) )
    {
        $response = "some data from query...";
        wp_send_json_success( $response );
    }
});

I was thinking to be able to use this code by adding \filter\1 to the url.
But I immediately received a JSON response from the base name of the site without any parameters and additions.
I'm just taking my first steps in WordPress and don't understand how it works there, although I've been using the "standard" AJAX features as XMLHttpRequest for a long time.


问:
Query document where includes reference document
how do i query a document based on found reference doucments.

so i do this query:

```<code>    const user_reservations = await TimeSlot.findOne({
      user_id: user._id,
    });
</code>```

and now i want to find parent document like so:

```<code>await Schedule.find({
      timeSlots: user_reservations,
    })
</code>```

this is does not give back a valid query.

i tried looping through user_reservations and querying timeslots based on id:

```<code>user_reservations.map(async (d) => {
      await Schedule.findOne().populate({
        path: "timeSlots",
        match: { _id: d._id },
      });
    });
</code>```

this also does nothing.

Body:
how do i query a document based on found reference doucments.

so i do this query:

    const user_reservations = await TimeSlot.findOne({
      user_id: user._id,
    });

and now i want to find parent document like so:

await Schedule.find({
      timeSlots: user_reservations,
    })

this is does not give back a valid query.

i tried looping through user_reservations and querying timeslots based on id:

user_reservations.map(async (d) => {
      await Schedule.findOne().populate({
        path: "timeSlots",
        match: { _id: d._id },
      });
    });

this also does nothing.


问:
Passport.js + express.js = Cannot post /(...)
I have searched everywhere for an answer, and I tried debugging as much as I could.
I am using passport.js to authenticate my app with a simple username/password (local) strategy.

A little background:

Until now I was tracking .\node_modules on my git repository (well, I had my reasons...). Recently I changed that and I also migrated the ORM from sequelize to TypeORM.

Well, I don't have a clue if one of these is the reason but all of a sudden, I can't log in my app anymore. I mean, I can authenticate and the session record goes into the database. But when I redirect to the success route, where I do some additional logic, I get acannot POST /login/success message.

I tried everything and I even switched to an old branch, but I highly suspect some package was updated to a version that causes this (I may have updated one or another when running npm install).

Nevertheless, I give you my middleware code, maybe you find something:

```<code>const auth = express.Router();

passport.use(new LocalStrategy(async function verify(username,password,cb){
  cb(null,{uname:username});
}));

passport.serializeUser(function(user, cb) {
  process.nextTick(function() {
    cb(null, { id: user.username});
  });
});

passport.deserializeUser(function(user, cb) {
  process.nextTick(function() {
    return cb(null, user);
  });
});

auth.post('/login',passport.authenticate('local', {
    successRedirect: '/login/success',
    failureRedirect: '/debug'
  }));

auth.post('/logout',function(req,res,next){
  req.logout(async function(err){
    if (err) {return next(err);}

    req.session.destroy(function(err){
      if (err) { return next(err);}
    })
    res.redirect('/logout/success');
  });
})

// !!
auth.get('/login/success', async function(req,res){
  res.send("You are logged in");

})

auth.get('/logout/success', (req,res)=>{
  res.send("You logged out successfully");
})

export default auth;
</code>```

I even removed all the database and authentication logic to remove any possible bugs in that part.

I could solve this by changing auth.get('login/success') to auth.post('login/success'). But this is when I get confused! When express redirects, it should convert a POST method into a GET - well at least until very recently it was doing so! Nevertheless, I tested a new rout /abc`` and did res.redirect(308,"/login/success") but the POST remains a POST...

can anyone help?

Thanks in advance!

P.S.: I forgot a tiny little thing:
on my app main file (index.ts), I have it like this:

```<code>//...
const app = express();
app.use(session({
   //...
});
app.use(passport.authenticate('local');
app.use('/',auth);
//where auth is the import from my authentication file that I show above
</code>```

Body:
I have searched everywhere for an answer, and I tried debugging as much as I could.
I am using passport.js to authenticate my app with a simple username/password (local) strategy.

A little background:

Until now I was tracking .\node_modules on my git repository (well, I had my reasons...). Recently I changed that and I also migrated the ORM from sequelize to TypeORM.

Well, I don't have a clue if one of these is the reason but all of a sudden, I can't log in my app anymore. I mean, I can authenticate and the session record goes into the database. But when I redirect to the success route, where I do some additional logic, I get acannot POST /login/success message.

I tried everything and I even switched to an old branch, but I highly suspect some package was updated to a version that causes this (I may have updated one or another when running npm install).

Nevertheless, I give you my middleware code, maybe you find something:

const auth = express.Router();

passport.use(new LocalStrategy(async function verify(username,password,cb){
  cb(null,{uname:username});
}));

passport.serializeUser(function(user, cb) {
  process.nextTick(function() {
    cb(null, { id: user.username});
  });
});

passport.deserializeUser(function(user, cb) {
  process.nextTick(function() {
    return cb(null, user);
  });
});

auth.post('/login',passport.authenticate('local', {
    successRedirect: '/login/success',
    failureRedirect: '/debug'
  }));

auth.post('/logout',function(req,res,next){
  req.logout(async function(err){
    if (err) {return next(err);}

    req.session.destroy(function(err){
      if (err) { return next(err);}
    })
    res.redirect('/logout/success');
  });
})

// !!
auth.get('/login/success', async function(req,res){
  res.send("You are logged in");

})

auth.get('/logout/success', (req,res)=>{
  res.send("You logged out successfully");
})

export default auth;

I even removed all the database and authentication logic to remove any possible bugs in that part.

I could solve this by changing auth.get('login/success') to auth.post('login/success'). But this is when I get confused! When express redirects, it should convert a POST method into a GET - well at least until very recently it was doing so! Nevertheless, I tested a new rout /abc`` and did res.redirect(308,"/login/success") but the POST remains a POST...

can anyone help?

Thanks in advance!

P.S.: I forgot a tiny little thing:
on my app main file (index.ts), I have it like this:

//...
const app = express();
app.use(session({
   //...
});
app.use(passport.authenticate('local');
app.use('/',auth);
//where auth is the import from my authentication file that I show above


问:
Have gradle task depend on compileDebugKotlin in android project
I have some code generating task that needs to be performed before compilation. I thought I could achieve this by adding compileDebugKotlin.dependsOn myGenerateTask in my build.gradle but I am getting this error:

```<code>Caused by: groovy.lang.MissingPropertyException: Could not get unknown property 'compileDebugKotlin' for project ':app' of type org.gradle.api.Project.
    at org.gradle.internal.metaobject.AbstractDynamicObject.getMissingProperty(AbstractDynamicObject.java:85)
    at org.gradle.groovy.scripts.BasicScript$ScriptDynamicObject.getMissingProperty(BasicScript.java:157)
    at org.gradle.internal.metaobject.AbstractDynamicObject.getProperty(AbstractDynamicObject.java:62)
    at org.gradle.groovy.scripts.BasicScript.getProperty(BasicScript.java:66)
</code>```

I have also tried tasks.getByPath(":app:compileDebugKotlin").dependsOn("myGenerateTask") but it returns a similar error:

```<code>Caused by: org.gradle.api.UnknownTaskException: Task with path ':app:compileDebugKotlin' not found in project ':app'.
    at org.gradle.api.internal.tasks.DefaultTaskContainer.getByPath(DefaultTaskContainer.java:490)
    at org.gradle.api.tasks.TaskContainer$getByPath.call(Unknown Source)
    at build_c7dk0wsonuoytidfaztoeg8ht.run(A:\ws\AndroidStudioProjects\trygghetscentralen2\app\build.gradle:103)
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:91)
    ... 170 more
</code>```

I know that :app:compileDebugKotlin is executed when running gradle build but I can't access the task from my apps build.gradle. How can I depend on this gradle task in an android project?

Body:
I have some code generating task that needs to be performed before compilation. I thought I could achieve this by adding compileDebugKotlin.dependsOn myGenerateTask in my build.gradle but I am getting this error:

Caused by: groovy.lang.MissingPropertyException: Could not get unknown property 'compileDebugKotlin' for project ':app' of type org.gradle.api.Project.
    at org.gradle.internal.metaobject.AbstractDynamicObject.getMissingProperty(AbstractDynamicObject.java:85)
    at org.gradle.groovy.scripts.BasicScript$ScriptDynamicObject.getMissingProperty(BasicScript.java:157)
    at org.gradle.internal.metaobject.AbstractDynamicObject.getProperty(AbstractDynamicObject.java:62)
    at org.gradle.groovy.scripts.BasicScript.getProperty(BasicScript.java:66)

I have also tried tasks.getByPath(":app:compileDebugKotlin").dependsOn("myGenerateTask") but it returns a similar error:

Caused by: org.gradle.api.UnknownTaskException: Task with path ':app:compileDebugKotlin' not found in project ':app'.
    at org.gradle.api.internal.tasks.DefaultTaskContainer.getByPath(DefaultTaskContainer.java:490)
    at org.gradle.api.tasks.TaskContainer$getByPath.call(Unknown Source)
    at build_c7dk0wsonuoytidfaztoeg8ht.run(A:\ws\AndroidStudioProjects\trygghetscentralen2\app\build.gradle:103)
    at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:91)
    ... 170 more

I know that :app:compileDebugKotlin is executed when running gradle build but I can't access the task from my apps build.gradle. How can I depend on this gradle task in an android project?


问:
Recommended way to merge layers of textures in Metal?
Say I have a tree of graphics objects, and each one renders itself into a 'layer' – a Metal texture. Then as a final step I want to merge all these layers into one final output image, to display to screen.

My first idea on how to do this is to run a basic render pass with simple rectangle shapes for each layer. The fragment shader would be a basic texture sampling shader. This works, but it seems wasteful. To define a rectangle, I have to define two triangles, so I imagine the GPU is doing work to calculate their shapes and sample the texture, when really all I want to do is merge rectangles of pixels.

Is there a better way to do this?


问:
Displaying number of correct answers for quiz app
I'm currently stuck on trying to display the number of correct answers once the quiz is finished.

Basically, I have created a state that keeps track of the number of correct answers shown within the QuizItem component. If the user selected answer matches the correct answer, then the user selected answer turns to green and it will increase the state of correctCount (as seen in the code) to 1. This new value is then passed to the parent component of QuizItem which is QuizList.

```<code>
/* eslint-disable react/prop-types */
import React from "react";

import AnswerButton from "../UI/AnswerButton";

import classes from "./QuizItem.module.css";

export default function QuizItem(props) {
const [correctCount, setCorrectCount] = React.useState(0)

function addToCorrectCount() {
    setCorrectCount(correctCount + 1)
  }

props.onSaveCorrectCountData(correctCount)

console.log(correctCount);

  return (
    <div>
      <div key={props.id} className={classes.quizlist__quizitem}>
        <h3 className={classes.quizitem__h3}>{props.question}</h3>
        {props.choices.map((choice) => {
          const styles = {
            backgroundColor: choice.isSelected ? "#D6DBF5" : "white",
          };

          // React.useEffect(() => {
          //   if (choice.isSelected && choice.choice === choice.correct) {
          //     addToCorrectCount();
          //   }
          // }, [choice.isSelected, choice.correct]);

          function checkAnswerStyle() {
            /* this is to indicate that the selected answer is right, makes button go green*/
            if (choice.isSelected && choice.choice === choice.correct) {
              addToCorrectCount()
              return {
                backgroundColor: "#94D7A2",
                color: "#4D5B9E",
                border: "none",
              };
              /* this is to indicate that the selected answer is wrong, makes button go red*/
            } else if (choice.isSelected && choice.choice !== choice.correct) {
              return {
                backgroundColor: "#F8BCBC",
                color: "#4D5B9E",
                border: "none",
              };
              /* this is to highlight the right answer if a selected answer is wrong*/
            } else if (choice.choice === choice.correct) {
              return {
                backgroundColor: "#94D7A2",
                color: "#4D5B9E",
                border: "none",
              };
              /* this is to grey out the incorrect answers*/
            } else {
              return {
                color: "#bfc0c0",
                border: "1px solid #bfc0c0",
                backgroundColor: "white",
              };
            }
          }

          return (
            <AnswerButton
              key={choice.id}
              onClick={() => {
                props.holdAnswer(choice.id);
              }}
              style={props.endQuiz ? checkAnswerStyle() : styles}
            >
              {choice.choice}
            </AnswerButton>
          );
        })}
      </div>
    </div>
  );
}
// create a counter, and for every correct answer (green button), increase the counter by 1.

</code>```

In the QuizList component, I have set another state to receive the incoming value from the QuizItem component and use this new value to display the number of correct answers once the check answers button has been clicked.

```<code>import React from "react";
import { nanoid } from "nanoid";

import QuizItem from "./QuizItem";
import Button from "../UI/Button";
import Card from "../UI/Card";

import classes from "./QuizList.module.css";

export default function QuizList(props) {
  const [quiz, setQuiz] = React.useState([]);
  const [endQuiz, setEndQuiz] = React.useState(false);
  // const [newGame, setNewGame] = React.useState(false);
  const [noOfCorrectAnswers, setNoOfCorrectAnswers] = React.useState()

  function addCorrectCountHandler(correctCount) {
    setNoOfCorrectAnswers(correctCount)
  }

  React.useEffect(() => {
    /* This function turns HTML element entities into normal words */
    function decodeHtml(html) {
      const txt = document.createElement("textarea");
      txt.innerHTML = html;
      return txt.value;
    }

    fetch(
      "https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple"
    )
      .then((res) => res.json())
      .then((data) => {
        const dataArray = data.results;
        const newDataArray = dataArray.map((item) => {
          return {
            question: decodeHtml(item.question),
            choices: [
              {
                choice: decodeHtml(item.correct_answer),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
              {
                choice: decodeHtml(item.incorrect_answers[0]),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
              {
                choice: decodeHtml(item.incorrect_answers[1]),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
              {
                choice: decodeHtml(item.incorrect_answers[2]),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
            ].sort(() => 0.5 - Math.random()),
            id: nanoid(),
          };
        });
        return setQuiz(newDataArray);
      });
  }, []);

  // console.log(quiz);

  function finishQuiz() {
    setEndQuiz((prevEndQuiz) => !prevEndQuiz);
  }

  // function startNewGame() {
  //   setNewGame(true);
  // }

  function holdAnswer(quizId, choiceId) {
    setQuiz((oldQuiz) =>
      oldQuiz.map((quiz) => {
        if (quiz.id !== quizId) return quiz;
        return {
          ...quiz,
          choices: quiz.choices.map((choice) =>
            choice.id === choiceId
              ? // If the choice selected is the current choice, toggle its selected state
                { ...choice, isSelected: !choice.isSelected }
              : // Otherwise, deselect the choice
                { ...choice, isSelected: false }
          ),
        };
      })
    );
  }

  const quizItemComponents = quiz.map((item) => {
    return (
      <QuizItem
        key={item.id}
        question={item.question}
        choices={item.choices}
        holdAnswer={(id) => holdAnswer(item.id, id)}
        endQuiz={endQuiz}
        correct={quiz.correct}
        onSaveCorrectCountData={addCorrectCountHandler}
      />
    );
  });

  return (
    <Card className={classes.quizlist}>
      {quizItemComponents}
      {!endQuiz && <Button onClick={finishQuiz}>Check Answers</Button>}
      {endQuiz && (
        <div className={classes.result}>
          <p>You scored {noOfCorrectAnswers}/5 answers</p>
          <Button onClick={startNewGame}>Play Again</Button>
        </div>
      )}
    </Card>
  );
}
</code>```

The error that I was getting is that there were too many re-renders, so I tried using useEffect on the setCorrectCount state within my QuizItem component (this can be seen in my code and greyed out) but it would not tally up the count.

Is there a good workaround to this problem? Any help or advice would be appreciated.

Link to the code via Stackblitz:
https://stackblitz.com/edit/quizzical

Body:
I'm currently stuck on trying to display the number of correct answers once the quiz is finished.

Basically, I have created a state that keeps track of the number of correct answers shown within the QuizItem component. If the user selected answer matches the correct answer, then the user selected answer turns to green and it will increase the state of correctCount (as seen in the code) to 1. This new value is then passed to the parent component of QuizItem which is QuizList.

/* eslint-disable react/prop-types */
import React from "react";

import AnswerButton from "../UI/AnswerButton";

import classes from "./QuizItem.module.css";

export default function QuizItem(props) {
const [correctCount, setCorrectCount] = React.useState(0)

function addToCorrectCount() {
    setCorrectCount(correctCount + 1)
  }

props.onSaveCorrectCountData(correctCount)

console.log(correctCount);

  return (

{props.question}

        {props.choices.map((choice) => {
          const styles = {
            backgroundColor: choice.isSelected ? "#D6DBF5" : "white",
          };

          // React.useEffect(() => {
          //   if (choice.isSelected && choice.choice === choice.correct) {
          //     addToCorrectCount();
          //   }
          // }, [choice.isSelected, choice.correct]);

          function checkAnswerStyle() {
            /* this is to indicate that the selected answer is right, makes button go green*/
            if (choice.isSelected && choice.choice === choice.correct) {
              addToCorrectCount()
              return {
                backgroundColor: "#94D7A2",
                color: "#4D5B9E",
                border: "none",
              };
              /* this is to indicate that the selected answer is wrong, makes button go red*/
            } else if (choice.isSelected && choice.choice !== choice.correct) {
              return {
                backgroundColor: "#F8BCBC",
                color: "#4D5B9E",
                border: "none",
              };
              /* this is to highlight the right answer if a selected answer is wrong*/
            } else if (choice.choice === choice.correct) {
              return {
                backgroundColor: "#94D7A2",
                color: "#4D5B9E",
                border: "none",
              };
              /* this is to grey out the incorrect answers*/
            } else {
              return {
                color: "#bfc0c0",
                border: "1px solid #bfc0c0",
                backgroundColor: "white",
              };
            }
          }

          return (
            <AnswerButton
              key={choice.id}
              onClick={() => {
                props.holdAnswer(choice.id);
              }}
              style={props.endQuiz ? checkAnswerStyle() : styles}
            >
              {choice.choice}
            </AnswerButton>
          );
        })}

  );
}
// create a counter, and for every correct answer (green button), increase the counter by 1.

In the QuizList component, I have set another state to receive the incoming value from the QuizItem component and use this new value to display the number of correct answers once the check answers button has been clicked.

import React from "react";
import { nanoid } from "nanoid";

import QuizItem from "./QuizItem";
import Button from "../UI/Button";
import Card from "../UI/Card";

import classes from "./QuizList.module.css";

export default function QuizList(props) {
  const [quiz, setQuiz] = React.useState([]);
  const [endQuiz, setEndQuiz] = React.useState(false);
  // const [newGame, setNewGame] = React.useState(false);
  const [noOfCorrectAnswers, setNoOfCorrectAnswers] = React.useState()

  function addCorrectCountHandler(correctCount) {
    setNoOfCorrectAnswers(correctCount)
  }

  React.useEffect(() => {
    /* This function turns HTML element entities into normal words */
    function decodeHtml(html) {
      const txt = document.createElement("textarea");
      txt.innerHTML = html;
      return txt.value;
    }

    fetch(
      "https://opentdb.com/api.php?amount=5&category=9&difficulty=medium&type=multiple"
    )
      .then((res) => res.json())
      .then((data) => {
        const dataArray = data.results;
        const newDataArray = dataArray.map((item) => {
          return {
            question: decodeHtml(item.question),
            choices: [
              {
                choice: decodeHtml(item.correct_answer),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
              {
                choice: decodeHtml(item.incorrect_answers[0]),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
              {
                choice: decodeHtml(item.incorrect_answers[1]),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
              {
                choice: decodeHtml(item.incorrect_answers[2]),
                isSelected: false,
                correct: decodeHtml(item.correct_answer),
                id: nanoid(),
              },
            ].sort(() => 0.5 - Math.random()),
            id: nanoid(),
          };
        });
        return setQuiz(newDataArray);
      });
  }, []);

  // console.log(quiz);

  function finishQuiz() {
    setEndQuiz((prevEndQuiz) => !prevEndQuiz);
  }

  // function startNewGame() {
  //   setNewGame(true);
  // }

  function holdAnswer(quizId, choiceId) {
    setQuiz((oldQuiz) =>
      oldQuiz.map((quiz) => {
        if (quiz.id !== quizId) return quiz;
        return {
          ...quiz,
          choices: quiz.choices.map((choice) =>
            choice.id === choiceId
              ? // If the choice selected is the current choice, toggle its selected state
                { ...choice, isSelected: !choice.isSelected }
              : // Otherwise, deselect the choice
                { ...choice, isSelected: false }
          ),
        };
      })
    );
  }

  const quizItemComponents = quiz.map((item) => {
    return (
      <QuizItem
        key={item.id}
        question={item.question}
        choices={item.choices}
        holdAnswer={(id) => holdAnswer(item.id, id)}
        endQuiz={endQuiz}
        correct={quiz.correct}
        onSaveCorrectCountData={addCorrectCountHandler}
      />
    );
  });

  return (
    <Card className={classes.quizlist}>
      {quizItemComponents}
      {!endQuiz && <Button onClick={finishQuiz}>Check Answers</Button>}
      {endQuiz && (

You scored {noOfCorrectAnswers}/5 answers

          <Button onClick={startNewGame}>Play Again</Button>

      )}
    </Card>
  );
}

The error that I was getting is that there were too many re-renders, so I tried using useEffect on the setCorrectCount state within my QuizItem component (this can be seen in my code and greyed out) but it would not tally up the count.

Is there a good workaround to this problem? Any help or advice would be appreciated.

Link to the code via Stackblitz:
https://stackblitz.com/edit/quizzical


问:
Python Debugger in VS Code: ImportError: /usr/lib/python3.8/lib-dynload/_ctypes.cpython-38-x86_64-linux-gnu.so: undefined symbol: ffi_closure_alloc
While trying to run python debugger in VS Code I run into following error:

```<code>(explore) kaykay@kaykay:~/AutoML$  cd /home/kaykay/AutoML ; /usr/bin/env /bin/python3 /home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 45431 -- /home/kaykay/AutoML/.vscode/launch.json
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.13) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/__main__.py", line 91, in <module>
    main()
  File "/home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/__main__.py", line 18, in main
    from debugpy.launcher import debuggee
  File "/home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/launcher/debuggee.py", line 6, in <module>
    import ctypes
  File "/usr/lib/python3.8/ctypes/__init__.py", line 7, in <module>
    from _ctypes import Union, Structure, Array
ImportError: /usr/lib/python3.8/lib-dynload/_ctypes.cpython-38-x86_64-linux-gnu.so: undefined symbol: ffi_closure_alloc, version LIBFFI_CLOSURE_7.0
</code>```

My launch.json looks like this:

```<code>{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {"name":"Python: Current File","type":"python","request":"launch","program":"${file}","console":"integratedTerminal","justMyCode":true},
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}
</code>```

I tried updating urllib and chardet to no success. I also tried updating torch and torchvision as suggested here which though looks like a different issue.

Body:
While trying to run python debugger in VS Code I run into following error:

(explore) kaykay@kaykay:~/AutoML$  cd /home/kaykay/AutoML ; /usr/bin/env /bin/python3 /home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 45431 -- /home/kaykay/AutoML/.vscode/launch.json
/usr/lib/python3/dist-packages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.13) or chardet (3.0.4) doesn't match a supported version!
  warnings.warn("urllib3 ({}) or chardet ({}) doesn't match a supported "
Traceback (most recent call last):
  File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "/home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/__main__.py", line 91, in <module>
    main()
  File "/home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/__main__.py", line 18, in main
    from debugpy.launcher import debuggee
  File "/home/kaykay/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/launcher/debuggee.py", line 6, in <module>
    import ctypes
  File "/usr/lib/python3.8/ctypes/__init__.py", line 7, in <module>
    from _ctypes import Union, Structure, Array
ImportError: /usr/lib/python3.8/lib-dynload/_ctypes.cpython-38-x86_64-linux-gnu.so: undefined symbol: ffi_closure_alloc, version LIBFFI_CLOSURE_7.0

My launch.json looks like this:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {"name":"Python: Current File","type":"python","request":"launch","program":"${file}","console":"integratedTerminal","justMyCode":true},
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}

I tried updating urllib and chardet to no success. I also tried updating torch and torchvision as suggested here which though looks like a different issue.


问:
How can you make JS-functions for dragandrop work on JS-created-elements?
I want to make a drag-and-drop application were the drpzone-fields are variable (JS -> foreach).
The code workes on the manually created elements (HTML-code).

But when I tried to create a dropzone element in JS it does not work.

I do not know why it does not work.

```<code><div class="dropzone">
    <img id="draggable" src="https://cdn.pixabay.com/photo/2020/12/02/01/06/chipmunk-5795916__340.jpg" draggable="true" width="100" height="35">
</div>
<br/><br/><br/>
<div id="timetable">
    <div class="dropzone"></div>
    <div class="dropzone"></div>
    <div class="dropzone"></div>
</div>
<style>
    body {
        user-select: none;
    }

    #draggable {
        text-align: center;
        background: white;
    }

    .dropzone {
        width: 100px;
        height: 40px;
        background: lightblue;
        margin: 10px;
        padding: 10px;
    }
</style>

<script type='text/javascript'>
    let dragged = null;

    const source = document.getElementById("draggable");
    source.addEventListener("dragstart", (event) => {
        dragged = event.target;
    });

    const target = document.querySelectorAll(".dropzone");
    target.forEach(function (item) {
        item.addEventListener("dragover", (event) => {
            event.preventDefault();
        });

        item.addEventListener("drop", (event) => {
            event.preventDefault();
            if (event.target.className === "dropzone") {
                dragged.parentNode.removeChild(dragged);
                event.target.appendChild(dragged);
            }
        });
    });
    window.onload = () =>{
        createTimetable();
    }

    const createTimetable = () => {

        const ele = document.createElement("div");
        ele.className ="dropzone";
        document.getElementById("timetable").append(ele);

    }

</script>
</code>```


问:
polars LazyFrame.with_context().filter() throws unexpected NotFoundError for column
I have two LazyFrames, df1 and df2.

After filtering df2 according to df1 max value, I want to concatenate them.

But combination of with_context() and filter() on LazyFrames will raise NotFoundError.

What's the best way to do this?

import polars as pl

df1 = pl.DataFrame({'foo': [0, 1], 'bar': ['a', 'a']}).lazy()
df2 = pl.DataFrame({'foo': [1, 2, 3], 'bar': ['b', 'b', 'b']}).lazy()

df = pl.concat(
    [
        df1,
        df2.with_context(df1.select(pl.col('foo').alias('foo_')))
           .filter(pl.col('foo') > pl.col('foo_').max())
    ]).collect()

# ---------------------------------------------------------------------------
# NotFoundError                             Traceback (most recent call last)
# [<ipython-input-2-cf44deab2d4b>](https://localhost:8080/#) in <module>
#       4 df2 = pl.DataFrame({'foo': [1, 2, 3], 'bar': ['b', 'b', 'b']}).lazy()
#       5
# ----> 6 df = pl.concat(
#       7     [
#       8         df1,
#
# 1 frames
# [/usr/local/lib/python3.8/dist-packages/polars/utils.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
#     327         def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
#     328             _rename_kwargs(fn.__name__, kwargs, aliases)
# --> 329             return fn(*args, **kwargs)
#     330
#     331         return wrapper
#
# [/usr/local/lib/python3.8/dist-packages/polars/internals/lazyframe/frame.py](https://localhost:8080/#) in collect(self, type_coercion, predicate_pushdown, projection_pushdown, simplify_expression, no_optimization, slice_pushdown, common_subplan_elimination, streaming)
#    1166             streaming,
#    1167         )
# -> 1168         return pli.wrap_df(ldf.collect())
#    1169
#    1170     def sink_parquet(
#
# NotFoundError: foo_
```
<p>When I assign comparison result as a column, error not raised,</p>
<pre class="lang-py prettyprint-override"><code>(df2.with_context(df1.select(pl.col('foo').alias('foo_')))
    .with_column((pl.col('foo') > pl.col('foo_').max()).alias('x'))
    .filter(pl.col('x'))).collect()
# OK
</code>```

But I drop that column after filter(), error again.

(df2.with_context(df1.select(pl.col('foo').alias('foo_')))
    .with_column((pl.col('foo') > pl.col('foo_').max()).alias('x'))
    .filter(pl.col('x'))
    .drop('x')).collect()
# NotFoundError: foo_
```
<p>Finally I find this works. But what's the difference between the previous?<br />
(it seems verbose. other good solution exists?)</p>
<pre class="lang-py prettyprint-override"><code>(df2.with_context(df1.select(pl.col('foo').alias('foo_')))
    .with_column(pl.col('foo_').max())
    .filter(pl.col('foo') > pl.col('foo_'))
    .drop('foo_')).collect()
# OK
</code>```

related?
https://stackoverflow.com/a/71108312/7402018

Body:
I have two LazyFrames, df1 and df2.

After filtering df2 according to df1 max value, I want to concatenate them.

But combination of with_context() and filter() on LazyFrames will raise NotFoundError.

What's the best way to do this?

import polars as pl

df1 = pl.DataFrame({'foo': [0, 1], 'bar': ['a', 'a']}).lazy()
df2 = pl.DataFrame({'foo': [1, 2, 3], 'bar': ['b', 'b', 'b']}).lazy()

df = pl.concat(
    [
        df1,
        df2.with_context(df1.select(pl.col('foo').alias('foo_')))
           .filter(pl.col('foo') > pl.col('foo_').max())
    ]).collect()

# ---------------------------------------------------------------------------
# NotFoundError                             Traceback (most recent call last)
# [<ipython-input-2-cf44deab2d4b>](https://localhost:8080/#) in <module>
#       4 df2 = pl.DataFrame({'foo': [1, 2, 3], 'bar': ['b', 'b', 'b']}).lazy()
#       5
# ----> 6 df = pl.concat(
#       7     [
#       8         df1,
#
# 1 frames
# [/usr/local/lib/python3.8/dist-packages/polars/utils.py](https://localhost:8080/#) in wrapper(*args, **kwargs)
#     327         def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
#     328             _rename_kwargs(fn.__name__, kwargs, aliases)
# --> 329             return fn(*args, **kwargs)
#     330
#     331         return wrapper
#
# [/usr/local/lib/python3.8/dist-packages/polars/internals/lazyframe/frame.py](https://localhost:8080/#) in collect(self, type_coercion, predicate_pushdown, projection_pushdown, simplify_expression, no_optimization, slice_pushdown, common_subplan_elimination, streaming)
#    1166             streaming,
#    1167         )
# -> 1168         return pli.wrap_df(ldf.collect())
#    1169
#    1170     def sink_parquet(
#
# NotFoundError: foo_

When I assign comparison result as a column, error not raised,

(df2.with_context(df1.select(pl.col('foo').alias('foo_')))
    .with_column((pl.col('foo') > pl.col('foo_').max()).alias('x'))
    .filter(pl.col('x'))).collect()
# OK

But I drop that column after filter(), error again.

(df2.with_context(df1.select(pl.col('foo').alias('foo_')))
    .with_column((pl.col('foo') > pl.col('foo_').max()).alias('x'))
    .filter(pl.col('x'))
    .drop('x')).collect()
# NotFoundError: foo_

Finally I find this works. But what's the difference between the previous?

(it seems verbose. other good solution exists?)

(df2.with_context(df1.select(pl.col('foo').alias('foo_')))
    .with_column(pl.col('foo_').max())
    .filter(pl.col('foo') > pl.col('foo_'))
    .drop('foo_')).collect()
# OK

related?
https://stackoverflow.com/a/71108312/7402018


问:
Is there a filter or action to override Wordpress post_exists function for a custom post type?
I am using the permalink Post name in setup. I have a very large custom database where the post names are stored and would like not to create millions of posts in wp_posts. I have a custom template that gets invoked when the custom post type single- is invoked. If the post is not in wp_posts the template never gets invoked. Instead a 404 error is generated. I'd like to override wordpress in my plugin so it always thinks my custom post_type posts exist and have my template handle any missing posts, etc.

Does this make sense? I can't seem to find any info on any overrides. It seems I would want to override post_exists somehow?


问:
GTK4 doesn't show mnemonics underline in a button
I want to set a mnemonic underline in a button called Quit, but this underline is not displayed though keyboard acceleration works by pressing ALT and the specified mnemonic key. In the code I have set use-underline to true. but it just doesn't work. I want the Q character to be underlined so that the Q character is recognizable as menemonic to the user. What am I doing wrong?

Here is my simplified main code:

```<code>#include <gtk/gtk.h>
#include <glib/gstdio.h>

static void activate (GtkApplication *app, gpointer user_data) {
  GtkBuilder *builder = gtk_builder_new ();
  gtk_builder_add_from_file (builder, "builder1.ui", NULL);
  GObject *window = gtk_builder_get_object (builder, "window");
  gtk_window_set_application (GTK_WINDOW (window), app);
  gtk_widget_show (GTK_WIDGET (window));
}

int main (int argc, char *argv[]) {
#ifdef GTK_SRCDIR
  g_chdir (GTK_SRCDIR);
#endif

  GtkApplication *app = gtk_application_new ("org.gtk.example",
G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);

  int status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}
</code>```

Here is my builder code:

```<code><?xml version="1.0" encoding="UTF-8"?>
<interface>
<object id="window" class="GtkWindow">

    <property name="title">Grid</property>
    <child>
      <object id="grid" class="GtkGrid">
        <child>
          <object id="quit" class="GtkButton">
            <property name="use-underline">true</property>
            <property name="label">_Quit</property>
            <property name="has-frame">true</property>
            <layout>
              <property name="column">1</property>
              <property name="row">2</property>
              <property name="column-span">1</property>
            </layout>
          </object>
        </child>
      </object>
    </child>
  </object>
</interface>
</code>```

Body:
I want to set a mnemonic underline in a button called Quit, but this underline is not displayed though keyboard acceleration works by pressing ALT and the specified mnemonic key. In the code I have set use-underline to true. but it just doesn't work. I want the Q character to be underlined so that the Q character is recognizable as menemonic to the user. What am I doing wrong?

Here is my simplified main code:

#include <gtk/gtk.h>
#include <glib/gstdio.h>

static void activate (GtkApplication *app, gpointer user_data) {
  GtkBuilder *builder = gtk_builder_new ();
  gtk_builder_add_from_file (builder, "builder1.ui", NULL);
  GObject *window = gtk_builder_get_object (builder, "window");
  gtk_window_set_application (GTK_WINDOW (window), app);
  gtk_widget_show (GTK_WIDGET (window));
}

int main (int argc, char *argv[]) {
#ifdef GTK_SRCDIR
  g_chdir (GTK_SRCDIR);
#endif

  GtkApplication *app = gtk_application_new ("org.gtk.example",
G_APPLICATION_FLAGS_NONE);
  g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);

  int status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

Here is my builder code:

<?xml version="1.0" encoding="UTF-8"?>
<interface>
<object id="window" class="GtkWindow">

    <property name="title">Grid</property>
    <child>
      <object id="grid" class="GtkGrid">
        <child>
          <object id="quit" class="GtkButton">
            <property name="use-underline">true</property>
            <property name="label">_Quit</property>
            <property name="has-frame">true</property>
            <layout>
              <property name="column">1</property>
              <property name="row">2</property>
              <property name="column-span">1</property>
            </layout>
          </object>
        </child>
      </object>
    </child>
  </object>
</interface>


问:
Javafx custom pseudo class css parse error
I have written code using a PseudoClass in java code which is the same as various web examples such as the one in the javadoc: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#pseudoClassStateChanged-javafx.css.PseudoClass-boolean-

```<code>public class SuggestedButton extends Button {

    private static final PseudoClass SUGGESTED_PSEUDO_CLASS_STATE = PseudoClass.getPseudoClass("suggested");

    BooleanProperty suggestedState = new BooleanPropertyBase(false) {

        @Override public void invalidated() {
            pseudoClassStateChanged(SUGGESTED_PSEUDO_CLASS_STATE, get());
       }

        @Override public Object getBean() {
           return SuggestedButton.this;
       }

        @Override public String getName() {
           return "suggestedState";
       }
   };

   public void setSuggested(boolean isSuggested) {
        this.suggestedState.set(isSuggested);
      }
}
</code>```

This appears to work fine, however my editor highlights ":suggested" in red in the css file:

```<code>.btn-apply:suggested {
    -fx-background-color: green;
    background-color: green;
}
</code>```

When I run the program and use a controller that contains a SuggestedButton, I see this warning and the button doesn't change color:

Dec 26, 2022 4:06:05 PM javafx.css.CssParser declaration WARNING: CSS
Error parsing '*{btn-apply}: Expected COLON at [1,11]

In my .fxml file I am not setting the versions for javafx:

```<code>xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"
</code>```

I am using javafx version 13 in my dependencies.

Adding

```<code>System.out.println()
</code>```

shows that the events are firing correctly.

Any ideas on what is wrong?

Body:
I have written code using a PseudoClass in java code which is the same as various web examples such as the one in the javadoc: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#pseudoClassStateChanged-javafx.css.PseudoClass-boolean-

public class SuggestedButton extends Button {

    private static final PseudoClass SUGGESTED_PSEUDO_CLASS_STATE = PseudoClass.getPseudoClass("suggested");

    BooleanProperty suggestedState = new BooleanPropertyBase(false) {

        @Override public void invalidated() {
            pseudoClassStateChanged(SUGGESTED_PSEUDO_CLASS_STATE, get());
       }

        @Override public Object getBean() {
           return SuggestedButton.this;
       }

        @Override public String getName() {
           return "suggestedState";
       }
   };

   public void setSuggested(boolean isSuggested) {
        this.suggestedState.set(isSuggested);
      }
}

This appears to work fine, however my editor highlights ":suggested" in red in the css file:

.btn-apply:suggested {
    -fx-background-color: green;
    background-color: green;
}

When I run the program and use a controller that contains a SuggestedButton, I see this warning and the button doesn't change color:

Dec 26, 2022 4:06:05 PM javafx.css.CssParser declaration WARNING: CSS
Error parsing '*{btn-apply}: Expected COLON at [1,11]

In my .fxml file I am not setting the versions for javafx:

xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml"

I am using javafx version 13 in my dependencies.

Adding

System.out.println()

shows that the events are firing correctly.

Any ideas on what is wrong?


问:
getUserMedia mutes the sound while recording current tab
[Goal]: To record the sound of a tab and at the same time hear the sound while it's being recorded

[Means]: To use chrome.tabCapture because it's less invasive than chrome.desktopCapture or navigator.mediaDevices.getDisplayMedia. The former provides a better user experience as opposed to the latter which asks for tab selection every time and then intrusively shows the blue rectangle with a status bar and the "Stop Sharing" button

[Issue]: Tab sound is muted after getting the stream (recording not necessary, only calling getUserMedia) and can not be unmuted. Is this a bug? How can it be avoided?

[Technicals]:

Obtain the stream id in a foreground page (popup, options, or iframe pointing to an extension page, injected in the current DOM by a content script) because that's the only place where tabCapture is available

const tabId = ...get current tab id...
chrome.tabCapture.getMediaStreamId({ consumerTabId: tabId }, function(streamId) {
    // send the streamId to the content script
})
```
<ol start="2">
<li>Receive the streamId then use it to start the capture</li>
</ol>
<pre class="lang-js prettyprint-override"><code>const options = {
    audio: {
        mandatory: {
            chromeMediaSource: 'tab',
            chromeMediaSourceId: streamId
        }
    }
}
navigator.mediaDevices.getUserMedia(options).then((tabStream) => {
    // at this point the sound of the tab becomes muted with no way to unmute it
});
</code>```

Just invoking tabCapture will mute the tab. AudioContext source connecting to the default destination doesn't do anything for this stream and no error is thrown. If the callback promise from getUserMedia is empty, the sound of the tab comes back on its own in about 20 seconds or so. If MediaRecorder actually uses the stream to record the sound, the sound doesn't come back until recording is stopped. The sound of the tab is present in the recording, just muted while recording.

[Comparison 1]: Obtaining a MediaStream directly with chrome.tabCapture.capture instead of the above mechanism works as intended. The tab sound is muted, but can be reconnected to the speakers using AudioContext. The issue with this approach is that chrome.tabCapture.capture can't be started successfully in an injected iframe (always fails with the cryptic "Error starting tab capture"), so there's no way to capture the sound. It does work in a popup though, but not really an option given its volatile nature.

[Comparison 2]: chrome.desktopCapture works in the opposite way. The sound is always present in the tab while recording and can not be muted, not that this poses a problem.

Body:
[Goal]: To record the sound of a tab and at the same time hear the sound while it's being recorded

[Means]: To use chrome.tabCapture because it's less invasive than chrome.desktopCapture or navigator.mediaDevices.getDisplayMedia. The former provides a better user experience as opposed to the latter which asks for tab selection every time and then intrusively shows the blue rectangle with a status bar and the "Stop Sharing" button

[Issue]: Tab sound is muted after getting the stream (recording not necessary, only calling getUserMedia) and can not be unmuted. Is this a bug? How can it be avoided?

[Technicals]:

Obtain the stream id in a foreground page (popup, options, or iframe pointing to an extension page, injected in the current DOM by a content script) because that's the only place where tabCapture is available

const tabId = ...get current tab id...
chrome.tabCapture.getMediaStreamId({ consumerTabId: tabId }, function(streamId) {
    // send the streamId to the content script
})

Receive the streamId then use it to start the capture

const options = {
    audio: {
        mandatory: {
            chromeMediaSource: 'tab',
            chromeMediaSourceId: streamId
        }
    }
}
navigator.mediaDevices.getUserMedia(options).then((tabStream) => {
    // at this point the sound of the tab becomes muted with no way to unmute it
});

Just invoking tabCapture will mute the tab. AudioContext source connecting to the default destination doesn't do anything for this stream and no error is thrown. If the callback promise from getUserMedia is empty, the sound of the tab comes back on its own in about 20 seconds or so. If MediaRecorder actually uses the stream to record the sound, the sound doesn't come back until recording is stopped. The sound of the tab is present in the recording, just muted while recording.

[Comparison 1]: Obtaining a MediaStream directly with chrome.tabCapture.capture instead of the above mechanism works as intended. The tab sound is muted, but can be reconnected to the speakers using AudioContext. The issue with this approach is that chrome.tabCapture.capture can't be started successfully in an injected iframe (always fails with the cryptic "Error starting tab capture"), so there's no way to capture the sound. It does work in a popup though, but not really an option given its volatile nature.

[Comparison 2]: chrome.desktopCapture works in the opposite way. The sound is always present in the tab while recording and can not be muted, not that this poses a problem.


问:
Configure Google Cloud Platform bucket to serve example.com/page.html when user accesses example.com/page
I'm hosting a static (NextJS) site on a GCP bucket, with my domain CNAME (let's say example.com) pointing to GCP. When Javascript is disabled, NextJS links in my generated content point to URLs like:

Page 1

but the actual file stored in the bucket is:

pages/1.html

which generates a 404 error when Javascript is disabled and <Link> doesn't capture the click.

I'm aware of the specialty page option MainPageSuffix in GCP, but I have it set as index.html and I don't think it can be set to rewrite someaddress to someaddress.html (and even if it could, it would not serve my root index.html corrctly when I point my browser to example.com)

I'm also aware of the as option in NextJS, but if I use it like:

<Link
   href={`/pages/1`}
   as={`/pages/1.html`}
>
```

it will not work when Javascript is enabled and I'm serving the site locally with npm run dev (I suppose it confuses <Link>?).

Is there any way to make this work? I'm using Next.js v13.0.7

(Alternatively, is there any other (free tier) option to host my site? I thought I could use Cloudflare Pages, but my static site has a lot of small pages - in the order of 100k - and Pages has a file limit of 20k)

Body:
I'm hosting a static (NextJS) site on a GCP bucket, with my domain CNAME (let's say example.com) pointing to GCP. When Javascript is disabled, NextJS links in my generated content point to URLs like:

Page 1

but the actual file stored in the bucket is:

pages/1.html

which generates a 404 error when Javascript is disabled and <Link> doesn't capture the click.

I'm aware of the specialty page option MainPageSuffix in GCP, but I have it set as index.html and I don't think it can be set to rewrite someaddress to someaddress.html (and even if it could, it would not serve my root index.html corrctly when I point my browser to example.com)

I'm also aware of the as option in NextJS, but if I use it like:

<Link
   href={`/pages/1`}
   as={`/pages/1.html`}
>

it will not work when Javascript is enabled and I'm serving the site locally with npm run dev (I suppose it confuses <Link>?).

Is there any way to make this work? I'm using Next.js v13.0.7

(Alternatively, is there any other (free tier) option to host my site? I thought I could use Cloudflare Pages, but my static site has a lot of small pages - in the order of 100k - and Pages has a file limit of 20k)


问:
React: which 'loaders' are required to process a graphql query?
I am trying to use graphql with a react, apollo, typescript, prisma app.

When I try to refetch queries after a form is created, I get an error saying I may need other loaders to process that request.

Module parse failed: Unexpected token (119:36) File was processed with
these loaders: *
../../node_modules/next/dist/build/webpack/loaders/next-swc-loader.js

../../node_modules/@sentry/nextjs/cjs/config/loaders/proxyLoader.js You may need an additional loader to handle the result of these
loaders. | }); | }, > refetchAllIssueGroups ();

I tried updating my tsconfig to replace "preserve" with "react",

```<code>"jsx": "preserve",
</code>```

but everytime I stop the localhost and restart, the setting reverts back to 'preserve'. I don't know why.

Does anyone know which loaders I need to be able to ask graphql to refetch a query?

I have the request defined in my component as:

```<code>  const {  data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()
</code>```

Im trying to use it in my form success handler as follows:

```<code>  createIssueGroup({ variables: { data } }),
        {
            onSuccess: async (res, toast) => {
                await refetchAllIssueGroups()
                toast({
                    title: "IssueGroup created",
                    status: "success",
                })
                form.reset()
                onClose()
</code>```

Body:
I am trying to use graphql with a react, apollo, typescript, prisma app.

When I try to refetch queries after a form is created, I get an error saying I may need other loaders to process that request.

Module parse failed: Unexpected token (119:36) File was processed with
these loaders: *
../../node_modules/next/dist/build/webpack/loaders/next-swc-loader.js

../../node_modules/@sentry/nextjs/cjs/config/loaders/proxyLoader.js You may need an additional loader to handle the result of these
loaders. | }); | }, > refetchAllIssueGroups ();

I tried updating my tsconfig to replace "preserve" with "react",

"jsx": "preserve",

but everytime I stop the localhost and restart, the setting reverts back to 'preserve'. I don't know why.

Does anyone know which loaders I need to be able to ask graphql to refetch a query?

I have the request defined in my component as:

  const {  data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()

Im trying to use it in my form success handler as follows:

  createIssueGroup({ variables: { data } }),
        {
            onSuccess: async (res, toast) => {
                await refetchAllIssueGroups()
                toast({
                    title: "IssueGroup created",
                    status: "success",
                })
                form.reset()
                onClose()