问:
So I'm trying to make an app using PyQt5. Tried to give some functionality to a button, throws an error
```<code>def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
        if fileName:
            print(fileName)
</code>```

For this code, this is my output ,

fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files ();;Python Files (.py)", options=options)
TypeError: getOpenFileName(parent: QWidget = None, caption: str = '', directory: str = '', filter: str = '', initialFilter: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = 0): argument 1 has unexpected type 'Ui_MainWindow'

How do I fix this ?

(Post Edit) :
This is my GUI code :

```<code>def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(443, 427)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(350, 100, 75, 23))
        self.pushButton.setObjectName("pushButton")
        **self.pushButton.clicked.connect(self.openFileNameDialog)**
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(40, 100, 281, 21))
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 443, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Browse"))

</code>```

The error is thrown when I run the python script.

答:
Thanks for providing the GUI code. I believe the error most likely arises from inheritance complications. I am not sure why you are passing a separate MainWindow object to various functions. Instead, try to inherit from QMainWindow() and assign all the UI elements to self.</p>

```<code>import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setObjectName("MainWindow")
        self.resize(443, 427)
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(350, 100, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.openFileNameDialog)
        self.lineEdit = QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QRect(40, 100, 281, 21))
        self.lineEdit.setObjectName("lineEdit")
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 443, 21))
        self.menubar.setObjectName("menubar")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Browse"))

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
        if fileName:
            print(fileName)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MW = MainWindow()
    MW.show()
    sys.exit(app.exec_())
</code>```

Body:
def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
        if fileName:
            print(fileName)

For this code, this is my output ,

fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files ();;Python Files (.py)", options=options)
TypeError: getOpenFileName(parent: QWidget = None, caption: str = '', directory: str = '', filter: str = '', initialFilter: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = 0): argument 1 has unexpected type 'Ui_MainWindow'

How do I fix this ?

(Post Edit) :
This is my GUI code :

def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(443, 427)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(350, 100, 75, 23))
        self.pushButton.setObjectName("pushButton")
        **self.pushButton.clicked.connect(self.openFileNameDialog)**
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QtCore.QRect(40, 100, 281, 21))
        self.lineEdit.setObjectName("lineEdit")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 443, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Browse"))

The error is thrown when I run the python script.

Body:
Thanks for providing the GUI code. I believe the error most likely arises from inheritance complications. I am not sure why you are passing a separate MainWindow object to various functions. Instead, try to inherit from QMainWindow() and assign all the UI elements to self.

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setObjectName("MainWindow")
        self.resize(443, 427)
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton = QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QRect(350, 100, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.openFileNameDialog)
        self.lineEdit = QLineEdit(self.centralwidget)
        self.lineEdit.setGeometry(QRect(40, 100, 281, 21))
        self.lineEdit.setObjectName("lineEdit")
        self.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(self)
        self.menubar.setGeometry(QRect(0, 0, 443, 21))
        self.menubar.setObjectName("menubar")
        self.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        _translate = QCoreApplication.translate
        self.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Browse"))

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options)
        if fileName:
            print(fileName)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    MW = MainWindow()
    MW.show()
    sys.exit(app.exec_())


来源: stackexchange

问:
jaxb, single item setter for collections
I want to make sure that an xml element-content is unmarshalled in upper case on my object.

```<code>public class SZM {

    String field01;
    @XmlElement(name="field01")
    public void setField01(String value) {this.field01 = value.toUpperCase();}
    public String getField01() {return field01;}
</code>```

but how to do the same thing for every item in a collection? I want that any value read from the xml is capitalized.

```<code>@XmlElement
ArrayList<String>collection01;
</code>```

Thanks in advance,
Agostino

all the class, just in case:

```<code>package test.jaxb;

import java.util.ArrayList;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class SZM {
    String field01;
    @XmlElement(name="field01")
    public void setField01(String value) {this.field01 = value.toUpperCase();}
    public String getField01() {return field01;}

    @XmlElement
    ArrayList<String>collection01;

}
</code>```

答:
You can use an XmlAdapter to manipulate the String values:

StringCaseAdapter

```<code>import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringCaseAdapter extends XmlAdapter<String, String> {

    @Override
    public String unmarshal(String v) throws Exception {
        return v.toUpperCase();
    }

    @Override
    public String marshal(String v) throws Exception {
        return v.toLowerCase();
    }

}
</code>```

SZM

You reference the XmlAdapter as:

```<code>package test.jaxb;

import java.util.ArrayList;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class SZM {
    String field01;

    @XmlElement(name="field01")
    @XmlJavaTypeAdapter(StringCaseAdapter.class)
    public void setField01(String value) {this.field01 = value;}
    public String getField01() {return field01;}

    @XmlElement
    @XmlJavaTypeAdapter(StringCaseAdapter.class)
    ArrayList<String>collection01;

}
</code>```

input.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
    <collection01>def</collection01>
    <collection01>ghi</collection01>
    <field01>abc</field01>
</szm>
</code>```

Demo

```<code>import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(SZM.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        SZM szm = (SZM) unmarshaller.unmarshal(new File("input.xml"));

        System.out.println(szm.getField01());
        for(String item : szm.collection01) {
            System.out.println(item);
        }

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(szm, System.out);
    }

}
</code>```

Output

```<code>ABC
DEF
GHI
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
    <collection01>def</collection01>
    <collection01>ghi</collection01>
    <field01>abc</field01>
</szm>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to make sure that an xml element-content is unmarshalled in upper case on my object.

public class SZM {

    String field01;
    @XmlElement(name="field01")
    public void setField01(String value) {this.field01 = value.toUpperCase();}
    public String getField01() {return field01;}

but how to do the same thing for every item in a collection? I want that any value read from the xml is capitalized.

@XmlElement
ArrayList<String>collection01;

Thanks in advance,
Agostino

all the class, just in case:

package test.jaxb;

import java.util.ArrayList;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class SZM {
    String field01;
    @XmlElement(name="field01")
    public void setField01(String value) {this.field01 = value.toUpperCase();}
    public String getField01() {return field01;}

    @XmlElement
    ArrayList<String>collection01;

}

Body:
You can use an XmlAdapter to manipulate the String values:

StringCaseAdapter

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringCaseAdapter extends XmlAdapter<String, String> {

    @Override
    public String unmarshal(String v) throws Exception {
        return v.toUpperCase();
    }

    @Override
    public String marshal(String v) throws Exception {
        return v.toLowerCase();
    }

}

SZM

You reference the XmlAdapter as:

package test.jaxb;

import java.util.ArrayList;
import javax.xml.bind.annotation.*;

@XmlRootElement
public class SZM {
    String field01;

    @XmlElement(name="field01")
    @XmlJavaTypeAdapter(StringCaseAdapter.class)
    public void setField01(String value) {this.field01 = value;}
    public String getField01() {return field01;}

    @XmlElement
    @XmlJavaTypeAdapter(StringCaseAdapter.class)
    ArrayList<String>collection01;

}

input.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
    <collection01>def</collection01>
    <collection01>ghi</collection01>
    <field01>abc</field01>
</szm>

Demo

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(SZM.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        SZM szm = (SZM) unmarshaller.unmarshal(new File("input.xml"));

        System.out.println(szm.getField01());
        for(String item : szm.collection01) {
            System.out.println(item);
        }

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(szm, System.out);
    }

}

Output

ABC
DEF
GHI
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<szm>
    <collection01>def</collection01>
    <collection01>ghi</collection01>
    <field01>abc</field01>
</szm>


问:
Text overwrite in visual studio 2010
Really silly problem here.

In Visual Studio 2010, the text cursor has changed from the blinking line, to a blinking grey box around the characters. When I type overwrites the text in front of it.

I'm not sure how to get this off? It's like what happens when you press the insert key in microsoft word and overwrite mode gets turned on.

I'm working on a mac with a windows virtual machine so when I hit insert it's just a shortcut key for Parallels (the Virtual Machine program I'm running).

Would appreciate any help!!

答: press your keyboard Insert Key

ContentLicense: CC BY-SA 2.5

Title: Text overwrite in visual studio 2010

Body: press your keyboard Insert Key

ContentLicense: CC BY-SA 4.0


问:
Swift viewWillAppear not being called after dismissing view controller
I am presenting a view controller from a view controller called HomeController like so:

```<code>let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginController") as! LoginController

let navigationController: UINavigationController = UINavigationController(rootViewController: viewController)

present(navigationController, animated: true, completion: nil)
</code>```

In the presented view controller LoginController at some point gets dismissed:

```<code>self.dismiss(animated: true, completion: nil)
</code>```

But when it comes back to HomeController it is not calling viewWillAppear, I really need to check on condition on HomeController when it comes back to it, So how can I call viewWillAppear when LoginController dismisses the view?

答:
In iOS 13 , if you are presenting a view controller and when you are coming back viewWillAppear doesn't get called .
   I have changed it from present to push view controller and methods are getting called now . </p>

Body:
I am presenting a view controller from a view controller called HomeController like so:

let viewController = self.storyboard?.instantiateViewController(withIdentifier: "LoginController") as! LoginController

let navigationController: UINavigationController = UINavigationController(rootViewController: viewController)

present(navigationController, animated: true, completion: nil)

In the presented view controller LoginController at some point gets dismissed:

self.dismiss(animated: true, completion: nil)

But when it comes back to HomeController it is not calling viewWillAppear, I really need to check on condition on HomeController when it comes back to it, So how can I call viewWillAppear when LoginController dismisses the view?


问:
Flask webservice https call results in ssl error
I have Flask based webservice providing REST interfaces.

We have written webservice class inherited from flask.Flask and can't provide entire the code here but webservice app call looks like,
app.run(host=host, port=port, ssl_context='adhoc)

With this when I try to run GET request then I am getting SSL error,

```<code>  File "/opt/debesys/build/x86-64/debug/python/tt/pyrate/test/test_juno_sim.py", line 1077, in test_main_page
    resp = requests.get(self.url, headers=self.headers, verify=False)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/adapters.py", line 382, in send
    raise SSLError(e, request=request)
SSLError: [Errno 1] _ssl.c:507: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code>```

I have also tried starting app like,
app.run(host=host, port=port, ssl_context=('cert.pem', 'key.pem'))
Also used urllib2 module for get request instead of requests module.

But getting same error. If I try starting app without ssl_context and use http then getting response successfully.

Here I am using headers = {'Content-Type': 'application/json'} and url = "https://127.0.0.1:{}".format(port)

```<code>[shrishinde@localhost debesys]$ wget https://127.0.0.1:47855/
--2020-02-19 13:03:25--  https://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
[shrishinde@localhost debesys]$ wget http://127.0.0.1:47855/
--2020-02-19 13:03:28--  http://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31 [text/html]
Saving to: “index.html”

100%[=====================================================================================================================================================================>] 31          --.-K/s   in 0s

2020-02-19 13:03:28 (6.25 MB/s) - “index.html” saved [31/31]

[shrishinde@localhost debesys]$
</code>```

Update

Found solution:
After inheriting Flask, we have overridden Flask run method and in that WSGIServer is used so instead of ssl_context I should use ssl_args.

With hope that above steps will help user diagnose similar issues so keeping the question.

答:
Without the code it is only possible to guess.

Since the error states unknown protocol, you might want to check if you're calling the correct protocol, eg. not calling HTTPS instead of HTTP, which is a common mistake when developing on your local environment.

Body:
I have Flask based webservice providing REST interfaces.

We have written webservice class inherited from flask.Flask and can't provide entire the code here but webservice app call looks like,
app.run(host=host, port=port, ssl_context='adhoc)

With this when I try to run GET request then I am getting SSL error,

  File "/opt/debesys/build/x86-64/debug/python/tt/pyrate/test/test_juno_sim.py", line 1077, in test_main_page
    resp = requests.get(self.url, headers=self.headers, verify=False)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "/opt/debesys/ext/linux/x86-64/release/lib/python2.7/site-packages/requests/adapters.py", line 382, in send
    raise SSLError(e, request=request)
SSLError: [Errno 1] _ssl.c:507: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

I have also tried starting app like,
app.run(host=host, port=port, ssl_context=('cert.pem', 'key.pem'))
Also used urllib2 module for get request instead of requests module.

But getting same error. If I try starting app without ssl_context and use http then getting response successfully.

Here I am using headers = {'Content-Type': 'application/json'} and url = "https://127.0.0.1:{}".format(port)

[shrishinde@localhost debesys]$ wget https://127.0.0.1:47855/
--2020-02-19 13:03:25--  https://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
OpenSSL: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
Unable to establish SSL connection.
[shrishinde@localhost debesys]$ wget http://127.0.0.1:47855/
--2020-02-19 13:03:28--  http://127.0.0.1:47855/
Connecting to 127.0.0.1:47855... connected.
HTTP request sent, awaiting response... 200 OK
Length: 31 [text/html]
Saving to: “index.html”

100%[=====================================================================================================================================================================>] 31          --.-K/s   in 0s

2020-02-19 13:03:28 (6.25 MB/s) - “index.html” saved [31/31]

[shrishinde@localhost debesys]$

Update

Found solution:
After inheriting Flask, we have overridden Flask run method and in that WSGIServer is used so instead of ssl_context I should use ssl_args.

With hope that above steps will help user diagnose similar issues so keeping the question.


问:
Python SARIMA model is automatically using all cores of CPU. How?
I am running a Moving Average and SARIMA model for time series forecasting on my machine which has 12 cores.

The moving average model takes 25 min to run on a single core. By using the multiprocessing module, I was able to bring down the running time to ~4 min (by using 8 out of 12 cores). On checking the results of the "top" command, one can easily see that multiprocessing is actually using the 8 cores and the behaviour is as expected.

Moving Average(1 core) -> CPU Usage for Moving Average 1 core

Moving Average(8 core) -> CPU Usage for Moving Average 8 cores

I ran the same routines using the SARIMA model first without using multiprocessing. To my surprise, it was automatically using all the cores/distributing work on all cores. Unlike Moving Average model(Image 1) where I could see the CPU Usage of the process to be 100% for the single process and ~800% cumaltively on using 8 cores, here the CPU Usage for a single core only was fluctuating between 1000%-1200%(i.e all 12 cores). As expected, the multiprocessing module didn't help me much in this case and the results were far worse.

SARIMA(1 core) -> CPU USage Sarima 1 core

SARIMA (8 core) -> CPU Usage Sarima 8 core (Instead of one process using 1200% in this case, some processes go over 100% )

My question is why is the OS automatically distributing work on different cores in case of SARIMA model, while I have to do it explicitly(using multiprocessing)in Moving Average Model. Can it be due to the style of writing the python program?

Some other info:

I am using http://alkaline-ml.com/pmdarima/0.9.0/modules/generated/pyramid.arima.auto_arima.html for SARIMA Tuning.

I am using process queue technique to parallelise the code

SARIMA is taking 9 hrs on 1 core(maxing at 1200% as shown in above images) and more than 24 hrs if I use multiprocessing.

I am new to stackoverflow and will be happy to supplement any other information required. Please let me know if anything is not clear.

Updated:
I had raised an issue on the official repo of pyramid package and the author had replied. The same can be accessed here: https://github.com/alkaline-ml/pmdarima/issues/301

答:
The obvious reason is that SARIMA is developed to work on multiple cores of the CPU. Whereas Moving average does not have that functionality implemented into it. It has nothing to do with your style of writing the code. It is just that the package authors have developed the package code in 2 different ways i.e

No native multiprocessing support for Moving Average and

Native multiprocessing support for SARIMA

One more point to correct in your understanding is that the OS is not automatically distributing work on different cores in case of SARIMA. The package code of SARIMA is the master who is distributing all the work on different cores of CPU since it was developed to support and work with multiple cores by it's authors.

Update:

Your hunch is that multiprocessing code with client level multiprocessing + native multiprocessing should perform better. But actually it is not performing better. This is because,

Since the native multiprocessing of SARIMA is itself taking up the resources of all the cores of your CPU, what computation power will your client level multiprocessing have in order to speed up the process since all the computation power on all cores of CPU is being utilized by native multiprocessing of SARIMA?

This is the way a linux OS or any OS works. When there is no CPU power left for a process(in your case it is for client level multiprocessing process), the process is placed in a queue by the OS until the CPU becomes available to it. Since your client level multiprocessing process is placed in a queue and is not actively performing since there is no CPU left at all, it is stalling up. You could refer Linux OS documentations for verifying what I have said.


问:
How to make inline-block span inherit all text-decoration of all its ancestors?
I have made a inline-block span inside a tag u and a tag s, hoping it being displayed with both strike and undeline text-decorations, but none of them happened.

If I set its text-decoration to inherit, it will only inherit the text-decoration of its parent, without that of its other ancestors.

How to achieve this goal: while keep it as inline-block, it should inherit the text-decorations of all its ancestors.

span {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><u>
  <s>
    yes <span>man</span> no
  </s>
</u></code>```

答:
You can use the following solution:

u s span {
  display: inline-block;
  text-decoration: underline line-through;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><u><s>yes <span>man</span> no</s></u></code>```

You can set the text-decoration with underline and line-through for the  element to get the same text-decoration caused by the nested  and <s> elements. Using text-decoration: inherits; only inherits the text-decoration of the parent element (here <s>).

You can use the following CSS to cover different combinations of the tags:

.editor-container u s span,
.editor-container s u span {
  display: inline-block;
  text-decoration: underline line-through;
}
.editor-container u span {
  display: inline-block;
  text-decoration: underline;
}
.editor-container s span {
  display: inline-block;
  text-decoration: line-through;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="editor-container">
  <u><s>yes <span>man</span> no</s></u>
  <s><u>yes <span>man</span> no</u></s>
  <u>yes <span>man</span> no</u>
  <s>yes <span>man</span> no</s>

  <!-- you can also use b, strong, i without additional CSS -->
  <b><s>yes <span>man</span> no</s></b>
  <s><b>yes <span>man</span> no</b></s>
  <strong><s>yes <span>man</span> no</s></strong>
  <s><strong>yes <span>man</span> no</strong></s>
  <i><s>yes <span>man</span> no</s></i>
</div></code>```

You can also set the  of the editor to display: inline; instead of defining all these special rules:

.editor-container span {
  display: inline;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="editor-container">
  <u><s>yes <span>man</span> no</s></u>
</div></code>```

Body:
I have made a inline-block span inside a tag u and a tag s, hoping it being displayed with both strike and undeline text-decorations, but none of them happened.

If I set its text-decoration to inherit, it will only inherit the text-decoration of its parent, without that of its other ancestors.

How to achieve this goal: while keep it as inline-block, it should inherit the text-decorations of all its ancestors.

span {
  display: inline-block;
}

  <s>
    yes man no
  </s>

Body:
You can use the following solution:

u s span {
  display: inline-block;
  text-decoration: underline line-through;
}

<u><s>yes <span>man</span> no</s></u>

You can set the text-decoration with underline and line-through for the <span> element to get the same text-decoration caused by the nested <u> and <s> elements. Using text-decoration: inherits; only inherits the text-decoration of the parent element (here <s>).

You can use the following CSS to cover different combinations of the tags:

.editor-container u s span,
.editor-container s u span {
  display: inline-block;
  text-decoration: underline line-through;
}
.editor-container u span {
  display: inline-block;
  text-decoration: underline;
}
.editor-container s span {
  display: inline-block;
  text-decoration: line-through;
}

<div class="editor-container">
  <u><s>yes <span>man</span> no</s></u>
  <s><u>yes <span>man</span> no</u></s>
  <u>yes <span>man</span> no</u>
  <s>yes <span>man</span> no</s>

  <!-- you can also use b, strong, i without additional CSS -->
  <b><s>yes <span>man</span> no</s></b>
  <s><b>yes <span>man</span> no</b></s>
  <strong><s>yes <span>man</span> no</s></strong>
  <s><strong>yes <span>man</span> no</strong></s>
  <i><s>yes <span>man</span> no</s></i>
</div>

You can also set the <span> of the editor to display: inline; instead of defining all these special rules:

.editor-container span {
  display: inline;
}

<div class="editor-container">
  <u><s>yes <span>man</span> no</s></u>
</div>


问:
What are the differences between html preload and prefetch?
Preload and prefetch are both used to request resources in advance so that later resource loading can be quick. It seems that I can interchange the two

<link rel="preload" href="foo.js" as="script">

<link rel="prefetch" href="foo.js">

without noticing anything difference.

What are their differences?

答:
preload

<link rel="preload"> tells the browser to download and cache a
resource (like a script or a stylesheet) as soon as possible. It’s
helpful when you need that resource a few seconds after loading the
page, and you want to speed it up.

The browser doesn’t do anything with the resource after downloading
it. Scripts aren’t executed, stylesheets aren’t applied. It’s just
cached – so that when something else needs it, it’s available
immediately.

prefetch

<link rel="prefetch"> asks the browser to download and cache a
resource (like, a script or a stylesheet) in the background. The
download happens with a low priority, so it doesn’t interfere with
more important resources. It’s helpful when you know you’ll need that
resource on a subsequent page, and you want to cache it ahead of time.

The browser doesn’t do anything with the resource after downloading
it. Scripts aren’t executed, stylesheets aren’t applied. It’s just
cached – so that when something else needs it, it’s available
immediately.

Source


问:
Spring sleuth Baggage key not getting propagated
I've a filter (OncePerRequestFilter) which basically intercepts incoming request and logs traceId, spanId etc. which works well,
this filter lies in a common module which is included in other projects to avoid including spring sleuth dependency in all of my micro-services, the reason why I've created it as a library because any changes to library will be common to all modules.
Now I've to add a new propagation key which need to be propagated to all services via http headers like trace and spanId for that I've extracted current span from HttpTracing and added a baggage key to it (as shown below)

```<code> Span span = httpTracing.tracing().tracer().currentSpan();
    String corelationId =
        StringUtils.isEmpty(request.getHeader(CORELATION_ID))
            ? "n/a"
            : request.getHeader(CORELATION_ID);
    ExtraFieldPropagation.set(CUSTOM_TRACE_ID_MDC_KEY_NAME, corelationId);
    span.annotate("baggage_set");
    span.tag(CUSTOM_TRACE_ID_MDC_KEY_NAME, corelationId);
</code>```

I've added propagation-keys and whitelisted-mdc-keys to my application.yml (with my library) file like below

```<code>spring:
  sleuth:
    propagation-keys:
      - x-corelationId
    log:
      slf4j:
        whitelisted-mdc-keys:
          - x-corelationId
</code>```

After making this change in filter the corelationId is not available when I make a http call to another service with same app, basically keys are not getting propagated.

答:
I've gone through documentation and seems like I need to add spring.sleuth.propagation-keys and whitelist them by using spring.sleuth.log.slf4j.whitelisted-mdc-keys

Yes you need to do this

is there another way to add these properties in common module so that I do not need to include them in each and every micro services.

Yes, you can use Spring Cloud Config server and a properties file called application.yml / application.properties that would set those properties for all microservices

Body:
I've a filter (OncePerRequestFilter) which basically intercepts incoming request and logs traceId, spanId etc. which works well,
this filter lies in a common module which is included in other projects to avoid including spring sleuth dependency in all of my micro-services, the reason why I've created it as a library because any changes to library will be common to all modules.
Now I've to add a new propagation key which need to be propagated to all services via http headers like trace and spanId for that I've extracted current span from HttpTracing and added a baggage key to it (as shown below)

 Span span = httpTracing.tracing().tracer().currentSpan();
    String corelationId =
        StringUtils.isEmpty(request.getHeader(CORELATION_ID))
            ? "n/a"
            : request.getHeader(CORELATION_ID);
    ExtraFieldPropagation.set(CUSTOM_TRACE_ID_MDC_KEY_NAME, corelationId);
    span.annotate("baggage_set");
    span.tag(CUSTOM_TRACE_ID_MDC_KEY_NAME, corelationId);

I've added propagation-keys and whitelisted-mdc-keys to my application.yml (with my library) file like below

spring:
  sleuth:
    propagation-keys:
      - x-corelationId
    log:
      slf4j:
        whitelisted-mdc-keys:
          - x-corelationId

After making this change in filter the corelationId is not available when I make a http call to another service with same app, basically keys are not getting propagated.


问:
Mapping ReactJS list with data from an API.graphql call
I'm trying to map a list with data from an API call to a DynamoDB and I admit, there are many holes in my self-taught JavaScript knowledge.

How do I expose the songList object created in songs = () => {} to my return songList.map?

I've tried with API call outside the component declaration, and in and outside a function.

```<code>import React, { Component } from 'react';
import * as queries from '../graphql/queries';
import Song from './Song';

API.configure(awsconfig);

class SongList extends Component {
  render() {
    const songs = () => {
      API.graphql(graphqlOperation(queries.listSongs)).then(function (songData) {
        const songList = songData['data']['listSongs']['items'];
        return songList;
      });
    }

    console.log(songs()); // undefined

    return (
      <div>
        {
          songList.map((song, i) => <Song
            key={i}
            title={song['title']}
            author={song['author']}
            keywords={song['keywords']}
            instruments={song['instruments']}
            isrcCode={song['isrcCode']}
            lyrics={song['lyrics']}
          />)
        }
      </div>
    )
  }
}

export default SongList;
</code>```

答:
never NEVER do reqests in render method</p>

```<code>componentDidMount(){
 const songs = () => {
      API.graphql(graphqlOperation(queries.listSongs)).then(function (songData) {
        const songList = songData['data']['listSongs']['items'];
        return songList;
      });
this.setState({list:sondgs()})

}

render() {
    let list = this.state.list || []

    return (
      <div>
        {
          list.map((song, i) => <Song
            key={i}
            title={song['title']}
            author={song['author']}
            keywords={song['keywords']}
            instruments={song['instruments']}
            isrcCode={song['isrcCode']}
            lyrics={song['lyrics']}
          />)
        }
      </div>
    )
  }
}
</code>```

Body:
I'm trying to map a list with data from an API call to a DynamoDB and I admit, there are many holes in my self-taught JavaScript knowledge.

How do I expose the songList object created in songs = () => {} to my return songList.map?

I've tried with API call outside the component declaration, and in and outside a function.

import React, { Component } from 'react';
import * as queries from '../graphql/queries';
import Song from './Song';

API.configure(awsconfig);

class SongList extends Component {
  render() {
    const songs = () => {
      API.graphql(graphqlOperation(queries.listSongs)).then(function (songData) {
        const songList = songData['data']['listSongs']['items'];
        return songList;
      });
    }

    console.log(songs()); // undefined

    return (

        {
          songList.map((song, i) => <Song
            key={i}
            title={song['title']}
            author={song['author']}
            keywords={song['keywords']}
            instruments={song['instruments']}
            isrcCode={song['isrcCode']}
            lyrics={song['lyrics']}
          />)
        }

    )
  }
}

export default SongList;

Body:
never NEVER do reqests in render method

componentDidMount(){
 const songs = () => {
      API.graphql(graphqlOperation(queries.listSongs)).then(function (songData) {
        const songList = songData['data']['listSongs']['items'];
        return songList;
      });
this.setState({list:sondgs()})

}

render() {
    let list = this.state.list || []

    return (
      <div>
        {
          list.map((song, i) => <Song
            key={i}
            title={song['title']}
            author={song['author']}
            keywords={song['keywords']}
            instruments={song['instruments']}
            isrcCode={song['isrcCode']}
            lyrics={song['lyrics']}
          />)
        }
      </div>
    )
  }
}


问:
In Dijkstra's algorithm why must it first expand nodes with the current least cost?
I have read in other posts that Dijkstra's algorithm always expands the shortest path first. Why must it be implemented in such a way? Say we created a relaxed version of Dijkstra's that expands any unvisited paths/nodes as long as they have a cost (calculated on the previous iteration) that's less than infinity.

I have worked through some examples and have yet to show an example that fails to calculate the correct shortest path using this relaxed version of the algorithm.

答:
If you expand any node, you would eventually find some path to the goal but you cannot guarantee that the path cost to the goal is optimal.

If you find a cheaper path to an already visited node, you would have to update all nodes from this visited node transitively, rendering your relaxed algorithm less efficient than the original one.


问:
I need to do OpenGL texturing with certain color transparent
Still, I am using OpenGL 1.x;
 I could blit a 24bit targa image in OpenGL. Let's say I got a targa file with a monster on it.
its background is blue. How could I dicard this blue information?

An alternative: I know lesson32 in NeHe tutorial used a 32bit targa, Yeah, I could display it in my application. Here a new problem arises: How could I create 32bit TGA with certain area transparent. I don't get the point of the NeHe explanation.

here is my way in photoshop which does not work:

Create a new file, put the
background layer into the trash and
create a transparent layer.

Create a selection on the
transparent layer and fill it with
some solid color,say ,red.

Save the file as a 32bit TGA and
blit in my OpenGL app.

To my dismay, the region I thought should have been transparent is now pure white...
(the image loading method has no problem, as it can load some other good 32bit targas)

答: You're thinking in the terms of colour keying. But what you should use is a alpha channel. This is an additional channel, not being colour, but opaquenes value. In Photoshop you get this, by NOT filling the transparent parts with anything.


问:
visual basic error with trying to calculate average
I am trying to create a macro that gathers both a flat # count, and an average of existing values in a sheet. I'm getting an error at the line where i try to calculate the avgScore variable by dividing my summed up vulnScore by the counter value. I'm getting a 'runtime 6 error' at the 'avgScore = vulnScore / counter' line. It's working with a data set thats 77 lines long. I've tried converting the variables to Long (the only real suggestion I've found) but that has not worked. the 'element' variable is for an array thats about 26 in size containing string variables.

```<code>Dim counter As Long
Dim vulnScore As Long
Dim avgScore As Long
vulnScore = 0
counter = 0
avgScore = 0

Dim rowNum As Integer
''''''''''''''''''''
For Each element In arr
vulnScore = 0
counter = 0
avgScore = 0
'get #'s for putting into Treg
'''''''''
For i = 2 To Cells(Rows.Count, 3).End(xlUp).Row
If Cells(i, 3).Value = element Then
'# of times that server is listed
counter = counter + 1
'combining vulnerability scores for that server
vulnScore = vulnScore + Cells(i, 7).Value
End If
Next i
avgScore = vulnScore / counter
'''''''''

'find Treg column/row
colNum = WorksheetFunction.Match("Findings Variance (4/15 vs Current)", ActiveWorkbook.TREG.Range("1:1"), 0)
rowNum = WorksheetFunction.Match(element, ActiveWorkbook.TREG.Range("1:1"), 0)
Cells(rowNum, colNum - 1).Value = avgScore
Cells(rowNum, colNum - 2).Value = counter
'''''''''
Next element
</code>```

Sample: it's pulling data from this sheet which would be the activeSheet when the macro is run

Sample: it's pasting the data into the two blank columns in this sheet (TREG)

答:
You state in your comment to NautMeg's answer that both variables are 0 when it happens. That already gives you half of the answer: If counter is 0, you will get an divide by zero error (runtime error 11). With the exception of dividing 0 by 0, in that case VBA will not throw an divide by zero, it will throw an overflow error (runtime error 6).

You can try it by opening the immediate window (Ctrl+G) and enter:

```<code>? 1/0
</code>```

-->Runtime error 11

```<code>? 0/0
</code>```

-->Runtime error 6

In any case, you have to make up your mind what you want to see in your sheet. Maybe change your code to something like

```<code>colNum = WorksheetFunction.Match("Findings Variance (4/15 vs Current)", ActiveWorkbook.TREG.Range("1:1"), 0)
rowNum = WorksheetFunction.Match(element, ActiveWorkbook.TREG.Range("1:1"), 0)
if counter > 0 then
    avgScore = vulnScore / counter
    Cells(rowNum, colNum - 1).Value = avgScore
Else
    Cells(rowNum, colNum - 1).Value = ""
End IF
Cells(rowNum, colNum - 2).Value = counter
</code>```

Body:
I am trying to create a macro that gathers both a flat # count, and an average of existing values in a sheet. I'm getting an error at the line where i try to calculate the avgScore variable by dividing my summed up vulnScore by the counter value. I'm getting a 'runtime 6 error' at the 'avgScore = vulnScore / counter' line. It's working with a data set thats 77 lines long. I've tried converting the variables to Long (the only real suggestion I've found) but that has not worked. the 'element' variable is for an array thats about 26 in size containing string variables.

Dim counter As Long
Dim vulnScore As Long
Dim avgScore As Long
vulnScore = 0
counter = 0
avgScore = 0

Dim rowNum As Integer
''''''''''''''''''''
For Each element In arr
vulnScore = 0
counter = 0
avgScore = 0
'get #'s for putting into Treg
'''''''''
For i = 2 To Cells(Rows.Count, 3).End(xlUp).Row
If Cells(i, 3).Value = element Then
'# of times that server is listed
counter = counter + 1
'combining vulnerability scores for that server
vulnScore = vulnScore + Cells(i, 7).Value
End If
Next i
avgScore = vulnScore / counter
'''''''''

'find Treg column/row
colNum = WorksheetFunction.Match("Findings Variance (4/15 vs Current)", ActiveWorkbook.TREG.Range("1:1"), 0)
rowNum = WorksheetFunction.Match(element, ActiveWorkbook.TREG.Range("1:1"), 0)
Cells(rowNum, colNum - 1).Value = avgScore
Cells(rowNum, colNum - 2).Value = counter
'''''''''
Next element

Sample: it's pulling data from this sheet which would be the activeSheet when the macro is run

Sample: it's pasting the data into the two blank columns in this sheet (TREG)

Body:
You state in your comment to NautMeg's answer that both variables are 0 when it happens. That already gives you half of the answer: If counter is 0, you will get an divide by zero error (runtime error 11). With the exception of dividing 0 by 0, in that case VBA will not throw an divide by zero, it will throw an overflow error (runtime error 6).

You can try it by opening the immediate window (Ctrl+G) and enter:

? 1/0

-->Runtime error 11

? 0/0

-->Runtime error 6

In any case, you have to make up your mind what you want to see in your sheet. Maybe change your code to something like

colNum = WorksheetFunction.Match("Findings Variance (4/15 vs Current)", ActiveWorkbook.TREG.Range("1:1"), 0)
rowNum = WorksheetFunction.Match(element, ActiveWorkbook.TREG.Range("1:1"), 0)
if counter > 0 then
    avgScore = vulnScore / counter
    Cells(rowNum, colNum - 1).Value = avgScore
Else
    Cells(rowNum, colNum - 1).Value = ""
End IF
Cells(rowNum, colNum - 2).Value = counter


问:
getting an error when trying to run uwsgi: error while loading shared libraries: libpython3.4m.so.1.0
I've been runing uwsgi like so:

```<code>uwsgi --ini CMS_uwsgi.ini
</code>```

and it used to work. However, I tried running uwsgi again after a couple weeks and I get this error now:

```<code>uwsgi: error while loading shared libraries: libpython3.4m.so.1.0:
cannot open shared object file: No such file or directory
</code>```

I'm not sure why I'm getting this error now. It Might be because recently, I did

```<code>sudo apt-get autoremove
</code>```

to remove installed packages that used to be installed as dependencies but aren't any longer (as mentioned here https://askubuntu.com/questions/187888/what-is-the-correct-way-to-completely-remove-an-application).

I tried to find it by running:

```<code>find -name "libpython3.4m.so.1.0"
</code>```

but it did not return anything. Any idea on how to solve this issue?

I am using Lubuntu.

答:
If you trying to run uwsgi in a virtual environment. Then run the following

```<code>pip install python-pcre
</code>```

Now, try running the wsgi. Hope this helps!

Body:
I've been runing uwsgi like so:

uwsgi --ini CMS_uwsgi.ini

and it used to work. However, I tried running uwsgi again after a couple weeks and I get this error now:

uwsgi: error while loading shared libraries: libpython3.4m.so.1.0:
cannot open shared object file: No such file or directory

I'm not sure why I'm getting this error now. It Might be because recently, I did

sudo apt-get autoremove

to remove installed packages that used to be installed as dependencies but aren't any longer (as mentioned here https://askubuntu.com/questions/187888/what-is-the-correct-way-to-completely-remove-an-application).

I tried to find it by running:

find -name "libpython3.4m.so.1.0"

but it did not return anything. Any idea on how to solve this issue?

I am using Lubuntu.

Body:
If you trying to run uwsgi in a virtual environment. Then run the following

pip install python-pcre

Now, try running the wsgi. Hope this helps!


问:
what happens behind the scenes of executing `UIApplication.shared.registerForRemoteNotifications()` in iOS?
I'm wondering what's happening behind the scenes when registering ios applications for push notifications and how the ios device receives device-token in application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) callback. I need to know the complete scenario and protocol communication.

答:
the most related things I could find are:

https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html

https://developer.apple.com/library/archive/technotes/tn2265/_index.html

what I could understand is that most of the work is done by os that establishes a direct and persistent connection to apple's servers. no more information about any protocols or request-responses.


问:
how to update specific object in array which match conditions
actually i want to update specific object in my documents array which has viewProfile : true but it's gonna update all elements in array
here is my query:

```<code>const user = await User.updateMany(
    {
      _id: req.userData.id,
      "notifications.viewProfile" : true
    },
    {
      $set: {
        "notifications.$[].read": false
      }
    }
  );
</code>```

consider this document

```<code>/* 1 */
{
    "_id" : ObjectId("5e4ae76bd4e24418a020b665"),
    "username" : "test",
    "notifications" : [
        {
            "createdAt" : ISODate("2020-02-18T19:22:24.809Z"),
            "_id" : ObjectId("5e4c397075265a36203dab5a"),
            "message" : "testone is now following you.",
            "viewProfile" : false,
            "read" : false
        },
        {
            "createdAt" : ISODate("2020-02-18T19:22:29.200Z"),
            "_id" : ObjectId("5e4c397575265a36203dab5d"),
            "message" : "testone is now following you.",
            "viewProfile" : true,
            "read" : false
        }
    ],
}
</code>```

答:
Use filtered positional operator $[<identifier>] . Reference https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

```<code>const user = await User.update(
   {
      _id: req.userData.id
   },
   { $set: {  "notifications.$[element].read": false } },
   {
     multi: true,
     arrayFilters: [ { "element.viewProfile": true } ]
   }
)
</code>```

Body:
actually i want to update specific object in my documents array which has viewProfile : true but it's gonna update all elements in array
here is my query:

const user = await User.updateMany(
    {
      _id: req.userData.id,
      "notifications.viewProfile" : true
    },
    {
      $set: {
        "notifications.$[].read": false
      }
    }
  );

consider this document

/* 1 */
{
    "_id" : ObjectId("5e4ae76bd4e24418a020b665"),
    "username" : "test",
    "notifications" : [
        {
            "createdAt" : ISODate("2020-02-18T19:22:24.809Z"),
            "_id" : ObjectId("5e4c397075265a36203dab5a"),
            "message" : "testone is now following you.",
            "viewProfile" : false,
            "read" : false
        },
        {
            "createdAt" : ISODate("2020-02-18T19:22:29.200Z"),
            "_id" : ObjectId("5e4c397575265a36203dab5d"),
            "message" : "testone is now following you.",
            "viewProfile" : true,
            "read" : false
        }
    ],
}

Body:
Use filtered positional operator $[<identifier>] . Reference https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/

const user = await User.update(
   {
      _id: req.userData.id
   },
   { $set: {  "notifications.$[element].read": false } },
   {
     multi: true,
     arrayFilters: [ { "element.viewProfile": true } ]
   }
)


问:
How can I redirect using vue-router?
I have tried to access to others pages via url, but those pages never loads

http://localhost:8080/index

http://localhost:8080/about

This is my main.js file

```<code>import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import VueRouter from 'vue-router'

Vue.config.productionTip = false

Vue.use(VueRouter)

import Index from './views/Index';
const About = { template: '<p>about page</p>' }

const routes = [
  { path: '/index', name: 'index', component: Index },
  { path: '/about', name: 'about', component: About }
]

var router = new VueRouter({
  routes: routes,
  mode: 'history'
})

new Vue({
  router: router,
  vuetify,
  render: h => h(App)
}).$mount('#app')
</code>```

Does anyone can help me with vue-router? i am new in this framework

答:
Does it work if you access them like this:

http://localhost:8080/#/about

If yes, your vue-router is working in the default hash-mode. To get rid of the hash and get "normal" URLs you'll need to set it to history mode.

Edit:

As I see you're already using history mode. Do you use Vue CLI for local development? This should normally work out of the box. If not, you need to setup some redirect rules on other web servers. Please see the examples here: Example Server Configurations

Edit 2:
Can you show your App component?
I tried to reproduce your problem in a sandbox, but it works: https://codesandbox.io/s/confident-voice-zyg07

The App component here looks like this, including the router-view:

```<code><template>
  <div id="app">
    <router-view id="page"/>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {}
};
</script>
</code>```

Title: How can I redirect using vue-router?

Body:
I have tried to access to others pages via url, but those pages never loads

http://localhost:8080/index

http://localhost:8080/about

This is my main.js file

import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import VueRouter from 'vue-router'

Vue.config.productionTip = false

Vue.use(VueRouter)

import Index from './views/Index';
const About = { template: '
about page
' }

const routes = [
  { path: '/index', name: 'index', component: Index },
  { path: '/about', name: 'about', component: About }
]

var router = new VueRouter({
  routes: routes,
  mode: 'history'
})

new Vue({
  router: router,
  vuetify,
  render: h => h(App)
}).$mount('#app')

Does anyone can help me with vue-router? i am new in this framework

Body:
Does it work if you access them like this:

http://localhost:8080/#/about

If yes, your vue-router is working in the default hash-mode. To get rid of the hash and get "normal" URLs you'll need to set it to history mode.

Edit:

As I see you're already using history mode. Do you use Vue CLI for local development? This should normally work out of the box. If not, you need to setup some redirect rules on other web servers. Please see the examples here: Example Server Configurations

Edit 2:
Can you show your App component?
I tried to reproduce your problem in a sandbox, but it works: https://codesandbox.io/s/confident-voice-zyg07

The App component here looks like this, including the router-view:

<template>
  <div id="app">
    <router-view id="page"/>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {}
};
</script>


问:
I am trying to compare two arrays inside For Loops
I am creating a Lottery Program where I want to compare the winning numbers with the players numbers and if any numbers match, they win a prize. I have used count to do this in my match() method but it comes up with an error when I try to compare two arrays - getWinningNumbers() and getNumbers() which are from the other classes PLAYER and WINNINGNUMBERS. The error I am getting is "actual and formal parameters differ in length" but I am unsure how to fix this. I am using linked lists for the first time as well. Any help would be much appreciated.

The piece of code I am having trouble with is in the method match() in the Lottery Class.

```<code>public void matches() {
        PLAYER currentPlayer = pHead;
        int count = 0;
        for(int i = 0; i<6; i++) {
            for(int j = 0; j< 6; j++) {
                if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
                    count++;
                }
            }
        }

``````````````````````````````````````````````````````````````````````````
</code>```

答:
Maybe this example can help you a bit:

```<code>List<Integer> winningNumber = new LinkedList<>(Arrays.asList(3, 9, 15, 1, 11, 18));
List<Integer> playerNumbers = new LinkedList<>(Arrays.asList(2, 8, 15, 7, 11, 9));

matches(winningNumber, playerNumbers);

private static void matches(List<Integer> winningNumbers, List<Integer> playerNumbers) {
    if(winningNumbers.size() != playerNumbers.size()) {
        System.out.println("winning numbers and player numbers differ in size");
    }
    int counter = 0;
    for(int i = 0; i < winningNumbers.size(); i++) {
        if(winningNumbers.get(i) == playerNumbers.get(i)) {
            counter++;
        }
    }
    System.out.println("Number of matches in position: " + counter);

    // if the position of match is not important
    long matches = winningNumbers.stream()
            .filter(playerNumbers::contains)
            .count();
    System.out.println("Number of matches: " + matches);
}
</code>```

Number of matches in position: 2

Number of matches: 3

Body:
I am creating a Lottery Program where I want to compare the winning numbers with the players numbers and if any numbers match, they win a prize. I have used count to do this in my match() method but it comes up with an error when I try to compare two arrays - getWinningNumbers() and getNumbers() which are from the other classes PLAYER and WINNINGNUMBERS. The error I am getting is "actual and formal parameters differ in length" but I am unsure how to fix this. I am using linked lists for the first time as well. Any help would be much appreciated.

The piece of code I am having trouble with is in the method match() in the Lottery Class.

public void matches() {
        PLAYER currentPlayer = pHead;
        int count = 0;
        for(int i = 0; i<6; i++) {
            for(int j = 0; j< 6; j++) {
                if (win.getWinningNumbers(i) == currentPlayer.getNumbers(j)) {
                    count++;
                }
            }
        }

``````````````````````````````````````````````````````````````````````````

Body:
Maybe this example can help you a bit:

List<Integer> winningNumber = new LinkedList<>(Arrays.asList(3, 9, 15, 1, 11, 18));
List<Integer> playerNumbers = new LinkedList<>(Arrays.asList(2, 8, 15, 7, 11, 9));

matches(winningNumber, playerNumbers);

private static void matches(List<Integer> winningNumbers, List<Integer> playerNumbers) {
    if(winningNumbers.size() != playerNumbers.size()) {
        System.out.println("winning numbers and player numbers differ in size");
    }
    int counter = 0;
    for(int i = 0; i < winningNumbers.size(); i++) {
        if(winningNumbers.get(i) == playerNumbers.get(i)) {
            counter++;
        }
    }
    System.out.println("Number of matches in position: " + counter);

    // if the position of match is not important
    long matches = winningNumbers.stream()
            .filter(playerNumbers::contains)
            .count();
    System.out.println("Number of matches: " + matches);
}

Number of matches in position: 2

Number of matches: 3


问:
jspeex decoder not producing the correct output
I am using JSpeex api for decoding rtmp audio stream into wave file and using the same stream to save speex encoded audio to flv file.

I found that there are differences in both the audio.

Time length of both audio file is different. FLV shows the original timing while wave file time is always less than the FLV file.

The quality of FLV is better that wave file.

The voice does not match to speaker in wave file, but FLV seems to be perfect.

Can somebody guide me in this?

答: JSpeex is based on the 1.0.3. version of Speex, which was released in 2003. There have been several new versions since then, the most recent being 1.2rc1 (released in 2008). Is it possible that your audio has been encoded in a newer version of Speex than 1.0.3?</p>


问:
ConfigError "dnspython must be installed" when requirement already satisfied
Trying to connect a Colab Notebook to a MongoDB on Atlas.

```<code>from pymongo import MongoClient
uri = "mongodb+srv://MYUSERNAME:mypassword@mydatabase.mongodb.net/test"

client = MongoClient(uri)
</code>```

I am getting a CongfigurationError:

```<code>"dnspython" module must be installed to use mongodb+srv:// URIs.
</code>```

I installed the module.

```<code>pip install dnspython
</code>```

Got the message back

```<code>Requirement already satisfied: dnspython in /usr/local/lib/python3.6/dist-packages (1.16.0)
</code>```

Do not know what is wrong.

This worked a few days ago with another colab notebook (and another database).

Here is the entire error message:

```<code>ConfigurationError                        Traceback (most recent call last)
<ipython-input-30-a6c89e14e64f> in <module>()
----> 1 client = MongoClient(uri)

1 frames
/usr/local/lib/python3.6/dist-packages/pymongo/mongo_client.py in __init__(self, host, port, document_class, tz_aware, connect, type_registry, **kwargs)
    522         for entity in host:
    523             if "://" in entity:
--> 524                 res = uri_parser.parse_uri(entity, port, warn=True)
    525                 seeds.update(res["nodelist"])
    526                 username = res["username"] or username

/usr/local/lib/python3.6/dist-packages/pymongo/uri_parser.py in parse_uri(uri, default_port, validate, warn)
    316     elif uri.startswith(SRV_SCHEME):
    317         if not _HAVE_DNSPYTHON:
--> 318             raise ConfigurationError('The "dnspython" module must be '
    319                                      'installed to use mongodb+srv:// URIs')
    320         is_srv = True

ConfigurationError: The "dnspython" module must be installed to use mongodb+srv:// URIs
</code>```

答:
You have to restart runtime to have the changes take effect:

!pip install dnspython

Restart runtime Runtime -> Restart runtime...

Run your code

Body:
Trying to connect a Colab Notebook to a MongoDB on Atlas.

from pymongo import MongoClient
uri = "mongodb+srv://MYUSERNAME:mypassword@mydatabase.mongodb.net/test"

client = MongoClient(uri)

I am getting a CongfigurationError:

"dnspython" module must be installed to use mongodb+srv:// URIs.

I installed the module.

pip install dnspython

Got the message back

Requirement already satisfied: dnspython in /usr/local/lib/python3.6/dist-packages (1.16.0)

Do not know what is wrong.

This worked a few days ago with another colab notebook (and another database).

Here is the entire error message:

ConfigurationError                        Traceback (most recent call last)
<ipython-input-30-a6c89e14e64f> in <module>()
----> 1 client = MongoClient(uri)

1 frames
/usr/local/lib/python3.6/dist-packages/pymongo/mongo_client.py in __init__(self, host, port, document_class, tz_aware, connect, type_registry, **kwargs)
    522         for entity in host:
    523             if "://" in entity:
--> 524                 res = uri_parser.parse_uri(entity, port, warn=True)
    525                 seeds.update(res["nodelist"])
    526                 username = res["username"] or username

/usr/local/lib/python3.6/dist-packages/pymongo/uri_parser.py in parse_uri(uri, default_port, validate, warn)
    316     elif uri.startswith(SRV_SCHEME):
    317         if not _HAVE_DNSPYTHON:
--> 318             raise ConfigurationError('The "dnspython" module must be '
    319                                      'installed to use mongodb+srv:// URIs')
    320         is_srv = True

ConfigurationError: The "dnspython" module must be installed to use mongodb+srv:// URIs


问:
django form resubmitted upon refresh
After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that.

Here's my form in template :

```<code><form action = "" method = "POST"> {% csrf_token %}
    {{ form.as_p }}
    <input type = "submit" value = "Shout!"/>
</form>
</code>```

How can I fix this ?

Here's my views:

```<code>def index(request):
    shouts = Shout.objects.all()

    if request.method == "POST":
        form = GuestBookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            shout = Shout(author = cd['author'], message = cd['message'])
            shout.save()
            form = GuestBookForm()
    else:
        form = GuestBookForm()

    return render_to_response('guestbook/index.html', {'shouts' : shouts,
                                             'form' : form },
                              context_instance = RequestContext(request))
</code>```

答:
This solution worked for me. After form submission we have have to display a message in our template in form of popup or text in any form so though HttpResponseRedirect may prevent form resubmission but it won't deliver the message so here is what I did.

```<code>from django.contrib import messages

def index_function(request):
     if request.method == "POST":
     form = some_form(request.POST)
     if form.is_valid():
        # do processing
        # save model, etc.
        messages.success(request, 'Form successfully submitted') # Any message you wish
     return HttpResponseRedirect("/url")
</code>```

Then inside your template, you can show this message. Since this is global parameter you can display it in any HTML template like the following.

```<code>{% if messages %}
<div class="alert alert-success alert-dismissible">
  {% for message in messages %}
    <p>{{ message }}</p>
  {% endfor %}
</div>
{% endif %}
</code>```

Title: django form resubmitted upon refresh

Body:
After I submit the form for the first time and then refresh the form it gets resubmitted and and I don't want that.

Here's my form in template :

<form action = "" method = "POST"> {% csrf_token %}
    {{ form.as_p }}
    <input type = "submit" value = "Shout!"/>
</form>

How can I fix this ?

Here's my views:

def index(request):
    shouts = Shout.objects.all()

    if request.method == "POST":
        form = GuestBookForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            shout = Shout(author = cd['author'], message = cd['message'])
            shout.save()
            form = GuestBookForm()
    else:
        form = GuestBookForm()

    return render_to_response('guestbook/index.html', {'shouts' : shouts,
                                             'form' : form },
                              context_instance = RequestContext(request))

Body:
This solution worked for me. After form submission we have have to display a message in our template in form of popup or text in any form so though HttpResponseRedirect may prevent form resubmission but it won't deliver the message so here is what I did.

from django.contrib import messages

def index_function(request):
     if request.method == "POST":
     form = some_form(request.POST)
     if form.is_valid():
        # do processing
        # save model, etc.
        messages.success(request, 'Form successfully submitted') # Any message you wish
     return HttpResponseRedirect("/url")

Then inside your template, you can show this message. Since this is global parameter you can display it in any HTML template like the following.

{% if messages %}
<div class="alert alert-success alert-dismissible">
  {% for message in messages %}
    <p>{{ message }}</p>
  {% endfor %}
</div>
{% endif %}


问:
How to get TextField value from another class or method
I don't know how JTextField works. I'm trying a lots.
My question is: How to get TextField value from another class or method?

```<code>import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MuGUI extends JPanel {
    public MyGui() {
        JTextField betText = new JTextField("");
    }

    public void method2() {
        // error this line, cant find betText
        String value = betText.getText();
    }
</code>```

答:
You can declare your JTextField globally and then you initialize it inside your constructor. Now you have access to your variable in your methods too. </p>

```<code>public class MyGUI extends JPanel
{
  private JTextField betText;

  public MyGUI(){
     //other operations
     betText = new JTextField("");
  }

  public void test(){
     String a = betText.getText();
  }
 }
</code>```

Body:
I don't know how JTextField works. I'm trying a lots.
My question is: How to get TextField value from another class or method?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MuGUI extends JPanel {
    public MyGui() {
        JTextField betText = new JTextField("");
    }

    public void method2() {
        // error this line, cant find betText
        String value = betText.getText();
    }

Body:
You can declare your JTextField globally and then you initialize it inside your constructor. Now you have access to your variable in your methods too.

public class MyGUI extends JPanel
{
  private JTextField betText;

  public MyGUI(){
     //other operations
     betText = new JTextField("");
  }

  public void test(){
     String a = betText.getText();
  }
 }


答:
Im using the dplyr library to filter() the data by quantile():
The code:

```<code>library(dplyr)
library(ggplot2)

 ggplot()+
geom_point(data=filter(dfw,Hs.Obs>quantile(dfw$Hs.Mod,.99)),aes(x=sort(Hs.Obs),y=sort(Hs.Mod), col="Cuantile 99%"))+
geom_point(data=filter(dfw,Hs.Obs<quantile(dfw$Hs.Mod,.99)),aes(x=sort(Hs.Obs),y=sort(Hs.Mod), col="Cuantile 1-98%"))+
geom_abline(linetype=2)+xlab('Obs') + ylab('Model')+ theme_bw()
</code>```

Title: Colour a Q-Q plot comparing two distributions by quartiles in R

Body:
I am trying to construct a Q-Q plot comparing two distributions, with the 99th percentile colored like the following example:

However I am not sure how to achieve this, here is a subset of my data:

dfw <- structure(list(Date.Time = structure(c(848502000, 848509200,
                                               848512800, 848520000, 848523600, 848530800, 848534400, 848541600,
                                               848545200, 848552400, 848556000, 848563200, 848566800, 848574000,
                                               848577600, 848588400, 848595600, 848599200, 848606400, 848610000,
                                               848617200, 848620800, 848628000, 848631600, 848638800, 848642400,
                                               848649600, 848653200, 848660400, 848664000, 848674800, 848682000,
                                               848685600, 848692800, 848696400, 848703600, 848707200, 848714400,
                                               848718000, 848725200, 848728800, 848736000, 848739600, 848746800,
                                               848750400, 848761200, 848768400, 848772000, 848779200, 848782800,
                                               848790000, 848793600, 848800800, 848804400, 848811600, 848815200,
                                               848822400, 848826000, 848833200, 848847600, 848854800, 848858400,
                                               848865600, 848869200, 848876400, 848880000, 848887200, 848890800,
                                               848898000, 848901600, 848908800, 848912400, 848919600, 848923200,
                                               848934000, 848941200, 848944800, 848952000, 848955600, 848962800,
                                               848966400, 848973600, 848977200, 848984400, 848988000, 848995200,
                                               848998800, 849006000, 849009600, 853682400, 853686000, 853714800,
                                               853718400, 853725600, 853729200, 853736400, 853750800, 853758000,
                                               853761600, 853768800), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
                       Hs.Mod = c(1.5960001, 1.5600001, 1.5480001, 1.552, 1.552,
                                  1.534, 1.5180001, 1.462, 1.4260001, 1.3740001, 1.36, 1.3340001,
                                  1.3080001, 1.2720001, 1.256, 1.218, 1.212, 1.21, 1.2060001,
                                  1.2160001, 1.248, 1.25, 1.25, 1.264, 1.3560001, 1.394, 1.3700001,
                                  1.332, 1.2900001, 1.2800001, 1.268, 1.2800001, 1.2800001,
                                  1.3240001, 1.3240001, 1.286, 1.2540001, 1.19, 1.172, 1.1700001,
                                  1.1860001, 1.2340001, 1.274, 1.3640001, 1.4120001, 1.58,
                                  1.6580001, 1.6660001, 1.682, 1.748, 1.9280001, 1.9800001,
                                  2.026, 2.052, 2.214, 2.328, 2.4320002, 2.39, 2.2180002, 1.9080001,
                                  1.792, 1.7400001, 1.7140001, 1.7140001, 1.692, 1.6680001,
                                  1.608, 1.58, 1.536, 1.524, 1.5640001, 1.5760001, 1.6100001,
                                  1.6240001, 1.6120001, 1.5920001, 1.58, 1.542, 1.5200001,
                                  1.48, 1.4640001, 1.4260001, 1.406, 1.386, 1.3820001, 1.34,
                                  1.312, 1.268, 1.248, 1.8080001, 1.7960001, 1.644, 1.6420001,
                                  1.6600001, 1.6880001, 1.7820001, 2.138, 2.2740002, 2.2940001,
                                  2.252), Hs.Obs = c(1.741, 1.524, 1.618, 1.658, 1.697, 1.822,
                                                     1.792, 1.463, 1.433, 1.376, 1.208, 1.299, 1.255, 1.304, 1.328,
                                                     1.182, 1.282, 1.293, 1.228, 1.281, 1.45, 1.356, 1.501, 1.5,
                                                     1.356, 1.477, 1.408, 1.544, 1.497, 1.768, 2.04, 2.074, 2.042,
                                                     2.147, 2.224, 2.022, 2.017, 2.047, 2.353, 2.597, 2.838, 2.67,
                                                     2.762, 2.687, 2.734, 2.738, 2.938, 2.795, 2.549, 2.669, 2.447,
                                                     2.676, 2.577, 2.383, 2.362, 2.284, 2.341, 2.33, 2.397, 2.498,
                                                     2.317, 2.373, 2.377, 2.362, 2.218, 2.226, 1.97, 2.087, 1.874,
                                                     2.116, 2.022, 1.886, 2.046, 1.879, 1.638, 1.677, 1.638, 1.647,
                                                     1.551, 1.596, 1.591, 1.384, 1.345, 1.522, 1.469, 1.503, 1.459,
                                                     1.327, 1.453, 2.448, 2.235, 2.104, 1.958, 2.118, 2.209, 2.034,
                                                     2.229, 2.505, 2.163, 2.372)), row.names = c(NA, 100L), class = "data.frame")

Code to make the Q-Q plot:

ggplot(data=dfw, aes(x=sort(Hs.Obs), y=sort(Hs.Mod))) + geom_point(shape = 1, size =2) + xlab('Obs') + ylab('Model')+
  theme_bw()+
  geom_abline(linetype=2)

Code attempting to colour the 99th percentile:

ggplot(data=dfw, aes(x=sort(Hs.Obs), y=sort(Hs.Mod), col=cut(Hs.Mod,quantile(Hs.Mod, probs = .99)))) +
  geom_point(shape = 1, size =2) + xlab('Obs') + ylab('Model')+
  theme_bw()+
  geom_abline(linetype=2)

Resulting plot:

I'm looking for some help to sort this out, as the attempts I have tried aren't working.
Thanks in advance!

Body:
Im using the dplyr library to filter() the data by quantile():
The code:

library(dplyr)
library(ggplot2)

 ggplot()+
geom_point(data=filter(dfw,Hs.Obs>quantile(dfw$Hs.Mod,.99)),aes(x=sort(Hs.Obs),y=sort(Hs.Mod), col="Cuantile 99%"))+
geom_point(data=filter(dfw,Hs.Obs<quantile(dfw$Hs.Mod,.99)),aes(x=sort(Hs.Obs),y=sort(Hs.Mod), col="Cuantile 1-98%"))+
geom_abline(linetype=2)+xlab('Obs') + ylab('Model')+ theme_bw()


问:
Which ML Algorithm should I use to predict a list of events?
I'm new to data science model selection and I hope you can help on the model selection to my current problem.

I'm trying to predict the list of events based on the categorical features with numerical labels. For example:

```<code>x1 x2 x3 x4 x5 y1
1   1  3  4  5  Injury
2   2  2  1  3  Flood
3   1  2  3  2  Injury
3   2  1  1  1  Fire
1   1  1  1  1  Protest
</code>```

I like to predict the top 3 events based on the categorical features. I assume it involves probability method in the machine learning, which algorithm / ML / Deep Learning method would you suggest me to use?

Expectation output would be as follows:

```<code>1. Injury
2. Fire
3. Flood
</code>```

答:
I assume that you have fixed-size input, five categorical variables.

First proposal try to use embedings vectors instead of simple integers for categorical value encoding. The simplest way is use embeding layers and let the network create embedings for you.

Second proposal, for this purpose seems to me ok use multilayer perceptron or 1D convolution layer(maybe combine both of them). Philosophy should be, you apply your input features, these will be processed following dense or 1D CNNN layers, the output layer will be dense layer. If these are only possible diagnosis

Injury

Flood

Fire

Protest

Than your output will have 4 units. If you want a list, you may try the treshold approach, so if unit activation passed through the treshold value is considered as part of possible diagnosis list.

About technical aspect you not mention about your background. So I recommend to use some standard ML library tensorflow, pytorch... Is relatively easy to setup and perform experiments.

Edit

Network may looks like:

```<code>model = Sequential()
model.add(Dense(units, activation="relu", input_shape=appropriate_shape))
model.add(Dense(output_units, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=['acc']))
</code>```

If you construct network at such manner(see softmax at output layer and categorical_crossentropy as loss) network will natural produce probabilities as output. After training, if you use model as:

```<code>results = model.predict(input_data)
</code>```

Results will be list of lists of probabilities(one list for every input sample). If you calculate sum of one such a list, you get the 1.

Body:
I'm new to data science model selection and I hope you can help on the model selection to my current problem.

I'm trying to predict the list of events based on the categorical features with numerical labels. For example:

x1 x2 x3 x4 x5 y1
1   1  3  4  5  Injury
2   2  2  1  3  Flood
3   1  2  3  2  Injury
3   2  1  1  1  Fire
1   1  1  1  1  Protest

I like to predict the top 3 events based on the categorical features. I assume it involves probability method in the machine learning, which algorithm / ML / Deep Learning method would you suggest me to use?

Expectation output would be as follows:

1. Injury
2. Fire
3. Flood

Body:
I assume that you have fixed-size input, five categorical variables.

First proposal try to use embedings vectors instead of simple integers for categorical value encoding. The simplest way is use embeding layers and let the network create embedings for you.

Second proposal, for this purpose seems to me ok use multilayer perceptron or 1D convolution layer(maybe combine both of them). Philosophy should be, you apply your input features, these will be processed following dense or 1D CNNN layers, the output layer will be dense layer. If these are only possible diagnosis

Injury

Flood

Fire

Protest

Than your output will have 4 units. If you want a list, you may try the treshold approach, so if unit activation passed through the treshold value is considered as part of possible diagnosis list.

About technical aspect you not mention about your background. So I recommend to use some standard ML library tensorflow, pytorch... Is relatively easy to setup and perform experiments.

Edit

Network may looks like:

model = Sequential()
model.add(Dense(units, activation="relu", input_shape=appropriate_shape))
model.add(Dense(output_units, activation="softmax"))
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=['acc']))

If you construct network at such manner(see softmax at output layer and categorical_crossentropy as loss) network will natural produce probabilities as output. After training, if you use model as:

results = model.predict(input_data)

Results will be list of lists of probabilities(one list for every input sample). If you calculate sum of one such a list, you get the 1.


问:
Debugging Azure Service Fabric Application in Visual Studio for 5 node cluster
I am having a very simple use case where I need to setup a 5 node cluster environment in Azure Service Fabric and then debug the code.

The problem that I am facing is that when I deploy my application locally for a 5 node cluster, since there is only one node that can use my port on machine, my application just runs on 1 node cluster and the deployment fails on other 4 nodes because the port is unavailable.

I am looking for steps to deploy and test multi-node cluster in local environment. Any lead will be appreciated and is this possible also to test locally a multi-node Azure Service Fabric cluster.

答:
Can you try this?:

Use environment specific settings to define the port number:

  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="Web1Pkg" ServiceManifestVersion="1.0.0" />
    <ResourceOverrides>
      <Endpoints>
        <Endpoint Name="ServiceEndpoint" Port="[MyWebAPI_PortNumber]"/>
      </Endpoints>
    </ResourceOverrides>
    <ConfigOverrides />
  </ServiceManifestImport>
```

<p>Define an <strong>empty</strong> default value in the app manifest, to use a random port by default:</p>

<pre class="lang-xml prettyprint-override"><code><Parameters>
  <Parameter Name="MyWebAPI_PortNumber" DefaultValue="" />
</Parameters>
</code>```

Define an environment specific override value in cloud.xml, to use port 80 in that environment:

  <Parameters>
    <Parameter Name="MyWebAPI_PortNumber" Value="80" />
  </Parameters>
```

In the production cluster you can use the same port on every node.

On your local 5-node development cluster, you'd use different ports.

More info here.

Body:
Can you try this?:

Use environment specific settings to define the port number:

  <ServiceManifestImport>
    <ServiceManifestRef ServiceManifestName="Web1Pkg" ServiceManifestVersion="1.0.0" />
    <ResourceOverrides>
      <Endpoints>
        <Endpoint Name="ServiceEndpoint" Port="[MyWebAPI_PortNumber]"/>
      </Endpoints>
    </ResourceOverrides>
    <ConfigOverrides />
  </ServiceManifestImport>

Define an empty default value in the app manifest, to use a random port by default:

<Parameters>
  <Parameter Name="MyWebAPI_PortNumber" DefaultValue="" />
</Parameters>

Define an environment specific override value in cloud.xml, to use port 80 in that environment:

  <Parameters>
    <Parameter Name="MyWebAPI_PortNumber" Value="80" />
  </Parameters>

In the production cluster you can use the same port on every node.

On your local 5-node development cluster, you'd use different ports.

More info here.


问:
Style views passed to custom view in SwiftUI
What I would like to be able to do is use a custom View like this: The number or types of views passed to Nav can be different.

```<code>Nav(
    width: 200
) {
    NavButton("Item 1", action: {self.someAction}, isActive: true)
    NavButton("Item 1", action: {self.someAction}, isActive: false)
    NavTitle("Page 1")
}
</code>```

And that it would give the same result as:

```<code>HStack {
    NavButton("Item 1", action: {self.someAction}, isActive: true)
    .frame(width: 200 / 3)
    NavButton("Item 1", action: {self.someAction}, isActive: false)
    .frame(width: 200 / 3)
    NavTitle("Page 1")
    .frame(width: 200 / 3)
}
</code>```

The idea is to have evenly spaced items in a navbar.

I thought about using an array of views and passing it as a property, but that looks awful to me. Is there a way to do the same as in my example above, or any better way to do this?

答:
Like This :- </p>

```<code>import SwiftUI

struct ContentView: View {

    var body: some View {

        HStack {
            CustomText(text: "kjahsfgdi f")
            Spacer()
            CustomText(text: "abc")
            Spacer()
            CustomText(text: "abc")
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct CustomText : View{
    @State var text: String
    var body: some View {
        Text(text)
            .lineLimit(nil)
            .frame(width: 100, height: nil, alignment: .center)
    }
}
</code>```

Body:
What I would like to be able to do is use a custom View like this: The number or types of views passed to Nav can be different.

Nav(
    width: 200
) {
    NavButton("Item 1", action: {self.someAction}, isActive: true)
    NavButton("Item 1", action: {self.someAction}, isActive: false)
    NavTitle("Page 1")
}

And that it would give the same result as:

HStack {
    NavButton("Item 1", action: {self.someAction}, isActive: true)
    .frame(width: 200 / 3)
    NavButton("Item 1", action: {self.someAction}, isActive: false)
    .frame(width: 200 / 3)
    NavTitle("Page 1")
    .frame(width: 200 / 3)
}

The idea is to have evenly spaced items in a navbar.

I thought about using an array of views and passing it as a property, but that looks awful to me. Is there a way to do the same as in my example above, or any better way to do this?

Body:
Like This :-

import SwiftUI

struct ContentView: View {

    var body: some View {

        HStack {
            CustomText(text: "kjahsfgdi f")
            Spacer()
            CustomText(text: "abc")
            Spacer()
            CustomText(text: "abc")
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct CustomText : View{
    @State var text: String
    var body: some View {
        Text(text)
            .lineLimit(nil)
            .frame(width: 100, height: nil, alignment: .center)
    }
}


问:
Putting a list into a class c#
Is it possible to put a list into a class? So for example if I have a class of Person and their properties are Name, Age, Valuables can the Valuables property be a list that holds a Valuable class with properties like ItemName, Cost, Quantity?</p>

答:
Yes, absolutely!

You would just have

```<code>public class Person {
     string Name;
     int Age;
     List<Valuable> Valuables = new List<Valuable>();
}

public class Valuable {
    string ItemName;
    double Cost;
    int Quantity;
}
</code>```

to use the code, you would then

```<code>Person bob = new Person { Name = "Bob", Age = 29 };
Valuable bobsCrystalBall = new Valuable { ItemName = "CrystalBall", Cost = 9.99, Quantity = 1}
bob.Valuables.Add(bobsCrystalBall);
</code>```

@SomeBody should have specified that you can't do Person.Valuables.Add directly, you have to do that on an instance of that class. You create an instance of a class with the keyword new. Similarly with adding an instance of the class Valuable.

Title: Putting a list into a class c#

Body:
Yes, absolutely!

You would just have

public class Person {
     string Name;
     int Age;
     List<Valuable> Valuables = new List<Valuable>();
}

public class Valuable {
    string ItemName;
    double Cost;
    int Quantity;
}

to use the code, you would then

Person bob = new Person { Name = "Bob", Age = 29 };
Valuable bobsCrystalBall = new Valuable { ItemName = "CrystalBall", Cost = 9.99, Quantity = 1}
bob.Valuables.Add(bobsCrystalBall);

@SomeBody should have specified that you can't do Person.Valuables.Add directly, you have to do that on an instance of that class. You create an instance of a class with the keyword new. Similarly with adding an instance of the class Valuable.


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答: I am assuming you are using the Windows Shell here. If you invoke the compiler from a cygwin Bash shell, all the paths should be set for you. </p>

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: Francis Beaudet


问:
What is the right way to get an NSString object from an NSArray, keeping Memory Managment in mind?
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
</code>```

Now I want to get an object from this NSArray at index 2.

```<code>NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?
</code>```

OR I should first alloc nameString and then assign value to it ?

答:
```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
NSString *nameString = [myNewArray objectAtIndex:2]
[myArray release];
</code>```

That's it, no need to bother any more with it. NSString will be released by environment itself.

Body:
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];

Now I want to get an object from this NSArray at index 2.

NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?

OR I should first alloc nameString and then assign value to it ?

Body:
NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
NSString *nameString = [myNewArray objectAtIndex:2]
[myArray release];

That's it, no need to bother any more with it. NSString will be released by environment itself.