问:
Simple Container Toolchain - failed to deploy : Exceeded maximum number of retries
I'm trying to run the deploy pipeline created by the Simple Container Toolchain example.  The output of the deployment log is:

```<code>...
2017-07-03 15:49:43 UTC : creating group: /tmp/extension_content/cf ic group create --name hello-containers-XXXX_2 --publish 80 --desired 2 --min 1 --max 6 registry.ng.bluemix.net/chstest/hello-containers-XXXX:1
OK
The creation of the container group was requested.
The container group "hello-containers-XXXX_2" (ID: YYYY) was created.
Minimum container instances: 1
Maximum container instances: 6
Desired container instances: 2
2017-07-03 15:49:49 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
2017-07-03 15:49:53 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
...
... CREATE_IN_PROGRESS message repeated about 150 times
...
2017-07-03 16:02:51 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
2017-07-03 16:02:55 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
2017-07-03 16:02:58 UTC : Create group is not completed and stays in status 'CREATE_IN_PROGRESS'
2017-07-03 16:02:58 UTC : Failed to deploy group
To send notifications, set SLACK_WEBHOOK_PATH or HIP_CHAT_TOKEN in the environment

Finished: FAILED
</code>```

If I navigate to the container dashboard in Bluemix, I see the following error log:

```<code>Group failed
Resource CREATE failed: ResourceInError: resources.asg.resources.i2jghszuv3br.resources.server: Went to status ERROR due to "Message: Exceeded maximum number of retries. Exceeded max scheduling attempts 3 for instance ZZZZ. Last exception: [u'Traceback (most recent call last): \n', u' File "/opt/bbc/openstack-12.1.90/nova/local/lib/python2.7/site-packages, Code: 500"
</code>```

How can I debug this further?

答: Please open a Bluemix support ticket against the Containers SRE Team. Do this by logging into your Bluemix account and in the upper right hand corner there is an option for "Support" = "Add Ticket".</p>

Body:
I'm trying to run the deploy pipeline created by the Simple Container Toolchain example.  The output of the deployment log is:

...
2017-07-03 15:49:43 UTC : creating group: /tmp/extension_content/cf ic group create --name hello-containers-XXXX_2 --publish 80 --desired 2 --min 1 --max 6 registry.ng.bluemix.net/chstest/hello-containers-XXXX:1
OK
The creation of the container group was requested.
The container group "hello-containers-XXXX_2" (ID: YYYY) was created.
Minimum container instances: 1
Maximum container instances: 6
Desired container instances: 2
2017-07-03 15:49:49 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
2017-07-03 15:49:53 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
...
... CREATE_IN_PROGRESS message repeated about 150 times
...
2017-07-03 16:02:51 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
2017-07-03 16:02:55 UTC : hello-containers-XXXX_2 is 'CREATE_IN_PROGRESS'
2017-07-03 16:02:58 UTC : Create group is not completed and stays in status 'CREATE_IN_PROGRESS'
2017-07-03 16:02:58 UTC : Failed to deploy group
To send notifications, set SLACK_WEBHOOK_PATH or HIP_CHAT_TOKEN in the environment

Finished: FAILED

If I navigate to the container dashboard in Bluemix, I see the following error log:

Group failed
Resource CREATE failed: ResourceInError: resources.asg.resources.i2jghszuv3br.resources.server: Went to status ERROR due to "Message: Exceeded maximum number of retries. Exceeded max scheduling attempts 3 for instance ZZZZ. Last exception: [u'Traceback (most recent call last): \n', u' File "/opt/bbc/openstack-12.1.90/nova/local/lib/python2.7/site-packages, Code: 500"

How can I debug this further?


来源: stackexchange

问:
Using Oracle.DataAccess.DLL already on PC, not providing it
I am looking to make my program more dynamic. I would like it to be able to support an Oracle 10g and an Oracle 11g database with the same program. If I build the program using the .DLL reference for one version then the other fails. Is there a way to use the Oracle.DataAccess.DLL that is already on the computer being installed upon, instead of providing the DLL in my installer?

Thanks in advance.

答:
See @MattRodatus' excellent answer about using a binding redirect if you need to get your application to support multiple versions of Oracle.DataAccess that might be on a machine you're deploying to.

However, you should be able to access a 10g or an 11g database with either version of the Oracle client installation.

See the @the.jxc's answer at Oracle: Does a 10g oracle client work with an 11g server? for a good synopsis of which clients support which databases.

ContentLicense: CC BY-SA 2.5


问:
Using socketio with react redux
Im building a small chat application using react,redux,socketio and node with mongoose. Normally redux flows through actions (which makes API calls and receive data) and dispatch the data. But in my case the socket will emit to a certain event but it would not return data until we manually emit the data from the back-end. so to achieve the proper redux flow should i add a socket event on actions to retrieve the data (coming from back-end) and then dispatch it or is there any other proper way to achieve this?

Here is a sample code of what i'm planing to do in
Actions file

```<code>    function sendMessage(data) {
      return {
        type: SEND_MESSAGE,
        payload: data
      };
    }

    export const sendNewMessage = (socket,data) => {
         return dispatch => {
              socket.emit("send message",data);
              socket.on("new message",function(data){
                  dispatch(sendMessage(data));
               });

    };

};
</code>```

答:
That seems perfectly reasonable to me. I would suggest using thunk's "extra argument" for this such that your components do not need to know about the actual socket object:</p>

```<code>const store = createStore(
  reducer,
  applyMiddleware(thunk.withExtraArgument({ socket }))
)

export const sendNewMessage = (data) =>
  (dispatch, getState, { socket }) => {
    socket.emit("send message", data)
    socket.on("new message", (data) => {
      dispatch(sendMessage(data))
    })
  }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using socketio with react redux

Body:
Im building a small chat application using react,redux,socketio and node with mongoose. Normally redux flows through actions (which makes API calls and receive data) and dispatch the data. But in my case the socket will emit to a certain event but it would not return data until we manually emit the data from the back-end. so to achieve the proper redux flow should i add a socket event on actions to retrieve the data (coming from back-end) and then dispatch it or is there any other proper way to achieve this?

Here is a sample code of what i'm planing to do in
Actions file

    function sendMessage(data) {
      return {
        type: SEND_MESSAGE,
        payload: data
      };
    }

    export const sendNewMessage = (socket,data) => {
         return dispatch => {
              socket.emit("send message",data);
              socket.on("new message",function(data){
                  dispatch(sendMessage(data));
               });

    };

};

Body:
That seems perfectly reasonable to me. I would suggest using thunk's "extra argument" for this such that your components do not need to know about the actual socket object:

const store = createStore(
  reducer,
  applyMiddleware(thunk.withExtraArgument({ socket }))
)

export const sendNewMessage = (data) =>
  (dispatch, getState, { socket }) => {
    socket.emit("send message", data)
    socket.on("new message", (data) => {
      dispatch(sendMessage(data))
    })
  }


问:
How to handle events produced by Osgi modules before a listener is registered to Felix Event Admin
I have an OSGi module A which produces an Event EA in a PostConstruct.

I have another OSGi module B which depends on the event EA to perform some operations.

But the module B is loaded and hence registers its event listener to Felix Event Admin after the module A has loaded and already produced the event EA.

So the module B fails after waiting for the event EA for a certain timeout value.

Is there a way I can access all the produced events before a listener from module B is registered?

I tried using OSGiService(waitTimeout = 1000), but this only waits for service to become available.. but not for its methods to finish executing.

Thanks.

答:
It sounds as though Event Admin isn't really the right tool for what you're trying to do, which seems a lot more like persistent messaging than eventing.

An eventing model should either:

Have listeners that don't care about when they join the event stream, or

Maintain a separate event stream for each listener which starts when each listener joins

Not start delivering events until the listeners are all available and ready

If you need to send an "event" at a particular time, but can't wait for the listener then what you want is a persistent messaging implementation (for example JMS). That way when your listener starts up it can begin processing whatever messages were queued while it was starting.


问:
How to order data with Symfony and Doctrine?
I want to build datagrid filter but ->addOrderBy amd ->orderBy don't work for me.

```<code>$query
    ->andWhere('o.pizza = :pizza')
    ->setParameter('pizza', $pizzaId)
    ->addOrderBy(o.status,'ASC')
</code>```

How ever if I do this:

```<code>$query
    ->andWhere('o.pizza = :spizza')
    ->setParameter('pizza', $pizzaId)
    ->andWhere('o.status = :status')
    ->setParameter('status',Pizza\PizzaApply::STATUS_READY)
</code>```

It shows me only the pizzas with status 'ready'. But I want to sort by status 'ready' shoulde first and 'On hold' under them.

答:
I had a similar problem really recently and managed to sort it out using this in my Admin Class: (in my case I wanted a double order)

```<code>public function createQuery($context = 'list')
{
    $query = parent::createQuery($context);
    $query->orderby('o.dateUpdated DESC, o.name');
    return $query;
}
</code>```

As an alternative, you can also use that in your Admin class:

```<code>/**
 * Default Datagrid values
 *
 * @var array
 */
protected $datagridValues = array(
    '_page' => 1,
    '_sort_order' => 'DESC',
    '_sort_by' => 'dateUpdated'
);
</code>```

Body:
I want to build datagrid filter but ->addOrderBy amd ->orderBy don't work for me.

$query
    ->andWhere('o.pizza = :pizza')
    ->setParameter('pizza', $pizzaId)
    ->addOrderBy(o.status,'ASC')

How ever if I do this:

$query
    ->andWhere('o.pizza = :spizza')
    ->setParameter('pizza', $pizzaId)
    ->andWhere('o.status = :status')
    ->setParameter('status',Pizza\PizzaApply::STATUS_READY)

It shows me only the pizzas with status 'ready'. But I want to sort by status 'ready' shoulde first and 'On hold' under them.

Body:
I had a similar problem really recently and managed to sort it out using this in my Admin Class: (in my case I wanted a double order)

public function createQuery($context = 'list')
{
    $query = parent::createQuery($context);
    $query->orderby('o.dateUpdated DESC, o.name');
    return $query;
}

As an alternative, you can also use that in your Admin class:

/**
 * Default Datagrid values
 *
 * @var array
 */
protected $datagridValues = array(
    '_page' => 1,
    '_sort_order' => 'DESC',
    '_sort_by' => 'dateUpdated'
);


问:
QT Application segmentation fault on exit when using std::unique_ptr for the QMainWindow
I should clarify first, my question is, why does the segfault happen in the case where I use a std::unique_ptr but it doesn't when I change the code to use new and delete? I don't really have an issue here, since the segfault is fixed and I know I'm properly cleaning things up with new and delete. I just want to know why I couldn't use a std::unique_ptr.

If I create my QMainWindow instance in a std::unique_ptr and my MainWindow creates a child window (e.g. opening a QComboBox or ToolTip), my application will segfault on exit. In this case, if my MainWindow does not create any child windows, there is no segfault.

If I manage my QMainWindow instance myself with new and delete, there is no segfault regardless of whether or not I create a child window.

This is my main, it simply calls run on my Bridge class that handles creating the instance of my MainWindow class and starting it.

```<code>int main(int argc, char *argv[])
{
    Bridge bridge(argc, argv);
    bridge.run(); // Handles starting the main window
}
</code>```

This is a shortened version of my Bridge class that results in a segfault (using std::unique_ptr I get a segfault on exit):

```<code>class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(), isRunning(true), app(argc, argv) {}
    ~IMPL() = default;
public:
    std::unique_ptr<MainWindow> mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow.reset(new MainWindow(this));
}
</code>```

This is the Bridge class with no segfault (slightly modified to remove the std::unique_ptr and instead use new and delete. This version of the Bridge class DOES NOT CRASH):

```<code>class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(nullptr), isRunning(true), app(argc, argv) {}
    ~IMPL() {
        if (mainwindow) {
            delete mainwindow;
        }
    }
public:
    MainWindow* mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow= new MainWindow(this);
}
</code>```

This is the back-trace when a segfault would happen:

Also there is a weird print-out about QBasicTimer that doesn't get printed after I changed the code to use new and delete instead of std::unique_ptr

```<code>QBasicTimer::start: QBasicTimer can only be used with threads started with QThread

Thread 1 "application" received signal SIGSEGV, Segmentation fault.
0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
(gdb) bt
#0  0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#1  0x00007fffe75bf5c4 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#2  0x00007fffe75b9669 in QXcbConnection::removeWindowEventListener(unsigned int) () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#3  0x00007fffe75ceafa in QXcbWindow::destroy() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#4  0x00007fffe75cec07 in QXcbWindow::~QXcbWindow() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#5  0x00007fffe43ce2ee in ?? () from /home/user/Qt/5.9/gcc_64/plugins/xcbglintegrations/libqxcb-glx-integration.so
#6  0x00007ffff4b56f46 in QWindowPrivate::destroy() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Gui.so.5
#7  0x00007ffff534ecd7 in QWidgetPrivate::deleteTLSysExtra() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#8  0x00007ffff53524d8 in QWidget::destroy(bool, bool) () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#9  0x00007ffff53598b0 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#10 0x00007ffff541ae7a in ?? () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#11 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#12 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#13 0x00007ffff540eac9 in QComboBox::~QComboBox() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#14 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#15 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#16 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#17 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#18 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#19 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#20 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#21 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#22 0x0000000000421ed4 in MainWindow::~MainWindow() ()
#23 0x0000000000421f0e in MainWindow::~MainWindow() ()
#24 0x0000000000421698 in std::default_delete<MainWindow>::operator()(MainWindow*) const ()
#25 0x0000000000421171 in std::unique_ptr<MainWindow, std::default_delete<MainWindow> >::~unique_ptr() ()
#26 0x000000000042191c in Bridge::IMPL::~IMPL() ()
#27 0x0000000000421942 in std::default_delete<Bridge::IMPL>::operator()(Bridge::IMPL*) const ()
#28 0x0000000000421387 in std::unique_ptr<Bridge::IMPL, std::default_delete<Bridge::IMPL> >::~unique_ptr() ()
#29 0x0000000000420cb0 in Bridge::~Bridge() ()
#30 0x0000000000421c41 in main ()
</code>```

It should also be noted that this QApplication is run using a while loop and calls to app.processEvents() rather than calling exec(). I realize that's not the best way to do it, however this app is part of another application that polls for events from somewhere else and since the nature of this application is more "proof-of-concept" than anything else, I wanted to keep it simple by having it all in one thread. See below for a snippet of my run method:

```<code>while (isRunning()) {
    poller.poll(25);
    app.processEvents();
}
</code>```

EDIT:

In my constructor for MainWindow the this I'm passing is not being set as the parent (the parent is nullptr):

header:

```<code>class MainWindow: public QMainWindow
{
    Q_OBJECT
public:
    class BridgeInterface{
    public:
        // Some pure virtual methods here
    };

    explicit MainWindow(BridgeInterface* interface, QWidget* parent = nullptr);

// some more stuff...

private:
    class IMPL;
    std::unique_ptr<IMPL> pImpl;
};
</code>```

source:

```<code>MainWindow::MainWindow(BridgeInterface* interface, QWidget* parent) :
    QMainWindow(parent), pImpl(make_unique<IMPL>()) {

    pImpl->ui->setupUi(this);
    pImpl->bridgeInterface = interface;

    // Connect slots and stuff
}
</code>```

答:
In your class, QApplication's destructor is being called before your mainwindow is destroyed. That's because class variables are initalized in the order they're listed, then destroyed in the opposite order.

If you move QApplication app; so it's the first variable in the class, its destructor will be called last, AFTER mainwindow is destroyed, which is the correct behavior.

The reason it works when you delete it explicitly is that you're deleting mainwindow via the IMPL's destructor. ~IMPL() runs before the class variable destructors are run, resulting in mainwindow being destroyed first.

Body:
I should clarify first, my question is, why does the segfault happen in the case where I use a std::unique_ptr but it doesn't when I change the code to use new and delete? I don't really have an issue here, since the segfault is fixed and I know I'm properly cleaning things up with new and delete. I just want to know why I couldn't use a std::unique_ptr.

If I create my QMainWindow instance in a std::unique_ptr and my MainWindow creates a child window (e.g. opening a QComboBox or ToolTip), my application will segfault on exit. In this case, if my MainWindow does not create any child windows, there is no segfault.

If I manage my QMainWindow instance myself with new and delete, there is no segfault regardless of whether or not I create a child window.

This is my main, it simply calls run on my Bridge class that handles creating the instance of my MainWindow class and starting it.

int main(int argc, char *argv[])
{
    Bridge bridge(argc, argv);
    bridge.run(); // Handles starting the main window
}

This is a shortened version of my Bridge class that results in a segfault (using std::unique_ptr I get a segfault on exit):

class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(), isRunning(true), app(argc, argv) {}
    ~IMPL() = default;
public:
    std::unique_ptr<MainWindow> mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow.reset(new MainWindow(this));
}

This is the Bridge class with no segfault (slightly modified to remove the std::unique_ptr and instead use new and delete. This version of the Bridge class DOES NOT CRASH):

class Bridge::IMPL {
public:
    IMPL(int& argc, char ** argv) :
        mainwindow(nullptr), isRunning(true), app(argc, argv) {}
    ~IMPL() {
        if (mainwindow) {
            delete mainwindow;
        }
    }
public:
    MainWindow* mainwindow;
    bool isRunning;
    QApplication app;
};

Bridge::Bridge(int& argc, char ** argv) :
    pImpl(make_unique<IMPL>(argc, argv)) {

    pImpl->mainwindow= new MainWindow(this);
}

This is the back-trace when a segfault would happen:

Also there is a weird print-out about QBasicTimer that doesn't get printed after I changed the code to use new and delete instead of std::unique_ptr

QBasicTimer::start: QBasicTimer can only be used with threads started with QThread

Thread 1 "application" received signal SIGSEGV, Segmentation fault.
0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
(gdb) bt
#0  0x00007fffe75bf2e2 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#1  0x00007fffe75bf5c4 in ?? () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#2  0x00007fffe75b9669 in QXcbConnection::removeWindowEventListener(unsigned int) () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#3  0x00007fffe75ceafa in QXcbWindow::destroy() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#4  0x00007fffe75cec07 in QXcbWindow::~QXcbWindow() () from /home/user/Qt/5.9/gcc_64/plugins/platforms/../../lib/libQt5XcbQpa.so.5
#5  0x00007fffe43ce2ee in ?? () from /home/user/Qt/5.9/gcc_64/plugins/xcbglintegrations/libqxcb-glx-integration.so
#6  0x00007ffff4b56f46 in QWindowPrivate::destroy() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Gui.so.5
#7  0x00007ffff534ecd7 in QWidgetPrivate::deleteTLSysExtra() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#8  0x00007ffff53524d8 in QWidget::destroy(bool, bool) () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#9  0x00007ffff53598b0 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#10 0x00007ffff541ae7a in ?? () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#11 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#12 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#13 0x00007ffff540eac9 in QComboBox::~QComboBox() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#14 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#15 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#16 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#17 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#18 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#19 0x00007ffff5359ab9 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#20 0x00007ffff4580b83 in QObjectPrivate::deleteChildren() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Core.so.5
#21 0x00007ffff5359894 in QWidget::~QWidget() () from /home/user/Qt/5.9/gcc_64/lib/libQt5Widgets.so.5
#22 0x0000000000421ed4 in MainWindow::~MainWindow() ()
#23 0x0000000000421f0e in MainWindow::~MainWindow() ()
#24 0x0000000000421698 in std::default_delete<MainWindow>::operator()(MainWindow*) const ()
#25 0x0000000000421171 in std::unique_ptr<MainWindow, std::default_delete<MainWindow> >::~unique_ptr() ()
#26 0x000000000042191c in Bridge::IMPL::~IMPL() ()
#27 0x0000000000421942 in std::default_delete<Bridge::IMPL>::operator()(Bridge::IMPL*) const ()
#28 0x0000000000421387 in std::unique_ptr<Bridge::IMPL, std::default_delete<Bridge::IMPL> >::~unique_ptr() ()
#29 0x0000000000420cb0 in Bridge::~Bridge() ()
#30 0x0000000000421c41 in main ()

It should also be noted that this QApplication is run using a while loop and calls to app.processEvents() rather than calling exec(). I realize that's not the best way to do it, however this app is part of another application that polls for events from somewhere else and since the nature of this application is more "proof-of-concept" than anything else, I wanted to keep it simple by having it all in one thread. See below for a snippet of my run method:

while (isRunning()) {
    poller.poll(25);
    app.processEvents();
}

EDIT:

In my constructor for MainWindow the this I'm passing is not being set as the parent (the parent is nullptr):

header:

class MainWindow: public QMainWindow
{
    Q_OBJECT
public:
    class BridgeInterface{
    public:
        // Some pure virtual methods here
    };

    explicit MainWindow(BridgeInterface* interface, QWidget* parent = nullptr);

// some more stuff...

private:
    class IMPL;
    std::unique_ptr<IMPL> pImpl;
};

source:

MainWindow::MainWindow(BridgeInterface* interface, QWidget* parent) :
    QMainWindow(parent), pImpl(make_unique<IMPL>()) {

    pImpl->ui->setupUi(this);
    pImpl->bridgeInterface = interface;

    // Connect slots and stuff
}


问:
Dynamic Addition of Option Menu tKinter Python
I'm quite new to python. I have a requirement where I have to read a data file and based on the number of records inside the file, I have to create the same number of option menus related to that data. But option menu's options can be fetched from simple list. Please find the code below.

```<code>import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")

Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable = StringVar(root)
variable.set(Grids[0])

for i in range(len(ing)):

  label = tk.Label(root,text=ing[i])
  label.grid(row=i,pady=3,sticky=W)
  w=OptionMenu (root, variable, *tuple(Grids)))
  w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()
</code>```

The above code is able to give me n number of option menus but if I choose one value in one option menu other option menu's value also changes. Can someone please let me know how to achieve this.

Thanks,
Santty.

答:
This is happening because each of your OptionMenu are using the same StringVar.  So naturally when one OptionMenu makes a change to that StringVar, the other menus also reflect that change.

To prevent this you can use a separate StringVar for each menu:

```<code>import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")

Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable_dict = {}

for i in range(len(ing)):
    variable = StringVar(root)
    variable.set(Grids[0])
    variable_dict[i] = variable

    label = tk.Label(root,text=ing[i])
    label.grid(row=i,pady=3,sticky=W)
    w=OptionMenu (root, variable, *tuple(Grids)))
    w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()
</code>```

You can then access each of the StringVars through the dictionary variable_dict

Body:
I'm quite new to python. I have a requirement where I have to read a data file and based on the number of records inside the file, I have to create the same number of option menus related to that data. But option menu's options can be fetched from simple list. Please find the code below.

import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")

Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable = StringVar(root)
variable.set(Grids[0])

for i in range(len(ing)):

  label = tk.Label(root,text=ing[i])
  label.grid(row=i,pady=3,sticky=W)
  w=OptionMenu (root, variable, *tuple(Grids)))
  w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()

The above code is able to give me n number of option menus but if I choose one value in one option menu other option menu's value also changes. Can someone please let me know how to achieve this.

Thanks,
Santty.

Body:
This is happening because each of your OptionMenu are using the same StringVar.  So naturally when one OptionMenu makes a change to that StringVar, the other menus also reflect that change.

To prevent this you can use a separate StringVar for each menu:

import tkinter as tk
from tkinter import *

root=tk.Tk()
root.title("GridAssign")

Grids=('Grid1','Grid2','Grid3','Grid4','Grid5')
file=open(Datafilepath,"r")
ing=file.read().splitlines()
print (len(ing))

variable_dict = {}

for i in range(len(ing)):
    variable = StringVar(root)
    variable.set(Grids[0])
    variable_dict[i] = variable

    label = tk.Label(root,text=ing[i])
    label.grid(row=i,pady=3,sticky=W)
    w=OptionMenu (root, variable, *tuple(Grids)))
    w.grid(row=i,column=2,pady=3,sticky=E)

root.mainloop()

You can then access each of the StringVars through the dictionary variable_dict


问:
React navigation broken within function call
I'm new to react native and I can only seem to find documentation for how to navigate between screens in the return() method for react native.  I'm wondering what the syntax is for navigation in a function call.  The line I am having trouble with is line 37 (in the login function).

import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  TouchableOpacity,
  TextInput
} from 'react-native';
import Input from './Input';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {firebaseApp} from './App';
import {Tabs} from './Router';

export default class LoginScreen extends Component {
  constructor(props) {
    super(props)

    this.state = {
      email: '',
      password: '',
      status: ''
    }

    this.login = this.login.bind(this);
  }

  login(){
    console.log("Logging in");

    firebaseApp.auth().signInWithEmailAndPassword(this.state.email, this.state.password).catch(function(error) {
      console.log(error.code);
      console.log(error.message);
    })

    this.props.navigation.navigate('TabNav');

    console.log("Navigate to Home");

  }

  render() {
    var styles = require('./Styles');
    const {navigate} = this.props.navigation;

    return(
      <View style={styles.loginContainer}>
        <Text style={styles.loginHeader}>PRINCETON EVENTS</Text>
        <TextInput
          style={styles.loginInput}
          placeholder="Email"
          autoCapitalize='none'
          onChangeText={(text) => this.setState({email: text})}
          value={this.state.email}
          returnKeyType='next'/>
        <TextInput
          secureTextEntry
          style={styles.loginInput} placeholder="Password"
          onChangeText={(text) => this.setState({password: text})}
          value={this.state.password}
          autoCapitalize='none'
          returnKeyType='go'/>
        <TouchableOpacity style={styles.loginButton}>
          <Text style={styles.loginText} onPress={this.login}>LOGIN</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.loginButton}
          onPress = {() => navigate('CreateAccount')}>
          <Text style={styles.loginText}> CREATE ACCOUNT </Text>
        </TouchableOpacity>
      </View>
    );

}
}
```

<p>This is Router.js</p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import {StackNavigator, TabNavigator} from 'react-navigation';

import InputScreen from './InputPage';
import HomeScreen from './Home';
import DetailsScreen from './Details';
import MyEventsScreen from './MyEvents';
import EditScreen from './EditPage';
import MapScreen from './Map';
import CreateAccountScreen from './CreateAccount';
import LoginScreen from './Login';

export const MyEventsStack = StackNavigator({

  MyEvents: {
    screen: MyEventsScreen,
    navigationOptions: {
      header: null
    }
  },
  MyEventsDetails: {
    screen: EditScreen,
    navigationOptions: {
      header: null,

    },
  },

});

export const EventsStack = StackNavigator({
  Home: {
    screen: HomeScreen,
    navigationOptions: {
      header: null,
    },
  },
  Details: {
    screen: DetailsScreen,
    navigationOptions: {
      header: null,
    },
  },
});

export const Tabs = TabNavigator({
  Home: {screen: EventsStack},
  EventMap: {screen: MapScreen},
  Input: {screen: InputScreen},
  MyEvents:{screen: MyEventsStack},
},{
    tabBarOptions: {
      activeTintColors: '#e91e63',
    }
});

export const LoginNav = StackNavigator({
  Login: { screen: LoginScreen,
    navigationOptions: {
      header: null,
    },
  },
  CreateAccount: { screen: CreateAccountScreen,
    navigationOptions: {
      header: null,
    }
  },
});

/*export const SuccessLoginNav = StackNavigator({
  Main: { screen: Tabs,
    navigationOptions: {
      header: null,
    }
  },
});*/

export const Root = StackNavigator({
  TabNav: {
    screen: Tabs,
  }

}, {headerMode: 'none'});
</code>```

答:
In login, you're declaring a function but neither invoking it or assigning it to anything:

```<code>() => this.props.navigation.navigate('Home');
</code>```

Essentially that line does nothing.  Try removing the anonymous function declaration:

```<code>this.props.navigation.navigate('Home');
</code>```

Body:
I'm new to react native and I can only seem to find documentation for how to navigate between screens in the return() method for react native.  I'm wondering what the syntax is for navigation in a function call.  The line I am having trouble with is line 37 (in the login function).

import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  TouchableOpacity,
  TextInput
} from 'react-native';
import Input from './Input';
import Icon from 'react-native-vector-icons/MaterialIcons';
import {firebaseApp} from './App';
import {Tabs} from './Router';

export default class LoginScreen extends Component {
  constructor(props) {
    super(props)

    this.state = {
      email: '',
      password: '',
      status: ''
    }

    this.login = this.login.bind(this);
  }

  login(){
    console.log("Logging in");

    firebaseApp.auth().signInWithEmailAndPassword(this.state.email, this.state.password).catch(function(error) {
      console.log(error.code);
      console.log(error.message);
    })

    this.props.navigation.navigate('TabNav');

    console.log("Navigate to Home");

  }

  render() {
    var styles = require('./Styles');
    const {navigate} = this.props.navigation;

    return(
      <View style={styles.loginContainer}>
        <Text style={styles.loginHeader}>PRINCETON EVENTS</Text>
        <TextInput
          style={styles.loginInput}
          placeholder="Email"
          autoCapitalize='none'
          onChangeText={(text) => this.setState({email: text})}
          value={this.state.email}
          returnKeyType='next'/>
        <TextInput
          secureTextEntry
          style={styles.loginInput} placeholder="Password"
          onChangeText={(text) => this.setState({password: text})}
          value={this.state.password}
          autoCapitalize='none'
          returnKeyType='go'/>
        <TouchableOpacity style={styles.loginButton}>
          <Text style={styles.loginText} onPress={this.login}>LOGIN</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.loginButton}
          onPress = {() => navigate('CreateAccount')}>
          <Text style={styles.loginText}> CREATE ACCOUNT </Text>
        </TouchableOpacity>
      </View>
    );

}
}

This is Router.js

import React from 'react';
import {StackNavigator, TabNavigator} from 'react-navigation';

import InputScreen from './InputPage';
import HomeScreen from './Home';
import DetailsScreen from './Details';
import MyEventsScreen from './MyEvents';
import EditScreen from './EditPage';
import MapScreen from './Map';
import CreateAccountScreen from './CreateAccount';
import LoginScreen from './Login';

export const MyEventsStack = StackNavigator({

  MyEvents: {
    screen: MyEventsScreen,
    navigationOptions: {
      header: null
    }
  },
  MyEventsDetails: {
    screen: EditScreen,
    navigationOptions: {
      header: null,

    },
  },

});

export const EventsStack = StackNavigator({
  Home: {
    screen: HomeScreen,
    navigationOptions: {
      header: null,
    },
  },
  Details: {
    screen: DetailsScreen,
    navigationOptions: {
      header: null,
    },
  },
});

export const Tabs = TabNavigator({
  Home: {screen: EventsStack},
  EventMap: {screen: MapScreen},
  Input: {screen: InputScreen},
  MyEvents:{screen: MyEventsStack},
},{
    tabBarOptions: {
      activeTintColors: '#e91e63',
    }
});

export const LoginNav = StackNavigator({
  Login: { screen: LoginScreen,
    navigationOptions: {
      header: null,
    },
  },
  CreateAccount: { screen: CreateAccountScreen,
    navigationOptions: {
      header: null,
    }
  },
});

/*export const SuccessLoginNav = StackNavigator({
  Main: { screen: Tabs,
    navigationOptions: {
      header: null,
    }
  },
});*/

export const Root = StackNavigator({
  TabNav: {
    screen: Tabs,
  }

}, {headerMode: 'none'});

Body:
In login, you're declaring a function but neither invoking it or assigning it to anything:

() => this.props.navigation.navigate('Home');

Essentially that line does nothing.  Try removing the anonymous function declaration:

this.props.navigation.navigate('Home');


问:
Using :after element to make header that is rotated and height of the parent div
been struggling with this all afternoon. I want the black header to sit perfectly to the right of the quarter circles and dynamically fill the height. The colors are intended to be off screen and will use a rotate animation on mouseover to rotate them in.

You can check out the codepen here: https://codepen.io/Dawsraki/pen/LLrajZ

```<code>.quarter{
    position: fixed;
    width: 40vh;
    height: 40vh;
}
.quarter1{
    top: 0;
    left: 0;
    background-color: red;
    border-radius: 100% 0 0 0;
}
.quarter1:after{
    content:"Home";
    width:40vh;
    position:absolute;
    right:0;
    transform: rotate(-90deg);
    background:black;
    color:white;
    /* Safari */
    -webkit-transform: rotate(-90deg);
    /* Firefox */
    -moz-transform: rotate(-90deg);
    /* IE */
    -ms-transform: rotate(-90deg);
    /* Opera */
    -o-transform: rotate(-90deg);
    /* Internet Explorer */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    transform: rotate(-90deg);
}
</code>```

答:
You need to combine the rotate with translate and set a proper transform-origin

```<code>transform: rotate(-90deg) translateX(-50%);        /*  counter clockwise  */
transform-origin: center top;                      /*  defaults to center center  */
</code>```

Updated codepen

For clockwise rotation

```<code>transform: rotate(90deg) translateX(50%);
</code>```

Body:
been struggling with this all afternoon. I want the black header to sit perfectly to the right of the quarter circles and dynamically fill the height. The colors are intended to be off screen and will use a rotate animation on mouseover to rotate them in.

You can check out the codepen here: https://codepen.io/Dawsraki/pen/LLrajZ

.quarter{
    position: fixed;
    width: 40vh;
    height: 40vh;
}
.quarter1{
    top: 0;
    left: 0;
    background-color: red;
    border-radius: 100% 0 0 0;
}
.quarter1:after{
    content:"Home";
    width:40vh;
    position:absolute;
    right:0;
    transform: rotate(-90deg);
    background:black;
    color:white;
    /* Safari */
    -webkit-transform: rotate(-90deg);
    /* Firefox */
    -moz-transform: rotate(-90deg);
    /* IE */
    -ms-transform: rotate(-90deg);
    /* Opera */
    -o-transform: rotate(-90deg);
    /* Internet Explorer */
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    transform: rotate(-90deg);
}

Body:
You need to combine the rotate with translate and set a proper transform-origin

transform: rotate(-90deg) translateX(-50%);        /*  counter clockwise  */
transform-origin: center top;                      /*  defaults to center center  */

Updated codepen

For clockwise rotation

transform: rotate(90deg) translateX(50%);


问:
Initialization and pushing data in array
First, I declare an array :

```<code>let arr = [];
</code>```

Hence, I fill this array in the following way :

```<code>(async function loop() {
        for(let i=timeStart; i<=timeEnd; i+=3600000)
        {
          await ExternDataProvider.getCountData(i, (i+3600000), localSearchFilters)
            .then(function(dataResult){
              arr.push(dataResult);
            })
            .catch(function(err){
            });
        }
      })();
</code>```

But, when I make a console.log of the variable "arr", I have the following result :

So why I dont have something like [2251,215] instead ?

答:
If you console.log() your array after calling the function, you will have an empty array in the console, but after the data is resolved the console will refresh the content of the array. But if you console.log(arr[0]) it will show you undefined immediatly.

In my opinion you should return your array (or resolve it) and capture the resolved value in another then and execute your console.log inside this then

Try this:

```<code>let arr = [];
setTimeout(function() {
    arr.push(1)
}, 5000);

console.log(arr[0]); // prints undefined
console.log(arr); // prints an empty array if you expand the array before 5 seconds, and it will print [1] if you re-expand it after 5 seconds
</code>```

Body:
First, I declare an array :

let arr = [];

Hence, I fill this array in the following way :

(async function loop() {
        for(let i=timeStart; i<=timeEnd; i+=3600000)
        {
          await ExternDataProvider.getCountData(i, (i+3600000), localSearchFilters)
            .then(function(dataResult){
              arr.push(dataResult);
            })
            .catch(function(err){
            });
        }
      })();

But, when I make a console.log of the variable "arr", I have the following result :

So why I dont have something like [2251,215] instead ?

Body:
If you console.log() your array after calling the function, you will have an empty array in the console, but after the data is resolved the console will refresh the content of the array. But if you console.log(arr[0]) it will show you undefined immediatly.

In my opinion you should return your array (or resolve it) and capture the resolved value in another then and execute your console.log inside this then

Try this:

let arr = [];
setTimeout(function() {
    arr.push(1)
}, 5000);

console.log(arr[0]); // prints undefined
console.log(arr); // prints an empty array if you expand the array before 5 seconds, and it will print [1] if you re-expand it after 5 seconds


问:
Python 2.7: Trouble Encoding to UTF-8
I have a dataframe that has a column, _text, containing the text of an article.  I'm trying to get the length of the article for each row in my dataframe.  Here's my attempt:

```<code>from bs4 import BeautifulSoup
result_df['_text'] = [BeautifulSoup(text, "lxml").get_text() for text in result_df['_text']]

text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]
</code>```

Unfortunately, I get this error:

```<code>    ---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-8-f6c8ab83a46f> in <module>()
----> 1 text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 231: ordinal not in range(128)
</code>```

Seems like I should be specifying "utf-8" somewhere, I'm just not sure where...

Thanks!

答:
I assume that you use a Python 2 version, and that your input text contains non ASCII characters. The problem arises at str(x) which by default when x is a unicode string ends in x.encode('ascii')

You have 2 ways to solve this problem:

correctly encode the  unicode string in utf-8:

```<code>text_word_length = [len(x.encode('utf-8').split(" ")) for x in result_df['_text']]
</code>```

split the string as unicode:

```<code>text_word_length = [len(x.split(u" ")) for x in result_df['_text']]
</code>```

Title: Python 2.7: Trouble Encoding to UTF-8

Body:
I have a dataframe that has a column, _text, containing the text of an article.  I'm trying to get the length of the article for each row in my dataframe.  Here's my attempt:

from bs4 import BeautifulSoup
result_df['_text'] = [BeautifulSoup(text, "lxml").get_text() for text in result_df['_text']]

text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]

Unfortunately, I get this error:

    ---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-8-f6c8ab83a46f> in <module>()
----> 1 text_word_length = [len(str(x).split(" ")) for x in result_df['_text']]

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 231: ordinal not in range(128)

Seems like I should be specifying "utf-8" somewhere, I'm just not sure where...

Thanks!

Body:
I assume that you use a Python 2 version, and that your input text contains non ASCII characters. The problem arises at str(x) which by default when x is a unicode string ends in x.encode('ascii')

You have 2 ways to solve this problem:

correctly encode the  unicode string in utf-8:

text_word_length = [len(x.encode('utf-8').split(" ")) for x in result_df['_text']]

split the string as unicode:

text_word_length = [len(x.split(u" ")) for x in result_df['_text']]


问:
How to override CSS selector?
My page includes a legacy css file which defines a style for the :invalid psuedo-class. I want to use some of the styles from this file, but I do not want invalid inputs to be red by default, I want input fields to use the default styling for input fields defined in the legacy file.

legacy.css

```<code>input:invalid {
  background-color: #F00
}
</code>```

Is there a way to override the style defined in legacy.css, and force it to use some other style from the file? Is there a better option for approaching this?

my.css

```<code>input:invalid {
  // super input:valid
}
</code>```

答:
If your CSS is loaded after the legacy one, it will take priority, otherwise, just add !important to your style</p>

```<code>input:invalid {
  background-color: #FF00 !important
}
</code>```

Title: How to override CSS selector?

Body:
My page includes a legacy css file which defines a style for the :invalid psuedo-class. I want to use some of the styles from this file, but I do not want invalid inputs to be red by default, I want input fields to use the default styling for input fields defined in the legacy file.

legacy.css

input:invalid {
  background-color: #F00
}

Is there a way to override the style defined in legacy.css, and force it to use some other style from the file? Is there a better option for approaching this?

my.css

input:invalid {
  // super input:valid
}

Body:
If your CSS is loaded after the legacy one, it will take priority, otherwise, just add !important to your style

input:invalid {
  background-color: #FF00 !important
}


问:
Trigger anonymous function inside setInterval immediately
So I have a timer that looks like this

```<code>my_timer = setInterval(function(){
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}, 1000);
</code>```

And I want it to run immediately, and every second after that. I tried appending () to the end of the function, but that caused it to run only once (because it is not returning the function itself to the setInterval?). I then tried to return this; so that it would possibly return the function itself, but that did no good either. That was a random guess.

Is there any way I can get this to work without creating a named function? Thanks!

答:
Would this work for you?

```<code>function startItUp()
{
   bla();
   setInterval( bla, 1000);
}

function bla()
{
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}
</code>```

Hope this helps,

Body:
So I have a timer that looks like this

my_timer = setInterval(function(){
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}, 1000);

And I want it to run immediately, and every second after that. I tried appending () to the end of the function, but that caused it to run only once (because it is not returning the function itself to the setInterval?). I then tried to return this; so that it would possibly return the function itself, but that did no good either. That was a random guess.

Is there any way I can get this to work without creating a named function? Thanks!

Body:
Would this work for you?

function startItUp()
{
   bla();
   setInterval( bla, 1000);
}

function bla()
{
    do_something_amazing();
    do_more.stuff_here();
    var etc_etc = "foo" + bar;
}

Hope this helps,


问:
Gradle sync failed (.rawproto), failed to save settings
I've installed Android studio and created my first application from standard pattern. Now I have problems with opening it:

I opened idea.log and started to search by word 'fail'. Found:

```<code>    2017-06-14 19:56:31,148 [ 190717]   WARN - mponents.impl.stores.StoreUtil - Save settings failed
java.lang.RuntimeException: java.io.FileNotFoundException: C:\Program Files\Android\AndroidStudioProjects\HelloWorld\.idea\workspace.xml___jb_tmp___ (ϲ롧ᮮ ⡤ﲲ
    at com.intellij.util.lang.CompoundRuntimeException.throwIfNotEmpty(CompoundRuntimeException.java:151)
    at com.intellij.configurationStore.ComponentStoreImpl.save(ComponentStoreImpl.kt:166)
    at com.intellij.openapi.components.impl.stores.StoreUtil.save(StoreUtil.java:49)
    at com.intellij.openapi.project.impl.ProjectImpl.save(ProjectImpl.java:343)
    at com.intellij.ide.SaveAndSyncHandlerImpl.doSaveDocumentsAndProjectsAndApp(SaveAndSyncHandlerImpl.java:137)
    at com.intellij.ide.SaveAndSyncHandlerImpl.saveProjectsAndDocuments(SaveAndSyncHandlerImpl.java:125)
    at com.intellij.ide.SaveAndSyncHandlerImpl$2.lambda$onFrameDeactivated$0(SaveAndSyncHandlerImpl.java:94)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    at com.intellij.openapi.application.TransactionGuardImpl.access$300(TransactionGuardImpl.java:40)
    at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:113)
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:123)
    at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:109)
    at com.intellij.ide.SaveAndSyncHandlerImpl$2.onFrameDeactivated(SaveAndSyncHandlerImpl.java:92)
    at com.intellij.ide.FrameStateManagerImpl.fireDeactivationEvent(FrameStateManagerImpl.java:84)
    at com.intellij.ide.FrameStateManagerImpl.access$500(FrameStateManagerImpl.java:32)
    at com.intellij.ide.FrameStateManagerImpl$2.lambda$applicationDeactivated$0(FrameStateManagerImpl.java:70)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:222)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:378)
    at com.intellij.openapi.application.TransactionGuardImpl$6.run(TransactionGuardImpl.java:291)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:326)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:310)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:795)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:631)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:387)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.io.FileNotFoundException: C:\Program Files\Android\AndroidStudioProjects\HelloWorld\.idea\workspace.xml___jb_tmp___
</code>```

答: Problem was decided by upgrade</p>

Body:
I've installed Android studio and created my first application from standard pattern. Now I have problems with opening it:

I opened idea.log and started to search by word 'fail'. Found:

    2017-06-14 19:56:31,148 [ 190717]   WARN - mponents.impl.stores.StoreUtil - Save settings failed
java.lang.RuntimeException: java.io.FileNotFoundException: C:\Program Files\Android\AndroidStudioProjects\HelloWorld\.idea\workspace.xml___jb_tmp___ (ϲ롧ᮮ ⡤ﲲ
    at com.intellij.util.lang.CompoundRuntimeException.throwIfNotEmpty(CompoundRuntimeException.java:151)
    at com.intellij.configurationStore.ComponentStoreImpl.save(ComponentStoreImpl.kt:166)
    at com.intellij.openapi.components.impl.stores.StoreUtil.save(StoreUtil.java:49)
    at com.intellij.openapi.project.impl.ProjectImpl.save(ProjectImpl.java:343)
    at com.intellij.ide.SaveAndSyncHandlerImpl.doSaveDocumentsAndProjectsAndApp(SaveAndSyncHandlerImpl.java:137)
    at com.intellij.ide.SaveAndSyncHandlerImpl.saveProjectsAndDocuments(SaveAndSyncHandlerImpl.java:125)
    at com.intellij.ide.SaveAndSyncHandlerImpl$2.lambda$onFrameDeactivated$0(SaveAndSyncHandlerImpl.java:94)
    at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    at com.intellij.openapi.application.TransactionGuardImpl.access$300(TransactionGuardImpl.java:40)
    at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:113)
    at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:123)
    at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:109)
    at com.intellij.ide.SaveAndSyncHandlerImpl$2.onFrameDeactivated(SaveAndSyncHandlerImpl.java:92)
    at com.intellij.ide.FrameStateManagerImpl.fireDeactivationEvent(FrameStateManagerImpl.java:84)
    at com.intellij.ide.FrameStateManagerImpl.access$500(FrameStateManagerImpl.java:32)
    at com.intellij.ide.FrameStateManagerImpl$2.lambda$applicationDeactivated$0(FrameStateManagerImpl.java:70)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:222)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:378)
    at com.intellij.openapi.application.TransactionGuardImpl$6.run(TransactionGuardImpl.java:291)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:326)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:310)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:795)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:631)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:387)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: java.io.FileNotFoundException: C:\Program Files\Android\AndroidStudioProjects\HelloWorld\.idea\workspace.xml___jb_tmp___

Body: Problem was decided by upgrade


问:
Show the complete description of an example
In RSpec, how can we generate a string from an example, representing the current meta description of the current example?

Example:

```<code>RSpec.describe Api::V1::Public::Signin::ByEmailController, type: :controller do
  describe 'POST #create' do
    context 'when the provider is "email"' do
      context 'when there is a saved email' do
        context 'when the password is good' do
          it 'signs in' do
            expect(current_metadata_description).to eq 'Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in'
          end
        end
      end
    end
  end
end
</code>```

As we can see, the current meta description of the given example is:

Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in

Thanks.

Edit:

The current_metadata_description is not provided by RSpec. I just invented it to give an example of what I would like to have.

答:
Try to run rspec with --format option:

```<code>bundle exec rspec --format documentation
</code>```

Update:

I don't know any rspec method that would do that for you. One way I can think of is, write the spec description to a file while running the tests and then read the description from it in your custom current_metadata_description method. Here is a tutorial on Generating documentation from specs. Hope that helps!

Body:
In RSpec, how can we generate a string from an example, representing the current meta description of the current example?

Example:

RSpec.describe Api::V1::Public::Signin::ByEmailController, type: :controller do
  describe 'POST #create' do
    context 'when the provider is "email"' do
      context 'when there is a saved email' do
        context 'when the password is good' do
          it 'signs in' do
            expect(current_metadata_description).to eq 'Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in'
          end
        end
      end
    end
  end
end

As we can see, the current meta description of the given example is:

Api::V1::Public::Signin::ByEmailController POST #create when the provider is "email" when there is a saved email when the password is good signs in

Thanks.

Edit:

The current_metadata_description is not provided by RSpec. I just invented it to give an example of what I would like to have.

Body:
Try to run rspec with --format option:

bundle exec rspec --format documentation

Update:

I don't know any rspec method that would do that for you. One way I can think of is, write the spec description to a file while running the tests and then read the description from it in your custom current_metadata_description method. Here is a tutorial on Generating documentation from specs. Hope that helps!


问:
Convert timestamp to time and keep seconds, minutes and hour
I have a function to convert timestamp to real hour, minute and second, I would to keep the format like: hh:mm:ss even if it is only some minutes and seconds, I should get 00:10:32 instead of 10:32:

```<code>// format can be either : or blank
function toTime($timestamp, $format)
{
    $hours = floor($timestamp / 3600);
    $minutes = floor($timestamp % 3600 / 60);
    $seconds = $timestamp % 60;

            if($format == ':') {
                $hourDuration = sprintf('%02d:', $hours);
                //echo 'hour: '.$hourDuration.'<br />';
                $minDuration =  sprintf('%02d:', $minutes);
                //echo 'min: '.$minDuration.'<br />';
                $secDuration =  sprintf('%02d', $seconds);
                //echo 'sec: '.$secDuration.'<br />';
                $HourMinSec = $hourDuration.$minDuration.$secDuration;
            } else {
                $hourDuration = sprintf('%02d h', $hours);
                //echo 'hour: '.$hourDuration.'<br />';
                $minDuration =  sprintf('%02d m', $minutes);
                //echo 'min: '.$minDuration.'<br />';
                $secDuration =  sprintf('%02d s', $seconds);
                //echo 'sec: '.$secDuration.'<br />';
                $HourMinSec = '';
            }

            if($hourDuration > 0){
                $hourDuration = $hourDuration;
            } else {
                $hourDuration = '';
            }

            if($minDuration > 0){
                $minDuration = $minDuration;
            } else {
                $minDuration = '';
            }

            if($secDuration > 0){
                $secDuration = $secDuration;
            } else {
                $secDuration = '';
            }

    //$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
    $HourMinSec = $hourDuration.$minDuration.$secDuration;

    return $HourMinSec;
}
</code>```

This function is used to get a video timestamp like: 1508.7397460938, and I would like to sort out, how many hours, minutes and seconds are in that video

Thanks for your assistance

答:
I would have done it that way

```<code>function toTime($timestamp, $format)
    {
        $hours = floor($timestamp / 3600);
        $minutes = floor($timestamp % 3600 / 60);
        $seconds = $timestamp % 60;

                if($format == ':') {
                    $hourDuration = sprintf('%02d:', $hours);
                    //echo 'hour: '.$hourDuration.'<br />';
                    $minDuration =  sprintf('%02d:', $minutes);
                    //echo 'min: '.$minDuration.'<br />';
                    $secDuration =  sprintf('%02d', $seconds);
                    //echo 'sec: '.$secDuration.'<br />';
                    $HourMinSec = $hourDuration.$minDuration.$secDuration;
                } else {
                    $hourDuration = sprintf('%02d h', $hours);
                    //echo 'hour: '.$hourDuration.'<br />';
                    $minDuration =  sprintf('%02d m', $minutes);
                    //echo 'min: '.$minDuration.'<br />';
                    $secDuration =  sprintf('%02d s', $seconds);
                    //echo 'sec: '.$secDuration.'<br />';
                    $HourMinSec = '';
                }

                if($hourDuration > 0){
                    $hourDuration = $hourDuration;
                } else {
                    $hourDuration = ($format == ':' ? '00:' : '00 h');
                }

                if($minDuration > 0){
                    $minDuration = $minDuration;
                } else {
                    $minDuration = ($format == ':' ? '00:' : '00 m');
                }

                if($secDuration > 0){
                    $secDuration = $secDuration;
                } else {
                    $secDuration = '00';
                }

        //$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
        $HourMinSec = $hourDuration.$minDuration.$secDuration;

        return $HourMinSec;
    }
</code>```

In that case it would bring you the following result for adding

```<code>echo toTime(1508.7397460938);
Output --> 00 h25 m08 s
echo toTime(1508.7397460938,':');
Output --> 00:25:08
</code>```

The other variant is to use the php ready function gmdate by typing:

```<code>echo gmdate("H:i:s", 1508.7397460938);
</code>```

// Use that only if the amount of hours is less than 24 , that function would now show more than 24 hours and if so it would show inaccurate data.

Body:
I have a function to convert timestamp to real hour, minute and second, I would to keep the format like: hh:mm:ss even if it is only some minutes and seconds, I should get 00:10:32 instead of 10:32:

// format can be either : or blank
function toTime($timestamp, $format)
{
    $hours = floor($timestamp / 3600);
    $minutes = floor($timestamp % 3600 / 60);
    $seconds = $timestamp % 60;

            if($format == ':') {
                $hourDuration = sprintf('%02d:', $hours);
                //echo 'hour: '.$hourDuration.'
';
                $minDuration =  sprintf('%02d:', $minutes);
                //echo 'min: '.$minDuration.'
';
                $secDuration =  sprintf('%02d', $seconds);
                //echo 'sec: '.$secDuration.'
';
                $HourMinSec = $hourDuration.$minDuration.$secDuration;
            } else {
                $hourDuration = sprintf('%02d h', $hours);
                //echo 'hour: '.$hourDuration.'
';
                $minDuration =  sprintf('%02d m', $minutes);
                //echo 'min: '.$minDuration.'
';
                $secDuration =  sprintf('%02d s', $seconds);
                //echo 'sec: '.$secDuration.'
';
                $HourMinSec = '';
            }

            if($hourDuration > 0){
                $hourDuration = $hourDuration;
            } else {
                $hourDuration = '';
            }

            if($minDuration > 0){
                $minDuration = $minDuration;
            } else {
                $minDuration = '';
            }

            if($secDuration > 0){
                $secDuration = $secDuration;
            } else {
                $secDuration = '';
            }

    //$HourMinSec = $hourDuration.' '.$minDuration.' '.$secDuration;
    $HourMinSec = $hourDuration.$minDuration.$secDuration;

    return $HourMinSec;
}

This function is used to get a video timestamp like: 1508.7397460938, and I would like to sort out, how many hours, minutes and seconds are in that video

Thanks for your assistance

Body:
I would have done it that way

function toTime($timestamp, $format)
    {
        $hours = floor($timestamp / 3600);
        $minutes = floor($timestamp % 3600 / 60);
        $seconds = $timestamp % 60;

                if($format == ':') {
                    $hourDuration = sprintf('%02d:', $hours);
                    //echo 'hour: '.$hourDuration.'<br />';
                    $minDuration =  sprintf('%02d:', $minutes);
                    //echo 'min: '.$minDuration.'<br />';
                    $secDuration =  sprintf('%02d', $seconds);
                    //echo 'sec: '.$secDuration.'<br />';
                    $HourMinSec = $hourDuration.$minDuration.$secDuration;
                } else {
                    $hourDuration = sprintf('%02d h', $hours);
                    //echo 'hour: '.$hourDuration.'<br />';
                    $minDuration =  sprintf('%02d m', $minutes);
                    //echo 'min: '.$minDuration.'<br />';
                    $secDuration =  sprintf('%02d s', $seconds);
                    //echo 'sec: '.$secDuration.'<br />';
                    $HourMinSec = '';
                }

                if($hourDuration > 0){
                    $hourDuration = $hourDuration;
                } else {
                    $hourDuration = ($format == ':' ? '00:' : '00 h');
                }

                if($minDuration > 0){
                    $minDuration = $minDuration;
                } else {
                    $minDuration = ($format == ':' ? '00:' : '00 m');
                }

                if($secDuration > 0){
                    $secDuration = $secDuration;
                } else {
                    $secDuration = '00';
                }

        //$HourMinSec = $hourDuration.'&nbsp;'.$minDuration.'&nbsp;'.$secDuration;
        $HourMinSec = $hourDuration.$minDuration.$secDuration;

        return $HourMinSec;
    }

In that case it would bring you the following result for adding

echo toTime(1508.7397460938);
Output --> 00 h25 m08 s
echo toTime(1508.7397460938,':');
Output --> 00:25:08

The other variant is to use the php ready function gmdate by typing:

echo gmdate("H:i:s", 1508.7397460938);

// Use that only if the amount of hours is less than 24 , that function would now show more than 24 hours and if so it would show inaccurate data.


问:
Gsoap Http event callback
I downloaded gSoap and generated source code for wsdl. And I could connect to the server and send the request.

But I can't understand how I can catch http events like bytes sent, bytes recv.
I read this document http://www.cs.fsu.edu/~engelen/soapdoc2.html.

But I can't find what I need. I found function fsend. As I understand this function is being executed when we're sending a request to the server. Do I have to do something like this?

```<code>service.fsend = Custom;
</code>```

Where Custom is my callback?

I've found other callback is ffiltersend.
As I understand this function is being runned when request is sending.
I use it.
But I don't understand last parametr in this method is pointer to size_t.
When I get value from this pointer and devide by 2 I get count of my real bytes. Why?

答:
To obtain statistics on the number of bytes sent, received, and to log the inbound and outbound messages to a file system, use the "logging plugin" that comes with the gSOAP software.

First, register the plugin with:

```<code>#include "plugin/logging.h" // this file is in the gSOAP distro path
...
soap_register_plugin(soap, logging);
</code>```

Then use these functions to set the logging destinations for inbound and outbound messages:

```<code>soap_set_logging_inbound(struct soap*, FILE*);
soap_set_logging_outbound(struct soap*, FILE*);
</code>```

where the file descriptor passed as the second argument points to an open file that you can open and close before and after logging.  Use NULL as the second argument to disable logging.

To obtain stats, i.e. message size byte counts, use:

```<code>soap_get_logging_stats(struct soap*, size_t *sent, size_t *recv);
</code>```

where the second and third arguments will be updated by this call.

That's all there is too it.

If you want to use your own message handling callbacks then perhaps a good place to start is to learn from the plugin/logging.c file on how that is done. This file is short.

Title: Gsoap Http event callback

Body:
I downloaded gSoap and generated source code for wsdl. And I could connect to the server and send the request.

But I can't understand how I can catch http events like bytes sent, bytes recv.
I read this document http://www.cs.fsu.edu/~engelen/soapdoc2.html.

But I can't find what I need. I found function fsend. As I understand this function is being executed when we're sending a request to the server. Do I have to do something like this?

service.fsend = Custom;

Where Custom is my callback?

I've found other callback is ffiltersend.
As I understand this function is being runned when request is sending.
I use it.
But I don't understand last parametr in this method is pointer to size_t.
When I get value from this pointer and devide by 2 I get count of my real bytes. Why?

Body:
To obtain statistics on the number of bytes sent, received, and to log the inbound and outbound messages to a file system, use the "logging plugin" that comes with the gSOAP software.

First, register the plugin with:

#include "plugin/logging.h" // this file is in the gSOAP distro path
...
soap_register_plugin(soap, logging);

Then use these functions to set the logging destinations for inbound and outbound messages:

soap_set_logging_inbound(struct soap*, FILE*);
soap_set_logging_outbound(struct soap*, FILE*);

where the file descriptor passed as the second argument points to an open file that you can open and close before and after logging.  Use NULL as the second argument to disable logging.

To obtain stats, i.e. message size byte counts, use:

soap_get_logging_stats(struct soap*, size_t *sent, size_t *recv);

where the second and third arguments will be updated by this call.

That's all there is too it.

If you want to use your own message handling callbacks then perhaps a good place to start is to learn from the plugin/logging.c file on how that is done. This file is short.


Title: MySQL - subtracting certain rows of a table and presenting the results alongside other rows

Body:
I have been struggling with getting this query right for hours now. I have  a huge amount of data and I want to show just the departments with IDs 10,15,18 and 25. From here, I want to subtract the profits for each dept with ID 18 from 15, i.e. 15-18.

I filter the data with the following query:

SELECT * FROM deptTable WHERE ID IN(10,15,18,25) AND date = '2009-01-25'

dept ---------- date ---------------- ID ----------------- profit

UK ---------- 2009-01-25 ---------- 10 ---------------- 2000

Brazil ------- 2009-01-25 ---------- 10 ---------------- 1300

Japan-------  2009-01-25 --------- 10 ---------------- 2500

Spain-------  2009-01-25 ---------- 10 ---------------- 3200

UK ---------- 2009-01-25 ---------- 15 ---------------- 4000

Brazil ------- 2009-01-25 ---------- 15 ---------------- 1700

Japan-------  2009-01-25 ---------- 15 ---------------- 3500

Spain--------  2009-01-25 ---------- 15 --------------- 1200

UK ---------- 2009-01-25 ---------- 18 ---------------- 2500

Brazil ------- 2009-01-25 ---------- 18 ---------------- 1300

Japan-------  2009-01-25 --------- 18 ---------------- 2120

Spain-------  2009-01-25 ---------- 18 ---------------- 800

UK ---------- 2009-01-25 ---------- 25 ---------------- 3000

Brazil ------- 2009-01-25 ---------- 25 ---------------- 1850

Japan-------  2009-01-25 --------- 25 ---------------- 1580

Spain--------  2009-01-25 ---------- 25 --------------- 1070

What I basically want is to then subtract each row with ID 18 from rows with ID 15. Taking the UK as an example:

4000 - 2500 = 1500, doing the rest of the dept regions will give the desired result which is:

dept ---------- date ---------------- ID ----------------- profit

UK ---------- 2009-01-25 ---------- 10 ---------------- 2000

Brazil ------- 2009-01-25 ---------- 10 ---------------- 1300

Japan-------  2009-01-25 --------- 10 ----------------- 2500

Spain-------  2009-01-25 ---------- 10 ---------------- 3200

UK ---------- 2009-01-25 ---------- 15-18 ------------ 1500

Brazil ------- 2009-01-25 ---------- 15-18 ------------ 400

Japan-------  2009-01-25 ---------- 15-18 ----------- 1380

Spain--------  2009-01-25 ---------- 15-18 ----------- 400

UK ---------- 2009-01-25 ---------- 25 ---------------- 3000

Brazil ------- 2009-01-25 ---------- 25 ---------------- 1850

Japan-------  2009-01-25 ---------- 25 ---------------- 1580

Spain--------  2009-01-25 ---------- 25 --------------- 1070

2 points:

1. The calculated rows ID column doesn't have to read '15-18', I've just typed '15-18' to help explain the issue

2. The italics/bold are the only calculated rows, all other rows remain the same

Surely something like this is possible?

Thanks,

Body:
I think that something like this will work...

SELECT a.dept, a.date, IF(a.id=15,'15-18',a.id) AS id, IF(b.profit IS NULL,a.profit,a.profit-b.profit) AS profit
FROM deptTable a
LEFT JOIN deptTable b ON a.ID=15 AND b.ID=18 AND a.dept=b.dept
WHERE a.ID IN(10,15,25) AND a.date = '2009-01-25'

Tested result:

+--------+------------+-------+--------+
| dept   | date       | id    | profit |
+--------+------------+-------+--------+
| UK     | 2009-01-25 | 10    |   2000 |
| Brazil | 2009-01-25 | 10    |   1300 |
| JAPAN  | 2009-01-25 | 10    |   2500 |
| SPAIN  | 2009-01-25 | 10    |   3200 |
| UK     | 2009-01-25 | 15-18 |   1500 |
| Brazil | 2009-01-25 | 15-18 |    400 |
| JAPAN  | 2009-01-25 | 15-18 |   1380 |
| SPAIN  | 2009-01-25 | 15-18 |    400 |
| UK     | 2009-01-25 | 25    |   3000 |
| Brazil | 2009-01-25 | 25    |   1850 |
| JAPAN  | 2009-01-25 | 25    |   1580 |
| SPAIN  | 2009-01-25 | 25    |   1070 |
+--------+------------+-------+--------+


问:
JavaFX TableView bold whole row iff `message.isUnread()==true`
I am trying to replicate Gmail behavior in Javafx TableView. Row of new Unread message should be shown in bold. Here is what I was able to do so far:

I can change background of the whole row, and bold a cell, but can't bold the whole row.
How to explain Javafx to do this?

```<code>for each Cell cell in tableview:
    get Message m corresponding to row.
    String style = m.isUnread() ? "
    cell.setStyle("-fx-font-weight: 800" : "-fx-font-weight: 100")

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Message {
    final static public ObservableList<Message> data = FXCollections.observableArrayList(
            new Message("Bob", "Where are you?", true, true),
            new Message("Elise", "Payment", false, false),
            new Message("Charlie", "Read this book: 'Clean code'", true, true),
            new Message("Oscar", "Golf class tonight", true, false),
            new Message("Sam", "How is your TableView progress?", false, true),
            new Message("Alice", "Latte", true, true)
    );

    final private String  name;
    final private String  title;
    private boolean isUnread;
    private boolean isArchived;

    public Message(String name, String title, boolean isUnread, boolean isArchived) {
        this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
    }
    public String  getName()    { return name;    }
    public String  getTitle()  { return title;  }
    public boolean getIsUnread() { return isUnread; }
    public boolean getisArchived() { return isArchived; }

    public void setIsUnread(boolean isUnread) { this.isUnread = isUnread;     }
 }
</code>```

MyTable.java

```<code>import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;

public class MyTable extends Application {
    public static void main(String[] args) throws Exception { launch(args); }
    public void start(final Stage stage) throws Exception {
        stage.setTitle("Inbox");

        // create a table.
        TableView<Message> table = new TableView(Message.data);
        table.getColumns().addAll(makeStringColumn("Name", "name", 150), makeStringColumn("Title", "title", 300), makeBooleanColumn("New", "isUnread", 150));
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        table.setPrefHeight(250);

        stage.setScene(new Scene(table));
        stage.getScene().getStylesheets().add(getClass().getResource("message.css").toExternalForm());
        stage.show();

        // highlight the table rows depending upon whether we expect to get paid.
        int i = 0;
        for (Node n: table.lookupAll("TableRow")) {
            if (n instanceof TableRow) {
                TableRow row = (TableRow) n;
                if (table.getItems().get(i).getIsUnread()) {
                    row.getStyleClass().add("isReadRow");
                } else {
                    row.getStyleClass().add("isUnreadRow");
                }
                i++;
                if (i == table.getItems().size())
                    break;
            }
        }
    }

    private TableColumn<Message, String> makeStringColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, String> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, String>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, String>, TableCell<Message, String>>() {
            @Override public TableCell<Message, String> call(TableColumn<Message, String> soCalledFriendStringTableColumn) {
                return new TableCell<Message, String>() {
                    @Override public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item);
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }

    private TableColumn<Message, Boolean> makeBooleanColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, Boolean> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, Boolean>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, Boolean>, TableCell<Message, Boolean>>() {
            @Override public TableCell<Message, Boolean> call(TableColumn<Message, Boolean> soCalledFriendBooleanTableColumn) {
                return new TableCell<Message, Boolean>() {
                    @Override public void updateItem(final Boolean item, final boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item.toString());
                            this.getStyleClass().add(item ? "isUnreadCell" : "isReadCell");
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }
}
</code>```

(Message.css)

```<code>   .column-header-background         { -fx-background-color: azure;       }
   .isReadRow                       { -fx-background-color: palegreen;   }
   .isUnreadRow                       { -fx-background-color: yellow;       }
   .isReadCell                      { -fx-font-weight: 100 ; -fx-text-fill: darkgreen;}
   .isUnreadCell                     { -fx-font-weight: 800 ; -fx-text-fill: red;}
</code>```

答:
I'd recommend using PseudoClasses to denote read/unread rows. Use a rowFactory to set the PseudoClasses. Also using a property for the read/unread state would be preferable, since this allows you to update the rows without refreshing the whole table:

```<code>private final BooleanProperty unread;

public void setUnread(boolean value) {
    this.unread.set(value);
}

public boolean isUnread() {
    return this.unread.get();
}

public BooleanProperty unreadProperty() {
    return unread;
}

public Message(String name, String title, boolean isUnread, boolean isArchived) {
    this.name = name;
    this.title = title;
    this.unread = new SimpleBooleanProperty(isUnread);
    this.isArchived = isArchived;
}
</code>```

```<code>final PseudoClass read = PseudoClass.getPseudoClass("read");
final PseudoClass unread = PseudoClass.getPseudoClass("unread");
table.setRowFactory(tv -> new TableRow<Message>() {

    private void setState(boolean readState, boolean unreadState) {
        pseudoClassStateChanged(unread, unreadState);
        pseudoClassStateChanged(read, readState);
    }

    private void setUnreadState(boolean unreadState) {
        setState(!unreadState, unreadState);
    }

    private final ChangeListener<Boolean> unreadListener = (observable, oldValue, newValue) -> setUnreadState(newValue);

    @Override
    protected void updateItem(Message item, boolean empty) {
        // remove listener from old item
        Message oldItem = getItem();
        if (oldItem != null) {
            oldItem.unreadProperty().removeListener(unreadListener);
        }

        super.updateItem(item, empty);

        if (empty || item == null) {
            setState(false, false);
        } else {
            // set appropriate state & add listener
            setUnreadState(item.isUnread());
            item.unreadProperty().addListener(unreadListener);
        }
    }

});

stage.setScene(new Scene(table));
</code>```

.table-row-cell:read {
    -fx-background-color: palegreen;
}

.table-row-cell:unread {
    -fx-background-color: yellow;
}

.table-row-cell:read>.table-cell {
    -fx-font-weight: 100;
    -fx-text-fill: darkgreen;
}

.table-row-cell:unread>.table-cell {
    -fx-font-weight: 800;
    -fx-text-fill: red;
}
```

<p>Also make sure to set the <code>text</code> of <code>TableCell</code>s even if they become empty. Otherwise you could see "ghost content":</p>

```@Override
public void updateItem(String item, boolean empty) {
    super.updateItem(item, empty);
    if (item != null) {
        setText(item);
    } else {
        setText("");
    }
}
```

```@Override
public void updateItem(final Boolean item, final boolean empty) {
    super.updateItem(item, empty);
    if (item != null) {
        setText(item.toString());
    } else {
        setText("");
    }
}
```

Body:
I am trying to replicate Gmail behavior in Javafx TableView. Row of new Unread message should be shown in bold. Here is what I was able to do so far:

I can change background of the whole row, and bold a cell, but can't bold the whole row.
How to explain Javafx to do this?

for each Cell cell in tableview:
    get Message m corresponding to row.
    String style = m.isUnread() ? "
    cell.setStyle("-fx-font-weight: 800" : "-fx-font-weight: 100")

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

public class Message {
    final static public ObservableList<Message> data = FXCollections.observableArrayList(
            new Message("Bob", "Where are you?", true, true),
            new Message("Elise", "Payment", false, false),
            new Message("Charlie", "Read this book: 'Clean code'", true, true),
            new Message("Oscar", "Golf class tonight", true, false),
            new Message("Sam", "How is your TableView progress?", false, true),
            new Message("Alice", "Latte", true, true)
    );

    final private String  name;
    final private String  title;
    private boolean isUnread;
    private boolean isArchived;

    public Message(String name, String title, boolean isUnread, boolean isArchived) {
        this.name = name; this.title = title; this.isUnread = isUnread;this.isArchived = isArchived;
    }
    public String  getName()    { return name;    }
    public String  getTitle()  { return title;  }
    public boolean getIsUnread() { return isUnread; }
    public boolean getisArchived() { return isArchived; }

    public void setIsUnread(boolean isUnread) { this.isUnread = isUnread;     }
 }

MyTable.java

import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;

public class MyTable extends Application {
    public static void main(String[] args) throws Exception { launch(args); }
    public void start(final Stage stage) throws Exception {
        stage.setTitle("Inbox");

        // create a table.
        TableView<Message> table = new TableView(Message.data);
        table.getColumns().addAll(makeStringColumn("Name", "name", 150), makeStringColumn("Title", "title", 300), makeBooleanColumn("New", "isUnread", 150));
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        table.setPrefHeight(250);

        stage.setScene(new Scene(table));
        stage.getScene().getStylesheets().add(getClass().getResource("message.css").toExternalForm());
        stage.show();

        // highlight the table rows depending upon whether we expect to get paid.
        int i = 0;
        for (Node n: table.lookupAll("TableRow")) {
            if (n instanceof TableRow) {
                TableRow row = (TableRow) n;
                if (table.getItems().get(i).getIsUnread()) {
                    row.getStyleClass().add("isReadRow");
                } else {
                    row.getStyleClass().add("isUnreadRow");
                }
                i++;
                if (i == table.getItems().size())
                    break;
            }
        }
    }

    private TableColumn<Message, String> makeStringColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, String> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, String>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, String>, TableCell<Message, String>>() {
            @Override public TableCell<Message, String> call(TableColumn<Message, String> soCalledFriendStringTableColumn) {
                return new TableCell<Message, String>() {
                    @Override public void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item);
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }

    private TableColumn<Message, Boolean> makeBooleanColumn(String columnName, String propertyName, int prefWidth) {
        TableColumn<Message, Boolean> column = new TableColumn<>(columnName);
        column.setCellValueFactory(new PropertyValueFactory<Message, Boolean>(propertyName));
        column.setCellFactory(new Callback<TableColumn<Message, Boolean>, TableCell<Message, Boolean>>() {
            @Override public TableCell<Message, Boolean> call(TableColumn<Message, Boolean> soCalledFriendBooleanTableColumn) {
                return new TableCell<Message, Boolean>() {
                    @Override public void updateItem(final Boolean item, final boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null) {
                            setText(item.toString());
                            this.getStyleClass().add(item ? "isUnreadCell" : "isReadCell");
                        }
                    }
                };
            }
        });
        column.setPrefWidth(prefWidth);
        column.setSortable(false);
        return column;
    }
}

(Message.css)

   .column-header-background         { -fx-background-color: azure;       }
   .isReadRow                       { -fx-background-color: palegreen;   }
   .isUnreadRow                       { -fx-background-color: yellow;       }
   .isReadCell                      { -fx-font-weight: 100 ; -fx-text-fill: darkgreen;}
   .isUnreadCell                     { -fx-font-weight: 800 ; -fx-text-fill: red;}

Body:
I'd recommend using PseudoClasses to denote read/unread rows. Use a rowFactory to set the PseudoClasses. Also using a property for the read/unread state would be preferable, since this allows you to update the rows without refreshing the whole table:

private final BooleanProperty unread;

public void setUnread(boolean value) {
    this.unread.set(value);
}

public boolean isUnread() {
    return this.unread.get();
}

public BooleanProperty unreadProperty() {
    return unread;
}

public Message(String name, String title, boolean isUnread, boolean isArchived) {
    this.name = name;
    this.title = title;
    this.unread = new SimpleBooleanProperty(isUnread);
    this.isArchived = isArchived;
}

final PseudoClass read = PseudoClass.getPseudoClass("read");
final PseudoClass unread = PseudoClass.getPseudoClass("unread");
table.setRowFactory(tv -> new TableRow<Message>() {

    private void setState(boolean readState, boolean unreadState) {
        pseudoClassStateChanged(unread, unreadState);
        pseudoClassStateChanged(read, readState);
    }

    private void setUnreadState(boolean unreadState) {
        setState(!unreadState, unreadState);
    }

    private final ChangeListener<Boolean> unreadListener = (observable, oldValue, newValue) -> setUnreadState(newValue);

    @Override
    protected void updateItem(Message item, boolean empty) {
        // remove listener from old item
        Message oldItem = getItem();
        if (oldItem != null) {
            oldItem.unreadProperty().removeListener(unreadListener);
        }

        super.updateItem(item, empty);

        if (empty || item == null) {
            setState(false, false);
        } else {
            // set appropriate state & add listener
            setUnreadState(item.isUnread());
            item.unreadProperty().addListener(unreadListener);
        }
    }

});

stage.setScene(new Scene(table));

.table-row-cell:read {
    -fx-background-color: palegreen;
}

.table-row-cell:unread {
    -fx-background-color: yellow;
}

.table-row-cell:read>.table-cell {
    -fx-font-weight: 100;
    -fx-text-fill: darkgreen;
}

.table-row-cell:unread>.table-cell {
    -fx-font-weight: 800;
    -fx-text-fill: red;
}

Also make sure to set the text of TableCells even if they become empty. Otherwise you could see "ghost content":

@Override
public void updateItem(String item, boolean empty) {
    super.updateItem(item, empty);
    if (item != null) {
        setText(item);
    } else {
        setText("");
    }
}

@Override
public void updateItem(final Boolean item, final boolean empty) {
    super.updateItem(item, empty);
    if (item != null) {
        setText(item.toString());
    } else {
        setText("");
    }
}


问:
How to match payload in POST request
I've got a GET request like this:

```<code><FORM action='vieweto0.php' method='POST'>
  <SELECT name='ID_Profil'>
    <OPTION value=3> blank3</OPTION>
    <OPTION value=2> blank2</OPTION>
    <OPTION value=4>blank4</OPTION>
  </SELECT>
  <br><input type='submit' type=hidden name='OK' value='choose this one'>
</FORM>
</code>```

How my POST request should look like if I want to choose OPTION 'blank4'?

Where I can read more about POST request like this?

答: You can use this $_POST['ID_Profil'];</p>

Title: How to match payload in POST request

Body:
I've got a GET request like this:

<FORM action='vieweto0.php' method='POST'>
  <SELECT name='ID_Profil'>
    <OPTION value=3> blank3</OPTION>
    <OPTION value=2> blank2</OPTION>
    <OPTION value=4>blank4</OPTION>
  </SELECT>

<input type='submit' type=hidden name='OK' value='choose this one'>
</FORM>

How my POST request should look like if I want to choose OPTION 'blank4'?

Where I can read more about POST request like this?

Body: You can use this $_POST['ID_Profil'];