问:
TensorFlow convolutional neural network using higher resolution images
I've been following some TensorFlow tutorials for convolutional neural networks for a while and everything has been going fine whilst using the test sets used for the examples, however when I try to move on to using my own labelled data, things seem to stop working.

The images I have are 700x700 px images, so after changing some small things in the script I can get the training to start, however the accuracies never seem to update from the starting value (see below).

I have a total of around 800 images, so I would understand if the model was overfitting but not updating at all seems odd.

The code I use is below.

I've also found that if I split the images up into smaller images of around 140x140 px the script is able to train fine, so my guess would be that it's a memory issue. But I would have expected that if this were the case it would come back with an error rather than just not training?

Thanks in advance for any help.

```<code>from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
import os
import random
from shutil import copyfile
import time

device = tf.config.list_physical_devices('GPU')
print(f'Running on device: {device}')

def create_train_val_dirs(root_path):
    """
    Creates directories for the train and test sets

    Args:
        root_path (string) - the base directory path to create subdirectories from

    Returns:
        None
    """

    os.makedirs(root_path)

    val_path = os.path.join(root_path, 'validation')
    train_path = os.path.join(root_path, 'training')
    os.makedirs(train_path)
    os.makedirs(val_path)

    os.makedirs(os.path.join(val_path, 'Good'))
    os.makedirs(os.path.join(val_path, 'Bad'))
    os.makedirs(os.path.join(train_path, 'Good'))
    os.makedirs(os.path.join(train_path, 'Bad'))

def split_data(SOURCE_DIR, TRAINING_DIR, VALIDATION_DIR, SPLIT_SIZE):

    """
    Splits the data into train and test sets

    Args:
        SOURCE_DIR (string): directory path containing the images
        TRAINING_DIR (string): directory path to be used for training
        VALIDATION_DIR (string): directory path to be used for validation
        SPLIT_SIZE (float): proportion of the dataset to be used for training

    Returns:
        None
    """

    im_list = random.sample(os.listdir(SOURCE_DIR), len(os.listdir(SOURCE_DIR)))

    for index, im in enumerate(im_list):
        if os.path.getsize(os.path.join(SOURCE_DIR, im)) == 0:
            print(f"{im} is zero length, so ignoring.")
            continue
        if index <= SPLIT_SIZE*len(im_list):
            copyfile(os.path.join(SOURCE_DIR, im), os.path.join(TRAINING_DIR, im))
        else:
            copyfile(os.path.join(SOURCE_DIR, im), os.path.join(VALIDATION_DIR, im))

def train_val_generators(TRAINING_DIR, VALIDATION_DIR, batch_size, input_size):
    """
    Creates the training and validation data generators

    Args:
        TRAINING_DIR (string): directory path containing the training images
        VALIDATION_DIR (string): directory path containing the testing/validation images
        batch_size (integer): Integer number of batches (amount of images trained per loop).
        input_size (tensor: (int, int)): Tensor containing the size of the input image, or
        preferred input size (if different to the actual size it will be scaled).

    Returns:
        train_generator, validation_generator - tuple containing the generators
    """

    # Instantiate the ImageDataGenerator class (don't forget to set the arguments to augment the images)
    train_datagen = ImageDataGenerator(rescale=1./255.0,
                                    #  rotation_range=90,           #Turned off since it wasn't on previously
                                    #  width_shift_range=0.2,
                                    #  height_shift_range=0.2,
                                    #  shear_range=0.2,
                                    #  zoom_range=0.2,
                                    horizontal_flip=True,
                                    vertical_flip=True,
                                    #  fill_mode='nearest'
                                    )

    # Pass in the appropriate arguments to the flow_from_directory method
    train_generator = train_datagen.flow_from_directory(directory=TRAINING_DIR,
                                                        batch_size=batch_size,
                                                        class_mode='binary',
                                                        target_size=target_size,
                                                        color_mode= 'grayscale')

    # Instantiate the ImageDataGenerator class (don't forget to set the rescale argument)
    validation_datagen = ImageDataGenerator(rescale=1./255.0)

    # Pass in the appropriate arguments to the flow_from_directory method
    validation_generator = validation_datagen.flow_from_directory(directory=VALIDATION_DIR,
                                                                batch_size=batch_size,
                                                                class_mode='binary',
                                                                target_size=target_size,
                                                                color_mode= 'grayscale')
    ### END CODE HERE
    return train_generator, validation_generator

# Find the start time
initial_t = time.perf_counter()

# set tf_xla_enable_xla_devices flags
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
os.environ['KMP_DUPLICATE_LIB_OK']='True'

# Define paths
SSD_DIR = Path(os.getcwd())
DATA_DIR = SSD_DIR.joinpath(r'Python_scripts\Machine_Learning\Si111\Tensorflow\Dataset\Binary_notc\all\No_splitting')
SOURCE_DIR = DATA_DIR.joinpath('Input_data')
ROOT_DIR = DATA_DIR.joinpath('ForRuns')

GOOD_SOURCE_DIR = SOURCE_DIR.joinpath("Good")
BAD_SOURCE_DIR = SOURCE_DIR.joinpath("Bad")

TRAINING_DIR = ROOT_DIR.joinpath('training')
VALIDATION_DIR = ROOT_DIR.joinpath('validation')

TRAINING_GOOD_DIR = TRAINING_DIR.joinpath("Good")
VALIDATION_GOOD_DIR = VALIDATION_DIR.joinpath("Good")

TRAINING_BAD_DIR = TRAINING_DIR.joinpath("Bad")
VALIDATION_BAD_DIR = VALIDATION_DIR.joinpath("Bad")

try:
  create_train_val_dirs(root_path=ROOT_DIR)
  print(f'Creating directory at {ROOT_DIR}...')
except FileExistsError:
  print(f"{ROOT_DIR} already exists.")

# Empty directories in case you run this cell multiple times
if len(os.listdir(TRAINING_BAD_DIR)) > 0:
    for file in os.listdir(TRAINING_BAD_DIR):
        os.remove(TRAINING_BAD_DIR.joinpath(file))
if len(os.listdir(TRAINING_GOOD_DIR)) > 0:
    for file in os.listdir(TRAINING_GOOD_DIR):
        os.remove(TRAINING_GOOD_DIR.joinpath(file))
if len(os.listdir(VALIDATION_BAD_DIR)) > 0:
    for file in os.listdir(VALIDATION_BAD_DIR):
        os.remove(VALIDATION_BAD_DIR.joinpath(file))
if len(os.listdir(VALIDATION_GOOD_DIR)) > 0:
    for file in os.listdir(VALIDATION_GOOD_DIR):
        os.remove(VALIDATION_GOOD_DIR.joinpath(file))

# Define proportion of images used for training
split_size = .9

# Run the function
# NOTE: Messages about zero length images should be printed out
split_data(GOOD_SOURCE_DIR, TRAINING_GOOD_DIR, VALIDATION_GOOD_DIR, split_size)
split_data(BAD_SOURCE_DIR, TRAINING_BAD_DIR, VALIDATION_BAD_DIR, split_size)

batch_size = 5
target_size = (700, 700)
epochs = 25
layers = 2
starting = 512

train_generator, validation_generator = train_val_generators(TRAINING_DIR, VALIDATION_DIR, batch_size=batch_size, input_size=target_size)

model = tf.keras.models.Sequential([

      tf.keras.layers.Conv2D(40, (3,3), activation='relu', input_shape= (700,700,1)),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Conv2D(80, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Conv2D(160, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Conv2D(320, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(32, activation='relu'),
      tf.keras.layers.Dropout(0.5),
    #   tf.keras.layers.Dense(512, activation='relu'),
    #   tf.keras.layers.Dropout(0.5),
      tf.keras.layers.Dense(1, activation='sigmoid'),
  ])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.summary()

# Begin training!
history = model.fit(train_generator,
                    epochs=epochs,
                    verbose=1,
                    validation_data=validation_generator)

# Find the final time (before plotting etc.)
def convert_to_preferred_format(sec):
   sec = sec % (24 * 3600)
   hour = sec // 3600
   sec %= 3600
   min = sec // 60
   sec %= 60
   return "%02d:%02d:%02d" % (hour, min, sec)

final_t = time.perf_counter()

total_time = final_t - initial_t
print('*'*20)
print(f'Total time taken for training was {convert_to_preferred_format(total_time)}')
print('*'*20)

# Save the model, history and accuracy plot
save_name = f'AnotherAttempt'
Models_dir = SSD_DIR.joinpath('ML/Models/TensorFlow/Si(111)')

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epoch_range = range(len(acc))

plt.plot(epoch_range, acc, 'r', label='Training accuracy')
plt.plot(epoch_range, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)

plt.savefig(Models_dir.joinpath(f'acc_plots/No_splitting/{save_name}.png'))
model.save(Models_dir.joinpath(f'models/No_splitting/{save_name}.h5'))

# convert the history.history dict to a pandas DataFrame:
hist_df = pd.DataFrame(history.history)

# or save to csv:
hist_csv_file = Models_dir.joinpath(f'histories/No_splitting/{save_name}.csv')
with open(hist_csv_file, mode='w') as f:
    hist_df.to_csv(f)

tf.keras.backend.clear_session()
plt.close()
</code>```

Body:
I've been following some TensorFlow tutorials for convolutional neural networks for a while and everything has been going fine whilst using the test sets used for the examples, however when I try to move on to using my own labelled data, things seem to stop working.

The images I have are 700x700 px images, so after changing some small things in the script I can get the training to start, however the accuracies never seem to update from the starting value (see below).

I have a total of around 800 images, so I would understand if the model was overfitting but not updating at all seems odd.

The code I use is below.

I've also found that if I split the images up into smaller images of around 140x140 px the script is able to train fine, so my guess would be that it's a memory issue. But I would have expected that if this were the case it would come back with an error rather than just not training?

Thanks in advance for any help.

from keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
import os
import random
from shutil import copyfile
import time

device = tf.config.list_physical_devices('GPU')
print(f'Running on device: {device}')

def create_train_val_dirs(root_path):
    """
    Creates directories for the train and test sets

    Args:
        root_path (string) - the base directory path to create subdirectories from

    Returns:
        None
    """

    os.makedirs(root_path)

    val_path = os.path.join(root_path, 'validation')
    train_path = os.path.join(root_path, 'training')
    os.makedirs(train_path)
    os.makedirs(val_path)

    os.makedirs(os.path.join(val_path, 'Good'))
    os.makedirs(os.path.join(val_path, 'Bad'))
    os.makedirs(os.path.join(train_path, 'Good'))
    os.makedirs(os.path.join(train_path, 'Bad'))

def split_data(SOURCE_DIR, TRAINING_DIR, VALIDATION_DIR, SPLIT_SIZE):

    """
    Splits the data into train and test sets

    Args:
        SOURCE_DIR (string): directory path containing the images
        TRAINING_DIR (string): directory path to be used for training
        VALIDATION_DIR (string): directory path to be used for validation
        SPLIT_SIZE (float): proportion of the dataset to be used for training

    Returns:
        None
    """

    im_list = random.sample(os.listdir(SOURCE_DIR), len(os.listdir(SOURCE_DIR)))

    for index, im in enumerate(im_list):
        if os.path.getsize(os.path.join(SOURCE_DIR, im)) == 0:
            print(f"{im} is zero length, so ignoring.")
            continue
        if index <= SPLIT_SIZE*len(im_list):
            copyfile(os.path.join(SOURCE_DIR, im), os.path.join(TRAINING_DIR, im))
        else:
            copyfile(os.path.join(SOURCE_DIR, im), os.path.join(VALIDATION_DIR, im))

def train_val_generators(TRAINING_DIR, VALIDATION_DIR, batch_size, input_size):
    """
    Creates the training and validation data generators

    Args:
        TRAINING_DIR (string): directory path containing the training images
        VALIDATION_DIR (string): directory path containing the testing/validation images
        batch_size (integer): Integer number of batches (amount of images trained per loop).
        input_size (tensor: (int, int)): Tensor containing the size of the input image, or
        preferred input size (if different to the actual size it will be scaled).

    Returns:
        train_generator, validation_generator - tuple containing the generators
    """

    # Instantiate the ImageDataGenerator class (don't forget to set the arguments to augment the images)
    train_datagen = ImageDataGenerator(rescale=1./255.0,
                                    #  rotation_range=90,           #Turned off since it wasn't on previously
                                    #  width_shift_range=0.2,
                                    #  height_shift_range=0.2,
                                    #  shear_range=0.2,
                                    #  zoom_range=0.2,
                                    horizontal_flip=True,
                                    vertical_flip=True,
                                    #  fill_mode='nearest'
                                    )

    # Pass in the appropriate arguments to the flow_from_directory method
    train_generator = train_datagen.flow_from_directory(directory=TRAINING_DIR,
                                                        batch_size=batch_size,
                                                        class_mode='binary',
                                                        target_size=target_size,
                                                        color_mode= 'grayscale')

    # Instantiate the ImageDataGenerator class (don't forget to set the rescale argument)
    validation_datagen = ImageDataGenerator(rescale=1./255.0)

    # Pass in the appropriate arguments to the flow_from_directory method
    validation_generator = validation_datagen.flow_from_directory(directory=VALIDATION_DIR,
                                                                batch_size=batch_size,
                                                                class_mode='binary',
                                                                target_size=target_size,
                                                                color_mode= 'grayscale')
    ### END CODE HERE
    return train_generator, validation_generator

# Find the start time
initial_t = time.perf_counter()

# set tf_xla_enable_xla_devices flags
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
os.environ['KMP_DUPLICATE_LIB_OK']='True'

# Define paths
SSD_DIR = Path(os.getcwd())
DATA_DIR = SSD_DIR.joinpath(r'Python_scripts\Machine_Learning\Si111\Tensorflow\Dataset\Binary_notc\all\No_splitting')
SOURCE_DIR = DATA_DIR.joinpath('Input_data')
ROOT_DIR = DATA_DIR.joinpath('ForRuns')

GOOD_SOURCE_DIR = SOURCE_DIR.joinpath("Good")
BAD_SOURCE_DIR = SOURCE_DIR.joinpath("Bad")

TRAINING_DIR = ROOT_DIR.joinpath('training')
VALIDATION_DIR = ROOT_DIR.joinpath('validation')

TRAINING_GOOD_DIR = TRAINING_DIR.joinpath("Good")
VALIDATION_GOOD_DIR = VALIDATION_DIR.joinpath("Good")

TRAINING_BAD_DIR = TRAINING_DIR.joinpath("Bad")
VALIDATION_BAD_DIR = VALIDATION_DIR.joinpath("Bad")

try:
  create_train_val_dirs(root_path=ROOT_DIR)
  print(f'Creating directory at {ROOT_DIR}...')
except FileExistsError:
  print(f"{ROOT_DIR} already exists.")

# Empty directories in case you run this cell multiple times
if len(os.listdir(TRAINING_BAD_DIR)) > 0:
    for file in os.listdir(TRAINING_BAD_DIR):
        os.remove(TRAINING_BAD_DIR.joinpath(file))
if len(os.listdir(TRAINING_GOOD_DIR)) > 0:
    for file in os.listdir(TRAINING_GOOD_DIR):
        os.remove(TRAINING_GOOD_DIR.joinpath(file))
if len(os.listdir(VALIDATION_BAD_DIR)) > 0:
    for file in os.listdir(VALIDATION_BAD_DIR):
        os.remove(VALIDATION_BAD_DIR.joinpath(file))
if len(os.listdir(VALIDATION_GOOD_DIR)) > 0:
    for file in os.listdir(VALIDATION_GOOD_DIR):
        os.remove(VALIDATION_GOOD_DIR.joinpath(file))

# Define proportion of images used for training
split_size = .9

# Run the function
# NOTE: Messages about zero length images should be printed out
split_data(GOOD_SOURCE_DIR, TRAINING_GOOD_DIR, VALIDATION_GOOD_DIR, split_size)
split_data(BAD_SOURCE_DIR, TRAINING_BAD_DIR, VALIDATION_BAD_DIR, split_size)

batch_size = 5
target_size = (700, 700)
epochs = 25
layers = 2
starting = 512

train_generator, validation_generator = train_val_generators(TRAINING_DIR, VALIDATION_DIR, batch_size=batch_size, input_size=target_size)

model = tf.keras.models.Sequential([

      tf.keras.layers.Conv2D(40, (3,3), activation='relu', input_shape= (700,700,1)),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Conv2D(80, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Conv2D(160, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Conv2D(320, (3,3), activation='relu'),
      tf.keras.layers.MaxPooling2D((2,2)),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(32, activation='relu'),
      tf.keras.layers.Dropout(0.5),
    #   tf.keras.layers.Dense(512, activation='relu'),
    #   tf.keras.layers.Dropout(0.5),
      tf.keras.layers.Dense(1, activation='sigmoid'),
  ])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.summary()

# Begin training!
history = model.fit(train_generator,
                    epochs=epochs,
                    verbose=1,
                    validation_data=validation_generator)

# Find the final time (before plotting etc.)
def convert_to_preferred_format(sec):
   sec = sec % (24 * 3600)
   hour = sec // 3600
   sec %= 3600
   min = sec // 60
   sec %= 60
   return "%02d:%02d:%02d" % (hour, min, sec)

final_t = time.perf_counter()

total_time = final_t - initial_t
print('*'*20)
print(f'Total time taken for training was {convert_to_preferred_format(total_time)}')
print('*'*20)

# Save the model, history and accuracy plot
save_name = f'AnotherAttempt'
Models_dir = SSD_DIR.joinpath('ML/Models/TensorFlow/Si(111)')

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epoch_range = range(len(acc))

plt.plot(epoch_range, acc, 'r', label='Training accuracy')
plt.plot(epoch_range, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)

plt.savefig(Models_dir.joinpath(f'acc_plots/No_splitting/{save_name}.png'))
model.save(Models_dir.joinpath(f'models/No_splitting/{save_name}.h5'))

# convert the history.history dict to a pandas DataFrame:
hist_df = pd.DataFrame(history.history)

# or save to csv:
hist_csv_file = Models_dir.joinpath(f'histories/No_splitting/{save_name}.csv')
with open(hist_csv_file, mode='w') as f:
    hist_df.to_csv(f)

tf.keras.backend.clear_session()
plt.close()


来源: stackexchange

问:
Next.js vert slow to start on Windows OS
I have this big issue with starting Next.js, the same project on 2 different OS, it has completely different startup times, 1s on MacOSX vs 10s on Windows 11.
Has anyone else had the same problem? Is there any way to fix it?

enter image description here

Here's my next.js conf:

```<code>const { resolve } = require('path')

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
  openAnalyzer: true,
})

module.exports = withBundleAnalyzer(
  {
    i18n: {
      locales: ['en', 'it'],
      defaultLocale: 'en',
      localeDetection: true,
    },

    compiler: {
      removeConsole: process.env.NODE_ENV !== 'development',
    },

    swcMinify: true,

    eslint: {
      ignoreDuringBuilds: true,
    },

    webpack: (config) => {
      config.plugins = config.plugins || []

      config.optimization.providedExports = true

      config.resolve.alias = {
        ...config.resolve.alias,
        '@': resolve(__dirname, './src/'),
      }

      config.resolve.fallback = { ...config.resolve.fallback, fs: false }

      config.module.rules.push({
        test: /\.(glsl|vs|fs|vert|frag)$/,
        use: ['raw-loader', 'glslify-loader'],
      })

      return config
    },
  },
)

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this big issue with starting Next.js, the same project on 2 different OS, it has completely different startup times, 1s on MacOSX vs 10s on Windows 11.
Has anyone else had the same problem? Is there any way to fix it?

enter image description here

Here's my next.js conf:

const { resolve } = require('path')

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
  openAnalyzer: true,
})

module.exports = withBundleAnalyzer(
  {
    i18n: {
      locales: ['en', 'it'],
      defaultLocale: 'en',
      localeDetection: true,
    },

    compiler: {
      removeConsole: process.env.NODE_ENV !== 'development',
    },

    swcMinify: true,

    eslint: {
      ignoreDuringBuilds: true,
    },

    webpack: (config) => {
      config.plugins = config.plugins || []

      config.optimization.providedExports = true

      config.resolve.alias = {
        ...config.resolve.alias,
        '@': resolve(__dirname, './src/'),
      }

      config.resolve.fallback = { ...config.resolve.fallback, fs: false }

      config.module.rules.push({
        test: /\.(glsl|vs|fs|vert|frag)$/,
        use: ['raw-loader', 'glslify-loader'],
      })

      return config
    },
  },
)


问:
How to animate multiple children while scrolling using 'flutter_animate' package
I am trying to animate many widgets such as Text(), Image.asset() and other stuff when they are visible. I tried multiple libraries for checking visibilty of Widgets inside a SingleChildScrollView() but all solutions were either very complicated or it takes a lot of coding to achieve it for multiple widgets. The question that is most similar to mine is this, but it is simple for one or two widgets, but it will be messy for many Widgets. Can someone help me in achieving this requirement?

Edit:

I found that 'flutter_animate' depends on controllers, such as ScrollController, but no documentation about it was mentioned.
enter link description here


问:
Unable to serialize VariableSpec(shape=(1,), dtype=tf.float32, alias_id=None) to JSON
I am launching the following neural network, and I suspect that there is a mistake with some variables (especially in the MeanShift function) with the initialization of weights and biases.

```<code>################
##### RCAN #####
################

def RCAN(n_RCAB=3, n_RG=5, rgb_mean = [0.4488], rgb_std = 1, **kwargs):

    def _func(input_shape):
        import sys
        sys.setrecursionlimit(25000)

        # Start of the Model
        inputs = Input(input_shape)
        scaled_inputs = tf.keras.layers.experimental.preprocessing.Rescaling(255)(inputs)
        scaled_inputs = MeanShift(rgb_range=255, rgb_mean=rgb_mean, rgb_std=rgb_std)(inputs)

        # Head module
        x = Conv2D(64, 3, padding='same')(scaled_inputs)
        _inp = x

        # Body module
        for i in range(n_RG):
            x = ResidualGroup(x, n_RCAB)
        x = Conv2D(64, 3, padding='same')(x)

        add_global = tf.keras.layers.Add()([x, _inp])

        # Tail module
        x = UpSampling(add_global)
        x = Conv2D(1, 3, padding='same')(x)

        outputs = MeanShift(rgb_range=255, rgb_mean=rgb_mean, rgb_std=rgb_std, sign=1)(x)
        outputs = tf.keras.layers.experimental.preprocessing.Rescaling(1.0 / 255)(outputs)

        # Defining the model
        model = Model(inputs=inputs, outputs=outputs)
        return model
    return _func

######################
##### ABOUT RCAN #####
######################

def RCAB(x):
    _res = x

    x = Conv2D(64, 3, padding='same')(x)
    x = tf.keras.layers.LeakyReLU()(x)
    x = Conv2D(64, 3, padding='same')(x)

    x = ChannelAttention(x)
    x = tf.keras.layers.Add()([x, _res])
    return x

def ChannelAttention(x):
    _res = x

    avg_pool = tf.math.reduce_mean(x, axis=[1, 2, 3], keepdims=True)

    feat_mix = Conv2D(4, 1, padding='same', activation='relu')(avg_pool)
    feat_mix = Conv2D(64, 1, padding='same', activation='sigmoid')(feat_mix)

    multi = tf.keras.layers.Multiply()([feat_mix, _res])
    return multi

def ResidualGroup(x,  n_RCAB):
    skip_connection = x

    for i in range(n_RCAB):
        x = RCAB(x)

    x = Conv2D(64, 3, padding='same')(x)
    x = tf.keras.layers.Add()([x, skip_connection])
    return x

def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights
        weight_initer = tf.constant(value=1., dtype=tf.float32, shape=[1])
        W = tf.Variable(weight_initer, name="Weight", dtype=tf.float32)

        # Initilize bias
        bias_initer = tf.constant(value=[m * rgb_range * sign / rgb_std for m in rgb_mean], dtype=tf.float32)
        b = tf.Variable(bias_initer, name="Bias", dtype=tf.float32)

        x = Conv2D(1, 1, padding="same", kernel_initializer=keras.initializers.Constant(W), bias_initializer=keras.initializers.Constant(b), activation="relu")(x)
        return x

    return _func

def UpSampling(x, act=False):
    features = Conv2D(256, 3, padding='same')(x)
    high_res = tf.nn.depth_to_space(features, 2)

    if act:
        high_res = tf.keras.layers.ReLU(max_value=1)(high_res)

    return high_res
</code>```

The error is when saving the weights (with checkpoints every 5 epochs), but the update of any version (2.4 or 2.9) of tensorflow isn't working.

ValueError: Unable to serialize VariableSpec(shape=(1,),
dtype=tf.float32, trainable=True, alias_id=None) to JSON, because the
TypeSpec class <class
'tensorflow.python.ops.resource_variable_ops.VariableSpec'> has not
been registered

Moreover, my inputs and target are percentile normalized. And I would like to know what layers or operations to add so that predictions matches best the targets (on the variables scaled_inputs and outputs of RCAN function for example).

I would appreciate any help. Thank you in advance.

EDIT:

Ok, found the problem: i think that kernel and bias were not trainable due to keras.initializers.Constant(W) (and same for b) in the Conv2D layer, or due to the tensorflow initializer (I was a bit lost because multiple ones exist). So I replaced it by: and it works

```<code>def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights and bias
        W = tf.keras.initializers.Constant(1.)
        b = tf.keras.initializers.Constant(rgb_mean[0] * rgb_range * sign / rgb_std)

        x = Conv2D(1, 1, padding="same", kernel_initializer=W, bias_initializer=b)(x)
        return x

    return _func
</code>```

Body:
I am launching the following neural network, and I suspect that there is a mistake with some variables (especially in the MeanShift function) with the initialization of weights and biases.

################
##### RCAN #####
################

def RCAN(n_RCAB=3, n_RG=5, rgb_mean = [0.4488], rgb_std = 1, **kwargs):

    def _func(input_shape):
        import sys
        sys.setrecursionlimit(25000)

        # Start of the Model
        inputs = Input(input_shape)
        scaled_inputs = tf.keras.layers.experimental.preprocessing.Rescaling(255)(inputs)
        scaled_inputs = MeanShift(rgb_range=255, rgb_mean=rgb_mean, rgb_std=rgb_std)(inputs)

        # Head module
        x = Conv2D(64, 3, padding='same')(scaled_inputs)
        _inp = x

        # Body module
        for i in range(n_RG):
            x = ResidualGroup(x, n_RCAB)
        x = Conv2D(64, 3, padding='same')(x)

        add_global = tf.keras.layers.Add()([x, _inp])

        # Tail module
        x = UpSampling(add_global)
        x = Conv2D(1, 3, padding='same')(x)

        outputs = MeanShift(rgb_range=255, rgb_mean=rgb_mean, rgb_std=rgb_std, sign=1)(x)
        outputs = tf.keras.layers.experimental.preprocessing.Rescaling(1.0 / 255)(outputs)

        # Defining the model
        model = Model(inputs=inputs, outputs=outputs)
        return model
    return _func

######################
##### ABOUT RCAN #####
######################

def RCAB(x):
    _res = x

    x = Conv2D(64, 3, padding='same')(x)
    x = tf.keras.layers.LeakyReLU()(x)
    x = Conv2D(64, 3, padding='same')(x)

    x = ChannelAttention(x)
    x = tf.keras.layers.Add()([x, _res])
    return x

def ChannelAttention(x):
    _res = x

    avg_pool = tf.math.reduce_mean(x, axis=[1, 2, 3], keepdims=True)

    feat_mix = Conv2D(4, 1, padding='same', activation='relu')(avg_pool)
    feat_mix = Conv2D(64, 1, padding='same', activation='sigmoid')(feat_mix)

    multi = tf.keras.layers.Multiply()([feat_mix, _res])
    return multi

def ResidualGroup(x,  n_RCAB):
    skip_connection = x

    for i in range(n_RCAB):
        x = RCAB(x)

    x = Conv2D(64, 3, padding='same')(x)
    x = tf.keras.layers.Add()([x, skip_connection])
    return x

def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights
        weight_initer = tf.constant(value=1., dtype=tf.float32, shape=[1])
        W = tf.Variable(weight_initer, name="Weight", dtype=tf.float32)

        # Initilize bias
        bias_initer = tf.constant(value=[m * rgb_range * sign / rgb_std for m in rgb_mean], dtype=tf.float32)
        b = tf.Variable(bias_initer, name="Bias", dtype=tf.float32)

        x = Conv2D(1, 1, padding="same", kernel_initializer=keras.initializers.Constant(W), bias_initializer=keras.initializers.Constant(b), activation="relu")(x)
        return x

    return _func

def UpSampling(x, act=False):
    features = Conv2D(256, 3, padding='same')(x)
    high_res = tf.nn.depth_to_space(features, 2)

    if act:
        high_res = tf.keras.layers.ReLU(max_value=1)(high_res)

    return high_res

The error is when saving the weights (with checkpoints every 5 epochs), but the update of any version (2.4 or 2.9) of tensorflow isn't working.

ValueError: Unable to serialize VariableSpec(shape=(1,),
dtype=tf.float32, trainable=True, alias_id=None) to JSON, because the
TypeSpec class <class
'tensorflow.python.ops.resource_variable_ops.VariableSpec'> has not
been registered

Moreover, my inputs and target are percentile normalized. And I would like to know what layers or operations to add so that predictions matches best the targets (on the variables scaled_inputs and outputs of RCAN function for example).

I would appreciate any help. Thank you in advance.

EDIT:

Ok, found the problem: i think that kernel and bias were not trainable due to keras.initializers.Constant(W) (and same for b) in the Conv2D layer, or due to the tensorflow initializer (I was a bit lost because multiple ones exist). So I replaced it by: and it works

def MeanShift(rgb_range, rgb_mean, rgb_std, sign=-1):
    def _func(x):
        # Initilize weights and bias
        W = tf.keras.initializers.Constant(1.)
        b = tf.keras.initializers.Constant(rgb_mean[0] * rgb_range * sign / rgb_std)

        x = Conv2D(1, 1, padding="same", kernel_initializer=W, bias_initializer=b)(x)
        return x

    return _func


问:
How to implement custom design in ListTitle in flutter
I am trying to add design like below image but wihtout success in ListTitle.

Design Image

I try to add design like image but right side alignment and icon set time error showing in ListTitle using flutter.

```<code>class DriverListTile extends ListTile {
   int assigned=1;
   DriverListTile(Loads data,BuildContext context)
      : super(

     // dense:true,
          //  title: Text('COMMODITY : '+data.commodity!,style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),
       contentPadding: EdgeInsets. symmetric(vertical: 8.0,horizontal: 8.0),

            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,

              children: <Widget>[
                new Text(""+data.pickupAdd!+" ( - )",style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),
             [enter image description here](https://i.stack.imgur.com/IlpnK.jpg),

                new Text("DISTANCE : "+data.routeDistance! +"mi",style: TextStyle(color: Colors.white)),
                // new Text('ID : '+data.dispatch_id),
               // new Text("CLIENT NAME : "+data.clientContactName!,style: TextStyle(color: Colors.white)),
                new Text("PICKUP TIME : "+data.pickupDateTime!,style: TextStyle(color: Colors.white)),
                new Text("PICKUP WEIGHT : "+data.weightPickup!,style: TextStyle(color: Colors.white)),
                new Text("LOAD NUMBER : "+data.dispatchId!,style: TextStyle(color: Colors.white))

              ],
            ),
           // leading: CircleAvatar(child: Text(data.commodity[0])),
            dense: false,
      trailing: Text("\$100",style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),

      // trailing: Icon(
            //   Icons.arrow_forward,
            //   size: 24.0,
            //   color: Colors.deepPurple,
            // ),
            onTap: () async {

            });

}
</code>```

Body:
I am trying to add design like below image but wihtout success in ListTitle.

Design Image

I try to add design like image but right side alignment and icon set time error showing in ListTitle using flutter.

class DriverListTile extends ListTile {
   int assigned=1;
   DriverListTile(Loads data,BuildContext context)
      : super(

     // dense:true,
          //  title: Text('COMMODITY : '+data.commodity!,style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),
       contentPadding: EdgeInsets. symmetric(vertical: 8.0,horizontal: 8.0),

            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,

              children: <Widget>[
                new Text(""+data.pickupAdd!+" ( - )",style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),
             [enter image description here](https://i.stack.imgur.com/IlpnK.jpg),

                new Text("DISTANCE : "+data.routeDistance! +"mi",style: TextStyle(color: Colors.white)),
                // new Text('ID : '+data.dispatch_id),
               // new Text("CLIENT NAME : "+data.clientContactName!,style: TextStyle(color: Colors.white)),
                new Text("PICKUP TIME : "+data.pickupDateTime!,style: TextStyle(color: Colors.white)),
                new Text("PICKUP WEIGHT : "+data.weightPickup!,style: TextStyle(color: Colors.white)),
                new Text("LOAD NUMBER : "+data.dispatchId!,style: TextStyle(color: Colors.white))

              ],
            ),
           // leading: CircleAvatar(child: Text(data.commodity[0])),
            dense: false,
      trailing: Text("\$100",style: TextStyle(color: Colors.white),textAlign: TextAlign.center,),

      // trailing: Icon(
            //   Icons.arrow_forward,
            //   size: 24.0,
            //   color: Colors.deepPurple,
            // ),
            onTap: () async {

            });

}


问:
Create users with same email address
I want to create multiple Orchard users with different username but same email address.

I've configured the IdentityOptions to RequireUniqueEmail = false, but when I create a second user the same email address I get an error: "Email 'email@email.com' is already used."

My Program.cs:
`

```<code>services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredUniqueChars = 5;
    options.Password.RequiredLength = 10;
    options.User.RequireUniqueEmail = false;
});
</code>```

`

The password options are working, so I don't know why the RequiredUniqueEmail is not.
Any ideas?

Title: Create users with same email address

Body:
I want to create multiple Orchard users with different username but same email address.

I've configured the IdentityOptions to RequireUniqueEmail = false, but when I create a second user the same email address I get an error: "Email 'email@email.com' is already used."

My Program.cs:
`

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequiredUniqueChars = 5;
    options.Password.RequiredLength = 10;
    options.User.RequireUniqueEmail = false;
});

`

The password options are working, so I don't know why the RequiredUniqueEmail is not.
Any ideas?


问:
Track the fingers Up and Down Swipe is not working in Google VrVideoView Android
I am new to google vr sdk . I implemented 360 video's in VrVideoview. I can swipe left and right while playing the video But I can't swipe up and down it. Thanks for your help in advance.</p>
```<code> mVrVideoView!!.isVerticalFadingEdgeEnabled = false
    mVrVideoView!!.setInfoButtonEnabled(false)
    mSeekBar!!.setOnSeekBarChangeListener(this)

    if (prefs.goggles) {
        mVrVideoView!!.displayMode = VrWidgetView.DisplayMode.FULLSCREEN_STEREO
    } else {
        mVrVideoView!!.displayMode = VrWidgetView.DisplayMode.EMBEDDED
    }
    mVrVideoView!!.setTouchTrackingEnabled(true)
    mVrVideoView!!.setTransitionViewEnabled(true)
    mVrVideoView!!.setFullscreenButtonEnabled(false)
    mVrVideoView!!.setStereoModeButtonEnabled(false)
</code>```

Body:
I am new to google vr sdk . I implemented 360 video's in VrVideoview. I can swipe left and right while playing the video But I can't swipe up and down it. Thanks for your help in advance.

 mVrVideoView!!.isVerticalFadingEdgeEnabled = false
    mVrVideoView!!.setInfoButtonEnabled(false)
    mSeekBar!!.setOnSeekBarChangeListener(this)

    if (prefs.goggles) {
        mVrVideoView!!.displayMode = VrWidgetView.DisplayMode.FULLSCREEN_STEREO
    } else {
        mVrVideoView!!.displayMode = VrWidgetView.DisplayMode.EMBEDDED
    }
    mVrVideoView!!.setTouchTrackingEnabled(true)
    mVrVideoView!!.setTransitionViewEnabled(true)
    mVrVideoView!!.setFullscreenButtonEnabled(false)
    mVrVideoView!!.setStereoModeButtonEnabled(false)


问:
Could not create the Java Virtual Machine. intelli idea ubuntu 20.04

trying to raise a project on my new laptop I have the error
Could not create the Java Virtual Machine.
Yes, I have java installed, only the project compiles perfectly when I give maven install, the problem is at the time of deployment

I have already tried changing the memory as indicated here (Intellij idea showing error: could not create the java virtual machine) without results


问:
how can i read in a binary file given path-to-file in typescript?
ionic v6.20
angular v14

on iOS and Android i take a picture and am given the path to the image file. i simply want to read in that file and store the contents in a blob. sounds simple, but i've had no luck finding an example of doing just that. NOTE: storing the result in a BLOB is simple, i just need to read the contents of the image!

i've tried various functions that i found in "FileReader()", but they expect a BLOB as the parameter.

```<code>let reader = new FileReader();
reader.onload = function(e) {
   console.log(reader.result);
}
reader.readAsText(path-to-image);
</code>```

where path-to-image (a string!) looks like '/tmp/blah/blah/image.jpg'. Perhaps there's something else besides FileReader(), but i have no idea what. can someone help this somewhat novice TypeScript coder?

Body:
ionic v6.20
angular v14

on iOS and Android i take a picture and am given the path to the image file. i simply want to read in that file and store the contents in a blob. sounds simple, but i've had no luck finding an example of doing just that. NOTE: storing the result in a BLOB is simple, i just need to read the contents of the image!

i've tried various functions that i found in "FileReader()", but they expect a BLOB as the parameter.

let reader = new FileReader();
reader.onload = function(e) {
   console.log(reader.result);
}
reader.readAsText(path-to-image);

where path-to-image (a string!) looks like '/tmp/blah/blah/image.jpg'. Perhaps there's something else besides FileReader(), but i have no idea what. can someone help this somewhat novice TypeScript coder?


问:
Date Hierarchy from calculated column - how?
I have a dashboard to convert - source needs to change from custom, local Excel file to a dataset and SQL Server table via DirectQuery. Excel file was created by exporting data from said dataset, which have been worked over.

Now, the problem is that I don't have date column available, all I can do is convert date_key (int) column into date, and I need a hierarchy to drill down in visuals from years to days.

This is what I have in table based off Excel:

This is what I have in table that I need to use:

Definition of Date:

```<code>Date = FORMAT(Date(Left('A'[date_key],4),Right(left('A'[date_key],6),2),right('A'[date_key],2)), "dd/mmmm/yyyy", "en-GB" )
</code>```

I can create additional columns to add to the hierarchy:

...and it sort of works, but visual is awful to read when drilling down:

 instead of

and of course converting month to name (January instead of 1) reorders them alpabetically...

Is there something to be done here, please?

Body:
I have a dashboard to convert - source needs to change from custom, local Excel file to a dataset and SQL Server table via DirectQuery. Excel file was created by exporting data from said dataset, which have been worked over.

Now, the problem is that I don't have date column available, all I can do is convert date_key (int) column into date, and I need a hierarchy to drill down in visuals from years to days.

This is what I have in table based off Excel:

This is what I have in table that I need to use:

Definition of Date:

Date = FORMAT(Date(Left('A'[date_key],4),Right(left('A'[date_key],6),2),right('A'[date_key],2)), "dd/mmmm/yyyy", "en-GB" )

I can create additional columns to add to the hierarchy:

...and it sort of works, but visual is awful to read when drilling down:

 instead of

and of course converting month to name (January instead of 1) reorders them alpabetically...

Is there something to be done here, please?


问:
How to prevent firestore from resetting Query data onDataChanged?
In my app, I added a filter functionality where I can get all students from a specific course and display the total results. The problem is that when I change something in the database, the total results displayed is not based on the query anymore.

```<code>private void load() {
    Query query = createQuery();
    FirestoreRecyclerOptions<Student> options = new FirestoreRecyclerOptions.Builder<Student>()
            .setQuery(query, Student.class)
            .build();

    myStudentAdapter = new MyStudentAdapter(options){
        @Override
        public void onDataChanged() {
            super.onDataChanged();
            tv_total.setText(String.valueOf(getItemCount()));
        }
    };
    rv.setAdapter(myStudentAdapter);
    myStudentAdapter.startListening();
}

private Query createQuery() {
    if (!search.isEmpty()) {
        if (!course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (!course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (!course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (!course.isEmpty() && year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else {
            return db.collection("Student")
                    .orderBy("fullName")
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        }
    } else {
        if (!course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block);
        } else if (!course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year);
        } else if (!course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("block", block);
        } else if (course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block);
        } else if (!course.isEmpty() && year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course);
        } else if (course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year);
        } else if (course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("block", block);
        } else {
            return db.collection("Student")
                    .orderBy("fullName");
        }
    }
}
</code>```

At first firestore returns 20 students (which is correct) but then I did a filter and return all BSCS students so firestore now returns 5 students (which is correct) but then I changed student1 fullName and now firestore returns 20 students (which is incorrect). I think firestore reset the Query information onDataChanged()

Body:
In my app, I added a filter functionality where I can get all students from a specific course and display the total results. The problem is that when I change something in the database, the total results displayed is not based on the query anymore.

private void load() {
    Query query = createQuery();
    FirestoreRecyclerOptions<Student> options = new FirestoreRecyclerOptions.Builder<Student>()
            .setQuery(query, Student.class)
            .build();

    myStudentAdapter = new MyStudentAdapter(options){
        @Override
        public void onDataChanged() {
            super.onDataChanged();
            tv_total.setText(String.valueOf(getItemCount()));
        }
    };
    rv.setAdapter(myStudentAdapter);
    myStudentAdapter.startListening();
}

private Query createQuery() {
    if (!search.isEmpty()) {
        if (!course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (!course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (!course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (!course.isEmpty() && year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else if (course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("block", block)
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        } else {
            return db.collection("Student")
                    .orderBy("fullName")
                    .startAt(search)
                    .endAt(search + '\uf8ff');
        }
    } else {
        if (!course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block);
        } else if (!course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("year", year);
        } else if (!course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course)
                    .whereEqualTo("block", block);
        } else if (course.isEmpty() && !year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year)
                    .whereEqualTo("block", block);
        } else if (!course.isEmpty() && year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("course", course);
        } else if (course.isEmpty() && !year.isEmpty() && block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("year", year);
        } else if (course.isEmpty() && year.isEmpty() && !block.isEmpty()) {
            return db.collection("Student")
                    .orderBy("fullName")
                    .whereEqualTo("block", block);
        } else {
            return db.collection("Student")
                    .orderBy("fullName");
        }
    }
}

At first firestore returns 20 students (which is correct) but then I did a filter and return all BSCS students so firestore now returns 5 students (which is correct) but then I changed student1 fullName and now firestore returns 20 students (which is incorrect). I think firestore reset the Query information onDataChanged()


问:
why does my vue client not receive websocket messages
I want to send messages via queue and topic to my frontend but it doesnt work, useing SOCKJS and STOMP. My backend logs, that new memeber subscribe, but when i send a message via convertAndSend or convertAndSendToUser nothing happens on the client side. pls help me. ty in advance. pls dont delete this question.

SERVER:
CONFIG:

@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
    config.enableSimpleBroker("/user", "/topic", "/queue");
    config.setApplicationDestinationPrefixes("/ws");
}

@Override
public void configureClientInboundChannel(final ChannelRegistration registration) {
    registration.interceptors(new UserInterceptor());
}

@Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
    registry.addEndpoint("/connect").setAllowedOriginPatterns("*").withSockJS();
}
```
<p>CONTROLLER:</p>
<pre class="lang-java prettyprint-override"><code>@Controller
@Slf4j
public class WebsocketController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    LobbyManagerService lobbyManagerService;

    @Autowired
    WebsocketService websocketService;
    final String newMember = "/queue/newMember/";
    final String lobbyDestination = "/topic/lobby/";

    @MessageMapping("/get/infos/on/join/{lobby}")
    public void getInfosOnJoinLobby(final SimpMessageHeaderAccessor sha, @DestinationVariable final String lobby) throws JsonProcessingException {
        log.info("Send lobby infos to newly joined player");
        final Message joinLobbyMessage = new JoinLobbyMessage(lobbyManagerService.getLobby(lobby).getPlayerNames());
        final MessageWrapper joinLobbyMessageWrapped = websocketService.wrapMessage(joinLobbyMessage, Purpose.JOIN_LOBBY_MESSAGE);
        simpMessagingTemplate.convertAndSendToUser(sha.getUser().getName(), newMember + lobby, joinLobbyMessageWrapped);
    }

    @MessageMapping("/lobby/{lobby}/join/team/{team}/player/{player}")
    public void joinTeam(@DestinationVariable final String lobby, @DestinationVariable final String team, @DestinationVariable final String player) throws JsonProcessingException {
        log.info("player '{}' joined team '{}' in lobby '{}'", player, team, lobby);
        final JoinTeamMessage joinTeamMessage = new JoinTeamMessage(team, player);
        final MessageWrapper joinTeamMessageWrapped = websocketService.wrapMessage(joinTeamMessage, Purpose.JOIN_TEAM_MESSAGE);
        simpMessagingTemplate.convertAndSend(lobbyDestination + lobby, joinTeamMessageWrapped);
    }

    @MessageMapping("/start/lobby/{lobby}")
    public void startLobby(@DestinationVariable final String lobby) {
        log.info("start lobby");
        //todo this methods will be implemented later
    }
}
</code>```

CLIENT:

function connect() {
  console.log("connect to lobby");
  return new Promise((resolve, reject) => {
    stompClientGame.value = Stomp.over(
      new SockJS("/minigames/towercrush/api/v1/connect")
    );
    let uuid = generateUUID();
    console.log("players uuid was: ", uuid);
    stompClientGame.value.connect(
      { player: player.value, lobby: lobby.value, userUUID: uuid },
      () => resolve(stompClientGame.value)
    );
  });
}

function connectToLobby() {
  connect()
    .then(() => {
      stompClientGame.value.subscribe(
        "/user/queue/newMember/" + lobby.value,
        function (messageOutput: any) {
          handleMessageReceipt(messageOutput.body);
        }
      );
    })
    .then(() => {
      stompClientGame.value.subscribe(
        "/topic/lobby/" + lobby.value,
        function (messageOutput: any) {
          handleMessageReceipt(messageOutput.body);
        }
      );
    });
}
```

i tryed literally every possible variation that came to my mind but nothing worked. pls help.

Body:
I want to send messages via queue and topic to my frontend but it doesnt work, useing SOCKJS and STOMP. My backend logs, that new memeber subscribe, but when i send a message via convertAndSend or convertAndSendToUser nothing happens on the client side. pls help me. ty in advance. pls dont delete this question.

SERVER:
CONFIG:

@Override
public void configureMessageBroker(final MessageBrokerRegistry config) {
    config.enableSimpleBroker("/user", "/topic", "/queue");
    config.setApplicationDestinationPrefixes("/ws");
}

@Override
public void configureClientInboundChannel(final ChannelRegistration registration) {
    registration.interceptors(new UserInterceptor());
}

@Override
public void registerStompEndpoints(final StompEndpointRegistry registry) {
    registry.addEndpoint("/connect").setAllowedOriginPatterns("*").withSockJS();
}

CONTROLLER:

@Controller
@Slf4j
public class WebsocketController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    LobbyManagerService lobbyManagerService;

    @Autowired
    WebsocketService websocketService;
    final String newMember = "/queue/newMember/";
    final String lobbyDestination = "/topic/lobby/";

    @MessageMapping("/get/infos/on/join/{lobby}")
    public void getInfosOnJoinLobby(final SimpMessageHeaderAccessor sha, @DestinationVariable final String lobby) throws JsonProcessingException {
        log.info("Send lobby infos to newly joined player");
        final Message joinLobbyMessage = new JoinLobbyMessage(lobbyManagerService.getLobby(lobby).getPlayerNames());
        final MessageWrapper joinLobbyMessageWrapped = websocketService.wrapMessage(joinLobbyMessage, Purpose.JOIN_LOBBY_MESSAGE);
        simpMessagingTemplate.convertAndSendToUser(sha.getUser().getName(), newMember + lobby, joinLobbyMessageWrapped);
    }

    @MessageMapping("/lobby/{lobby}/join/team/{team}/player/{player}")
    public void joinTeam(@DestinationVariable final String lobby, @DestinationVariable final String team, @DestinationVariable final String player) throws JsonProcessingException {
        log.info("player '{}' joined team '{}' in lobby '{}'", player, team, lobby);
        final JoinTeamMessage joinTeamMessage = new JoinTeamMessage(team, player);
        final MessageWrapper joinTeamMessageWrapped = websocketService.wrapMessage(joinTeamMessage, Purpose.JOIN_TEAM_MESSAGE);
        simpMessagingTemplate.convertAndSend(lobbyDestination + lobby, joinTeamMessageWrapped);
    }

    @MessageMapping("/start/lobby/{lobby}")
    public void startLobby(@DestinationVariable final String lobby) {
        log.info("start lobby");
        //todo this methods will be implemented later
    }
}

CLIENT:

function connect() {
  console.log("connect to lobby");
  return new Promise((resolve, reject) => {
    stompClientGame.value = Stomp.over(
      new SockJS("/minigames/towercrush/api/v1/connect")
    );
    let uuid = generateUUID();
    console.log("players uuid was: ", uuid);
    stompClientGame.value.connect(
      { player: player.value, lobby: lobby.value, userUUID: uuid },
      () => resolve(stompClientGame.value)
    );
  });
}

function connectToLobby() {
  connect()
    .then(() => {
      stompClientGame.value.subscribe(
        "/user/queue/newMember/" + lobby.value,
        function (messageOutput: any) {
          handleMessageReceipt(messageOutput.body);
        }
      );
    })
    .then(() => {
      stompClientGame.value.subscribe(
        "/topic/lobby/" + lobby.value,
        function (messageOutput: any) {
          handleMessageReceipt(messageOutput.body);
        }
      );
    });
}

i tryed literally every possible variation that came to my mind but nothing worked. pls help.


问:
VSCode automatically opens single subfolder in opened folder
so I have a folder structure like this folder structure expanded which is is a single folder "folderB" containing interesting data in a parent folder "folderA". I want to move folderB around by drag-and-drop mechanism within the VSCode explorer. If I therefore open folderA it automatically expands folderB and displays all of its content (see first image), which becomes annoying when folderB contains lots of files, so the rest of my folder structure is pushed out of the explorer window. The problem seems to be that VSCode tries to open all folders, if they are the only element of a parent folder.

How to prevent this, i.e., how to tell VSCode only to open the folder that I clicked on? Like this folder structure unexpanded, which so far I only achieve by manually closing folderB.

I found the explorer.compactFolder setting, which only controls the inlining of a single child folder with its parent folder, but nothing to prevent the behaviour described above.


问:
Results only show after select option change
I am making a ascii and binary translator app. What my code attempts to do is wait for selected option, puts the value to state, then checks it and runs corresponding function. After clicking the button the results show. I am getting a bug, where if I type in the text field, then press the button, nothing happens. Then, when I change the option, it will work as expected. I can even change back to the original option, and it will work as expected.</p>
```<code>const [text, setText] = useState("")
const [getFunction, setGetFunction]= useState();
const [results, setResults] = useState("");

function handleText(e){
  setText(e.target.value)
}

function a() {
  // some logic involving text state variable
  return {/*result of some logic*/};
}

function b() {
  // some logic involving text state variable
  return {/*result of some logic*/};
}

handleChange(e) {
  if (e.target.value == "a") {
    setGetFunction(a())
  }
  else if (e.target.value == "b") {
    setGetFunction(b())
  }
}

handleClick(e){
  e.preventDefault();
    setResults(getFunction)
}

return (
  <div>
    <form>
      <select onChange={handleChange}>
        <option value="a">a</option>
        <option value="b">b</option>
      </select>
      <textarea
          type="text"
          id="message"
          onChange={handleText}
          value={message}
        ></textarea>
      <button onClick={handleClick}></button>
    </form>
    <h2>{results}</h2>
  </div>
)

</code>```

Body:
I am making a ascii and binary translator app. What my code attempts to do is wait for selected option, puts the value to state, then checks it and runs corresponding function. After clicking the button the results show. I am getting a bug, where if I type in the text field, then press the button, nothing happens. Then, when I change the option, it will work as expected. I can even change back to the original option, and it will work as expected.

const [text, setText] = useState("")
const [getFunction, setGetFunction]= useState();
const [results, setResults] = useState("");

function handleText(e){
  setText(e.target.value)
}

function a() {
  // some logic involving text state variable
  return {/*result of some logic*/};
}

function b() {
  // some logic involving text state variable
  return {/*result of some logic*/};
}

handleChange(e) {
  if (e.target.value == "a") {
    setGetFunction(a())
  }
  else if (e.target.value == "b") {
    setGetFunction(b())
  }
}

handleClick(e){
  e.preventDefault();
    setResults(getFunction)
}

return (

    <form>
      <select onChange={handleChange}>
        <option value="a">a</option>
        <option value="b">b</option>
      </select>
      <textarea
          type="text"
          id="message"
          onChange={handleText}
          value={message}
        ></textarea>
      <button onClick={handleClick}></button>
    </form>

{results}

)


问:
how to stop scanf while the user is writing
i have this code and the user need to write a number in one second
the problem is i dont know how to stop the scanf after one second,

for example :
the user press enter to start
a timer will start in the same time
i want to break the while after one second
the problem is scanf doesnt stop after 1 second

ps :it works when the user doesnt enter anything.

```<code>
  int i = 0;
  int max = 0;
  int num;
  int counter = 0;

  while (i != 10) {

    char ch;
    printf("Hit enter when ready\n");
    fgetc(stdin);

    scanf("%c", &ch);

    if (ch == 0x0A || ch != 0x0A) {
      num = -1;
      DWORD start_time = GetTickCount();
      DWORD check_time = start_time + 1000;
      printf("ENTER KEY is pressed.\n");
      while ((check_time > GetTickCount())) {
        if (kbhit()) {
                //fflush(stdin);
          scanf("%d", &num);

          break;
        }
      }

      if (num == -1) {
        printf(" :(\n");
      } else {
        printf("%d\n", num);
        counter++;
        if (num > max)
          max = num;
      }

    }

    i++;
  }
  printf("you entred %d numbers\n", counter);
  printf("the biggest number is %d\n", max);
}```
```

Body:
i have this code and the user need to write a number in one second
the problem is i dont know how to stop the scanf after one second,

for example :
the user press enter to start
a timer will start in the same time
i want to break the while after one second
the problem is scanf doesnt stop after 1 second

ps :it works when the user doesnt enter anything.

  int i = 0;
  int max = 0;
  int num;
  int counter = 0;

  while (i != 10) {

    char ch;
    printf("Hit enter when ready\n");
    fgetc(stdin);

    scanf("%c", &ch);

    if (ch == 0x0A || ch != 0x0A) {
      num = -1;
      DWORD start_time = GetTickCount();
      DWORD check_time = start_time + 1000;
      printf("ENTER KEY is pressed.\n");
      while ((check_time > GetTickCount())) {
        if (kbhit()) {
                //fflush(stdin);
          scanf("%d", &num);

          break;
        }
      }

      if (num == -1) {
        printf(" :(\n");
      } else {
        printf("%d\n", num);
        counter++;
        if (num > max)
          max = num;
      }

    }

    i++;
  }
  printf("you entred %d numbers\n", counter);
  printf("the biggest number is %d\n", max);
}```


问:
angular 15 TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': String contains non ISO-8859-1 code point
Angular 15

```<code>import { HttpClient,HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Buffer } from 'buffer';
import { Observable } from "rxjs";

@Injectable({
    providedIn:'root'
})
export class InfoService{
    private baseUrl='http://aa.localhost.com:1616/abc/';
    constructor(private _http:HttpClient){}

    getInfor():Observable<any>{
        let headers = new HttpHeaders()
        .set('Content-Type','application/json')
        .set('Access-Control-Allow-Origin','*')
        .set('Authorization','Basic '+ Buffer.from('abc:abc123','base64'));

        console.log(headers.get('Authorization')); # shows Basic ��-�x-z�b�v

        return this._http.get(`${this.baseUrl+"test?id=101"}`,{
            'headers':headers
        });
    }

}
</code>```

get ERROR TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': String contains non ISO-8859-1 code point.

bota is deprecated

I do not find polyfills.ts on Angular 15, so I created it by my own and added

```<code>(window as any).global = window;

window.Buffer = window.Buffer || require('buffer').Buffer;
</code>```

it's not working.

also I installed Buffer package

and. added script to index.html, still not working

```<code>  <script>
    var global = global || window;
    var Buffer = Buffer || [];
    var process = process || {
      env: { DEBUG: undefined },
      version: []
    };
  </script>
</code>```

Body:
Angular 15

import { HttpClient,HttpHeaders } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Buffer } from 'buffer';
import { Observable } from "rxjs";

@Injectable({
    providedIn:'root'
})
export class InfoService{
    private baseUrl='http://aa.localhost.com:1616/abc/';
    constructor(private _http:HttpClient){}

    getInfor():Observable<any>{
        let headers = new HttpHeaders()
        .set('Content-Type','application/json')
        .set('Access-Control-Allow-Origin','*')
        .set('Authorization','Basic '+ Buffer.from('abc:abc123','base64'));

        console.log(headers.get('Authorization')); # shows Basic ��-�x-z�b�v

        return this._http.get(`${this.baseUrl+"test?id=101"}`,{
            'headers':headers
        });
    }

}

get ERROR TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': String contains non ISO-8859-1 code point.

bota is deprecated

I do not find polyfills.ts on Angular 15, so I created it by my own and added

(window as any).global = window;

window.Buffer = window.Buffer || require('buffer').Buffer;

it's not working.

also I installed Buffer package

and. added script to index.html, still not working


问:
How to return Custom Response for MaxUploadSizeExceededException during MultiPart File Upload Request?
I'm using a Spring Boot 2.7.5 Backend for a Multipart File Upload.

I want to return a Custom Response if the uploaded file exceeds the specified upload size limit in the configuration.

I originally tried using an ExceptionHandler in a ControllerAdvice as such:

```<code>    @ExceptionHandler(value = [MaxUploadSizeExceededException::class])
    fun handleSizeLimitExceededException(): ResponseEntity<Any> {
        val fileSizeMegabyte = multipartProperties.maxFileSize.toMegabytes().toString()
        val message = "The file is too big for the upload. Files are not allowed to be bigger than $fileSizeMegabyte MB"
        LOG.warn(message)
        return ResponseEntity(CustomErrorDto(FILE_TOO_LARGE, message, mapOf("maxFileSize" to fileSizeMegabyte)), HttpStatus.BAD_REQUEST)
    }
</code>```

Now this code gets executed, but it is ultimately ignored, as the Multipart Exception already gets handled (Connection Aborted) before the ControllerAdvice is even in play.

An exception occurred: java.lang.Throwable: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.lang.IllegalStateException: SRVE8021E: The file being uploaded is too large.

I tried using the spring.servlet.multipart.resolve-lazily: true property which seemed to work for some people in this thread here, as well as using an ErrorController (which is not applicable for my use case, as it is not a Spring MVC application)

Any hints will be much appreciated, so if you ever dealt with this or a similar issue, please let me know!

Thanks in advance!

Body:
I'm using a Spring Boot 2.7.5 Backend for a Multipart File Upload.

I want to return a Custom Response if the uploaded file exceeds the specified upload size limit in the configuration.

I originally tried using an ExceptionHandler in a ControllerAdvice as such:

    @ExceptionHandler(value = [MaxUploadSizeExceededException::class])
    fun handleSizeLimitExceededException(): ResponseEntity<Any> {
        val fileSizeMegabyte = multipartProperties.maxFileSize.toMegabytes().toString()
        val message = "The file is too big for the upload. Files are not allowed to be bigger than $fileSizeMegabyte MB"
        LOG.warn(message)
        return ResponseEntity(CustomErrorDto(FILE_TOO_LARGE, message, mapOf("maxFileSize" to fileSizeMegabyte)), HttpStatus.BAD_REQUEST)
    }

Now this code gets executed, but it is ultimately ignored, as the Multipart Exception already gets handled (Connection Aborted) before the ControllerAdvice is even in play.

An exception occurred: java.lang.Throwable: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Failed to parse multipart servlet request; nested exception is java.lang.IllegalStateException: SRVE8021E: The file being uploaded is too large.

I tried using the spring.servlet.multipart.resolve-lazily: true property which seemed to work for some people in this thread here, as well as using an ErrorController (which is not applicable for my use case, as it is not a Spring MVC application)

Any hints will be much appreciated, so if you ever dealt with this or a similar issue, please let me know!

Thanks in advance!


问:
Fibonacci Recursion with Python

I have the following exercise:

"Write a recursive function that prints the n-th number of the fibonacci sequence. The function parameters are 'n','current_number' [F(0)] and 'next_number' [F(1)]. [F(0)] and [F(1)] are the initial seeds of the sequence. Write the main program that ask user for the input parameters. Your code must output the result as follows.

```<code>fibon({n},{current_number},{next_number}) = {result}
fibon(5,4,5) = 37
fibon(5,0,1) = 5
fibon(10,0,1) = 55
</code>```

The following solution seems to work

def fibon(n, current_number, next_number):
    #print(f'n is {n} from the outset')
    if n == 0:
        #print('n == 0 is true')
        return current_number
    elif n == 1:
        #print('n == 1 is true')
        return next_number
    else:
        n = n-1
        #print(f'this is n-1 {fibon(n-1, current_number, next_number)}')
        #print(f'this is n {fibon(n, current_number, next_number)}')
        fib= fibon(n-1, current_number, next_number) + fibon(n, current_number, next_number)
        #print(fib)
        return(fib)
```

However, I don't understand how 'fibon' is returning the value of nth number in fibonacci series. It is a recursive function and I don't understand how every time it loops, it gets the fibonacci number for the nth position. If you look at the code, " fibon(n-1, current_number, next_number) + fibon(n, current_number, next_number)" can only return a number when n== 1 or n==0. If so, how it can reutrn other numbers in the position when they are not in the 1th or 0 position?

I am not sure if I made a lot of sense but I tried to express my confusin. Thanks in advance!

The code is working but I do not seem to understand why it is working. You can also propose a better solution if there is one. Thank you very much!

Title: Fibonacci Recursion with Python

Body:
I have the following exercise:

"Write a recursive function that prints the n-th number of the fibonacci sequence. The function parameters are 'n','current_number' [F(0)] and 'next_number' [F(1)]. [F(0)] and [F(1)] are the initial seeds of the sequence. Write the main program that ask user for the input parameters. Your code must output the result as follows.

fibon({n},{current_number},{next_number}) = {result}
fibon(5,4,5) = 37
fibon(5,0,1) = 5
fibon(10,0,1) = 55

The following solution seems to work

def fibon(n, current_number, next_number):
    #print(f'n is {n} from the outset')
    if n == 0:
        #print('n == 0 is true')
        return current_number
    elif n == 1:
        #print('n == 1 is true')
        return next_number
    else:
        n = n-1
        #print(f'this is n-1 {fibon(n-1, current_number, next_number)}')
        #print(f'this is n {fibon(n, current_number, next_number)}')
        fib= fibon(n-1, current_number, next_number) + fibon(n, current_number, next_number)
        #print(fib)
        return(fib)

However, I don't understand how 'fibon' is returning the value of nth number in fibonacci series. It is a recursive function and I don't understand how every time it loops, it gets the fibonacci number for the nth position. If you look at the code, " fibon(n-1, current_number, next_number) + fibon(n, current_number, next_number)" can only return a number when n== 1 or n==0. If so, how it can reutrn other numbers in the position when they are not in the 1th or 0 position?

I am not sure if I made a lot of sense but I tried to express my confusin. Thanks in advance!

The code is working but I do not seem to understand why it is working. You can also propose a better solution if there is one. Thank you very much!


问:
Deploy Manual only after approval in Gitlab
We have two stages , Build and deploy in our project.

Every time user creates a merge request from Feature branch to Master(PROD) ,it starts the pipeline with the build stage and stops for manual action to deploy.

Approval is only set for merge request and  after the pipeline is successful it would merge to master.But the developer/approver can start the manual action to deploy without even merge request approval .

I want the user or approver to click the manual button only after the merge request is approved. Is it possible to control this or can i add a stage in-between only for approval?

```<code>deploy prod:
  <<: *deploy
  stage: deploy prod
  environment: PROD
  extends: .dockerprod
  when: manual
</code>```

Body:
We have two stages , Build and deploy in our project.

Every time user creates a merge request from Feature branch to Master(PROD) ,it starts the pipeline with the build stage and stops for manual action to deploy.

Approval is only set for merge request and  after the pipeline is successful it would merge to master.But the developer/approver can start the manual action to deploy without even merge request approval .

I want the user or approver to click the manual button only after the merge request is approved. Is it possible to control this or can i add a stage in-between only for approval?

deploy prod:
  <<: *deploy
  stage: deploy prod
  environment: PROD
  extends: .dockerprod
  when: manual


问:
TypeError: Cannot read properties of undefined (reading 'toString') react and redux
Hi I am a bit of a noob at fixing react issues. I have a page that dispatches items from strapi using redux, but is not returning items, instead throws undefined error.

I know its to do with the async await, think it needs some kind of option chaining in useEffect but don't know how to add this
thanks.

const ShoppingList = () => {
    const dispatch = useDispatch()
    const [value, setValue] = useState("all")
    const items = useSelector((state) => state.cart.items)
    const isNonMobile = useMediaQuery("(min-width: 600px)")
    console.log(items)

    const handleChange = (event, newValue) => {
        setValue(newValue)
    }

    async function getItems() {
        const items = await fetch(
            "http://localhost:1337/api/items?populate=image",
            {method: "GET"}
        )
        const itemsJson = await items.json()
        dispatch(setItems(itemsJson.data))
    }

    useEffect(()=> {
            getItems()

    }, []) //eslint-disable-line react-hooks/exhaustive-deps

    const topRatedItems = items.filter(
        (item)=> item.attributes.category === "topRated"
    )
    const newArrivalsItems = items.filter(
        (item)=> item.attributes.category === "newArrivals"
    )
    const bestSellersItems = items.filter(
        (item)=> item.attributes.category === "bestSellers"
    )```


问:
Google cloud Logs: do not mark "Invalid request, unable to process." as an Error
I have a Firebase Function defined as a callable reference.
So it's available to my Firebase App, but not to anyone with the link, like a HTTP request would be.

exports.myFunFunction = functions
.runWith({
  memory: '256MB',
})
.https.onCall(async (data, context) => {
  // doesn't matter
})
```
<p>The annoying part happens when someone or something tries to access my function through its URL. The request fails, as it should. But it also causes a log of 'severity: "ERROR"' in Google Cloud logging, which causes an alert in Slack and sends an email to the team, basically it's a Boy Who Cried Wolf situation.</p>
<p>I don't seem to have much control over the way the error is thrown and its severity level.
Since it's thrown before reaching my code.</p>
<p>The only thing I can think of is to refine what triggers alerts in Slack, email etc. to exclude these errors, but the error is so vague I'd rather not filter out every log with the <code>"textPayload": "Invalid request, unable to process."</code>.</p>
<p>Also, as far as I'm concerned, the function failing on these cases is the desired behavior, not an error.</p>
<p>Any ideas as to how I could control the Error thrown by Google?</p>
<p>The full error log looks like this.</p>
<pre class="lang-json prettyprint-override"><code>{
  "textPayload": "Invalid request, unable to process.",
  "insertId": "6390a8060000foo5e8foobar",
  "resource": {
    "type": "cloud_function",
    "labels": {
      "region": "us-central1",
      "function_name": "myFunFunction",
      "project_id": "myFunProject"
    }
  },
  "timestamp": "2022-12-07T14:49:42.056773Z",
  "severity": "ERROR",
  "labels": {
    "execution_id": "tsx3lffoobar",
    "instance_id": "00c61b117cae46cf4a674fbb94f3a5af3699484833a15105927db5dd99a1240e23e896be8ef292d6273b9c0da5f5b8f13913567c854152foobar"
  },
  "logName": "projects/myFunProject/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
  "trace": "projects/myFunProject/traces/d17269042ad8c98da19ac1b0c3foobar",
  "receiveTimestamp": "2022-12-07T14:49:42.242663699Z"
}
</code>```

and it happens right after a warning, which I wouldn't mind keeping:

{
  "textPayload": "Request has incorrect Content-Type. ",
  "insertId": "6390a8060000dce76bfoobar",
  "resource": {
    "type": "cloud_function",
    "labels": {
      "region": "us-central1",
      "project_id": "myFunProject",
      "function_name": "myFunFunction"
    }
  },
  "timestamp": "2022-12-07T14:49:42.056551Z",
  "severity": "WARNING",
  "labels": {
    "instance_id": "00c61b117cae46cf4a674fbb94f3a5af3699484833a15105927db5dd99a1240e23e896be8ef292d6273b9c0da5f5b8f13913567c854152foobar",
    "execution_id": "tsx3lffoobar"
  },
  "logName": "projects/myFunProject/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
  "trace": "projects/myFunProject/traces/d17269042ad8c98da19ac1b0c3foobar",
  "receiveTimestamp": "2022-12-07T14:49:42.242663699Z"
}
```

Body:
I have a Firebase Function defined as a callable reference.
So it's available to my Firebase App, but not to anyone with the link, like a HTTP request would be.

exports.myFunFunction = functions
.runWith({
  memory: '256MB',
})
.https.onCall(async (data, context) => {
  // doesn't matter
})

The annoying part happens when someone or something tries to access my function through its URL. The request fails, as it should. But it also causes a log of 'severity: "ERROR"' in Google Cloud logging, which causes an alert in Slack and sends an email to the team, basically it's a Boy Who Cried Wolf situation.

I don't seem to have much control over the way the error is thrown and its severity level.
Since it's thrown before reaching my code.

The only thing I can think of is to refine what triggers alerts in Slack, email etc. to exclude these errors, but the error is so vague I'd rather not filter out every log with the "textPayload": "Invalid request, unable to process.".

Also, as far as I'm concerned, the function failing on these cases is the desired behavior, not an error.

Any ideas as to how I could control the Error thrown by Google?

The full error log looks like this.

{
  "textPayload": "Invalid request, unable to process.",
  "insertId": "6390a8060000foo5e8foobar",
  "resource": {
    "type": "cloud_function",
    "labels": {
      "region": "us-central1",
      "function_name": "myFunFunction",
      "project_id": "myFunProject"
    }
  },
  "timestamp": "2022-12-07T14:49:42.056773Z",
  "severity": "ERROR",
  "labels": {
    "execution_id": "tsx3lffoobar",
    "instance_id": "00c61b117cae46cf4a674fbb94f3a5af3699484833a15105927db5dd99a1240e23e896be8ef292d6273b9c0da5f5b8f13913567c854152foobar"
  },
  "logName": "projects/myFunProject/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
  "trace": "projects/myFunProject/traces/d17269042ad8c98da19ac1b0c3foobar",
  "receiveTimestamp": "2022-12-07T14:49:42.242663699Z"
}

and it happens right after a warning, which I wouldn't mind keeping:

{
  "textPayload": "Request has incorrect Content-Type. ",
  "insertId": "6390a8060000dce76bfoobar",
  "resource": {
    "type": "cloud_function",
    "labels": {
      "region": "us-central1",
      "project_id": "myFunProject",
      "function_name": "myFunFunction"
    }
  },
  "timestamp": "2022-12-07T14:49:42.056551Z",
  "severity": "WARNING",
  "labels": {
    "instance_id": "00c61b117cae46cf4a674fbb94f3a5af3699484833a15105927db5dd99a1240e23e896be8ef292d6273b9c0da5f5b8f13913567c854152foobar",
    "execution_id": "tsx3lffoobar"
  },
  "logName": "projects/myFunProject/logs/cloudfunctions.googleapis.com%2Fcloud-functions",
  "trace": "projects/myFunProject/traces/d17269042ad8c98da19ac1b0c3foobar",
  "receiveTimestamp": "2022-12-07T14:49:42.242663699Z"
}


问:
fitting the best distribution for every column in df
I have the following code that fits the best distribution to a specific column in a df
and it works fine when I run in for a single column, but when I created a function to loop threw all columns in the df it keeps fitting in an endless loop, can anyone see the problem?

```<code>def fit_des (column):
    lens_calibration = df[column].values
    f = Fitter(lens_calibration,
               distributions=['alpha',
                                 'anglit','arcsine','argus','beta','betaprime','bradford','burr','burr12','cauchy','chi','chi2','cosine','crystalball',
                                 'dgamma', 'dweibull', 'erlang', 'expon', 'exponnorm', 'exponpow', 'exponweib', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'gamma', 'gausshyper', 'genexpon', 'genextreme', 'gengamma',
                                 'genhalflogistic', 'geninvgauss', 'genlogistic', 'gennorm', 'genpareto', 'gilbrat', 'gompertz', 'gumbel_l', 'gumbel_r', 'halfcauchy', 'halfgennorm', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb','johnsonsu',
                                 'kappa3', 'kappa4', 'ksone', 'kstwo', 'kstwobign', 'laplace', 'laplace_asymmetric', 'levy', 'levy_l', 'levy_stable', 'loggamma', 'logistic', 'loglaplace',
                                 'lognorm', 'loguniform', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncf', 'nct', 'ncx2', 'norm', 'norminvgauss', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rayleigh','rdist',
                                 'recipinvgauss', 'reciprocal', 'rice', 'rv_continuous', 'rv_histogram', 'semicircular', 'skewnorm', 't', 'trapezoid', 'trapz', 'triang','truncexpon','truncnorm','tukeylambda','uniform','vonmises','vonmises_line','wald','weibull_max','weibull_min','wrapcauchy'])
    f.fit()
    f.summary()
    f.get_best(method = 'sumsquare_error')

for column in df:
    fit_des(column)
</code>```

output when it runs in a function

Body:
I have the following code that fits the best distribution to a specific column in a df
and it works fine when I run in for a single column, but when I created a function to loop threw all columns in the df it keeps fitting in an endless loop, can anyone see the problem?

def fit_des (column):
    lens_calibration = df[column].values
    f = Fitter(lens_calibration,
               distributions=['alpha',
                                 'anglit','arcsine','argus','beta','betaprime','bradford','burr','burr12','cauchy','chi','chi2','cosine','crystalball',
                                 'dgamma', 'dweibull', 'erlang', 'expon', 'exponnorm', 'exponpow', 'exponweib', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'gamma', 'gausshyper', 'genexpon', 'genextreme', 'gengamma',
                                 'genhalflogistic', 'geninvgauss', 'genlogistic', 'gennorm', 'genpareto', 'gilbrat', 'gompertz', 'gumbel_l', 'gumbel_r', 'halfcauchy', 'halfgennorm', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb','johnsonsu',
                                 'kappa3', 'kappa4', 'ksone', 'kstwo', 'kstwobign', 'laplace', 'laplace_asymmetric', 'levy', 'levy_l', 'levy_stable', 'loggamma', 'logistic', 'loglaplace',
                                 'lognorm', 'loguniform', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncf', 'nct', 'ncx2', 'norm', 'norminvgauss', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rayleigh','rdist',
                                 'recipinvgauss', 'reciprocal', 'rice', 'rv_continuous', 'rv_histogram', 'semicircular', 'skewnorm', 't', 'trapezoid', 'trapz', 'triang','truncexpon','truncnorm','tukeylambda','uniform','vonmises','vonmises_line','wald','weibull_max','weibull_min','wrapcauchy'])
    f.fit()
    f.summary()
    f.get_best(method = 'sumsquare_error')

for column in df:
    fit_des(column)

output when it runs in a function