问:
how to emit two signals in pyqt5
below is a groubox with 3 radio and one push button

so far connecting one widget to slot is fairly easy
self.versuch_2_radio.toggled.connect(self.printstuff())

but how can i emit 2 signals to one slot ?

in pseudocode I want to execute self.versuch_2_radio.toggled() and self.select_button.clicked() print('something')

or do I need to create two slots ?

```<code>        self.groupbox = qtw.QGroupBox(self)
        # groupbox.setAlignment(qtc.Qt.AlignHCenter)

        vlayout = qtw.QVBoxLayout()
        vlayout.setAlignment(qtc.Qt.AlignHCenter)

        versuch_1_radio = qtw.QRadioButton("toggle1")
        vlayout.addWidget(versuch_1_radio)
        self.versuch_2_radio = qtw.QRadioButton("toggle2")
        vlayout.addWidget(self.versuch_2_radio)
        versuch_3_radio = qtw.QRadioButton("toggle3")
        vlayout.addWidget(versuch_3_radio)
        self.select_button = qtw.QPushButton('select')
        vlayout.addWidget(self.select_button)

        self.groupbox.setLayout(vlayout)

        # hauptlayout
        haupt_layout = qtw.QFormLayout()
        haupt_layout.addRow(benutzer_label)
        haupt_layout.addRow(ueberschrift_label)
        haupt_layout.setVerticalSpacing(40)
        haupt_layout.addRow(self.groupbox)

        self.setLayout(haupt_layout)

  def printstuff(self):
        print("connected")

</code>```

答:
The logic is only to detect the clicked QPushButton and to verify the status of the QRadioButton in the slot:</p>

```<code>self.select_button.clicked.connect(self.printstuff)
</code>```

```<code>def printstuff(self):
    if self.versuch_2_radio.isChecked():
        print("connected")
</code>```

Title: how to emit two signals in pyqt5

Body:
below is a groubox with 3 radio and one push button

so far connecting one widget to slot is fairly easy
self.versuch_2_radio.toggled.connect(self.printstuff())

but how can i emit 2 signals to one slot ?

in pseudocode I want to execute self.versuch_2_radio.toggled() and self.select_button.clicked() print('something')

or do I need to create two slots ?

        self.groupbox = qtw.QGroupBox(self)
        # groupbox.setAlignment(qtc.Qt.AlignHCenter)

        vlayout = qtw.QVBoxLayout()
        vlayout.setAlignment(qtc.Qt.AlignHCenter)

        versuch_1_radio = qtw.QRadioButton("toggle1")
        vlayout.addWidget(versuch_1_radio)
        self.versuch_2_radio = qtw.QRadioButton("toggle2")
        vlayout.addWidget(self.versuch_2_radio)
        versuch_3_radio = qtw.QRadioButton("toggle3")
        vlayout.addWidget(versuch_3_radio)
        self.select_button = qtw.QPushButton('select')
        vlayout.addWidget(self.select_button)

        self.groupbox.setLayout(vlayout)

        # hauptlayout
        haupt_layout = qtw.QFormLayout()
        haupt_layout.addRow(benutzer_label)
        haupt_layout.addRow(ueberschrift_label)
        haupt_layout.setVerticalSpacing(40)
        haupt_layout.addRow(self.groupbox)

        self.setLayout(haupt_layout)

  def printstuff(self):
        print("connected")

Body:
The logic is only to detect the clicked QPushButton and to verify the status of the QRadioButton in the slot:

self.select_button.clicked.connect(self.printstuff)

def printstuff(self):
    if self.versuch_2_radio.isChecked():
        print("connected")


来源: stackexchange

问:
AutoMapper ProjectTo with DbContext multi level Include()
I need to perform multi level Include() query during EF Core select. I use AutoMapper with ProjectTo<>().

I have specified in mappings ExplicitExpansion() which means navigation properties will not be populated automatically, because I want to have possibility to execute the same query multiple times and
one time Include() navigation property but second time ignore it.

ProjectTo<>() method has params which allows me to include navigation properties into my select, but I need to perform multi level include. Is this possible? Such syntax like Include(e => e.Collection.Select(sc => sc.MyProperty)) not working in this case.

I tried to use Include().ThenInclude() for DbContext and then perform ProjectTo, but in that case ProjectTo overrides my includes and they are ignored.

Now I'm not sure if that's possible at all to have ProjectTo, ExplicitExpansion() specified in mapping and have multi level include?

答:
I tried to use Include().ThenInclude() for DbContext and then perform ProjectTo, but in that case ProjectTo overrides my includes and they are ignored.

This overriding is working as intended.

Select() overrides Include()

This is explicitly mentioned in the EF documentation:

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.

In the following example, the include operators are based on the Blog, but then the Select operator is used to change the query to return an anonymous type. In this case, the include operators have no effect.

Include

Include() instructs EF to load some related entities when fetching the requested result set. This behavior is added to the default loading behavior of EF:

```<code>var people = db.People.ToList();

var peopleWithPets = db.People.Include(person => person.Pets).ToList();
</code>```

By adding the Include(), you've essentially expanded the loading behavior that happens under the hood when the collection is enumerated (in this case, ToList()).

Select

Select() overrides the default loading behavior with the new behavior you've defined.

```<code>var people = db.People.ToList();

var names = db.People.Select(person => person.Name).ToList();
</code>```

When you call Select(), you essentially instruct EF to not perform its default loading behavior (which may or may not entail additional includes), and instead load exactly what you have specified (in this case, person => person.Name).

ProjectTo<>() is a wrapper around Select()

You can think of ProjectTo<TDestination>() as a sort of SelectFactory which generates the appropriate Select statement based on the TDestination mapping that has been configured in Automapper.

Under the hood, EF still executes a Select(), and therefore the same behavior as described above applies when using ProjectTo<>().

If you want to include additional related entities or any of their properties, you need to expand the Automapper mapping, as opposed to using Include on the query. If your mapping includes additional fields, Automapper will expand its underlying Select() accordingly.

Even if you had been able to include the related entities using Include, Automapper would ignore them anyway if you never defined them as a mapping.

ContentLicense: CC BY-SA 4.0

Body:
I tried to use Include().ThenInclude() for DbContext and then perform ProjectTo, but in that case ProjectTo overrides my includes and they are ignored.

This overriding is working as intended.

Select() overrides Include()

This is explicitly mentioned in the EF documentation:

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored.

In the following example, the include operators are based on the Blog, but then the Select operator is used to change the query to return an anonymous type. In this case, the include operators have no effect.

Include

Include() instructs EF to load some related entities when fetching the requested result set. This behavior is added to the default loading behavior of EF:

var people = db.People.ToList();

var peopleWithPets = db.People.Include(person => person.Pets).ToList();

By adding the Include(), you've essentially expanded the loading behavior that happens under the hood when the collection is enumerated (in this case, ToList()).

Select

Select() overrides the default loading behavior with the new behavior you've defined.

var people = db.People.ToList();

var names = db.People.Select(person => person.Name).ToList();

When you call Select(), you essentially instruct EF to not perform its default loading behavior (which may or may not entail additional includes), and instead load exactly what you have specified (in this case, person => person.Name).

ProjectTo<>() is a wrapper around Select()

You can think of ProjectTo<TDestination>() as a sort of SelectFactory which generates the appropriate Select statement based on the TDestination mapping that has been configured in Automapper.

Under the hood, EF still executes a Select(), and therefore the same behavior as described above applies when using ProjectTo<>().

If you want to include additional related entities or any of their properties, you need to expand the Automapper mapping, as opposed to using Include on the query. If your mapping includes additional fields, Automapper will expand its underlying Select() accordingly.

Even if you had been able to include the related entities using Include, Automapper would ignore them anyway if you never defined them as a mapping.


问:
Spring Data Elasticsearch : @Field and non @Field all got indexed
I chose to use my @Entity class to be marked with @Document as well, so that saving the overhead of maintaining the DTOs.

Now, when trying to index into elasticsearch these entities, they got stored into elastic with all properties (Unless i explicitly mark those unwanted with @JsonIgnore).

Could anyone just explain to me what really happens, and if it is possible to just selectively chose specific properties.

Note : marking some of them a @Field does not make any difference

答:
See Field description in: https://docs.spring.io/spring-data/elasticsearch/docs/3.2.4.RELEASE/reference/html/#elasticsearch.mapping.meta-model.annotations  It states:

@Field: Applied at the field level and defines properties of the field, most of the attributes map to the respective Elasticsearch Mapping definitions

I.e. @Field annotation defines field properties, not its presence in a mapping.

If you don't want to map a variable you have (at least) two options:

Use @JsonIgnore annotation

Use @Mapping for importing your mapping file. In the mapping file, disable Dynamic Mapping - https://www.elastic.co/guide/en/elasticsearch/guide/current/dynamic-mapping.html

ContentLicense: CC BY-SA 3.0


问:
How to calculate the number of documents a term occurs in using python?
I'm trying to calculate IDF values for TF-IDF vectorization. I'm trying to calculate number of documents that contain each unique word of the vocab.

This is the corpus:

corpus = ['this is the first document',
          'this document is the second document',
          'and this is the third one',
          'is this the first document']

my code:

...

IDF values:

```<code>for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c)
</code>```

...

Output i'm getting:
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 1
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5

The output i need:
this 4
is 4
the 4
first 2
document 3
second 1
and 1
third 1
one 1

答:
I assume that n contains your vocabulary. Then you can do this:

```<code>wordsets = [ frozenset(document.split(' ')) for document in corpus ]
results = []
for word in n:
    count = sum( 1 for s in wordsets if word in s )
    results.append((count, word))
for count, word in sorted(results, reverse=True):
    print(word, count)
</code>```

Body:
I'm trying to calculate IDF values for TF-IDF vectorization. I'm trying to calculate number of documents that contain each unique word of the vocab.

This is the corpus:

corpus = ['this is the first document',
          'this document is the second document',
          'and this is the third one',
          'is this the first document']

my code:

...

IDF values:

for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c)

...

Output i'm getting:
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 1
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5

The output i need:
this 4
is 4
the 4
first 2
document 3
second 1
and 1
third 1
one 1

Body:
I assume that n contains your vocabulary. Then you can do this:

wordsets = [ frozenset(document.split(' ')) for document in corpus ]
results = []
for word in n:
    count = sum( 1 for s in wordsets if word in s )
    results.append((count, word))
for count, word in sorted(results, reverse=True):
    print(word, count)


问:
What is the best way to cancel a socket receive request?
In C# you have 3 ways to try and receive TCP data on a Socket:

Socket.Receive is a synchronous, blocking method. It doesn't return until it succeeds, barring failure or [optionally] timeout.

Socket.BeginReceive is asynchronous, a supplied callback/delegate is called when there is data to receive, using the now-antiquated Begin/End pattern

Socket.ReceiveAsync begins an asynchronous request to receive data

However my understanding is none of these actually let you cancel the receive operation? The docs suggest EndReceive is used for completing a read, not something one could call to terminate the request?

You often see code like
while(socket.Available==0 && !cancel)Sleep(50); if(!cancel)socket.Receive(...);

But that's pretty terrible.

If I want to sit waiting for data but at some point cancel the receive, say the user hits "stop" button how can this neatly be done so I don't get a callback triggered later on when unexpected?

I had wondered about closing the socket, which would cause the Receive operation to fail, but it seems somewhat ugly. Am I thinking along the right lines or do the various API methods listed above allow a direct cancellation so I don't risk dangling async operations?

答:
There is no known way to cancel it (AFAIK)

One thing you can do it set the Socket.Blocking = false. The receive will return immediately when there is no data. This way it will not hang.

You should check the Socket.Blocking property.

I advise you to use the BeginReceive(IList<ArraySegment<Byte>>, SocketFlags, SocketError, AsyncCallback, Object) overload to prevent it throwing exceptions.

Check the SocketError on "Would Block", meaning "there is not data". So you can try again.

Didn't tested it but ->

A nice idea is using the non-async version Receive to receive 0 bytes (use a static byte[] emptyBuffer = new byte[0]) , and if the sockerError returns with a 'would block', you can have a short delay and retry it. When it doesn't return a socketError there is probably data. So you can start an async version.


问:
how to avoid form from submitting if both these values are valid
Hi Below is the code that i am using for my form to validate id's entered in two input fields.All code is working fine.Only thing is that how to stop form from submitting if both the fields are not valid as i am disabling and enabling submit button if record return is true.but if any one field is valid then submit button is enabling and allowing user to submit form.</p>

```<code><form>
<input type="text" id="1" value=""/>
<input type="text" id="2" value=""/>
<input type="submit" value="submit"  id="submitbutton" >
</form>
<script type="text/javascript">
            $$(document).ready(function() {
            $$('#1').blur(function() {
            var id = $$('#1').val();
            $$.getJSON("user.cfc?method=getRequests&returnformat=json&queryFormat=column",{"status":id}, function(res1,code) {

                if(res1.ROWCOUNT > 0){

                  for(var i=0; i<res1.ROWCOUNT; i++) {
                    s = "<span class='dPostTxt'>" + res1.DATA.ID[i] + " " + res1.DATA.FIRST_NAME[i] + " " + res1.DATA.LAST_NAME[i] + " " + "is valid." + "</span>";
                  };
                 $$('#submitbutton').removeAttr('disabled');//now id is valid so enabling submit button
                }
                else {
                  $$('#submitbutton').attr('disabled', 'disabled'); //error with id so disabling button
                  alert(" ID Is Not Valid.Please Enter Valid ID");
                  var s = "Entered  ID Is Not Valid.";
                }

                $$("#results").html(s);
                },"json");
           });  });
    </script>

<script type="text/javascript">
            $$(document).ready(function() {
            $$('#2').blur(function() {
            var id = $$('#2').val();
            $$.getJSON("user.cfc?method=getRequests&returnformat=json&queryFormat=column",{"status":id}, function(res,code) {

                if(res.ROWCOUNT > 0){

                  for(var i=0; i<res.ROWCOUNT; i++) {
                    s = "<span class='dPostTxt'>" + res.DATA.ID[i] + " " + res.DATA.FIRST_NAME[i] + " " + res.DATA.LAST_NAME[i] + " " + "is valid." + "</span>";
                  };
                 $$('#submitbutton').removeAttr('disabled');//now id is valid so enabling submit button
                }
                else {
                  $$('#submitbutton').attr('disabled', 'disabled'); //error with id so disabling button
                  alert(" ID Is Not Valid.Please Enter Valid ID");
                  var s = "Entered  ID Is Not Valid.";
                }

                $$("#results1").html(s);
                },"json");
           });  });
    </script>
</code>```

答:
```<code>$("form").submit(function() {
    bool valid = goValidateForm();
    if(!valid)
        return false; //prevents form from submitting
    else
        goDoSomeCoolStuff();

});
</code>```

Body:
Hi Below is the code that i am using for my form to validate id's entered in two input fields.All code is working fine.Only thing is that how to stop form from submitting if both the fields are not valid as i am disabling and enabling submit button if record return is true.but if any one field is valid then submit button is enabling and allowing user to submit form.

<form>
<input type="text" id="1" value=""/>
<input type="text" id="2" value=""/>
<input type="submit" value="submit"  id="submitbutton" >
</form>


问:
PHP date - get name of the months in local language
I have this part of the function, which gives me name of the months in English. How can I translate them to my local language (Serbian)?

```<code>$month_name = date('F', mktime(0, 0, 0, $i));
</code>```

Where $i is the number of the month (values 1 - 12). See also PHP:mktime.

答:
For all who struggle with German (and de_DE), make sure you are using the right language code. Login to your server and run locale -a to see a list of all available ones. For me it shows:

C
C.UTF-8
de_AT.utf8
de_BE.utf8
de_CH.utf8
de_DE.utf8
de_LI.utf8
de_LU.utf8
...

You need to use one of those codes.

Then you can use:

```<code>date_default_timezone_set('Europe/Berlin');
setlocale(LC_ALL, 'de_DE.utf8');
$date_now = date('Y-m-d');
$month_available = strftime('%B %Y', strtotime($date_now));
$month_next = strftime('%B %Y', strtotime($date_now.' +1 month'));

</code>```

and "März 2020" etc. get displayed correctly.

Body:
I have this part of the function, which gives me name of the months in English. How can I translate them to my local language (Serbian)?

$month_name = date('F', mktime(0, 0, 0, $i));

Where $i is the number of the month (values 1 - 12). See also PHP:mktime.

Body:
For all who struggle with German (and de_DE), make sure you are using the right language code. Login to your server and run locale -a to see a list of all available ones. For me it shows:

C
C.UTF-8
de_AT.utf8
de_BE.utf8
de_CH.utf8
de_DE.utf8
de_LI.utf8
de_LU.utf8
...

You need to use one of those codes.

Then you can use:

date_default_timezone_set('Europe/Berlin');
setlocale(LC_ALL, 'de_DE.utf8');
$date_now = date('Y-m-d');
$month_available = strftime('%B %Y', strtotime($date_now));
$month_next = strftime('%B %Y', strtotime($date_now.' +1 month'));

and "März 2020" etc. get displayed correctly.


问:
I´m trying to writing a .txt on windows server 12 using ip addres from a raspberry
I managed to make a program in python that, what it does is receive the weight of a scale and copy it to a file, then I made another program that reads that file, all this I have in a raspberry.
what I need is to have these two programs in the raspberry but the .txt where I write the weight I need it to have on a server running on windows server 12.
the inconvenience I am having is that when creating a .txt on the server, if I access that file from the raspberry it does not give me the necessary permissions to edit it, just to read ... someone knows how I can configure the raspberry to receive the File from the server with permissions to edit it? and I would like this file to be constantly refreshed in order to read the weight in real time.

EDITION 1)

Im using this code on de raspberry terminal:

$sudo apt-get install cifs-utils

$sudo mkdir /media/Balanza

$sudo mount -t cifs -o username=usuario,password=50922  //192.168.0.8/Balanzas  /media/Balanza

$sudo chmod 777 /media/Balanza

$sudo chmod 777 /media/Balanza/Balanza_1.txt

In the reading file I wrote:

```<code>import time
import string
import serial
import socket

while True:
    f = open("/media/Balanza/Balanza_peso.txt")
    line = f.readline()
    print(line)
    f.close()
</code>```

in the writing file I wrote:

```<code>####
####
####
f = open("/media/Balanza/Balanza_peso.txt","w")
f.write(datos+"\n")
</code>```

When I start the reading program it goes OK.
But when I try to open the writing one, it sends me back this errno:

```<code>PermissionError:[Errno 13] Permission denied:'/media/Balanza/Balanza_peso.txt'
</code>```

actually I didn´t need to be that way, I can save a file on the raspberry and read it from the Server, but I find no way to do so, if anyone have another way to solve the problem it is very welcome

**I forgot to tell, first of all, I share the windows folder with all permissions **

答:
Have you had a look at running a Flask application on your windows server to recieve incoming web requests?

import os
from flask import Flask, request

app = Flask(__name__)

local_path = os.path.dirname(os.path.abspath(__file__))
output_filename = 'Balanza_peso.txt'

@app.route('/temperature')
def my_endpoint():
    temp = request.args.get('temp')
    with open(os.path.join(local_path, output_filename), 'a') as out_file:
        out_file.write(f'temperature : {temp}')
    return (f'written the temperature {temp} to a local file')

if __name__ == '__main__':
    app.run(host='0.0.0.0')
```

<p>then it's a case of curling from your raspberry pi to your windows machine:</p>

<pre class="lang-sh prettyprint-override"><code>curl <windows server ip>:5000/temperature?temp=23
</code>```

Body:
I managed to make a program in python that, what it does is receive the weight of a scale and copy it to a file, then I made another program that reads that file, all this I have in a raspberry.
what I need is to have these two programs in the raspberry but the .txt where I write the weight I need it to have on a server running on windows server 12.
the inconvenience I am having is that when creating a .txt on the server, if I access that file from the raspberry it does not give me the necessary permissions to edit it, just to read ... someone knows how I can configure the raspberry to receive the File from the server with permissions to edit it? and I would like this file to be constantly refreshed in order to read the weight in real time.

EDITION 1)

Im using this code on de raspberry terminal:

$sudo apt-get install cifs-utils

$sudo mkdir /media/Balanza

$sudo mount -t cifs -o username=usuario,password=50922  //192.168.0.8/Balanzas  /media/Balanza

$sudo chmod 777 /media/Balanza

$sudo chmod 777 /media/Balanza/Balanza_1.txt

In the reading file I wrote:

import time
import string
import serial
import socket

while True:
    f = open("/media/Balanza/Balanza_peso.txt")
    line = f.readline()
    print(line)
    f.close()

in the writing file I wrote:

####
####
####
f = open("/media/Balanza/Balanza_peso.txt","w")
f.write(datos+"\n")

When I start the reading program it goes OK.
But when I try to open the writing one, it sends me back this errno:

PermissionError:[Errno 13] Permission denied:'/media/Balanza/Balanza_peso.txt'

actually I didn´t need to be that way, I can save a file on the raspberry and read it from the Server, but I find no way to do so, if anyone have another way to solve the problem it is very welcome

**I forgot to tell, first of all, I share the windows folder with all permissions **

Body:
Have you had a look at running a Flask application on your windows server to recieve incoming web requests?

import os
from flask import Flask, request

app = Flask(__name__)

local_path = os.path.dirname(os.path.abspath(__file__))
output_filename = 'Balanza_peso.txt'

@app.route('/temperature')
def my_endpoint():
    temp = request.args.get('temp')
    with open(os.path.join(local_path, output_filename), 'a') as out_file:
        out_file.write(f'temperature : {temp}')
    return (f'written the temperature {temp} to a local file')

if __name__ == '__main__':
    app.run(host='0.0.0.0')

then it's a case of curling from your raspberry pi to your windows machine:

curl <windows server ip>:5000/temperature?temp=23


问:
Create a MATLAB function that estimates e and outlines the error
I'm attempting to create a function that provides me with an estimate of e(exp(1)), and that provides me with information about the error within the function.
Estimating e was not an issue, however, when attempting to use an if statement created an infinite recursion within my function.

Here is my function

```<code>function e = myExpFunction(i)
for i = 1:20
    n = 10.^i;
    e = (1+1./n).^n;
    if abs(exp(1) - myExpFunction(i)) < abs(exp(1) - myExpFunction(i-1))
        fprintf('The error always decreases as n increases.\n')
    end
end
end
</code>```

And here is the error message

```<code>myExpFunction(i)
Out of memory. The likely cause is an infinite recursion within the program.

Error in myExpFunction (line 5)
    if abs(exp(1) - myExpFunction(i)) < abs(exp(1) - myExpFunction(i-1))
</code>```

I have tried using a while loop to bound the value of i between 1 and 20 but got the same error message. So I suppose I must have created an infinite loop within those bounds.

I'm having trouble fixing this as I don't understand where in the program I have created an infinite recursion. If anyone could help me out and shed some light it would be a massive help, thanks.

答:
I guess I understood the problem. In "If" you are calling the function you are in, you must call the variable "e(i)" and "e(i-1)" to avoid the infinite loop.</p>

```<code>function e = myExpFunction(i)

e(1) = (1+1/10)^10
for i = 2:20
    n = 10.^i;
    e(i) = (1+1/n)^n;
    if abs(exp(1) - e(i)) < abs(exp(1) - e(i-1))
        fprintf('The error always decreases as n increases.\n')
    end
end

end
</code>```

Body:
I'm attempting to create a function that provides me with an estimate of e(exp(1)), and that provides me with information about the error within the function.
Estimating e was not an issue, however, when attempting to use an if statement created an infinite recursion within my function.

Here is my function

function e = myExpFunction(i)
for i = 1:20
    n = 10.^i;
    e = (1+1./n).^n;
    if abs(exp(1) - myExpFunction(i)) < abs(exp(1) - myExpFunction(i-1))
        fprintf('The error always decreases as n increases.\n')
    end
end
end

And here is the error message

myExpFunction(i)
Out of memory. The likely cause is an infinite recursion within the program.

Error in myExpFunction (line 5)
    if abs(exp(1) - myExpFunction(i)) < abs(exp(1) - myExpFunction(i-1))

I have tried using a while loop to bound the value of i between 1 and 20 but got the same error message. So I suppose I must have created an infinite loop within those bounds.

I'm having trouble fixing this as I don't understand where in the program I have created an infinite recursion. If anyone could help me out and shed some light it would be a massive help, thanks.

Body:
I guess I understood the problem. In "If" you are calling the function you are in, you must call the variable "e(i)" and "e(i-1)" to avoid the infinite loop.

function e = myExpFunction(i)

e(1) = (1+1/10)^10
for i = 2:20
    n = 10.^i;
    e(i) = (1+1/n)^n;
    if abs(exp(1) - e(i)) < abs(exp(1) - e(i-1))
        fprintf('The error always decreases as n increases.\n')
    end
end

end


问:
Add or Append section with rows on top of tableView data values Swift
I have created a DataList in UITableView with sections and rows. Plus I have implemented delegate function for add & delete functions. Actually I need to add or append new section and row value which is selected. My first model is PickListData and then other sections values retrieving from Item -> pickList.

Model Hierarchy: PickListData -> let items: [Item]? -> var pickList: [SectionList]? -> textField

I implemented func didAddnewRow(_ sender: UIButton) but its adding row within the section and I need new section on top with name of Selected.

Issue is how to put Section Selected and row which is selected from below sections.

Images attached current and actual I want to implement.

答:
You forgot to add a new section before adding a row to that section. After inserting “Selected” section, the "A. Items" section will be moved down.</p>

```<code>func numberOfSections(in tableView: UITableView) -> Int {
        return AppData?.pickList?.count ?? 0
    }

 func sectionIndexTitles(for tableView: UITableView) -> [String]? {

  return [“Selected", “A. Items"]
}

 func didAddnewRow(_ sender: UIButton) {
    if let cell = sender.superview?.superview as? DictionaryTableViewCell,
        let indexPath = self.tableView.indexPath(for: cell) {

        if let selectedItem = AppData?.pickList?[indexPath.section].items?[indexPath.row] {

            let insertIndexPath = IndexPath(item: AppData?.pickList?[0].items?.count ?? 0, section: 0)

    if !AppData?.pickList.contains(where: {$0.title == “Selected" }) {

   AppData?.pickList.append(SectionList(title: “Selected”, items: selectedItem))

   tableView.insertSections(IndexSet([selectedItem]), with: .automatic)

    } else {

      AppData?.pickList?[0].items?.append(selectedItem)
  }

            cell.btnAdd.isHidden = true
            cell.btnDelete.isHidden = false
            tableView.beginUpdates()

            tableView.insertRows(at: [insertIndexPath], with: .automatic)
            tableView.endUpdates()

        }
    }
}
</code>```

Body:
You forgot to add a new section before adding a row to that section. After inserting “Selected” section, the "A. Items" section will be moved down.

func numberOfSections(in tableView: UITableView) -> Int {
        return AppData?.pickList?.count ?? 0
    }

 func sectionIndexTitles(for tableView: UITableView) -> [String]? {

  return [“Selected", “A. Items"]
}

 func didAddnewRow(_ sender: UIButton) {
    if let cell = sender.superview?.superview as? DictionaryTableViewCell,
        let indexPath = self.tableView.indexPath(for: cell) {

        if let selectedItem = AppData?.pickList?[indexPath.section].items?[indexPath.row] {

            let insertIndexPath = IndexPath(item: AppData?.pickList?[0].items?.count ?? 0, section: 0)

    if !AppData?.pickList.contains(where: {$0.title == “Selected" }) {

   AppData?.pickList.append(SectionList(title: “Selected”, items: selectedItem))

   tableView.insertSections(IndexSet([selectedItem]), with: .automatic)

    } else {

      AppData?.pickList?[0].items?.append(selectedItem)
  }

            cell.btnAdd.isHidden = true
            cell.btnDelete.isHidden = false
            tableView.beginUpdates()

            tableView.insertRows(at: [insertIndexPath], with: .automatic)
            tableView.endUpdates()

        }
    }
}


问:
How to remove white space from the top of my website page
How to remove white space from the top of this website

I had added

```<code>*{
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}
</code>```

on my  css but still i am getting that white space

答: You have . (dot) right above in body, remove it

Body:
How to remove white space from the top of this website

I had added

*{
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}

on my  css but still i am getting that white space


问:
Insert data in selected columns
I am using cakephp with php, I have table with field id having data type auto number.

In my form I do not have any field with id that's why it sets blank in my model and when I tries to save data it gives error.

how can I insert data into selected columns using model in cakephp?

答:
When you pull the form data, make sure you are using an array with the model name and field names. For example, if you are saving a book to the book model, the array would look something like:

```<code>$data['Book']['name'] = 'Title of Book';
$data['Book']['author'] = 'Name of Author';
$data['Book']['pages'] = 205; // number of pages
</code>```

Then when you save the data, you must call create, then save:

```<code>$this->Book->create();
$this->Book->save($data);
</code>```

This will automatically add the ID (whether auto-increment or UUID) and save the new record.

Title: Insert data in selected columns

Body:
When you pull the form data, make sure you are using an array with the model name and field names. For example, if you are saving a book to the book model, the array would look something like:

$data['Book']['name'] = 'Title of Book';
$data['Book']['author'] = 'Name of Author';
$data['Book']['pages'] = 205; // number of pages

Then when you save the data, you must call create, then save:

$this->Book->create();
$this->Book->save($data);

This will automatically add the ID (whether auto-increment or UUID) and save the new record.


问:
Authorization Flow returns 400
I've been trying to fix this issue for a good hour, and I can't seem to fix this. I'm using node-fetch for my requests (which is just a replica of the Fetch API for browsers, but cloned for Node). I've got the following code:

fetch("https://accounts.spotify.com/api/token", {
    body: `grant_type=authorization_code&code=${req.query.code}&redirect_uri=${encodeURIComponent("http://localhost:3000/callback")}`,
    headers: {
        Authorization: `Basic ${btoa(my_client_id)}:${btoa(my_client_secret)}`,
        "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST"
})
```

This is supposed to take the code from the callback, and send it to Spotify for a refresh token.

Expected behaviour:

Returned should be the following:

Actual behaviour:

400 Bad Request (consistently)

答:
This works. It looks like you are encoding the credentials incorrectly.
Its base64({id}:{secret}) not base64({id}):base64({secret}).

I used request-promise purely for convenience, so if you fix the Authorization header in your fetch, it should work.

```<code>const rp = require('request-promise');

const clientId = 'xxx';
const clientSecret = 'xxx';

async function auth() {
    const credentialsBuffer = Buffer.from(`${clientId}:${clientSecret}`);
    const options = {
        method: 'POST',
        uri: 'https://accounts.spotify.com/api/token',
        form: {
            grant_type: 'client_credentials'
        },
        headers: {
            Authorization: `Basic  ${credentialsBuffer.toString('base64')}`
        },
    };
    const resp = await rp(options);
    console.log(resp);
}

(async () => {
    await auth();
})()
</code>```

Title: Authorization Flow returns 400

Body:
I've been trying to fix this issue for a good hour, and I can't seem to fix this. I'm using node-fetch for my requests (which is just a replica of the Fetch API for browsers, but cloned for Node). I've got the following code:

fetch("https://accounts.spotify.com/api/token", {
    body: `grant_type=authorization_code&code=${req.query.code}&redirect_uri=${encodeURIComponent("http://localhost:3000/callback")}`,
    headers: {
        Authorization: `Basic ${btoa(my_client_id)}:${btoa(my_client_secret)}`,
        "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST"
})

This is supposed to take the code from the callback, and send it to Spotify for a refresh token.

Expected behaviour:

Returned should be the following:

Actual behaviour:

400 Bad Request (consistently)

Body:
This works. It looks like you are encoding the credentials incorrectly.
Its base64({id}:{secret}) not base64({id}):base64({secret}).

I used request-promise purely for convenience, so if you fix the Authorization header in your fetch, it should work.

const rp = require('request-promise');

const clientId = 'xxx';
const clientSecret = 'xxx';

async function auth() {
    const credentialsBuffer = Buffer.from(`${clientId}:${clientSecret}`);
    const options = {
        method: 'POST',
        uri: 'https://accounts.spotify.com/api/token',
        form: {
            grant_type: 'client_credentials'
        },
        headers: {
            Authorization: `Basic  ${credentialsBuffer.toString('base64')}`
        },
    };
    const resp = await rp(options);
    console.log(resp);
}

(async () => {
    await auth();
})()


问:
Why are all my Remix test accounts showing 0 ETH?
I'm trying to write a TicTacToe game on remix.ethereum.org but all of a sudden all my test accounts show 0 ETH balance, so I can't use them to deploy my contracts anymore.

Here is the solidity code that I was deploying when it happened:

```<code>pragma solidity ^0.4.19;

contract TicTacToe {

    uint8 public boardSize = 3;

    address[3][3] board;

    address public player1;
    address public player2;

    constructor() public {
        player1 = msg.sender;
    }

    function joinGame() public {
        assert(player2 == address(0));
        player2 = msg.sender;
    }

    function setStone(uint8 x, uint8 y) public {
        board[x][y] = msg.sender;
    }

}
</code>```

New test accounts still show 100 ETH upon creation.

答:
I don't think this is anything to do with deploying your Solidity code.

What blockchain environment are you using? It is most likely a problem there.

Remix environment menu

Body:
I'm trying to write a TicTacToe game on remix.ethereum.org but all of a sudden all my test accounts show 0 ETH balance, so I can't use them to deploy my contracts anymore.

Here is the solidity code that I was deploying when it happened:

pragma solidity ^0.4.19;

contract TicTacToe {

    uint8 public boardSize = 3;

    address[3][3] board;

    address public player1;
    address public player2;

    constructor() public {
        player1 = msg.sender;
    }

    function joinGame() public {
        assert(player2 == address(0));
        player2 = msg.sender;
    }

    function setStone(uint8 x, uint8 y) public {
        board[x][y] = msg.sender;
    }

}

New test accounts still show 100 ETH upon creation.


问:
Why ESLint throws 'no-unused-vars' for TypeScript interface?
So, I have this piece of code in .ts file:

```<code>import {MicroEventInterface} from '../Interfaces';

export default class MicroEvent implements MicroEventInterface {

// code
</code>```

And ESLint throws this error:

I have this config for TypeScript in ESLint:

```<code>typescript: {
    extends: [
        'plugin:@private/private/react' // private rep with React config
    ],
    parser: '@typescript-eslint/parser',
    plugins: [
        '@typescript-eslint',
        'import'
    ],
    settings: {
        'import/resolver': {
            'node': {
                'extensions': [
                    '.js',
                    '.jsx',
                    '.ts',
                    '.tsx'
                ],
                'moduleDirectory': [
                    'node_modules/',
                    'src/'
                ]
            }
        },
        react: {
            createClass: 'createClass',
            pragma: 'React',
            version: '0.14.9'
        }
    }
}
</code>```

So, everything seems like fine, but I can't conquer this error.

Any suggestions?

Thanks!

UPD:

Looks like if I console.log( --- , MicroEventInterface); error disappears. I think, ESLint does not treat implements as actual usage.

答:
Use @typescript-eslint/no-unused-vars-experimental and turn off @typescript-eslint/no-unused-vars.

The issue is resolved in the latter version (experimental).

Sample config:

```<code>// .eslintrc
{
  ...
  "rules": {
    "@typescript-eslint/no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars-experimental": "error"
  }
  ...
}

</code>```

Body:
So, I have this piece of code in .ts file:

import {MicroEventInterface} from '../Interfaces';

export default class MicroEvent implements MicroEventInterface {

// code

And ESLint throws this error:

I have this config for TypeScript in ESLint:

typescript: {
    extends: [
        'plugin:@private/private/react' // private rep with React config
    ],
    parser: '@typescript-eslint/parser',
    plugins: [
        '@typescript-eslint',
        'import'
    ],
    settings: {
        'import/resolver': {
            'node': {
                'extensions': [
                    '.js',
                    '.jsx',
                    '.ts',
                    '.tsx'
                ],
                'moduleDirectory': [
                    'node_modules/',
                    'src/'
                ]
            }
        },
        react: {
            createClass: 'createClass',
            pragma: 'React',
            version: '0.14.9'
        }
    }
}

So, everything seems like fine, but I can't conquer this error.

Any suggestions?

Thanks!

UPD:

Looks like if I console.log( --- , MicroEventInterface); error disappears. I think, ESLint does not treat implements as actual usage.

Body:
Use @typescript-eslint/no-unused-vars-experimental and turn off @typescript-eslint/no-unused-vars.

The issue is resolved in the latter version (experimental).

Sample config:

// .eslintrc
{
  ...
  "rules": {
    "@typescript-eslint/no-unused-vars": "off",
    "@typescript-eslint/no-unused-vars-experimental": "error"
  }
  ...
}


问:
Pandas : New rows based on existing rows
I have a Pandas dataframe df with the following structure : dataId, nodeId, tickDatetime

This dataset represent the time (tickDatetime), where an element (dataId) pass through a node (nodeId).

Here is an example :

```<code>           dataId    nodeId     tickDatetime
0          data-0   node-01             3000
1          data-0   node-02             5000
2          data-1   node-02             4000
3          data-1   node-01             6000
4          data-0   node-01             8000
5          data-0   node-00            10000
...           ...       ...
</code>```

From this dataframe, I want to create a new dataframe routes that would contains the sequence of nodes and travel times for each dataId.

So I did the following :

```<code>routes = df.sort_values('tickDatetime').groupby('dataId').agg({'nodeId':[lambda x: list(x)],'tickDatetime':lambda x: list(x)})

def datetimes_to_travel_times(datetimes):
    traveltimes = np.empty(len(datetimes))
    old_value = datetimes[0]
    traveltimes[0] = 0

    for i in range(1,len(datetimes)):
        traveltimes[i] = datetimes[i] - old_value
        old_value = datetimes[i]

    return traveltimes

routes['traveltimes'] = routes['tickDatetime'].apply(lambda row: datetimes_to_travel_times(row))
</code>```

Which give me the expected output (maybe not the best way to do it ?) :

```<code>           dataId                              nodeId                tickDatetime           traveltimes
0          data-0   [node-01,node-02,node-01,node-00]      [3000,5000,8000,10000]    [0,2000,3000,2000]
1          data-1                   [node-02,node-01]                 [4000,6000]              [0,2000]
</code>```

Now I want my routes to be splitted if the traveltime goes above et certain threshold.

For example, with a threshold of 3000, I would like my routes dataframe to look like this :

```<code>           dataId   routeId              nodeId    tickDatetime    traveltimes
0          data-0         0   [node-01,node-02]      [3000,5000]      [0,2000]
1          data-0         1   [node-01,node-00]     [8000,10000]      [0,2000]
2          data-1         0   [node-02,node-01]      [4000,6000]      [0,2000]
</code>```

How can I achieve that using Pandas ?

EDIT :

I managed to resolve my problem :

```<code>def split_routes(row):
    threshold = 3000
    nodes = row['nodeId']
    traveltimes = row['traveltimes']

    rows = []
    route_id = 0
    route_nodes = []
    route_traveltimes = []
    for i in range(0, len(traveltimes)):
        if(traveltimes[i]<threshold):
            route_nodes.append(nodes[i])
            route_traveltimes.append(traveltimes[i])
        else :
            # Route route_id completed, starting a new one
            row['route_id'] = route_id
            row['Reader'] = route_nodes
            row['traveltimes'] = route_traveltimes
            rows.append(row)
            route_id+=1
            route_nodes.append(nodes[i])
            route_traveltimes.append(0)

    # Route route_id completed, starting a new one
    row['route_id'] = route_id
    row['Reader'] = route_nodes
    row['traveltimes'] = route_traveltimes
    rows.append(row)

    return pd.DataFrame(rows)

splitted_routes_array = []
for index, row in routes.iterrows():
    splitted_routes_array.append(split_routes(row))

splitted_routes = pd.concat(splitted_routes_array)
</code>```

答:
```<code>df = pd.DataFrame({
'dataId':['data-0','data-0','data-1','data-1','data-0','data-0'],
'nodeId':['node-01','node-02','node-02','node-01','node-01','node-00'],
'tickDatetime':[3000,5000,4000,6000,8000,10000]})

append_ = lambda x:list(x)

df_2 = pd.DataFrame()
df_2['nodeId'] = df.groupby('dataId')['nodeId'].apply(append_)
df_2['tickDatetime'] = df.groupby('dataId')['tickDatetime'].apply(append_)
print(df_2)
</code>```

Output:

```<code>                                  nodeId               tickDatetime
dataId
data-0  [node-01, node-02, node-01, node-00]  [3000, 5000, 8000, 10000]
data-1                    [node-02, node-01]               [4000, 6000]
</code>```

Body:
I have a Pandas dataframe df with the following structure : dataId, nodeId, tickDatetime

This dataset represent the time (tickDatetime), where an element (dataId) pass through a node (nodeId).

Here is an example :

           dataId    nodeId     tickDatetime
0          data-0   node-01             3000
1          data-0   node-02             5000
2          data-1   node-02             4000
3          data-1   node-01             6000
4          data-0   node-01             8000
5          data-0   node-00            10000
...           ...       ...

From this dataframe, I want to create a new dataframe routes that would contains the sequence of nodes and travel times for each dataId.

So I did the following :

routes = df.sort_values('tickDatetime').groupby('dataId').agg({'nodeId':[lambda x: list(x)],'tickDatetime':lambda x: list(x)})

def datetimes_to_travel_times(datetimes):
    traveltimes = np.empty(len(datetimes))
    old_value = datetimes[0]
    traveltimes[0] = 0

    for i in range(1,len(datetimes)):
        traveltimes[i] = datetimes[i] - old_value
        old_value = datetimes[i]

    return traveltimes

routes['traveltimes'] = routes['tickDatetime'].apply(lambda row: datetimes_to_travel_times(row))

Which give me the expected output (maybe not the best way to do it ?) :

           dataId                              nodeId                tickDatetime           traveltimes
0          data-0   [node-01,node-02,node-01,node-00]      [3000,5000,8000,10000]    [0,2000,3000,2000]
1          data-1                   [node-02,node-01]                 [4000,6000]              [0,2000]

Now I want my routes to be splitted if the traveltime goes above et certain threshold.

For example, with a threshold of 3000, I would like my routes dataframe to look like this :

           dataId   routeId              nodeId    tickDatetime    traveltimes
0          data-0         0   [node-01,node-02]      [3000,5000]      [0,2000]
1          data-0         1   [node-01,node-00]     [8000,10000]      [0,2000]
2          data-1         0   [node-02,node-01]      [4000,6000]      [0,2000]

How can I achieve that using Pandas ?

EDIT :

I managed to resolve my problem :

def split_routes(row):
    threshold = 3000
    nodes = row['nodeId']
    traveltimes = row['traveltimes']

    rows = []
    route_id = 0
    route_nodes = []
    route_traveltimes = []
    for i in range(0, len(traveltimes)):
        if(traveltimes[i]<threshold):
            route_nodes.append(nodes[i])
            route_traveltimes.append(traveltimes[i])
        else :
            # Route route_id completed, starting a new one
            row['route_id'] = route_id
            row['Reader'] = route_nodes
            row['traveltimes'] = route_traveltimes
            rows.append(row)
            route_id+=1
            route_nodes.append(nodes[i])
            route_traveltimes.append(0)

    # Route route_id completed, starting a new one
    row['route_id'] = route_id
    row['Reader'] = route_nodes
    row['traveltimes'] = route_traveltimes
    rows.append(row)

    return pd.DataFrame(rows)

splitted_routes_array = []
for index, row in routes.iterrows():
    splitted_routes_array.append(split_routes(row))

splitted_routes = pd.concat(splitted_routes_array)

Body:
df = pd.DataFrame({
'dataId':['data-0','data-0','data-1','data-1','data-0','data-0'],
'nodeId':['node-01','node-02','node-02','node-01','node-01','node-00'],
'tickDatetime':[3000,5000,4000,6000,8000,10000]})

append_ = lambda x:list(x)

df_2 = pd.DataFrame()
df_2['nodeId'] = df.groupby('dataId')['nodeId'].apply(append_)
df_2['tickDatetime'] = df.groupby('dataId')['tickDatetime'].apply(append_)
print(df_2)

Output:

                                  nodeId               tickDatetime
dataId
data-0  [node-01, node-02, node-01, node-00]  [3000, 5000, 8000, 10000]
data-1                    [node-02, node-01]               [4000, 6000]


问:
Python: list index out of range even if I am looking at element with index 0
sorry if this question has already been asked but I can't find any answer that solves my problem.
I am using Python 3.8 with PyCharm on Mac (if that information can help).
I just started learning python and have a solid C and MatLab background.
My goal here is to read some information about train stations from a file in the format

and then ask the user for a station and give out the names of the stations that are connected by trains. Here is my code:

```<code>fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
    words = lines[i].split()
    for i in range(0,4):
        print(words[i]) #put to check if the words list actually stores the different words
    if words[0] == station:
        to_station.append(words[2])
    if words[2] == station:
        from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()
</code>```

I keep getting the Index out of bounds error for print(words[i]) in line 17 even if my complier (or interpreter) manages to print the right informartions without any problem.
I cannot manage to compile the code after the end of the for.

Thank you in advance for your help

EDIT: Even if I make that correction you suggested - I didn't notice in the inner loop that mistake - I still keep getting that error. I get that error even if I remove that inner loop altogether.

答: Use another variable in the inner loop other than 'i'.</p>

Body:
sorry if this question has already been asked but I can't find any answer that solves my problem.
I am using Python 3.8 with PyCharm on Mac (if that information can help).
I just started learning python and have a solid C and MatLab background.
My goal here is to read some information about train stations from a file in the format

and then ask the user for a station and give out the names of the stations that are connected by trains. Here is my code:

fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
    words = lines[i].split()
    for i in range(0,4):
        print(words[i]) #put to check if the words list actually stores the different words
    if words[0] == station:
        to_station.append(words[2])
    if words[2] == station:
        from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()

I keep getting the Index out of bounds error for print(words[i]) in line 17 even if my complier (or interpreter) manages to print the right informartions without any problem.
I cannot manage to compile the code after the end of the for.

Thank you in advance for your help

EDIT: Even if I make that correction you suggested - I didn't notice in the inner loop that mistake - I still keep getting that error. I get that error even if I remove that inner loop altogether.


问:
Combine: Publisher sometimes loses value and completes
I have a simple Deferred Publisher that reads data from disk and I display the data in a SwiftUI List, the Publisher works well most of the time, but sometimes it doesn't behave well, it just loses its value (which's an array of Model objects) and completes with finished message. I've tried a workaround mentioned here to use the buffer operator to keep the value in buffer because I believe the Combine's Publisher by design won't pass the data downstream if there is no demand requested by subscribers and hence dropping this data and completes, however using buffer didn't solve the issue.

The code I have:

```<code>enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
           .receive(on: self.readQueue)
           .eraseToAnyPublisher()
        }
}
</code>```

This is a link to download a working sample project.

EDIT:

Environment: Xcode 11.3.1, iOS 13.3 iPhone 11 Pro Max simulator and device.

gif screenshot (notice the console output)

EDIT2:

if I add any downstream publishers, like combineLatest for example just before sink in the consumer function readData() then a new behavior introduced, which's chaining an async publisher (readFromBundle) with a sync publisher (combineLatest) will result in the value will not deliver at all on iOS 13.3+ devices and will sometimes deliver on devices below iOS 13.3, as stated on this link.

答:
the first run does not fail, it just "needs" a time to load it....you can check this by adding this.

```<code>print("ready")
promise(.success(modelArray))
</code>```

and then set a breakpoint to "not loaded yet" and you will see that the "not loaded yet" appears before the "ready" is printed in the console. This is not a drop of the publisher.

As onAppear() says, it will be called after the UI was shown....

```<code>if self.viewModel.modelArray.count == 0 {
                Text("not loaded yet")
            } else {
                List(self.viewModel.modelArray) { model in
                    Text("\(model.name)")
                }
            }
</code>```

Body:
I have a simple Deferred Publisher that reads data from disk and I display the data in a SwiftUI List, the Publisher works well most of the time, but sometimes it doesn't behave well, it just loses its value (which's an array of Model objects) and completes with finished message. I've tried a workaround mentioned here to use the buffer operator to keep the value in buffer because I believe the Combine's Publisher by design won't pass the data downstream if there is no demand requested by subscribers and hence dropping this data and completes, however using buffer didn't solve the issue.

The code I have:

enum FileError: Error {
    case someError
}

class ViewModel: ObservableObject {
    @Published var modelArray = [Model]()
    private var subscriptions = Set<AnyCancellable>()
    func readData() {
        DataSource()
            .readFromBundle(resource: "Sample", type: "json")
            .receive(on: DispatchQueue.main)
            .sink(receiveCompletion: { completion in
                print("Completion: \(completion)")
            }) { array in
                self.modelArray = array
        }.store(in: &subscriptions)
    }
}
struct ContentView: View {
    @ObservedObject var viewModel: ViewModel

    var body: some View {
        VStack {
            List(self.viewModel.modelArray) { model in
                Text("\(model.name)")
            }
        }
        .onAppear {
            self.viewModel.readData()
        }
    }
}

struct Model: Codable, Identifiable {
    var id: Int
    var name: String
}

class DataSource {
    private let readQueue = DispatchQueue(label: "ReadQueue", qos: .default, attributes: .concurrent)

    func readFromBundle (resource: String, type:String) -> AnyPublisher<[Model], FileError> {
            Deferred {
                 Future { promise in
                    guard let url = Bundle.main.url(forResource: "Sample", withExtension: "json"),
                      let data = try? Data(contentsOf: url),
                      let modelArray = try? JSONDecoder().decode([Model].self, from: data)
                      else {
                        promise(.failure(.someError))
                        return
                    }
                      promise(.success(modelArray))
                }
            }
           .receive(on: self.readQueue)
           .eraseToAnyPublisher()
        }
}

This is a link to download a working sample project.

EDIT:

Environment: Xcode 11.3.1, iOS 13.3 iPhone 11 Pro Max simulator and device.

gif screenshot (notice the console output)

EDIT2:

if I add any downstream publishers, like combineLatest for example just before sink in the consumer function readData() then a new behavior introduced, which's chaining an async publisher (readFromBundle) with a sync publisher (combineLatest) will result in the value will not deliver at all on iOS 13.3+ devices and will sometimes deliver on devices below iOS 13.3, as stated on this link.

Body:
the first run does not fail, it just "needs" a time to load it....you can check this by adding this.

print("ready")
promise(.success(modelArray))

and then set a breakpoint to "not loaded yet" and you will see that the "not loaded yet" appears before the "ready" is printed in the console. This is not a drop of the publisher.

As onAppear() says, it will be called after the UI was shown....

if self.viewModel.modelArray.count == 0 {
                Text("not loaded yet")
            } else {
                List(self.viewModel.modelArray) { model in
                    Text("\(model.name)")
                }
            }


问:
How to display different title depends on action?
I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have
..
 in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)

```<code>@RequestMapping(path = "/.../update", method = RequestMethod.GET)
    public String updatePage(@RequestParam("...") String ..., Model model) {
        String[] tokens = ....split("_");
        Template template= class.method(...);
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save")
    public String newMappingPage(Model model) {
        Template template = new Template();
        template.setCostIndex("10");
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save", method = RequestMethod.POST)
    public String saveMapping(@ModelAttribute Template template) {
        class.method(template);
        return "redirect:/main-page";
    }
</code>```

save.hml file

```<code><html>
<head>
    <title>Engine</title>
    <link rel="stylesheet" th:href="@{/css/file.css}"/>
</head>
<body>
<h1>New/Update mapping</h1>
<form action="save" method="post" th:object="${template}">
    <fieldset>
        <label for="...">....[min]</label>
        <input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
        <label for="...">...</label>
        <input type="number" id="...." th:field="*{...}" required="true"/>
        <label for="...">....</label>
        <input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
        <br/>
        <br/>
        <label for="response">Response</label>
        <br/>
        <textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
        <br/>
        <input id="submit" type="submit" class="primary" value="Submit"/>
    </fieldset>
</form>
</body>
</html>
</code>```

答:
Update your method like this:</p>

```<code>@PostMapping(path = "/.../{}/save")
public ModelAndView save(Model model) {
  ModelAndView obj = new ModelAndView("save");
  model = new Model();
  if (model.getId() > 0) {
    model = findById(model.getId());
    obj .addAttribute("heading", "Update Mapping");
  } else {
    obj .addAttribute("heading", "New Mapping");
  }
  //Call method to store data from jsp file
  return obj;
}
</code>```

Body:
I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have
..
 in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)

@RequestMapping(path = "/.../update", method = RequestMethod.GET)
    public String updatePage(@RequestParam("...") String ..., Model model) {
        String[] tokens = ....split("_");
        Template template= class.method(...);
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save")
    public String newMappingPage(Model model) {
        Template template = new Template();
        template.setCostIndex("10");
        model.addAttribute("template", template);
        return "save";
    }

    @RequestMapping(path = "/.../save", method = RequestMethod.POST)
    public String saveMapping(@ModelAttribute Template template) {
        class.method(template);
        return "redirect:/main-page";
    }

save.hml file

    <title>Engine</title>
    <link rel="stylesheet" th:href="@{/css/file.css}"/>

New/Update mapping

<form action="save" method="post" th:object="${template}">
    <fieldset>
        ....[min]
        <input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
        ...
        <input type="number" id="...." th:field="*{...}" required="true"/>
        ....
        <input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>

        Response

        <textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>

        <input id="submit" type="submit" class="primary" value="Submit"/>
    </fieldset>
</form>

Body:
Update your method like this:

@PostMapping(path = "/.../{}/save")
public ModelAndView save(Model model) {
  ModelAndView obj = new ModelAndView("save");
  model = new Model();
  if (model.getId() > 0) {
    model = findById(model.getId());
    obj .addAttribute("heading", "Update Mapping");
  } else {
    obj .addAttribute("heading", "New Mapping");
  }
  //Call method to store data from jsp file
  return obj;
}


问:
task_struct -> parent always points to root process not the actual parent
I am trying to implement a module which takes a pid as input and simply prints some properties of that process. Printing siblings' information is also a part of the module. However, when I entered a 2nd or 3rd degree leaf process, it directly returns parent with pid=1 which is the root. I cannot figure out why this happens.

Here is my code: (I know this is not the best style of coding)

```<code>#include <linux/list.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/moduleparam.h>
#include <linux/stat.h>

static int pid = -1;

module_param(pid, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );

int pid_init(void){

    if(pid == -1){
        printk(KERN_ALERT "No input entered!\n");
    }

    struct pid *pid_struct = find_get_pid(pid);
    struct task_struct *ptr = pid_task(pid_struct, PIDTYPE_PID);

    struct task_struct *my_parent = ptr->parent;

    printk(KERN_INFO "Parent PID: %d\n", my_parent->pid);
    printk(KERN_INFO "Parent Name: %s\n", my_parent->comm);

    printk(KERN_INFO "Current State: %ld\n", ptr->state);
    printk(KERN_INFO "Current Name: %s\n", ptr->comm);

    printk(KERN_INFO "Siblings: \n");

    struct task_struct *sib;
    struct list_head *list;

    list_for_each(list, &my_parent->children) {
        sib = list_entry(list, struct task_struct, sibling);
        printk(KERN_INFO "SIbling PID: %d\n", sib->pid);
        printk(KERN_INFO "Sibling state: %ld\n", sib->state);
        printk(KERN_INFO "Sibling name: %s\n", sib->comm);
    }

   return 0;
}

void pid_exit(void){

    printk(KERN_INFO "Removing module ... \n");

}

module_init(pid_init);
module_exit(pid_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harun Sasmaz");
MODULE_DESCRIPTION("PID MODULE");
</code>```

For example when I say: sudo insmod mymodule pid=821, parent should be 809 but program goes to 1.

```<code>─udisksd(809)─┬─{udisksd}(821)
              ├─{udisksd}(824)
              ├─{udisksd}(928)
              └─{udisksd}(953)
</code>```

答:
In order to list the threads and it's PID of group of process, it is required to iterate over the threads of group_leader structure.

I am posting the modified code here:

```<code>#include <linux/list.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/sched/signal.h>
#include <linux/pid.h>
#include <linux/moduleparam.h>
#include <linux/stat.h>

static int pid = -1;

module_param(pid, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );

int pid_init(void){

    if(pid == -1){
        printk(KERN_ALERT "No input entered!\n");
    }

    struct pid *pid_struct = find_get_pid(pid);
    struct task_struct *ptr = pid_task(pid_struct, PIDTYPE_PID);

    struct task_struct *leader = ptr->group_leader;
    struct task_struct *t;

    printk(KERN_INFO "Parent PID: %d\n", leader->pid);
    printk(KERN_INFO "Parent Name: %s\n", leader->comm);
    printk(KERN_INFO "PID: %d\n", ptr->pid);
    printk(KERN_INFO "Threads: %d\n", leader->signal->nr_threads);

    for (t = next_thread(leader); t != leader; t = next_thread(t)) {
        printk(KERN_INFO "CPID: %d %s\n", t->pid, t->comm);
    }
   return 0;
}

void pid_exit(void){

    printk(KERN_INFO "Removing module ... \n");

}

module_init(pid_init);
module_exit(pid_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harun Sasmaz");
MODULE_DESCRIPTION("PID MODULE");
</code>```

Body:
I am trying to implement a module which takes a pid as input and simply prints some properties of that process. Printing siblings' information is also a part of the module. However, when I entered a 2nd or 3rd degree leaf process, it directly returns parent with pid=1 which is the root. I cannot figure out why this happens.

Here is my code: (I know this is not the best style of coding)

#include <linux/list.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/pid.h>
#include <linux/moduleparam.h>
#include <linux/stat.h>

static int pid = -1;

module_param(pid, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );

int pid_init(void){

    if(pid == -1){
        printk(KERN_ALERT "No input entered!\n");
    }

    struct pid *pid_struct = find_get_pid(pid);
    struct task_struct *ptr = pid_task(pid_struct, PIDTYPE_PID);

    struct task_struct *my_parent = ptr->parent;

    printk(KERN_INFO "Parent PID: %d\n", my_parent->pid);
    printk(KERN_INFO "Parent Name: %s\n", my_parent->comm);

    printk(KERN_INFO "Current State: %ld\n", ptr->state);
    printk(KERN_INFO "Current Name: %s\n", ptr->comm);

    printk(KERN_INFO "Siblings: \n");

    struct task_struct *sib;
    struct list_head *list;

    list_for_each(list, &my_parent->children) {
        sib = list_entry(list, struct task_struct, sibling);
        printk(KERN_INFO "SIbling PID: %d\n", sib->pid);
        printk(KERN_INFO "Sibling state: %ld\n", sib->state);
        printk(KERN_INFO "Sibling name: %s\n", sib->comm);
    }

   return 0;
}

void pid_exit(void){

    printk(KERN_INFO "Removing module ... \n");

}

module_init(pid_init);
module_exit(pid_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harun Sasmaz");
MODULE_DESCRIPTION("PID MODULE");

For example when I say: sudo insmod mymodule pid=821, parent should be 809 but program goes to 1.

─udisksd(809)─┬─{udisksd}(821)
              ├─{udisksd}(824)
              ├─{udisksd}(928)
              └─{udisksd}(953)

Body:
In order to list the threads and it's PID of group of process, it is required to iterate over the threads of group_leader structure.

I am posting the modified code here:

#include <linux/list.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/sched/signal.h>
#include <linux/pid.h>
#include <linux/moduleparam.h>
#include <linux/stat.h>

static int pid = -1;

module_param(pid, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP );

int pid_init(void){

    if(pid == -1){
        printk(KERN_ALERT "No input entered!\n");
    }

    struct pid *pid_struct = find_get_pid(pid);
    struct task_struct *ptr = pid_task(pid_struct, PIDTYPE_PID);

    struct task_struct *leader = ptr->group_leader;
    struct task_struct *t;

    printk(KERN_INFO "Parent PID: %d\n", leader->pid);
    printk(KERN_INFO "Parent Name: %s\n", leader->comm);
    printk(KERN_INFO "PID: %d\n", ptr->pid);
    printk(KERN_INFO "Threads: %d\n", leader->signal->nr_threads);

    for (t = next_thread(leader); t != leader; t = next_thread(t)) {
        printk(KERN_INFO "CPID: %d %s\n", t->pid, t->comm);
    }
   return 0;
}

void pid_exit(void){

    printk(KERN_INFO "Removing module ... \n");

}

module_init(pid_init);
module_exit(pid_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Harun Sasmaz");
MODULE_DESCRIPTION("PID MODULE");


问:
How to calculate the number of documents a term occurs in using python?
I'm trying to calculate IDF values for TF-IDF vectorization. I'm trying to calculate number of documents that contain each unique word of the vocab.

This is the corpus:

corpus = ['this is the first document',
          'this document is the second document',
          'and this is the third one',
          'is this the first document']

my code:

...

IDF values:

```<code>for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c)
</code>```

...

Output i'm getting:
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 1
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5

The output i need:
this 4
is 4
the 4
first 2
document 3
second 1
and 1
third 1
one 1

答:
This is perfect for the Counter class from the collections package

```<code>from collections import Counter

words = ' '.join(corpus)
output = Counter(words.split()).most_common()
</code>```

Body:
I'm trying to calculate IDF values for TF-IDF vectorization. I'm trying to calculate number of documents that contain each unique word of the vocab.

This is the corpus:

corpus = ['this is the first document',
          'this document is the second document',
          'and this is the third one',
          'is this the first document']

my code:

...

IDF values:

for i in range(0,len(corpus)):
    o=corpus[i].split(' ')
    c=0
    for wor in n:
        for k in range(0,len(corpus)):
            if wor in o[k]:
            c=c+1
        print(wor, c)

...

Output i'm getting:
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 1
document 1
first 1
is 3
one 3
second 3
the 4
third 4
this 5
and 0
document 0
first 1
is 3
one 3
second 3
the 4
third 4
this 5

The output i need:
this 4
is 4
the 4
first 2
document 3
second 1
and 1
third 1
one 1

Body:
This is perfect for the Counter class from the collections package

from collections import Counter

words = ' '.join(corpus)
output = Counter(words.split()).most_common()


问:
Oracle SQL - creating "unstored" procedure
I have this SQL query

```<code>SELECT ACCBAL_DATE, ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE ACC_KEY = '964570223'
AND ACCBAL_KEY = '16'
ORDER BY ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;
</code>```

It returns one row but I need to use this query for many ACC_KEYS (about 600).

So first way to do that is to run this query about 600x with different ACC_KEY parameter.

The second one is creating a procedure I think.

Procedure which will use variable acc_key and move it to WHERE statement.
Issue is that I can't create procedure stored on server because of permissions.

Is there some way to solve it without storing procedure on server?

EDIT: I know the IN clause but that is not what I need. I need something which will run the query about 600x, each execution with another ACC_KEY in WHERE clause and the output should be 600 rows.

答:
You can store the keys in a table or use a derived table in the query.  I would recommend something more like this:

```<code>WITH keys as (
      SELECT '964570223' as ACC_KEY FROM DUAL UNION ALL
      . . .
     )
SELECT k.ACC_KEY, MAX(ab.ACCBAL_DATE) as ACCBAL_DATE,
       MAX(ab.ACCBAL_AMOUNT) KEEP (DENSE_RANK FIRST ORDER BY ab.ACCBAL_DATE DESC) as ACCBAL_AMOUNT
FROM keys k LEFT JOIN
     ACCOUNT_BALANCES ab
     ON ab.ACC_KEY = k.ACC_KEY AND
        ab.ACCBAL_KEY = '16'
GROUP BY k.ACC_KEY;
</code>```

Of course the CTE keys could be replaced with a table that has the accounts of interest.

Note that this replaces your logic with aggregation logic.  You just want the most recent date and balance, which Oracle supports using the KEEP keyword.

Body:
I have this SQL query

SELECT ACCBAL_DATE, ACCBAL_AMOUNT
FROM ACCOUNT_BALANCES t
WHERE ACC_KEY = '964570223'
AND ACCBAL_KEY = '16'
ORDER BY ACCBAL_DATE DESC
FETCH FIRST 1 ROWS ONLY;

It returns one row but I need to use this query for many ACC_KEYS (about 600).

So first way to do that is to run this query about 600x with different ACC_KEY parameter.

The second one is creating a procedure I think.

Procedure which will use variable acc_key and move it to WHERE statement.
Issue is that I can't create procedure stored on server because of permissions.

Is there some way to solve it without storing procedure on server?

EDIT: I know the IN clause but that is not what I need. I need something which will run the query about 600x, each execution with another ACC_KEY in WHERE clause and the output should be 600 rows.

Body:
You can store the keys in a table or use a derived table in the query.  I would recommend something more like this:

WITH keys as (
      SELECT '964570223' as ACC_KEY FROM DUAL UNION ALL
      . . .
     )
SELECT k.ACC_KEY, MAX(ab.ACCBAL_DATE) as ACCBAL_DATE,
       MAX(ab.ACCBAL_AMOUNT) KEEP (DENSE_RANK FIRST ORDER BY ab.ACCBAL_DATE DESC) as ACCBAL_AMOUNT
FROM keys k LEFT JOIN
     ACCOUNT_BALANCES ab
     ON ab.ACC_KEY = k.ACC_KEY AND
        ab.ACCBAL_KEY = '16'
GROUP BY k.ACC_KEY;

Of course the CTE keys could be replaced with a table that has the accounts of interest.

Note that this replaces your logic with aggregation logic.  You just want the most recent date and balance, which Oracle supports using the KEEP keyword.


问:
How do I make my sizeof sum struct work with an empty parameter pack
I have this variadic struct for determining the sum of the sizeof all the types passed in:

```<code>template <typename U, typename... T> struct TotalSizeOf
    : std::integral_constant<size_t, sizeof(U) + TotalSizeOf<T...>::value> {};

template <typename U> struct TotalSizeOf<U>
    : std::integral_constant<size_t, sizeof(U)> {};
</code>```

Usage:
TotalSizeOf<double, int, char>::value

The question is, how do I modify this to allow it to work on an empty parameter pack, to return 0;

e.g. TotalSizeOf<>::value

Currently, I get the error error: wrong number of template arguments (0, should be at least 1)

I only have C++14 available.

答:
You simply must specialize also for <>

Example:

```<code>template < typename... T> struct TotalSizeOf;

template < typename U, typename... T> struct TotalSizeOf<U, T...>
: std::integral_constant<size_t, sizeof(U) + TotalSizeOf<T...>::value> {};

template <> struct TotalSizeOf<> :
std::integral_constant<size_t, 0 > { };

int main()
{
    std::cout << TotalSizeOf< int, char>::value << std::endl;
    std::cout << TotalSizeOf< char>::value << std::endl;
    std::cout << TotalSizeOf< >::value << std::endl;
}
</code>```

Body:
I have this variadic struct for determining the sum of the sizeof all the types passed in:

template <typename U, typename... T> struct TotalSizeOf
    : std::integral_constant<size_t, sizeof(U) + TotalSizeOf<T...>::value> {};

template <typename U> struct TotalSizeOf
    : std::integral_constant<size_t, sizeof(U)> {};

Usage:
TotalSizeOf<double, int, char>::value

The question is, how do I modify this to allow it to work on an empty parameter pack, to return 0;

e.g. TotalSizeOf<>::value

Currently, I get the error error: wrong number of template arguments (0, should be at least 1)

I only have C++14 available.

Body:
You simply must specialize also for <>

Example:

template < typename... T> struct TotalSizeOf;

template < typename U, typename... T> struct TotalSizeOf<U, T...>
: std::integral_constant<size_t, sizeof(U) + TotalSizeOf<T...>::value> {};

template <> struct TotalSizeOf<> :
std::integral_constant<size_t, 0 > { };

int main()
{
    std::cout << TotalSizeOf< int, char>::value << std::endl;
    std::cout << TotalSizeOf< char>::value << std::endl;
    std::cout << TotalSizeOf< >::value << std::endl;
}


答: Developer tools shows some characters at the beginning of your body tag. Remove them.

Title: How to remove white space from the top of my website page

Body:
How to remove white space from the top of this website

I had added

*{
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}

on my  css but still i am getting that white space


问:
Difference between two time using dayjs
I have two inputs of time and I want to get the difference/time-interval between these two using dayjs

```<code>fromtime = '13:00'
totime = '17:00'
</code>```

So the output for the above two should be 4:00 hours

I tried

console.log(
          dayjs(fromtime).diff(dayjs(totime), "hours")
        );
```

But am not getting the expected output.

答:
Dayjs expects a Date in a certain format (dayjs parse string) not just a time. However you can set the hour (dayjs set hour) without setting a certain date (dayjs parse now):

var fromtime = dayjs().hour(13)
var totime = dayjs().hour(17)

console.log(totime.diff(fromtime, "hours"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script></code>```

EDIT

What if the input contains fromtime = '10.25' and totime = '11.30'. So my output should be '1.05'. But when I follow your method the output is 1. Is there a way to solve this

You can set The minutes also (dayjs set minute). Unfortunately i do not see any formatting options for time-differences in that library. So we will have to calculate that on our own:

function formatInterval(minutes) {
  let interval = [
    Math.floor(minutes / 60).toString(),  //hours ("1" - "12")
    (minutes % 60).toString()             //minutes ("1" - "59")
  ];
  return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}

let fromtime = dayjs().hour(10).minute(25);
let totime = dayjs().hour(11).minute(30);

let interval = totime.diff(fromtime, "minute");

console.log(formatInterval(interval));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script></code>```

EDIT2

This will fail if the day switches between the two first lines

OK was assuming the fromtime will always be a smaller number than the totime ... if thats not the case we can just substract negative amount of minutes from the total amount of minutes in a day like so:

function formatInterval(minutes) {
  let interval = [Math.floor(minutes / 60).toString(), (minutes % 60).toString()];
  return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}

function getInterval(from, to) {
    let [hoursA, minutesA] = from.split(':');
    let [hoursB, minutesB] = to.split(':');
    let timeA = dayjs().hour(hoursA).minute(minutesA);
    let timeB = dayjs().hour(hoursB).minute(minutesB);
    let interval = timeB.diff(timeA, 'minutes');
    if(interval < 0) {
      return formatInterval(24 * 60 + timeB.diff(timeA, 'minutes'));
    }
    return formatInterval(interval);
}

console.log(getInterval('23:00', '1:45'));
console.log(getInterval('10:25', '11:30'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script></code>```

Title: Difference between two time using dayjs

Body:
I have two inputs of time and I want to get the difference/time-interval between these two using dayjs

fromtime = '13:00'
totime = '17:00'

So the output for the above two should be 4:00 hours

I tried

console.log(
          dayjs(fromtime).diff(dayjs(totime), "hours")
        );

But am not getting the expected output.

Body:
Dayjs expects a Date in a certain format (dayjs parse string) not just a time. However you can set the hour (dayjs set hour) without setting a certain date (dayjs parse now):

var fromtime = dayjs().hour(13)
var totime = dayjs().hour(17)

console.log(totime.diff(fromtime, "hours"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>

EDIT

What if the input contains fromtime = '10.25' and totime = '11.30'. So my output should be '1.05'. But when I follow your method the output is 1. Is there a way to solve this

You can set The minutes also (dayjs set minute). Unfortunately i do not see any formatting options for time-differences in that library. So we will have to calculate that on our own:

function formatInterval(minutes) {
  let interval = [
    Math.floor(minutes / 60).toString(),  //hours ("1" - "12")
    (minutes % 60).toString()             //minutes ("1" - "59")
  ];
  return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}

let fromtime = dayjs().hour(10).minute(25);
let totime = dayjs().hour(11).minute(30);

let interval = totime.diff(fromtime, "minute");

console.log(formatInterval(interval));

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>

EDIT2

This will fail if the day switches between the two first lines

OK was assuming the fromtime will always be a smaller number than the totime ... if thats not the case we can just substract negative amount of minutes from the total amount of minutes in a day like so:

function formatInterval(minutes) {
  let interval = [Math.floor(minutes / 60).toString(), (minutes % 60).toString()];
  return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}

function getInterval(from, to) {
    let [hoursA, minutesA] = from.split(':');
    let [hoursB, minutesB] = to.split(':');
    let timeA = dayjs().hour(hoursA).minute(minutesA);
    let timeB = dayjs().hour(hoursB).minute(minutesB);
    let interval = timeB.diff(timeA, 'minutes');
    if(interval < 0) {
      return formatInterval(24 * 60 + timeB.diff(timeA, 'minutes'));
    }
    return formatInterval(interval);
}

console.log(getInterval('23:00', '1:45'));
console.log(getInterval('10:25', '11:30'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>


答:
The problem comes from your inner loop and also the iterator on the list words. You may have a list of two words then can have a Index out of bounds error.</p>

```<code>fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
    words = lines[i].split()
    for j in range(0,len(words)):
        print(words[j]) #put to check if the words list actually stores the different words
    if words[0] == station:
        to_station.append(words[2])
    if words[2] == station:
        from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()
</code>```

Title: Python: list index out of range even if I am looking at element with index 0

Body:
The problem comes from your inner loop and also the iterator on the list words. You may have a list of two words then can have a Index out of bounds error.

fin = open('trains', 'r')
string = fin.read()
lines = string.split('\n')
print(lines)
station = input("Insert station name\n")
from_station = [] #stations from which trains arrive at the user's station
to_station = [] #stations to which trains arrive from user's station
for i in range(0,len(lines)):
    words = lines[i].split()
    for j in range(0,len(words)):
        print(words[j]) #put to check if the words list actually stores the different words
    if words[0] == station:
        to_station.append(words[2])
    if words[2] == station:
        from_station.append(words[0])
print("Trains arriving from stations: ")
print(from_station)
print("Trains going to stations: ")
print(to_station)
fin.close()


问:
Secureboot: grub can be loaded, but the bzImage has a "Invalid Signature"
I want to make a bootable emergency USB-stick that automatically repartitions my system and unpacks a rootfs to the hard disk, installs the bootloader, etc.

I compiled my own kernel and created my own initrd with various scripts.
this works very well. only booting from an USB-stick causes problems when secureboot is active.

to work around the problem I took an official Ubuntu livecd and copied all the content like isolinux/ EFI/* and so on, I changed all grub-configuration-boot-entrys to my kernel and my initrd. So I think the bootloader should be secureboot capable.

i set the following parameters in grub.cfg and built a new iso:

```<code>set check_signatures=no
</code>```

if secureboot is disabled, the system boots correctly.
if secureboot is active, the bootloader can be loaded. so the secureboot is done? but then the process aborts with the following error:

```<code>invalid signature: /boot/bzImage
</code>```

although set check_signatures=no is set.

Does anyone have an idea?

Is there no other way than to sign my kernel and distribute the keys across all systems? - can I distribute the key via ssh without direct access to the hardware?

答: problem solved with signed-shim bootloader, free to download</p>

Body:
I want to make a bootable emergency USB-stick that automatically repartitions my system and unpacks a rootfs to the hard disk, installs the bootloader, etc.

I compiled my own kernel and created my own initrd with various scripts.
this works very well. only booting from an USB-stick causes problems when secureboot is active.

to work around the problem I took an official Ubuntu livecd and copied all the content like isolinux/ EFI/* and so on, I changed all grub-configuration-boot-entrys to my kernel and my initrd. So I think the bootloader should be secureboot capable.

i set the following parameters in grub.cfg and built a new iso:

set check_signatures=no

if secureboot is disabled, the system boots correctly.
if secureboot is active, the bootloader can be loaded. so the secureboot is done? but then the process aborts with the following error:

invalid signature: /boot/bzImage

although set check_signatures=no is set.

Does anyone have an idea?

Is there no other way than to sign my kernel and distribute the keys across all systems? - can I distribute the key via ssh without direct access to the hardware?


问:
What's the difference between XSL Pattern and XPath in syntax?
I'm updating codes to use MSXML6.0 from MSXML3.0.
However, I noticed that, for MSXML3.0, the default "SelectionLanguage" is "XSL Pattern", while MSXML6.0 only support XPath.
I have concerns that this change would introduce differences in the query syntax.

Can somebody list the difference of syntax between these two syntax?

答:
XSL Patterns appear to be part of WD-XSL, "working draft XSL", which means versions predating the XSL recommendation (1999), which differ significantly from the final 1.0 version.

Microsoft has the relevant info on "XSL Patterns". Here's a quote from the section XPath 1.0 APIs:

MSXML 2.0 provides support for XSL Patterns, the precursor to XPath 1.0. The notion of an XML addressing language was introduced into the original W3C XSL Working Drafts (http://www.w3.org/TR/1998/WD-xsl-19981216.html) and called XSL Patterns. MSXML 2.0 implements the XSL Patterns language as described in the original XSL specification with a few minor exceptions.

MSXML 3.0 provides support for the legacy XSL Patterns syntax as well as XPath 1.0.

ContentLicense: CC BY-SA 2.5


问:
How remove new lines from string in twig
I have this code:

```<code>{% set pageDescription = item.description|length > 197 ? item.description|striptags|trim|slice(0, 197) ~ '...' : item.description %}
</code>```

I will remove new lines from item.description

example I have

```<code><meta name="description" content="An easy playing game about the natural numbers. There will randomly appear the natural. You have to choose what the right after number is. It’s so easy to play this game, isn’t it?

The..." />
</code>```

change to

```<code><meta name="description" content="An easy playing game about the natural numbers. There will randomly appear the natural. You have to choose what the right after number is. It’s so easy to play this game, isn’t it? The..." />
</code>```

How I can do?

Thank you.

答: If you need it only html tag maybe the spaceless {% spaceless %} ... {% endspaceless %} would be enough

Body:
I have this code:

{% set pageDescription = item.description|length > 197 ? item.description|striptags|trim|slice(0, 197) ~ '...' : item.description %}

I will remove new lines from item.description

example I have

<meta name="description" content="An easy playing game about the natural numbers. There will randomly appear the natural. You have to choose what the right after number is. It&#8217;s so easy to play this game, isn&#8217;t it?

The..." />

change to

<meta name="description" content="An easy playing game about the natural numbers. There will randomly appear the natural. You have to choose what the right after number is. It&#8217;s so easy to play this game, isn&#8217;t it? The..." />

How I can do?

Thank you.


问:
Securely using a variable in URL in a Flask webapp
I am using Flask to make a webappthat will contain a variable within the URL (example below).

```<code>@app.route('/landingpage/<id>')  # /landingpage/A
def landing_page(id):
    # Storage of a hashed <id>...
</code>```

My question relates to the variable within the URL which could contain confidential information, which should not be accessible to anyone other than the person entering the URL.

Would it be sufficient for the connection to be made over HTTPS to prevent anyone else accessing the variable prior to it being stored in a hashed format?

答:
You can use UUID in url, flask have support for this type of url, and i recommend to use this lib flask-uuid to gerate the uuid to your client access</p>

```<code>from flask_uuid import FlaskUUID

flask_uuid = FlaskUUID()
flask_uuid.init_app(app)

@app.route('/personalID')
def gerate_uuid():
    return make_response({'uuid':uuid.uuid4()})

@app.route('/landingpage/<uuid:id>')  # /landingpage/A
def landing_page(id):
    return id  # 'id' is a uuid.UUID instance
</code>```

Body:
I am using Flask to make a webappthat will contain a variable within the URL (example below).

@app.route('/landingpage/<id>')  # /landingpage/A
def landing_page(id):
    # Storage of a hashed <id>...

My question relates to the variable within the URL which could contain confidential information, which should not be accessible to anyone other than the person entering the URL.

Would it be sufficient for the connection to be made over HTTPS to prevent anyone else accessing the variable prior to it being stored in a hashed format?

Body:
You can use UUID in url, flask have support for this type of url, and i recommend to use this lib flask-uuid to gerate the uuid to your client access

from flask_uuid import FlaskUUID

flask_uuid = FlaskUUID()
flask_uuid.init_app(app)

@app.route('/personalID')
def gerate_uuid():
    return make_response({'uuid':uuid.uuid4()})

@app.route('/landingpage/<uuid:id>')  # /landingpage/A
def landing_page(id):
    return id  # 'id' is a uuid.UUID instance