问:
Why use (t1-t2)>(1U<<31) instead of pure comparison?
I get the code from the old project:

```<code>inline bool timer_timestamp_less(uint32_t t1,uint32_t t2){
        return (t1-t2)>(1U<<31);
}
</code>```

somewhere:

```<code> if(!timer_timestamp_less(t1,t2)) ..
</code>```

After a headache, I understand the code is equivalent

```<code>if(t1>t2)...
</code>```

My predecessor has code while lacking cafe. Or do I think too simple?

答:
No your refactoring doesn't recover the same result in all cases: if(!timer_timestamp_less(t1, t2)) is nearly the same as if(t1 > t2).

The original implementation appears to be relying on the well-defined wraparound behaviour for the expression t1 - t2, which will inject 1 into the most significant bit for the case where t2 is greater than t1, and neither t1 nor t2 have that original bit set to 1. (In the latter case the behaviour is much more complicated.)

For values of t1 and t2 in the range [0, 231 - 1], the equivalent expression is, in fact, !(t1 < t2). Currently the way you have it, the expressions differ for the case where t1 and t2 are equal:

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

inline bool timer_timestamp_less_1(uint32_t t1,uint32_t t2){
    return (t1-t2)>(1U<<31);
}

inline bool timer_timestamp_less_2(uint32_t t1,uint32_t t2){
    return (t1 < t2);
}

int main(){
    // Equivalent
    cout << !timer_timestamp_less_1(1, 2) << endl; // 0
    cout << !timer_timestamp_less_2(1, 2) << endl; // 0
    // Not Equivalent
    cout << !timer_timestamp_less_1(-1, 2) << endl; // 0
    cout << !timer_timestamp_less_2(-1, 2) << endl; // 1
}
</code>```

Code: https://ideone.com/yocmS2

Body:
I get the code from the old project:

inline bool timer_timestamp_less(uint32_t t1,uint32_t t2){
        return (t1-t2)>(1U<<31);
}

somewhere:

 if(!timer_timestamp_less(t1,t2)) ..

After a headache, I understand the code is equivalent

if(t1>t2)...

My predecessor has code while lacking cafe. Or do I think too simple?

Body:
No your refactoring doesn't recover the same result in all cases: if(!timer_timestamp_less(t1, t2)) is nearly the same as if(t1 > t2).

The original implementation appears to be relying on the well-defined wraparound behaviour for the expression t1 - t2, which will inject 1 into the most significant bit for the case where t2 is greater than t1, and neither t1 nor t2 have that original bit set to 1. (In the latter case the behaviour is much more complicated.)

For values of t1 and t2 in the range [0, 231 - 1], the equivalent expression is, in fact, !(t1 < t2). Currently the way you have it, the expressions differ for the case where t1 and t2 are equal:

#include <iostream>
using namespace std;

inline bool timer_timestamp_less_1(uint32_t t1,uint32_t t2){
    return (t1-t2)>(1U<<31);
}

inline bool timer_timestamp_less_2(uint32_t t1,uint32_t t2){
    return (t1 < t2);
}

int main(){
    // Equivalent
    cout << !timer_timestamp_less_1(1, 2) << endl; // 0
    cout << !timer_timestamp_less_2(1, 2) << endl; // 0
    // Not Equivalent
    cout << !timer_timestamp_less_1(-1, 2) << endl; // 0
    cout << !timer_timestamp_less_2(-1, 2) << endl; // 1
}

Code: https://ideone.com/yocmS2


来源: stackexchange

问:
How to access the local Django webserver from outside world
I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver.  If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked.

I realize the Django webserver is not a production server, but it's important for me for testing purposes to be able to access it from the outside world -- i.e. not from a web browser on the server, but from a different computer.

I tried:

```<code>http://mywebserver:port_django_runs_on
</code>```

but it did not work.  I also tried using the IP instead (based on ifconfig) to access:

```<code>http://myipaddress:port_django_runs_on
</code>```

which did not work either.

The web server is running so it must be accessible from the outside, I'm just not sure how.  I am running Linux with Apache, though I have not configured Django with Apache.

Any ideas on how to do this?

答:
just do this:

```<code>python manage.py runserver 0:8000
</code>```

by the above command you are actually binding it to the external IP address.
so now when you access your IP address with the port number, you will be able to access it in the browser without any problem.

just type in the following in the browser address bar:

```<code><your ip address>:8000
</code>```

eg:

```<code>192.168.1.130:8000
</code>```

you may have to edit the settings.py
add the following in the settings.py in the last line:

```<code>ALLOWED_HOSTS = ['*']
</code>```

hope this will help...

ContentLicense: CC BY-SA 3.0

Body:
I followed the instructions here to run Django using the built-in webserver and was able to successfully run it using python manage.py runserver.  If I access 127.0.0.1:port locally from the webserver, I get the Django page indicating it worked.

I realize the Django webserver is not a production server, but it's important for me for testing purposes to be able to access it from the outside world -- i.e. not from a web browser on the server, but from a different computer.

I tried:

http://mywebserver:port_django_runs_on

but it did not work.  I also tried using the IP instead (based on ifconfig) to access:

http://myipaddress:port_django_runs_on

which did not work either.

The web server is running so it must be accessible from the outside, I'm just not sure how.  I am running Linux with Apache, though I have not configured Django with Apache.

Any ideas on how to do this?

Body:
just do this:

python manage.py runserver 0:8000

by the above command you are actually binding it to the external IP address.
so now when you access your IP address with the port number, you will be able to access it in the browser without any problem.

just type in the following in the browser address bar:

<your ip address>:8000

eg:

192.168.1.130:8000

you may have to edit the settings.py
add the following in the settings.py in the last line:

ALLOWED_HOSTS = ['*']

hope this will help...


问:
Responsive Table layout for different size screen android
When I am try to develop a simple table layout it's occur a problem. The layout is works fine for big screen. But when I'm use that in small phone then the problem create. The full rows aren't visible.

Can anyone help me out? I just want to make a simple table layout like that:

here what I made xml layout

```<code>               <TableLayout
                android:layout_below="@+id/jonosonkha"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:stretchColumns="5">
                <TableRow>
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="পরিবার"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="20sp"
                        android:text="পুরুষ"
                        android:gravity="left"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="মহিলা"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="20sp"
                        android:text="গড় সদস্য"
                        android:gravity="left"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="20sp"
                        android:text="ঘনত্ব/কি.মি"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>

                <TableRow
                    android:layout_marginTop="2dp"
                    >
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="৮৯৮৬৩"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="16sp"
                        android:text="২০৫০৭৫"
                        android:gravity="center"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="২০৯১১৩"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="16sp"
                        android:text="৪.৫৪"
                        android:gravity="center"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="16sp"
                        android:text="২১৩৮"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>
            </TableLayout>
</code>```

It's works fine for big screen but the problem is some of rows are covered by the small screen. Any solution please.

答:
You should define the width attribute of the table rows, like:

```<code><TableRow
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
</code>```

and the weight attribute of all the Textviews:

```<code><TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:textColor="#000"
    android:background="#ffea00"
    android:textSize="20sp"
    android:text="পরিবার"
    android:paddingLeft="5dp" />
</code>```

Body:
When I am try to develop a simple table layout it's occur a problem. The layout is works fine for big screen. But when I'm use that in small phone then the problem create. The full rows aren't visible.

Can anyone help me out? I just want to make a simple table layout like that:

here what I made xml layout

               <TableLayout
                android:layout_below="@+id/jonosonkha"
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:stretchColumns="5">
                <TableRow>
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="পরিবার"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="20sp"
                        android:text="পুরুষ"
                        android:gravity="left"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="20sp"
                        android:text="মহিলা"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="20sp"
                        android:text="গড় সদস্য"
                        android:gravity="left"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="20sp"
                        android:text="ঘনত্ব/কি.মি"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>

                <TableRow
                    android:layout_marginTop="2dp"
                    >
                    <TextView
                        android:textColor="#000"
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="৮৯৮৬৩"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textColor="#fff"
                        android:textSize="16sp"
                        android:text="২০৫০৭৫"
                        android:gravity="center"
                        android:paddingLeft="5dp"/>
                    <TextView
                        android:background="#ffea00"
                        android:textSize="16sp"
                        android:text="২০৯১১৩"
                        android:textColor="#000"
                        android:gravity="center"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#000"
                        android:textSize="16sp"
                        android:text="৪.৫৪"
                        android:gravity="center"
                        android:textColor="#fff"
                        android:paddingLeft="5dp" />
                    <TextView
                        android:background="#ffea00"
                        android:textColor="#000"
                        android:textSize="16sp"
                        android:text="২১৩৮"
                        android:gravity="left"
                        android:paddingLeft="5dp" />
                </TableRow>
            </TableLayout>

It's works fine for big screen but the problem is some of rows are covered by the small screen. Any solution please.

Body:
You should define the width attribute of the table rows, like:

<TableRow
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

and the weight attribute of all the Textviews:

<TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:textColor="#000"
    android:background="#ffea00"
    android:textSize="20sp"
    android:text="পরিবার"
    android:paddingLeft="5dp" />


问:
Actionscript - Obtain the name of the current function
I want to get the name of a function from inside that function. e.g.:

```<code>function blah() {
    //I want to get the string "blah" here, from the function's name
}
</code>```

Or at least the Function object?

答:
Use arguments.callee to get a reference to the current function.

I you want to get the function name, it is a bit trickier: All functions are treated as method closures (pieces of code which can be passed around as an argument), so they do not own a reference to an enclosing class type, nor do they have a "current name".

However, if (and only if) the method is public, and you want to get the method name from the class declaration of an instance object containing the method, you can use describeType:

```<code>public function someFunction() : void {
    var callee:Function = arguments.callee;
    trace (getFunctionName(callee, this)); // ==> someFunction
}

private function someOtherFunction() : void {
    var callee:Function = arguments.callee;
    trace (getFunctionName(callee, this)); // ==> not found
}

private function getFunctionName (callee:Function, parent:Object):String {
    for each ( var m:XML in describeType(parent)..method) {
        if ( parent[m.@name] == callee) return m.@name;
    }
    return "not found";
}
</code>```

Note that this would not work when you call someFunction() from a constructor, because the object is not fully instantiated - describeType(this) in a constructor would cause a compilation error.

ContentLicense: CC BY-SA 2.5

Body:
I want to get the name of a function from inside that function. e.g.:

function blah() {
    //I want to get the string "blah" here, from the function's name
}

Or at least the Function object?

Body:
Use arguments.callee to get a reference to the current function.

I you want to get the function name, it is a bit trickier: All functions are treated as method closures (pieces of code which can be passed around as an argument), so they do not own a reference to an enclosing class type, nor do they have a "current name".

However, if (and only if) the method is public, and you want to get the method name from the class declaration of an instance object containing the method, you can use describeType:

public function someFunction() : void {
    var callee:Function = arguments.callee;
    trace (getFunctionName(callee, this)); // ==> someFunction
}

private function someOtherFunction() : void {
    var callee:Function = arguments.callee;
    trace (getFunctionName(callee, this)); // ==> not found
}

private function getFunctionName (callee:Function, parent:Object):String {
    for each ( var m:XML in describeType(parent)..method) {
        if ( parent[m.@name] == callee) return m.@name;
    }
    return "not found";
}

Note that this would not work when you call someFunction() from a constructor, because the object is not fully instantiated - describeType(this) in a constructor would cause a compilation error.


问:
HttpWebRequest.GetResponse() keeps getting timed out
i wrote a simple C# function to retrieve trade history from MtGox with following API call:

```<code>https://data.mtgox.com/api/1/BTCUSD/trades?since=<trade_id>
</code>```

documented here: https://en.bitcoin.it/wiki/MtGox/API/HTTP/v1#Multi_currency_trades

here's the function:

```<code>string GetTradesOnline(Int64 tid)
{
    Thread.Sleep(30000);

    // communicate
    string url = "https://data.mtgox.com/api/1/BTCUSD/trades?since=" + tid.ToString();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());

    string json = reader.ReadToEnd();
    reader.Close();
    reader.Dispose();
    response.Close();

    return json;
}
</code>```

i'm starting at tid=0 (trade id) to get the data (from the very beginning). for each request, i receive a response containing 1000 trade details. i always send the trade id from the previous response for the next request. it works fine for exactly 4 requests & responses. but after that, the following line throws a "System.Net.WebException", saying that "The operation has timed out":

```<code>HttpWebResponse response = (HttpWebResponse)request.GetResponse();
</code>```

here are the facts:

catching the exception and retying keeps causing the same exception

the default HttpWebRequest .Timeout and .ReadWriteTimeout are already high enough (over a minute)

changing HttpWebRequest.KeepAlive to false didn't solve anything either

it seems to always work in the browser even while the function is failing

it has no problems retrieveing the response from https://www.google.com

the amount of successful responses before the exceptions varies from day to day (but browser always works)

starting at the trade id that failed last time causes the exception immediately

calling this function from the main thread instead still caused the exception

running it on a different machine didn't work

running it from a different IP didn't work

increasing Thread.Sleep inbetween requests does not help

any ideas of what could be wrong?

答: For what it's worth, I was experiencing the same issues with timeouts every time I used it, even though calls went through to the server I was calling. The problem in my case was that I had Expect set to application/json, when that wasn't what the server was returning.</p>

Body:
i wrote a simple C# function to retrieve trade history from MtGox with following API call:

https://data.mtgox.com/api/1/BTCUSD/trades?since=<trade_id>

documented here: https://en.bitcoin.it/wiki/MtGox/API/HTTP/v1#Multi_currency_trades

here's the function:

string GetTradesOnline(Int64 tid)
{
    Thread.Sleep(30000);

    // communicate
    string url = "https://data.mtgox.com/api/1/BTCUSD/trades?since=" + tid.ToString();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());

    string json = reader.ReadToEnd();
    reader.Close();
    reader.Dispose();
    response.Close();

    return json;
}

i'm starting at tid=0 (trade id) to get the data (from the very beginning). for each request, i receive a response containing 1000 trade details. i always send the trade id from the previous response for the next request. it works fine for exactly 4 requests & responses. but after that, the following line throws a "System.Net.WebException", saying that "The operation has timed out":

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

here are the facts:

catching the exception and retying keeps causing the same exception

the default HttpWebRequest .Timeout and .ReadWriteTimeout are already high enough (over a minute)

changing HttpWebRequest.KeepAlive to false didn't solve anything either

it seems to always work in the browser even while the function is failing

it has no problems retrieveing the response from https://www.google.com

the amount of successful responses before the exceptions varies from day to day (but browser always works)

starting at the trade id that failed last time causes the exception immediately

calling this function from the main thread instead still caused the exception

running it on a different machine didn't work

running it from a different IP didn't work

increasing Thread.Sleep inbetween requests does not help

any ideas of what could be wrong?


问:
How to stretch the table to fill all available space
This question might be simple, but I cannot find an answer.

I have the following html:

```<code><div>
  some text
  <div>
    <table>
        <tr><td>
            Test
        </tr>
    </table>
  </div>
</div>
</code>```

and css:

```<code>body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}

table {
    height: 100%;
    margin: 0 auto;
    background: red;
}
</code>```

How can I stretch the table vertically without change of the height property of div? I want the table to have height: 100% but it does not work because the outer containers do not have a fixed height (as I understand).

http://jsfiddle.net/8qedxug9/

答:
If an HTML element's default width and height is relative to its parent. So in this instance, the table is 100% of the height of its parent Div element. The Div that the table is in will therefore, also need to have a height of 100%. </p>

<p>In your Fiddle, adding a 100% height to all div's makes the div stretch to 100% of the body height, and thus the table stretch to 100% height also: </p>

```<code>body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}
div {
    height: 100%;
}

table {
    height: 100%;
    margin: 0 auto;
    background: red;
}

td {
    vertical-align: top;
}
</code>```

Body:
This question might be simple, but I cannot find an answer.

I have the following html:

  some text

            Test

and css:

body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}

table {
    height: 100%;
    margin: 0 auto;
    background: red;
}

How can I stretch the table vertically without change of the height property of div? I want the table to have height: 100% but it does not work because the outer containers do not have a fixed height (as I understand).

http://jsfiddle.net/8qedxug9/

Body:
If an HTML element's default width and height is relative to its parent. So in this instance, the table is 100% of the height of its parent Div element. The Div that the table is in will therefore, also need to have a height of 100%.

In your Fiddle, adding a 100% height to all div's makes the div stretch to 100% of the body height, and thus the table stretch to 100% height also:

body,html {
    height: 100%;
    width: 100%;
    margin: 0;
}
div {
    height: 100%;
}

table {
    height: 100%;
    margin: 0 auto;
    background: red;
}

td {
    vertical-align: top;
}


问:
v-if not rendering when state changes in a method
I'm using vue for the first time and so for I'm satisfied with what it can do. I have a problem though, I have a method in my vue instance that does a query like so :

var vm = new Vue({
    el: "#app",
    data: {
        search: "",
        results: [],
        loading: false,
    },
    methods: {
        find: function(event) {
            this.loading = true;
            var siret = this.search.length > 9;
            var ep = this.$resource('/api/v1/.../{id}');
            ep.get({id: this.search, limit: 100}).then(function(response) {
                this.results = response.data;
            }, function(response) {
                // error handling
            });
            this.loading = false;
        }
    }
});
```

<p>Now in my HTML I have something like this :</p>

<pre class="lang-html prettyprint-override"><code><div v-show="loading" style="width:100%;" class="loader"></div>
</code>```

Thing is, when I'm in the method, the state isn't instantly taken into account and is only rendered when exiting the method. What could I do so my loader appears as soon as this method is called and hidden when the method returns ?

To clarify what I meant :
If I modify the state of loader in the method to true, it displays the loader correctly. But if I modify it to true at the start of the method and set it back to false at the end of the method, I'd expect the loader to display for the time the method executes and then disapear. But it doesn't display at all. As if the state and the rendering was only rendered outside the method and not inside.

EDIT

I did not realize the ajax request was actually returning a promise, thus the method took only a few ms, not enough to see the loader. The problem was fixed by simply using this.loading = false inside the promise.

答:
Use an arrow function in the success callback of your ajax request for this to represent the correct vue instance

```<code>ep.get({id: this.search, limit: 100}).then((response) => {
            this.results = response.data;
        }, function(response) {
            // error handling
        });
</code>```

this inside your success callback is not pointing towards the vue instance that's why you cannot access the date of properties and mutate them.

Arrow functions bind the value of this lexically pointing the correct vue instance.

Or use the concept of closure by creating a var self = this inside your method and use self  inside the success callback

```<code>methods: {
    find: function(event) {
        var self = this;
        this.loading = true;
        var siret = this.search.length > 9;
        var ep = this.$resource('/api/v1/.../{id}');
        ep.get({id: this.search, limit: 100}).then(function(response) {
            self.results = response.data;
            self.loading = false;
        }, function(response) {
            // error handling
        });

    }
}
</code>```

Body:
I'm using vue for the first time and so for I'm satisfied with what it can do. I have a problem though, I have a method in my vue instance that does a query like so :

var vm = new Vue({
    el: "#app",
    data: {
        search: "",
        results: [],
        loading: false,
    },
    methods: {
        find: function(event) {
            this.loading = true;
            var siret = this.search.length > 9;
            var ep = this.$resource('/api/v1/.../{id}');
            ep.get({id: this.search, limit: 100}).then(function(response) {
                this.results = response.data;
            }, function(response) {
                // error handling
            });
            this.loading = false;
        }
    }
});

Now in my HTML I have something like this :

Thing is, when I'm in the method, the state isn't instantly taken into account and is only rendered when exiting the method. What could I do so my loader appears as soon as this method is called and hidden when the method returns ?

To clarify what I meant :
If I modify the state of loader in the method to true, it displays the loader correctly. But if I modify it to true at the start of the method and set it back to false at the end of the method, I'd expect the loader to display for the time the method executes and then disapear. But it doesn't display at all. As if the state and the rendering was only rendered outside the method and not inside.

EDIT

I did not realize the ajax request was actually returning a promise, thus the method took only a few ms, not enough to see the loader. The problem was fixed by simply using this.loading = false inside the promise.

Body:
Use an arrow function in the success callback of your ajax request for this to represent the correct vue instance

ep.get({id: this.search, limit: 100}).then((response) => {
            this.results = response.data;
        }, function(response) {
            // error handling
        });

this inside your success callback is not pointing towards the vue instance that's why you cannot access the date of properties and mutate them.

Arrow functions bind the value of this lexically pointing the correct vue instance.

Or use the concept of closure by creating a var self = this inside your method and use self  inside the success callback

methods: {
    find: function(event) {
        var self = this;
        this.loading = true;
        var siret = this.search.length > 9;
        var ep = this.$resource('/api/v1/.../{id}');
        ep.get({id: this.search, limit: 100}).then(function(response) {
            self.results = response.data;
            self.loading = false;
        }, function(response) {
            // error handling
        });

    }
}


问:
DB connection pool in Qt
I have Qt application which has DatabaseService singleton with only one QSqlDatabase instance, and many threads which should to use this instance of QSqlDatabase, mutex is locked when some thread uses instance of QSqlDatabase. But I understand that this isn't best pattern for this task.

Should I use some kind of DB connection pool here or something like this? And how can I implement it in Qt?

Please provide some examples.

UPD:

A class whose instance will already have its own thread, there will be multiple instances of this class:

.cpp:

```<code>//...

QFuture<QMap<QString, QString>> future = QtConcurrent::run(DatabaseService::executeQuery, sqlCommand);

future.waitForFinished();

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

DatabaseService:

.h:

```<code>class DatabaseService
{
public:
    //...
    static QMap<QString, QString> executeQuery(QString command);

private:
    static QThreadStorage<QSqlDatabase> mDatabasePool;
    static QSqlDatabase getDatabase();

};
</code>```

.cpp:

```<code>//...
QThreadStorage<QSqlDatabase> DatabaseService::mDatabasePool;

QSqlDatabase DatabaseService::getDatabase()
{
    if(DatabaseService::mDatabasePool.hasLocalData()) {
        return DatabaseService::mDatabasePool.localData();
    } else {
        auto database = QSqlDatabase::addDatabase("QPSQL", QUuid::createUuid().toString());
        database.setHostName("hostName");
        database.setDatabaseName("databaseName");
        database.setUserName("user");
        database.setPassword("password");
        DatabaseService::mDatabasePool.setLocalData(database);
        return database;
    }
}

QMap<QString,QString> DatabaseService::executeQuery(QString command){

    QSqlQuery query (DatabaseService::getDatabase());
    query.exec(command);

    //...

    return result;
}

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

UPD 2:

main.cpp:

```<code>int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;

    server.listen(QHostAddress::Any, 1234);

    return a.exec();
}
</code>```

myserver.h:

```<code>class MyServer : public QTcpServer
{
    Q_OBJECT

    explicit MyServer(QObject *parent = 0);
    ~MyServer();

protected:
    void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;

signals:
    void stopAll();
};
</code>```

myserver.cpp:

```<code>MyServer::MyServer(QObject *parent) : QTcpServer(parent)
{

}

MyServer::~MyServer(){
    emit stopAll();
}

void MyServer::incomingConnection(qintptr socketDescriptor){
    QThread* clientThread = new QThread;
    MyClient *client = new MyClient(socketDescriptor, this);

    client->moveToThread(clientThread);

    connect(clientThread, SIGNAL(started()), client, SLOT(process()));

    connect(client, SIGNAL(finished()), clientThread, SLOT(quit()));
    connect(this, SIGNAL(stopAll()), client, SLOT(stopFromServer()));
    connect(client, SIGNAL(finished()), client, SLOT(deleteLater()));
    connect(clientThread, SIGNAL(finished()), clientThread, SLOT(deleteLater()));

    clientThread->start();
}
</code>```

myclient.h:

```<code>class MyClient : public QObject
{
    Q_OBJECT
public:
    explicit MyClient(int socketDescriptor, MyServer *server);
    ~MyClient();

private:
    QSslSocket* socket = NULL;

public slots:
    void process();
}
</code>```

myclient.cpp:

```<code>void MyClient::process(){
    //typical connection things
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(ready()));
}

void MyClient::ready(){
    connect(socket,SIGNAL(readyRead()),this, SLOT(newData()));
}
</code>```

答:
I have made a software also using database connection. I don't use QThread on my application but use QFuture and the thread will take from global thread pool (normaly the number of thread pool will be the number of the CPU thread).

And when accessing the database, each pool will has its own QSqlDatabase. I am using QThreadStorage as the storage of QSqlDatabase.

```<code>static QThreadStorage<QSqlDatabase> mDatabasePool;
....
QSqlDatabase Db::getDatabase()
{
    if(mDatabasePool.hasLocalData()) {
        return mDatabasePool.localData();
    } else {
        auto database = QSqlDatabase::addDatabase(SQLDRIVERNAME[DBTYPE], QUuid::createUuid().toString());
        mDatabasePool.setLocalData(database);
        return database;
    }
}
</code>```

So the database connection will only created when the thread does not has the connection.

For full sample project you can check on my project :https://github.com/apinprastya/sultan. The database is inside the libdb and the worker QFuture is in libserver. You can use it as reference. But I am not sure if my design is suitable for you.

Title: DB connection pool in Qt

Body:
I have Qt application which has DatabaseService singleton with only one QSqlDatabase instance, and many threads which should to use this instance of QSqlDatabase, mutex is locked when some thread uses instance of QSqlDatabase. But I understand that this isn't best pattern for this task.

Should I use some kind of DB connection pool here or something like this? And how can I implement it in Qt?

Please provide some examples.

UPD:

A class whose instance will already have its own thread, there will be multiple instances of this class:

.cpp:

//...

QFuture<QMap<QString, QString>> future = QtConcurrent::run(DatabaseService::executeQuery, sqlCommand);

future.waitForFinished();

//...

DatabaseService:

.h:

class DatabaseService
{
public:
    //...
    static QMap<QString, QString> executeQuery(QString command);

private:
    static QThreadStorage<QSqlDatabase> mDatabasePool;
    static QSqlDatabase getDatabase();

};

.cpp:

//...
QThreadStorage<QSqlDatabase> DatabaseService::mDatabasePool;

QSqlDatabase DatabaseService::getDatabase()
{
    if(DatabaseService::mDatabasePool.hasLocalData()) {
        return DatabaseService::mDatabasePool.localData();
    } else {
        auto database = QSqlDatabase::addDatabase("QPSQL", QUuid::createUuid().toString());
        database.setHostName("hostName");
        database.setDatabaseName("databaseName");
        database.setUserName("user");
        database.setPassword("password");
        DatabaseService::mDatabasePool.setLocalData(database);
        return database;
    }
}

QMap<QString,QString> DatabaseService::executeQuery(QString command){

    QSqlQuery query (DatabaseService::getDatabase());
    query.exec(command);

    //...

    return result;
}

//...

UPD 2:

main.cpp:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;

    server.listen(QHostAddress::Any, 1234);

    return a.exec();
}

myserver.h:

class MyServer : public QTcpServer
{
    Q_OBJECT

    explicit MyServer(QObject *parent = 0);
    ~MyServer();

protected:
    void incomingConnection(qintptr socketDescriptor) Q_DECL_OVERRIDE;

signals:
    void stopAll();
};

myserver.cpp:

MyServer::MyServer(QObject *parent) : QTcpServer(parent)
{

}

MyServer::~MyServer(){
    emit stopAll();
}

void MyServer::incomingConnection(qintptr socketDescriptor){
    QThread* clientThread = new QThread;
    MyClient *client = new MyClient(socketDescriptor, this);

    client->moveToThread(clientThread);

    connect(clientThread, SIGNAL(started()), client, SLOT(process()));

    connect(client, SIGNAL(finished()), clientThread, SLOT(quit()));
    connect(this, SIGNAL(stopAll()), client, SLOT(stopFromServer()));
    connect(client, SIGNAL(finished()), client, SLOT(deleteLater()));
    connect(clientThread, SIGNAL(finished()), clientThread, SLOT(deleteLater()));

    clientThread->start();
}

myclient.h:

class MyClient : public QObject
{
    Q_OBJECT
public:
    explicit MyClient(int socketDescriptor, MyServer *server);
    ~MyClient();

private:
    QSslSocket* socket = NULL;

public slots:
    void process();
}

myclient.cpp:

void MyClient::process(){
    //typical connection things
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(ready()));
}

void MyClient::ready(){
    connect(socket,SIGNAL(readyRead()),this, SLOT(newData()));
}

Body:
I have made a software also using database connection. I don't use QThread on my application but use QFuture and the thread will take from global thread pool (normaly the number of thread pool will be the number of the CPU thread).

And when accessing the database, each pool will has its own QSqlDatabase. I am using QThreadStorage as the storage of QSqlDatabase.

static QThreadStorage<QSqlDatabase> mDatabasePool;
....
QSqlDatabase Db::getDatabase()
{
    if(mDatabasePool.hasLocalData()) {
        return mDatabasePool.localData();
    } else {
        auto database = QSqlDatabase::addDatabase(SQLDRIVERNAME[DBTYPE], QUuid::createUuid().toString());
        mDatabasePool.setLocalData(database);
        return database;
    }
}

So the database connection will only created when the thread does not has the connection.

For full sample project you can check on my project :https://github.com/apinprastya/sultan. The database is inside the libdb and the worker QFuture is in libserver. You can use it as reference. But I am not sure if my design is suitable for you.


问:
Android app doesn't call "onDestroy()" when killed (ICS)
I'm developing an android app using bluetooth communication (using a propetary protocol) and I need to catch the moment when the app is killed.

I wanted to use the "onDestroy()" method but it isn't called every time the app is killed.
I noticed that it is called when I press the back button and, only sometimes, when I kill the app from the task manager.

The question is: How can I catch the moment before the app is killed?

Here is the code I tried to use:

```<code>@Override
public void onDestroy() {
    sendMessage(msg);
    Log.d("SampleApp", "destroy");
    super.onDestroy();
}

@Override
public void finish(){

    sendMessage(msg);
    Log.d("SampleApp", "finish");
    super.finish();
}
</code>```

Unfortunately finish() is never called and onDestroy isn't called every time I close the app from the task manager.

How can I handle this?

答:
I just resolved a similar kind of issue.

Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.

Inside your Manifest file, keep flag stopWithTask as true for Service. Like:

```<code><service
    android:name="com.myapp.MyService"
    android:stopWithTask="true" />
</code>```

But as you say you want to unregister listeners and stop notification etc, I would suggest this approach:

Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

```<code><service
    android:name="com.myapp.MyService"
    android:stopWithTask="false" />
</code>```

Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).

```<code>public void onTaskRemoved(Intent rootIntent) {

    //unregister listeners
    //do any other cleanup if required

    //stop service
    stopSelf();
}
</code>```

Refer this question for more details, which contains other part of code, too.

Start service like below

startService(new Intent(this, MyService.class));

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
I'm developing an android app using bluetooth communication (using a propetary protocol) and I need to catch the moment when the app is killed.

I wanted to use the "onDestroy()" method but it isn't called every time the app is killed.
I noticed that it is called when I press the back button and, only sometimes, when I kill the app from the task manager.

The question is: How can I catch the moment before the app is killed?

Here is the code I tried to use:

@Override
public void onDestroy() {
    sendMessage(msg);
    Log.d("SampleApp", "destroy");
    super.onDestroy();
}

@Override
public void finish(){

    sendMessage(msg);
    Log.d("SampleApp", "finish");
    super.finish();
}

Unfortunately finish() is never called and onDestroy isn't called every time I close the app from the task manager.

How can I handle this?

Body:
I just resolved a similar kind of issue.

Here is what you can do if its just about stopping service when application is killed by swiping from Recent app list.

Inside your Manifest file, keep flag stopWithTask as true for Service. Like:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="true" />

But as you say you want to unregister listeners and stop notification etc, I would suggest this approach:

Inside your Manifest file, keep flag stopWithTask as false for Service. Like:

<service
    android:name="com.myapp.MyService"
    android:stopWithTask="false" />

Now in your MyService service, override method onTaskRemoved. (This will be fired only if stopWithTask is set to false).

public void onTaskRemoved(Intent rootIntent) {

    //unregister listeners
    //do any other cleanup if required

    //stop service
    stopSelf();
}

Refer this question for more details, which contains other part of code, too.

Start service like below

startService(new Intent(this, MyService.class));

Hope this helps.


问:
Symfony 3 connection to multiple databases
```<code>dynamic:
driver:   %database_driver%
host:     %database_host%
port:     %database_port%
dbname:   %database name%
user:     %database_user%
password: %database_password%
charset:  UTF8
</code>```

Hi everybody

I would like to connect to multiple databases dynamically. I read this tutorial http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html and it works as it was explained.

But my only problem is to change the value of dbname directly from my Controller to connect to all my databases.

It will be 24 hours that I am on this problem. if you have ideas I really need it

答:
Your code example shows only one connection. You've to define to database connection, like the example from the documentation:

Easy hack: don't use an entity manager, but just connection.

If you want an easy way out, don't use an EntityManager at all. It might be overkill if you only want to get some information about the database and don't want to store information or use Entities. Then, just create a custom connection and use 'vanilla' SQL:

```<code>$this->get('doctrine.dbal.connection_factory')->createConnection($params);
</code>```

Your question does not say how many database you expect. So let's describe two possibilities: a small number of (fixed) database or a dynamic connection.

Multiple connections, the simple way

```<code>doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   pdo_mysql
                host:     '%database_host%'
                port:     '%database_port%'
                dbname:   '%database_name%'
                user:     '%database_user%'
                password: '%database_password%'
                charset:  UTF8
            model_a:
                driver:   pdo_mysql
                host:     '%database_hosta%'
                port:     '%database_porta%'
                dbname:   '%database_namea%'
                user:     '%database_usera%'
                password: '%database_passworda%'
                charset:  UTF8
            model_b:
                driver:   pdo_mysql
                host:     '%database_hostb%'
                port:     '%database_portb%'
                dbname:   '%database_nameb%'
                user:     '%database_userb%'
                password: '%database_passwordb%'
                charset:  UTF8
    orm:
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
            model_a:
                connection: model_a
            model_b:
                connection: model_b
</code>```

By default, connection default will be used. In your controller, you can switch to another connection:

```<code>$customerEm = $this->getDoctrine()->getManager('model_a');
</code>```

And of course, you can dynamically choose your Manager:

```<code>//just an example, I don't know how you choose which database to use.
$managerName = $company->getModelName();
$em = $this->getDoctrine()->getManager($managerName);
</code>```

Dynamically create EntityManager

The DoctrineBundle has no support for dynamic values (other than configured values like the first example). You can create your own EntityManager, if you don't want (or can't) define multiple connections because the dynamic table name.

Create a factory and define it a service:

```<code>class EntityManagerFactory
{
    public function createManager($dbname)
    {
        $isDevMode = false;
        $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
        // or if you prefer yaml or XML
        //$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);
        //$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yaml"), $isDevMode);

        $conn = [
            'driver' => 'pdo_mysql',
            'username' => 'foo',
            'password' => 'foo',
            'dbname' => $dbname
        ];

        // obtaining the entity manager
        return EntityManager::create($conn, $config);
    }
}
</code>```

And use it in your controller:

```<code>public function controllerAction()
{
    $em = $this->get(EntityManagerFactory::class)->getManager('model-name');
}
</code>```

Body:
dynamic:
driver:   %database_driver%
host:     %database_host%
port:     %database_port%
dbname:   %database name%
user:     %database_user%
password: %database_password%
charset:  UTF8

Hi everybody

I would like to connect to multiple databases dynamically. I read this tutorial http://symfony.com/doc/current/cookbook/doctrine/multiple_entity_managers.html and it works as it was explained.

But my only problem is to change the value of dbname directly from my Controller to connect to all my databases.

It will be 24 hours that I am on this problem. if you have ideas I really need it

Body:
Your code example shows only one connection. You've to define to database connection, like the example from the documentation:

Easy hack: don't use an entity manager, but just connection.

If you want an easy way out, don't use an EntityManager at all. It might be overkill if you only want to get some information about the database and don't want to store information or use Entities. Then, just create a custom connection and use 'vanilla' SQL:

$this->get('doctrine.dbal.connection_factory')->createConnection($params);

Your question does not say how many database you expect. So let's describe two possibilities: a small number of (fixed) database or a dynamic connection.

Multiple connections, the simple way

doctrine:
    dbal:
        default_connection: default
        connections:
            default:
                driver:   pdo_mysql
                host:     '%database_host%'
                port:     '%database_port%'
                dbname:   '%database_name%'
                user:     '%database_user%'
                password: '%database_password%'
                charset:  UTF8
            model_a:
                driver:   pdo_mysql
                host:     '%database_hosta%'
                port:     '%database_porta%'
                dbname:   '%database_namea%'
                user:     '%database_usera%'
                password: '%database_passworda%'
                charset:  UTF8
            model_b:
                driver:   pdo_mysql
                host:     '%database_hostb%'
                port:     '%database_portb%'
                dbname:   '%database_nameb%'
                user:     '%database_userb%'
                password: '%database_passwordb%'
                charset:  UTF8
    orm:
        default_entity_manager: default
        entity_managers:
            default:
                connection: default
            model_a:
                connection: model_a
            model_b:
                connection: model_b

By default, connection default will be used. In your controller, you can switch to another connection:

$customerEm = $this->getDoctrine()->getManager('model_a');

And of course, you can dynamically choose your Manager:

//just an example, I don't know how you choose which database to use.
$managerName = $company->getModelName();
$em = $this->getDoctrine()->getManager($managerName);

Dynamically create EntityManager

The DoctrineBundle has no support for dynamic values (other than configured values like the first example). You can create your own EntityManager, if you don't want (or can't) define multiple connections because the dynamic table name.

Create a factory and define it a service:

class EntityManagerFactory
{
    public function createManager($dbname)
    {
        $isDevMode = false;
        $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__."/src"), $isDevMode);
        // or if you prefer yaml or XML
        //$config = Setup::createXMLMetadataConfiguration(array(__DIR__."/config/xml"), $isDevMode);
        //$config = Setup::createYAMLMetadataConfiguration(array(__DIR__."/config/yaml"), $isDevMode);

        $conn = [
            'driver' => 'pdo_mysql',
            'username' => 'foo',
            'password' => 'foo',
            'dbname' => $dbname
        ];

        // obtaining the entity manager
        return EntityManager::create($conn, $config);
    }
}

And use it in your controller:

public function controllerAction()
{
    $em = $this->get(EntityManagerFactory::class)->getManager('model-name');
}