问:
Problems getting QTimer to start when using QThread
I'm trying to implement a webcam using PyQt5 from an example I found (here, but not really relevant).
Getting the example to work wasn't an issue, but I wanted to modify some things and I am stuck on one particular problem.

I have two classes, one QObject Capture which has a QBasicTimer that I want to start, and a QWidget MyWidget with a button that is supposed to start the timer of the Capture object, which is inside a QThread.

If I directly connect the button click to the method that starts the timer, everything works fine.

But I want to do some other things when I click the button, so I connected the button to a method of MyWidget first and call the start method of Capture from there. This, however, doesn't work: the timer doesn't start.

Here is a minimal working example:

```<code>from PyQt5 import QtCore, QtWidgets
import sys

class Capture(QtCore.QObject):
    def __init__(self, parent=None):
        super(Capture, self).__init__(parent)

        self.m_timer = QtCore.QBasicTimer()

    def start(self):
        print("capture start called")
        self.m_timer.start(1000, self)

    def timerEvent(self, event):
        print("time event")

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)

        lay = QtWidgets.QVBoxLayout(self)
        self.btn_start = QtWidgets.QPushButton("Start")
        lay.addWidget(self.btn_start)

        self.capture = Capture()
        captureThread = QtCore.QThread(self)
        captureThread.start()
        self.capture.moveToThread(captureThread)

        # self.btn_start.clicked.connect(self.capture.start) # this works
        self.btn_start.clicked.connect(self.startCapture) # this doesn't
        # self.capture.start() # this doesn't either

        self.show()

    def startCapture(self):
        self.capture.start()

def run_app():
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MyWidget()
    mainWin.show()
    app.exec_()

run_app()
</code>```

It is some problem with the QThread, because if I don't use threading it works. I thought maybe it has something to do with the thread not being in some way available when called from a different method than the one it was created in, but calling self.capture.start() directly from the init does not work either.

I only have a very basic grasp of threads. Can someone tell me how I can properly call self.capture.start() from MyWidget and why it works without problems when directly connecting it to the button click?

答:
If you connect the button's clicked signal to the worker's start slot, Qt will automatically detect that it's a cross-thread connection. When the signal is eventually emitted, it will be queued in the receiving thread's event-queue, which ensures the slot will be called within the worker thread.

However, if you connect the button's clicked signal to the startCapture slot, there's no cross-thread connection, because the slot belongs to MyWidget (which lives in the main thread). When the signal is emitted this time, the slot tries to create the timer from within the main thread, which is not supported. Timers must always be started within the thread that creates them (otherwise Qt will print a message like "QBasicTimer::start: Timers cannot be started from another thread").

A better approach is to connect the started and finished signals of the thread to some start and stop slots in the worker, and then call the thread's start and quit methods to control the worker. Here's a demo based on your script, which shows how to implement that:

```<code>from PyQt5 import QtCore, QtWidgets
import sys

class Capture(QtCore.QObject):
    def __init__(self, parent=None):
        super(Capture, self).__init__(parent)
        self.m_timer = QtCore.QBasicTimer()

    def start(self):
        print("capture start called")
        self.m_timer.start(1000, self)

    def stop(self):
        print("capture stop called")
        self.m_timer.stop()

    def timerEvent(self, event):
        print("time event")

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        self.btn_start = QtWidgets.QPushButton("Start")
        lay.addWidget(self.btn_start)
        self.capture = Capture()
        self.captureThread = QtCore.QThread(self)
        self.capture.moveToThread(self.captureThread)
        self.captureThread.started.connect(self.capture.start)
        self.captureThread.finished.connect(self.capture.stop)
        self.btn_start.clicked.connect(self.startCapture)
        self.show()

    def startCapture(self):
        if not self.captureThread.isRunning():
            self.btn_start.setText('Stop')
            self.captureThread.start()
        else:
            self.btn_start.setText('Start')
            self.stopCapture()

    def stopCapture(self):
        self.captureThread.quit()
        self.captureThread.wait()

    def closeEvent(self, event):
        self.stopCapture()

def run_app():
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MyWidget()
    mainWin.show()
    app.exec_()

run_app()
</code>```

Body:
I'm trying to implement a webcam using PyQt5 from an example I found (here, but not really relevant).
Getting the example to work wasn't an issue, but I wanted to modify some things and I am stuck on one particular problem.

I have two classes, one QObject Capture which has a QBasicTimer that I want to start, and a QWidget MyWidget with a button that is supposed to start the timer of the Capture object, which is inside a QThread.

If I directly connect the button click to the method that starts the timer, everything works fine.

But I want to do some other things when I click the button, so I connected the button to a method of MyWidget first and call the start method of Capture from there. This, however, doesn't work: the timer doesn't start.

Here is a minimal working example:

from PyQt5 import QtCore, QtWidgets
import sys

class Capture(QtCore.QObject):
    def __init__(self, parent=None):
        super(Capture, self).__init__(parent)

        self.m_timer = QtCore.QBasicTimer()

    def start(self):
        print("capture start called")
        self.m_timer.start(1000, self)

    def timerEvent(self, event):
        print("time event")

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)

        lay = QtWidgets.QVBoxLayout(self)
        self.btn_start = QtWidgets.QPushButton("Start")
        lay.addWidget(self.btn_start)

        self.capture = Capture()
        captureThread = QtCore.QThread(self)
        captureThread.start()
        self.capture.moveToThread(captureThread)

        # self.btn_start.clicked.connect(self.capture.start) # this works
        self.btn_start.clicked.connect(self.startCapture) # this doesn't
        # self.capture.start() # this doesn't either

        self.show()

    def startCapture(self):
        self.capture.start()

def run_app():
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MyWidget()
    mainWin.show()
    app.exec_()

run_app()

It is some problem with the QThread, because if I don't use threading it works. I thought maybe it has something to do with the thread not being in some way available when called from a different method than the one it was created in, but calling self.capture.start() directly from the init does not work either.

I only have a very basic grasp of threads. Can someone tell me how I can properly call self.capture.start() from MyWidget and why it works without problems when directly connecting it to the button click?

Body:
If you connect the button's clicked signal to the worker's start slot, Qt will automatically detect that it's a cross-thread connection. When the signal is eventually emitted, it will be queued in the receiving thread's event-queue, which ensures the slot will be called within the worker thread.

However, if you connect the button's clicked signal to the startCapture slot, there's no cross-thread connection, because the slot belongs to MyWidget (which lives in the main thread). When the signal is emitted this time, the slot tries to create the timer from within the main thread, which is not supported. Timers must always be started within the thread that creates them (otherwise Qt will print a message like "QBasicTimer::start: Timers cannot be started from another thread").

A better approach is to connect the started and finished signals of the thread to some start and stop slots in the worker, and then call the thread's start and quit methods to control the worker. Here's a demo based on your script, which shows how to implement that:

from PyQt5 import QtCore, QtWidgets
import sys

class Capture(QtCore.QObject):
    def __init__(self, parent=None):
        super(Capture, self).__init__(parent)
        self.m_timer = QtCore.QBasicTimer()

    def start(self):
        print("capture start called")
        self.m_timer.start(1000, self)

    def stop(self):
        print("capture stop called")
        self.m_timer.stop()

    def timerEvent(self, event):
        print("time event")

class MyWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        self.btn_start = QtWidgets.QPushButton("Start")
        lay.addWidget(self.btn_start)
        self.capture = Capture()
        self.captureThread = QtCore.QThread(self)
        self.capture.moveToThread(self.captureThread)
        self.captureThread.started.connect(self.capture.start)
        self.captureThread.finished.connect(self.capture.stop)
        self.btn_start.clicked.connect(self.startCapture)
        self.show()

    def startCapture(self):
        if not self.captureThread.isRunning():
            self.btn_start.setText('Stop')
            self.captureThread.start()
        else:
            self.btn_start.setText('Start')
            self.stopCapture()

    def stopCapture(self):
        self.captureThread.quit()
        self.captureThread.wait()

    def closeEvent(self, event):
        self.stopCapture()

def run_app():
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MyWidget()
    mainWin.show()
    app.exec_()

run_app()


来源: stackexchange

问:
Own DSL with XText. Problem with unlimited brackets ("(", ")")
I am developing my own DSL in XText.

I want do something like this:

```<code>1 AND (2 OR (3 OR 4))
</code>```

Here my current .xtext file:

```<code>grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

Model:
    (greetings+=CONDITION_LEVEL)
;

terminal NUMBER :
    ('1'..'9') ('0'..'9')*
;

AND:
    ' AND '
;

OR:
    ' OR '
;

OPERATOR :
    AND | OR
;

CONDITION_LEVEL:
    ('('* NUMBER (=>')')* OPERATOR)+ NUMBER ')'*
;
</code>```

The problem I am having is that the dsl should have the possibility to make unlimited bracket, but show an error when the programmer don't closes all opened bracket.

example:

```<code>1 AND (2 OR (3 OR 4)
</code>```

one bracket is missing --> should make error.

I don't know how I can realize this in XText. Can anybody help?

thx for helping.

答:
Try this:

```<code>CONDITION_LEVEL
  :  ATOM ((AND | OR) ATOM)*
  ;

ATOM
  :  NUMBER
  |  '(' CONDITION_LEVEL ')'
  ;
</code>```

Note that I have no experience with XText (so I did not test this), but this does work with ANTLR, on which XText is built (or perhaps it only uses ANTLR...).

Aslo, you probably don't want to surround your operator-tokens with spaces, but put them on a hidden-parser channel:

```<code>grammar org.xtext.example.mydsl.MyDsl hidden(SPACE)

...

terminal SPACE : (' '|'\t'|'\r'|'\n')+;

...
</code>```

Otherwise source like this would fail:

```<code>1 AND(2 OR 3)
</code>```

For details, see Hidden Terminal Symbols from the XText user guide.

ContentLicense: CC BY-SA 3.0

Body:
I am developing my own DSL in XText.

I want do something like this:

1 AND (2 OR (3 OR 4))

Here my current .xtext file:

grammar org.xtext.example.mydsl.MyDsl with org.eclipse.xtext.common.Terminals

generate myDsl "http://www.xtext.org/example/mydsl/MyDsl"

Model:
    (greetings+=CONDITION_LEVEL)
;

terminal NUMBER :
    ('1'..'9') ('0'..'9')*
;

AND:
    ' AND '
;

OR:
    ' OR '
;

OPERATOR :
    AND | OR
;

CONDITION_LEVEL:
    ('('* NUMBER (=>')')* OPERATOR)+ NUMBER ')'*
;

The problem I am having is that the dsl should have the possibility to make unlimited bracket, but show an error when the programmer don't closes all opened bracket.

example:

1 AND (2 OR (3 OR 4)

one bracket is missing --> should make error.

I don't know how I can realize this in XText. Can anybody help?

thx for helping.

Body:
Try this:

CONDITION_LEVEL
  :  ATOM ((AND | OR) ATOM)*
  ;

ATOM
  :  NUMBER
  |  '(' CONDITION_LEVEL ')'
  ;

Note that I have no experience with XText (so I did not test this), but this does work with ANTLR, on which XText is built (or perhaps it only uses ANTLR...).

Aslo, you probably don't want to surround your operator-tokens with spaces, but put them on a hidden-parser channel:

grammar org.xtext.example.mydsl.MyDsl hidden(SPACE)

...

terminal SPACE : (' '|'\t'|'\r'|'\n')+;

...

Otherwise source like this would fail:

1 AND(2 OR 3)

For details, see Hidden Terminal Symbols from the XText user guide.


问:
How can I mock Stripe in Go?
I am trying to mock Stripe for some tests.

```<code>//testify mock
type Backend struct {
    mock.Mock
}

func (s Backend) Call(method, path, key string, params stripe.ParamsContainer, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) SetMaxNetworkRetries(maxNetworkRetries int) {
    s.Called(maxNetworkRetries)
}
</code>```

then in test initialise:

```<code>//stripe
backend := new(mock.Backend)
backend.On("CallRaw", testify.Anything, testify.Anything, testify.Anything, testify.Anything, testify.Anything).
    Return(nil)
backend.On("Call",
    testify.
        MatchedBy(func(req stripe.ParamsContainer) bool {
            customerParams, ok := req.(*stripe.CustomerParams)
            if ok {
                return *customerParams.Email == "failure@email.com"
            }
            return false
        })).
    Return(fmt.Errorf("downstream stripe error"))
backend.On("Call",
    testify.
        MatchedBy(func(req stripe.ParamsContainer) bool {
            customerParams, ok := req.(*stripe.CustomerParams)
            if ok {
                return *customerParams.Email == "success@email.com"
            }
            return false
        })).
    Return(nil)
sc := &client.API{}
sc.Init("", &stripe.Backends{
    API:     backend,
    Connect: backend,
    Uploads: backend,
})
</code>```

This works - but I can't work out how I can mock to actually get the Customer? I don't want to mock client.API. The API code: https://github.com/stripe/stripe-go/blob/9c5fd87e31fd4a072b4d92571d67437e329dc9db/customer/client.go#L23

Is anyone else doing this? :)

Thanks

答:
Here the solution for stripe-go v72 (partially inspired by @kozmo answer)

```<code>import (
    "bytes"

    "github.com/stretchr/testify/mock"
    "github.com/stripe/stripe-go/v72"
    "github.com/stripe/stripe-go/v72/form"
)

type stripeBackendMock struct {
    mock.Mock
}

func (s *stripeBackendMock) Call(method, path, key string, params stripe.ParamsContainer, v stripe.LastResponseSetter) error {
    args := s.Called(method, path, key, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) CallStreaming(method, path, key string, params stripe.ParamsContainer, v stripe.StreamingLastResponseSetter) error {
    args := s.Called(method, path, key, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v stripe.LastResponseSetter) error {
    args := s.Called(method, path, key, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v stripe.LastResponseSetter) error {
    args := s.Called(method, path, key, boundary, body, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) SetMaxNetworkRetries(maxNetworkRetries int64) {
    s.Called(maxNetworkRetries)
}
</code>```

Then in your tests

```<code>stripeBackendMock := new(stripeBackendMock)
stripeTestBackends := &stripe.Backends{
    API: stripeBackendMock,
    Connect: stripeBackendMock,
    Uploads: stripeBackendMock,
}

stripe = client.New("sk_test", stripeTestBackends)
// ...

stripeBackendMock.On("Call", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
    stripeCustomer := args.Get(4).(*stripe.Customer)
    *stripeCustomer = stripe.Customer{ /* mock here */ }
}).Return(nil).Once()
// check stripe.Customers.New(...)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can I mock Stripe in Go?

Body:
I am trying to mock Stripe for some tests.

//testify mock
type Backend struct {
    mock.Mock
}

func (s Backend) Call(method, path, key string, params stripe.ParamsContainer, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v interface{}) error {
    args := s.Called(params)
    return args.Error(0)
}

func (s Backend) SetMaxNetworkRetries(maxNetworkRetries int) {
    s.Called(maxNetworkRetries)
}

then in test initialise:

//stripe
backend := new(mock.Backend)
backend.On("CallRaw", testify.Anything, testify.Anything, testify.Anything, testify.Anything, testify.Anything).
    Return(nil)
backend.On("Call",
    testify.
        MatchedBy(func(req stripe.ParamsContainer) bool {
            customerParams, ok := req.(*stripe.CustomerParams)
            if ok {
                return *customerParams.Email == "failure@email.com"
            }
            return false
        })).
    Return(fmt.Errorf("downstream stripe error"))
backend.On("Call",
    testify.
        MatchedBy(func(req stripe.ParamsContainer) bool {
            customerParams, ok := req.(*stripe.CustomerParams)
            if ok {
                return *customerParams.Email == "success@email.com"
            }
            return false
        })).
    Return(nil)
sc := &client.API{}
sc.Init("", &stripe.Backends{
    API:     backend,
    Connect: backend,
    Uploads: backend,
})

This works - but I can't work out how I can mock to actually get the Customer? I don't want to mock client.API. The API code: https://github.com/stripe/stripe-go/blob/9c5fd87e31fd4a072b4d92571d67437e329dc9db/customer/client.go#L23

Is anyone else doing this? :)

Thanks

Body:
Here the solution for stripe-go v72 (partially inspired by @kozmo answer)

import (
    "bytes"

    "github.com/stretchr/testify/mock"
    "github.com/stripe/stripe-go/v72"
    "github.com/stripe/stripe-go/v72/form"
)

type stripeBackendMock struct {
    mock.Mock
}

func (s *stripeBackendMock) Call(method, path, key string, params stripe.ParamsContainer, v stripe.LastResponseSetter) error {
    args := s.Called(method, path, key, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) CallStreaming(method, path, key string, params stripe.ParamsContainer, v stripe.StreamingLastResponseSetter) error {
    args := s.Called(method, path, key, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) CallRaw(method, path, key string, body *form.Values, params *stripe.Params, v stripe.LastResponseSetter) error {
    args := s.Called(method, path, key, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) CallMultipart(method, path, key, boundary string, body *bytes.Buffer, params *stripe.Params, v stripe.LastResponseSetter) error {
    args := s.Called(method, path, key, boundary, body, params, v)
    return args.Error(0)
}

func (s *stripeBackendMock) SetMaxNetworkRetries(maxNetworkRetries int64) {
    s.Called(maxNetworkRetries)
}

Then in your tests

stripeBackendMock := new(stripeBackendMock)
stripeTestBackends := &stripe.Backends{
    API: stripeBackendMock,
    Connect: stripeBackendMock,
    Uploads: stripeBackendMock,
}

stripe = client.New("sk_test", stripeTestBackends)
// ...

stripeBackendMock.On("Call", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) {
    stripeCustomer := args.Get(4).(*stripe.Customer)
    *stripeCustomer = stripe.Customer{ /* mock here */ }
}).Return(nil).Once()
// check stripe.Customers.New(...)


问:
make a deployment redownload an image with jenkins
I wrote a pipeline for an Hello World web app, nothing biggy, it's a simple hello world page.
I made it so if the tests pass, it'll deploy it to a remote kubernetes cluster.

My problem is that if I change the html page and try to redeploy into k8s the page remains the same (the pods aren't rerolled and the image is outdated).

I have the autopullpolicy set to always. I thought of using specific tags within the deployment yaml but I have no idea how to integrate that with my jenkins (as in how do I make jenkins set the BUILD_NUMBER as the tag for the image in the deployment).

Here is my pipeline:

```<code>pipeline {

agent any
environment
{
    user = "NAME"
    repo = "prework"
    imagename = "${user}/${repo}"
    registryCreds = 'dockerhub'
    containername = "${repo}-test"
}

stages
{
    stage ("Build")
    {
        steps {
        // Building artifact
            sh '''
            docker build -t ${imagename} .
            docker run -p 80 --name ${containername} -dt ${imagename}
            '''
            }
    }

    stage ("Test")
    {
        steps {
            sh '''

            IP=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${containername})
            STATUS=$(curl -sL -w "%{http_code} \n" $IP:80 -o /dev/null)

                if [ $STATUS -ne 200 ]; then
                echo "Site is not up, test failed"
                exit 1
                fi
                echo "Site is up, test succeeded"
            '''
        }
    }
    stage ("Store Artifact")
    {
        steps {
            echo "Storing artifact: ${imagename}:${BUILD_NUMBER}"
            script {
                docker.withRegistry('https://registry.hub.docker.com', 'dockerhub') {
                    def customImage = docker.image(imagename)
                customImage.push(BUILD_NUMBER)
                customImage.push("latest")
                }
            }
        }

    }
    stage ("Deploy to Kubernetes")
    {
        steps {

            echo "Deploy to k8s"
            script {
            kubernetesDeploy(configs: "deployment.yaml", kubeconfigId: "kubeconfig") }
            }
    }

}

post {
    always {

            echo "Pipeline has ended, deleting image and containers"
        sh '''
            docker stop ${containername}
            docker rm ${containername} -f
        '''
    }
}
</code>```

}

EDIT:
I used sed to replace the latest tag with the build number every time I'm running the pipeline and it works. I'm wondering if any of you have other ideas because it seems so messy right now.
Thanks.

答:
According to the information from Kubernetes Continuous Deploy Plugin p.6. you can add enableConfigSubstitution: true to kubernetesDeploy() section and use ${BUILD_NUMBER} instead of latest in deployment.yaml:

By checking "Enable Variable Substitution in Config", the variables
(in the form of $VARIABLE or `${VARIABLE}) in the configuration files
will be replaced with the values from corresponding environment
variables before they are fed to the Kubernetes management API. This
allows you to dynamically update the configurations according to each
Jenkins task, for example, using the Jenkins build number as the image
tag to be pulled.

Body:
I wrote a pipeline for an Hello World web app, nothing biggy, it's a simple hello world page.
I made it so if the tests pass, it'll deploy it to a remote kubernetes cluster.

My problem is that if I change the html page and try to redeploy into k8s the page remains the same (the pods aren't rerolled and the image is outdated).

I have the autopullpolicy set to always. I thought of using specific tags within the deployment yaml but I have no idea how to integrate that with my jenkins (as in how do I make jenkins set the BUILD_NUMBER as the tag for the image in the deployment).

Here is my pipeline:

pipeline {

agent any
environment
{
    user = "NAME"
    repo = "prework"
    imagename = "${user}/${repo}"
    registryCreds = 'dockerhub'
    containername = "${repo}-test"
}

stages
{
    stage ("Build")
    {
        steps {
        // Building artifact
            sh '''
            docker build -t ${imagename} .
            docker run -p 80 --name ${containername} -dt ${imagename}
            '''
            }
    }

    stage ("Test")
    {
        steps {
            sh '''

            IP=$(docker inspect --format '{{ .NetworkSettings.IPAddress }}' ${containername})
            STATUS=$(curl -sL -w "%{http_code} \n" $IP:80 -o /dev/null)

                if [ $STATUS -ne 200 ]; then
                echo "Site is not up, test failed"
                exit 1
                fi
                echo "Site is up, test succeeded"
            '''
        }
    }
    stage ("Store Artifact")
    {
        steps {
            echo "Storing artifact: ${imagename}:${BUILD_NUMBER}"
            script {
                docker.withRegistry('https://registry.hub.docker.com', 'dockerhub') {
                    def customImage = docker.image(imagename)
                customImage.push(BUILD_NUMBER)
                customImage.push("latest")
                }
            }
        }

    }
    stage ("Deploy to Kubernetes")
    {
        steps {

            echo "Deploy to k8s"
            script {
            kubernetesDeploy(configs: "deployment.yaml", kubeconfigId: "kubeconfig") }
            }
    }

}

post {
    always {

            echo "Pipeline has ended, deleting image and containers"
        sh '''
            docker stop ${containername}
            docker rm ${containername} -f
        '''
    }
}

}

EDIT:
I used sed to replace the latest tag with the build number every time I'm running the pipeline and it works. I'm wondering if any of you have other ideas because it seems so messy right now.
Thanks.


问:
Django: How to serialize a one to many relationship
I can't seem to figure out how to serialize a one to many relationship in Django, The information doesn't seem to even appear.

My models

```<code>class DataInfo(models.Model):
    component_id = models.CharField(max_length=4)
    component_name = models.CharField(max_length=255)
    data_id = models.IntegerField()
    data_name = models.CharField(max_length=255)

class Data(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='data_owner')
    subject = models.CharField(max_length=255)
    init_date = models.DateField()
    fin_date = models.DateField()
    data_info = models.ForeignKey(DataInfo, related_name="datainfo", on_delete=models.CASCADE)
</code>```

My View

```<code>class DataViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.DataSerializer

    def list(self, request):
        data = models.Data.objects.using(db_to_use).select_related('data_info').all()
        return Response(self.get_serializer(data, many=True).data)
</code>```

My serializers

```<code>class DataInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.DataInfo
        fields = ('id', 'component_id', 'component_name', 'data_id', 'data_name')

class DataSerializer(serializers.ModelSerializer):
    datainfo = DataInfoSerializer(source="datainfo", read_only=True)
    class Meta:
        model = models.Data
        fields = ('id', 'subject', 'init_date', 'fin_date', 'owner_id', 'data_info_id', 'datainfo')
</code>```

I'm essentially just trying to do a join between Data and DataInfo, showing all the fields of Data and DataInfo in one view (not nested). I tried doing a select_related, putting a source attribute, nothing seems to work. The response I get is just all fields of the Data table with no fields of the DataInfo table. Am I missing something with the serialization?

答:
This should work:

```<code>class DataSerializer(serializers.ModelSerializer):
    datainfo = DataInfoSerializer()

    class Meta:
        model = Data
        fields = '__all__'
</code>```

Also, try explicitly mentioning the data_info = models.ForeignKey(DataInfo, to_field=<data-info-id>) in Data model.

Body:
I can't seem to figure out how to serialize a one to many relationship in Django, The information doesn't seem to even appear.

My models

class DataInfo(models.Model):
    component_id = models.CharField(max_length=4)
    component_name = models.CharField(max_length=255)
    data_id = models.IntegerField()
    data_name = models.CharField(max_length=255)

class Data(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='data_owner')
    subject = models.CharField(max_length=255)
    init_date = models.DateField()
    fin_date = models.DateField()
    data_info = models.ForeignKey(DataInfo, related_name="datainfo", on_delete=models.CASCADE)

My View

class DataViewSet(viewsets.ModelViewSet):
    serializer_class = serializers.DataSerializer

    def list(self, request):
        data = models.Data.objects.using(db_to_use).select_related('data_info').all()
        return Response(self.get_serializer(data, many=True).data)

My serializers

class DataInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.DataInfo
        fields = ('id', 'component_id', 'component_name', 'data_id', 'data_name')

class DataSerializer(serializers.ModelSerializer):
    datainfo = DataInfoSerializer(source="datainfo", read_only=True)
    class Meta:
        model = models.Data
        fields = ('id', 'subject', 'init_date', 'fin_date', 'owner_id', 'data_info_id', 'datainfo')

I'm essentially just trying to do a join between Data and DataInfo, showing all the fields of Data and DataInfo in one view (not nested). I tried doing a select_related, putting a source attribute, nothing seems to work. The response I get is just all fields of the Data table with no fields of the DataInfo table. Am I missing something with the serialization?

Body:
This should work:

class DataSerializer(serializers.ModelSerializer):
    datainfo = DataInfoSerializer()

    class Meta:
        model = Data
        fields = '__all__'

Also, try explicitly mentioning the data_info = models.ForeignKey(DataInfo, to_field=<data-info-id>) in Data model.


问:
How do I fix this error, "Too many positional arguments: 0 expected, but 1 found."?
I have this function with firebase but I keep getting the error message stating "Too many positional arguments: 0 expected, but 1 found." with the items in the quotes in the lines with "snapshot.docs[0].data('Quote') as String?"

How can I fix this, any help is appreciated!

```<code>Future getNewsPostDetails(String newsPostId) async {
    QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collection('newsPosts')
        .where('newsPostId', isEqualTo: newsPostId)
        .get();
    newsPostDetails newPostDetails = newsPostDetails(
      newsPostTitle: snapshot.docs[0].data('newsPostTitle') as String?,
      newsPostAuthor: snapshot.docs[0].data('newsPostAuthor') as String?,
      newsPostContent: snapshot.docs[0].data('newsPostContent') as String?,
      date: snapshot.docs[0].data('date') as String?,
    );
    return newPostDetails;
  }
</code>```

Here is the newsPostDetails.dart

```<code>class newsPostDetails {
  final String? newsPostTitle;
  final String? newsPostAuthor;
  final String? newsPostContent;
  final String? date;

  newsPostDetails(
      {this.newsPostTitle,
      this.newsPostAuthor,
      this.newsPostContent,
      this.date});
}
</code>```

答:
The 'data()' function does not expect any arguments. The 'data()' function returns the map back. You can access the information you want from the map.

Future getNewsPostDetails(String newsPostId) async {
    QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collection('newsPosts')
        .where('newsPostId', isEqualTo: newsPostId)
        .get();
    final newPostData = snapshot.docs[0].data()! as Map<String, dynamic>;
    newsPostDetails newPostDetails = newsPostDetails(
      newsPostTitle: newPostData['newsPostTitle'] as String?,
      newsPostAuthor: newPostData['newsPostAuthor'] as String?,
      newsPostContent: newPostData['newsPostContent'] as String?,
      date: newPostData['date'] as String?,
    );
    return newPostDetails;
  }
```

Body:
I have this function with firebase but I keep getting the error message stating "Too many positional arguments: 0 expected, but 1 found." with the items in the quotes in the lines with "snapshot.docs[0].data('Quote') as String?"

How can I fix this, any help is appreciated!

Future getNewsPostDetails(String newsPostId) async {
    QuerySnapshot snapshot = await FirebaseFirestore.instance
        .collection('newsPosts')
        .where('newsPostId', isEqualTo: newsPostId)
        .get();
    newsPostDetails newPostDetails = newsPostDetails(
      newsPostTitle: snapshot.docs[0].data('newsPostTitle') as String?,
      newsPostAuthor: snapshot.docs[0].data('newsPostAuthor') as String?,
      newsPostContent: snapshot.docs[0].data('newsPostContent') as String?,
      date: snapshot.docs[0].data('date') as String?,
    );
    return newPostDetails;
  }

Here is the newsPostDetails.dart

class newsPostDetails {
  final String? newsPostTitle;
  final String? newsPostAuthor;
  final String? newsPostContent;
  final String? date;

  newsPostDetails(
      {this.newsPostTitle,
      this.newsPostAuthor,
      this.newsPostContent,
      this.date});
}


问:
EF Core 6 - System.InvalidOperationException: Unable to save changes because a circular dependency was detected in the data to be saved
for the sake of simplicity, let say I have to projects:

WebAPI and

UnitTest for WebAPI

Both projects were using EF Core 5. WebAPI uses SqlServer and UnitTest uses the Sqlite (inMemory). Both projects work correctly.

I migrated from EF Core 5 to EF Core 6 and now WebAPI works correctly but I can't execute any of my Unit Tests. I get the following error:

System.InvalidOperationException: Unable to save changes because a
circular dependency was detected in the data to be saved:
'Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation
-> Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation
-> Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation
-> Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation'..
at Microsoft.EntityFrameworkCore.Utilities.Multigraph2.ThrowCycle(List1
cycle, Func2 formatCycle, Func2 formatException)    at
Microsoft.EntityFrameworkCore.Utilities.Multigraph2.TopologicalSort(Func4
tryBreakEdge, Func2 formatCycle, Func2 formatException)    at
Microsoft.EntityFrameworkCore.Utilities.Multigraph2.TopologicalSort(Func4
tryBreakEdge)    at
Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.Sort(IEnumerable`1
operations, DiffContext diffContext)    at
Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationsModelDiffer.GetDifferences(IRelationalModel
source, IRelationalModel target)    at
Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.GetCreateTablesCommands(MigrationsSqlGenerationOptions
options)    at
Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.CreateTables()
at
Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated()
at
Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()

The circular reference seems to happen inside Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation and since the WebAPI project works, I assume that this is a problem with the Sqlite provider.

The error seems to happen when the EF Configurations are executed inside the OnModelCreating method of DbContext. At this point, no attempted to save/update and entity has been made. The unit test fails during the EF configuration.

At this point I am clueless about how to proceed. We have around 100 configurations and there is no more information provided in the exception. Since everything was working on EF Core 5, I am assuming it is either a breaking change (specific to Sqllite) or a bug in EF Core 6.

Has anybody run into this issue? o does anybody have any ideas about how to figure out what the cause of the problem is?

Any help is highly appreciated.

答: This has been fixed in version 6.0.2 I can confirm.</p>


问:
ValueError: unichr() arg not in range(0x10000) (narrow Python build)
I am trying to convert the html entity to unichar, the html entity is 󮠖
when i try to do the following:

```<code>unichr(int(976918))
</code>```

I got error that:

```<code>ValueError: unichr() arg not in range(0x10000) (narrow Python build)
</code>```

seems like it is out of range conversion for unichar.

答:
You can decode a string that has a Unicode escape (\U followed by 8 hex digits, zero-padded) using the "unicode-escape" encoding:

```<code>>>> s = "\\U%08x" % 976918
>>> s
'\\U000ee816'

>>> c = s.decode('unicode-escape')
>>> c
u'\U000ee816'
</code>```

On a narrow build it's stored as a UTF-16 surrogate pair:

```<code>>>> list(c)
[u'\udb7a', u'\udc16']
</code>```

This surrogate pair is processed correctly as a code unit during encoding:

```<code>>>> c.encode('utf-8')
'\xf3\xae\xa0\x96'

>>> '\xf3\xae\xa0\x96'.decode('utf-8')
u'\U000ee816'
</code>```

Body:
I am trying to convert the html entity to unichar, the html entity is 󮠖
when i try to do the following:

unichr(int(976918))

I got error that:

ValueError: unichr() arg not in range(0x10000) (narrow Python build)

seems like it is out of range conversion for unichar.

Body:
You can decode a string that has a Unicode escape (\U followed by 8 hex digits, zero-padded) using the "unicode-escape" encoding:

>>> s = "\\U%08x" % 976918
>>> s
'\\U000ee816'

>>> c = s.decode('unicode-escape')
>>> c
u'\U000ee816'

On a narrow build it's stored as a UTF-16 surrogate pair:

>>> list(c)
[u'\udb7a', u'\udc16']

This surrogate pair is processed correctly as a code unit during encoding:

>>> c.encode('utf-8')
'\xf3\xae\xa0\x96'

>>> '\xf3\xae\xa0\x96'.decode('utf-8')
u'\U000ee816'


问:
How to run WSL programs within AutoIt?
I'm trying to run a linux console application using AutoIt.
So far I was successful in generating a batch file with the following command:

```<code>wsl /home/ggeorgiev/DD/myprogram --json_file /mnt/c/Users/ggeorgiev/my_input.json
</code>```

This batch runs successfully from cmd, powershell and also when I just double click on it in the explorer. So, I'm thinking that part is okay.

In AutoIt, I'm trying to run the same batch file ("JBDD_start.bat") using the following function:

```<code>Func RunJBDD()

    Local $iPID = Run("cmd.exe " &  "JBDD_start.bat", @WorkingDir, @SW_HIDE, BitOR($STDERR_CHILD, $STDOUT_CHILD,$RUN_CREATE_NEW_CONSOLE ))
    Local $sOutput = ""
    While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then ; Exit the loop if the process closes or StdoutRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stdout Read:", $sOutput)
    WEnd

    $sOutput = ''
    While 1
        $sOutput &= StderrRead($iPID)
        If @error Then ; Exit the loop if the process closes or StderrRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stderr Read:", $sOutput)
    WEnd
EndFunc
</code>```

It doesn't show anything in the StdErr nor in StdOut message boxes.
Any suggestions on what may have gone wrong or how to find what happens "behind the scenes" are highly appreciated.

答:
I'm not familiar with AutoIt, but I'm going to take an educated guess here.  If I'm wrong, at least it might help someone else.

I notice that AutoIt comes with both 32-bit and 64-bit executables.  Make sure you are either:

Using the 64-bit version to execute your batch file

Or, if you really do need to run the 32-bit version of AutoIt, call C:\Windows\Sysnative\wsl.exe

Title: How to run WSL programs within AutoIt?

Body:
I'm trying to run a linux console application using AutoIt.
So far I was successful in generating a batch file with the following command:

wsl /home/ggeorgiev/DD/myprogram --json_file /mnt/c/Users/ggeorgiev/my_input.json

This batch runs successfully from cmd, powershell and also when I just double click on it in the explorer. So, I'm thinking that part is okay.

In AutoIt, I'm trying to run the same batch file ("JBDD_start.bat") using the following function:

Func RunJBDD()

    Local $iPID = Run("cmd.exe " &  "JBDD_start.bat", @WorkingDir, @SW_HIDE, BitOR($STDERR_CHILD, $STDOUT_CHILD,$RUN_CREATE_NEW_CONSOLE ))
    Local $sOutput = ""
    While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then ; Exit the loop if the process closes or StdoutRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stdout Read:", $sOutput)
    WEnd

    $sOutput = ''
    While 1
        $sOutput &= StderrRead($iPID)
        If @error Then ; Exit the loop if the process closes or StderrRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stderr Read:", $sOutput)
    WEnd
EndFunc

It doesn't show anything in the StdErr nor in StdOut message boxes.
Any suggestions on what may have gone wrong or how to find what happens "behind the scenes" are highly appreciated.


问:
Problem with returning object form a class extending AsyncTask
I'm having a problem with getter function returning object from a class HttpRequestCurrentWeather extending AsyncTask. In this class I receive data from API, and want to set some TextViews in CurrentWeatherFragment depending on what I received. The problem is I can't return the whole object of DataModel to the Fragment and set the components there nor set TextViews is onPostExecute() method, because I'm getting a NullPointerException ( java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference). What should I do to set those TextViews?</p>

```<code>public class CurrentWeatherFragment extends Fragment {
    DataModel dataModel = new DataModel();

    TextView tv_city;
    TextView tv_temperature;
    TextView tv_pressure;

    public void setComponents() {
        this.tv_city = getView().findViewById(R.id.tv_current_city_name);
        tv_city.setText(dataModel.getName());

        this.tv_temperature = getView().findViewById(R.id.tv_current_temperature);
        tv_temperature.setText(dataModel.getTemp());

        this.tv_pressure = getView().findViewById(R.id.tv_current_pressure);
        tv_pressure.setText(dataModel.getPressure());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View RootView = inflater.inflate(R.layout.fragment_current_weather_layout, container, false);

        HttpRequestCurrentWeather httpRequestCurrentWeather1 = new HttpRequestCurrentWeather();
        httpRequestCurrentWeather1.execute("", "", "");

        // here I receive null object, but why?
        dataModel = httpRequestCurrentWeather1.getDataModel();

        // set the texts in components:
        setComponents();

        return RootView;
    }
}
</code>```

```<code>public class HttpRequestCurrentWeather extends AsyncTask<String, Void, DataModel> {
        DataModel dataModel;

        public HttpRequestCurrentWeather() {
            this.dataModel = null;
        }

        @Override
        protected DataModel doInBackground(String... params) {
            ApiCurrentWeather apiCurrentWeather1 = new ApiCurrentWeather("London", "uk");

            try {
                // catch the model with recived data from API:
                dataModel = apiCurrentWeather1.getWeather();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return dataModel;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(DataModel dataModel) {
        super.onPostExecute(dataModel);

        CurrentWeatherFragment fragment = new CurrentWeatherFragment();

        TextView tv_temperature = (TextView)fragment.getView().findViewById(R.id.tv_current_temperature);
        tv_temperature.setText(dataModel.getTemp());

    }

    // this function returns NULL object ????
    public DataModel getDataModel(){
        return this.dataModel;
    }
}
</code>```

答: To be honest, this is not how the appropriate answer should look like, but what I was trying to achieve using AsyncTask seemed far more easier using Retrofit, so I finally gave up this idea and decided to use Retrofit instead. If you have similar problem, forget about AsyncTask - Retrofit is more suitable for this!

Body:
I'm having a problem with getter function returning object from a class HttpRequestCurrentWeather extending AsyncTask. In this class I receive data from API, and want to set some TextViews in CurrentWeatherFragment depending on what I received. The problem is I can't return the whole object of DataModel to the Fragment and set the components there nor set TextViews is onPostExecute() method, because I'm getting a NullPointerException ( java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference). What should I do to set those TextViews?

public class CurrentWeatherFragment extends Fragment {
    DataModel dataModel = new DataModel();

    TextView tv_city;
    TextView tv_temperature;
    TextView tv_pressure;

    public void setComponents() {
        this.tv_city = getView().findViewById(R.id.tv_current_city_name);
        tv_city.setText(dataModel.getName());

        this.tv_temperature = getView().findViewById(R.id.tv_current_temperature);
        tv_temperature.setText(dataModel.getTemp());

        this.tv_pressure = getView().findViewById(R.id.tv_current_pressure);
        tv_pressure.setText(dataModel.getPressure());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View RootView = inflater.inflate(R.layout.fragment_current_weather_layout, container, false);

        HttpRequestCurrentWeather httpRequestCurrentWeather1 = new HttpRequestCurrentWeather();
        httpRequestCurrentWeather1.execute("", "", "");

        // here I receive null object, but why?
        dataModel = httpRequestCurrentWeather1.getDataModel();

        // set the texts in components:
        setComponents();

        return RootView;
    }
}

public class HttpRequestCurrentWeather extends AsyncTask<String, Void, DataModel> {
        DataModel dataModel;

        public HttpRequestCurrentWeather() {
            this.dataModel = null;
        }

        @Override
        protected DataModel doInBackground(String... params) {
            ApiCurrentWeather apiCurrentWeather1 = new ApiCurrentWeather("London", "uk");

            try {
                // catch the model with recived data from API:
                dataModel = apiCurrentWeather1.getWeather();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return dataModel;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(DataModel dataModel) {
        super.onPostExecute(dataModel);

        CurrentWeatherFragment fragment = new CurrentWeatherFragment();

        TextView tv_temperature = (TextView)fragment.getView().findViewById(R.id.tv_current_temperature);
        tv_temperature.setText(dataModel.getTemp());

    }

    // this function returns NULL object ????
    public DataModel getDataModel(){
        return this.dataModel;
    }
}


问:
Screen zombie process after Ctrl+d
When using screen on a macOS (Big Sur) I have issues where Ctrl+d in a screen will logout of the shell and then my screen will disappear. Processes running on this screen instance are still running, but I can no longer resume the screen and have to go about manually tracking down and killing processes which have locked certain ports

答:
In order to disconnect from screen you should use Ctrl + a,d, not Ctrl + d.

But if you want to prevent Ctrl + d from exiting the bash you can disable this behavior by eg calling:

```<code>set -o ignoreeof
</code>```

And if you have a dead session in screen and you want to remove it use:

```<code>screen -wipe
</code>```

Title: Screen zombie process after Ctrl+d

Body:
In order to disconnect from screen you should use Ctrl + a,d, not Ctrl + d.

But if you want to prevent Ctrl + d from exiting the bash you can disable this behavior by eg calling:

set -o ignoreeof

And if you have a dead session in screen and you want to remove it use:

screen -wipe


问:
Rearrange Strings Alphabetically Across Rows in Pandas
I'm trying to rearrange strings alphabetically across any column name which is an integer.

Example Code / Minimum Reproducible Sample:

```<code>import pandas as pd

data = {

  0: ["amazon", "ebay", "paypal"],
  2: ["paypal", "amazon", "ebay"],
  3: ["ebay", "paypal", "amazon"]
}

# Create DataFrame
df = pd.DataFrame(data)

# print dataframe.
print(df)
</code>```

Current Output:

```<code>        0       1       2
0  amazon  paypal    ebay
1    ebay  amazon  paypal
2  paypal    ebay  amazon
</code>```

Desired Output:

```<code>        0       1       2
0  amazon    ebay    paypal
1  amazon    ebay    paypal
2  amazon    ebay    paypal
</code>```

The number of int columns isn't fixed, and is dependant on the input data. I'm pretty stumped but I've tried this code:

```<code>df[[0, 1]] = df[[1,0]].where(
    df[1].isin(df[0].tolist()), df[[0,1]].values)
</code>```

(The general idea is to check if a value is found in the adjacent cell, and swap the value - but I don't know how to scale it for a dynamic number of columns - and not sure it's the best solution).

答:
You can use the builtin sorted function for each row to sort the cell values:

```<code>df = df.apply(lambda x: pd.Series(sorted(x)), axis=1)
</code>```

Output:

```<code>>>> df
        0     1       2
0  amazon  ebay  paypal
1  amazon  ebay  paypal
2  amazon  ebay  paypal
</code>```

Body:
I'm trying to rearrange strings alphabetically across any column name which is an integer.

Example Code / Minimum Reproducible Sample:

import pandas as pd

data = {

  0: ["amazon", "ebay", "paypal"],
  2: ["paypal", "amazon", "ebay"],
  3: ["ebay", "paypal", "amazon"]
}

# Create DataFrame
df = pd.DataFrame(data)

# print dataframe.
print(df)

Current Output:

        0       1       2
0  amazon  paypal    ebay
1    ebay  amazon  paypal
2  paypal    ebay  amazon

Desired Output:

        0       1       2
0  amazon    ebay    paypal
1  amazon    ebay    paypal
2  amazon    ebay    paypal

The number of int columns isn't fixed, and is dependant on the input data. I'm pretty stumped but I've tried this code:

df[[0, 1]] = df[[1,0]].where(
    df[1].isin(df[0].tolist()), df[[0,1]].values)

(The general idea is to check if a value is found in the adjacent cell, and swap the value - but I don't know how to scale it for a dynamic number of columns - and not sure it's the best solution).

Body:
You can use the builtin sorted function for each row to sort the cell values:

df = df.apply(lambda x: pd.Series(sorted(x)), axis=1)

Output:

>>> df
        0     1       2
0  amazon  ebay  paypal
1  amazon  ebay  paypal
2  amazon  ebay  paypal


问:
How to insert wait step in Splunk Synthetics (formerly Rigor) API test
Trying to program in a wait step within Splunk Synthetics (Rigor) API test.

Use case: Submitting a test file to an API endpoint and takes 10 seconds to process file.  Successfully being able to submit this file is the test criteria to pass/fail on.  Response body from endpoint includes status but need to program in a wait step or a while loop.  Splunk Synthetics does not have a wait step natively in API mode.  Anyone ever done this via a saved JS file or script?

If status="processing" then loop
OR
If status ="in progress" wait 15 sec and check again
THEN
If status= "complete" then pass; if status= "failed" then fail.

答: I got the answer from Splunk Support, right now you cannot.  There is a work around to call out to an external site able to pause for a set time to occupy the bots time then make a call back to get status.  I added a request to the IdeaBoard for future implementation.  Just putting this answer here for anyone else that looks for it.</p>


问:
Delete whole 3d array if contains any nan
I have a set of images represented by a 3d ndarray. Abstractly what I want to do is, delete an entire image if any of its pixel values is a nan.
Imagine we got the following ndarray:

```<code>a = np.arange(18).reshape(3, 2, 3)
a = 1.0 * a
a[0][0][1] = np.nan
a[1][0][0] = np.nan
a
[[[ 0. nan  2.]
  [ 3.  4.  5.]]

 [[nan  7.  8.]
  [ 9. 10. 11.]]

 [[12. 13. 14.]
  [15. 16. 17.]]]
</code>```

Now what I want to get is a function that given that ndarray returns True, True, False. In order to finally use np.delete.

I have try the following, which works:

```<code>np.delete(a, [np.isnan(image.flatten()).any() for image in a], axis=0)
array([[[12., 13., 14.],
        [15., 16., 17.]]]))
</code>```

However, I find it hard to believe that there isn't a function in numpy that is more efficient, and since I have a lot of images I would like to optimise it as much as possible.

答:
As already answered by Michael Szczesny, more Pythonic way would be:

```<code>filtered_images=a[~np.isnan(a).any(axis=(2,1))]
</code>```

If that piece of code is hard to understand, then consider extracting each image with a for loop as follows:

```<code>filtered_images=list()
for value in a:
  if(np.isnan(value).any()!=True):
    filtered_images.append(value)
</code>```

Both approaches should give you similar output!

Body:
I have a set of images represented by a 3d ndarray. Abstractly what I want to do is, delete an entire image if any of its pixel values is a nan.
Imagine we got the following ndarray:

a = np.arange(18).reshape(3, 2, 3)
a = 1.0 * a
a[0][0][1] = np.nan
a[1][0][0] = np.nan
a
[[[ 0. nan  2.]
  [ 3.  4.  5.]]

 [[nan  7.  8.]
  [ 9. 10. 11.]]

 [[12. 13. 14.]
  [15. 16. 17.]]]

Now what I want to get is a function that given that ndarray returns True, True, False. In order to finally use np.delete.

I have try the following, which works:

np.delete(a, [np.isnan(image.flatten()).any() for image in a], axis=0)
array([[[12., 13., 14.],
        [15., 16., 17.]]]))

However, I find it hard to believe that there isn't a function in numpy that is more efficient, and since I have a lot of images I would like to optimise it as much as possible.

Body:
As already answered by Michael Szczesny, more Pythonic way would be:

filtered_images=a[~np.isnan(a).any(axis=(2,1))]

If that piece of code is hard to understand, then consider extracting each image with a for loop as follows:

filtered_images=list()
for value in a:
  if(np.isnan(value).any()!=True):
    filtered_images.append(value)

Both approaches should give you similar output!


问:
Terminology for a deterministic function with no side-effects?
I need the proper terminology for a specific type of function.

Suppose you write a function in your SQL database, whose inputs and outputs are contained within the scope of a database transaction.

That is, if you call this function in the scope of a database transaction, all the data used by the function is available within the same scope.  It can query a database table, but it can't read a file from the filesystem, or ping a web site, etc.  If you call the function twice within a single transaction with REPEATABLE READ isolation, you should get the same result, even if other clients are making changes in the database.

Likewise, the function has no side-effects, except within the same transaction scope.  Changes in state outside the scope of the database transaction are not allowed.  The function shouldn't send emails, nor write to the filesystem, nor store a value in memcached, etc.  If the function changes data within the database, that's okay because if the calling transaction is rolled back, then the effects of the function are too.

The arguments of the function are okay, since they're basically used as constants.

What would be the proper term for a function of this type?  "Deterministic" doesn't really seem to be specific enough.  How would you describe this class of function?

Thanks for your answers, but none of them is exactly what I had in mind.  Idempotent gets closest, so I marked that as the accepted answer.  But each of you got an upvote from me regardless.

Pure functions have no side-effects, and their result is based solely on their arguments.  The result given the same arguments is always identical.  This doesn't work because the database functions I have in mind can be based on the state of data, and the function can also affect the state of data.

Idempotent functions can return a result based on the state of data, and given the same state of data, the result is always identical.  But this doesn't work for what I have in mind exactly; the effects of an idempotent functions must result in an unchanging result no matter how many times the function is called.  But there's no distinction between changes made within transaction isolation and changes made external to that scope.

答: You can also call these pure functions.</p>

OwnerDisplayName: Bill Karwin

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: chaos

Body: You can also call these pure functions.


问:
Unexpected directories with Environment.GetFolderPath(Environment.SpecialFolder.Personal)
I am using following to get path to 'My Documents' folder in Windows 7 and iterate through its directories:

```<code>Dim diri As New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal))
For Each diri In diri.GetDirectories
 MessageBox.Show(diri.Name)
Next
</code>```

One of the message boxes I get is for a 'My Music' folder. I do not have that folder in the 'My Documents' folder.

Is this the expected behavior?

答:
used the below to get non hidden directories</p>

```<code>Dim diri As New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal))
For Each diri In diri.GetDirectories
 If(dir.Attributes = FileAttributes.Directory) Then
   MessageBox.Show(diri.Name)
 End If
Next
</code>```

Body:
I am using following to get path to 'My Documents' folder in Windows 7 and iterate through its directories:

Dim diri As New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal))
For Each diri In diri.GetDirectories
 MessageBox.Show(diri.Name)
Next

One of the message boxes I get is for a 'My Music' folder. I do not have that folder in the 'My Documents' folder.

Is this the expected behavior?

Body:
used the below to get non hidden directories

Dim diri As New DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal))
For Each diri In diri.GetDirectories
 If(dir.Attributes = FileAttributes.Directory) Then
   MessageBox.Show(diri.Name)
 End If
Next


问:
AWS - Give readonly permissions for all services
Is there a way in AWS to give readonly permissions to all services via a central policy? Currently, am forced to do this per service, like for IAM below -

```<code>{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": [
            "iam:Get*",
            "iam:List*",
            "iam:Generate*"
        ],
        "Resource": "*"
    }
}
</code>```

Having to do this for each and every resource is error prone and tedious. How can we define a policy to give read-only for all services.

Thanks

答:
You can use the AWS managed policy named ReadOnlyAccess:

the ReadOnlyAccess AWS managed policy provides read-only access to all AWS services and resources. When a service launches a new feature, AWS adds read-only permissions for new operations and resources.

Body:
Is there a way in AWS to give readonly permissions to all services via a central policy? Currently, am forced to do this per service, like for IAM below -

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": [
            "iam:Get*",
            "iam:List*",
            "iam:Generate*"
        ],
        "Resource": "*"
    }
}

Having to do this for each and every resource is error prone and tedious. How can we define a policy to give read-only for all services.

Thanks


问:
Error: Child Compilation failed - Module.createRequire is not a function
I have worked on a React/Typescript application on my Mac Machine, and zipped up the application (including node_modules) and emailed it to a colleague via Google Drive (Link).  However, I was informed that this error (pictured above) occurred when attempting to run the application with 'npm install' and 'npm run start'.  I have tried testing the application by sending the zipped app to my Windows machine and it seems to work fine.

My colleague is on a Linux/Ubuntu machine.  I'm not very familiar with Linux, and not quite sure how to resolve this, and am open to suggestions.

答: Probably your colleague is running outdated version of node and npm. I guess that the project was created with create-react-app. If it's true, your colleague will need to have Node >= 14.0.0 and npm >= 5.6 on the machine.</p>


问:
Is there a way to link a single M Code document to multiple workbooks?
I have several workbooks linked to the same set of CSV files. I use the same Power Query transform steps for each CSV file in each workbook. Instead of copying M code from the advanced editor of one workbook and pasting it into the advanced editor of another, is there somewhere I can store a "master" M code document? I would like to be able to link all workbooks to a single text file containing M code so that when I make changes in this master document the Power Query transformations are made in each linked workbook - similar to style sheets in css.</p>

答:
Another approach to this is to use Dataflows. These are essentially queries stored in the Power BI Service that you can connect your Power BI files to.

Recommended reading:

https://learn.microsoft.com/en-us/power-bi/transform-model/dataflows/dataflows-introduction-self-service

https://radacad.com/what-are-the-use-cases-of-dataflow-for-you-in-power-bi


问:
JavaFX Media constructor throws InvocationTargetException
I want to use javafx media library for audiofiles, but making a new Media instance throws InvocationTargetException written in minecraft enchantment table language.

I tried to instantiate it in multiple ways: by passing path.toString(), by passing a file as a string or just hardcoded string. All of them throw the same exception.

```<code>new MediaPlayer(new Media(new File(filePath).toURI().toString()));
</code>```

Where filePath is C:\Users\User\Desktop\folder\java\AudioCutter\target\classes\audioFile.wav

A file or AudioInputStream with the same path works.

JavaFX is imported as a library in Intellij Idea project structure, and it works.

I use java 16.

答:
Troubleshooting media exceptions

To get more debugging information, apply the code template for error handling provided in:

the javafx.media package documentation.

Creating a new test project

However, rather than trying to get your current setup to work, I advise creating a new project just to verify the execution of this functionality in your environment.

As you are using Idea, create a new project as outlined in the answer to:

can not resolve symbol "javafx.scene.web"

except:

add the pom.xml dependency for javafx-media AND

adjust the module-info to require javafx.media

Load your media file in the start method of the new project.

About the error message in your question

The extra zeros in the error message are probably a result of a character encoding issue, e.g. processing utf-16 characters as utf-8.

I guess the “Minecraft enchantment table language” was a joke.

I don’t think there is an easy way to pin down the cause of that in this forum. The issue is likely an environmental, configuration or setup issue on your end, or an attempt to use an unsupported or invalid media file format.

Instead, take a different approach using a new project configuration and media files that have been known to work for others and make use of the full debugging source template mentioned earlier.

Body:
I want to use javafx media library for audiofiles, but making a new Media instance throws InvocationTargetException written in minecraft enchantment table language.

I tried to instantiate it in multiple ways: by passing path.toString(), by passing a file as a string or just hardcoded string. All of them throw the same exception.

new MediaPlayer(new Media(new File(filePath).toURI().toString()));

Where filePath is C:\Users\User\Desktop\folder\java\AudioCutter\target\classes\audioFile.wav

A file or AudioInputStream with the same path works.

JavaFX is imported as a library in Intellij Idea project structure, and it works.

I use java 16.


问:
Fit a straight line ignoring data points having ceiling effect
I have a data like below and I would like to fit a straight line (like a Black line) ignoring the points following ceiling effect. Then I would like to predict Y values of these points using the slope and find the expected difference due to ceiling effect.

I tried using following code from other stackoverflow question but it does not do a good job at ignoring points with ceiling effect.

```<code>from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit
</code>```

Please feel free to provide any ideas or suggestions. Thank you.

答:
Thank you everyone for suggestions. If I modify my function like below it fits the data well.

```<code>from scipy.optimize import curve_fit

def f(x, a, b, c):
    return np.minimum(a*(x-c) + b, a*c)

popt, pcov = curve_fit(f, x, y) # your data x, y to fit
</code>```

Body:
I have a data like below and I would like to fit a straight line (like a Black line) ignoring the points following ceiling effect. Then I would like to predict Y values of these points using the slope and find the expected difference due to ceiling effect.

I tried using following code from other stackoverflow question but it does not do a good job at ignoring points with ceiling effect.

from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit

Please feel free to provide any ideas or suggestions. Thank you.

Body:
Thank you everyone for suggestions. If I modify my function like below it fits the data well.

from scipy.optimize import curve_fit

def f(x, a, b, c):
    return np.minimum(a*(x-c) + b, a*c)

popt, pcov = curve_fit(f, x, y) # your data x, y to fit


问:
SQL Query Across Partitioned Database (by Day)
So in the past 3 months, we have gone from a Google Sheets with 5 tabs, up to a connected BigQuery DB referencing the Google Sheets with 5 tables and writing queries.  Today, we just upgraded again to a full daily partitioned database.

I am struggling to figure out how to write my queries across multiple days of data.

When I go to start the query it defaults to today.

```<code>SELECT order_number
FROM `project-123456.client_name.orders`
WHERE DATE(submitted_date) = "2022-02-10"
LIMIT 1000
</code>```

I am trying to figure out the syntax for the month of January for example (and I know this isn't right)

```<code>WHERE DATE(submitted_date) = Jan 1 - Jan 31.
</code>```

Any suggestions would be great, I am learning SQL at an alarming pace but in this case, I think I just don't know the right question to ask.

答:
Ok I figured it out.</p>
```<code>WHERE DATE(submitted_date) >= "2022-01-01" AND DATE(submitted_date) <= "2022-01-31"
</code>```

Body:
So in the past 3 months, we have gone from a Google Sheets with 5 tabs, up to a connected BigQuery DB referencing the Google Sheets with 5 tables and writing queries.  Today, we just upgraded again to a full daily partitioned database.

I am struggling to figure out how to write my queries across multiple days of data.

When I go to start the query it defaults to today.

SELECT order_number
FROM `project-123456.client_name.orders`
WHERE DATE(submitted_date) = "2022-02-10"
LIMIT 1000

I am trying to figure out the syntax for the month of January for example (and I know this isn't right)

WHERE DATE(submitted_date) = Jan 1 - Jan 31.

Any suggestions would be great, I am learning SQL at an alarming pace but in this case, I think I just don't know the right question to ask.

Body:
Ok I figured it out.

WHERE DATE(submitted_date) >= "2022-01-01" AND DATE(submitted_date) <= "2022-01-31"


问:
Authentication Handler not blocking requests
I have added authentication to my API with the possibility to authenticate with two different authentication schemes.
Based on the format of the Auth header I forward the authentication request to the appropriate Authentication handler using a ForwardDefaultSelector.

```<code> services.AddAuthentication(opt =>
                    {
                        opt.DefaultScheme = "ForwardScheme";
                        opt.DefaultChallengeScheme = "ForwardScheme";
                    })
                    .AddPolicyScheme("ForwardScheme", "ForwardScheme", options =>
                        options.ForwardDefaultSelector = context =>
                            context.Request.IsSchemeA()
                                ? "SchemeA"
                                : "SchemeB")
                    .AddSchemeA()
                    .AddSchemeB();
</code>```

Adding Schemes:

```<code>public static AuthenticationBuilder AddSchemeA(this AuthenticationBuilder builder)
        {
            builder.AddScheme<AuthenticationSchemeOptions, SchemeAHandler>(
                "SchemeA", null);
            return builder;
        }
</code>```

The forwarding seems to be working fine, I can see the request coming to the right auth handler based on the header value.

The problem is even when the auth fails, the API call is not blocked and I still get a 200 response back.

In the AuthHandler I am just returning this:

```<code> return AuthenticateResult.Fail("Authentication Failed");
</code>```

Any idea what I am missing here?
Thanks.

答:
If you register an authentication scheme for your application and you add the authentication middleware to the ASP.NET core request pipeline, you are basically asking the ASP.NET core framework of trying to authenticate any incoming request, by using the specified authentication scheme. This won't change, by itself, the response status code from 200 to 401.

In order for you to get a 401 response when an anonymous request gets to your server, you need to raise a so called authetication challenge to the incoming request.

The simplest way to do that is basically requiring the request principal to be authenticated in order to execute a certain action method. To do that you simply need to decorate the action method by using the [Authorize] attribute. This way you are setting an execution policy to your action method, which allows the method execution only if the request principal is authenticated.

Body:
I have added authentication to my API with the possibility to authenticate with two different authentication schemes.
Based on the format of the Auth header I forward the authentication request to the appropriate Authentication handler using a ForwardDefaultSelector.

 services.AddAuthentication(opt =>
                    {
                        opt.DefaultScheme = "ForwardScheme";
                        opt.DefaultChallengeScheme = "ForwardScheme";
                    })
                    .AddPolicyScheme("ForwardScheme", "ForwardScheme", options =>
                        options.ForwardDefaultSelector = context =>
                            context.Request.IsSchemeA()
                                ? "SchemeA"
                                : "SchemeB")
                    .AddSchemeA()
                    .AddSchemeB();

Adding Schemes:

public static AuthenticationBuilder AddSchemeA(this AuthenticationBuilder builder)
        {
            builder.AddScheme<AuthenticationSchemeOptions, SchemeAHandler>(
                "SchemeA", null);
            return builder;
        }

The forwarding seems to be working fine, I can see the request coming to the right auth handler based on the header value.

The problem is even when the auth fails, the API call is not blocked and I still get a 200 response back.

In the AuthHandler I am just returning this:

 return AuthenticateResult.Fail("Authentication Failed");

Any idea what I am missing here?
Thanks.


问:
Check if array column contains any value from a query array
I have a table with the column names VARCHAR(30) ARRAY NOT NULL and I want to query using a list of names, and return rows where the names column has values which are also in my query list.

names for a certain row will look like: {margret,susan,karen,daren}

Right now I can select using contains and one value

```<code>SELECT * FROM test_table WHERE names @> '{"john"}';

^Returns the rows where names array contains john. (As intended).
</code>```

Everything I try querying using multiple values (ex: `john', 'doe', 'jane') results in errors... here is what I tried and the corresponding errors:

```<code>SELECT * FROM test_table WHERE names @> ANY('{"john", "jane"}');

^ERROR:  could not find array type for data type character varying[]
</code>```
```<code>SELECT * FROM test_table WHERE names @> ANY('{"john", "jane"}'::varchar(40));

^ERROR:  op ANY/ALL (array) requires array on right side
</code>```

答:
Will this work?

```<code>create table testarr(names varchar(10)[] );
insert into testarr values(array['margaret','susan','karen','daren']);
select * from testarr where names && '{"margaret","john"}';
select * from testarr where names && '{"mary","john"}';
</code>```

Result:

```<code>postgres=# create table testarr(names varchar(10)[] );
CREATE TABLE
postgres=# insert into testarr values(array['margaret','susan','karen','daren']);
INSERT 0 1
postgres=# select * from testarr where names && '{"margaret","john"}';
            names
------------------------------
 {margaret,susan,karen,daren}
(1 row)

postgres=# select * from testarr where names && '{"mary","john"}';
 names
-------
(0 rows)

</code>```

Body:
I have a table with the column names VARCHAR(30) ARRAY NOT NULL and I want to query using a list of names, and return rows where the names column has values which are also in my query list.

names for a certain row will look like: {margret,susan,karen,daren}

Right now I can select using contains and one value

SELECT * FROM test_table WHERE names @> '{"john"}';

^Returns the rows where names array contains john. (As intended).

Everything I try querying using multiple values (ex: `john', 'doe', 'jane') results in errors... here is what I tried and the corresponding errors:

SELECT * FROM test_table WHERE names @> ANY('{"john", "jane"}');

^ERROR:  could not find array type for data type character varying[]

SELECT * FROM test_table WHERE names @> ANY('{"john", "jane"}'::varchar(40));

^ERROR:  op ANY/ALL (array) requires array on right side

Body:
Will this work?

create table testarr(names varchar(10)[] );
insert into testarr values(array['margaret','susan','karen','daren']);
select * from testarr where names && '{"margaret","john"}';
select * from testarr where names && '{"mary","john"}';

Result:

postgres=# create table testarr(names varchar(10)[] );
CREATE TABLE
postgres=# insert into testarr values(array['margaret','susan','karen','daren']);
INSERT 0 1
postgres=# select * from testarr where names && '{"margaret","john"}';
            names
------------------------------
 {margaret,susan,karen,daren}
(1 row)

postgres=# select * from testarr where names && '{"mary","john"}';
 names
-------
(0 rows)


问:
Angular *ngIf Directive Does Not Trigger Change Detection When Bound to a Function
I have a button that I would like to show only if something is dirty and requires a save.  I have the following within my HTML

```<code><mat-action-row>
    <button mat-raised-button color="primary" *ngIf="IsDirty(segmentGroup)"
         (click)="Save(segmentGroup)">Save</button>
</mat-action-row>
</code>```

Here is the IsDirty Method in the TS

```<code>IsDirty(segmentGroup: SegmentGroup) {
    // Segment Group Dirty
    if (segmentGroup.isDirty)
      return true;

    segmentGroup.segmentDefinitions.forEach(segmentDefinition => {
      if (segmentDefinition.isDirty || segmentDefinition.startTimeLineDefinition.isDirty || segmentDefinition.endTimeLineDefinition.isDirty)
        return true;
    });

    return false;
  }
</code>```

I need to check 3 levels of the object for an is dirty field, ie itself, a child object that is within an array, and a child object of the child within the array.

The issue i have is, the *ngIf method is called when the button is rendered and only when the button is rendered.  Its not bound to a property therefore change detection doesnt trigger anything.  So if I update IsDirty on any of the 3 levels the button never shows.

Is there a way to force the re-render or execution of the ngIf when either a property is changed or on a (change) event on the input?

答:
I believe you answered your own question, using a function for the *ngIf directive will only be evaluated when the element is connected to the DOM and subsequent change detection cycles triggered by other means.

You could programmatically force change detection per the comment above to force the function call however, I believe the more appropriate implementation is as you pointed out, to bind the directive to a local class variable.

Calling functions directly from template markup is frowned upon for
performance reasons

```<code>isDirty = false

<button *ngIf="isDirty">

isDirty = true
</code>```

The above will trigger change detection because false is no longer equal to true, hence the term "change detection".

```<code>*ngIf="isDirty()"
</code>```

This will never trigger change detection without some other means because function is always equal to function and it never changes... thus no change to trigger "change detection"

Set a boolean value to a local variable and bind that to the *ngIf directive, then find some other means to trigger your isDirty function to set that boolean value... on form change or input change is the typical implementation to calling a function like this.

Body:
I have a button that I would like to show only if something is dirty and requires a save.  I have the following within my HTML

<mat-action-row>
    <button mat-raised-button color="primary" *ngIf="IsDirty(segmentGroup)"
         (click)="Save(segmentGroup)">Save</button>
</mat-action-row>

Here is the IsDirty Method in the TS

IsDirty(segmentGroup: SegmentGroup) {
    // Segment Group Dirty
    if (segmentGroup.isDirty)
      return true;

    segmentGroup.segmentDefinitions.forEach(segmentDefinition => {
      if (segmentDefinition.isDirty || segmentDefinition.startTimeLineDefinition.isDirty || segmentDefinition.endTimeLineDefinition.isDirty)
        return true;
    });

    return false;
  }

I need to check 3 levels of the object for an is dirty field, ie itself, a child object that is within an array, and a child object of the child within the array.

The issue i have is, the *ngIf method is called when the button is rendered and only when the button is rendered.  Its not bound to a property therefore change detection doesnt trigger anything.  So if I update IsDirty on any of the 3 levels the button never shows.

Is there a way to force the re-render or execution of the ngIf when either a property is changed or on a (change) event on the input?

Body:
I believe you answered your own question, using a function for the *ngIf directive will only be evaluated when the element is connected to the DOM and subsequent change detection cycles triggered by other means.

You could programmatically force change detection per the comment above to force the function call however, I believe the more appropriate implementation is as you pointed out, to bind the directive to a local class variable.

Calling functions directly from template markup is frowned upon for
performance reasons

isDirty = false

<button *ngIf="isDirty">

isDirty = true

The above will trigger change detection because false is no longer equal to true, hence the term "change detection".

*ngIf="isDirty()"

This will never trigger change detection without some other means because function is always equal to function and it never changes... thus no change to trigger "change detection"

Set a boolean value to a local variable and bind that to the *ngIf directive, then find some other means to trigger your isDirty function to set that boolean value... on form change or input change is the typical implementation to calling a function like this.


问:
Custom Filepath Exporting a Pandas Dataframe
I am working with financial data, and I am cleaning the data in Python before exporting it as a CSV. I want this file to be reused, so I want to make sure that the exported files are not overwritten. I am including this piece of code to help with this:

```<code># Fill this out; this will help identify the dataset after it is exported
latestFY = '21'
earliestFY = '19'
</code>```

I want the user to change the earliest and latest fiscal year variables to reflect the data they are working with, so when the data is exported, it is called financialData_FY19_FY21, for example. How can I do this using the to_csv function?

Here is what I currently have:

```<code>mergedDF.to_csv("merged_financial_data_FY.csv", index = False)
</code>```

Here is what I want the file path to look like: financialData_FY19_FY21 where the 19 and 21 can be changed based on the input above.

答:
You can use an f-string to update the strings that will be your file paths.

```<code>latestFY = '21'
earliestFY = '19'
filename = f"merged_financial_data_FY{earliestFY}_{latestFY}.csv"
mergedDF.to_csv(filename, index=False)
</code>```

Link to docs

Body:
I am working with financial data, and I am cleaning the data in Python before exporting it as a CSV. I want this file to be reused, so I want to make sure that the exported files are not overwritten. I am including this piece of code to help with this:

# Fill this out; this will help identify the dataset after it is exported
latestFY = '21'
earliestFY = '19'

I want the user to change the earliest and latest fiscal year variables to reflect the data they are working with, so when the data is exported, it is called financialData_FY19_FY21, for example. How can I do this using the to_csv function?

Here is what I currently have:

mergedDF.to_csv("merged_financial_data_FY.csv", index = False)

Here is what I want the file path to look like: financialData_FY19_FY21 where the 19 and 21 can be changed based on the input above.

Body:
You can use an f-string to update the strings that will be your file paths.

latestFY = '21'
earliestFY = '19'
filename = f"merged_financial_data_FY{earliestFY}_{latestFY}.csv"
mergedDF.to_csv(filename, index=False)

Link to docs


问:
python gives invalid argument error on OS level
i have this piece of code:

```<code>symbol = 'PSTV'
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"

a_json=requests.get(end_point).json()
if a_json['status'] == 'OK':
    candle_open  = a_json['ticker']['min']['o']
    candle_close = a_json['ticker']['min']['c']
    candle_high  = a_json['ticker']['min']['h']
    candle_low   = a_json['ticker']['min']['l']
    candle_ts    = a_json['ticker']['lastQuote']['t']
    print(candle_ts/1000000)
    candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
    print("OK")
</code>```

im trying to convert timestamp to a readable format like so:

```<code>candle_ts    = a_json['ticker']['lastQuote']['t'] #get the timestamp
print(candle_ts/1000000)
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
</code>```

the print is : 1644529277457.4104

I have no clue why but the error is :

```<code>    candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
OSError: [Errno 22] Invalid argument
</code>```

Why do I get such an unusual error??

答:
The value for candle_ts is out of range, as you can see below sample script. The max limit is year 5138 which is around 11digits only. Your value for candle_ts is 13digits.</p>
```<code>from datetime import datetime
candle_ts = 1644529277457.4104
try:
    candle_ts = datetime.fromtimestamp(candle_ts).strftime('%Y-%m-%d %H:%M:%S')
    print(candle_ts)
except Exception as e:
    print(e)

Result:
 year 54083 is out of range
</code>```

Body:
i have this piece of code:

symbol = 'PSTV'
end_point="https://api.polygon.io/v2/snapshot/locale/us/markets/stocks/tickers/"+symbol+"?apiKey=my_key"

a_json=requests.get(end_point).json()
if a_json['status'] == 'OK':
    candle_open  = a_json['ticker']['min']['o']
    candle_close = a_json['ticker']['min']['c']
    candle_high  = a_json['ticker']['min']['h']
    candle_low   = a_json['ticker']['min']['l']
    candle_ts    = a_json['ticker']['lastQuote']['t']
    print(candle_ts/1000000)
    candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
    print("OK")

im trying to convert timestamp to a readable format like so:

candle_ts    = a_json['ticker']['lastQuote']['t'] #get the timestamp
print(candle_ts/1000000)
candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')

the print is : 1644529277457.4104

I have no clue why but the error is :

    candle_ts = datetime.fromtimestamp(candle_ts/1000000).strftime('%Y-%m-%d %H:%M:%S')
OSError: [Errno 22] Invalid argument

Why do I get such an unusual error??

Body:
The value for candle_ts is out of range, as you can see below sample script. The max limit is year 5138 which is around 11digits only. Your value for candle_ts is 13digits.

from datetime import datetime
candle_ts = 1644529277457.4104
try:
    candle_ts = datetime.fromtimestamp(candle_ts).strftime('%Y-%m-%d %H:%M:%S')
    print(candle_ts)
except Exception as e:
    print(e)

Result:
 year 54083 is out of range


问:
.find() Is finding values elements that are not apart of the search criteria
I am using .find() on the following json object, which I've named records:

```<code>[
  {
    "_id": "61f9da9fcc6888f201f722cb",
    "firstName": "joe",
    "lastName": "jergen",
    "email": "joe@outlook.com",
    "status": "active",
    "amount": "5600"
  }
]
</code>```

I then try to find a user in my object using find():

let userProfile = records.find((x) => (x.email = "peter@google.com"));

When I log userProfile it seems to pull joe@outlook.com still even though the user is not in the object. The desired behaviour would be null/undefined

答:
You probably want to do x.email === "peter@google.com"

= is an assignment operator while === is a comparison operator.

Body:
I am using .find() on the following json object, which I've named records:

[
  {
    "_id": "61f9da9fcc6888f201f722cb",
    "firstName": "joe",
    "lastName": "jergen",
    "email": "joe@outlook.com",
    "status": "active",
    "amount": "5600"
  }
]

I then try to find a user in my object using find():

let userProfile = records.find((x) => (x.email = "peter@google.com"));

When I log userProfile it seems to pull joe@outlook.com still even though the user is not in the object. The desired behaviour would be null/undefined


问:
flutter firebase offline error caused by sending get request to real time database
im currently trying to use flutter and firebase realtime database together but i keep on getting this error whenever i try and get or update the database. it was working fine a few days ago but i accidently rolled back the changes.

i have done

WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    name: "main_app",
    options: FirebaseOptions(
        apiKey: "XXXXXXXXXXXXXXXXXXXXXXXX",
        authDomain: "fXXXXXXXXXXXXX",
        databaseURL: "XXXXXXXXXXXXXXX",
        projectId: "XXXXXXXXXXXXXXXXX",
        storageBucket: "XXXXXXXXXXXXXX",
        messagingSenderId: "XXXXXXXXXX",
        appId: "XXXXXXXXXXXXXXXXXXXXX",
        measurementId: "XXXXX"
    )
  );
```
<p>the error occurs wheneever i do
<code>FirebaseDatabase.instance.ref("/users").get()</code>
i have tried different end points to check if that is the problem but the error is hard to understand imo</p>
<pre class="lang-java prettyprint-override"><code>I/RepoOperation( 6096): get for query / falling back to disk cache after error: Client is offline
E/firebase_database( 6096): An unknown error occurred handling native method call Query#get
E/firebase_database( 6096): java.util.concurrent.ExecutionException: java.lang.Exception: Client is offline
E/firebase_database( 6096):     at com.google.android.gms.tasks.Tasks.zza(com.google.android.gms:play-services-tasks@@18.0.1:5)
E/firebase_database( 6096):     at com.google.android.gms.tasks.Tasks.await(com.google.android.gms:play-services-tasks@@18.0.1:8)
E/firebase_database( 6096):     at io.flutter.plugins.firebase.database.FirebaseDatabasePlugin.lambda$queryGet$8$FirebaseDatabasePlugin(FirebaseDatabasePlugin.java:248)
E/firebase_database( 6096):     at io.flutter.plugins.firebase.database.-$$Lambda$FirebaseDatabasePlugin$zohedUhq4ZX8w6dhHgizPHWixGY.call(Unknown Source:4)
E/firebase_database( 6096):     at com.google.android.gms.tasks.zzz.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
E/firebase_database( 6096):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/firebase_database( 6096):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/firebase_database( 6096):     at java.lang.Thread.run(Thread.java:919)
E/firebase_database( 6096): Caused by: java.lang.Exception: Client is offline
E/firebase_database( 6096):     at com.google.firebase.database.connection.PersistentConnectionImpl.lambda$get$1$PersistentConnectionImpl(PersistentConnectionImpl.java:441)
E/firebase_database( 6096):     at com.google.firebase.database.connection.-$$Lambda$PersistentConnectionImpl$DHovbqW2nxPacSd_wNZBtpYapws.run(Unknown Source:8)
E/firebase_database( 6096):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
E/firebase_database( 6096):     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
E/firebase_database( 6096):     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
E/firebase_database( 6096):     ... 3 more
E/flutter ( 6096): [ERROR:flutter/shell/common/shell.cc(94)] Dart Unhandled Exception: [firebase_database/unknown] java.lang.Exception: Client is offline
E/flutter ( 6096):
E/flutter ( 6096): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter ( 6096): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #2      MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:367:43)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #3      MethodChannelQuery.get (package:firebase_database_platform_interface/src/method_channel/method_channel_query.dart:74:22)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #4      Query.get (package:firebase_database/src/query.dart:21:27)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): , stack trace: #0      MethodChannelQuery.get (package:firebase_database_platform_interface/src/method_channel/method_channel_query.dart:86:7)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #1      Query.get (package:firebase_database/src/query.dart:21:27)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096):
</code>```

答:
You seem to be calling get(), while you're offline and with no data in the cache.

Keep in mind you have to explicitly enable disk persistence for the Firebase Realtime Database before it can read data from it while you're offline. You can do this by calling setPersistenceEnabled(true) at the start of the app, before calling any methods that read/write data:

```<code>FirebaseDatabase.instance.setPersistenceEnabled(true);
</code>```

Body:
im currently trying to use flutter and firebase realtime database together but i keep on getting this error whenever i try and get or update the database. it was working fine a few days ago but i accidently rolled back the changes.

i have done

WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    name: "main_app",
    options: FirebaseOptions(
        apiKey: "XXXXXXXXXXXXXXXXXXXXXXXX",
        authDomain: "fXXXXXXXXXXXXX",
        databaseURL: "XXXXXXXXXXXXXXX",
        projectId: "XXXXXXXXXXXXXXXXX",
        storageBucket: "XXXXXXXXXXXXXX",
        messagingSenderId: "XXXXXXXXXX",
        appId: "XXXXXXXXXXXXXXXXXXXXX",
        measurementId: "XXXXX"
    )
  );

the error occurs wheneever i do
FirebaseDatabase.instance.ref("/users").get()
i have tried different end points to check if that is the problem but the error is hard to understand imo

I/RepoOperation( 6096): get for query / falling back to disk cache after error: Client is offline
E/firebase_database( 6096): An unknown error occurred handling native method call Query#get
E/firebase_database( 6096): java.util.concurrent.ExecutionException: java.lang.Exception: Client is offline
E/firebase_database( 6096):     at com.google.android.gms.tasks.Tasks.zza(com.google.android.gms:play-services-tasks@@18.0.1:5)
E/firebase_database( 6096):     at com.google.android.gms.tasks.Tasks.await(com.google.android.gms:play-services-tasks@@18.0.1:8)
E/firebase_database( 6096):     at io.flutter.plugins.firebase.database.FirebaseDatabasePlugin.lambda$queryGet$8$FirebaseDatabasePlugin(FirebaseDatabasePlugin.java:248)
E/firebase_database( 6096):     at io.flutter.plugins.firebase.database.-$$Lambda$FirebaseDatabasePlugin$zohedUhq4ZX8w6dhHgizPHWixGY.call(Unknown Source:4)
E/firebase_database( 6096):     at com.google.android.gms.tasks.zzz.run(com.google.android.gms:play-services-tasks@@18.0.1:1)
E/firebase_database( 6096):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/firebase_database( 6096):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/firebase_database( 6096):     at java.lang.Thread.run(Thread.java:919)
E/firebase_database( 6096): Caused by: java.lang.Exception: Client is offline
E/firebase_database( 6096):     at com.google.firebase.database.connection.PersistentConnectionImpl.lambda$get$1$PersistentConnectionImpl(PersistentConnectionImpl.java:441)
E/firebase_database( 6096):     at com.google.firebase.database.connection.-$$Lambda$PersistentConnectionImpl$DHovbqW2nxPacSd_wNZBtpYapws.run(Unknown Source:8)
E/firebase_database( 6096):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:462)
E/firebase_database( 6096):     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
E/firebase_database( 6096):     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
E/firebase_database( 6096):     ... 3 more
E/flutter ( 6096): [ERROR:flutter/shell/common/shell.cc(94)] Dart Unhandled Exception: [firebase_database/unknown] java.lang.Exception: Client is offline
E/flutter ( 6096):
E/flutter ( 6096): #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter ( 6096): #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:167:18)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #2      MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:367:43)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #3      MethodChannelQuery.get (package:firebase_database_platform_interface/src/method_channel/method_channel_query.dart:74:22)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #4      Query.get (package:firebase_database/src/query.dart:21:27)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): , stack trace: #0      MethodChannelQuery.get (package:firebase_database_platform_interface/src/method_channel/method_channel_query.dart:86:7)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096): #1      Query.get (package:firebase_database/src/query.dart:21:27)
E/flutter ( 6096): <asynchronous suspension>
E/flutter ( 6096):

Body:
You seem to be calling get(), while you're offline and with no data in the cache.

Keep in mind you have to explicitly enable disk persistence for the Firebase Realtime Database before it can read data from it while you're offline. You can do this by calling setPersistenceEnabled(true) at the start of the app, before calling any methods that read/write data:

FirebaseDatabase.instance.setPersistenceEnabled(true);