问:
Error when using Vgg16 output and adding extra custom layers. ValueError: Error when checking input
I am trying to take the outputs of images (train and validation) passed through a Vgg16 network with include_top = false , and then adding the final few layers as can be seen in the code below.

I want x to store the complete model so that I can create a tflite file out of it(including vgg and the layers being added by me)

```<code>from tensorflow.keras.models import Model
import os

x= vgg16.output
print(x.shape)
x = GlobalAveragePooling2D()(x)

x = Flatten()(x)
x = Dense(100)(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = (Dropout(0.5)) (x)
x = (Dense(50)) (x)
x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
x = Dropout(0.3)(x)
x = Dense(num_classes, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=vgg16.input, outputs=x)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in vgg16.layers:
    layer.trainable = False

model.compile(loss='categorical_crossentropy',
   optimizer=optimizers.RMSprop(lr=1e-4),
   metrics=['acc'])

# train the model on the new data for a few epochs
history = model.fit(train_data, train_labels,
   epochs=15,
   batch_size=batch_size,
   validation_data=(validation_data, validation_labels))

model.save(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
    validation_data, validation_labels, batch_size=batch_size, verbose=1)
</code>```

The output of x.shape is (?, ?, ?, 512)

train_data.shape (1660, 2, 2, 512)

train_labels.shape (1660, 4)

validation_data.shape (137, 4)

validation_labels.shape (137, 2, 2, 512)

Error:

ValueError: Error when checking input: expected input_3 to have shape (None, None, 3) but got array with shape (2, 2, 512)

This error occurs on the line:

52    validation_data=(validation_data, validation_labels))

A previous code snippet as seen below works perfectly fine and gives accurate outputs. train_data stores a numpy array of vgg16.predict_generator()

```<code>
model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(100))
model.add(tf.keras.layers.LeakyReLU(alpha=0.2))
model.add(Dropout(0.5))
model.add(Dense(50))
model.add(tf.keras.layers.LeakyReLU(alpha=0.3))
model.add(Dropout(0.3))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
   optimizer=optimizers.RMSprop(lr=1e-4),
   metrics=['acc'])
history = model.fit(train_data, train_labels,
   epochs=15,
   batch_size=batch_size,
   validation_data=(validation_data, validation_labels),
   callbacks =[tensorboard])
model.save(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
    validation_data, validation_labels, batch_size=batch_size,     verbose=1)
print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
print("[INFO] Loss: {}".format(eval_loss))
</code>```

This step for passing all the images (train, validation, test; here only train is shown) through vgg16 is done for both the above snippets of code

```<code>train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
test_data_dir = 'data/test'

# number of epochs to train top model
epochs = 7 #this has been changed after multiple model run
# batch size used by flow_from_directory and predict_generator
batch_size = 32

#Loading vgc16 model
vgg16 = applications.VGG16(include_top=False, weights='imagenet')
datagen = ImageDataGenerator(rescale=1. / 255)
generator = datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode=None,
    shuffle=False)

nb_train_samples = len(generator.filenames)
num_classes = len(generator.class_indices)

predict_size_train = int(math.ceil(nb_train_samples / batch_size))

train_data = vgg16.predict_generator(generator, predict_size_train)
</code>```

答:
Well...

You defined the target_size=(img_width, img_height) and if (img_width, img_height) is not (224, 224) then you need also do define target_size in the VGG model:

vgg16 = applications.VGG16(
  include_top=False,
  weights='imagenet',
  target_size=(img_width, img_height, 3))
```

<ol start="2">
<li><p>Why do you use <code>class_mode=None</code> in the <code>datagen.flow_from_directory</code>? <code>None</code> is a default value. If you want to make it <em>categorical</em> write <code>class_mode='categorical'</code>, but using <code>class_mode=None</code> doesn't make sense at all.</p></li>
<li><p><code>predict_generator</code> returns predictions. Right now <code>predict_generator</code> is deprecated, but you can use <code>predict</code> which works OK with generators. But <code>predict</code> should be used after training. The right way of using generators is:</p></li>
</ol>

<pre class="lang-py prettyprint-override"><code>datagen = ImageDataGenerator(rescale=1. / 255)
generator = datagen.flow_from_directory(
  train_data_dir,
  target_size=(img_width, img_height),
  batch_size=batch_size,
  shuffle=False)
// ...
history = model.fit(
  generator,
  epochs=15,
  steps_per_epoch=len(generator),
  batch_size=batch_size,
  validation_data=validation_generator,
  validation_steps=len(validation_generator))
</code>```

and later, if you want to make a prediction use: model.predict(test_generator)

You don't need to use Flatten after GlobalAveragePooling2D in this case. GlobalAveragePooling2D will reduce output to a 1D array.

Body:
I am trying to take the outputs of images (train and validation) passed through a Vgg16 network with include_top = false , and then adding the final few layers as can be seen in the code below.

I want x to store the complete model so that I can create a tflite file out of it(including vgg and the layers being added by me)

from tensorflow.keras.models import Model
import os

x= vgg16.output
print(x.shape)
x = GlobalAveragePooling2D()(x)

x = Flatten()(x)
x = Dense(100)(x)
x = tf.keras.layers.LeakyReLU(alpha=0.2)(x)
x = (Dropout(0.5)) (x)
x = (Dense(50)) (x)
x = tf.keras.layers.LeakyReLU(alpha=0.3)(x)
x = Dropout(0.3)(x)
x = Dense(num_classes, activation='softmax')(x)

# this is the model we will train
model = Model(inputs=vgg16.input, outputs=x)

# first: train only the top layers (which were randomly initialized)
# i.e. freeze all convolutional InceptionV3 layers
for layer in vgg16.layers:
    layer.trainable = False

model.compile(loss='categorical_crossentropy',
   optimizer=optimizers.RMSprop(lr=1e-4),
   metrics=['acc'])

# train the model on the new data for a few epochs
history = model.fit(train_data, train_labels,
   epochs=15,
   batch_size=batch_size,
   validation_data=(validation_data, validation_labels))

model.save(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
    validation_data, validation_labels, batch_size=batch_size, verbose=1)

The output of x.shape is (?, ?, ?, 512)

train_data.shape (1660, 2, 2, 512)

train_labels.shape (1660, 4)

validation_data.shape (137, 4)

validation_labels.shape (137, 2, 2, 512)

Error:

ValueError: Error when checking input: expected input_3 to have shape (None, None, 3) but got array with shape (2, 2, 512)

This error occurs on the line:

52    validation_data=(validation_data, validation_labels))

A previous code snippet as seen below works perfectly fine and gives accurate outputs. train_data stores a numpy array of vgg16.predict_generator()

model = Sequential()
model.add(Flatten(input_shape=train_data.shape[1:]))
model.add(Dense(100))
model.add(tf.keras.layers.LeakyReLU(alpha=0.2))
model.add(Dropout(0.5))
model.add(Dense(50))
model.add(tf.keras.layers.LeakyReLU(alpha=0.3))
model.add(Dropout(0.3))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
   optimizer=optimizers.RMSprop(lr=1e-4),
   metrics=['acc'])
history = model.fit(train_data, train_labels,
   epochs=15,
   batch_size=batch_size,
   validation_data=(validation_data, validation_labels),
   callbacks =[tensorboard])
model.save(top_model_weights_path)
(eval_loss, eval_accuracy) = model.evaluate(
    validation_data, validation_labels, batch_size=batch_size,     verbose=1)
print("[INFO] accuracy: {:.2f}%".format(eval_accuracy * 100))
print("[INFO] Loss: {}".format(eval_loss))

This step for passing all the images (train, validation, test; here only train is shown) through vgg16 is done for both the above snippets of code

train_data_dir = 'data/train'
validation_data_dir = 'data/validation'
test_data_dir = 'data/test'

# number of epochs to train top model
epochs = 7 #this has been changed after multiple model run
# batch size used by flow_from_directory and predict_generator
batch_size = 32

#Loading vgc16 model
vgg16 = applications.VGG16(include_top=False, weights='imagenet')
datagen = ImageDataGenerator(rescale=1. / 255)
generator = datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode=None,
    shuffle=False)

nb_train_samples = len(generator.filenames)
num_classes = len(generator.class_indices)

predict_size_train = int(math.ceil(nb_train_samples / batch_size))

train_data = vgg16.predict_generator(generator, predict_size_train)

Body:
Well...

You defined the target_size=(img_width, img_height) and if (img_width, img_height) is not (224, 224) then you need also do define target_size in the VGG model:

vgg16 = applications.VGG16(
  include_top=False,
  weights='imagenet',
  target_size=(img_width, img_height, 3))

Why do you use class_mode=None in the datagen.flow_from_directory? None is a default value. If you want to make it categorical write class_mode='categorical', but using class_mode=None doesn't make sense at all.

predict_generator returns predictions. Right now predict_generator is deprecated, but you can use predict which works OK with generators. But predict should be used after training. The right way of using generators is:

datagen = ImageDataGenerator(rescale=1. / 255)
generator = datagen.flow_from_directory(
  train_data_dir,
  target_size=(img_width, img_height),
  batch_size=batch_size,
  shuffle=False)
// ...
history = model.fit(
  generator,
  epochs=15,
  steps_per_epoch=len(generator),
  batch_size=batch_size,
  validation_data=validation_generator,
  validation_steps=len(validation_generator))

and later, if you want to make a prediction use: model.predict(test_generator)

You don't need to use Flatten after GlobalAveragePooling2D in this case. GlobalAveragePooling2D will reduce output to a 1D array.


来源: stackexchange

问:
S4 exports specified in 'NAMESPACE' but not defined in package
I just finished some minor updates to an R package I've had on CRAN for a few years (haven't had to update in a while).  My package passes Check on my local machine and on winbuilder, but it just bounced back from CRAN with the message

```<code>checking whether package 'riverdist' can be installed ... WARNING
Found the following significant warnings:
  Warning: S4 exports specified in 'NAMESPACE' but not defined in package 'riverdist'
</code>```

I use roxygen2 to build my package NAMESPACE and don't have any S4 exports that I'm aware of.

Perhaps this might be related to changes in R version 4.0.0?

If anyone's encountered this error, I'd love to hear how you were able to resolve it.  Thanks!

答:
I received this message from rdevel

"This is a new check in R-devel. The NEWS say:

R CMD check etc now warn when a package exports non-existing S4 classes or methods, also in case of no "methods" presence

In your case, the NAMESPACE contains

exportClasses(classify)

exportClasses(gonad_mature)

exportClasses(morphMat)

but your package does not define these S4 classes.

You seem to instruct roxygen2 to create these invalid directives using
@exportClass tags manually instead of just @export. Simply remove these
wrong @exportClass tags from your source files and regenerate your
NAMESPACE.

Best regards,

```<code>    Sebastian Meyer"
</code>```

https://www.mail-archive.com/r-package-devel@r-project.org/msg05436.html

ContentLicense: CC BY-SA 4.0

Body:
I just finished some minor updates to an R package I've had on CRAN for a few years (haven't had to update in a while).  My package passes Check on my local machine and on winbuilder, but it just bounced back from CRAN with the message

checking whether package 'riverdist' can be installed ... WARNING
Found the following significant warnings:
  Warning: S4 exports specified in 'NAMESPACE' but not defined in package 'riverdist'

I use roxygen2 to build my package NAMESPACE and don't have any S4 exports that I'm aware of.

Perhaps this might be related to changes in R version 4.0.0?

If anyone's encountered this error, I'd love to hear how you were able to resolve it.  Thanks!

Body:
I received this message from rdevel

"This is a new check in R-devel. The NEWS say:

R CMD check etc now warn when a package exports non-existing S4 classes or methods, also in case of no "methods" presence

In your case, the NAMESPACE contains

exportClasses(classify)

exportClasses(gonad_mature)

exportClasses(morphMat)

but your package does not define these S4 classes.

You seem to instruct roxygen2 to create these invalid directives using
@exportClass tags manually instead of just @export. Simply remove these
wrong @exportClass tags from your source files and regenerate your
NAMESPACE.

Best regards,

    Sebastian Meyer"

https://www.mail-archive.com/r-package-devel@r-project.org/msg05436.html


问:
AWS Ampify console preview build from a forked branch
We have an app in AWS Amplify that has previews enabled for it.

Devs fork our github repo, create a branch in that fork and issue a pull request from that forked branch into the upstream master branch.  This doesn't trigger the preview build in Amplify.  Has anyone tried this?

It seems to work fine with PR from a branch within the repo, but not a forked version.  The other wrinkle is that we have other checks/webhooks that run on PR as well.

答:
It looks like this is not supported at the moment, but there is a GitHub issue tracking the feature request: https://github.com/aws-amplify/amplify-console/issues/508

We mainly use a fork / PR workflow, so this would be a big help for us too.


问:
Checking for TextField changes once a form was submitted in Coldfusion
I have code that displays database entries, and allows for editing/deletion.

I am trying to find some way on submission to see if a particular field has been changed, so if the old data of the field is not referenced by any database entries, I can delete it. Any ideas on how to do this?

To respond to the first comment / Edit: It is somewhat hard to put code of this problem up here, but I will try to grab some snippets that help.

```<code><td>Upload File:</td>
<td>
    <input type="file" name="txtName" size="50" />
</td>
<cfif url.filesid neq "0">
<td>Or Use Server File:</td>
    <td>
    <select name="ddlFilesNames">
        <option value="" selected></option>
            <cfoutput query="qfiles">
                <option
                  value="#qfiles.name#"
                  #iif(qfiles.name eq recEditFiles.fileName,DE("selected"),DE(""))#
                >#qfiles.name#</option>
            </cfoutput>
    </select>
    </td>
</cfif>
</code>```

These are the two fields I need to check if they changed, when the edit button is hit the select drop down list has the current server file displayed, but during editing they can either add a file to the textfield (through a browse option to upload a new file) or they can select another file from the dropdown list, and then hit an update button that submits the changes.

When the update button is hit I need to somehow check to see if the fields were changed at all.

I feel that one of the main problems is that once the button is hit, a javascript method is called, and so far I have been unsuccessful is lacing coldfusion within javascript methods, everytime I try to do this or visa-versa it breaks the program.

答:
A simple way to compare whether fields on a form have changed from the original is to include the original data in a hidden form field then on the action page compare the values of the form field and its hidden counterpart and see if they've changed.

form:

```<code><input type="text" name="myField" value="#q.myField#" />
<input type="hidden" name="myField_original" value="#q.myField#" />
</code>```

action:

```<code><cfif form.myField NEQ form.myField_original>
  <cfset fieldHasChanged = true />
<cfelse>
  <cfset fieldHasChanged = false />
</cfif>
</code>```

If you're consistent with form field names it'll be easy to create a loop on the action page to do these comparisons.

ContentLicense: CC BY-SA 3.0

Body:
I have code that displays database entries, and allows for editing/deletion.

I am trying to find some way on submission to see if a particular field has been changed, so if the old data of the field is not referenced by any database entries, I can delete it. Any ideas on how to do this?

To respond to the first comment / Edit: It is somewhat hard to put code of this problem up here, but I will try to grab some snippets that help.

Upload File:

    <input type="file" name="txtName" size="50" />

<cfif url.filesid neq "0">
Or Use Server File:

    <select name="ddlFilesNames">
        <option value="" selected></option>
            <cfoutput query="qfiles">
                <option
                  value="#qfiles.name#"
                  #iif(qfiles.name eq recEditFiles.fileName,DE("selected"),DE(""))#
                >#qfiles.name#</option>
            </cfoutput>
    </select>

</cfif>

These are the two fields I need to check if they changed, when the edit button is hit the select drop down list has the current server file displayed, but during editing they can either add a file to the textfield (through a browse option to upload a new file) or they can select another file from the dropdown list, and then hit an update button that submits the changes.

When the update button is hit I need to somehow check to see if the fields were changed at all.

I feel that one of the main problems is that once the button is hit, a javascript method is called, and so far I have been unsuccessful is lacing coldfusion within javascript methods, everytime I try to do this or visa-versa it breaks the program.

Body:
A simple way to compare whether fields on a form have changed from the original is to include the original data in a hidden form field then on the action page compare the values of the form field and its hidden counterpart and see if they've changed.

form:

<input type="text" name="myField" value="#q.myField#" />
<input type="hidden" name="myField_original" value="#q.myField#" />

action:

<cfif form.myField NEQ form.myField_original>
  <cfset fieldHasChanged = true />
<cfelse>
  <cfset fieldHasChanged = false />
</cfif>

If you're consistent with form field names it'll be easy to create a loop on the action page to do these comparisons.


问:
Tensorflow 2.2.0 gather maximum elements over one dimension
I have the following problem:

I have a tensor of shape (1600, 29) and I want to obtain the maximum of axis 1. The result should be a (1600, 1) tensor. For simplification I will use a (5,3) tensor to demonstrate my problem:

```<code>B = tf.constant([[2, 20, 30],
                 [2, 7, 6],
                 [3, 11, 16],
                 [19, 1, 8],
                 [14, 45, 23]])

x = x = tf.math.argmax(B, 1) --> 5 Values [2 1 2 0 1]
z = tf.gather(B, x, axis=1) --> Shape: (5,5) [[30 20 30  2 20]
                                              [ 6  7  6  2  7]
                                              [16 11 16  3 11]
                                              [ 8  1  8 19  1]
                                              [23 45 23 14 45]]
</code>```

Okay, now, x gives me the maximum element over my axis, however, tf.gather does not return [30, 7, 16, 19, 45], but some weird tensor. How do I "reduce" the dimension properly?

My "rather" dirty way is this:

```<code>eye_z = tf.eye(5, 5)

intermed_result = z*eye_z

result = tf.linalg.matvec(intermed_result,tf.transpose(tf.constant([1,1,1,1,1], dtype=tf.float32)))
</code>```

Which results in the correct tensor: [30.  7. 16. 19. 45.]

答:
You have tf.math.reduce_max for this:

```<code>m = tf.math.reduce_max(B, axis=1)

sess = tf.InteractiveSession()
sess.run(m)
# array([30,  7, 16, 19, 45])
</code>```

Body:
I have the following problem:

I have a tensor of shape (1600, 29) and I want to obtain the maximum of axis 1. The result should be a (1600, 1) tensor. For simplification I will use a (5,3) tensor to demonstrate my problem:

B = tf.constant([[2, 20, 30],
                 [2, 7, 6],
                 [3, 11, 16],
                 [19, 1, 8],
                 [14, 45, 23]])

x = x = tf.math.argmax(B, 1) --> 5 Values [2 1 2 0 1]
z = tf.gather(B, x, axis=1) --> Shape: (5,5) [[30 20 30  2 20]
                                              [ 6  7  6  2  7]
                                              [16 11 16  3 11]
                                              [ 8  1  8 19  1]
                                              [23 45 23 14 45]]

Okay, now, x gives me the maximum element over my axis, however, tf.gather does not return [30, 7, 16, 19, 45], but some weird tensor. How do I "reduce" the dimension properly?

My "rather" dirty way is this:

eye_z = tf.eye(5, 5)

intermed_result = z*eye_z

result = tf.linalg.matvec(intermed_result,tf.transpose(tf.constant([1,1,1,1,1], dtype=tf.float32)))

Which results in the correct tensor: [30.  7. 16. 19. 45.]

Body:
You have tf.math.reduce_max for this:

m = tf.math.reduce_max(B, axis=1)

sess = tf.InteractiveSession()
sess.run(m)
# array([30,  7, 16, 19, 45])


问:
TextIO.Read().From() vs TextIO.ReadFiles() over withHintMatchesManyFiles()
In my usecase getting set of matching filepattern from Kafka,

PCollection<String> filepatterns = p.apply(KafkaIO.read()...);

Here each pattern could match upto 300+ files.

Q1. How can I use TextIO.Read() to match data from PCollection, as withHintMatchesManyFiles() available only for TextIO.Read() not for TextIO.ReadFiles().

Q2. If path via FileIO.Match->FileIO.ReadMatch()->TextIO.ReadFiles() is used, withHintMatchesManyFiles() isn't available in this path, how it will impact the read performance?

Q3. Is there any other optimized path for above usecase?

答:
Yes, you can't have withHintMatchesManyFiles() with TextIO.ReadFiles() out of the box. Actually, TextIO.Read().withHintMatchesManyFiles() is implemented via FileIO transforms + TextIO.ReadFiles() (see details). In this way, FileIO.readMatches() should distribute the files reading over the workers.

So, I think you can use the same approach while reading file names from Kafka topic.


问:
MediaQuery.of() called with a context that does not contain a MediaQuery. (emergency aid)
I deleted the 'MaterialApp' code block because I couldn't write the codes I wanted at the beginning.

Now it gives an error, how can I fix this? I have to handle this in a very short time, I have to put the codes I wrote in the "MaterialApp" block, but I can't.

Can you help me ?

```<code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return CupertinoTabScaffold(
        tabBar: CupertinoTabBar(
            items: < BottomNavigationBarItem > [
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.home),
                    title: Text('Enes'),
                ),
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.bluetooth),
                    title: Text('Mehmet'),
                ),
            ],
        ),
        tabBuilder: (BuildContext context, int index) {
            return CupertinoTabView(
                builder: (BuildContext context) {
                    return CupertinoPageScaffold(
                        navigationBar: CupertinoNavigationBar(
                            middle: Text('Page 1 of tab $index'),
                        ),
                        child: Center(
                            child: CupertinoButton(
                                child: const Text('Next Page'),
                                    onPressed: () {
                                        Navigator.of(context).push(
                                            CupertinoPageRoute < void > (
                                                builder: (BuildContext context) {
                                                    return CupertinoPageScaffold(
                                                        navigationBar: CupertinoNavigationBar(
                                                            middle: Text('Page 2 of tab $index'),
                                                        ),
                                                        child: Center(
                                                            child: CupertinoButton(
                                                                child: const Text('Back'),
                                                                    onPressed: () {
                                                                        Navigator.of(context).pop();
                                                                    },
                                                            ),
                                                        ),
                                                    );
                                                },
                                            ),
                                        );
                                    },
                            ),
                        ),
                    );
                },
            );
        },
    );
}
</code>```

}

答:
It seems like you want to develop an app with iOS elements. If so, you need to replace MaterialApp with CupertinoApp. If not, you MUST NOT delete MaterialApp because it is necessary to be there.

```<code>class CupertinoApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
   return CupertinoApp(
     home: CupertinoHomePage(),
    );
  }
}
</code>```

I wish it helps.

Body:
I deleted the 'MaterialApp' code block because I couldn't write the codes I wanted at the beginning.

Now it gives an error, how can I fix this? I have to handle this in a very short time, I have to put the codes I wrote in the "MaterialApp" block, but I can't.

Can you help me ?

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
    return CupertinoTabScaffold(
        tabBar: CupertinoTabBar(
            items: < BottomNavigationBarItem > [
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.home),
                    title: Text('Enes'),
                ),
                new BottomNavigationBarItem(
                    icon: new Icon(Icons.bluetooth),
                    title: Text('Mehmet'),
                ),
            ],
        ),
        tabBuilder: (BuildContext context, int index) {
            return CupertinoTabView(
                builder: (BuildContext context) {
                    return CupertinoPageScaffold(
                        navigationBar: CupertinoNavigationBar(
                            middle: Text('Page 1 of tab $index'),
                        ),
                        child: Center(
                            child: CupertinoButton(
                                child: const Text('Next Page'),
                                    onPressed: () {
                                        Navigator.of(context).push(
                                            CupertinoPageRoute < void > (
                                                builder: (BuildContext context) {
                                                    return CupertinoPageScaffold(
                                                        navigationBar: CupertinoNavigationBar(
                                                            middle: Text('Page 2 of tab $index'),
                                                        ),
                                                        child: Center(
                                                            child: CupertinoButton(
                                                                child: const Text('Back'),
                                                                    onPressed: () {
                                                                        Navigator.of(context).pop();
                                                                    },
                                                            ),
                                                        ),
                                                    );
                                                },
                                            ),
                                        );
                                    },
                            ),
                        ),
                    );
                },
            );
        },
    );
}

}

Body:
It seems like you want to develop an app with iOS elements. If so, you need to replace MaterialApp with CupertinoApp. If not, you MUST NOT delete MaterialApp because it is necessary to be there.

class CupertinoApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
   return CupertinoApp(
     home: CupertinoHomePage(),
    );
  }
}

I wish it helps.


问:
How to check if a sentence begins with a non-english word in python?
I have tried the following code to check if the sentence has non-english words.But I want to check if the beginning of the sentence itself has the non-english word and hence remove that entire sentence. I have also tried the startswith() method along with the isalpha() method but didn't work.

So if there are a list of non-english and english sentences I want to recognize the non-english ones and remove them from the list. Please help me resolve this.

```<code>import nltk
#nltk.download('words')
words = set(nltk.corpus.words.words())

sent = "Какую выберешь ты? abcd12 すべてのように置いてみましょう . Выложи фото с продукцией или боржоми и получи за это деньги. За подробностями пиши в директ."
wr=[]
for w in nltk.wordpunct_tokenize(sent):
    #print(w)
    if(w.isalpha()==True):
        wr.append(w)

print(wr)
</code>```

答:
You can use the enchant library to access a dictionary:</p>

```<code>import enchant

dict = enchant.Dict('en_US')

sent = "Какую выберешь ты? abcd12 すべてのように置いてみましょう . Выложи фото с продукцией или боржоми и получи за это деньги. За подробностями пиши в директ."
new_sent = ''

for sentence in sent.split('.'):
    if dict.check(sentence.split(' ')[0]):
        print(sentence)
</code>```

Body:
I have tried the following code to check if the sentence has non-english words.But I want to check if the beginning of the sentence itself has the non-english word and hence remove that entire sentence. I have also tried the startswith() method along with the isalpha() method but didn't work.

So if there are a list of non-english and english sentences I want to recognize the non-english ones and remove them from the list. Please help me resolve this.

import nltk
#nltk.download('words')
words = set(nltk.corpus.words.words())

sent = "Какую выберешь ты? abcd12 すべてのように置いてみましょう . Выложи фото с продукцией или боржоми и получи за это деньги. За подробностями пиши в директ."
wr=[]
for w in nltk.wordpunct_tokenize(sent):
    #print(w)
    if(w.isalpha()==True):
        wr.append(w)

print(wr)

Body:
You can use the enchant library to access a dictionary:

import enchant

dict = enchant.Dict('en_US')

sent = "Какую выберешь ты? abcd12 すべてのように置いてみましょう . Выложи фото с продукцией или боржоми и получи за это деньги. За подробностями пиши в директ."
new_sent = ''

for sentence in sent.split('.'):
    if dict.check(sentence.split(' ')[0]):
        print(sentence)


问:
Is there a library that allows checking if a 24-hour time is valid?
I am trying to check if a given time is valid, using any of python's multiple datetime libraries. This given time would be in 24hr format, and examples of valid inputs are 2359, 0000, 1330, while examples of invalid inputs would be 2400, 2360, 2500.

May I ask if there is a better way to check the validity of the input, without parsing through the strings to check individually?

Preferably using python libraries, if possible

If there are no such libraries, may I instead ask how this should be done in regex?

答:
Regex approach need to be added in your date time scenario

```<code>^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$ (js engine)
</code>```

Logic:

The first number (hours) is either: a number between 0 and 19 -->
[0-1]?[0-9] (allowing single digit number) or a number between 20 -
23 --> 2[0-3]

the second number (minutes) is always a number between 00 and 59 -->
[0-5][0-9] (not allowing a single digit)

Body:
Regex approach need to be added in your date time scenario

^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$ (js engine)

Logic:

The first number (hours) is either: a number between 0 and 19 -->
[0-1]?[0-9] (allowing single digit number) or a number between 20 -
23 --> 2[0-3]

the second number (minutes) is always a number between 00 and 59 -->
[0-5][0-9] (not allowing a single digit)


问:
Change dropdown to dependent dropdown
As shown in the below code, Semester dropdown and Programme dropdown is current working separately where it isn't depend to each other.

How to change it to a dependent dropdown?

Eg: When user select the 31934 semester, only program(student_prg) that exists under that semester(semester) should display in the program dropdown.

Code

```<code><div class="modal-body">
            <div class="form-group">
                  <label for="title">Select Current Semester:</label>
                  <select name="semester" class="form-control">
                      <option value="">--- Select Current Semester ---</option>

                      <?php
                        require('../setting/config.php');
                          $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
                          $do = mysqli_query($conn, $query);
                          while($row = mysqli_fetch_array($do)){
                              echo '<option value="'.$row['student_matric'].'">'.$row['semester'].'</option>';
                          }
                      ?>
                  </select>
              </div>
              <div class="form-group">
                  <label for="title">Select Programme:</label>
                  <select id="prg" name="prg" class="form-control">
                    <option value="">--- Select Programme ---</option>

                    <?php
                        $query2 = "SELECT student_prg, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC";
                          $do = mysqli_query($conn, $query2);
                          while($row = mysqli_fetch_array($do)){
                              echo '<option value="'.$row['student_matric'].'" data-count="'.$row['count'].'">'.$row['student_prg'].'</option>';
                          }
                    ?>
                  </select>
</code>```

Screenshot

Database

```<code>mysql> describe marketing_data;
+---------------+------------------+------+-----+---------+--------------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+--------------------+
| student_matric| varchar(10) unsigned | NO   | PRI | NULL    | auto_increment |
| student_prg   | text unsigned        | YES  |     | NULL    |                |
| semester      | varchar(10)          | YES  |     | NULL    |                |
| intake_year   | int(10)              | YES  |     | NULL    |                |
| student_city  | text                 | YES  |     | NULL    |                |
| city_lat      | varchar(20)          | YES  |     | NULL    |                |
| city_long     | varchar(20)          | YES  |     | NULL    |                |
| student_state | text                 | YES  |     | NULL    |                |
| state_code    | varchar(100)         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+--------------------+
</code>```

Reply to the comment @VPC

When I select the Semester, the program dropdown becomes empty.

After refresh the page, when I select program all the semesters able to view in the dropdown.

答:
```<code><div class="modal-body">
    <div class="form-group">
        <label for="title">Select Current Semester:</label>
        <select name="semester" class="form-control">
            <option value="" selected disabled>--- Select Current Semester ---</option> // Don't allow them to re-select this value

            <?php
            require('../setting/config.php');
            $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
            $do = mysqli_query($conn, $query);
            while ($row = mysqli_fetch_array($do)) {
                echo '<option value="' . $row['student_matric'] . '">' . $row['semester'] . '</option>';
            }
            ?>
        </select>
    </div>
    <div class="form-group">
        <label for="title">Select Programme:</label>
        <select id="prg" name="prg" class="form-control">
            <option value="" selected disabled>--- Select Programme ---</option> // Don't allow them to re-select this value

            <?php
            //get semester field also the result
            $query2 = "SELECT student_prg , semester, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC";
            $do = mysqli_query($conn, $query2);
            while ($row = mysqli_fetch_array($do)) {
                //we are trying to add a common class to all the options
                //then another class with semester id appended into it so it will be relevent to the specific semester expecting that semester field contains the semester code of other dropdown
                echo '<option class="hidden_options semester_' . $row['semester'] . '" value="' . $row['student_matric'] . '" data-count="' . $row['count'] . '">' . $row['student_prg'] . '</option>';
            }
            ?>
        </select>

        <script>
            //what we are trying to achieve here is when the user selects a semester, first it will hide all the option from programme dropdown then it will only show option which have the class sememter_$semeter_code
            $("select[name='semester']").change(function() {
                var selectValue = $(this).text(); //current semester text i.e semester code
                $('.hidden_options').hide(); //hide all the options
                $('.semester_' + selectValue).show(); //show only options with semester value prefixed into it
            });
        </script>
</code>```

Title: Change dropdown to dependent dropdown

Body:
As shown in the below code, Semester dropdown and Programme dropdown is current working separately where it isn't depend to each other.

How to change it to a dependent dropdown?

Eg: When user select the 31934 semester, only program(student_prg) that exists under that semester(semester) should display in the program dropdown.

Code

                  Select Current Semester:
                  <select name="semester" class="form-control">
                      <option value="">--- Select Current Semester ---</option>

                      <?php
                        require('../setting/config.php');
                          $query = "SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC";
                          $do = mysqli_query($conn, $query);
                          while($row = mysqli_fetch_array($do)){
                              echo '<option value="'.$row['student_matric'].'">'.$row['semester'].'</option>';
                          }
                      ?>
                  </select>

                  Select Programme:
                  <select id="prg" name="prg" class="form-control">
                    <option value="">--- Select Programme ---</option>

                    <?php
                        $query2 = "SELECT student_prg, COUNT(student_prg) as count FROM marketing_data GROUP BY student_prg ORDER BY student_prg DESC";
                          $do = mysqli_query($conn, $query2);
                          while($row = mysqli_fetch_array($do)){
                              echo '<option value="'.$row['student_matric'].'" data-count="'.$row['count'].'">'.$row['student_prg'].'</option>';
                          }
                    ?>
                  </select>

Screenshot

Database

mysql> describe marketing_data;
+---------------+------------------+------+-----+---------+--------------------+
| Field         | Type                 | Null | Key | Default | Extra          |
+---------------+------------------+------+-----+---------+--------------------+
| student_matric| varchar(10) unsigned | NO   | PRI | NULL    | auto_increment |
| student_prg   | text unsigned        | YES  |     | NULL    |                |
| semester      | varchar(10)          | YES  |     | NULL    |                |
| intake_year   | int(10)              | YES  |     | NULL    |                |
| student_city  | text                 | YES  |     | NULL    |                |
| city_lat      | varchar(20)          | YES  |     | NULL    |                |
| city_long     | varchar(20)          | YES  |     | NULL    |                |
| student_state | text                 | YES  |     | NULL    |                |
| state_code    | varchar(100)         | YES  |     | NULL    |                |
+---------------+------------------+------+-----+---------+--------------------+

Reply to the comment @VPC

When I select the Semester, the program dropdown becomes empty.

After refresh the page, when I select program all the semesters able to view in the dropdown.


答:
You can attempt to parse it using time.strptime:

```<code>import time

def is_valid_time(value):
    try:
        _ = time.strptime(value, '%H%M')
    except ValueError:
        return False

    return True
</code>```

Title: Is there a library that allows checking if a 24-hour time is valid?

Body:
I am trying to check if a given time is valid, using any of python's multiple datetime libraries. This given time would be in 24hr format, and examples of valid inputs are 2359, 0000, 1330, while examples of invalid inputs would be 2400, 2360, 2500.

May I ask if there is a better way to check the validity of the input, without parsing through the strings to check individually?

Preferably using python libraries, if possible

If there are no such libraries, may I instead ask how this should be done in regex?

Body:
You can attempt to parse it using time.strptime:

import time

def is_valid_time(value):
    try:
        _ = time.strptime(value, '%H%M')
    except ValueError:
        return False

    return True


问:
Copying result from pgAdmin to a spreadsheet
I am copying every result of Query (application pgAdmin) into Google Docs Sheet.

I am wonder if it is possible to set Postgres to output tabs instead of semicolon ; to separate values in columns - I would like to simply copy and paste from Postgres to Google Docs sheet.

If it is not possible, is there any way to write a macro in Google Docs sheet?

I would like to ask one more question - how can I divide two values which I get by using select command (and how to demand from Postgres SQL to store values as for example double)?

答: Use the export ability.</p>

Body: Use the export ability.


答:
You can use strptime for parsing, with format %H%M.  If it fails, it is invalid.

```<code>from datetime import datetime

try:
    datetime.strptime('2359', '%H%M')
    print('valid')
except ValueError:
    print('invalid')
</code>```

Body:
You can use strptime for parsing, with format %H%M.  If it fails, it is invalid.

from datetime import datetime

try:
    datetime.strptime('2359', '%H%M')
    print('valid')
except ValueError:
    print('invalid')


问:
SQL function causes Segfault on database server (MariaDB) when called twice
I'm using a MariaDB MySql server (version 10.4.13-MariaDB) on Arch Linux and I have managed to create a function that crashes the database whenever it is called for a second time (or at least it has never crashed the server upon the first use in my testing).
No visible error is ever printed, the server just restarts, I've looked at journalctl -e -u mariadb.service but it is not of much help to me although it has let me to believe the crash is caused by a segmentation fault.

I have found some bug reports from 2005 which describe similar errors, but after closer inspection I don't think this is caused by the same issue. Can anybody please give me some clues as to what is going on here? It has been driving me crazy all day.

The SQL function is called register_user and looks like this:
It just performs a few checks regarding the validity of the provided invite code before adding a row to the User table.

DELIMITER $$
CREATE PROCEDURE register_user(user_name TEXT, user_email TEXT, user_passw_hash TEXT, user_invite_code INT)
RETURNS BOOLEAN
BEGIN
    -- Check: no previous use of email and invite code is still valid.
    IF NOT EXISTS (
        SELECT * FROM User WHERE email = user_email
    )
    AND EXISTS (
        SELECT * FROM Invite
        WHERE id = user_invite_code
        AND valid_till > NOW()
    )
    AND NOT EXISTS (
        SELECT Invite.id, Invite.max_uses, COUNT(User.joined_with)
        FROM Invite
        LEFT JOIN User ON User.joined_with = Invite.id
        GROUP BY Invite.id, Invite.max_uses
        HAVING COUNT(User.joined_with) >= Invite.max_uses
    )

    -- If checks succeed insert values into users table and return true.
    THEN INSERT INTO User(email, name, passw_hash, joined_with)
        VALUES(user_email, user_name, user_passw_hash, user_invite_code);
        RETURN TRUE;

    ELSE RETURN FALSE;

    END IF;
END$$

DELIMITER ;
```

<p>Edit: I changed some of the function parameter names to be less confusing.</p>

<p>The following tables are used by the function:</p>

<pre class="lang-sql prettyprint-override"><code>
CREATE TABLE Invite (
    id INT PRIMARY KEY,
    valid_till TIMESTAMP,
    max_uses INT UNSIGNED
);

CREATE TABLE User (
    id SERIAL PRIMARY KEY,
    email TEXT NOT NULL DEFAULT '' UNIQUE,
    name TEXT,
    passw_hash TEXT DEFAULT '' NOT NULL,
    joined_with INT NOT NULL,
    joined_on TIMESTAMP,
    FOREIGN KEY (joined_with) REFERENCES Invite(id)
);
</code>```

Output of journalctl -e -u mariadb.service:

```<code>jun 02 17:49:14 LinuxIsPower systemd[1]: Started MariaDB 10.4.13 database server.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: 200602 17:50:35 [ERROR] mysqld got signal 11 ;
jun 02 17:50:35 LinuxIsPower mysqld[29155]: This could be because you hit a bug. It is also possible that this binary
jun 02 17:50:35 LinuxIsPower mysqld[29155]: or one of the libraries it was linked against is corrupt, improperly built,
jun 02 17:50:35 LinuxIsPower mysqld[29155]: or misconfigured. This error can also be caused by malfunctioning hardware.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: To report this bug, see https://mariadb.com/kb/en/reporting-bugs
jun 02 17:50:35 LinuxIsPower mysqld[29155]: We will try our best to scrape up some info that will hopefully help
jun 02 17:50:35 LinuxIsPower mysqld[29155]: diagnose the problem, but since we have already crashed,
jun 02 17:50:35 LinuxIsPower mysqld[29155]: something is definitely wrong and this may fail.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Server version: 10.4.13-MariaDB
jun 02 17:50:35 LinuxIsPower mysqld[29155]: key_buffer_size=134217728
jun 02 17:50:35 LinuxIsPower mysqld[29155]: read_buffer_size=131072
jun 02 17:50:35 LinuxIsPower mysqld[29155]: max_used_connections=1
jun 02 17:50:35 LinuxIsPower mysqld[29155]: max_threads=153
jun 02 17:50:35 LinuxIsPower mysqld[29155]: thread_count=7
un 02 17:50:35 LinuxIsPower mysqld[29155]: It is possible that mysqld could use up to
jun 02 17:50:35 LinuxIsPower mysqld[29155]: key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 467756 K  bytes of memory
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Hope that's ok; if not, decrease some variables in the equation.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Thread pointer: 0x7f34e7807348
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Attempting backtrace. You can use the following information to find out
jun 02 17:50:35 LinuxIsPower mysqld[29155]: where mysqld died. If you see no messages after this, something went
jun 02 17:50:35 LinuxIsPower mysqld[29155]: terribly wrong...
jun 02 17:50:35 LinuxIsPower mysqld[29155]: stack_bottom = 0x7f35254835b8 thread_stack 0x49000
jun 02 17:50:35 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(my_print_stacktrace+0x2a)[0x557ad1d044ea]
jun 02 17:50:35 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(handle_fatal_signal+0x578)[0x557ad181b9f8]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: sigaction.c:0(__restore_rt)[0x7f3526002960]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN7cleanupEb+0x2c3)[0x557ad165da93]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN7destroyEv+0x40)[0x557ad165def0]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN13st_select_lex7cleanupEv+0x6a)[0x557ad16c48ca]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN30subselect_single_select_engine7prepareEP3THD+0x3a)[0x557ad18ce64a]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN14Item_subselect10fix_fieldsEP3THDPP4Item+0x139)[0x557ad18ce0a9]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN9Item_cond10fix_fieldsEP3THDPP4Item+0x1b8)[0x557ad1852958]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN3THD16sp_fix_func_itemEPP4Item+0x2c)[0x557ad15890ec]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN3THD20sp_prepare_func_itemEPP4Itemj+0xf)[0x557ad158915f]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN20sp_instr_jump_if_not9exec_coreEP3THDPj+0x1e)[0x557ad15891be]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN13sp_lex_keeper23reset_lex_and_exec_coreEP3THDPjbP8sp_instr+0x114)[0x557ad158fdb4]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7sp_head7executeEP3THDb+0x8cc)[0x557ad158accc]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7sp_head16execute_functionEP3THDPP4ItemjP5FieldPP11sp_rcontextP11Query_arena+0x53d)[0x557ad158cb7d]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7Item_sp12execute_implEP3THDPP4Itemj+0x122)[0x557ad1838742]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7Item_sp7executeEP3THDPbPP4Itemj+0x23)[0x557ad1838903]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN12Item_func_sp7val_intEv+0xa)[0x557ad189944a]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZNK12Type_handler14Item_send_tinyEP4ItemP8ProtocolP8st_value+0x18)[0x557ad176cb48]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN8Protocol19send_result_set_rowEP4ListI4ItemE+0xa5)[0x557ad156e5d5]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN11select_send9send_dataER4ListI4ItemE+0x4b)[0x557ad15d1d0b]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN10exec_innerEv+0xd14)[0x557ad167e4e4]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN4execEv+0x25)[0x557ad167e755]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z12mysql_selectP3THDP10TABLE_LISTjR4ListI4ItemEPS4_jP8st_orderS9_S7_S9_yP13select_resultP18st_select_lex_unitP13st_select_lex+0x138)[0x557ad167c8c8]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z13handle_selectP3THDP3LEXP13select_resultm+0x154)[0x557ad167d394]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(+0x66c02c)[0x557ad160f02c]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z21mysql_execute_commandP3THD+0x68c7)[0x557ad161d617]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z11mysql_parseP3THDPcjP12Parser_statebb+0x1c9)[0x557ad161fed9]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z16dispatch_command19enum_server_commandP3THDPcjbb+0x1d34)[0x557ad1622de4]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z10do_commandP3THD+0x105)[0x557ad1624625]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z24do_handle_one_connectionP7CONNECT+0x1c6)[0x557ad1708936]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(handle_one_connection+0x33)[0x557ad1708a73]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: pthread_create.c:0(start_thread)[0x7f3525ff7422]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: :0(__GI___clone)[0x7f35257c7bf3]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Trying to get some variables.
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Some pointers may be invalid and cause the dump to abort.
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Query (0x7f34e785fde0): SELECT register_user('matthijs', 'an@email.com', 'sdalioas', 1235) AS success
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Connection ID (thread ID): 8
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Status: NOT_KILLED
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Optimizer switch: index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,engine_condition_pushdown=off,index_condition_push>
jun 02 17:50:36 LinuxIsPower mysqld[29155]: The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
jun 02 17:50:36 LinuxIsPower mysqld[29155]: information that should help you find out what is causing the crash.
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Writing a core file...
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Working directory at /var/lib/mysql
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Resource Limits:
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Limit                     Soft Limit           Hard Limit           Units
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max cpu time              unlimited            unlimited            seconds
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max file size             unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max data size             unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max stack size            8388608              unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max core file size        unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max resident set          unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max processes             62581                62581                processes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max open files            16364                16364                files
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max locked memory         65536                65536                bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max address space         unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max file locks            unlimited            unlimited            locks
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max pending signals       62581                62581                signals
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max msgqueue size         819200               819200               bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max nice priority         0                    0
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max realtime priority     0                    0
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max realtime timeout      unlimited            unlimited            us
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Core pattern: |/usr/lib/systemd/systemd-coredump %P %u %g %s %t %c ...
jun 02 17:50:37 LinuxIsPower systemd[1]: mariadb.service: Main process exited, code=killed, status=11/SEGV
jun 02 17:50:37 LinuxIsPower systemd[1]: mariadb.service: Failed with result 'signal'.
jun 02 17:50:42 LinuxIsPower systemd[1]: mariadb.service: Scheduled restart job, restart counter is at 21.
jun 02 17:50:42 LinuxIsPower systemd[1]: Stopped MariaDB 10.4.13 database server.
jun 02 17:50:42 LinuxIsPower systemd[1]: Starting MariaDB 10.4.13 database server...
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] /usr/bin/mysqld (mysqld 10.4.13-MariaDB) starting as process 29410 ...
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Warning] Could not increase number of max_open_files to more than 16364 (request: 32194)
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Using Linux native AIO
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Uses event mutexes
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Number of pools: 1
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Using SSE2 crc32 instructions
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] mysqld: O_TMPFILE is not supported on /tmp (disabling future attempts)
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Completed initialization of buffer pool
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Starting crash recovery from checkpoint LSN=2135060
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Creating shared tablespace for temporary tables
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Waiting for purge to start
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: 10.4.13 started; log sequence number 2135069; transaction id 4666
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Buffer pool(s) load completed at 200602 17:50:42
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] Server socket created on IP: '::'.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] Reading of all Master_info entries succeeded
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] Added new Master_info '' to hash table
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] /usr/bin/mysqld: ready for connections.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: Version: '10.4.13-MariaDB'  socket: '/run/mysqld/mysqld.sock'  port: 3306  Arch Linux
jun 02 17:50:42 LinuxIsPower systemd[1]: Started MariaDB 10.4.13 database server.
</code>```

答:
The database should not crash, that is correct. To improve your code (and possibly reduce the possibility of a crash), you could do following:

Use procedure instead of a function as what you do looks more like a procedure

Shoudn't the second check also include the invite_code passed in as parameter?

Fix the GROUP BY query as it does not seem to be correct

Do not use parameter names that match column names (like name)

Body:
I'm using a MariaDB MySql server (version 10.4.13-MariaDB) on Arch Linux and I have managed to create a function that crashes the database whenever it is called for a second time (or at least it has never crashed the server upon the first use in my testing).
No visible error is ever printed, the server just restarts, I've looked at journalctl -e -u mariadb.service but it is not of much help to me although it has let me to believe the crash is caused by a segmentation fault.

I have found some bug reports from 2005 which describe similar errors, but after closer inspection I don't think this is caused by the same issue. Can anybody please give me some clues as to what is going on here? It has been driving me crazy all day.

The SQL function is called register_user and looks like this:
It just performs a few checks regarding the validity of the provided invite code before adding a row to the User table.

DELIMITER $$
CREATE PROCEDURE register_user(user_name TEXT, user_email TEXT, user_passw_hash TEXT, user_invite_code INT)
RETURNS BOOLEAN
BEGIN
    -- Check: no previous use of email and invite code is still valid.
    IF NOT EXISTS (
        SELECT * FROM User WHERE email = user_email
    )
    AND EXISTS (
        SELECT * FROM Invite
        WHERE id = user_invite_code
        AND valid_till > NOW()
    )
    AND NOT EXISTS (
        SELECT Invite.id, Invite.max_uses, COUNT(User.joined_with)
        FROM Invite
        LEFT JOIN User ON User.joined_with = Invite.id
        GROUP BY Invite.id, Invite.max_uses
        HAVING COUNT(User.joined_with) >= Invite.max_uses
    )

    -- If checks succeed insert values into users table and return true.
    THEN INSERT INTO User(email, name, passw_hash, joined_with)
        VALUES(user_email, user_name, user_passw_hash, user_invite_code);
        RETURN TRUE;

    ELSE RETURN FALSE;

    END IF;
END$$

DELIMITER ;

Edit: I changed some of the function parameter names to be less confusing.

The following tables are used by the function:

CREATE TABLE Invite (
    id INT PRIMARY KEY,
    valid_till TIMESTAMP,
    max_uses INT UNSIGNED
);

CREATE TABLE User (
    id SERIAL PRIMARY KEY,
    email TEXT NOT NULL DEFAULT '' UNIQUE,
    name TEXT,
    passw_hash TEXT DEFAULT '' NOT NULL,
    joined_with INT NOT NULL,
    joined_on TIMESTAMP,
    FOREIGN KEY (joined_with) REFERENCES Invite(id)
);

Output of journalctl -e -u mariadb.service:

jun 02 17:49:14 LinuxIsPower systemd[1]: Started MariaDB 10.4.13 database server.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: 200602 17:50:35 [ERROR] mysqld got signal 11 ;
jun 02 17:50:35 LinuxIsPower mysqld[29155]: This could be because you hit a bug. It is also possible that this binary
jun 02 17:50:35 LinuxIsPower mysqld[29155]: or one of the libraries it was linked against is corrupt, improperly built,
jun 02 17:50:35 LinuxIsPower mysqld[29155]: or misconfigured. This error can also be caused by malfunctioning hardware.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: To report this bug, see https://mariadb.com/kb/en/reporting-bugs
jun 02 17:50:35 LinuxIsPower mysqld[29155]: We will try our best to scrape up some info that will hopefully help
jun 02 17:50:35 LinuxIsPower mysqld[29155]: diagnose the problem, but since we have already crashed,
jun 02 17:50:35 LinuxIsPower mysqld[29155]: something is definitely wrong and this may fail.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Server version: 10.4.13-MariaDB
jun 02 17:50:35 LinuxIsPower mysqld[29155]: key_buffer_size=134217728
jun 02 17:50:35 LinuxIsPower mysqld[29155]: read_buffer_size=131072
jun 02 17:50:35 LinuxIsPower mysqld[29155]: max_used_connections=1
jun 02 17:50:35 LinuxIsPower mysqld[29155]: max_threads=153
jun 02 17:50:35 LinuxIsPower mysqld[29155]: thread_count=7
un 02 17:50:35 LinuxIsPower mysqld[29155]: It is possible that mysqld could use up to
jun 02 17:50:35 LinuxIsPower mysqld[29155]: key_buffer_size + (read_buffer_size + sort_buffer_size)*max_threads = 467756 K  bytes of memory
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Hope that's ok; if not, decrease some variables in the equation.
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Thread pointer: 0x7f34e7807348
jun 02 17:50:35 LinuxIsPower mysqld[29155]: Attempting backtrace. You can use the following information to find out
jun 02 17:50:35 LinuxIsPower mysqld[29155]: where mysqld died. If you see no messages after this, something went
jun 02 17:50:35 LinuxIsPower mysqld[29155]: terribly wrong...
jun 02 17:50:35 LinuxIsPower mysqld[29155]: stack_bottom = 0x7f35254835b8 thread_stack 0x49000
jun 02 17:50:35 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(my_print_stacktrace+0x2a)[0x557ad1d044ea]
jun 02 17:50:35 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(handle_fatal_signal+0x578)[0x557ad181b9f8]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: sigaction.c:0(__restore_rt)[0x7f3526002960]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN7cleanupEb+0x2c3)[0x557ad165da93]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN7destroyEv+0x40)[0x557ad165def0]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN13st_select_lex7cleanupEv+0x6a)[0x557ad16c48ca]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN30subselect_single_select_engine7prepareEP3THD+0x3a)[0x557ad18ce64a]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN14Item_subselect10fix_fieldsEP3THDPP4Item+0x139)[0x557ad18ce0a9]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN9Item_cond10fix_fieldsEP3THDPP4Item+0x1b8)[0x557ad1852958]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN3THD16sp_fix_func_itemEPP4Item+0x2c)[0x557ad15890ec]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN3THD20sp_prepare_func_itemEPP4Itemj+0xf)[0x557ad158915f]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN20sp_instr_jump_if_not9exec_coreEP3THDPj+0x1e)[0x557ad15891be]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN13sp_lex_keeper23reset_lex_and_exec_coreEP3THDPjbP8sp_instr+0x114)[0x557ad158fdb4]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7sp_head7executeEP3THDb+0x8cc)[0x557ad158accc]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7sp_head16execute_functionEP3THDPP4ItemjP5FieldPP11sp_rcontextP11Query_arena+0x53d)[0x557ad158cb7d]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7Item_sp12execute_implEP3THDPP4Itemj+0x122)[0x557ad1838742]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN7Item_sp7executeEP3THDPbPP4Itemj+0x23)[0x557ad1838903]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN12Item_func_sp7val_intEv+0xa)[0x557ad189944a]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZNK12Type_handler14Item_send_tinyEP4ItemP8ProtocolP8st_value+0x18)[0x557ad176cb48]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN8Protocol19send_result_set_rowEP4ListI4ItemE+0xa5)[0x557ad156e5d5]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN11select_send9send_dataER4ListI4ItemE+0x4b)[0x557ad15d1d0b]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN10exec_innerEv+0xd14)[0x557ad167e4e4]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_ZN4JOIN4execEv+0x25)[0x557ad167e755]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z12mysql_selectP3THDP10TABLE_LISTjR4ListI4ItemEPS4_jP8st_orderS9_S7_S9_yP13select_resultP18st_select_lex_unitP13st_select_lex+0x138)[0x557ad167c8c8]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z13handle_selectP3THDP3LEXP13select_resultm+0x154)[0x557ad167d394]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(+0x66c02c)[0x557ad160f02c]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z21mysql_execute_commandP3THD+0x68c7)[0x557ad161d617]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z11mysql_parseP3THDPcjP12Parser_statebb+0x1c9)[0x557ad161fed9]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z16dispatch_command19enum_server_commandP3THDPcjbb+0x1d34)[0x557ad1622de4]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z10do_commandP3THD+0x105)[0x557ad1624625]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(_Z24do_handle_one_connectionP7CONNECT+0x1c6)[0x557ad1708936]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: /usr/bin/mysqld(handle_one_connection+0x33)[0x557ad1708a73]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: pthread_create.c:0(start_thread)[0x7f3525ff7422]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: :0(__GI___clone)[0x7f35257c7bf3]
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Trying to get some variables.
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Some pointers may be invalid and cause the dump to abort.
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Query (0x7f34e785fde0): SELECT register_user('matthijs', 'an@email.com', 'sdalioas', 1235) AS success
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Connection ID (thread ID): 8
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Status: NOT_KILLED
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Optimizer switch: index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,index_merge_sort_intersection=off,engine_condition_pushdown=off,index_condition_push>
jun 02 17:50:36 LinuxIsPower mysqld[29155]: The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
jun 02 17:50:36 LinuxIsPower mysqld[29155]: information that should help you find out what is causing the crash.
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Writing a core file...
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Working directory at /var/lib/mysql
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Resource Limits:
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Limit                     Soft Limit           Hard Limit           Units
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max cpu time              unlimited            unlimited            seconds
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max file size             unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max data size             unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max stack size            8388608              unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max core file size        unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max resident set          unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max processes             62581                62581                processes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max open files            16364                16364                files
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max locked memory         65536                65536                bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max address space         unlimited            unlimited            bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max file locks            unlimited            unlimited            locks
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max pending signals       62581                62581                signals
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max msgqueue size         819200               819200               bytes
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max nice priority         0                    0
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max realtime priority     0                    0
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Max realtime timeout      unlimited            unlimited            us
jun 02 17:50:36 LinuxIsPower mysqld[29155]: Core pattern: |/usr/lib/systemd/systemd-coredump %P %u %g %s %t %c ...
jun 02 17:50:37 LinuxIsPower systemd[1]: mariadb.service: Main process exited, code=killed, status=11/SEGV
jun 02 17:50:37 LinuxIsPower systemd[1]: mariadb.service: Failed with result 'signal'.
jun 02 17:50:42 LinuxIsPower systemd[1]: mariadb.service: Scheduled restart job, restart counter is at 21.
jun 02 17:50:42 LinuxIsPower systemd[1]: Stopped MariaDB 10.4.13 database server.
jun 02 17:50:42 LinuxIsPower systemd[1]: Starting MariaDB 10.4.13 database server...
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] /usr/bin/mysqld (mysqld 10.4.13-MariaDB) starting as process 29410 ...
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Warning] Could not increase number of max_open_files to more than 16364 (request: 32194)
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Using Linux native AIO
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Uses event mutexes
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Number of pools: 1
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Using SSE2 crc32 instructions
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] mysqld: O_TMPFILE is not supported on /tmp (disabling future attempts)
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Completed initialization of buffer pool
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Starting crash recovery from checkpoint LSN=2135060
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Creating shared tablespace for temporary tables
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Waiting for purge to start
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: 10.4.13 started; log sequence number 2135069; transaction id 4666
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] InnoDB: Buffer pool(s) load completed at 200602 17:50:42
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] Server socket created on IP: '::'.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] Reading of all Master_info entries succeeded
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] Added new Master_info '' to hash table
jun 02 17:50:42 LinuxIsPower mysqld[29410]: 2020-06-02 17:50:42 0 [Note] /usr/bin/mysqld: ready for connections.
jun 02 17:50:42 LinuxIsPower mysqld[29410]: Version: '10.4.13-MariaDB'  socket: '/run/mysqld/mysqld.sock'  port: 3306  Arch Linux
jun 02 17:50:42 LinuxIsPower systemd[1]: Started MariaDB 10.4.13 database server.


问:
Azure Blobs: Get Block List in C#
I am working with Block Blobs in Azure Storage. I need to get uncommitted blocks, as far as I have found I need to call "Get Block List". Here is the problem.

Does "Get Block List" functionality exists in C# (Microsoft.WindowsAzure.StorageClient.dll)?

MSDN only says about doing a HTTP request, not a word about StorageClient API.

If this function does not exists in C#, are there any plans to include it to the C# API?

答:
You may want to look into GetBlockListResponse class in Microsoft.WindowsAzure.StorageClient.Protocol namespace: http://msdn.microsoft.com/en-us/library/ee758632.aspx

Hope this helps

Thanks

Gaurav

Title: Azure Blobs: Get Block List in C#


问:
Swiper widget itemCount change from infinite
I'm building a list of  assistants with the Swiper Library.
But the problem is that from the assistants list I'm receiving only 1 or 2 instances, but the Swiper is repeating those users infinite times. I'm wondering how to limit it to the number of assistants.
this is my code:</p>

```<code>    child: Swiper(
      autoplay: true,
      autoplayDelay: 2000,
      itemBuilder: (BuildContext context, int index) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            CircleAvatar(
              backgroundImage: NetworkImage(
                  "host${_user.img}"),
              radius: 35.0,
            ),
            Text(
              assistants[index].username,
              style: TextStyle(fontSize: 12.0),
            ),
          ],
        );
      },
      scale: .01,
      itemCount: assistants.length,
      viewportFraction: .18,
    ),
</code>```

答:
Well actually it is already building only 2 items (or better say its building items according to your assistants list length) But the thing is that its looping it by default. So if you want it to end up somewhere you can easily set the loop property to false. Try the code below:

```<code>  child: Swiper(
  autoplay: true,
  loop: false,  //this is the property that prevents the swiper from looping
  autoplayDelay: 2000,
  itemBuilder: (BuildContext context, int index) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        CircleAvatar(
          backgroundImage: NetworkImage(
              "host${_user.img}"),
          radius: 35.0,
        ),
        Text(
          assistants[index].username,
          style: TextStyle(fontSize: 12.0),
        ),
      ],
    );
  },
  scale: .01,
  itemCount: assistants.length,
  viewportFraction: .18,
),
</code>```

Also here's a list of Swiper library properties that you can have a look for any
further changes.

Body:
I'm building a list of  assistants with the Swiper Library.
But the problem is that from the assistants list I'm receiving only 1 or 2 instances, but the Swiper is repeating those users infinite times. I'm wondering how to limit it to the number of assistants.
this is my code:

    child: Swiper(
      autoplay: true,
      autoplayDelay: 2000,
      itemBuilder: (BuildContext context, int index) {
        return Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            CircleAvatar(
              backgroundImage: NetworkImage(
                  "host${_user.img}"),
              radius: 35.0,
            ),
            Text(
              assistants[index].username,
              style: TextStyle(fontSize: 12.0),
            ),
          ],
        );
      },
      scale: .01,
      itemCount: assistants.length,
      viewportFraction: .18,
    ),

Body:
Well actually it is already building only 2 items (or better say its building items according to your assistants list length) But the thing is that its looping it by default. So if you want it to end up somewhere you can easily set the loop property to false. Try the code below:

  child: Swiper(
  autoplay: true,
  loop: false,  //this is the property that prevents the swiper from looping
  autoplayDelay: 2000,
  itemBuilder: (BuildContext context, int index) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        CircleAvatar(
          backgroundImage: NetworkImage(
              "host${_user.img}"),
          radius: 35.0,
        ),
        Text(
          assistants[index].username,
          style: TextStyle(fontSize: 12.0),
        ),
      ],
    );
  },
  scale: .01,
  itemCount: assistants.length,
  viewportFraction: .18,
),

Also here's a list of Swiper library properties that you can have a look for any
further changes.


问:
Uncaught (in promise) TypeError: _this is not a function
I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

```<code>this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}
</code>```

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

答:
The problem is that you are misreading the scope. To solve your problem, change the function for an arrow function.

```<code>this.razorPayOptions = {
'key': process.env.MIX_RAZORPAY_KEY,
'name': process.env.MIX_APP_NAME,
'description': 'Details ...',
'handler': (request) => {
    axios.post('/api/transaction/complete', request)
        .then(response => {
            console.log(response);
            this.toast(response.data, response.status); // this is where the error occurs
        });
   }
}
</code>```

could you read this post https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc.

Body:
I'm making a simple axios call and on success, call a toast. The toast function is also there and working fine because I am using it at 100 different places.

console log shows {data: "Payment Successful", status: 200, statusText: "OK", headers: {…}, config: {…}, …} means the call is working fine, it's just the this is not ...

this.razorPayOptions = {
    'key': process.env.MIX_RAZORPAY_KEY,
    'name': process.env.MIX_APP_NAME,
    'description': 'Details ...',
    'handler': function (request) {
        axios.post('/api/transaction/complete', request)
            .then(response => {
                console.log(response);
                this.toast(response.data, response.status); // this is where the error occurs
            });
    }
}

Error: Uncaught (in promise) TypeError: _this.toast is not a function

I've searched on internet for past 2 days but couldn't find anything. Some suggested to use async/await but no luck either. As always, stack overflow is my last resort. If you need more info, please add a comment below.

Thank You.

Body:
The problem is that you are misreading the scope. To solve your problem, change the function for an arrow function.

this.razorPayOptions = {
'key': process.env.MIX_RAZORPAY_KEY,
'name': process.env.MIX_APP_NAME,
'description': 'Details ...',
'handler': (request) => {
    axios.post('/api/transaction/complete', request)
        .then(response => {
            console.log(response);
            this.toast(response.data, response.status); // this is where the error occurs
        });
   }
}

could you read this post https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc.


问:
T-SQL query to show table definition?
What is a query that will show me the full definition, including indexes and keys for a SQL Server table?  I want a pure query - and know that SQL Studio can give this to me, but I am often on "wild" computers that have only the most bare-bones apps and I have no rights to install studio.  But SQLCMD is always an option.

UPDATE:  I have tried sp_help, but is just yields one record which shows Name, Owner, Type and Created_Datetime.  Is there something else I am missing with sp_help?

Here is what I call:

sp_help airports

Note that I really do want the DDL that defines the table.

答:
There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.</p>

```<code>SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'

SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')
</code>```

Title: T-SQL query to show table definition?

Body:
There is no easy way to return the DDL. However you can get most of the details from Information Schema Views and System Views.

SELECT ORDINAL_POSITION, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH
       , IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'Customers'

SELECT CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_NAME = 'Customers'

SELECT name, type_desc, is_unique, is_primary_key
FROM sys.indexes
WHERE [object_id] = OBJECT_ID('dbo.Customers')


问:
Replace mp4 file's audio with part of mp3 in ffmpeg
I have a around 30 minutes mp4 file and 1h30m mp3 file, let's say I need to replace mp4 file's audio with part of mp3 file, for example, starting from 30m00s.

I have used the following ffmpeg command which works for replacing the mp3 to mp4's audio but not specify the starting time.

How could I modify it? Thanks.

```<code>ffmpeg -i input.mp4 -i input.mp3 -map 0:0 -map 1:0 -c:v copy -c:a aac -b:a 256k -shortest output.mp4
</code>```

答:
Add -ss input option:

```<code>ffmpeg -i input.mp4 -ss 00:30:00 -i input.mp3 -map 0:v -map 1:a -c:v copy -c:a aac -b:a 256k -shortest -movflags +faststart output.mp4
</code>```

Body:
I have a around 30 minutes mp4 file and 1h30m mp3 file, let's say I need to replace mp4 file's audio with part of mp3 file, for example, starting from 30m00s.

I have used the following ffmpeg command which works for replacing the mp3 to mp4's audio but not specify the starting time.

How could I modify it? Thanks.

ffmpeg -i input.mp4 -i input.mp3 -map 0:0 -map 1:0 -c:v copy -c:a aac -b:a 256k -shortest output.mp4

Body:
Add -ss input option:

ffmpeg -i input.mp4 -ss 00:30:00 -i input.mp3 -map 0:v -map 1:a -c:v copy -c:a aac -b:a 256k -shortest -movflags +faststart output.mp4


问:
how to make django dynamic URL works properly with django form
This is my form

```<code><form action="{%url 'topicname' %}" method="GET">
              <input type="search" placeholder="Search topics" name="searchtopic">
              <button type="submit">Search</button>
 </form>
</code>```

This is my View

```<code>def searchtopic(request):
    if request.method == 'GET':
        mysearchtopic = request.GET['searchtopic']

        mydata = myhashtaglist.objects.filter(slug = mysearchtopic)
        context = {
            'mydata':mydata,
            }
    return render(request, 'hzone/result.html',context)
</code>```

This is my result.html page

```<code>{% for m in mydata %}
<a href="{% url 'topicname' m.slug %}">{{ m.title }}</a>
{% endfor %}
</code>```

This is my urls.py

```<code>urlpatterns = [
    path('', views.apphome, name = 'homepage'),
    path('topic/', views.searchtopic, name = 'topicname'),
]
</code>```

This is my model

```<code>class myhashtaglist(models.Model):
    title = models.CharField(max_length = 200)
    slug = models.SlugField(max_length = 150, null=True, blank = True)
    topicdetails = models.TextField(max_length = 500)
</code>```

what i want is whenever user click on any of the topic on result page this topic should open.
my reult page looks like

```<code>intro to django
django tutorial 1
django tutorial 2
django tutorial 3
</code>```

but when i am clicking on any of the topic its not taking me to that topic.

答:
I think the problem lies in your urls.py. You have one view (searchtopic) for two different purposes, first you are searching using def searchtopic(request) and then using the same function for getting a result. You must create a another view for your result something like def get_result(request, slug) and then define a url in your urls.py after that in your form you can do something like this:

```<code>{% for m in mydata %}
   <a href="{% url 'your-url-for-resul' m.slug %}">{{ m.title }}</a>
{% endfor %}
</code>```

and the following code will be the second view:

```<code>def get_result(request, slug):
    result = get_object_or_404(Result, slug=slug)

    return render(request, 'your_template_result.html', {'result': result})
</code>```

Then you must have a .html file (here is your_template_result.html) to redirect to that page and also unpack your data (here is result) inside the same html file.

I think this can solve your problem.

Body:
This is my form

<form action="{%url 'topicname' %}" method="GET">
              <input type="search" placeholder="Search topics" name="searchtopic">
              <button type="submit">Search</button>
 </form>

This is my View

def searchtopic(request):
    if request.method == 'GET':
        mysearchtopic = request.GET['searchtopic']

        mydata = myhashtaglist.objects.filter(slug = mysearchtopic)
        context = {
            'mydata':mydata,
            }
    return render(request, 'hzone/result.html',context)

This is my result.html page

{% for m in mydata %}
{{ m.title }}
{% endfor %}

This is my urls.py

urlpatterns = [
    path('', views.apphome, name = 'homepage'),
    path('topic/', views.searchtopic, name = 'topicname'),
]

This is my model

class myhashtaglist(models.Model):
    title = models.CharField(max_length = 200)
    slug = models.SlugField(max_length = 150, null=True, blank = True)
    topicdetails = models.TextField(max_length = 500)

what i want is whenever user click on any of the topic on result page this topic should open.
my reult page looks like

intro to django
django tutorial 1
django tutorial 2
django tutorial 3

but when i am clicking on any of the topic its not taking me to that topic.

Body:
I think the problem lies in your urls.py. You have one view (searchtopic) for two different purposes, first you are searching using def searchtopic(request) and then using the same function for getting a result. You must create a another view for your result something like def get_result(request, slug) and then define a url in your urls.py after that in your form you can do something like this:

{% for m in mydata %}
   <a href="{% url 'your-url-for-resul' m.slug %}">{{ m.title }}</a>
{% endfor %}

and the following code will be the second view:

def get_result(request, slug):
    result = get_object_or_404(Result, slug=slug)

    return render(request, 'your_template_result.html', {'result': result})

Then you must have a .html file (here is your_template_result.html) to redirect to that page and also unpack your data (here is result) inside the same html file.

I think this can solve your problem.


问:
How is Firebase storage usage calculated?

I have an ionic app that uploads some photos and download the url to store it in mlab, thats fine. I can upload 10 photos at once and download them, thats 100 uploads/downloads. Then I print the photo in a card component.

The thing is that on every click on my home page, I see so many calls to firebase to retrieve image. So I checked my free account SPARK plan on firebase and I reached 20k operations in one day just with 3 users/10 photos(upload/download) and reads in my home page.

As I said I don't get why if the image is loaded from mlab, that should print it once not load them so many times.

```<code>   private uploadPhotosToFirebase() {
    this.showLoading();
    return Promise.all(this.arrPhotos.map(photo => this.upload(photo)))
      .then((urls: string[]) => {
        console.log(`All success`, urls);
        urls.forEach((url) => this.photosUrlDownload.push(url));
        return Promise.resolve();
      })
      .catch((error) => {
        console.log(`Some failed: `, error)
        return Promise.reject();
      });
  }

  private upload(photo: PhotoModel): Promise<any> {
    var storageRef = this.firebaseStorage.storage.ref(this.userId).child(photo.name);

    return storageRef.putString(photo.base64.replace('data:image/jpeg;base64,', ''), 'base64')
      .then((snapshot) => {
        // uploaded OK
        return storageRef.getDownloadURL()
          .then((url) => {
            // downloaded OK
            return url;
          })
          .catch((err) => {
            // downloaded KO
            return err;
          });
      }).catch((error) => {
        // uploaded KO
        return error;
      });
  }
</code>```

```<code><ion-card>
  <div class="relative">
    <img class="absolute owner-image absolute small-image" src="https://ionicframework.com/docs/demos/api/card/madison.jpg" alt=""> <!-- QUITAR-->
    <ion-card-subtitle class="absolute color-white type-product">{{item.type}}</ion-card-subtitle>
    <img class="main-image" *ngIf="item && item.photos && item.photos[0]" [src]="sanitizer.bypassSecurityTrustUrl(item.photos[0])">

    <ion-icon (click)="likeProduct()" class="absolute heart color-white small-image" [name]="liking === true ? 'heart' : 'heart-outline'"></ion-icon>
  </div>
  <div class="content-wrapper">
    <ion-card-header>
      <ion-card-subtitle>{{item.name}}</ion-card-subtitle>
      <ion-card-title>{{item.price}}€</ion-card-title> <!-- CURRENCY PIPE HERE -->
    </ion-card-header>
    <ion-card-content *ngIf="item && item.description">{{item.description}}</ion-card-content>
  </div>
</ion-card>
</code>```

答:
Adding a function call directly in the HTML template is considered to be a bad practice since it will run each time the change detection has fired.

This will cause performance issues and the issue that you have (excessive requests for resources).

The correct way to address this problem is by using a custom pipe and making sure you declare it as a pure pipe so Angular will cache the result and will not run it every time the change detection has fired.

```<code>import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Pipe({
    name: 'safeURL'
})
export class SafeUrlPipe implements PipeTransform {

    constructor(
        protected sanitizer: DomSanitizer
    ) { }

    public transform(value: string): SafeUrl {
        if (!value || value === "none") {
            return "assets/img/no_image_placeholder.png"
        } else {
            return this.sanitizer.bypassSecurityTrustUrl(value);
        }
    };

};
</code>```

Body:
I have an ionic app that uploads some photos and download the url to store it in mlab, thats fine. I can upload 10 photos at once and download them, thats 100 uploads/downloads. Then I print the photo in a card component.

The thing is that on every click on my home page, I see so many calls to firebase to retrieve image. So I checked my free account SPARK plan on firebase and I reached 20k operations in one day just with 3 users/10 photos(upload/download) and reads in my home page.

As I said I don't get why if the image is loaded from mlab, that should print it once not load them so many times.

   private uploadPhotosToFirebase() {
    this.showLoading();
    return Promise.all(this.arrPhotos.map(photo => this.upload(photo)))
      .then((urls: string[]) => {
        console.log(`All success`, urls);
        urls.forEach((url) => this.photosUrlDownload.push(url));
        return Promise.resolve();
      })
      .catch((error) => {
        console.log(`Some failed: `, error)
        return Promise.reject();
      });
  }

  private upload(photo: PhotoModel): Promise<any> {
    var storageRef = this.firebaseStorage.storage.ref(this.userId).child(photo.name);

    return storageRef.putString(photo.base64.replace('data:image/jpeg;base64,', ''), 'base64')
      .then((snapshot) => {
        // uploaded OK
        return storageRef.getDownloadURL()
          .then((url) => {
            // downloaded OK
            return url;
          })
          .catch((err) => {
            // downloaded KO
            return err;
          });
      }).catch((error) => {
        // uploaded KO
        return error;
      });
  }

<ion-card>

    <ion-card-subtitle class="absolute color-white type-product">{{item.type}}</ion-card-subtitle>

    <ion-icon (click)="likeProduct()" class="absolute heart color-white small-image" [name]="liking === true ? 'heart' : 'heart-outline'"></ion-icon>

    <ion-card-header>
      <ion-card-subtitle>{{item.name}}</ion-card-subtitle>
      <ion-card-title>{{item.price}}€</ion-card-title>
    </ion-card-header>
    <ion-card-content *ngIf="item && item.description">{{item.description}}</ion-card-content>

</ion-card>

Body:
Adding a function call directly in the HTML template is considered to be a bad practice since it will run each time the change detection has fired.

This will cause performance issues and the issue that you have (excessive requests for resources).

The correct way to address this problem is by using a custom pipe and making sure you declare it as a pure pipe so Angular will cache the result and will not run it every time the change detection has fired.

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

@Pipe({
    name: 'safeURL'
})
export class SafeUrlPipe implements PipeTransform {

    constructor(
        protected sanitizer: DomSanitizer
    ) { }

    public transform(value: string): SafeUrl {
        if (!value || value === "none") {
            return "assets/img/no_image_placeholder.png"
        } else {
            return this.sanitizer.bypassSecurityTrustUrl(value);
        }
    };

};