问:
How to solve for input received in cascading dropdown?
I am a complete beginner making a site for fun/skill development. I saw this code snippet online for cascading dropdowns, but when I run the below code, the form value for "First" comes through as the index number for the value I see in the dropdown (eg. Meals comes through as a 1).

  <meta name="viewport" content="width=device-width, initial-scale=1">

Cascading Dropdown Example

  <form name="form1" id="form1" action="/action_page.php">
    First:
    <select name="first" id="first">
      <option value="" selected="selected">Select type</option>
    </select>

 Second A:
    <select name="seconda" id="seconda">
      <option value="" selected="selected">Please select first</option>
    </select>

 Second B:
    <select name="secondb" id="secondb">
      <option value="" selected="selected">Please select first</option>
    </select>

    <input type="submit" value="Submit">
  </form>

```

I know how to alter the code to get the value of First to come through as the text, but that then messes up the cascading dropdowns. How can I get the form, upon hitting submit, to give me the text value from "First" and not the index number of whatever is selected?

Body:
I am a complete beginner making a site for fun/skill development. I saw this code snippet online for cascading dropdowns, but when I run the below code, the form value for "First" comes through as the index number for the value I see in the dropdown (eg. Meals comes through as a 1).

  <meta name="viewport" content="width=device-width, initial-scale=1">

Cascading Dropdown Example

  <form name="form1" id="form1" action="/action_page.php">
    First:
    <select name="first" id="first">
      <option value="" selected="selected">Select type</option>
    </select>

 Second A:
    <select name="seconda" id="seconda">
      <option value="" selected="selected">Please select first</option>
    </select>

 Second B:
    <select name="secondb" id="secondb">
      <option value="" selected="selected">Please select first</option>
    </select>

    <input type="submit" value="Submit">
  </form>

I know how to alter the code to get the value of First to come through as the text, but that then messes up the cascading dropdowns. How can I get the form, upon hitting submit, to give me the text value from "First" and not the index number of whatever is selected?


来源: stackexchange

问:
Time-Series Transformer Model trains well but performs worse on Test Data
I have created a transformer model for multivariate time series predictions (many-to-one classification model).

Details about the Dataset

I have the hourly varying data i.e., 8 different features (hour, month, temperature, humidity, windspeed, solar radiations concentration etc.) and with them I am trying to predict the time sequence (energy consumption of a building. So my input has the shape X.shape = (8783, 168, 8) i.e., 8783 time sequences, each sequence contains 168 hourly entries/vectors and each vector contains 8 features. My output has the shape Y.shape = (8783,1) i.e., 8783 sequences each containing 1 output value (i.e., building energy consumption value after every hour).

Model Details

I took as a model an example from the official keras site. It is created for classification problems, I modified it for my regression problem by changing the activation of last output layer from sigmoid to relu.
Input shape (train_f) = (8783, 168, 8)
Output shape (train_P) = (8783,1)
When I train the model for 100 no. of epochs it converges very well for less number of epochs as compared to my reference models (i.e., LSTMs and LSTMS with self attention). After training, when the model is asked to make prediction by feeding in the test data, the prediction performance is worse as compare to the reference models.

I would be grateful if you please have a look at the code and let me know of the potential steps to improve the prediction/test accuracy.

Here is the code;

```<code>df_weather = pd.read_excel(r"Downloads\WeatherData.xlsx")
df_energy = pd.read_excel(r"Downloads\Building_energy_consumption_record.xlsx")
visa = pd.concat([df_weather, df_energy], axis = 1)
df_data = visa.loc[:, ~visa.columns.isin(["Time1", "TD", "U", "DR", "FX"])

msna.bar(df_data)

plt.figure(figsize = (16,6))
sb.heatmap(df_data.corr(), annot = True, linewidths=1, fmt = ".2g", cmap= 'coolwarm')
plt.xticks(rotation = 'horizontal')  # how the titles will look likemeans their orientation

extract_for_normalization = list(df_data)[1:9]

df_data_float = df_data[extract_for_normalization].astype(float)

from sklearn.model_selection import train_test_split
train_X, test_X = train_test_split(df_data_float, train_size = 0.7, shuffle = False)

scaler = MinMaxScaler(feature_range=(0, 1))

scaled_train_X=scaler.fit_transform(train_X)

**Converting train_X into required shape (inputs,sequences, features)**

train_f = []  #features input from training data
train_p = [] # prediction values
#test_q = []
#test_r = []
n_future = 1 #number of days we want to predict into the future
n_past = 168 # no. of time series input features to be considered for training

for val in range(n_past, len(scaled_train_X) - n_future+1):
    train_f.append(scaled_train_X[val - n_past:val, 0:scaled_train_X.shape[1]])
    train_p.append(scaled_train_X[val + n_future - 1:val + n_future, -1])

train_f, train_p = np.array(train_f), np.array(train_p)

**Transformer Model**

def transformer_encoder(inputs, head_size, num_heads, ff_dim, dropout=0):
    # Normalization and Attention
    x = layers.LayerNormalization(epsilon=1e-6)(inputs)
    x = layers.MultiHeadAttention(
        key_dim=head_size, num_heads=num_heads, dropout=dropout
    )(x, x)
    x = layers.Dropout(dropout)(x)
    res = x + inputs

    # Feed Forward Part
    x = layers.LayerNormalization(epsilon=1e-6)(res)
    x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
    x = layers.Dropout(dropout)(x)
    x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
    return x + res

def build_model(
    input_shape,
    head_size,
    num_heads,
    ff_dim,
    num_transformer_blocks,
    mlp_units,
    dropout=0,
    mlp_dropout=0,
):
    inputs = keras.Input(shape=input_shape)
    x = inputs
    for _ in range(num_transformer_blocks):
        x = transformer_encoder(x, head_size, num_heads, ff_dim, dropout)

    x = layers.GlobalAveragePooling1D(data_format="channels_first")(x)
    for dim in mlp_units:
        x = layers.Dense(dim, activation="relu")(x)
        x = layers.Dropout(mlp_dropout)(x)
    outputs = layers.Dense(train_p.shape[1])(x)
    return keras.Model(inputs, outputs)

input_shape = (train_f.shape[1], train_f.shape[2])

model = build_model(
    input_shape,
    head_size=256,
    num_heads=4,
    ff_dim=4,
    num_transformer_blocks=4,
    mlp_units=[128],
    mlp_dropout=0.4,
    dropout=0.25,
)

model.compile(loss=tf.keras.losses.mean_absolute_error,
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
              metrics=["mse"])

model.summary()

history = model.fit(train_f, train_p, epochs=100, batch_size = 32, validation_split = 0.15, verbose = 1)

trainYPredict = model.predict(train_f)

**Inverse transform the prediction and keep the last value(output)**

trainYPredict1 = np.repeat(trainYPredict, scaled_train_X.shape[1], axis = -1)
trainYPredict_actual = scaler.inverse_transform(trainYPredict1)[:, -1]

train_p_actual = np.repeat(train_p, scaled_train_X.shape[1], axis = -1)

train_p_actual1 = scaler.inverse_transform(train_p_actual)[:, -1]

Prediction_mse=mean_squared_error(train_p_actual1 ,trainYPredict_actual)
print("Mean Squared Error of prediction is:", str(Prediction_mse))

Prediction_rmse =sqrt(Prediction_mse)
print("Root Mean Squared Error of prediction is:", str(Prediction_rmse))

prediction_r2=r2_score(train_p_actual1 ,trainYPredict_actual)
print("R2 score of predictions is:", str(prediction_r2))

prediction_mae=mean_absolute_error(train_p_actual1 ,trainYPredict_actual)
print("Mean absolute error of prediction is:", prediction_mae)

**Testing of model**

scaled_test_X = scaler.transform(test_X)
test_q = []
test_r = []

for val in range(n_past, len(scaled_test_X) - n_future+1):
    test_q.append(scaled_test_X[val - n_past:val, 0:scaled_test_X.shape[1]])
    test_r.append(scaled_test_X[val + n_future - 1:val + n_future, -1])

test_q, test_r = np.array(test_q), np.array(test_r)

testPredict = model.predict(test_q )
</code>```

Validation and training loss image is also attached Training and validation Loss

ContentLicense: CC BY-SA 4.0

Body:
I have created a transformer model for multivariate time series predictions (many-to-one classification model).

Details about the Dataset

I have the hourly varying data i.e., 8 different features (hour, month, temperature, humidity, windspeed, solar radiations concentration etc.) and with them I am trying to predict the time sequence (energy consumption of a building. So my input has the shape X.shape = (8783, 168, 8) i.e., 8783 time sequences, each sequence contains 168 hourly entries/vectors and each vector contains 8 features. My output has the shape Y.shape = (8783,1) i.e., 8783 sequences each containing 1 output value (i.e., building energy consumption value after every hour).

Model Details

I took as a model an example from the official keras site. It is created for classification problems, I modified it for my regression problem by changing the activation of last output layer from sigmoid to relu.
Input shape (train_f) = (8783, 168, 8)
Output shape (train_P) = (8783,1)
When I train the model for 100 no. of epochs it converges very well for less number of epochs as compared to my reference models (i.e., LSTMs and LSTMS with self attention). After training, when the model is asked to make prediction by feeding in the test data, the prediction performance is worse as compare to the reference models.

I would be grateful if you please have a look at the code and let me know of the potential steps to improve the prediction/test accuracy.

Here is the code;

df_weather = pd.read_excel(r"Downloads\WeatherData.xlsx")
df_energy = pd.read_excel(r"Downloads\Building_energy_consumption_record.xlsx")
visa = pd.concat([df_weather, df_energy], axis = 1)
df_data = visa.loc[:, ~visa.columns.isin(["Time1", "TD", "U", "DR", "FX"])

msna.bar(df_data)

plt.figure(figsize = (16,6))
sb.heatmap(df_data.corr(), annot = True, linewidths=1, fmt = ".2g", cmap= 'coolwarm')
plt.xticks(rotation = 'horizontal')  # how the titles will look likemeans their orientation

extract_for_normalization = list(df_data)[1:9]

df_data_float = df_data[extract_for_normalization].astype(float)

from sklearn.model_selection import train_test_split
train_X, test_X = train_test_split(df_data_float, train_size = 0.7, shuffle = False)

scaler = MinMaxScaler(feature_range=(0, 1))

scaled_train_X=scaler.fit_transform(train_X)

**Converting train_X into required shape (inputs,sequences, features)**

train_f = []  #features input from training data
train_p = [] # prediction values
#test_q = []
#test_r = []
n_future = 1 #number of days we want to predict into the future
n_past = 168 # no. of time series input features to be considered for training

for val in range(n_past, len(scaled_train_X) - n_future+1):
    train_f.append(scaled_train_X[val - n_past:val, 0:scaled_train_X.shape[1]])
    train_p.append(scaled_train_X[val + n_future - 1:val + n_future, -1])

train_f, train_p = np.array(train_f), np.array(train_p)

**Transformer Model**

def transformer_encoder(inputs, head_size, num_heads, ff_dim, dropout=0):
    # Normalization and Attention
    x = layers.LayerNormalization(epsilon=1e-6)(inputs)
    x = layers.MultiHeadAttention(
        key_dim=head_size, num_heads=num_heads, dropout=dropout
    )(x, x)
    x = layers.Dropout(dropout)(x)
    res = x + inputs

    # Feed Forward Part
    x = layers.LayerNormalization(epsilon=1e-6)(res)
    x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
    x = layers.Dropout(dropout)(x)
    x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
    return x + res

def build_model(
    input_shape,
    head_size,
    num_heads,
    ff_dim,
    num_transformer_blocks,
    mlp_units,
    dropout=0,
    mlp_dropout=0,
):
    inputs = keras.Input(shape=input_shape)
    x = inputs
    for _ in range(num_transformer_blocks):
        x = transformer_encoder(x, head_size, num_heads, ff_dim, dropout)

    x = layers.GlobalAveragePooling1D(data_format="channels_first")(x)
    for dim in mlp_units:
        x = layers.Dense(dim, activation="relu")(x)
        x = layers.Dropout(mlp_dropout)(x)
    outputs = layers.Dense(train_p.shape[1])(x)
    return keras.Model(inputs, outputs)

input_shape = (train_f.shape[1], train_f.shape[2])

model = build_model(
    input_shape,
    head_size=256,
    num_heads=4,
    ff_dim=4,
    num_transformer_blocks=4,
    mlp_units=[128],
    mlp_dropout=0.4,
    dropout=0.25,
)

model.compile(loss=tf.keras.losses.mean_absolute_error,
              optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
              metrics=["mse"])

model.summary()

history = model.fit(train_f, train_p, epochs=100, batch_size = 32, validation_split = 0.15, verbose = 1)

trainYPredict = model.predict(train_f)

**Inverse transform the prediction and keep the last value(output)**

trainYPredict1 = np.repeat(trainYPredict, scaled_train_X.shape[1], axis = -1)
trainYPredict_actual = scaler.inverse_transform(trainYPredict1)[:, -1]

train_p_actual = np.repeat(train_p, scaled_train_X.shape[1], axis = -1)

train_p_actual1 = scaler.inverse_transform(train_p_actual)[:, -1]

Prediction_mse=mean_squared_error(train_p_actual1 ,trainYPredict_actual)
print("Mean Squared Error of prediction is:", str(Prediction_mse))

Prediction_rmse =sqrt(Prediction_mse)
print("Root Mean Squared Error of prediction is:", str(Prediction_rmse))

prediction_r2=r2_score(train_p_actual1 ,trainYPredict_actual)
print("R2 score of predictions is:", str(prediction_r2))

prediction_mae=mean_absolute_error(train_p_actual1 ,trainYPredict_actual)
print("Mean absolute error of prediction is:", prediction_mae)

**Testing of model**

scaled_test_X = scaler.transform(test_X)
test_q = []
test_r = []

for val in range(n_past, len(scaled_test_X) - n_future+1):
    test_q.append(scaled_test_X[val - n_past:val, 0:scaled_test_X.shape[1]])
    test_r.append(scaled_test_X[val + n_future - 1:val + n_future, -1])

test_q, test_r = np.array(test_q), np.array(test_r)

testPredict = model.predict(test_q )

Validation and training loss image is also attached Training and validation Loss


问:
TypeError: object of type 'NoneType' has no len()
I tried this code with the library django-zxcvbn-password when i do it without using this library everything work but when i use this library it seems like when i write a weak password the password field doesn't receive it and that lead to a NoneType Object because password is empty, and i don't know why but when i try it with a good password everything works perfectly.

I use this library for security purpose.

```<code>class SignUpForm(forms.Form)

    """password_regex = RegexValidator(
        regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$',
        message="Password must be at least 8 characters in length and contain at least one uppercase letter, "
                "one lowercase letter, and one digit. "
    )"""

    name_regex = RegexValidator(
        regex=r'^[A-Z][a-z]{2,149}$',
        message="Names must begin with an uppercase letter followed by lowercase letters."
    )
    username_regex = RegexValidator(
        regex=r'^[a-zA-Z][a-zA-Z0-9]{5,149}$',
        message="Username must begin with a letter followed by letters or digits and have a length of at least 6 "
                "characters and a maximum of 150 characters. "
    )
    username = forms.CharField(validators=[username_regex], min_length=5, max_length=150)
    email = forms.EmailField(validators=[EmailValidator],
                             error_messages={'invalid': 'Please enter a valid email address.'})
    first_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150)
    last_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150)
    password = PasswordField()
    confirm_password = PasswordConfirmationField(confirm_with='password')
    #password = forms.CharField(widget=forms.PasswordInput, validators=[password_regex], min_length=8)
    #confirm_password = forms.CharField(widget=forms.PasswordInput)

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("password2")
        print(password)
        score = zxcvbn(password, confirm_password)['score']
        if score <= 2:
            self.add_error("password", "Passwords do not match.")
        elif score == 3:
            self.add_error("password", "Passwords do not match.")

        if password and confirm_password and password != confirm_password:
            self.add_error("confirm_password", "Passwords do not match.")
</code>```

I don't know what's happening and why it doesn't get the good password

```<code>{% load static %}
<!DOCTYPE html>
{% autoescape on %}
<html>
<head>
  <title>SIGN UP</title>
  <link rel="stylesheet" href="{% static 'css/signup.css' %}">
</head>
<body>
  <h1>SIGN UP</h1>
  <form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
    <h3> If you already have an account sign in</h3>
    <button type="button"><a href='signin'>Sign In</a></button>
  </form>
</body>
</html>
{% endautoescape %}
</code>```

And the error

```<code>Traceback (most recent call last):
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
    return self.application(environ, start_response)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\wsgi.py", line 131, in __call__
    response = self.get_response(request)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 140, in get_response
    response = self._middleware_chain(request)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
    response = response_for_exception(request, exc)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
    response = handle_uncaught_exception(
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 181, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django_extensions\management\technical_response.py", line 40, in null_technical_500_response
    raise exc_value.with_traceback(tb)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User.DESKTOP-TJSM0H2\git\agenda_project\agenda\views.py", line 41, in signup
    print(form)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\utils.py", line 67, in render
    context = context or self.get_context()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 326, in get_context
    top_errors = self.non_field_errors().copy()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 362, in non_field_errors
    return self.errors.get(
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 200, in errors
    self.full_clean()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 438, in full_clean
    self._clean_form()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 459, in _clean_form
    cleaned_data = self.clean()
  File "C:\Users\User.DESKTOP-TJSM0H2\git\agenda_project\agenda\forms.py", line 55, in clean
    score = zxcvbn(password, confirm_password)['score']
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\zxcvbn\__init__.py", line 27, in zxcvbn
    matches = matching.omnimatch(password, ranked_dictionaries)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\zxcvbn\matching.py", line 90, in omnimatch
    matches.extend(matcher(password, _ranked_dictionaries=_ranked_dictionaries))
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\zxcvbn\matching.py", line 98, in dictionary_match
    length = len(password)
TypeError: object of type 'NoneType' has no len()
</code>```

Body:
I tried this code with the library django-zxcvbn-password when i do it without using this library everything work but when i use this library it seems like when i write a weak password the password field doesn't receive it and that lead to a NoneType Object because password is empty, and i don't know why but when i try it with a good password everything works perfectly.

I use this library for security purpose.

class SignUpForm(forms.Form)

    """password_regex = RegexValidator(
        regex=r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$',
        message="Password must be at least 8 characters in length and contain at least one uppercase letter, "
                "one lowercase letter, and one digit. "
    )"""

    name_regex = RegexValidator(
        regex=r'^[A-Z][a-z]{2,149}$',
        message="Names must begin with an uppercase letter followed by lowercase letters."
    )
    username_regex = RegexValidator(
        regex=r'^[a-zA-Z][a-zA-Z0-9]{5,149}$',
        message="Username must begin with a letter followed by letters or digits and have a length of at least 6 "
                "characters and a maximum of 150 characters. "
    )
    username = forms.CharField(validators=[username_regex], min_length=5, max_length=150)
    email = forms.EmailField(validators=[EmailValidator],
                             error_messages={'invalid': 'Please enter a valid email address.'})
    first_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150)
    last_name = forms.CharField(validators=[name_regex], min_length=2, max_length=150)
    password = PasswordField()
    confirm_password = PasswordConfirmationField(confirm_with='password')
    #password = forms.CharField(widget=forms.PasswordInput, validators=[password_regex], min_length=8)
    #confirm_password = forms.CharField(widget=forms.PasswordInput)

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get("password")
        confirm_password = cleaned_data.get("password2")
        print(password)
        score = zxcvbn(password, confirm_password)['score']
        if score <= 2:
            self.add_error("password", "Passwords do not match.")
        elif score == 3:
            self.add_error("password", "Passwords do not match.")

        if password and confirm_password and password != confirm_password:
            self.add_error("confirm_password", "Passwords do not match.")

I don't know what's happening and why it doesn't get the good password

{% load static %}
<!DOCTYPE html>
{% autoescape on %}

  <title>SIGN UP</title>
  <link rel="stylesheet" href="{% static 'css/signup.css' %}">

SIGN UP

  <form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">

 If you already have an account sign in

    <button type="button">Sign In</button>
  </form>

{% endautoescape %}

And the error

Traceback (most recent call last):
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\handlers.py", line 80, in __call__
    return self.application(environ, start_response)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\wsgi.py", line 131, in __call__
    response = self.get_response(request)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 140, in get_response
    response = self._middleware_chain(request)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 57, in inner
    response = response_for_exception(request, exc)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 140, in response_for_exception
    response = handle_uncaught_exception(
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 181, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django_extensions\management\technical_response.py", line 40, in null_technical_500_response
    raise exc_value.with_traceback(tb)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\User.DESKTOP-TJSM0H2\git\agenda_project\agenda\views.py", line 41, in signup
    print(form)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\utils.py", line 67, in render
    context = context or self.get_context()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 326, in get_context
    top_errors = self.non_field_errors().copy()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 362, in non_field_errors
    return self.errors.get(
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 200, in errors
    self.full_clean()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 438, in full_clean
    self._clean_form()
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\django\forms\forms.py", line 459, in _clean_form
    cleaned_data = self.clean()
  File "C:\Users\User.DESKTOP-TJSM0H2\git\agenda_project\agenda\forms.py", line 55, in clean
    score = zxcvbn(password, confirm_password)['score']
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\zxcvbn\__init__.py", line 27, in zxcvbn
    matches = matching.omnimatch(password, ranked_dictionaries)
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\zxcvbn\matching.py", line 90, in omnimatch
    matches.extend(matcher(password, _ranked_dictionaries=_ranked_dictionaries))
  File "C:\Users\User.DESKTOP-TJSM0H2\AppData\Local\Programs\Python\Python310\lib\site-packages\zxcvbn\matching.py", line 98, in dictionary_match
    length = len(password)
TypeError: object of type 'NoneType' has no len()


问:
How can I use SSH to rsync an attached external volume on a Mac server?
I've got several servers (mac, linux, etc).. The Mac has an external HDD attached to it (yeah, Mac - you can no longer add internal drives, because only pro's would want that, and we can't allow pros to use Mac, because we're special!)...
Anyway. so the attached volume - let's call it "Bob"
it's on /dev/disk5s1/
or it's on /Volumes/Bob/

Now my linux servers need to access Bob.
I've already shared public keys from the linux box, so my linux server can ssh into the Mac, and can access its internal drives without passwords, etc..  the linux can fully access internal drives on the Mac..

so I have chrons doing standard backups - like rsync -a  macsucks@10.1.12.122:/Library/Datastuff/Backups/....
These auto chrons are wonderful and they prevent me from having to touch a mouse on the mac.

However, I'm unsure of how to get to Bob, and pull/push data to Bob. Because Bob is special.

So, if, say:  ls -lh macksucks@10.1.12.122/.....  I can get to the internal HDD, but can't get to the external drive, becuase it's mounted on /, not mounted on the macsucks user.

so if i'm ssh'd into the linux box, and tell it to do that (ls -lh ....), no matter how I try, i get a response of: "No such file or directory"...

HOW can I touch this external drive using ssh for doing remote data access?

thanks!

I don't know how to mount or call Bob, to get it to show up externally..
kinda lost..


问:
How to change dependency versions accepted in package
I have an expo project using rn-pdf-reader-js with what is below (in package-lock.json)

```<code>"node_modules/rn-pdf-reader-js": {
  "version": "4.1.1",
  "resolved": "https://registry.npmjs.org/rn-pdf-reader-js/-/rn-pdf-reader-js-4.1.1.tgz",
  "integrity": "sha512-KnBzB1wfHPdE/Qb6oMmX0/iAD60tp+kf0TZaHw6tb0ULrdSvaG5rspTJArUEA724qYFwuVG1U2B0WTK8inpe1Q==",
  "dependencies": {
    "buffer": "5.1.0",
    "csstype": "2.6.8",
    "js-base64": "2.4.5"
  },
  "peerDependencies": {
    "expo": ">= 33.0.x < 37.0.x",
    "expo-constants": ">= 5.0.0 < 9.x",
    "expo-file-system": ">= 5.0.0 < 9.x",
    "react": "16.x",
    "react-native": "*",
    "react-native-webview": ">= 7.0.5 < 8.x"
  }
},
</code>```

However I am using expo version 47.0.9

So, I was wondering if I can just edit the peerDependencies for rn-pdf-reader-js to be "expo": ">= 33.0.x < 50.0.x" instead of "expo": ">= 33.0.x < 37.0.x"

I ask because everytime I would install any other dependency I would get an error saying rn-pdf-reader-js is not compatible and then I would have to install with --legacy-peer-deps. This works fine in the expo-go app (the app runs normally) and although the package rn-pdf-reader-js is supposedly outdated I don't see any issues.

However now I cannot build my project because that runs npm install which throws the error

```<code>Cannot read properties of null (reading 'children')
</code>```

Is this the correct approach to fixing the issue and not having to use --legacy-peer-deps for everything?

Body:
I have an expo project using rn-pdf-reader-js with what is below (in package-lock.json)

"node_modules/rn-pdf-reader-js": {
  "version": "4.1.1",
  "resolved": "https://registry.npmjs.org/rn-pdf-reader-js/-/rn-pdf-reader-js-4.1.1.tgz",
  "integrity": "sha512-KnBzB1wfHPdE/Qb6oMmX0/iAD60tp+kf0TZaHw6tb0ULrdSvaG5rspTJArUEA724qYFwuVG1U2B0WTK8inpe1Q==",
  "dependencies": {
    "buffer": "5.1.0",
    "csstype": "2.6.8",
    "js-base64": "2.4.5"
  },
  "peerDependencies": {
    "expo": ">= 33.0.x < 37.0.x",
    "expo-constants": ">= 5.0.0 < 9.x",
    "expo-file-system": ">= 5.0.0 < 9.x",
    "react": "16.x",
    "react-native": "*",
    "react-native-webview": ">= 7.0.5 < 8.x"
  }
},

However I am using expo version 47.0.9

So, I was wondering if I can just edit the peerDependencies for rn-pdf-reader-js to be "expo": ">= 33.0.x < 50.0.x" instead of "expo": ">= 33.0.x < 37.0.x"

I ask because everytime I would install any other dependency I would get an error saying rn-pdf-reader-js is not compatible and then I would have to install with --legacy-peer-deps. This works fine in the expo-go app (the app runs normally) and although the package rn-pdf-reader-js is supposedly outdated I don't see any issues.

However now I cannot build my project because that runs npm install which throws the error

Cannot read properties of null (reading 'children')

Is this the correct approach to fixing the issue and not having to use --legacy-peer-deps for everything?


问:
How does one mask neurons in Masked Autoencoders?
I learned about Masked AutoEncoders in this course and am now trying to code it. I am following Kaparthy's implementation over here.

I am unable to understand what's going on in the following lines -

```<code>    # sample the order of the inputs and the connectivity of all neurons
    self.m[-1] = np.arange(self.nin) if self.natural_ordering else rng.permutation(self.nin)
    for l in range(L):
        self.m[l] = rng.randint(self.m[l-1].min(), self.nin-1, size=self.hidden_sizes[l])

    # construct the mask matrices
    masks = [self.m[l-1][:,None] <= self.m[l][None,:] for l in range(L)]
    masks.append(self.m[L-1][:,None] < self.m[-1][None,:])
</code>```

I understand the concept of the paper though. Basically, each output should only be conditioned on its corresponding or prior input. That means output y_1 should depend on x_1, y_2 should depend on x_1 and x_2.

Body:
I learned about Masked AutoEncoders in this course and am now trying to code it. I am following Kaparthy's implementation over here.

I am unable to understand what's going on in the following lines -

    # sample the order of the inputs and the connectivity of all neurons
    self.m[-1] = np.arange(self.nin) if self.natural_ordering else rng.permutation(self.nin)
    for l in range(L):
        self.m[l] = rng.randint(self.m[l-1].min(), self.nin-1, size=self.hidden_sizes[l])

    # construct the mask matrices
    masks = [self.m[l-1][:,None] <= self.m[l][None,:] for l in range(L)]
    masks.append(self.m[L-1][:,None] < self.m[-1][None,:])

I understand the concept of the paper though. Basically, each output should only be conditioned on its corresponding or prior input. That means output y_1 should depend on x_1, y_2 should depend on x_1 and x_2.


问:
Hide button for In-app Review after a successful review in Android Studio
I followed this guide to create an in-app review button for my android application in android studio (https://developer.android.com/guide/playcore/in-app-review) everything works correctly, the button is displayed and you can review it.

The issue is that after having successfully completed the review the button is still displayed without any sense, what I want is that if and when the user has placed a review the button simply disappears, but while it does not continue to be displayed, could you help me please.

```<code>    void startReviewFlow()
{
    if(reviewInfo !=null)
    {
        Task<Void> flow = manager.launchReviewFlow(this,reviewInfo);
        flow.addOnCompleteListener(task -> {

            Toast.makeText(this, "¡Gracias, review completada!", Toast.LENGTH_SHORT).show();

        });
    }
}
</code>```

Thanks

Body:
I followed this guide to create an in-app review button for my android application in android studio (https://developer.android.com/guide/playcore/in-app-review) everything works correctly, the button is displayed and you can review it.

The issue is that after having successfully completed the review the button is still displayed without any sense, what I want is that if and when the user has placed a review the button simply disappears, but while it does not continue to be displayed, could you help me please.

    void startReviewFlow()
{
    if(reviewInfo !=null)
    {
        Task<Void> flow = manager.launchReviewFlow(this,reviewInfo);
        flow.addOnCompleteListener(task -> {

            Toast.makeText(this, "¡Gracias, review completada!", Toast.LENGTH_SHORT).show();

        });
    }
}

Thanks


问:
Assembly _start function for Windows 10+
I am trying to make a Compiler and I don't know how to make _start function for windows.
Compiler compiles successfully but only for linux, for windows it waits 2 s and exits.

I've tried

```<code>.globl _WinMain@16
_WinMain@16:
  ; Code here
</code>```

Body:
I am trying to make a Compiler and I don't know how to make _start function for windows.
Compiler compiles successfully but only for linux, for windows it waits 2 s and exits.

I've tried

.globl _WinMain@16
_WinMain@16:
  ; Code here


问:
How to wait for Streambuilder to return a value before coming off a loading screen

Question

I have an app that loads a list of habits as a Stream from Firestore, and I want the app to show a loading screen until habit loading has completed, and then show the list if there is one. Is there a way to keep a loading screen showing until we've either finished loading the first value in the stream or determined there won't be one?

The issue I'm having is that while my app is showing the loading screen, it briefly loads with a "no habits found" view before switching to show the list of habits.

Setup

This view uses three components:

I have a model-view-viewmodel architecture based on the Stacked Package.

(1) My view is a ViewModelBuilder widget with a StreamBuilder inside it. It looks at a (2) DailyViewModel, where the relevant components are an isBusy boolean property and a Stream<List<HabitCompletionViewModel> property that the view's StreamBuilder looks at to display the habits. The habits are loaded from Firestore via a FirestoreHabitService (this is an asynchronous call - will be described in a minute).

The View works as follows:

If DailyViewModel.isBusy is true, show a Loading... text.

If isBusy is false, it will show a Stream of Habits, or the text "No Habits Found" if the stream is not returning any habits (either snapshot.hasData is false, or data.length is less than 1).

```<code>
  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder.reactive(
      viewModelBuilder: () => vm,
      disposeViewModel: false,
      builder: (context, DailyViewModel vm, child) => vm.isBusy
          ? Center(child: Text('Loading...'))
          : SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                      'BaseDate of ${DateFormat.yMd().format(vm.week.baseDate)}'),
                  Text(
                      'Week ${DateFormat.yMd().format(vm.week.beginningOfWeek)} - ${DateFormat.yMd().format(vm.week.endOfWeek)}'),
                  SizedBox(height: 20),
                  Row(
                    children: [
                      Flexible(
                        child: Text('Today',
                            style: Theme.of(context).textTheme.headline6),
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.all(2)),
                  StreamBuilder<List<HabitCompletionViewModel>>(
                      stream: vm.todaysHabits,
                      builder: ((context, snapshot) {
                        if (snapshot.hasData == false ||
                            snapshot.data == null ||
                            snapshot.data!.length < 1) {
                          return Center(child: Text('No Habits Found'));
                        } else {
                          return Column(children: [
                            ListView.builder(
                              scrollDirection: Axis.vertical,
                              shrinkWrap: true,
                              itemCount: snapshot.data!.length,
                              itemBuilder: (context, i) => HabitCompletionTile(
                                key: ValueKey(snapshot.data![i].habit.id),
                                vm: snapshot.data![i],
                              ),
                            ),
                          ]);
                        }
                      })),
                  SizedBox(height: 40),
                  TextButton(
                    child: Text('Create a New Habit'),
                    onPressed: () => vm.navigateToCreateHabitPage(),
                  ),
                ],
              ),
            ),
    );
  }
}
</code>```

Process of Loading the Data

My loading happens as follows:

The ViewModel is initialized, and setBusy is set to true.

```<code>  DailyViewModel({required WeekDates week}) {
    setBusy(true);
    _log.v('initializing the daily viewmodel');
    pageSubtitle =
        'Week of ${week.startWeekday.title} ${DateFormat.Md().format(week.beginningOfWeek)}';
    _log.v('page subtitle is $pageSubtitle');

    mainAsyncCode();
}
</code>```

Then it starts this mainAsyncCode() method, which gets a stream of habits from the FirestoreHabitService (this returns a Future<Stream<List<Habit>>> because there is a potential modification function performed on the habits before returning them), and once that is completed, transforms that stream into a Stream<List<HabitCompletionViewModel>>, and then sets isBusy on the ViewModel to false.

```<code>  void mainAsyncCode() async {
    _myHabits = await _habitService.loadActiveHabitsByUserFuture(_loginAndUserService.loggedInUser!.id!);

    todaysHabits = _myHabits!.transform(currentViewModelCompletion);
    await Future.delayed(Duration(seconds: 5));
    setBusy(false);
  }
</code>```

Issue

The problem is that there is a temporary delay where the screen goes from "Loading..." to "No Habits Found" before it shows the list of Habits. I want it to wait on "Loading" until the stream list has been published, but I can't think of a way to do that.

Are there any options for doing this that others are aware of?

Body:
Question

I have an app that loads a list of habits as a Stream from Firestore, and I want the app to show a loading screen until habit loading has completed, and then show the list if there is one. Is there a way to keep a loading screen showing until we've either finished loading the first value in the stream or determined there won't be one?

The issue I'm having is that while my app is showing the loading screen, it briefly loads with a "no habits found" view before switching to show the list of habits.

Setup

This view uses three components:

I have a model-view-viewmodel architecture based on the Stacked Package.

(1) My view is a ViewModelBuilder widget with a StreamBuilder inside it. It looks at a (2) DailyViewModel, where the relevant components are an isBusy boolean property and a Stream<List<HabitCompletionViewModel> property that the view's StreamBuilder looks at to display the habits. The habits are loaded from Firestore via a FirestoreHabitService (this is an asynchronous call - will be described in a minute).

The View works as follows:

If DailyViewModel.isBusy is true, show a Loading... text.

If isBusy is false, it will show a Stream of Habits, or the text "No Habits Found" if the stream is not returning any habits (either snapshot.hasData is false, or data.length is less than 1).

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder.reactive(
      viewModelBuilder: () => vm,
      disposeViewModel: false,
      builder: (context, DailyViewModel vm, child) => vm.isBusy
          ? Center(child: Text('Loading...'))
          : SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                      'BaseDate of ${DateFormat.yMd().format(vm.week.baseDate)}'),
                  Text(
                      'Week ${DateFormat.yMd().format(vm.week.beginningOfWeek)} - ${DateFormat.yMd().format(vm.week.endOfWeek)}'),
                  SizedBox(height: 20),
                  Row(
                    children: [
                      Flexible(
                        child: Text('Today',
                            style: Theme.of(context).textTheme.headline6),
                      ),
                    ],
                  ),
                  const Padding(padding: EdgeInsets.all(2)),
                  StreamBuilder<List<HabitCompletionViewModel>>(
                      stream: vm.todaysHabits,
                      builder: ((context, snapshot) {
                        if (snapshot.hasData == false ||
                            snapshot.data == null ||
                            snapshot.data!.length < 1) {
                          return Center(child: Text('No Habits Found'));
                        } else {
                          return Column(children: [
                            ListView.builder(
                              scrollDirection: Axis.vertical,
                              shrinkWrap: true,
                              itemCount: snapshot.data!.length,
                              itemBuilder: (context, i) => HabitCompletionTile(
                                key: ValueKey(snapshot.data![i].habit.id),
                                vm: snapshot.data![i],
                              ),
                            ),
                          ]);
                        }
                      })),
                  SizedBox(height: 40),
                  TextButton(
                    child: Text('Create a New Habit'),
                    onPressed: () => vm.navigateToCreateHabitPage(),
                  ),
                ],
              ),
            ),
    );
  }
}

Process of Loading the Data

My loading happens as follows:

The ViewModel is initialized, and setBusy is set to true.

  DailyViewModel({required WeekDates week}) {
    setBusy(true);
    _log.v('initializing the daily viewmodel');
    pageSubtitle =
        'Week of ${week.startWeekday.title} ${DateFormat.Md().format(week.beginningOfWeek)}';
    _log.v('page subtitle is $pageSubtitle');

    mainAsyncCode();
}

Then it starts this mainAsyncCode() method, which gets a stream of habits from the FirestoreHabitService (this returns a Future<Stream<List<Habit>>> because there is a potential modification function performed on the habits before returning them), and once that is completed, transforms that stream into a Stream<List<HabitCompletionViewModel>>, and then sets isBusy on the ViewModel to false.

  void mainAsyncCode() async {
    _myHabits = await _habitService.loadActiveHabitsByUserFuture(_loginAndUserService.loggedInUser!.id!);

    todaysHabits = _myHabits!.transform(currentViewModelCompletion);
    await Future.delayed(Duration(seconds: 5));
    setBusy(false);
  }

Issue

The problem is that there is a temporary delay where the screen goes from "Loading..." to "No Habits Found" before it shows the list of Habits. I want it to wait on "Loading" until the stream list has been published, but I can't think of a way to do that.

Are there any options for doing this that others are aware of?


问:
How can I live stream video to a website without using any third party video host?
I want to live stream on a website without using any third party video host like Youtube, Vimeo and the like.

I want to do it by directly coding it using standard open web technologies. How should I proceed?


问:
When I try to redirect to an external URL to get data from it and send it to the client, I get a CORS error (client:ReactJS, server:ExpressJS)
I made a button in React that sends a GET method request to the server, redirects to an external URL to get data from it  and send it to the client. But I get a CORS error. But when I use the Chrome CORS extension (Allow CORS: Access-Control-Allow-Origin), I receive data.

When I use Chrome extension(Allow CORS: Access-Control-Allow-Origin).I get data in console

```<code>Object
config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
data: "<!doctype html><html itemscope=\"\" itemtype=\"ht
headers: AxiosHeaders {cache-control: 'private, max-age=0', content-length: '48373', content-type: 'text/html; charset=UTF-8', expires: '-1'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""
</code>```

Server
App.js

```<code>const express = require("express");
const app = express();
const cors = require("cors");

const authRoute = require("./routes/redirect");

app.use(express.json(), cors());
app.use("/api/redirect", authRoute);
</code>```

redirect.js

```<code>router.get("/", (req, res) => {
  res.status(301).redirect("https://www.google.com");
});
</code>```

Client

```<code> const handleRedirect = (id) => {
    axios
      .get(`http://localhost:4000/api/redirect`)
      .then((res) => {
        console.log(res);
      });
  };
</code>```

Error

Access to XMLHttpRequest at 'https://www.google.com/' (redirected from 'http://localhost:4000/api/redirect') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I expect to get data from that redirected external URL.

Body:
I made a button in React that sends a GET method request to the server, redirects to an external URL to get data from it  and send it to the client. But I get a CORS error. But when I use the Chrome CORS extension (Allow CORS: Access-Control-Allow-Origin), I receive data.

When I use Chrome extension(Allow CORS: Access-Control-Allow-Origin).I get data in console

Object
config : {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
data: "<!doctype html><html itemscope=\"\" itemtype=\"ht
headers: AxiosHeaders {cache-control: 'private, max-age=0', content-length: '48373', content-type: 'text/html; charset=UTF-8', expires: '-1'}
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
status: 200
statusText: ""

Server
App.js

const express = require("express");
const app = express();
const cors = require("cors");

const authRoute = require("./routes/redirect");

app.use(express.json(), cors());
app.use("/api/redirect", authRoute);

redirect.js

router.get("/", (req, res) => {
  res.status(301).redirect("https://www.google.com");
});

Client

 const handleRedirect = (id) => {
    axios
      .get(`http://localhost:4000/api/redirect`)
      .then((res) => {
        console.log(res);
      });
  };

Error

Access to XMLHttpRequest at 'https://www.google.com/' (redirected from 'http://localhost:4000/api/redirect') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I expect to get data from that redirected external URL.


问:
Loss does not change during training of my model
I want to predict a time series using cnn-lstm model.This is my model:

```<code>def generate_model():
 model = keras.models.Sequential([

  Conv1D(64, 3, padding='causal', activation='relu', input_shape=(24, 20)),
  BatchNormalization(),
  Conv1D(64, 3, padding='causal', activation='relu'),
  BatchNormalization(),
  Conv1D(32, 3, padding='causal', activation='relu'),
  MaxPool1D(3),
  LSTM(100, dropout=0.2, return_sequences=True),
  LSTM(50, dropout=0.3),
  Dense(1, activation='relu')
 ])

 model.compile(optimizer=tf.keras.optimizers.Adam(),
            loss='mean_squared_error',
            metrics=[tf.keras.metrics.MeanAbsoluteError(),  tf.keras.metrics.RootMeanSquaredError(), RSquare()])

  return model
</code>```

Then I use this line of code to train my model:

```<code>history1 = model1.fit(X1_train, y1_train, epochs=200, batch_size=32, validation_data=(X1_test, y1_test), verbose=2, callbacks=callbacks)
</code>```

But values of loss and metrics stays the same and does not change. This is how they look.

These are my callbacks, just in case:

```<code>from keras.callbacks import LearningRateScheduler

def decay_schedule(epoch, lr):

lr = lr - 0.0001
return lr

lr_scheduler = LearningRateScheduler(decay_schedule)

callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='max', min_delta=1e-3, patience=50)

callbacks=[lr_scheduler, callback]
</code>```

Thank you in advance.

Body:
I want to predict a time series using cnn-lstm model.This is my model:

def generate_model():
 model = keras.models.Sequential([

  Conv1D(64, 3, padding='causal', activation='relu', input_shape=(24, 20)),
  BatchNormalization(),
  Conv1D(64, 3, padding='causal', activation='relu'),
  BatchNormalization(),
  Conv1D(32, 3, padding='causal', activation='relu'),
  MaxPool1D(3),
  LSTM(100, dropout=0.2, return_sequences=True),
  LSTM(50, dropout=0.3),
  Dense(1, activation='relu')
 ])

 model.compile(optimizer=tf.keras.optimizers.Adam(),
            loss='mean_squared_error',
            metrics=[tf.keras.metrics.MeanAbsoluteError(),  tf.keras.metrics.RootMeanSquaredError(), RSquare()])

  return model

Then I use this line of code to train my model:

history1 = model1.fit(X1_train, y1_train, epochs=200, batch_size=32, validation_data=(X1_test, y1_test), verbose=2, callbacks=callbacks)

But values of loss and metrics stays the same and does not change. This is how they look.

These are my callbacks, just in case:

from keras.callbacks import LearningRateScheduler

def decay_schedule(epoch, lr):

lr = lr - 0.0001
return lr

lr_scheduler = LearningRateScheduler(decay_schedule)

callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='max', min_delta=1e-3, patience=50)

callbacks=[lr_scheduler, callback]

Thank you in advance.


问:
MySQL: CONVERT_TZ function is not working with field value as argument
I'm working on an app that involves users (teachers) making scheduled lessons. As users of the app could potentially be from around the world the user table has a 'timezone' field, with a default value of 'Australia/Victoria'. The lesson table has a 'starttime' field, which records a DATETIME for the start of a lesson in UTC time. The creator of a lesson is identified by an 'ownerId' field, which refers to an id in the user table.
Now, what I want to do is convert the UTC starttime to the user's timezone as part of a select query.

If I run this:

SELECT l.starttime, u.timezone, CONVERT_TZ(l.starttime,"UTC",u.timezone) AS userstart FROM lesson l JOIN user u ON l.ownerId = u.id

I get a result of:

2022-09-29 09:05:00 | Australia/Victoria | NULL

Yet if i change the third argument of the CONVERT_TZ function call to a string literal like so:

SELECT l.starttime, u.timezone, CONVERT_TZ(l.starttime,"UTC","Australia/Victoria") AS userstart FROM lesson l JOIN user u ON l.ownerId = u.id

I get this:

2022-09-29 09:05:00 | Australia/Victoria | 2022-09-29 19:05:00

Why would this be?


问:
which is the right syntaxis of TIMEsTAMPDIFF in ASP.NET CORE?
I'm trying to translate aproject from SqlServer to MySql and having problems with the query

```<code>var r = await _context.Rankings
             .Include(x => x.Perfil)
             .Include(x => x.Juego)
             .Include(x => x.Categoria)
             .Where(x => TIMESTAMPDIFF(YEAR, DateTime.Now, x.Fecha) == 0)
             .ToListAsync();
</code>```

the compiler does not accpt the statement neither
accepts DBFuncions.TIMESTAMPDIFF

I'm using POMELO.EntityFrameworkCore.MySql for connecting to database

Which is the rigth syntaxis for the statement?

Body:
I'm trying to translate aproject from SqlServer to MySql and having problems with the query

var r = await _context.Rankings
             .Include(x => x.Perfil)
             .Include(x => x.Juego)
             .Include(x => x.Categoria)
             .Where(x => TIMESTAMPDIFF(YEAR, DateTime.Now, x.Fecha) == 0)
             .ToListAsync();

the compiler does not accpt the statement neither
accepts DBFuncions.TIMESTAMPDIFF

I'm using POMELO.EntityFrameworkCore.MySql for connecting to database

Which is the rigth syntaxis for the statement?


问:
Accessing environment variables securely client-side in Next.js (for FullCalendar)
I am using FullCalendar in a Next.js project. I specifically am trying to feed it events from a public Google Calendar (see documentation here). My problem is that linking FullCalendar to the Google Calendar API requires use of an API key, and I cannot figure out how to let the component access the API key secretly, since I cannot access .env.local variables client-side.

I know that, in general, you can make API routes that keep your API keys secret - but I'm not sure how/if that helps, since FullCalendar fetches from the Google Calendar API with its own logic.

I know you can also access API keys via the next.config.js, or in the .env.local if written with NEXT_PUBLIC_..., but if I understand correctly, then that will leave those keys exposed.

The following code correctly renders events from the public Google calendar:

```<code><FullCalendar
        eventContent={(arg) => {
          return (
            <Tooltip title={arg.event.extendedProps.description} arrow>
              {renderInnerContent(arg)}
            </Tooltip>
          );
        }}
        headerToolbar={{
          start: "title",
          center: "dayGridMonth,listMonth",
          end: "today prev,next",
        }}
        plugins={[dayGridPlugin, list, googleCalendarPlugin]}
        initialView="listMonth"
        eventDisplay="block"
        weekends={false}
        googleCalendarApiKey="exposedApiKey" // sample API key
        eventSources={[
          {
            googleCalendarId:
              "sampleCalendar@group.calendar.google.com", // sample calendar address
          },
        ]}
/>
</code>```

Thanks in advance.

Body:
I am using FullCalendar in a Next.js project. I specifically am trying to feed it events from a public Google Calendar (see documentation here). My problem is that linking FullCalendar to the Google Calendar API requires use of an API key, and I cannot figure out how to let the component access the API key secretly, since I cannot access .env.local variables client-side.

I know that, in general, you can make API routes that keep your API keys secret - but I'm not sure how/if that helps, since FullCalendar fetches from the Google Calendar API with its own logic.

I know you can also access API keys via the next.config.js, or in the .env.local if written with NEXT_PUBLIC_..., but if I understand correctly, then that will leave those keys exposed.

The following code correctly renders events from the public Google calendar:

<FullCalendar
        eventContent={(arg) => {
          return (
            <Tooltip title={arg.event.extendedProps.description} arrow>
              {renderInnerContent(arg)}
            </Tooltip>
          );
        }}
        headerToolbar={{
          start: "title",
          center: "dayGridMonth,listMonth",
          end: "today prev,next",
        }}
        plugins={[dayGridPlugin, list, googleCalendarPlugin]}
        initialView="listMonth"
        eventDisplay="block"
        weekends={false}
        googleCalendarApiKey="exposedApiKey" // sample API key
        eventSources={[
          {
            googleCalendarId:
              "sampleCalendar@group.calendar.google.com", // sample calendar address
          },
        ]}
/>

Thanks in advance.


问:
streaming data/variables to templete using django
I have a method that returns float variables and I m streaming it to an HTML template using StreamingHttpResponse in Django, to catch the variable I found a way to use XMLHttpRequest in ajax as shown in the code below:

```<code>#method to return speed as a list of three float values
def gen_speed(video_feed):
    while True:
        speed, frame, gray, output = video_feed.get_frames()
        yield speed
</code>```
```<code>def speed_stream(request):
    try:
        pathVideo = r"static\app_resources\videos\rl4_pb8-7.mp4"
        cam = model.video_feed(pathVideo)
        stream = model.gen_speed(cam)
        response = StreamingHttpResponse(stream,
                                         status=200,
                                         content_type='text/event-stream')
        #response['Cache-Control'] = 'no-cache'
        return response
    except:
          pass

</code>```

this is code is in my HTML :

```<code><script>
url = '{% url "test_stream" %}';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("get", url, true);
xmlhttp.send();

function handleEvent(e) {

    console.log(e.target.responseText);

}

xmlhttp.addEventListener('progress',handleEvent);

}
<script>
</code>```

the results are like this  :

as you see the streaming is working but the problem is that I don't know how to handle the values in the template, the values that XMLHttpRequest catches are not separated.
what I want is a way to catch this dictionary and access to it so that I can give each value to a streaming chart each time.

Body:
I have a method that returns float variables and I m streaming it to an HTML template using StreamingHttpResponse in Django, to catch the variable I found a way to use XMLHttpRequest in ajax as shown in the code below:

#method to return speed as a list of three float values
def gen_speed(video_feed):
    while True:
        speed, frame, gray, output = video_feed.get_frames()
        yield speed

def speed_stream(request):
    try:
        pathVideo = r"static\app_resources\videos\rl4_pb8-7.mp4"
        cam = model.video_feed(pathVideo)
        stream = model.gen_speed(cam)
        response = StreamingHttpResponse(stream,
                                         status=200,
                                         content_type='text/event-stream')
        #response['Cache-Control'] = 'no-cache'
        return response
    except:
          pass

this is code is in my HTML :


问:
How to get an image from a DIV using html2canvas?
I have a React app with a UI of a Payment Receipt. I need to download the receipt as a pdf file. To make it a pdf, I have the jsPDF module. But, I need to send the relevant div, including the entire UI as an image, to the jsPDF module. I use the html2canvas module to make the image from the selected div as follows. The problem is, even though it shows the selected div in the console, it returns a blank image.

```<code>import { jsPDF } from "jspdf";
import html2canvas from 'html2canvas';
import React, { Component, createRef } from 'react';

class PaymentReceipt extends Component {
    constructor(props){
        super(props);
        this.receiptRef = createRef();
    }

    downloadReceipt = () => {
        const input = this.receiptRef.current;
        html2canvas(input)
        .then((canvas) => {
                console.log("input", input); // This shows the whole div correctly
                const imgData = canvas.toDataURL('image/jpeg');
                console.log("imgData", imgData); // This shows an empty image
                const pdf = new jsPDF();
                pdf.addImage(imgData, 'JPEG', 15, 40, 180, 160);
                pdf.save("receipt.pdf"); // So this downloads an empty image
            });
    }

    render() {
        return (
          <div>
               <div ref={this.receiptRef}> My Receipt UI goes here </div>
               <button onClick={this.downloadReceipt}>Download Receipt</button>
          </div>
        )
    }
}

export default PaymentReceipt;
</code>```

How can I solve this?

Body:
I have a React app with a UI of a Payment Receipt. I need to download the receipt as a pdf file. To make it a pdf, I have the jsPDF module. But, I need to send the relevant div, including the entire UI as an image, to the jsPDF module. I use the html2canvas module to make the image from the selected div as follows. The problem is, even though it shows the selected div in the console, it returns a blank image.

import { jsPDF } from "jspdf";
import html2canvas from 'html2canvas';
import React, { Component, createRef } from 'react';

class PaymentReceipt extends Component {
    constructor(props){
        super(props);
        this.receiptRef = createRef();
    }

    downloadReceipt = () => {
        const input = this.receiptRef.current;
        html2canvas(input)
        .then((canvas) => {
                console.log("input", input); // This shows the whole div correctly
                const imgData = canvas.toDataURL('image/jpeg');
                console.log("imgData", imgData); // This shows an empty image
                const pdf = new jsPDF();
                pdf.addImage(imgData, 'JPEG', 15, 40, 180, 160);
                pdf.save("receipt.pdf"); // So this downloads an empty image
            });
    }

    render() {
        return (

 My Receipt UI goes here

               <button onClick={this.downloadReceipt}>Download Receipt</button>

        )
    }
}

export default PaymentReceipt;

How can I solve this?


问:
yolov7 "remember" training images
I try to run yolov7 on a custom data.
From some reason it seems that the model remember images, even though that they are not in the train/ val images or in the train/val.txt files.
I had that error:
No such file or directory: 'runs/train/yolov7-w6-custom43/labels/0482cd2221a91d16fa1d1cd53d3be5ef_4_1.txt'

so I deletetd that image from all the data folders and txt file, ans it still looks for that image.
why?

Thanks

Title: yolov7 "remember" training images


问:
How do I show Data in React frontend properly from Django?

I am building an API with Django rest-framework. I expect the map function to return the chapters of the course but nothing was returned to the frontend. Although, I got a response from the API when I checked the network tab.
Here is my Course View in Django:

```<code>class CourseDetail(generics.RetrieveAPIView):
    queryset = models.Course.objects.all()
    serializer_class = CourseSerializer
</code>```

Here is the chapter model:

```<code>class Chapter(models.Model):
    course = models.ForeignKey(
        Course, on_delete=models.CASCADE, related_name='course_chapters')
    title = models.CharField(max_length=150)
    description = models.TextField()
    video = models.FileField(upload_to='chapter_videos/')
    remarks = models.TextField()

    class Meta:
        verbose_name_plural = "4. Chapters"

</code>```

Here is React component:

```<code> useEffect(()=>{
        let ignorePrev = false
            try{
              axios.get(baseUrlCourse+course_id)
              .then((res)=>{
                  if(!ignorePrev){
                      setCourseData(res.data);
                      setCourseChapter(res.data.course_chapter);
                      setCourseTeacher(res.data.teacher);
                  }
              })
          }catch(error){
              console.log(error)
          }
          return(()=>{
            ignorePrev = true;
          })

      },[])
</code>```

```<code>{courseChapter && courseChapter.map((chapter, index) =>
>
>
>                 <ul className='list-group list-group-flush'>
>
>                     <li key={index} className='list-group-item'>{chapter.title}</li> </ul>)}
</code>```

**The picture attached is the response I got
**
I have tried changing

```<code>generics.RetrieveAPIView)
</code>```

to :

```<code>generics.RetrieveUpdateDestroAPIView
</code>```

but it didn't work.

Body:
I am building an API with Django rest-framework. I expect the map function to return the chapters of the course but nothing was returned to the frontend. Although, I got a response from the API when I checked the network tab.
Here is my Course View in Django:

class CourseDetail(generics.RetrieveAPIView):
    queryset = models.Course.objects.all()
    serializer_class = CourseSerializer

Here is the chapter model:

class Chapter(models.Model):
    course = models.ForeignKey(
        Course, on_delete=models.CASCADE, related_name='course_chapters')
    title = models.CharField(max_length=150)
    description = models.TextField()
    video = models.FileField(upload_to='chapter_videos/')
    remarks = models.TextField()

    class Meta:
        verbose_name_plural = "4. Chapters"

Here is React component:

 useEffect(()=>{
        let ignorePrev = false
            try{
              axios.get(baseUrlCourse+course_id)
              .then((res)=>{
                  if(!ignorePrev){
                      setCourseData(res.data);
                      setCourseChapter(res.data.course_chapter);
                      setCourseTeacher(res.data.teacher);
                  }
              })
          }catch(error){
              console.log(error)
          }
          return(()=>{
            ignorePrev = true;
          })

      },[])

{courseChapter && courseChapter.map((chapter, index) =>
>
>
>

>
>
{chapter.title}

)}

**The picture attached is the response I got
**
I have tried changing

generics.RetrieveAPIView)

to :

generics.RetrieveUpdateDestroAPIView

but it didn't work.


问:
How can I deactivate loading spinner after href link opens?
I have a button that, when clicked, a loading spinner div is added:

HTML:

```<code><a class="button-solid" href="./appointments/" rel="noopener">
       Request Appointment
       <div class="lds-ring">
               <div></div>
               <div></div>
               <div></div>
               <div></div>
       </div>
</a>
</code>```

I have Javascript that adds a class "active" to lds-ring when the button is clicked. And CSS to make the spinner.

Javascript:

```<code>const buttons = document.querySelectorAll('.button-solid');

[...buttons].forEach(button => {
  button.addEventListener('click', (e) => {

    toggleLoadingSpinner(e);

  })
});

function toggleLoadingSpinner(e) {
  const loader = e.target.querySelector('.lds-ring');
  const loaderDivChildren = e.target.querySelectorAll('.lds-ring div');

  if (loader) {
    loader.classList.toggle('active');
    [...loaderDivChildren].forEach(child => child.classList.toggle('active'));
  }
}
</code>```

Adding the spinner works when the button is clicked. However, I run into the problem where on mobile, if I click the button then go back to the previous page, the spinner is still spinning. I'm assuming this is due to back/forward cache? Clicking the button leads to another page on my website.

My question is, whats the most logical way to turn the spinner off (i.e. remove the 'active' class on the button) after the button is clicked AND the target link is open? So that when I click the button then go back, the spinner won't still be spinning.

I'm looking into different things like page unload. Or, target page load / readyState. I spent a few hours messing around with visibilitychange event listeners until I realized it was for opening new tabs, not opening links/pages within the same tab. Not really sure how to approach this, any help is appreciated.

Body:
I have a button that, when clicked, a loading spinner div is added:

HTML:

       Request Appointment

I have Javascript that adds a class "active" to lds-ring when the button is clicked. And CSS to make the spinner.

Javascript:

const buttons = document.querySelectorAll('.button-solid');

[...buttons].forEach(button => {
  button.addEventListener('click', (e) => {

    toggleLoadingSpinner(e);

  })
});

function toggleLoadingSpinner(e) {
  const loader = e.target.querySelector('.lds-ring');
  const loaderDivChildren = e.target.querySelectorAll('.lds-ring div');

  if (loader) {
    loader.classList.toggle('active');
    [...loaderDivChildren].forEach(child => child.classList.toggle('active'));
  }
}

Adding the spinner works when the button is clicked. However, I run into the problem where on mobile, if I click the button then go back to the previous page, the spinner is still spinning. I'm assuming this is due to back/forward cache? Clicking the button leads to another page on my website.

My question is, whats the most logical way to turn the spinner off (i.e. remove the 'active' class on the button) after the button is clicked AND the target link is open? So that when I click the button then go back, the spinner won't still be spinning.

I'm looking into different things like page unload. Or, target page load / readyState. I spent a few hours messing around with visibilitychange event listeners until I realized it was for opening new tabs, not opening links/pages within the same tab. Not really sure how to approach this, any help is appreciated.


问:
Display currency formatted values in AG Charts
I am using Angular and I cannot display currency values in any AG chart.  I can successfully format the values to currency within the ag grid, they look fine and aggregation works, but when I try creating a chart the values revert back to the raw number.  I am using value formatter to convert to currency.  I have also used cell renderer to convert to currency, but neither will stay currency when generating a chart.  I have also tried converting the values to money in the sql query itself, but that seems to mess things up even more.</p>


问:
Qt - Stretch frame borders to be uniform in window
I'm having some trouble understanding how Qt assigns sizes to frames when there are several frames in a window in a grid pattern (using the grid layout). As you can see I have several frames but I want the smaller frames to extend horizontally (east and west) so that they are all almost touching each other and the window borders. I'm using the qt binding for Golang by the way, so my code below is Go but if anyone can offer any help using C++ or just an explanation of what I'm doing wrong it would be GREATLY appreciated.

What I want:
Written in Python

What I have:
Written in Go

This is my code for the first frame that is within my main frame (process_frame):

`

```<code>// Cancel Reason subframe
frame_cancel_reason := widgets.NewQFrame(nil, 0)
frame_cancel_reason.SetStyleSheet(FRAME_BORDER + colors["gold"])
frame_cancel_reason_layout := widgets.NewQGridLayout(frame_cancel_reason)
process_frame_layout.AddWidget2(frame_cancel_reason, 0, 0, core.Qt__AlignJustify)

label_cancel_reason := widgets.NewQLabel2("Please select a cancellation reason", frame_cancel_reason, 0)
label_cancel_reason.SetFont(FONT_MAIN_LABEL)
label_cancel_reason.SetStyleSheet(NO_FRAME_BORDER)
frame_cancel_reason_layout.AddWidget2(label_cancel_reason, 0, 0, core.Qt__AlignCenter)

cancel_reason_options := []string{"Lost Business (with removals)", "Lost Business (no removals)", "Store Closing"}
frame_cancel_reason_options := widgets.NewQFrame(nil, 0)
cancel_reason_otions_layout := widgets.NewQGridLayout(frame_cancel_reason_options)
frame_cancel_reason_options.SetLayout(cancel_reason_otions_layout)
frame_cancel_reason_options.SetStyleSheet(NO_FRAME_BORDER)
cancel_reason_group := widgets.NewQButtonGroup(nil)
for i, cancel_reason_option := range cancel_reason_options {
    r := widgets.NewQRadioButton2(cancel_reason_option, nil)
    r.SetFont(FONT_ITEM)
    r.SetStyleSheet(NO_FRAME_BORDER)
    cancel_reason_group.AddButton(r, i)
    cancel_reason_otions_layout.AddWidget2(r, i, 0, core.Qt__AlignLeading)
}
frame_cancel_reason_layout.AddWidget2(frame_cancel_reason_options, 1, 0, core.Qt__AlignCenter)
</code>```

`

I've gone through the Qt documentation, searched stackoverflow, and googled but can't seem to find an answer.

Update
So I came up with the following solution, but I'm thinking there has to be a more elegant way. Basically, what I did was grab each frame and manually resize it (by adjusting margins) based on the size of the main window:

```<code>// Sizing - So all frames are more uniform
new_frame_width := (process_frame.FrameGeometry().Width() / 2)
children := process_frame.FindChildren("", core.Qt__FindDirectChildrenOnly)
for _, child := range children {
    if child.MetaObject().ClassName() == "QFrame" {
        actual_child := widgets.NewQFrameFromPointer(child.Pointer())
        child_width := actual_child.FrameGeometry().Width()
        new_margin := (new_frame_width - child_width) / 2
        actual_child.SetContentsMargins(new_margin, 0, new_margin, 0)

    }
</code>```

Body:
I'm having some trouble understanding how Qt assigns sizes to frames when there are several frames in a window in a grid pattern (using the grid layout). As you can see I have several frames but I want the smaller frames to extend horizontally (east and west) so that they are all almost touching each other and the window borders. I'm using the qt binding for Golang by the way, so my code below is Go but if anyone can offer any help using C++ or just an explanation of what I'm doing wrong it would be GREATLY appreciated.

What I want:
Written in Python

What I have:
Written in Go

This is my code for the first frame that is within my main frame (process_frame):

`

// Cancel Reason subframe
frame_cancel_reason := widgets.NewQFrame(nil, 0)
frame_cancel_reason.SetStyleSheet(FRAME_BORDER + colors["gold"])
frame_cancel_reason_layout := widgets.NewQGridLayout(frame_cancel_reason)
process_frame_layout.AddWidget2(frame_cancel_reason, 0, 0, core.Qt__AlignJustify)

label_cancel_reason := widgets.NewQLabel2("Please select a cancellation reason", frame_cancel_reason, 0)
label_cancel_reason.SetFont(FONT_MAIN_LABEL)
label_cancel_reason.SetStyleSheet(NO_FRAME_BORDER)
frame_cancel_reason_layout.AddWidget2(label_cancel_reason, 0, 0, core.Qt__AlignCenter)

cancel_reason_options := []string{"Lost Business (with removals)", "Lost Business (no removals)", "Store Closing"}
frame_cancel_reason_options := widgets.NewQFrame(nil, 0)
cancel_reason_otions_layout := widgets.NewQGridLayout(frame_cancel_reason_options)
frame_cancel_reason_options.SetLayout(cancel_reason_otions_layout)
frame_cancel_reason_options.SetStyleSheet(NO_FRAME_BORDER)
cancel_reason_group := widgets.NewQButtonGroup(nil)
for i, cancel_reason_option := range cancel_reason_options {
    r := widgets.NewQRadioButton2(cancel_reason_option, nil)
    r.SetFont(FONT_ITEM)
    r.SetStyleSheet(NO_FRAME_BORDER)
    cancel_reason_group.AddButton(r, i)
    cancel_reason_otions_layout.AddWidget2(r, i, 0, core.Qt__AlignLeading)
}
frame_cancel_reason_layout.AddWidget2(frame_cancel_reason_options, 1, 0, core.Qt__AlignCenter)

`

I've gone through the Qt documentation, searched stackoverflow, and googled but can't seem to find an answer.

Update
So I came up with the following solution, but I'm thinking there has to be a more elegant way. Basically, what I did was grab each frame and manually resize it (by adjusting margins) based on the size of the main window:

// Sizing - So all frames are more uniform
new_frame_width := (process_frame.FrameGeometry().Width() / 2)
children := process_frame.FindChildren("", core.Qt__FindDirectChildrenOnly)
for _, child := range children {
    if child.MetaObject().ClassName() == "QFrame" {
        actual_child := widgets.NewQFrameFromPointer(child.Pointer())
        child_width := actual_child.FrameGeometry().Width()
        new_margin := (new_frame_width - child_width) / 2
        actual_child.SetContentsMargins(new_margin, 0, new_margin, 0)

    }


问:
Tkinter Pillow Resize Image Looks Choppy While Resizing
I have a frame that stores a label which stores a background image. When I resize the form and the frame resizes, the background image of the label looks really choppy while it's being resized by the function. I was thinking about putting the function on a separate thread because I believe the image might look choppy because of it being on the main thread.

Here's what I've tried:

```<code>from tkinter import Tk, Button, Label, Frame
from tkinter import ttk, PhotoImage
import threading
import time
from PIL import Image, ImageTk

class MainWindow(Tk):
    def __init__(self):
        super().__init__()

#create groupbox1 background image for modern look framing
    self.gb1_img = Image.open('imgs/groupbox-1.png')
    self.gb1_img = self.gb1_img.resize((260, 490), Image.Resampling.LANCZOS)
    self.gb1_img = ImageTk.PhotoImage(self.gb1_img)

    self.gb1_container = Frame(self, bg='#333333', width=280)
    self.gb1_container.pack(side='left', fill='y', padx=20, pady=(120, 20))
    self.gb1_container.bind('<Configure>', self.start_resize_gb1)

    self.gb1 = Label(self.gb1_container, image=self.gb1_img, bg='#333333')
    self.gb1.place(x=0, y=0)

def start_resize_gb1(self, e):
    t = threading.Thread(target=self.resize_gb1, args=(e,), daemon=1)
    t.start()

#resize groupbox1 frame image
    def resize_gb1(self, e):
        self.gb1_img1 = Image.open('imgs/groupbox-1.png')
        self.gb1_img1 = self.gb1_img1.resize((e.width, e.height), Image.Resampling.LANCZOS)
        self.gb1_img1 = ImageTk.PhotoImage(self.gb1_img1)
        self.gb1.configure(image=self.gb1_img1)

if __name__ == '__main__':
    app = MainWindow()
    app.title('Main Window')
    app.configure(bg='#333333')

    #center the Main Window:
    w = 1000  # Width
    h = 620  # Height

    app.geometry('%dx%d+%d+%d' % (w, h, x, y))
    app.mainloop()
</code>```

Is there a way that I can bind the function on it's own thread so that it doesn't look so choppy while resizing?

The error that I keep getting is:

```<code>Exception in thread Thread-57 (resize_gb1):
Traceback (most recent call last):
  File "C:\Users\Aaron\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Users\Aaron\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Aaron\Documents\Python\Project1\testing\MAIN.py", line 92, in resize_gb1
    self.gb1_img1 = ImageTk.PhotoImage(self.gb1_img1)
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\ImageTk.py", line 143, in __init__
    self.paste(image)
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\ImageTk.py", line 195, in paste
    im.load()
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\ImageFile.py", line 268, in load
    self.load_end()
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\PngImagePlugin.py", line 962, in load_end
    self.fp.read(4)  # CRC
AttributeError: 'NoneType' object has no attribute 'read'
</code>```

Body:
I have a frame that stores a label which stores a background image. When I resize the form and the frame resizes, the background image of the label looks really choppy while it's being resized by the function. I was thinking about putting the function on a separate thread because I believe the image might look choppy because of it being on the main thread.

Here's what I've tried:

from tkinter import Tk, Button, Label, Frame
from tkinter import ttk, PhotoImage
import threading
import time
from PIL import Image, ImageTk

class MainWindow(Tk):
    def __init__(self):
        super().__init__()

#create groupbox1 background image for modern look framing
    self.gb1_img = Image.open('imgs/groupbox-1.png')
    self.gb1_img = self.gb1_img.resize((260, 490), Image.Resampling.LANCZOS)
    self.gb1_img = ImageTk.PhotoImage(self.gb1_img)

    self.gb1_container = Frame(self, bg='#333333', width=280)
    self.gb1_container.pack(side='left', fill='y', padx=20, pady=(120, 20))
    self.gb1_container.bind('<Configure>', self.start_resize_gb1)

    self.gb1 = Label(self.gb1_container, image=self.gb1_img, bg='#333333')
    self.gb1.place(x=0, y=0)

def start_resize_gb1(self, e):
    t = threading.Thread(target=self.resize_gb1, args=(e,), daemon=1)
    t.start()

#resize groupbox1 frame image
    def resize_gb1(self, e):
        self.gb1_img1 = Image.open('imgs/groupbox-1.png')
        self.gb1_img1 = self.gb1_img1.resize((e.width, e.height), Image.Resampling.LANCZOS)
        self.gb1_img1 = ImageTk.PhotoImage(self.gb1_img1)
        self.gb1.configure(image=self.gb1_img1)

if __name__ == '__main__':
    app = MainWindow()
    app.title('Main Window')
    app.configure(bg='#333333')

    #center the Main Window:
    w = 1000  # Width
    h = 620  # Height

    app.geometry('%dx%d+%d+%d' % (w, h, x, y))
    app.mainloop()

Is there a way that I can bind the function on it's own thread so that it doesn't look so choppy while resizing?

The error that I keep getting is:

Exception in thread Thread-57 (resize_gb1):
Traceback (most recent call last):
  File "C:\Users\Aaron\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Users\Aaron\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Aaron\Documents\Python\Project1\testing\MAIN.py", line 92, in resize_gb1
    self.gb1_img1 = ImageTk.PhotoImage(self.gb1_img1)
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\ImageTk.py", line 143, in __init__
    self.paste(image)
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\ImageTk.py", line 195, in paste
    im.load()
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\ImageFile.py", line 268, in load
    self.load_end()
  File "C:\Users\Aaron\AppData\Roaming\Python\Python310\site-packages\PIL\PngImagePlugin.py", line 962, in load_end
    self.fp.read(4)  # CRC
AttributeError: 'NoneType' object has no attribute 'read'


问:
VB Webbrowser ProgressChange Altering
```<code>Private Sub BusyTimer_Timer()
  If WebBrowser.Busy = True Then
    WebBusy.Caption = Chr$(BusyChr(BusyIdx))
    BusyIdx = IIf(BusyIdx >= UBound(BusyChr()), 0, BusyIdx + 1)
  Else
    ' Elements.AddItem "Busy Timer Ends"
    Me.Caption = WebBrowser.LocationName
    BusyTimer.Enabled = False
    ScanTimer.Interval = 10000
    ScanTimer.Enabled = True
  End If
End Sub
</code>```

So I'm using the WebBrowser in an application and am trying to give indication that the browser is still busy fetching the webpage and this was my initial work of art in making it happen.
WebBusy is a Label on the form.
BusyChr() is the clocks from WingDings.

The issue with this is that if you click on a link while busy, order of precedence breaks the BusyTimer and it quits working.

So then I just moved this into the WebBrowser_ProgressChange event and have no problems with it.

But I find that the interval ProgressChange gets called is, slow.

Is there a means to change the interval?

Title: VB Webbrowser ProgressChange Altering

Body:
Private Sub BusyTimer_Timer()
  If WebBrowser.Busy = True Then
    WebBusy.Caption = Chr$(BusyChr(BusyIdx))
    BusyIdx = IIf(BusyIdx >= UBound(BusyChr()), 0, BusyIdx + 1)
  Else
    ' Elements.AddItem "Busy Timer Ends"
    Me.Caption = WebBrowser.LocationName
    BusyTimer.Enabled = False
    ScanTimer.Interval = 10000
    ScanTimer.Enabled = True
  End If
End Sub

So I'm using the WebBrowser in an application and am trying to give indication that the browser is still busy fetching the webpage and this was my initial work of art in making it happen.
WebBusy is a Label on the form.
BusyChr() is the clocks from WingDings.

The issue with this is that if you click on a link while busy, order of precedence breaks the BusyTimer and it quits working.

So then I just moved this into the WebBrowser_ProgressChange event and have no problems with it.

But I find that the interval ProgressChange gets called is, slow.

Is there a means to change the interval?


问:
Getting 'role ___ does not exist' when running Django makemigrations
I am attempting to connect a Django app to a local database, per the instructions here.

My settings.py:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'OPTIONS': {
            'service': 'my_service',
            'passfile': '.my_pgpass',
        },
    }
}

</code>```

My .pg_service.conf:

```<code>[my_service]
host=localhost
user=firstlast
dbname=my_db
port=5432
</code>```

My .my_pgpass:

```<code>localhost:5432:my_db:firstlast:password
</code>```

I've defined a new Model, and when I run python manage.py makemigrations myapp I get the following error:

```<code>/path/to/myproject/venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:143:
RuntimeWarning: Got an error checking a consistent migration history
performed for database connection 'default': connection to server at
"localhost" (127.0.0.1), port 5432 failed: FATAL:  role "first"
does not exist

  warnings.warn(
No changes detected in app 'myapp'
</code>```

Note that the role in the error is different than the user defined in .pg_service.conf and .my_pgpass.

Why is the user wrong? Why am I unable to connect to the database?

Thanks in advance for the help. Apologies if there is something obvious I am missing.

Body:
I am attempting to connect a Django app to a local database, per the instructions here.

My settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'OPTIONS': {
            'service': 'my_service',
            'passfile': '.my_pgpass',
        },
    }
}

My .pg_service.conf:

[my_service]
host=localhost
user=firstlast
dbname=my_db
port=5432

My .my_pgpass:

localhost:5432:my_db:firstlast:password

I've defined a new Model, and when I run python manage.py makemigrations myapp I get the following error:

/path/to/myproject/venv/lib/python3.9/site-packages/django/core/management/commands/makemigrations.py:143:
RuntimeWarning: Got an error checking a consistent migration history
performed for database connection 'default': connection to server at
"localhost" (127.0.0.1), port 5432 failed: FATAL:  role "first"
does not exist

  warnings.warn(
No changes detected in app 'myapp'

Note that the role in the error is different than the user defined in .pg_service.conf and .my_pgpass.

Why is the user wrong? Why am I unable to connect to the database?

Thanks in advance for the help. Apologies if there is something obvious I am missing.


问:
vb.net dt.select not recognizing data changed in dgv
I populate a dt using an sql query.
It gets 3 rows

```<code>pn tag
p1 52
RT 78
RT 99
</code>```

if I run the following select, I will get 2

```<code>(dt.select("pn='rt'")).count 'returns 2
</code>```

I use the dt as the datasource for a dgv, where I change the second row to have a pn of p1.

```<code>pn tag
p1 52
p1 78
RT 99
</code>```

I can show the new data in a messagebox no prob

```<code>messagebox.show(dt.rows(1)("pn")) 'returns p1
</code>```

But when I rerun the above select, I still get 2.  And if I run it for p1 I still get 1.

```<code>(dt.select("pn='rt'")).count 'still returns 2
(dt.select("pn='p1'")).count 'still returns 1
</code>```

I can even do a select on the tag# and it return the correct (changed) p/n!

```<code>messagebox.show((dt.select("tag=78"))(0)("pn").tostring) 'returns p1
</code>```

It's like the .select only searches on the 'original' copy of the dt instead of the current data, even though it returns current.

What am I missing?

Solution:
When I was done editing a field, I was automatically clicking (ot TABing) in another field of the same row.
If you either click in a different row, or, I added a focus elsewhere at the start of the CellValueChanged event, the .select suddenly uses the updated data in its search

```<code>other_DGV.Focus()
</code>```

Body:
I populate a dt using an sql query.
It gets 3 rows

pn tag
p1 52
RT 78
RT 99

if I run the following select, I will get 2

(dt.select("pn='rt'")).count 'returns 2

I use the dt as the datasource for a dgv, where I change the second row to have a pn of p1.

pn tag
p1 52
p1 78
RT 99

I can show the new data in a messagebox no prob

messagebox.show(dt.rows(1)("pn")) 'returns p1

But when I rerun the above select, I still get 2.  And if I run it for p1 I still get 1.

(dt.select("pn='rt'")).count 'still returns 2
(dt.select("pn='p1'")).count 'still returns 1

I can even do a select on the tag# and it return the correct (changed) p/n!

messagebox.show((dt.select("tag=78"))(0)("pn").tostring) 'returns p1

It's like the .select only searches on the 'original' copy of the dt instead of the current data, even though it returns current.

What am I missing?

Solution:
When I was done editing a field, I was automatically clicking (ot TABing) in another field of the same row.
If you either click in a different row, or, I added a focus elsewhere at the start of the CellValueChanged event, the .select suddenly uses the updated data in its search

other_DGV.Focus()


问:
Can the subversion ruby bindings use the user's stored credentials?
I'm writing a cross-platform ruby script to manage some subversion repositories. I initially generated bash commands but this proved to be very Windows-unfriendly. I then rewrote my script to use the SWIG ruby bindings provided with subversion. This works perfectly (as far as SVN operations are concerned) on all required platforms (Ubuntu, Fedora, OS X, Windows) with ruby 1.8.7.

I use the svn_wc gem to abstract part of the bindings because I don't yet understand the low-level code.

Now, my problem is that I have to give the user's credentials to the bindings. svn_wc uses this code:

```<code>ctx.add_simple_prompt_provider(0) do |cred, realm, username, may_save|
  cred.username = @svn_user
  cred.password = @svn_pass
  cred.may_save = false
end
</code>```

If @svn_user and @svn_pass are nil, the bindings fail with a segmentation fault:

```<code>~/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/svn/util.rb:86:
[BUG] Segmentation fault
ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin10.8.0]

[1]    4381 abort      my_script.rb
</code>```

If I comment this whole piece of code, my svn command fails with the following error:

```<code>cant get info: subversion/libsvn_ra_neon/util.c:608:
Svn::Error::RaNotAuthorized: OPTIONS of 'https://my.subversion.url':
authorization failed: Could not authenticate to server:
rejected Basic challenge (https://my.subversion.url) (SvnWc::RepoAccessError)
</code>```

I don't know what the may_save parameter is for. Changing it to true and giving no credentials still produces the segmentation fault.

My script should use the stored, encrypted credentials the same way the command line binary does. I don't want to type the credentials every time or to store them in a unencrypted configuration file.

I have found no documentation about this. Does anyone know if it's possible and how?

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a cross-platform ruby script to manage some subversion repositories. I initially generated bash commands but this proved to be very Windows-unfriendly. I then rewrote my script to use the SWIG ruby bindings provided with subversion. This works perfectly (as far as SVN operations are concerned) on all required platforms (Ubuntu, Fedora, OS X, Windows) with ruby 1.8.7.

I use the svn_wc gem to abstract part of the bindings because I don't yet understand the low-level code.

Now, my problem is that I have to give the user's credentials to the bindings. svn_wc uses this code:

ctx.add_simple_prompt_provider(0) do |cred, realm, username, may_save|
  cred.username = @svn_user
  cred.password = @svn_pass
  cred.may_save = false
end

If @svn_user and @svn_pass are nil, the bindings fail with a segmentation fault:

~/.rvm/rubies/ruby-1.8.7-p334/lib/ruby/1.8/svn/util.rb:86:
[BUG] Segmentation fault
ruby 1.8.7 (2011-02-18 patchlevel 334) [i686-darwin10.8.0]

[1]    4381 abort      my_script.rb

If I comment this whole piece of code, my svn command fails with the following error:

cant get info: subversion/libsvn_ra_neon/util.c:608:
Svn::Error::RaNotAuthorized: OPTIONS of 'https://my.subversion.url':
authorization failed: Could not authenticate to server:
rejected Basic challenge (https://my.subversion.url) (SvnWc::RepoAccessError)

I don't know what the may_save parameter is for. Changing it to true and giving no credentials still produces the segmentation fault.

My script should use the stored, encrypted credentials the same way the command line binary does. I don't want to type the credentials every time or to store them in a unencrypted configuration file.

I have found no documentation about this. Does anyone know if it's possible and how?


问:
Active Admin Ruby on Rails: Article Content not Rendering on admin page
I am trying to setup rails active admin, successfully installed the gem file and able to run some codes but I am presently having issues with admin show/view page, If I click on any article to view from my column table, it won't show the content just the title. this is my code</p>
```<code>ActiveAdmin.register Article do

@articles = Article.all

end

  form do |f|
  f.semantic_errors # shows errors on :base
  f.inputs
  f.inputs do
    f.input :image, as: :file

  end
    f.actions         # adds the 'Submit' and 'Cancel' buttons
end

 index do
     column :id
     column "Title" do |article|
     link_to article.title, admin_article_path(article)
  end
      column :content
      column :created_at
      actions
  end

 show do
   h3 article.title
    div do
      simple_format article.content
    end
    active_admin_comments
  end

end

</code>```

Body:
I am trying to setup rails active admin, successfully installed the gem file and able to run some codes but I am presently having issues with admin show/view page, If I click on any article to view from my column table, it won't show the content just the title. this is my code

ActiveAdmin.register Article do

@articles = Article.all

end

  form do |f|
  f.semantic_errors # shows errors on :base
  f.inputs
  f.inputs do
    f.input :image, as: :file

  end
    f.actions         # adds the 'Submit' and 'Cancel' buttons
end

 index do
     column :id
     column "Title" do |article|
     link_to article.title, admin_article_path(article)
  end
      column :content
      column :created_at
      actions
  end

 show do
   h3 article.title
    div do
      simple_format article.content
    end
    active_admin_comments
  end

end


问:
Nextjs - Warning: Text content did not match. Server: "2022" Client: "2023"
my nextjs project gives such an error in live, does anyone have any good information in local?

```<code>Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.
</code>```

new year greeted with bugs

```<code>Warning: Text content did not match. Server: "2022" Client: "2023"
</code>```

Body:
my nextjs project gives such an error in live, does anyone have any good information in local?

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

new year greeted with bugs

Warning: Text content did not match. Server: "2022" Client: "2023"