问:
Position Elements within a flex container with predefined widths using tailwind CSS
I am currently having trouble with styling a card component using tailwind CSS.

As you cann see, the prices are not aligned properly - how can I make it aligned?

My current code for the Cards

```<code><div onClick={deleteItem} className="flex flex-row justify-center">
      <div className="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
        <div>
          <p>{props.itemName}</p>
        </div>
        <div>
          <p>{props.itemPrice} €</p>
        </div>
        <div>
          <p>X</p>
        </div>
      </div>
    </div>
</code>```

答:
The reason is flex items by default have a flex-basis: auto which means that the item should use its main size initially and flex-grow: 0, which means don't grow or don't take the available space. And what separates them is justify-between by its parent container.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

Salmon Sushi

18.99 €

X

pizza

10.5 €

X

```
</div>
</div>
</p>
<p>To fix this we will just let the last item which is the <code>X</code> parent container use its initial main size (size can also be defined), then we will distribute the free available space to the first two <code>div</code> containers or items equally.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.tailwindcss.com"></script>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="basis-0 grow bg-red-500">
      <p class="">Salmon Sushi</p>
    </div>
    <div class="basis-0 grow bg-green-500">
      <p>18.99 €</p>
    </div>
    <div class="bg-yellow-500">
      <p>X</p>
    </div>
  </div>
</div>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="basis-0 grow">
      <p>pizza</p>
    </div>
    <div class="basis-0 grow">
      <p>10.5 €</p>
    </div>
    <div class="">
      <p>X</p>
    </div>
  </div>
</div></code>```

By giving flex-basis: 0px; along with the flex-grow: 1 we are able to distribute the available spaces equally.

Additional: For lengthy texts.

Salmon Sushiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii

18.99 €€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€

X

pizza

10.5 €

X

```

Body:
I am currently having trouble with styling a card component using tailwind CSS.

As you cann see, the prices are not aligned properly - how can I make it aligned?

My current code for the Cards

{props.itemName}

{props.itemPrice} €

X

Body:
The reason is flex items by default have a flex-basis: auto which means that the item should use its main size initially and flex-grow: 0, which means don't grow or don't take the available space. And what separates them is justify-between by its parent container.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="bg-red-500">
      <p>Salmon Sushi</p>
    </div>
    <div class="bg-green-500">
      <p>18.99 €</p>
    </div>
    <div class="bg-yellow-500">
      <p>X</p>
    </div>
  </div>
</div>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="bg-red-500">
      <p>pizza</p>
    </div>
    <div class="bg-green-500">
      <p>10.5 €</p>
    </div>
    <div class="bg-yellow-500">
      <p>X</p>
    </div>
  </div>
</div>

To fix this we will just let the last item which is the X parent container use its initial main size (size can also be defined), then we will distribute the free available space to the first two div containers or items equally.

<script src="https://cdn.tailwindcss.com"></script>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="basis-0 grow bg-red-500">
      <p class="">Salmon Sushi</p>
    </div>
    <div class="basis-0 grow bg-green-500">
      <p>18.99 €</p>
    </div>
    <div class="bg-yellow-500">
      <p>X</p>
    </div>
  </div>
</div>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="basis-0 grow">
      <p>pizza</p>
    </div>
    <div class="basis-0 grow">
      <p>10.5 €</p>
    </div>
    <div class="">
      <p>X</p>
    </div>
  </div>
</div>

By giving flex-basis: 0px; along with the flex-grow: 1 we are able to distribute the available spaces equally.

Additional: For lengthy texts.

<script src="https://cdn.tailwindcss.com"></script>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="min-w-0 basis-0 grow whitespace-nowrap bg-red-500">
      <p class="truncate">Salmon Sushiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii</p>
    </div>
    <div class="min-w-0 basis-0 grow whitespace-nowrap bg-green-500">
      <p class="truncate">18.99 €€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€€</p>
    </div>
    <div class="bg-yellow-500">
      <p>X</p>
    </div>
  </div>
</div>

<div class="flex flex-row justify-center">
  <div class="bg-gray-100 w-10/12 m-1 rounded p-1 flex justify-between">
    <div class="basis-0 grow">
      <p>pizza</p>
    </div>
    <div class="basis-0 grow">
      <p>10.5 €</p>
    </div>
    <div class="">
      <p>X</p>
    </div>
  </div>
</div>


来源: stackexchange

问:
Using if statement with database in python
```<code>veri = sqlite3.connect('IBCKayıt')
v = veri.cursor()

v.execute("SELECT numsıra FROM kayıtlar WHERE EXISTS(SELECT * FROM kayıtlar WHERE numsıra)")
record = v.fetchall()

if numaraentry.get() in record:
    messagebox.showinfo("UYARI","Bu IBC Zaten Var")

if numaraentry.get() not in record:
    v.execute("INSERT INTO kayıtlar VALUES (:numsıra, :koruyucutarih, :numunedurumm, :kullandurumm)",
        {'numsıra':numaraentry.get(),
         'koruyucutarih':tarıhgırıs,
         'numunedurumm':secılmıs1.get(),
         'kullandurumm':secılmıs.get()
        })
    messagebox.showinfo("UYARI","Kayıt İşlemi Başarılı.")

veri.commit()
veri.close()
</code>```

I want it to give a warning when the same data is entered, but when I enter the same data, it does not give a warning. What do you think is the solution?

-I'm new to the form, I guess I don't know how to open a topic, sorry.

答:
Your first query doesn't make much sense; you'll want to use WHERE there.

Something like

```<code>veri = sqlite3.connect("IBCKayıt")

num = numaraentry.num()

v = veri.cursor()

v.execute("SELECT numsıra FROM kayıtlar WHERE numsıra = ? LIMIT 1", (num,))
records = v.fetchall()

if records:  # had a matching row, show error
    messagebox.showinfo("UYARI", "Bu IBC Zaten Var")
else:
    v.execute(
        "INSERT INTO kayıtlar VALUES (:numsıra, :koruyucutarih, :numunedurumm, :kullandurumm)",
        {
            "numsıra": num,
            "koruyucutarih": tarıhgırıs,
            "numunedurumm": secılmıs1.num(),
            "kullandurumm": secılmıs.num(),
        },
    )
    veri.commit()
    messagebox.showinfo("UYARI", "Kayıt İşlemi Başarılı.")

veri.close()
</code>```

should do the trick.

ContentLicense: CC BY-SA 4.0

Body:
veri = sqlite3.connect('IBCKayıt')
v = veri.cursor()

v.execute("SELECT numsıra FROM kayıtlar WHERE EXISTS(SELECT * FROM kayıtlar WHERE numsıra)")
record = v.fetchall()

if numaraentry.get() in record:
    messagebox.showinfo("UYARI","Bu IBC Zaten Var")

if numaraentry.get() not in record:
    v.execute("INSERT INTO kayıtlar VALUES (:numsıra, :koruyucutarih, :numunedurumm, :kullandurumm)",
        {'numsıra':numaraentry.get(),
         'koruyucutarih':tarıhgırıs,
         'numunedurumm':secılmıs1.get(),
         'kullandurumm':secılmıs.get()
        })
    messagebox.showinfo("UYARI","Kayıt İşlemi Başarılı.")

veri.commit()
veri.close()

I want it to give a warning when the same data is entered, but when I enter the same data, it does not give a warning. What do you think is the solution?

-I'm new to the form, I guess I don't know how to open a topic, sorry.

Body:
Your first query doesn't make much sense; you'll want to use WHERE there.

Something like

veri = sqlite3.connect("IBCKayıt")

num = numaraentry.num()

v = veri.cursor()

v.execute("SELECT numsıra FROM kayıtlar WHERE numsıra = ? LIMIT 1", (num,))
records = v.fetchall()

if records:  # had a matching row, show error
    messagebox.showinfo("UYARI", "Bu IBC Zaten Var")
else:
    v.execute(
        "INSERT INTO kayıtlar VALUES (:numsıra, :koruyucutarih, :numunedurumm, :kullandurumm)",
        {
            "numsıra": num,
            "koruyucutarih": tarıhgırıs,
            "numunedurumm": secılmıs1.num(),
            "kullandurumm": secılmıs.num(),
        },
    )
    veri.commit()
    messagebox.showinfo("UYARI", "Kayıt İşlemi Başarılı.")

veri.close()

should do the trick.


问:
Numpy matrix multiplication causing windows exception
This morning I updated my anaconda environment in the usual way using conda update --all. This seems to have broken matrix multiplication in Numpy. During the update Spyder, of which I use the iPython console to run this code, was updated from version 5.2.2.0 to version 5.2.2.2. This is the the update report generated by anaconda. Furthermore, I am running Python version 3.9.10, iPython version 7.31.1 and Numpy version 1.22.2 on a windows 10 machine.

Every time I try to run either np.dot(A, B), np.matmul(A, B) or A @ B with square two-dimensional Numpy arrays I get a Windows fatal exception with code 0xc06d007e. But when either A or B are one-dimensional arrays, the matrix multiplication works as expected. Below I show a minimal code snippet reproducing this:

```<code>Python 3.9.10 | packaged by conda-forge | (main, Feb  1 2022, 21:22:07) [MSC v.1929 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.31.1 -- An enhanced Interactive Python.

In[1]: import numpy as np

In[2]: dims = 1

In[3]: N = 30

In[4]: A = np.arange(N**dims).reshape(*[N]*dims)

In[5]: B = np.eye(N)

In[6]: B @ A
Out[6]:
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25.,
       26., 27., 28., 29.])

In[7]: dims = 2

In[8]: A = np.arange(N**dims).reshape(*[N]*dims)

In[9]: B @ A

Windows fatal exception: code 0xc06d007e

Main thread:
Current thread 0x00003934 (most recent call first):
  File "C:\Users\timvr\AppData\Local\Temp\ipykernel_18916\2990787033.py", line 1 in <module>

Restarting kernel...
</code>```

I've tracked the error to the @array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) decorator decorating the definition of dot in ENVIRONMENT_PATH\Lib\site-packages\numpy\core\multiarray.py.

答:
I was able to resolve the issue by reinstalling Spyder, Numpy and their dependencies. After each reinstall I ran the code in my original question to see if anything had broken yet. The list of packages that I manually reinstalled after uninstalling Spyder and Numpy were:

Numpy

Scipy

Spyder

Uncertainties

QCodes

QuTip

HDF5

PyQTGraph

LMFit

Body:
This morning I updated my anaconda environment in the usual way using conda update --all. This seems to have broken matrix multiplication in Numpy. During the update Spyder, of which I use the iPython console to run this code, was updated from version 5.2.2.0 to version 5.2.2.2. This is the the update report generated by anaconda. Furthermore, I am running Python version 3.9.10, iPython version 7.31.1 and Numpy version 1.22.2 on a windows 10 machine.

Every time I try to run either np.dot(A, B), np.matmul(A, B) or A @ B with square two-dimensional Numpy arrays I get a Windows fatal exception with code 0xc06d007e. But when either A or B are one-dimensional arrays, the matrix multiplication works as expected. Below I show a minimal code snippet reproducing this:

Python 3.9.10 | packaged by conda-forge | (main, Feb  1 2022, 21:22:07) [MSC v.1929 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.31.1 -- An enhanced Interactive Python.

In[1]: import numpy as np

In[2]: dims = 1

In[3]: N = 30

In[4]: A = np.arange(N**dims).reshape(*[N]*dims)

In[5]: B = np.eye(N)

In[6]: B @ A
Out[6]:
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25.,
       26., 27., 28., 29.])

In[7]: dims = 2

In[8]: A = np.arange(N**dims).reshape(*[N]*dims)

In[9]: B @ A

Windows fatal exception: code 0xc06d007e

Main thread:
Current thread 0x00003934 (most recent call first):
  File "C:\Users\timvr\AppData\Local\Temp\ipykernel_18916\2990787033.py", line 1 in <module>

Restarting kernel...

I've tracked the error to the @array_function_from_c_func_and_dispatcher(_multiarray_umath.dot) decorator decorating the definition of dot in ENVIRONMENT_PATH\Lib\site-packages\numpy\core\multiarray.py.


问:
Using Spring IoC to set up enum values
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

```<code>public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}
</code>```

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

答:
I don't think it can be done from Spring's ApplicationContext configuration. But, do you really need it done by Spring, or can you settle for simple externalization using ResourceBundle; like this:

```<code>public enum Car
{
    NANO,
    MERCEDES,
    FERRARI;

    public final String cost;
    public final String madeIn;

    Car()
    {
            this.cost = BUNDLE.getString("Car." + name() + ".cost");
            this.madeIn = BUNDLE.getString("Car." + name() + ".madeIn");
    }

    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(...);

}
</code>```

In the properties file, one for each specific locale, enter the keys describing the possible internal enum values:

```<code>Car.NANO.cost=Very cheap
Car.NANO.madeIn=India
Car.MERCEDES.cost=Expensive
...
</code>```

The only drawback of this approach is having to repeat the name of enum fields (cost, madeIn) in Java code as strings. Edit: And on the plus side, you can stack all properties of all enums into one properties file per language/locale.

OwnerDisplayName: Olivier

ContentLicense: CC BY-SA 3.0

Title: Using Spring IoC to set up enum values

Body:
Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

LastEditorDisplayName: Olivier

Body:
I don't think it can be done from Spring's ApplicationContext configuration. But, do you really need it done by Spring, or can you settle for simple externalization using ResourceBundle; like this:

public enum Car
{
    NANO,
    MERCEDES,
    FERRARI;

    public final String cost;
    public final String madeIn;

    Car()
    {
            this.cost = BUNDLE.getString("Car." + name() + ".cost");
            this.madeIn = BUNDLE.getString("Car." + name() + ".madeIn");
    }

    private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(...);

}

In the properties file, one for each specific locale, enter the keys describing the possible internal enum values:

Car.NANO.cost=Very cheap
Car.NANO.madeIn=India
Car.MERCEDES.cost=Expensive
...

The only drawback of this approach is having to repeat the name of enum fields (cost, madeIn) in Java code as strings. Edit: And on the plus side, you can stack all properties of all enums into one properties file per language/locale.

OwnerDisplayName: javashlook

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: javashlook


问:
property method and other methods in django models
I have been using the property method every now and then and understand its uses. It basically acts the same as the field but without actually creating a column in db, and can be easily accessed within the serializer as model fields. But how can the other methods be accessed just like this baby_boomer function of Person model here below? How can it be accessed in serializer and also in the views or queryset??</p>
```<code>class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

    @property
    def full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)
</code>```

答:
Pass the source parameter to a serializer field to access a method on the model, the method must take only a single self parameter

```<code>class PersonSerializer(serializers.ModelSerializer):

    foo = serializers.CharField(source='baby_boomer_status', read_only=True)

    class Meta:
        model = Person
        fields = ['field_a', 'field_b']
</code>```

Body:
I have been using the property method every now and then and understand its uses. It basically acts the same as the field but without actually creating a column in db, and can be easily accessed within the serializer as model fields. But how can the other methods be accessed just like this baby_boomer function of Person model here below? How can it be accessed in serializer and also in the views or queryset??

class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    birth_date = models.DateField()

    def baby_boomer_status(self):
        "Returns the person's baby-boomer status."
        import datetime
        if self.birth_date < datetime.date(1945, 8, 1):
            return "Pre-boomer"
        elif self.birth_date < datetime.date(1965, 1, 1):
            return "Baby boomer"
        else:
            return "Post-boomer"

    @property
    def full_name(self):
        "Returns the person's full name."
        return '%s %s' % (self.first_name, self.last_name)

Body:
Pass the source parameter to a serializer field to access a method on the model, the method must take only a single self parameter

class PersonSerializer(serializers.ModelSerializer):

    foo = serializers.CharField(source='baby_boomer_status', read_only=True)

    class Meta:
        model = Person
        fields = ['field_a', 'field_b']


问:
Problem with FreeCodeCamp's "MongoDB and Mongoose - Create a Model" Challenge
I am doing FreeCodeCamp's "MongoDB and Mongoose - Create a Model" challenge. I have submitted by code. However, I am getting this error:

```<code>Creating an instance from a mongoose schema should succeed
</code>```

Here are my codes:

```<code>let mongoose = require('mongoose')
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });

let personSchema = new mongoose.Schema({
  name: {type: String, required: true},
  age: Number,
  favoriteFoods: [String]
});

let Person = mongoose.model('Person', personSchema);
</code>```

Have I made any mistake?

答:
It appears that the problem occurs because a code below is trying to redeclare the "Person" variable (After making it a const). If you look at the boilerplate code on Replit, there were some codes present there already and part of this code has the following:
let Person;

Simply commenting this line out worked for me.

Body:
I am doing FreeCodeCamp's "MongoDB and Mongoose - Create a Model" challenge. I have submitted by code. However, I am getting this error:

Creating an instance from a mongoose schema should succeed

Here are my codes:

let mongoose = require('mongoose')
mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true });

let personSchema = new mongoose.Schema({
  name: {type: String, required: true},
  age: Number,
  favoriteFoods: [String]
});

let Person = mongoose.model('Person', personSchema);

Have I made any mistake?


问:
How to find all matches of IP v4 addresses and subnets in a text file and print matches line by line with given prefix using only one command?
I would like to replace this pipeline of three commands with one. I think that it is possible to achieve a similar result with only awk or sed.

Current solution with cat, greep and awk

```<code>cat textfile | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}(\/[0-9]{1,2}|)" | awk '{print "prefix "$0}'
</code>```

Text file example:

```<code>192.168.1.1 10.100.20.0/24 some text  2a05:d014:d13:26aa:f493:ef87:bb60:d85f
10.15.12.11, text "10.10.0.0/16" =25.0.0.0/12 etc
</code>```

Output:

```<code>prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12
</code>```

Body:
I would like to replace this pipeline of three commands with one. I think that it is possible to achieve a similar result with only awk or sed.

Current solution with cat, greep and awk

cat textfile | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}(\/[0-9]{1,2}|)" | awk '{print "prefix "$0}'

Text file example:

192.168.1.1 10.100.20.0/24 some text  2a05:d014:d13:26aa:f493:ef87:bb60:d85f
10.15.12.11, text "10.10.0.0/16" =25.0.0.0/12 etc

Output:

prefix 192.168.1.1
prefix 10.100.20.0/24
prefix 10.15.12.11
prefix 10.10.0.0/16
prefix 25.0.0.0/12

Body:
Using sed

$ sed -z 's/["=]\?\([0-9][^[:space:],"]*\)[a-z ",\n]*/prefeix \1\n/g' input_file
prefeix 192.168.1.1
prefeix 10.100.20.0/24
prefeix 10.15.12.11
prefeix 10.10.0.0/16
prefeix 25.0.0.0/12


问:
How can I split strings so that only numbers are selected?

please excuse me for the change in this question

I want to split a string (e.g. text1, text2), so that only numbers are output:

I tried the following:

```<code>import re

# example text1

text1 = " climb   -  95/ 85     0.18   low     -  4680"

split_text1 = re.split(" +", text1)

print(split_text1)

['', 'climb', '-', '95/', '85', '0.18', 'low', '-', '4680']

# example text2

text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

split_text2 = re.split(" +", text2)

print(split_text2)

['CD 3 TO', 'F TO GD', '.80000E+02', '.00000E+00', '.00000E+00', '.00000E+00 /']
</code>```

How can I get as result:

```<code># split_text1 = ['95', '85', '0.18', '4680']

# split_text2 = ['3', '80.0','0.0', '0.0', 0.0]
</code>```

答:
First version of the question:

You can ask to split with at least 2 spaces

import re

text = " climb   -  95/ 85     0.18   low     -  4680"

split_text = re.split("\s{2,}", text)

print(split_text)
# [' climb', '-', '95/ 85', '0.18', 'low', '-', '4680']
```
<p>Works too without regex</p>
<pre class="lang-py prettyprint-override"><code>text = " climb   -  95/ 85     0.18   low     -  4680"

split_text = text.split('  ')

print(split_text)
# [' climb', ' -', '95/ 85', '', ' 0.18', ' low', '', ' -', '4680']
</code>```

With some more manipulation, you can also remove extra spaces

text = " climb   -  95/ 85     0.18   low     -  4680"

split_text = list(map(lambda x: x.strip(), text.split('  ')))

print(split_text)
# ['climb', '-', '95/ 85', '', '0.18', 'low', '', '-', '4680']
```
<hr />
<p>Revised question</p>
<p>You need to match numbers (<code>\d</code> in regex), some are floats (so we need to match a single dot), some are exponential (we need to match <code>E+</code>)</p>
<p>Something like that should be a good start</p>
<pre class="lang-py prettyprint-override"><code>import re

regex = r'[\d.E+-]+' # try to match `E` and negatives

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = re.findall(regex, text1)
# ['-', '95', '85', '0.18', '-', '4680']

results2 = re.findall(regex, text2)
# ['3', '.80000E+02', '.00000E+00', '.00000E+00', '.00000E+00']
</code>```

It matches a single - without numbers, we can be more specific for negative numbers.

import re

regex = r'-?\d+[\d.E+-]*'

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = re.findall(regex, text1)
# ['95', '85', '0.18', '4680']

results2 = re.findall(regex, text2)
# ['3', '80000E+02', '00000E+00', '00000E+00', '00000E+00']
```
<p>You need to transform exponential to a float form, again, a map should do it</p>
<pre class="lang-py prettyprint-override"><code>import re

regex = r'-?\d+[\d.E+-]*'

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = list(map(float, re.findall(regex, text1)))
# [95.0, 85.0, 0.18, 4680.0]

results2 = list(map(float, re.findall(regex, text2)))
# [3.0, 8000000.0, 0.0, 0.0, 0.0]
</code>```

To be closest to your proposition

import re

regex = r'-?\d+[\d.E+-]*'

def transform(value):
    if 'E' in value:
        return str(float(value))

    return value

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = list(map(transform, re.findall(regex, text1)))
# ['95', '85', '0.18', '4680']

results2 = list(map(transform, re.findall(regex, text2)))
# ['3', '8000000.0', '0.0', '0.0', '0.0']
```
<p>And I just see now that my regex miss the first dot....</p>
<pre class="lang-py prettyprint-override"><code>import re

regex = r'-?(?:\d*\.\d+|\d+)(?:E[+-]\d+)?'

def transform(value):
    if 'E' in value:
        return str(float(value))

    return value

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = list(map(transform, re.findall(regex, text1)))
# ['95', '85', '0.18', '4680']

results2 = list(map(transform, re.findall(regex, text2)))
# ['3', '80.0', '0.0', '0.0', '0.0']
</code>```

To explain a little, -? it may start with minus.

(?: ) group without capturing, easier to group without changing the result

\d*\.\d+ match at least a dot and numbers after, may match numbers before the dot

| simple or

\d+ match any numbers

(?:\d*\.\d+|\d+) everything together, so a group without capture that match any float or any integer

[+-] can be + or -

(?:E[+-]\d+)? quite the same, it a group without capture that match an E followed by + or - with any integer after, the group itself can be here one time or never (the last ?)

Body:
please excuse me for the change in this question

I want to split a string (e.g. text1, text2), so that only numbers are output:

I tried the following:

import re

# example text1

text1 = " climb   -  95/ 85     0.18   low     -  4680"

split_text1 = re.split(" +", text1)

print(split_text1)

['', 'climb', '-', '95/', '85', '0.18', 'low', '-', '4680']

# example text2

text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

split_text2 = re.split(" +", text2)

print(split_text2)

['CD 3 TO', 'F TO GD', '.80000E+02', '.00000E+00', '.00000E+00', '.00000E+00 /']

How can I get as result:

# split_text1 = ['95', '85', '0.18', '4680']

# split_text2 = ['3', '80.0','0.0', '0.0', 0.0]

Body:
First version of the question:

You can ask to split with at least 2 spaces

import re

text = " climb   -  95/ 85     0.18   low     -  4680"

split_text = re.split("\s{2,}", text)

print(split_text)
# [' climb', '-', '95/ 85', '0.18', 'low', '-', '4680']

Works too without regex

text = " climb   -  95/ 85     0.18   low     -  4680"

split_text = text.split('  ')

print(split_text)
# [' climb', ' -', '95/ 85', '', ' 0.18', ' low', '', ' -', '4680']

With some more manipulation, you can also remove extra spaces

text = " climb   -  95/ 85     0.18   low     -  4680"

split_text = list(map(lambda x: x.strip(), text.split('  ')))

print(split_text)
# ['climb', '-', '95/ 85', '', '0.18', 'low', '', '-', '4680']

Revised question

You need to match numbers (\d in regex), some are floats (so we need to match a single dot), some are exponential (we need to match E+)

Something like that should be a good start

import re

regex = r'[\d.E+-]+' # try to match `E` and negatives

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = re.findall(regex, text1)
# ['-', '95', '85', '0.18', '-', '4680']

results2 = re.findall(regex, text2)
# ['3', '.80000E+02', '.00000E+00', '.00000E+00', '.00000E+00']

It matches a single - without numbers, we can be more specific for negative numbers.

import re

regex = r'-?\d+[\d.E+-]*'

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = re.findall(regex, text1)
# ['95', '85', '0.18', '4680']

results2 = re.findall(regex, text2)
# ['3', '80000E+02', '00000E+00', '00000E+00', '00000E+00']

You need to transform exponential to a float form, again, a map should do it

import re

regex = r'-?\d+[\d.E+-]*'

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = list(map(float, re.findall(regex, text1)))
# [95.0, 85.0, 0.18, 4680.0]

results2 = list(map(float, re.findall(regex, text2)))
# [3.0, 8000000.0, 0.0, 0.0, 0.0]

To be closest to your proposition

import re

regex = r'-?\d+[\d.E+-]*'

def transform(value):
    if 'E' in value:
        return str(float(value))

    return value

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = list(map(transform, re.findall(regex, text1)))
# ['95', '85', '0.18', '4680']

results2 = list(map(transform, re.findall(regex, text2)))
# ['3', '8000000.0', '0.0', '0.0', '0.0']

And I just see now that my regex miss the first dot....

import re

regex = r'-?(?:\d*\.\d+|\d+)(?:E[+-]\d+)?'

def transform(value):
    if 'E' in value:
        return str(float(value))

    return value

text1 = " climb   -  95/ 85     0.18   low     -  4680"
text2 = "CD 3 TO   F TO GD   .80000E+02   .00000E+00   .00000E+00   .00000E+00 /"

results1 = list(map(transform, re.findall(regex, text1)))
# ['95', '85', '0.18', '4680']

results2 = list(map(transform, re.findall(regex, text2)))
# ['3', '80.0', '0.0', '0.0', '0.0']

To explain a little, -? it may start with minus.

(?: ) group without capturing, easier to group without changing the result

\d*\.\d+ match at least a dot and numbers after, may match numbers before the dot

| simple or

\d+ match any numbers

(?:\d*\.\d+|\d+) everything together, so a group without capture that match any float or any integer

[+-] can be + or -

(?:E[+-]\d+)? quite the same, it a group without capture that match an E followed by + or - with any integer after, the group itself can be here one time or never (the last ?)


问:
CKEditor 5 video embed is not displayed on the presentation page
I know that this has been asked many times, but I open this discussion to solve my problem and to summarize all we know about this topic to help people in the future.

So, let's go.
We want to upload a video (e.g. from YouTube). We can do this pasting the video url or using the MediaEmbed button.

We have two possibility.

We can set or not in our editorConfig

mediaEmbed: { previewsInData: true }

WITHOUT previewsInData: true we obtain something like this:

  <oembed url="https://www.youtube.com/watch?v=something"></oembed>

```
</div>
</div>
</p>
<p>Instead WITH <code>previewsInData: true</code> we obtain something like this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><figure class="media">
  <div data-oembed-url="https://www.youtube.com/watch?v=vsl3gBVO2k4&ab_channel=H%C3%A9lderPalma">
    <div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 56.2493%;">
      <iframe src="https://www.youtube.com/embed/vsl3gBVO2k4" style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen="">
      </iframe>
    </div>
  </div>
</figure></code>```

In both cases i'm able to see the preview of the youtube video in my CKEditor.
But when I save the content of the editor and I get that to display it in my presentation page the video is not displayed.

Reading the other discussions here on the forum I couldn't figure out if this is just my problem or not. Many solutions concerning adding previewsInData: true in editorConfig, but for me absolutely nothing changes.

I think that the tag figure and the oembed div is useful to CKEditor to display a preview of the video. We know that this preview is like a picture, you can't play the video, you can't open in a new page, etc. This is ok, but i want to see the video in my presentation page.

So, where is the problem?

Is there something to change on the presentation page to have the video displayed?

Should I search for the figure tag and replace it with an iframe server side?

Any ideas?

I hope we can find a permanent solution to this problem.

答:
You should indeed use a 'frontend' to display the oembed tags, like it says in the manual on : https://ckeditor.com/docs/ckeditor5/latest/features/media-embed.html#displaying-embedded-media-on-your-website

You can provide your own mediaprovider using this :

```<code>        ClassicEditor
        .create( editorElement, {
            plugins: [ MediaEmbed, ... ],
            mediaEmbed: {
                extraProviders: [
                    {
                         name: 'extraProvider',
                         url: /^example\.com\/media\/(\w+)/,
                         html: match => '...'
                    },
                    ...
                ]
            }
        } )
    .then( ... )
    .catch( ... );
</code>```

and the html could be something like :

```<code>...
html: match =>
    '<div style="position:relative; padding-bottom:100%; height:0">' +
        '<iframe src="..." frameborder="0" ' +
            'style="position:absolute; width:100%; height:100%; top:0; left:0">' +
        '</iframe>' +
    '</div>'
</code>```

you can find more in de docs, here :

https://ckeditor.com/docs/ckeditor5/latest/api/module_media-embed_mediaembed-MediaEmbedProvider.html

you could also do something like this yourself, avoiding external oembed providers:

window.addEventListener('load', function(){
    document.querySelectorAll('oembed[url]').forEach( element => {
        // get just the code for this youtube video from the url
        let vCode = element.attributes.url.value.split('?v=')[1];
        // paste some BS5 embed code in place of the Figure tag
    element.parentElement.outerHTML= `

`;
    });
})```

You would ofcourse have to upgrade the script for all different versions of embedded content, this example will just work for youtube. You would have to analyze the URL from the oembed tag to check what is embedded so you can add the right code for each variant.

Body:
I know that this has been asked many times, but I open this discussion to solve my problem and to summarize all we know about this topic to help people in the future.

So, let's go.
We want to upload a video (e.g. from YouTube). We can do this pasting the video url or using the MediaEmbed button.

We have two possibility.

We can set or not in our editorConfig

mediaEmbed: { previewsInData: true }

WITHOUT previewsInData: true we obtain something like this:

  <oembed url="https://www.youtube.com/watch?v=something"></oembed>

Instead WITH previewsInData: true we obtain something like this

In both cases i'm able to see the preview of the youtube video in my CKEditor.
But when I save the content of the editor and I get that to display it in my presentation page the video is not displayed.

Reading the other discussions here on the forum I couldn't figure out if this is just my problem or not. Many solutions concerning adding previewsInData: true in editorConfig, but for me absolutely nothing changes.

I think that the tag figure and the oembed div is useful to CKEditor to display a preview of the video. We know that this preview is like a picture, you can't play the video, you can't open in a new page, etc. This is ok, but i want to see the video in my presentation page.

So, where is the problem?

Is there something to change on the presentation page to have the video displayed?

Should I search for the figure tag and replace it with an iframe server side?

Any ideas?

I hope we can find a permanent solution to this problem.

Body:
You should indeed use a 'frontend' to display the oembed tags, like it says in the manual on : https://ckeditor.com/docs/ckeditor5/latest/features/media-embed.html#displaying-embedded-media-on-your-website

You can provide your own mediaprovider using this :

        ClassicEditor
        .create( editorElement, {
            plugins: [ MediaEmbed, ... ],
            mediaEmbed: {
                extraProviders: [
                    {
                         name: 'extraProvider',
                         url: /^example\.com\/media\/(\w+)/,
                         html: match => '...'
                    },
                    ...
                ]
            }
        } )
    .then( ... )
    .catch( ... );

and the html could be something like :

...
html: match =>
    '<div style="position:relative; padding-bottom:100%; height:0">' +
        '<iframe src="..." frameborder="0" ' +
            'style="position:absolute; width:100%; height:100%; top:0; left:0">' +
        '</iframe>' +
    '</div>'

you can find more in de docs, here :

https://ckeditor.com/docs/ckeditor5/latest/api/module_media-embed_mediaembed-MediaEmbedProvider.html

you could also do something like this yourself, avoiding external oembed providers:

window.addEventListener('load', function(){
    document.querySelectorAll('oembed[url]').forEach( element => {
        // get just the code for this youtube video from the url
        let vCode = element.attributes.url.value.split('?v=')[1];
        // paste some BS5 embed code in place of the Figure tag
    element.parentElement.outerHTML= `
    <div class="ratio ratio-16x9">
        <iframe src="https://www.youtube.com/embed/${vCode}?rel=0"  allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    </div>`;
    });
})

You would ofcourse have to upgrade the script for all different versions of embedded content, this example will just work for youtube. You would have to analyze the URL from the oembed tag to check what is embedded so you can add the right code for each variant.


问:
Why isn't the C# inequality operator !==?
In C#, == is used to check equality, whereas = is for assignment.

Does this mean that checking for inequality should really be !==.

Why isn't this the case? Os it for historical reasons?

The rise of != has seen it establish itself in most SQL variations now too.

答:
== is just a synonym for Equality, != is just one for inequality. It is just a synonym! It is no logical expression and therefore there is no need to follow any logical rules! It is the same with &=, |=, ^=...

It is not that !!=====.Equals(true), it is just a name ;)


问:
How to update image source on hover?
I'm trying to use Next.js Image component to render images on my app page. I'm having issues understanding how to select and update the main Image src so that I can replace it with all the responsive sizes Next.js creates for Image elements.

I have a list of navigation links in my app menu and I want to assign data attributes to each one so that when these links are hovered over they update the main Image element and display a different main image for each link hovered over.

I'm new to React and the way it works, so I'm not sure what my issues are but I have made a start with some basic concepts. I have started to console log the data I have to see what I get but now I've hit a brick wall.

Here is what I have so far:

```<code>import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';

function Header() {

  const MenuHeroImg = useRef();

  function handleMouseEnter(e) {
    console.log(e.target.getAttribute('data-project-image-url'));
    console.log(MenuHeroImg.current);
  }

  return (
    <>
     <ul>
        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_2.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here">Link</Link>
        </li>
        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_3.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here_2">Link</Link>
        </li>
     <ul>
     <picture ref={MenuHeroImg}>
       <Image
        src="/public/images/projects/image_1.png"
        alt="Image"
        width={660}
        height={835}
        layout="responsive"
       />
     </picture>
    </>
  );
}

export default Header;
</code>```

Console Log:

答:
Rather than using data-* attributes to set the images paths, move the image source into a state variable that you can then update when each onMouseEnter gets triggered.

Also note that images in the public folder are referenced as /images/projects/image_1.png, without the /public.

import React, { useState } from 'react';
import Image from 'next/image';

function Header() {
    const [image, setImage] = useState('/images/projects/image_1.png');

    function handleMouseEnter(imagePath) {
        return () => {
            setImage(imagePath);
        };
    }

    return (
        <>

                <li
                    onMouseEnter={handleMouseEnter('/images/projects/image_2.png')}
                    className={`${navigationStyles['c-navigation-menu-link']}`}
                >
                    <Link href="/project-link-here">Link</Link>

                <li
                    onMouseEnter={handleMouseEnter('/images/projects/image_3.png')}
                    className={`${navigationStyles['c-navigation-menu-link']}`}
                >
                    <Link href="/project-link-here_2">Link</Link>

            <Image
                src={image}
                alt="Image"
                width={660}
                height={835}
                layout="responsive"
            />
        </>
    );
}

export default Header;
```

Title: How to update image source on hover?

Body:
I'm trying to use Next.js Image component to render images on my app page. I'm having issues understanding how to select and update the main Image src so that I can replace it with all the responsive sizes Next.js creates for Image elements.

I have a list of navigation links in my app menu and I want to assign data attributes to each one so that when these links are hovered over they update the main Image element and display a different main image for each link hovered over.

I'm new to React and the way it works, so I'm not sure what my issues are but I have made a start with some basic concepts. I have started to console log the data I have to see what I get but now I've hit a brick wall.

Here is what I have so far:

import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';

function Header() {

  const MenuHeroImg = useRef();

  function handleMouseEnter(e) {
    console.log(e.target.getAttribute('data-project-image-url'));
    console.log(MenuHeroImg.current);
  }

  return (
    <>

        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_2.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here">Link</Link>

        <li
         onMouseEnter={handleMouseEnter}
         data-project-image-url="/public/images/projects/image_3.png"
         className={`${navigationStyles['c-navigation-menu-link']}`}>
         <Link href="/project-link-here_2">Link</Link>

     <picture ref={MenuHeroImg}>
       <Image
        src="/public/images/projects/image_1.png"
        alt="Image"
        width={660}
        height={835}
        layout="responsive"
       />
     </picture>
    </>
  );
}

export default Header;

Console Log:

Body:
Rather than using data-* attributes to set the images paths, move the image source into a state variable that you can then update when each onMouseEnter gets triggered.

Also note that images in the public folder are referenced as /images/projects/image_1.png, without the /public.

import React, { useState } from 'react';
import Image from 'next/image';

function Header() {
    const [image, setImage] = useState('/images/projects/image_1.png');

    function handleMouseEnter(imagePath) {
        return () => {
            setImage(imagePath);
        };
    }

    return (
        <>
            <ul>
                <li
                    onMouseEnter={handleMouseEnter('/images/projects/image_2.png')}
                    className={`${navigationStyles['c-navigation-menu-link']}`}
                >
                    <Link href="/project-link-here">Link</Link>
                </li>
                <li
                    onMouseEnter={handleMouseEnter('/images/projects/image_3.png')}
                    className={`${navigationStyles['c-navigation-menu-link']}`}
                >
                    <Link href="/project-link-here_2">Link</Link>
                </li>
            <ul>
            <Image
                src={image}
                alt="Image"
                width={660}
                height={835}
                layout="responsive"
            />
        </>
    );
}

export default Header;


问:
qqplot and qqline in loop
i am trying to make a loop for each columns in the database.
i am getting this Error: Must use a vector in [, not an object of class matrix.
my data looks like this:
and this is my code:

```<code>for (q in 1:ncol(flat_file_numeric[])) {
    qqnorm(flat_file_numeric[,q])
    qqline(flat_file_numeric[,q], col= "steelblue",lwd=2)}
</code>```

i will appreciate any help.
thanks.

答:
Without some actual data is it hard to be sure, but from the error message it looks like some problem with the data itself.

I would start by trying this prior to the loop:

```<code>flat_file_numeric <- as.data.frame(flat_file_numeric)
</code>```

Title: qqplot and qqline in loop

Body:
i am trying to make a loop for each columns in the database.
i am getting this Error: Must use a vector in [, not an object of class matrix.
my data looks like this:
and this is my code:

for (q in 1:ncol(flat_file_numeric[])) {
    qqnorm(flat_file_numeric[,q])
    qqline(flat_file_numeric[,q], col= "steelblue",lwd=2)}

i will appreciate any help.
thanks.

Body:
Without some actual data is it hard to be sure, but from the error message it looks like some problem with the data itself.

I would start by trying this prior to the loop:

flat_file_numeric <- as.data.frame(flat_file_numeric)


问:
How to use vertex dentifiers in Boost graph of size int64_t
I am trying to add edges to a Boost undirected graph using boost::add_edge(...). The graph is defined as:

```<code>using osm_id_t = int64_t;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,
        // vertex properties
        boost::property<boost::vertex_index_t, osm_id_t,
        boost::property<boost::vertex_color_t, boost::default_color_type> >,
        // edge properties
        boost::no_property> UndirectedOSMIdGraph;

</code>```

I do not get compile errors. My code works fine, if the vertices are ints (e.g. boost::add_edge(1, 2, g)). However, as soon as I add vertices as int64_t, I get a "terminate called after throwing an instance of 'std::bad_alloc'

```<code>    UndirectedOSMIdGraph g;
    osm_id_t large {1810014749};
    boost::add_edge (large, 2, g);  //if instead large is just 1 it works
    boost::add_edge (2, 3, g);
    ...

</code>```

I guess I have to specify somehow the size of the vertex numbers - but I just do not understand how to do it. Note: I do not want to add extra properties to the vertices - I just need large numbers for the vertices (because they are identifiers from OpenStreetMap).

答:
Using vecS the vertex index is implicit. They correspond to the index in the vertex storage container, which is vector.

This means that using vertex index 1810014749 on g would be Undefined Behaviour if you have fewer than 1810014750 vertices. "Luckily" (?) for you add_edge is smart enough to detect this and resize the vector in the case of vecS container selector, so it tries to allocate enough storage for the highest vertex id mentioned before adding the edge, which fails because your program doesn't have access to that much memory:

```<code>    at /usr/include/c++/10/ext/new_allocator.h:115
115             return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));
</code>```

Here, 1810014750 * sizeof(_Tp) is 14,48 GB.

Other than that, 64 bits is no problem, since the vertex descriptor would already be 64 (albeit unsigned):

```<code>using V = UndirectedOSMIdGraph::vertex_descriptor;

static_assert(not std::is_same_v<osm_id_t, V>);
static_assert(std::is_same_v<std::make_unsigned_t<osm_id_t>, V>);
static_assert(sizeof(osm_id_t) == sizeof(V));
</code>```

So as long as you don't actually use negative osm_id_t there was no technical barrier to using osm_id_t as the index.

"Sparse" vertex index

If your vertex index isn't dense then vecS might be less suited for your storage. Consider using something else:

Live On Compiler Exlorer

```<code>#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>

using osm_id_t = int64_t;

using UndirectedOSMIdGraph = boost::adjacency_list<
    boost::vecS, boost::listS, boost::undirectedS,
    boost::property<
        boost::vertex_index_t, osm_id_t,
        boost::property<boost::vertex_color_t, boost::default_color_type>>,
    boost::no_property>;

using V = UndirectedOSMIdGraph::vertex_descriptor;

static_assert(not std::is_same_v<std::make_unsigned_t<osm_id_t>, V>);

int main() {
    UndirectedOSMIdGraph g;

    osm_id_t large{1810014749};
    auto     v2 = add_vertex(2, g);
    add_edge(add_vertex(large, g), v2, g);
    add_edge(v2, add_vertex(3, g), g);

    print_graph(g);
}
</code>```

Prints

```<code>2 <--> 1810014749 3
1810014749 <--> 2
3 <--> 2
</code>```

Body:
I am trying to add edges to a Boost undirected graph using boost::add_edge(...). The graph is defined as:

using osm_id_t = int64_t;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS,
        // vertex properties
        boost::property<boost::vertex_index_t, osm_id_t,
        boost::property<boost::vertex_color_t, boost::default_color_type> >,
        // edge properties
        boost::no_property> UndirectedOSMIdGraph;

I do not get compile errors. My code works fine, if the vertices are ints (e.g. boost::add_edge(1, 2, g)). However, as soon as I add vertices as int64_t, I get a "terminate called after throwing an instance of 'std::bad_alloc'

    UndirectedOSMIdGraph g;
    osm_id_t large {1810014749};
    boost::add_edge (large, 2, g);  //if instead large is just 1 it works
    boost::add_edge (2, 3, g);
    ...

I guess I have to specify somehow the size of the vertex numbers - but I just do not understand how to do it. Note: I do not want to add extra properties to the vertices - I just need large numbers for the vertices (because they are identifiers from OpenStreetMap).

Body:
Using vecS the vertex index is implicit. They correspond to the index in the vertex storage container, which is vector.

This means that using vertex index 1810014749 on g would be Undefined Behaviour if you have fewer than 1810014750 vertices. "Luckily" (?) for you add_edge is smart enough to detect this and resize the vector in the case of vecS container selector, so it tries to allocate enough storage for the highest vertex id mentioned before adding the edge, which fails because your program doesn't have access to that much memory:

    at /usr/include/c++/10/ext/new_allocator.h:115
115             return static_cast<_Tp*>(::operator new(__n * sizeof(_Tp)));

Here, 1810014750 * sizeof(_Tp) is 14,48 GB.

Other than that, 64 bits is no problem, since the vertex descriptor would already be 64 (albeit unsigned):

using V = UndirectedOSMIdGraph::vertex_descriptor;

static_assert(not std::is_same_v<osm_id_t, V>);
static_assert(std::is_same_v<std::make_unsigned_t<osm_id_t>, V>);
static_assert(sizeof(osm_id_t) == sizeof(V));

So as long as you don't actually use negative osm_id_t there was no technical barrier to using osm_id_t as the index.

"Sparse" vertex index

If your vertex index isn't dense then vecS might be less suited for your storage. Consider using something else:

Live On Compiler Exlorer

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>

using osm_id_t = int64_t;

using UndirectedOSMIdGraph = boost::adjacency_list<
    boost::vecS, boost::listS, boost::undirectedS,
    boost::property<
        boost::vertex_index_t, osm_id_t,
        boost::property<boost::vertex_color_t, boost::default_color_type>>,
    boost::no_property>;

using V = UndirectedOSMIdGraph::vertex_descriptor;

static_assert(not std::is_same_v<std::make_unsigned_t<osm_id_t>, V>);

int main() {
    UndirectedOSMIdGraph g;

    osm_id_t large{1810014749};
    auto     v2 = add_vertex(2, g);
    add_edge(add_vertex(large, g), v2, g);
    add_edge(v2, add_vertex(3, g), g);

    print_graph(g);
}

Prints

2 <--> 1810014749 3
1810014749 <--> 2
3 <--> 2


问:
Get address family from socket OS X
Getting address family can be done with getsockopt() with option SO_DOMAIN (see socket options) on linux.
(read Get address family from socket. Linux)

How do I do the same thing on OS X ?

When using the code that worked on linux on OS X I get

```<code>error: use of undeclared identifier 'SO_DOMAIN'
  int err = getsockopt(sock, SOL_SOCKET, SO_DOMAIN, &addr_family, &len);
                                         ^
</code>```

so not SO_DOMAIN ?

答:
use SO_TYPE instead of SO_DOMAIN

in OS X man GETSOCKOPT(2) says

```<code>SO_TYPE         get the type of the socket (get only)
</code>```

Title: Get address family from socket OS X

Body:
Getting address family can be done with getsockopt() with option SO_DOMAIN (see socket options) on linux.
(read Get address family from socket. Linux)

How do I do the same thing on OS X ?

When using the code that worked on linux on OS X I get

error: use of undeclared identifier 'SO_DOMAIN'
  int err = getsockopt(sock, SOL_SOCKET, SO_DOMAIN, &addr_family, &len);
                                         ^

so not SO_DOMAIN ?

Body:
use SO_TYPE instead of SO_DOMAIN

in OS X man GETSOCKOPT(2) says

SO_TYPE         get the type of the socket (get only)


问:
How can I tell if a font isn't supported in Silverlight
Suppose the user want to use a specific font to render the text in the textblock, are there some way to detect whether the font is support in Siliverlight? </p>

答:
Fonts are supplied by the operating system or ROM for windows phone. Then depending on the silveright version + target operating system, you will be able to select from those supported.

In Silverlight 4, any font on the local computer can be used.

In Silverlight 3, certain Latin and East Asian fonts will work depending on the Operating System. See: http://msdn.microsoft.com/en-us/library/cc189010(v=vs.95).aspx#silverlight_fonts

In either case, you can deploy the font with your application to ensure it is rendered correctly (by specifying the font source property http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.fontsource(v=vs.95).aspx ).


问:
Add pointLight in react three fiber
I want to add pointlight in react three fiber and it seems that it follows different syntax from usual three.js syntax.</p>

答:
All three.js objects will be treated as native JSX elements. The general rule is that React Three Fiber components are available under the camel-case version. Hence do this to add a point source light like this -

<pointLight position={[0, 10, -5]} intensity={1} color="#fff" />
```

Title: Add pointLight in react three fiber


问:
Annotations and superclasses
This is a question about best practice - consider I have the following base class module, base.py:

from __future__ import annotations
from typing import TYPE_CHECKING

if type_checking:
    from redis import Redis

class Base:
    redis: Redis

    def __init__(self, redis):
        self.redis = redis

```
<p>Assuming I want a class that inherits from <code>Base</code> - which of the following is considered better and why? Is there another way I didn't think of?</p>
<p>(1.) seems cleaner but in (2.) I declare <code>redis: Redis</code> explicitly, which might be better for type-checking tools</p>
<p>1.</p>
<pre class="lang-py prettyprint-override"><code>from base import Base

class Sub(Base):
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id
</code>```

from __future__ import annotations
from typing import TYPE_CHECKING
from base import Base

if TYPE_CHECKING:
    from redis import Redis

class Sub(Base):
    redis: Redis
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id
```

答:
As @deceze mentioned, type-checking tools should understand your inheritance model and handle the hint appropriately.

In terms of "best practices", your option 1 is perfectly fine since you don't have to re-declare redis.

If you want something cleaner, another option is to use dataclasses

from dataclasses import dataclass

@dataclass
class Base:
    redis: Redis

@dataclass
class Sub(Base):
    user_id: int
```

Reference docs: https://docs.python.org/3/library/dataclasses.html

Title: Annotations and superclasses

Body:
This is a question about best practice - consider I have the following base class module, base.py:

from __future__ import annotations
from typing import TYPE_CHECKING

if type_checking:
    from redis import Redis

class Base:
    redis: Redis

    def __init__(self, redis):
        self.redis = redis

Assuming I want a class that inherits from Base - which of the following is considered better and why? Is there another way I didn't think of?

(1.) seems cleaner but in (2.) I declare redis: Redis explicitly, which might be better for type-checking tools

1.

from base import Base

class Sub(Base):
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id

from __future__ import annotations
from typing import TYPE_CHECKING
from base import Base

if TYPE_CHECKING:
    from redis import Redis

class Sub(Base):
    redis: Redis
    user_id: int

    def __init__(self, redis, user_id):
        super().__init__(redis)
        self.user_id = user_id

Body:
As @deceze mentioned, type-checking tools should understand your inheritance model and handle the hint appropriately.

In terms of "best practices", your option 1 is perfectly fine since you don't have to re-declare redis.

If you want something cleaner, another option is to use dataclasses

from dataclasses import dataclass

@dataclass
class Base:
    redis: Redis

@dataclass
class Sub(Base):
    user_id: int

Reference docs: https://docs.python.org/3/library/dataclasses.html


问:
Why is it necessary to enter commit messages?
I have been using git for a while now, and I had a question. Why is it necessary to add commit messages when using git commit? I mean, I admit that it is quite useful for me in some cases when I actually want to explain what a specific change does to the project.

But why is it still made necessary to write a commit message? I mean what if I am committing a minor change like fixing a spelling mistake in my UI? Is it a good thing that this is made necessary? or would it be better/worst if this was optional?

答:
Git 2.36 (Q2 2022) updates the contributor-facing documents on proposed log messages.

It illustrates why commit messages are mandatory/important.

See commit cdba029, commit 607817a, commit fa1101a (27 Jan 2022) by Junio C Hamano (gitster).

(Merged by Junio C Hamano -- gitster -- in commit 8376093, 11 Feb 2022)

SubmittingPatches: explain why we care about log messages

Extend the "describe your changes well" section to cover whom we are trying to help by doing so in the first place.

SubmittingPatches now includes in its man page:

The log message that explains your changes is just as important as the
changes themselves.

Your code may be clearly written with in-code
comment to sufficiently explain how it works with the surrounding
code, but those who need to fix or enhance your code in the future
will need to know why your code does what it does, for a few
reasons:

Your code may be doing something differently from what you wanted it
to do.

Writing down what you actually wanted to achieve will help
them fix your code and make it do what it should have been doing
(also, you often discover your own bugs yourself, while writing the
log message to summarize the thought behind it).

Your code may be doing things that were only necessary for your
immediate needs (e.g. "do X to directories" without implementing or
even designing what is to be done on files).

Writing down why you
excluded what the code does not do will help guide future developers.
Writing down "we do X to directories, because directories have
characteristic Y" would help them infer "oh, files also have the same
characteristic Y, so perhaps doing X to them would also make sense?".

Saying "we don't do the same X to files, because ..." will help them
decide if the reasoning is sound (in which case they do not waste
time extending your code to cover files), or reason differently (in
which case, they can explain why they extend your code to cover
files, too).

The goal of your log message is to convey the why behind your
change to help future developers.


问:
For loop inside for loop for generating strings
I have the following code generating an image url based on an array of objects and their properties:

```<code>for (let s = 0; s < amount; s++) {
   console.log(projects[s].imagelocation + projects[s].images[0]);
}
</code>```

As an example this gives me the following output:

```<code>img/EnergyGoStix-assets/GoStix1.jpg
img/Premier-assets/PremierStudios1.jpg
img/Quickstix-assets/QuickStix1.jpg
img/MotherMonster-assets/MotherMonster1.jpg
img/Stepping-assets/SteppingBooklet1.jpg
</code>```

However, the images property is actually an array. This array contains multiple image sources such as GoStix1.jpg, GoStix2.jpg, etc. This number of image sources varies between the projects.

How do I create a loop within a loop that would incorporate images.length where it will first go through each project and generate all image sources, prior to moving onto the next one?

P.S - Sorry for the terrible post title, had no idea what to call this. If anyone can come up with a better one to help be more precise, please let me know so I can update it.

答:
Better than another for loop would be to use an Array iteration method:</p>
```<code>for (let s = 0; s < amount; s++) {
  projects[s].images.forEach(image => {
      console.log(projects[s].imagelocation + image);
  });
}
</code>```

Body:
I have the following code generating an image url based on an array of objects and their properties:

for (let s = 0; s < amount; s++) {
   console.log(projects[s].imagelocation + projects[s].images[0]);
}

As an example this gives me the following output:

img/EnergyGoStix-assets/GoStix1.jpg
img/Premier-assets/PremierStudios1.jpg
img/Quickstix-assets/QuickStix1.jpg
img/MotherMonster-assets/MotherMonster1.jpg
img/Stepping-assets/SteppingBooklet1.jpg

However, the images property is actually an array. This array contains multiple image sources such as GoStix1.jpg, GoStix2.jpg, etc. This number of image sources varies between the projects.

How do I create a loop within a loop that would incorporate images.length where it will first go through each project and generate all image sources, prior to moving onto the next one?

P.S - Sorry for the terrible post title, had no idea what to call this. If anyone can come up with a better one to help be more precise, please let me know so I can update it.

Body:
Better than another for loop would be to use an Array iteration method:

for (let s = 0; s < amount; s++) {
  projects[s].images.forEach(image => {
      console.log(projects[s].imagelocation + image);
  });
}


问:
How to find multiple elements in a list using linear search
I have three parallel arrays product, store and price. The program should ask for the product and store name and then display all the prices against that product and store. I have the following code but it's stopped displaying price once it's found the first value in the sorted price list. Is there any way to search for more than one value from the list? Here is my code.

```<code>product = ["Milk","Peanut","Onions","Milk","Onions","Cheese","Potatoes","Cheese"]
store = ["Axep","Dominion","Fortions","Axep","Extra Foods","Loblow","Axep","Loblow"]
price = [2,2,4,10,10,10,17,23]

def search(product,store,price):

  enterProduct = input("Enter product: ")
  enterStore = input("Enter store: ")

  counter = 0
  position = 0
  found = False

  while counter < len(price) and found == False:
    if product[counter] == enterProduct and store[counter] == enterStore:
      found = True
      position = counter

    counter = counter + 1

    if found == True:
      print(f"The price for {product[position]} in {store[position]} are {price[position]}")

def main():

  search(product,store,price)

main()
</code>```

Here is the output:

```<code>Enter product: Milk
Enter store: Axep
The price for Milk in Axep are 2
</code>```

which should be:

```<code>The price for Milk in Axep are:
2
10
</code>```

答:
There is no need to use the found flag at all. Just print right inside the if block:

counter = 0

while counter < len(price):
    if product[counter] == enterProduct and store[counter] == enterStore:
        print(f"The price for {product[counter]} in {store[counter]} are {price[counter]}")

    counter = counter + 1
```
<p>But using a  <code>while</code> loop like that is quite "unpythonic". It would be better to use the <code>zip</code> function to iterate over multiple lists at once:</p>
<pre class="lang-py prettyprint-override"><code>products = ["Milk", "Peanut", "Onions", "Milk", "Onions", "Cheese", "Potatoes", "Cheese"]
stores = ["Axep", "Dominion", "Fortions", "Axep", "Extra Foods", "Loblow", "Axep", "Loblow"]
prices = [2, 2, 4, 10, 10, 10, 17, 23]

enterProduct = input("Enter product: ")
enterStore = input("Enter store: ")

for product, store, price in zip(products, stores, prices):
    if product == enterProduct and store == enterStore:
        print(f"The price for {product} in {store} are {price}")
</code>```

Body:
I have three parallel arrays product, store and price. The program should ask for the product and store name and then display all the prices against that product and store. I have the following code but it's stopped displaying price once it's found the first value in the sorted price list. Is there any way to search for more than one value from the list? Here is my code.

product = ["Milk","Peanut","Onions","Milk","Onions","Cheese","Potatoes","Cheese"]
store = ["Axep","Dominion","Fortions","Axep","Extra Foods","Loblow","Axep","Loblow"]
price = [2,2,4,10,10,10,17,23]

def search(product,store,price):

  enterProduct = input("Enter product: ")
  enterStore = input("Enter store: ")

  counter = 0
  position = 0
  found = False

  while counter < len(price) and found == False:
    if product[counter] == enterProduct and store[counter] == enterStore:
      found = True
      position = counter

    counter = counter + 1

    if found == True:
      print(f"The price for {product[position]} in {store[position]} are {price[position]}")

def main():

  search(product,store,price)

main()

Here is the output:

Enter product: Milk
Enter store: Axep
The price for Milk in Axep are 2

which should be:

The price for Milk in Axep are:
2
10

Body:
There is no need to use the found flag at all. Just print right inside the if block:

counter = 0

while counter < len(price):
    if product[counter] == enterProduct and store[counter] == enterStore:
        print(f"The price for {product[counter]} in {store[counter]} are {price[counter]}")

    counter = counter + 1

But using a  while loop like that is quite "unpythonic". It would be better to use the zip function to iterate over multiple lists at once:

products = ["Milk", "Peanut", "Onions", "Milk", "Onions", "Cheese", "Potatoes", "Cheese"]
stores = ["Axep", "Dominion", "Fortions", "Axep", "Extra Foods", "Loblow", "Axep", "Loblow"]
prices = [2, 2, 4, 10, 10, 10, 17, 23]

enterProduct = input("Enter product: ")
enterStore = input("Enter store: ")

for product, store, price in zip(products, stores, prices):
    if product == enterProduct and store == enterStore:
        print(f"The price for {product} in {store} are {price}")


问:
Next.js (React) + Phaser: ReferenceError: navigator is not defined
I'm trying to use phaser along with ion-phaser/react to build a page with a game in a Next.js app. This is my pages/game.js (using the React example from here https://github.com/proyecto26/ion-phaser):

```<code>import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'

class App extends Component {
  state = {
    initialize: false,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {}
    }
  }
  render() {
    const { initialize, game } = this.state
    return (
      <IonPhaser game={game} initialize={initialize} />
    )
  }
}

export default App;
</code>```

Running next dev and visiting the page gives the following error:

```<code>ReferenceError: navigator is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
init
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (69:14)
Object.<anonymous>
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (186:18)
Module._compile
internal/modules/cjs/loader.js (1063:30)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1092:10)
Module.load
internal/modules/cjs/loader.js (928:32)
Function.Module._load
internal/modules/cjs/loader.js (769:14)
Module.require
internal/modules/cjs/loader.js (952:19)
require
internal/modules/cjs/helpers.js (88:18)
Object.<anonymous>
file:///C:/git_projects/floam/node_modules/phaser/src/device/index.js (32:9)
Module._compile
internal/modules/cjs/loader.js (1063:30)
</code>```

Why is navigator not defined?

These are my relevant package versions in package.json:

```<code>"next": "^9.5.5",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"phaser": "^3.55.2",
"@ion-phaser/react": "^1.3.0",
</code>```

答:
I had to use useEffect, like so:</p>
```<code>useEffect(async () => (window.Phaser = await import(`phaser`)), []);
</code>```

Body:
I'm trying to use phaser along with ion-phaser/react to build a page with a game in a Next.js app. This is my pages/game.js (using the React example from here https://github.com/proyecto26/ion-phaser):

import React, { Component } from 'react'
import Phaser from 'phaser'
import { IonPhaser } from '@ion-phaser/react'

class App extends Component {
  state = {
    initialize: false,
    game: {
      width: "100%",
      height: "100%",
      type: Phaser.AUTO,
      scene: {}
    }
  }
  render() {
    const { initialize, game } = this.state
    return (
      <IonPhaser game={game} initialize={initialize} />
    )
  }
}

export default App;

Running next dev and visiting the page gives the following error:

ReferenceError: navigator is not defined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Call Stack
init
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (69:14)
Object.<anonymous>
file:///C:/git_projects/game/node_modules/phaser/src/device/OS.js (186:18)
Module._compile
internal/modules/cjs/loader.js (1063:30)
Object.Module._extensions..js
internal/modules/cjs/loader.js (1092:10)
Module.load
internal/modules/cjs/loader.js (928:32)
Function.Module._load
internal/modules/cjs/loader.js (769:14)
Module.require
internal/modules/cjs/loader.js (952:19)
require
internal/modules/cjs/helpers.js (88:18)
Object.<anonymous>
file:///C:/git_projects/floam/node_modules/phaser/src/device/index.js (32:9)
Module._compile
internal/modules/cjs/loader.js (1063:30)

Why is navigator not defined?

These are my relevant package versions in package.json:

"next": "^9.5.5",
"react": "^16.5.2",
"react-dom": "^16.5.2",
"phaser": "^3.55.2",
"@ion-phaser/react": "^1.3.0",

Body:
I had to use useEffect, like so:

useEffect(async () => (window.Phaser = await import(`phaser`)), []);


问:
How to create a std::ofstream to a temp file?
Okay, mkstemp is the preferred way to create a temp file in POSIX.

But it opens the file and returns an int, which is a file descriptor. From that I can only create a FILE*, but not an std::ofstream, which I would prefer in C++. (Apparently, on AIX and some other systems, you can create an std::ofstream from a file descriptor, but my compiler complains when I try that.)

I know I could get a temp file name with tmpnam and then open my own ofstream with it, but that's apparently unsafe due to  race conditions, and results in a compiler warning (g++ v3.4. on Linux):

```<code>warning: the use of `tmpnam' is dangerous, better use `mkstemp'
</code>```

So, is there any portable way to create an std::ofstream to a temp file?

答:
Maybe this will work:

```<code>char tmpname[256];
ofstream f;
sprintf (tmpname, "/tmp/tmpfileXXXXXX");
int fd = mkstemp(tmpname);
ofstream f(tmpname);
</code>```

I haven't tried it, but you can check.

Body:
Okay, mkstemp is the preferred way to create a temp file in POSIX.

But it opens the file and returns an int, which is a file descriptor. From that I can only create a FILE*, but not an std::ofstream, which I would prefer in C++. (Apparently, on AIX and some other systems, you can create an std::ofstream from a file descriptor, but my compiler complains when I try that.)

I know I could get a temp file name with tmpnam and then open my own ofstream with it, but that's apparently unsafe due to  race conditions, and results in a compiler warning (g++ v3.4. on Linux):

warning: the use of `tmpnam' is dangerous, better use `mkstemp'

So, is there any portable way to create an std::ofstream to a temp file?

LastEditorDisplayName: MSalters

Body:
Maybe this will work:

char tmpname[256];
ofstream f;
sprintf (tmpname, "/tmp/tmpfileXXXXXX");
int fd = mkstemp(tmpname);
ofstream f(tmpname);

I haven't tried it, but you can check.


问:
Not getting system timer interrupts on QEMU aarch64 emulation
I am learning ARM baremetal development using QEMU as emulator. I am following this github repo as example.

The vectors are defined for EL1 :

```<code>vectors:
    ventry  sync_invalid_el1t           // Synchronous EL1t
    ventry  irq_invalid_el1t            // IRQ EL1t
    ventry  fiq_invalid_el1t            // FIQ EL1t
    ventry  error_invalid_el1t          // Error EL1t

    ventry  sync_invalid_el1h           // Synchronous EL1h
    ventry  el1_irq                 // IRQ EL1h
    ventry  fiq_invalid_el1h            // FIQ EL1h
    ventry  error_invalid_el1h          // Error EL1h

    ventry  sync_invalid_el0_64         // Synchronous 64-bit EL0
    ventry  irq_invalid_el0_64          // IRQ 64-bit EL0
    ventry  fiq_invalid_el0_64          // FIQ 64-bit EL0
    ventry  error_invalid_el0_64            // Error 64-bit EL0

    ventry  sync_invalid_el0_32         // Synchronous 32-bit EL0
    ventry  irq_invalid_el0_32          // IRQ 32-bit EL0
    ventry  fiq_invalid_el0_32          // FIQ 32-bit EL0
    ventry  error_invalid_el0_32            // Error 32-bit EL0

.globl irq_vector_init
irq_vector_init:
    adr x0, vectors     // load VBAR_EL1 with virtual
    msr vbar_el1, x0        // vector table address
    ret
</code>```

and setup well :

```<code>void enable_interrupt_controller()
{
    put32(ENABLE_IRQS_1, SYSTEM_TIMER_IRQ_1);
}
</code>```

The handler is defined like this :

```<code>el1_irq:
    kernel_entry
    bl  handle_irq
    kernel_exit
</code>```

Following is timer handler :

```<code>void handle_irq(void)
{
    unsigned int irq = get32(IRQ_PENDING_1);
    switch (irq) {
        case (SYSTEM_TIMER_IRQ_1):
            handle_timer_irq();
            break;
        default:
            printf("Unknown pending irq: %x\r\n", irq);
    }
}
</code>```

I am launching the binary using the following command, but I am not getting the timer handler prints, though other prints are working and binary works fine for me :

```<code>$ qemu-system-aarch64 -M raspi3 -device loader,file=./kernel8.img,addr=0x0 -serial null -serial stdio -display none
</code>```

EDIT

Environment details :

```<code>naveen@workstation:~$ qemu-system-aarch64 --version
QEMU emulator version 4.2.1 (Debian 1:4.2-3ubuntu6.18)
Copyright (c) 2003-2019 Fabrice Bellard and the QEMU Project developers
naveen@workstation:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal
</code>```

答:
A start for debugging this is to turn on the tracing in QEMU of events related to the bcm2835 system timer, which I think is what your code is using. You can do that with the command line option -d trace:bcm2835_systmr*. In particular the "timer #1 expired" (or whatever timer number it is) messages indicate that the timer has raised its interrupt. If the timer isn't raising the interrupt then you've programmed the timer wrongly; if it is then you've probably not set up the interrupt controller correctly.

You should probably also double-check that you're really executing in EL1 as you expect.

Older versions of QEMU supported the raspi3 board but did not implement this particular system timer device; so if you don't see timer expiry tracing then it's worth checking your QEMU is new enough. 6.2.0 definitely has this device implemented.

Body:
I am learning ARM baremetal development using QEMU as emulator. I am following this github repo as example.

The vectors are defined for EL1 :

vectors:
    ventry  sync_invalid_el1t           // Synchronous EL1t
    ventry  irq_invalid_el1t            // IRQ EL1t
    ventry  fiq_invalid_el1t            // FIQ EL1t
    ventry  error_invalid_el1t          // Error EL1t

    ventry  sync_invalid_el1h           // Synchronous EL1h
    ventry  el1_irq                 // IRQ EL1h
    ventry  fiq_invalid_el1h            // FIQ EL1h
    ventry  error_invalid_el1h          // Error EL1h

    ventry  sync_invalid_el0_64         // Synchronous 64-bit EL0
    ventry  irq_invalid_el0_64          // IRQ 64-bit EL0
    ventry  fiq_invalid_el0_64          // FIQ 64-bit EL0
    ventry  error_invalid_el0_64            // Error 64-bit EL0

    ventry  sync_invalid_el0_32         // Synchronous 32-bit EL0
    ventry  irq_invalid_el0_32          // IRQ 32-bit EL0
    ventry  fiq_invalid_el0_32          // FIQ 32-bit EL0
    ventry  error_invalid_el0_32            // Error 32-bit EL0

.globl irq_vector_init
irq_vector_init:
    adr x0, vectors     // load VBAR_EL1 with virtual
    msr vbar_el1, x0        // vector table address
    ret

and setup well :

void enable_interrupt_controller()
{
    put32(ENABLE_IRQS_1, SYSTEM_TIMER_IRQ_1);
}

The handler is defined like this :

el1_irq:
    kernel_entry
    bl  handle_irq
    kernel_exit

Following is timer handler :

void handle_irq(void)
{
    unsigned int irq = get32(IRQ_PENDING_1);
    switch (irq) {
        case (SYSTEM_TIMER_IRQ_1):
            handle_timer_irq();
            break;
        default:
            printf("Unknown pending irq: %x\r\n", irq);
    }
}

I am launching the binary using the following command, but I am not getting the timer handler prints, though other prints are working and binary works fine for me :

$ qemu-system-aarch64 -M raspi3 -device loader,file=./kernel8.img,addr=0x0 -serial null -serial stdio -display none

EDIT

Environment details :

naveen@workstation:~$ qemu-system-aarch64 --version
QEMU emulator version 4.2.1 (Debian 1:4.2-3ubuntu6.18)
Copyright (c) 2003-2019 Fabrice Bellard and the QEMU Project developers
naveen@workstation:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal


问:
Recursion Error while evaluating contact information
I am trying to access the contact information of the plant as below, by declaring an AbstractInputPort following this comment.

```<code>self.DeclareAbstractInputPort('contact_force', AbstractValue.Make(ContactResults()))
</code>```

Then I an trying to access the actual contact information from the declared input port (2) using,

```<code>contact_info = self.EvalAbstractInput(context, 2).get_value()
</code>```

However, I get a RecursionError: maximum recursion depth exceeded, whenever I try to simulate the system.

Any idea what's going wrong?

Edit

Trying to evaluate the method outside the simulation loop by,

```<code>contact_info = plant.get_contact_results_output_port().Eval(plant_context)
</code>```

returns expected results when querying for i^th contact force using,

```<code>contact_info.point_pair_contact_info(i).contact_force()
</code>```

My simulation setup requires computing the contact force at each instant during the simulation. I have a custom system which has an abstract input port declared as mentioned above. The input port is then connected to get contact results by,

```<code>builder.Connect(plant.get_contact_results_output_port(), my_system.get_input_port(2))
</code>```

Now, while trying to extract the value within my_system using get_value() as above, I get the recursion error.

Is the port I use to obtain contact results correct? Or is there a another way to get contact results during simulation?

答:
I ran the code you linked.

box_example.py

There were a bunch of errors in there that needed to be fixed before it could be run, and it's clear that you're running on an older version of drake (still importing from attic which is long removed).  Perhaps the new version will give you better error messages?

The one change that could have been more mysterious in an older version is that you were calling SetPositions with the wrong context.  I've changed it to use the plant_context, not context: plant.SetPositions(plant_context, object_instance, [0, 0, 0, 1, 0, 0, 0]).  With that fix (and fixing/updating the imports), that file runs fine for me.

perception.py

didn't actually have any runnable code.  So I'm not sure what I'm supposed to see there.

Body:
I am trying to access the contact information of the plant as below, by declaring an AbstractInputPort following this comment.

self.DeclareAbstractInputPort('contact_force', AbstractValue.Make(ContactResults()))

Then I an trying to access the actual contact information from the declared input port (2) using,

contact_info = self.EvalAbstractInput(context, 2).get_value()

However, I get a RecursionError: maximum recursion depth exceeded, whenever I try to simulate the system.

Any idea what's going wrong?

Edit

Trying to evaluate the method outside the simulation loop by,

contact_info = plant.get_contact_results_output_port().Eval(plant_context)

returns expected results when querying for i^th contact force using,

contact_info.point_pair_contact_info(i).contact_force()

My simulation setup requires computing the contact force at each instant during the simulation. I have a custom system which has an abstract input port declared as mentioned above. The input port is then connected to get contact results by,

builder.Connect(plant.get_contact_results_output_port(), my_system.get_input_port(2))

Now, while trying to extract the value within my_system using get_value() as above, I get the recursion error.

Is the port I use to obtain contact results correct? Or is there a another way to get contact results during simulation?


问:
google charts graphics Multiline text labels
For a statistics/monitoring tool we use google charts graphs to show messages and errors from an application. Those messages are shown in labels of a graphics on the vertical axis but most of the times the messagetexts are too long, having too much characters to be fit in the label. They get shortcutted by ... in the end but what we actually want is that they are wordwrapped or if that is not possible, manually linebreaked with html br tags. Too bad, those are just ignored by the google chart labels.

My question is, is there a way to break the messagetexts over multiple lines instead of getting shortcutted with ... at the end? If so, how can this be done? I already found the possibility for this for the horizontal axis here, but we want it to have it for the vertical axis. If it is possible of course.

I also tried to make a fiddler example but it seems fiddler can't handle google graphs that well. When I made the text as long as in our tool, the whole graphics just disappeared.

答:
I tried to decrease the font size and it worked for me. adjust font size according to your need, making font small will make it automatically multi-line</p>
```<code>
<Chart
              chartType='ColumnChart'
              width="100%"
              height="800px"
              data={this.state.graphData}
              options={{
                fontSize: 11
              }}
/>

</code>```

Body:
I tried to decrease the font size and it worked for me. adjust font size according to your need, making font small will make it automatically multi-line

<Chart
              chartType='ColumnChart'
              width="100%"
              height="800px"
              data={this.state.graphData}
              options={{
                fontSize: 11
              }}
/>


问:
Javax validation for spring Conveter
I have question about spring boot. How can I make validation for spring Converter? I tried to use ConstraintValidator from javax, but it run after Converter.</p>

答: You can try and use javax.validation annotations inside the converter in method's parameters. Then the input before passed to converter will be validated.</p>

Title: Javax validation for spring Conveter


问:
SV Assertion - Implication matches unique valid sequences
I have assertion property as
assert property P;

```<code>property P;
@(posedge clk) A |-> ##[1:5] B;
endproperty
</code>```
```<code>clk - 0 1 2 3 4 5 6 7 8 9 10
A   - 0 1 0 1 0 0 0 0 0 0 0
B   - 0 0 0 0 1 0 0 1 0 0 0
</code>```

Here B = 1 at Clock num 4 satisfies assertion For A at Clocks 1 and 3.

How to write an assertion that checks for each A==1 we see a unique B==1 , meaning
A=1 at Clk 1 should match against B=1 at Clk 4
AND
A=1 at Clk 3 should match against B=1 at Clk 7.

Thanks,

答:
Depending on you max number of outstanding A request without ack I would do something like:

```<code>// modeling layer

int A_cnt, B_cnt

always @(posedge clk)
  if (A)
    A_cnt += 1
  if (B)
    B_cnt += 1

property P;
int A_id_lv
@(posedge clk)
(A, A_id_lv=A_cnt) |-> ##[1:5] B && B_cnt == A_id_lv;
endproperty
</code>```

I did not compile the code, this is a first draft, but I think the concept is there

Body:
I have assertion property as
assert property P;

property P;
@(posedge clk) A |-> ##[1:5] B;
endproperty

clk - 0 1 2 3 4 5 6 7 8 9 10
A   - 0 1 0 1 0 0 0 0 0 0 0
B   - 0 0 0 0 1 0 0 1 0 0 0

Here B = 1 at Clock num 4 satisfies assertion For A at Clocks 1 and 3.

How to write an assertion that checks for each A==1 we see a unique B==1 , meaning
A=1 at Clk 1 should match against B=1 at Clk 4
AND
A=1 at Clk 3 should match against B=1 at Clk 7.

Thanks,

Body:
Depending on you max number of outstanding A request without ack I would do something like:

// modeling layer

int A_cnt, B_cnt

always @(posedge clk)
  if (A)
    A_cnt += 1
  if (B)
    B_cnt += 1

property P;
int A_id_lv
@(posedge clk)
(A, A_id_lv=A_cnt) |-> ##[1:5] B && B_cnt == A_id_lv;
endproperty

I did not compile the code, this is a first draft, but I think the concept is there


问:
AutoCompleteTextView to be inline
I am using AutoCompleteTextView to suggest my list  , but i want the suggestions to be inline and not show a drop down list. How can i achieve that ? This is my current code that works as drop down list:

```<code>String[] birds = getResources().getStringArray(
            R.array.birds_list);

// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, birds);

mAutoCompleteTextView.setAdapter(adapter);
mAutoCompleteTextView.setThreshold(1);

mAutoCompleteTextView
            .setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    mAutoCompleteTextView.showDropDown();

                }
            });

mAutoCompleteTextView
            .setOnEditorActionListener(new OnEditorActionListener() {

                @Override
                public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                    if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                                || (actionId == EditorInfo.IME_ACTION_DONE)) {
                        Utils.hideSoftKeyboard(AddMedicationActivity.this);
                    }
                    return false;
                }
            });
</code>```

答:
This question is pretty old, but I have implemented a simple example of how this can be achieved, The example is written in kotlin but can easily be used with Java as well:

```<code>class EditTextInlineAutoComplete : AppCompatEditText {

private var listOfOptions: Collection<String> = emptyList()
private var lastTypedKeyCode: Int = 0

constructor(context: Context) : super(context) {
    init()
}

constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    init()
}

constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init()
}

private fun init() {
    val textWatcher = object : TextWatcher {

        override fun afterTextChanged(stringToFind: Editable?) {

            if (lastTypedKeyCode == KeyEvent.KEYCODE_DEL) {
                lastTypedKeyCode = KeyEvent.KEYCODE_UNKNOWN
                return
            }

            removeTextChangedListener(this)

            var result = stringToFind?.let { listOfOptions.filter { x -> x.startsWith(it) }.take(1) }
            LoggingHelper.d("Candidates: ${result?.joinToString()}")
            if (result?.isEmpty() == true) {
                addTextChangedListener(this)
                return
            }
            val predictedNumber = result?.get(0)
            val indexInOriginalText = stringToFind?.let { predictedNumber?.indexOf(stringToFind.toString()) } ?: 0
            val startIndex = indexInOriginalText + stringToFind?.length!!
            val endIndex = predictedNumber?.length
            val suffixOfNumber = predictedNumber?.substring(startIndex, endIndex!!)
            stringToFind?.append(suffixOfNumber)
            setSelection(startIndex, text?.length!!)

            addTextChangedListener(this)

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

    }
    addTextChangedListener(textWatcher)
}

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    lastTypedKeyCode = keyCode
    return super.onKeyDown(keyCode, event)
}

fun updateCollection(strings: Collection<String>) {
    listOfOptions = strings
}
</code>```

}

Title: AutoCompleteTextView to be inline

Body:
I am using AutoCompleteTextView to suggest my list  , but i want the suggestions to be inline and not show a drop down list. How can i achieve that ? This is my current code that works as drop down list:

String[] birds = getResources().getStringArray(
            R.array.birds_list);

// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, birds);

mAutoCompleteTextView.setAdapter(adapter);
mAutoCompleteTextView.setThreshold(1);

mAutoCompleteTextView
            .setOnFocusChangeListener(new OnFocusChangeListener() {

                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    mAutoCompleteTextView.showDropDown();

                }
            });

mAutoCompleteTextView
            .setOnEditorActionListener(new OnEditorActionListener() {

                @Override
                public boolean onEditorAction(TextView v, int actionId,
                                                  KeyEvent event) {
                    if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                                || (actionId == EditorInfo.IME_ACTION_DONE)) {
                        Utils.hideSoftKeyboard(AddMedicationActivity.this);
                    }
                    return false;
                }
            });

Body:
This question is pretty old, but I have implemented a simple example of how this can be achieved, The example is written in kotlin but can easily be used with Java as well:

class EditTextInlineAutoComplete : AppCompatEditText {

private var listOfOptions: Collection<String> = emptyList()
private var lastTypedKeyCode: Int = 0

constructor(context: Context) : super(context) {
    init()
}

constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
    init()
}

constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
    init()
}

private fun init() {
    val textWatcher = object : TextWatcher {

        override fun afterTextChanged(stringToFind: Editable?) {

            if (lastTypedKeyCode == KeyEvent.KEYCODE_DEL) {
                lastTypedKeyCode = KeyEvent.KEYCODE_UNKNOWN
                return
            }

            removeTextChangedListener(this)

            var result = stringToFind?.let { listOfOptions.filter { x -> x.startsWith(it) }.take(1) }
            LoggingHelper.d("Candidates: ${result?.joinToString()}")
            if (result?.isEmpty() == true) {
                addTextChangedListener(this)
                return
            }
            val predictedNumber = result?.get(0)
            val indexInOriginalText = stringToFind?.let { predictedNumber?.indexOf(stringToFind.toString()) } ?: 0
            val startIndex = indexInOriginalText + stringToFind?.length!!
            val endIndex = predictedNumber?.length
            val suffixOfNumber = predictedNumber?.substring(startIndex, endIndex!!)
            stringToFind?.append(suffixOfNumber)
            setSelection(startIndex, text?.length!!)

            addTextChangedListener(this)

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

    }
    addTextChangedListener(textWatcher)
}

override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
    lastTypedKeyCode = keyCode
    return super.onKeyDown(keyCode, event)
}

fun updateCollection(strings: Collection<String>) {
    listOfOptions = strings
}

}