问:
PHP - Dynamic Dropdown on Class value using JS
I have two dropdowns which full information from my SQL table. One dropdown consist of "Colors." The other dropdown consist of members in the specific colors. I already have them in the different optgroup based on their class value which is "color."

My goal is to have the user select "COLOR" and only the members in that class show up in the member dropdown.

Ex. I select Red on the first dropdown. Only members in "Red" will be available in the second dropdown.

Hopefully it can be down using JavaScript

SQL Table:

+-----------+--------------+
| GroupName | MemberName   |
+-----------+--------------+
| Red       | Joe Bob      |
| Red       | Catherine    |
| Blue      | Tommy        |
| Orange    | John Razks   |
| Black     | Trevor Smith |
+-----------+--------------+

+--------+
| Color  |
+--------+
| Red    |
| Blue   |
| Orange |
| Black  |
+--------+```
</div>
</div>
</p>

<p>PHP Code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
  $conn = mysqli_connect("#Connecting");
  if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
  else{
    $color_result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
    $colors = array();
    while ($row = mysqli_fetch_assoc($color_result)){ $colors[] = $row['Color']; }
    $member_result = mysqli_query($conn, "SELECT distinct MemberName,GroupName from Members order by MemberName ASC");
    $members = array();
    while ($row = mysqli_fetch_assoc($member_result)){
      if(!isset($members[$row['GroupName']])){ $members[$row['GroupName']] = array(); }
        $members[$row['GroupName']][] = $row; }
  }
?>
<form id=#blah>
Color:
<select id="committee" name="committee">
    <option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>
        </div>

    <div class="sub_category_div" id="sub_category_div">
    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=\"".$key."\">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['MemberName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>
 </div>
  </form>

  <form id=#id>
  Color:
  <select id="committee" name="committee">
<option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>
        </div>

    <div class="sub_category_div" id="sub_category_div">
    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=".$key.">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>
  </form></code>```

答:
you can use this demo code which help you</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="firstmenu" name="City" onchange="select_other(this.value)">
<option value="Color1">Color1</option>
<option value="Color2">Color2</option>
<option value="Color3">Color3</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
<option value="Color1">Member1</option>
<option value="Color2">Member2</option>
<option value="Color3">Member3</option>
</select>

 <script>
 function select_other(value){
    $("#secondmenu").children('option').hide();
    $("#secondmenu").children("option[value^=" + value + "]").show();
    $("#secondmenu").children("option[value^=" + value + "]").attr('selected',true);
}
 </script>
</code>```

Body:
I have two dropdowns which full information from my SQL table. One dropdown consist of "Colors." The other dropdown consist of members in the specific colors. I already have them in the different optgroup based on their class value which is "color."

My goal is to have the user select "COLOR" and only the members in that class show up in the member dropdown.

Ex. I select Red on the first dropdown. Only members in "Red" will be available in the second dropdown.

Hopefully it can be down using JavaScript

SQL Table:

+-----------+--------------+
| GroupName | MemberName   |
+-----------+--------------+
| Red       | Joe Bob      |
| Red       | Catherine    |
| Blue      | Tommy        |
| Orange    | John Razks   |
| Black     | Trevor Smith |
+-----------+--------------+

+--------+
| Color  |
+--------+
| Red    |
| Blue   |
| Orange |
| Black  |
+--------+

PHP Code:

<?php
  $conn = mysqli_connect("#Connecting");
  if(!$conn){ die("Connection Failed".myslqi_connect_error()); }
  else{
    $color_result = mysqli_query($conn, "SELECT * from Color order by Color ASC");
    $colors = array();
    while ($row = mysqli_fetch_assoc($color_result)){ $colors[] = $row['Color']; }
    $member_result = mysqli_query($conn, "SELECT distinct MemberName,GroupName from Members order by MemberName ASC");
    $members = array();
    while ($row = mysqli_fetch_assoc($member_result)){
      if(!isset($members[$row['GroupName']])){ $members[$row['GroupName']] = array(); }
        $members[$row['GroupName']][] = $row; }
  }
?>
<form id=#blah>
Color:
<select id="committee" name="committee">
    <option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>

    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=\"".$key."\">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['MemberName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>

  </form>

  <form id=#id>
  Color:
  <select id="committee" name="committee">
<option value="">Select Color</option>
        <?php
            foreach($colors as $color){
              echo "<option value=\"".$color."\">".$color."</option>";
            }
         ?>
            </select>

    Individual:
    <select name="senator" id="senator">
        <option value="">Select Individual</option>
        <?php
        foreach($members as $key => $member_group){
                echo "<optgroup class=".$key.">";
                foreach($member_group as $val){
                    echo "<option value=\"".$val['ValueName']."\">".$val['MemberName']."</option>";
                }
                echo "</optgroup>";
        }
        ?>
    </select>
  </form>

Body:
you can use this demo code which help you

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="firstmenu" name="City" onchange="select_other(this.value)">
<option value="Color1">Color1</option>
<option value="Color2">Color2</option>
<option value="Color3">Color3</option>
</select>
<br/>
<select id="secondmenu" name="zipCode">
<option value="Color1">Member1</option>
<option value="Color2">Member2</option>
<option value="Color3">Member3</option>
</select>

 <script>
 function select_other(value){
    $("#secondmenu").children('option').hide();
    $("#secondmenu").children("option[value^=" + value + "]").show();
    $("#secondmenu").children("option[value^=" + value + "]").attr('selected',true);
}
 </script>


来源: stackexchange

问:
why does [XMLHttpReequest] Message come?
I am calling below javascript/ajax page method from code behind, then
why does [XMLHttpReequest] Message come?</p>

```<code>var options = {
  type: "POST",
  url: "Test.aspx/SendMessage",
  data: "{'toMailAddress':'" + val + "','rno':'" + rno+ "', 'nonrno':'" + nonrno+ "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
    var val1 = response.d;
    alert(val1);
    if (val1 == "1") {
      // Below code is used to close the window, if message has been sent to the user sucessfully.
      var windowObj = window.self;
      windowObj.opener = window.self;
      windowObj.close();
    }
  },
  error: function (result) {
    alert("Error in " + result);
  }
};
$.ajax(options);
</code>```

答:
I expect the message you are in fact seeing is "Error in XMLHttpRequest". This is what you would see if an error occurred during the call, because you have the wrong arguments for the error call back.

The method signature for the jQuery ajax error callback is:

```<code>error(XMLHttpRequest, textStatus, errorThrown)
</code>```

So your error alert is being passed the XMLHttpRequest object, which is probably not what you meant to do. The code implicitly calls the toString() method on the XMLHttpRequest which will return "[object XMLHttpRequest]".

If that message isn't coming from the error callback, then there must be another bit of code somewhere passing the XMLHttpRequest object to alert(). I suggest you set a break point after your own alert() and single step through to see where the other alert() is.

ContentLicense: CC BY-SA 2.5

Body:
I am calling below javascript/ajax page method from code behind, then
why does [XMLHttpReequest] Message come?

var options = {
  type: "POST",
  url: "Test.aspx/SendMessage",
  data: "{'toMailAddress':'" + val + "','rno':'" + rno+ "', 'nonrno':'" + nonrno+ "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (response) {
    var val1 = response.d;
    alert(val1);
    if (val1 == "1") {
      // Below code is used to close the window, if message has been sent to the user sucessfully.
      var windowObj = window.self;
      windowObj.opener = window.self;
      windowObj.close();
    }
  },
  error: function (result) {
    alert("Error in " + result);
  }
};
$.ajax(options);

Body:
I expect the message you are in fact seeing is "Error in XMLHttpRequest". This is what you would see if an error occurred during the call, because you have the wrong arguments for the error call back.

The method signature for the jQuery ajax error callback is:

error(XMLHttpRequest, textStatus, errorThrown)

So your error alert is being passed the XMLHttpRequest object, which is probably not what you meant to do. The code implicitly calls the toString() method on the XMLHttpRequest which will return "[object XMLHttpRequest]".

If that message isn't coming from the error callback, then there must be another bit of code somewhere passing the XMLHttpRequest object to alert(). I suggest you set a break point after your own alert() and single step through to see where the other alert() is.


问:
Joining three tables w/user input
I have three tables, A, B, C. Table B has foreign keys into both A & C. A & C don't have keys into each other.

I'm trying to write a query where I get every hit from a column in Table C whose primary key (foreign key in B) matches a primary key from Table A (also a foreign key in B). A wrinkle is that I am trying to get this info based on a user input, which will be a separate column in Table A.

Example:

```<code>TABLE A
-------
aID    aName
1      Squeakers
2      Formations
3      Hutsis
4      Pms

TABLE B
-------
bID    aID    cID
1      1      27930
2      1      21405
3      1      24013
4      2      21111
5      1      34100
6      1      20841
7      4      30001

TABLE C
-------
cID      cName
21405    Silver Flyer
27930    Babs McGee
30001    Jimmy McGill
24013    Fletcher Mason
21111    Spike Fester
34100    Hope Sisco
20841    Ellis Traeger
</code>```

So I want a user to put in ‘Squeakers’ and then get something that looks like:

```<code>Squeakers – Babs McGee, Silver Flyer, Fletcher Mason, Hope Sisco, Ellis Trager
</code>```

I've been stuck on this for multiple days and can't figure out the syntax. I'm not sure if I need a sub-query or if it's not all INNER JOINS?

答:
```<code>SELECT aName, GROUP_CONCAT(cName SEPARATOR ', ') as cNames
FROM A
INNER JOIN B
ON A.aID = B.aID
INNER JOIN C
ON B.cID = C.cID
GROUP BY aName, A.aID
</code>```

You will get two columns - one with aName and other with aggregated cNames, comma separated. I don't have MySQL at my current PC but it should more or less work like this.

ContentLicense: CC BY-SA 3.0

Title: Joining three tables w/user input

Body:
I have three tables, A, B, C. Table B has foreign keys into both A & C. A & C don't have keys into each other.

I'm trying to write a query where I get every hit from a column in Table C whose primary key (foreign key in B) matches a primary key from Table A (also a foreign key in B). A wrinkle is that I am trying to get this info based on a user input, which will be a separate column in Table A.

Example:

TABLE A
-------
aID    aName
1      Squeakers
2      Formations
3      Hutsis
4      Pms

TABLE B
-------
bID    aID    cID
1      1      27930
2      1      21405
3      1      24013
4      2      21111
5      1      34100
6      1      20841
7      4      30001

TABLE C
-------
cID      cName
21405    Silver Flyer
27930    Babs McGee
30001    Jimmy McGill
24013    Fletcher Mason
21111    Spike Fester
34100    Hope Sisco
20841    Ellis Traeger

So I want a user to put in ‘Squeakers’ and then get something that looks like:

Squeakers – Babs McGee, Silver Flyer, Fletcher Mason, Hope Sisco, Ellis Trager

I've been stuck on this for multiple days and can't figure out the syntax. I'm not sure if I need a sub-query or if it's not all INNER JOINS?

Body:
SELECT aName, GROUP_CONCAT(cName SEPARATOR ', ') as cNames
FROM A
INNER JOIN B
ON A.aID = B.aID
INNER JOIN C
ON B.cID = C.cID
GROUP BY aName, A.aID

You will get two columns - one with aName and other with aggregated cNames, comma separated. I don't have MySQL at my current PC but it should more or less work like this.


问:
stripping html tags in php with allowing an exception
For the past hour I've been trying to add an exception to strip tags, allowing only

 to remain, but unfortunately I haven't been successful in making this work, I don't get any errors either, the trim is present because it's removing whitespace from the data, any feedback would be much appreciated, thank you very much

```<code>trim(strip_tags($html->find('div[id=data]',"<p></p>")));
</code>```

答:
This is the common behaviour of php strip_tags() function that you can add the HTML tags that you want to allow.

If you have HTML content and suppose you would like to allow
 tag then just add this as second parameter. For example:

```<code>strip_tags($html_text, '<p>');
</code>```

For more you can check here

Body:
For the past hour I've been trying to add an exception to strip tags, allowing only

 to remain, but unfortunately I haven't been successful in making this work, I don't get any errors either, the trim is present because it's removing whitespace from the data, any feedback would be much appreciated, thank you very much

trim(strip_tags($html->find('div[id=data]',"

")));

Body:
This is the common behaviour of php strip_tags() function that you can add the HTML tags that you want to allow.

If you have HTML content and suppose you would like to allow
 tag then just add this as second parameter. For example:

strip_tags($html_text, '<p>');

For more you can check here


问:
Why is this CORS request failing only in Firefox?
I'm implementing CORS with credentials and a preflight request and I'm a bit mystified why the preflight request consistently fails in Firefox 30 but works in Safari (7.0.2) and Chrome 35. I think this issue is different from "Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?" because I am not getting a 401, but rather a CORS-specific message from the browser client:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myurl.dev.com. This can be fixed by moving the resource to the same domain or enabling CORS."

Without showing source code, here's what I'm doing:

On the server:

Headers for OPTIONS response:

Access-Control-Allow-Origin: [[copy origin from the request here]]

Access-Control-Allow-Methods: "POST GET OPTIONS"

Access-Control-Allow-Headers: "X-Requested-With"

Access-Control-Allow-Credentials: "true"

Headers for POST response:

Access-Control-Allow-Origin: [[copy origin from the request here]]

Access-Control-Allow-Credentials: "true"

In the browser client:

```<code>jQuery.ajax({
  url: requestUrl,
  type: 'POST',
  data: getData(),
  xhrFields: {
    withCredentials: true
  }
});
</code>```

Per the spec, this will trigger a OPTIONS preflight request which needs to have the CORS headers in its response.  I've read through the W3C spec several times and I can't identify what I'm doing wrong, if anything, in that preflight response.

答:
I have noticed that when you a send CORS(Cross Origin Resource Sharing) request with cookies set, Firefox doesn't send the required response headers.

Solution:

Below solution adds headers only for OPTIONS requests and accepts requests only from example.com. You can change the implementation for other request methods and expected hosts.

JS CODE

```<code>var xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials = true;

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {
        if (xmlhttp.status == 200) {
            success_callback(xmlhttp.responseText);
        } else {
            error_callback(xmlhttp.statusText);
        }
    }
};
xmlhttp.open("DELETE", url);
xmlhttp.send(null);
</code>```

When you send a DELETE request, the browser send a pre-flight request for OPTIONS, which expects Access-Control-Allow-Methods in the response headers. Based on this header value the actual DELETE request is sent. In Firefox, when you send a DELETE request the pre-flight request's response headers do not have expected headers, therefore it fails to send the actual DELETE request.

To overcome this problem use the below NGINX server config.

NGINX CODE

```<code>#handle CORS requests by adding required headers
if ($http_origin ~* .example.com) {
    set $cors "CORS-${request_method}";
}

if ($cors = "CORS-OPTIONS") {
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Content-Type';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE';
    add_header 'Access-Control-Allow-Origin' $http_origin;
}
</code>```

Good read on CORS: https://www.html5rocks.com/en/tutorials/cors/

Body:
I'm implementing CORS with credentials and a preflight request and I'm a bit mystified why the preflight request consistently fails in Firefox 30 but works in Safari (7.0.2) and Chrome 35. I think this issue is different from "Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?" because I am not getting a 401, but rather a CORS-specific message from the browser client:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://myurl.dev.com. This can be fixed by moving the resource to the same domain or enabling CORS."

Without showing source code, here's what I'm doing:

On the server:

Headers for OPTIONS response:

Access-Control-Allow-Origin: [[copy origin from the request here]]

Access-Control-Allow-Methods: "POST GET OPTIONS"

Access-Control-Allow-Headers: "X-Requested-With"

Access-Control-Allow-Credentials: "true"

Headers for POST response:

Access-Control-Allow-Origin: [[copy origin from the request here]]

Access-Control-Allow-Credentials: "true"

In the browser client:

jQuery.ajax({
  url: requestUrl,
  type: 'POST',
  data: getData(),
  xhrFields: {
    withCredentials: true
  }
});

Per the spec, this will trigger a OPTIONS preflight request which needs to have the CORS headers in its response.  I've read through the W3C spec several times and I can't identify what I'm doing wrong, if anything, in that preflight response.

Body:
I have noticed that when you a send CORS(Cross Origin Resource Sharing) request with cookies set, Firefox doesn't send the required response headers.

Solution:

Below solution adds headers only for OPTIONS requests and accepts requests only from example.com. You can change the implementation for other request methods and expected hosts.

JS CODE

var xmlhttp = new XMLHttpRequest();
xmlhttp.withCredentials = true;

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {
        if (xmlhttp.status == 200) {
            success_callback(xmlhttp.responseText);
        } else {
            error_callback(xmlhttp.statusText);
        }
    }
};
xmlhttp.open("DELETE", url);
xmlhttp.send(null);

When you send a DELETE request, the browser send a pre-flight request for OPTIONS, which expects Access-Control-Allow-Methods in the response headers. Based on this header value the actual DELETE request is sent. In Firefox, when you send a DELETE request the pre-flight request's response headers do not have expected headers, therefore it fails to send the actual DELETE request.

To overcome this problem use the below NGINX server config.

NGINX CODE

#handle CORS requests by adding required headers
if ($http_origin ~* .example.com) {
    set $cors "CORS-${request_method}";
}

if ($cors = "CORS-OPTIONS") {
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Content-Type';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE';
    add_header 'Access-Control-Allow-Origin' $http_origin;
}

Good read on CORS: https://www.html5rocks.com/en/tutorials/cors/


问:
Multiple assignment from method results in TypeError: Int is not iterable in Python
I am on a basic problem which outputs the number of coins types to be used to reach a sum which is inputted at method call.

Although I could do it in some other ways, I wanted to create a method and wanted to use multiple assignments.

The divide method is supposed to get 2 inputs, and should return division and remaining of the original value.

```<code>def divide(coin,value):
    if value >= coin:
        remains = value % coin
        value = (value - remains) / coin
        return value, remains
    else:
        return 0
</code>```

The main function is below, it calls the divide function, sending coin and value as arguments, to have the number of coins and initial value to be updated.

```<code>def stamps(x):
    fives, x = divide(5, x)
    twos, x = divide(2, x)
    print(fives, twos, x)

print stamps(0)
</code>```

This works fine when the coin outputs are calculated as positive integers. (like an input of 8 will output (1,1,1)) But If one or more coins are calculated as 0 (like, if you send 5, the output should be(1,0,0)) but it gives the following error:

twos, x = divide(2, x) TypeError: 'int' object is not iterable

I did not use any iterations (not on purpose at least). Why am I having this error? If value is smaller than the coin, divide method should return 0 isn't that correct?

答:
Your code is correct, the only problem is that you're returning only one value in else conditions, this is throwing this error.

Try the code below-

```<code>def divide(coin, value):
if value >= coin:
    remains = value % coin
    value = (value - remains) / coin
    return value, remains
else:
    return 0, 0  #or return 0, value

def stamps(x):
    fives, x = divide(5, x)
    twos, x = divide(2, x)
    print(fives, twos, x)

print(stamps(0))
</code>```

Body:
I am on a basic problem which outputs the number of coins types to be used to reach a sum which is inputted at method call.

Although I could do it in some other ways, I wanted to create a method and wanted to use multiple assignments.

The divide method is supposed to get 2 inputs, and should return division and remaining of the original value.

def divide(coin,value):
    if value >= coin:
        remains = value % coin
        value = (value - remains) / coin
        return value, remains
    else:
        return 0

The main function is below, it calls the divide function, sending coin and value as arguments, to have the number of coins and initial value to be updated.

def stamps(x):
    fives, x = divide(5, x)
    twos, x = divide(2, x)
    print(fives, twos, x)

print stamps(0)

This works fine when the coin outputs are calculated as positive integers. (like an input of 8 will output (1,1,1)) But If one or more coins are calculated as 0 (like, if you send 5, the output should be(1,0,0)) but it gives the following error:

twos, x = divide(2, x) TypeError: 'int' object is not iterable

I did not use any iterations (not on purpose at least). Why am I having this error? If value is smaller than the coin, divide method should return 0 isn't that correct?

Body:
Your code is correct, the only problem is that you're returning only one value in else conditions, this is throwing this error.

Try the code below-

def divide(coin, value):
if value >= coin:
    remains = value % coin
    value = (value - remains) / coin
    return value, remains
else:
    return 0, 0  #or return 0, value

def stamps(x):
    fives, x = divide(5, x)
    twos, x = divide(2, x)
    print(fives, twos, x)

print(stamps(0))


问:
Foxx url for ArangoDB version capture
Is there any inbuilt endpoint in default foxx app to get the running Arangodb version.
We have a monitoring tool and wants to capture arangodb version using a url.</p>

答: Have you tried the version endpoint?</p>

Title: Foxx url for ArangoDB version capture

Body: Have you tried the version endpoint?


问:
How do I fetch multiple table columns by php query?
I need to fetch two table columns from mysql & then replace part of contents of one column with contents of other. This is how I do but it shows nothing.

```<code>    $query  = "SELECT id, msg FROM msg2_qualities";
    $result = mysql_query($query);
    $outArray = array();
     if ($result) {
         while ($row = mysql_fetch_assoc($result))
                 {
                   $row2 = str_replace('testWord','$row[0]',$row[1]);
                   $outArray[] = $row2;
                  }
                 }
   echo json_encode($outArray);
</code>```

EDIT
I tested the code by echo & $row[0], $row[1] have no value. But If I run query to fetch single column from table, then it works fine like

```<code>     $query  = "SELECT msg FROM msg2_qualities"; OR
     $query  = "SELECT id FROM msg2_qualities";
</code>```

答:
Try removing the quotes around $row[0], and refer to the fields by name rather than index:

```<code>$row2 = str_replace('testWord', $row['id'], $row['msg']);
</code>```

Body:
I need to fetch two table columns from mysql & then replace part of contents of one column with contents of other. This is how I do but it shows nothing.

    $query  = "SELECT id, msg FROM msg2_qualities";
    $result = mysql_query($query);
    $outArray = array();
     if ($result) {
         while ($row = mysql_fetch_assoc($result))
                 {
                   $row2 = str_replace('testWord','$row[0]',$row[1]);
                   $outArray[] = $row2;
                  }
                 }
   echo json_encode($outArray);

EDIT
I tested the code by echo & $row[0], $row[1] have no value. But If I run query to fetch single column from table, then it works fine like

     $query  = "SELECT msg FROM msg2_qualities"; OR
     $query  = "SELECT id FROM msg2_qualities";

Body:
Try removing the quotes around $row[0], and refer to the fields by name rather than index:

$row2 = str_replace('testWord', $row['id'], $row['msg']);


问:
Turn variable elements into string for json
How can I make a foreach in here to turn every $values_x array element into a string?

```<code>$values_x = '';
if ( isset( $chart_render_data['options']['xAxis']['categories'] ) ) {
    $values_x = $chart_render_data['options']['xAxis']['categories'];
}
</code>```

$values_x outputs this, in the current graph I have:

```<code>array(14) {
  [0]=>float(2002)
  [1]=>float(2003)
  [2]=>float(2004)
  [3]=>float(2005)
  [4]=>float(2006)
  [5]=>float(2007)
  [6]=>float(2008)
  [7]=>float(2009)
  [8]=>float(2010)
  [9]=>float(2011)
  [10]=>float(2012)
  [11]=>float(2013)
  [12]=>float(2014)
  [13]=>float(2015)
}
bool(true)
</code>```

And I need it to output "2002", etc.
Any help is greatly appreciated.

答:
You can simply cast a value to a string by appending the value to a empty string $value = "".$value or use the cast (string)

in your case

```<code>$yourArray['values'] = array_map($yourArray['values'], function($value) {return (string)$value;})
</code>```

Body:
How can I make a foreach in here to turn every $values_x array element into a string?

$values_x = '';
if ( isset( $chart_render_data['options']['xAxis']['categories'] ) ) {
    $values_x = $chart_render_data['options']['xAxis']['categories'];
}

$values_x outputs this, in the current graph I have:

array(14) {
  [0]=>float(2002)
  [1]=>float(2003)
  [2]=>float(2004)
  [3]=>float(2005)
  [4]=>float(2006)
  [5]=>float(2007)
  [6]=>float(2008)
  [7]=>float(2009)
  [8]=>float(2010)
  [9]=>float(2011)
  [10]=>float(2012)
  [11]=>float(2013)
  [12]=>float(2014)
  [13]=>float(2015)
}
bool(true)

And I need it to output "2002", etc.
Any help is greatly appreciated.

Body:
You can simply cast a value to a string by appending the value to a empty string $value = "".$value or use the cast (string)

in your case

$yourArray['values'] = array_map($yourArray['values'], function($value) {return (string)$value;})


问:
Event Javascript
I have a problem with creating an event. I don't want to use innerHTML so I was trying different methods but none have worked. I'm making calculator, and I was trying to call nums array and itm as number holder but it didn't work. Question is how to make actually working event in there? Sorry if my post lack information, I hope you will be forgiving in this.

New, I have been doing a lot of research on my own but I can't find a solution to this. What I'm trying to do is to make operation buttons work like they are supposed to. I can't find a way to store button that I pressed previously and make operation on it. I ask for some hint's to make it work.

var nums = [
  ['7', '8', '9', 'C'],
  ['4', '5', '6', '+'],
  ['1', '2', '3', '-'],
  ['0', '.', '=']
];
var disp = document.getElementById('display');
var calc = document.getElementById('calc'),
  row, itm;

function keyPress(e) {
  console.log("Target:", e.target);
  console.log("Content:", e.target.textContent);
  console.log("Class:", e.target.className);
  disp.textContent = e.target.textContent;
  switch(e.target.textContent) {
    case 'C':
        disp.textContent = '0';
        break;
    case '+':
        //here i have been trying different things to make it work
        //but it seems i get the wrong idea all the time
        //this n1 is one of the vars i tried to save my numbers in
        disp.textContent = n1 + e.target.textContent;
        break;
    case '-':
        disp.textContent = '0';
        break;
    case '=':
        disp.textContent = '0';
        break;
  }
}

for (let i = 0; i < 4; ++i) {
  row = document.createElement('div');
  for (let j = 0; j < nums[i].length; ++j) {
    itm = document.createElement('div');
    itm.textContent = nums[i][j];
    if (nums[i][j] === '0')
      itm.setAttribute('class', 'double');
    itm.addEventListener('click', keyPress);
    row.appendChild(itm);
  }
  calc.appendChild(row);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div id="calc">
    <div>
      <div id="display">0</div>
    </div>
  </div>
  <script src="script.js"></script>
</body></code>```

答:
What exactly do you want to achieve? I'm guessing you want to do certain things when a key from your array is pressed. You could do something like:

function showKeycode(e) {
    var key = e.keyCode;
    switch(key) {
        case 49:
            console.log('1');
            break;
        case 50:
            console.log('2');
            break;
        case 51:
            console.log('3');
            break;
        case 52:
            console.log('and so on...')
            break;
    }
}

document.addEventListener('keydown', showKeycode);```

To get the keyCode of certain characters use '6'.charCodeAt(0).

ContentLicense: CC BY-SA 4.0

Title: Event Javascript

Body:
I have a problem with creating an event. I don't want to use innerHTML so I was trying different methods but none have worked. I'm making calculator, and I was trying to call nums array and itm as number holder but it didn't work. Question is how to make actually working event in there? Sorry if my post lack information, I hope you will be forgiving in this.

New, I have been doing a lot of research on my own but I can't find a solution to this. What I'm trying to do is to make operation buttons work like they are supposed to. I can't find a way to store button that I pressed previously and make operation on it. I ask for some hint's to make it work.

var nums = [
  ['7', '8', '9', 'C'],
  ['4', '5', '6', '+'],
  ['1', '2', '3', '-'],
  ['0', '.', '=']
];
var disp = document.getElementById('display');
var calc = document.getElementById('calc'),
  row, itm;

function keyPress(e) {
  console.log("Target:", e.target);
  console.log("Content:", e.target.textContent);
  console.log("Class:", e.target.className);
  disp.textContent = e.target.textContent;
  switch(e.target.textContent) {
    case 'C':
        disp.textContent = '0';
        break;
    case '+':
        //here i have been trying different things to make it work
        //but it seems i get the wrong idea all the time
        //this n1 is one of the vars i tried to save my numbers in
        disp.textContent = n1 + e.target.textContent;
        break;
    case '-':
        disp.textContent = '0';
        break;
    case '=':
        disp.textContent = '0';
        break;
  }
}

for (let i = 0; i < 4; ++i) {
  row = document.createElement('div');
  for (let j = 0; j < nums[i].length; ++j) {
    itm = document.createElement('div');
    itm.textContent = nums[i][j];
    if (nums[i][j] === '0')
      itm.setAttribute('class', 'double');
    itm.addEventListener('click', keyPress);
    row.appendChild(itm);
  }
  calc.appendChild(row);
}

0

Body:
What exactly do you want to achieve? I'm guessing you want to do certain things when a key from your array is pressed. You could do something like:

function showKeycode(e) {
    var key = e.keyCode;
    switch(key) {
        case 49:
            console.log('1');
            break;
        case 50:
            console.log('2');
            break;
        case 51:
            console.log('3');
            break;
        case 52:
            console.log('and so on...')
            break;
    }
}

document.addEventListener('keydown', showKeycode);

To get the keyCode of certain characters use '6'.charCodeAt(0).


问:
Identical values in an array has to be positioned together
```<code>var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]
</code>```

i have to arrange it in a way that  identical values has to be placed together

output array should be

```<code>["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]
</code>```

how to write the logic for this one ??

答:
Sort array using sort() method like this

var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"];

console.log(array1.sort());```

Body:
var array1 = ["ddd","aaa","eee","aaa","fff","bbb","ggg","aaa","ccc","fff"]

i have to arrange it in a way that  identical values has to be placed together

output array should be

["ddd","aaa","aaa","aaa","eee","fff","fff","bbb","ggg","ccc"]

how to write the logic for this one ??


答:
you are using mysql_fetch_assoc so code should be like this:-

```<code>while ($row = mysql_fetch_assoc($result))
 {
    $row2 = str_replace('testWord',$row['id'],$row['msg1']);
    $outArray[] = $row2;
 }
</code>```

Thanks.

Title: How do I fetch multiple table columns by php query?

Body:
you are using mysql_fetch_assoc so code should be like this:-

while ($row = mysql_fetch_assoc($result))
 {
    $row2 = str_replace('testWord',$row['id'],$row['msg1']);
    $outArray[] = $row2;
 }

Thanks.


问:
How do I detect a failed state on multiple files when running md5sum on multiple files
I use:

```<code>md5sum * > checklist.chk # Generates a list of checksums and files.
</code>```

and use:

```<code>md5sum -c checklist.chk   # runs through the list to check them
</code>```

How can I automate a PASS or FAIL state? I basically want to get a notification if something on my app changes. Whether by hacker or unauthorized change by a developer. I want to write a script that will notify of any changes to my code.

I found a few scripts online but they only appear to work for single files, I have been unable to adapt the script to work for multiple files with pass or fail states.

```<code>if [ "$(md5sum < File.name)" = "24f4ce42e0bc39ddf7b7e879a  -" ]
then
  echo Pass
else
  echo Fail
fi
</code>```

Reference:

Shell scripts and the md5/md5sum command: need to decide when to use which one
https://unix.stackexchange.com/questions/290240/md5sum-check-no-file

答:
I would do something like:</p>

```<code>for f in $(awk '{printf"%s ", $2}' checklist.chk); do
    md5sum=$(grep $f checklist.chk | awk '{print $1}')
    if [[ "$(md5sum < $f)" = "$md5sum  -" ]]; then
        echo Pass
    else
        echo Fail
    fi
done
</code>```

Body:
I use:

md5sum * > checklist.chk # Generates a list of checksums and files.

and use:

md5sum -c checklist.chk   # runs through the list to check them

How can I automate a PASS or FAIL state? I basically want to get a notification if something on my app changes. Whether by hacker or unauthorized change by a developer. I want to write a script that will notify of any changes to my code.

I found a few scripts online but they only appear to work for single files, I have been unable to adapt the script to work for multiple files with pass or fail states.

if [ "$(md5sum < File.name)" = "24f4ce42e0bc39ddf7b7e879a  -" ]
then
  echo Pass
else
  echo Fail
fi

Reference:

Shell scripts and the md5/md5sum command: need to decide when to use which one
https://unix.stackexchange.com/questions/290240/md5sum-check-no-file

Body:
I would do something like:

for f in $(awk '{printf"%s ", $2}' checklist.chk); do
    md5sum=$(grep $f checklist.chk | awk '{print $1}')
    if [[ "$(md5sum < $f)" = "$md5sum  -" ]]; then
        echo Pass
    else
        echo Fail
    fi
done


问:
JQuery Animation Slowing Down on KeyPress
I'm using JQuery to animate a div using the arrow keys.

For some reason when I repeat the arrow key press for the current direction, the animation slows dratically each time.

I thought $player.stop() and $player.clearQueue() would fix this, but apparently not. Any suggestions pleae?

There is a jsfiddle here: https://jsfiddle.net/qb484yp2/

My JS code is below.

```<code>$(document).ready(function () {

    var $player = $('#player'),
    $enemy1 = $('#enemy1'),
    $bg = $('#container'),
    playerW = $player.outerWidth(),
    playerH = $player.outerHeight(),
    bgW = $bg.width(),
    bgH = $bg.height(),
    playerX,
    playerY,
    enemySpeed = 1000,
    playerSpeed = 1000,
    direction,
    down = false;

    var targetSound1 = $('#targetSound1')[0];
    targetSound1.loop = true;

    function keypress(e) {

        $player.clearQueue();
        $player.stop()
        if (down) {
            return;
        }
        down = true;

        var playerLeft = $player.css('left');
        var playerTop = $player.css('top');
        var key = e.which || e.keyCode;
        if ([38, 40, 37, 39].includes(key)) {
            e.preventDefault(); // prevent defualts (scrolling)!
        }

        if (key == "37") {
            direction = 'left';
            playerLeft = 0;
        } else if (key == "38") {
            direction = 'up';
            playerTop = 0;
        } else if (key == "39") {
            direction = 'right';
            playerLeft = bgW - playerW;
        } else if (key == "40") {
            direction = 'down';
            playerTop = bgH - playerH;
        }

        $player.animate({
            left: playerLeft,
            top: playerTop
        },
            playerSpeed, 'linear');

    }

    function makeNewPosition($container) {

        // Get viewport dimensions (remove the dimension of the div)
        $container = ($container || $(window))
        var h = $container.height() - 50;
        var w = $container.width() - 50;
        var nh = Math.floor(Math.random() * h);
        var nw = Math.floor(Math.random() * w);

        return [nh, nw];
    }

    function animateDiv() {

        var $target = $($enemy1);
        var newq = makeNewPosition($target.parent());
        var oldq = $target.offset();
        var speed = enemySpeed;

        $($enemy1).animate({
            top: newq[0],
            left: newq[1]
        }, speed, 'linear', function () {
            animateDiv();
        });
    };

    $(document).on('keydown', keypress);
    $(document).on('keyup', function () {
        down = false
    });

    animateDiv();

});
</code>```

答:
i checked out your fiddle. I played around with it a bit and i got a solution. heres the fiddle. https://jsfiddle.net/qb484yp2/3/

solution : so my logic was if the key that is triggering an event was the key that triggered the previous event, we shouldnt be animating the #player div any longer. Only if the key changes we should animate it. This will stop unneccesary animations from piling up and slowing down the animation. So i thought we could probably keep track of the last animation and only if the key pressed has changed we would allow the animation to occur. Result : Smooth animation :)

this is the code that did the trick! check out the fiddle for the entire code

```<code>if(key==lastKey)
{
return;
}
else
lastKey=key;
</code>```

Also you'd have to remove this line from the code as it stops the animation of the player div.

```<code>$player.stop()
</code>```

Body:
I'm using JQuery to animate a div using the arrow keys.

For some reason when I repeat the arrow key press for the current direction, the animation slows dratically each time.

I thought $player.stop() and $player.clearQueue() would fix this, but apparently not. Any suggestions pleae?

There is a jsfiddle here: https://jsfiddle.net/qb484yp2/

My JS code is below.

$(document).ready(function () {

    var $player = $('#player'),
    $enemy1 = $('#enemy1'),
    $bg = $('#container'),
    playerW = $player.outerWidth(),
    playerH = $player.outerHeight(),
    bgW = $bg.width(),
    bgH = $bg.height(),
    playerX,
    playerY,
    enemySpeed = 1000,
    playerSpeed = 1000,
    direction,
    down = false;

    var targetSound1 = $('#targetSound1')[0];
    targetSound1.loop = true;

    function keypress(e) {

        $player.clearQueue();
        $player.stop()
        if (down) {
            return;
        }
        down = true;

        var playerLeft = $player.css('left');
        var playerTop = $player.css('top');
        var key = e.which || e.keyCode;
        if ([38, 40, 37, 39].includes(key)) {
            e.preventDefault(); // prevent defualts (scrolling)!
        }

        if (key == "37") {
            direction = 'left';
            playerLeft = 0;
        } else if (key == "38") {
            direction = 'up';
            playerTop = 0;
        } else if (key == "39") {
            direction = 'right';
            playerLeft = bgW - playerW;
        } else if (key == "40") {
            direction = 'down';
            playerTop = bgH - playerH;
        }

        $player.animate({
            left: playerLeft,
            top: playerTop
        },
            playerSpeed, 'linear');

    }

    function makeNewPosition($container) {

        // Get viewport dimensions (remove the dimension of the div)
        $container = ($container || $(window))
        var h = $container.height() - 50;
        var w = $container.width() - 50;
        var nh = Math.floor(Math.random() * h);
        var nw = Math.floor(Math.random() * w);

        return [nh, nw];
    }

    function animateDiv() {

        var $target = $($enemy1);
        var newq = makeNewPosition($target.parent());
        var oldq = $target.offset();
        var speed = enemySpeed;

        $($enemy1).animate({
            top: newq[0],
            left: newq[1]
        }, speed, 'linear', function () {
            animateDiv();
        });
    };

    $(document).on('keydown', keypress);
    $(document).on('keyup', function () {
        down = false
    });

    animateDiv();

});

Body:
i checked out your fiddle. I played around with it a bit and i got a solution. heres the fiddle. https://jsfiddle.net/qb484yp2/3/

solution : so my logic was if the key that is triggering an event was the key that triggered the previous event, we shouldnt be animating the #player div any longer. Only if the key changes we should animate it. This will stop unneccesary animations from piling up and slowing down the animation. So i thought we could probably keep track of the last animation and only if the key pressed has changed we would allow the animation to occur. Result : Smooth animation :)

this is the code that did the trick! check out the fiddle for the entire code

if(key==lastKey)
{
return;
}
else
lastKey=key;

Also you'd have to remove this line from the code as it stops the animation of the player div.

$player.stop()


问:
Pin Button to Bottom Right Corner of TextField IOS
I would like to pin a button to the bottom right corner of a textfield. I completed this in Android using a relativelayout. I don't know how to do this in IOS. I attempted to set top and bottom constraints, but it didn't work.
Help?

Example

答:
Since you're using a storyboard you'd probably want something like this if I'm not mistaken:

To do this set the following trailing and leading constraints on your textfield:

Your button should have the following constraints:


问:
Gnu Makefile - Handling dependencies
What approach do C++ programmers on Unix platform use to create and manage Makefiles?

I was using hand made Makefiles for my projects but they don't handle header file changes and other dependencies. I googled around and found a good solution here.

But I ran into a problem here in the sed command -

```<code>    sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
        -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \
</code>```

The problem is with the 3rd expression "-e 's/ *\$$//'.
It doesn't work. Its supposed to remove trailing backslashes. I understand that there has to be double dollar there since this is part of a Makefile. Can someone tell me what wrong here?

Here's the complete Makefile -

```<code>CC=g++
CFLAGS=-g -Wall
LIBS=-lpthread

OBJS=file1.o file2.o
TARGET=testProg

$(TARGET) : $(OBJS)
        $(CC) -o $@ $^ $(CFLAGS) $(LIBS)

%.o : %.cpp
        $(CC) -MMD -c -o $@ $< $(CFLAGS)
        @cp $*.d $*.P; \
            sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
                -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \
            rm -f $*.d

-include $(OBJS:%.o=%.P)

clean :
        rm -f $(TARGET) $(OBJS)

all : $(TARGET)
</code>```

Apart from the solution to this problem, I would also like some tips/pointers to my 1st question.

答:
I top tip that I have found useful when building dependency files is to include the dependency file as a target in the generated rule:

```<code>file.d file.o : file.c header.h header2.h ...
</code>```

Thus make will regenerate the dependencies if the source or any of the headers change.  Including phony targets for the headers (GCC -MP) should then allow stable builds when headers are removed - the absense of required header remains a compilation error, not a make dependency error.

Assuming that dependency files are generated into the same directory as the object files, the following should work for GCC on Unix:

```<code>-include $(OBJ:.o=.d)

$(OBJDIR)/%d : $(SRCDIR)/%.cpp
        mkdir -p $(@D)
        echo -n "$@ " > $@.tmp
        $(CXX) $(CPPFLAGS) -MM -MP -MT $(@:.d=.o) $< >> $@.tmp
        mv $@.tmp $@
</code>```

(from memory)

Title: Gnu Makefile - Handling dependencies

Body:
What approach do C++ programmers on Unix platform use to create and manage Makefiles?

I was using hand made Makefiles for my projects but they don't handle header file changes and other dependencies. I googled around and found a good solution here.

But I ran into a problem here in the sed command -

    sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
        -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \

The problem is with the 3rd expression "-e 's/ *\$$//'.
It doesn't work. Its supposed to remove trailing backslashes. I understand that there has to be double dollar there since this is part of a Makefile. Can someone tell me what wrong here?

Here's the complete Makefile -

CC=g++
CFLAGS=-g -Wall
LIBS=-lpthread

OBJS=file1.o file2.o
TARGET=testProg

$(TARGET) : $(OBJS)
        $(CC) -o $@ $^ $(CFLAGS) $(LIBS)

%.o : %.cpp
        $(CC) -MMD -c -o $@ $< $(CFLAGS)
        @cp $*.d $*.P; \
            sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
                -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $*.P; \
            rm -f $*.d

-include $(OBJS:%.o=%.P)

clean :
        rm -f $(TARGET) $(OBJS)

all : $(TARGET)

Apart from the solution to this problem, I would also like some tips/pointers to my 1st question.

Body:
I top tip that I have found useful when building dependency files is to include the dependency file as a target in the generated rule:

file.d file.o : file.c header.h header2.h ...

Thus make will regenerate the dependencies if the source or any of the headers change.  Including phony targets for the headers (GCC -MP) should then allow stable builds when headers are removed - the absense of required header remains a compilation error, not a make dependency error.

Assuming that dependency files are generated into the same directory as the object files, the following should work for GCC on Unix:

-include $(OBJ:.o=.d)

$(OBJDIR)/%d : $(SRCDIR)/%.cpp
        mkdir -p $(@D)
        echo -n "$@ " > $@.tmp
        $(CXX) $(CPPFLAGS) -MM -MP -MT $(@:.d=.o) $< >> $@.tmp
        mv $@.tmp $@

(from memory)


问:
Finding 'Next Available' Key in a dictionary or related collection
I want to write an linq extension (or a custom dictionary, sorted list list or whatever solution is best) that will allow me to add a value to a collection with its key being the 'next available' one.

For example:

```<code>int CreatedKey = IncrementDictionary.AddNext(myCustomer);
</code>```

If the currently existing keys are as follows:

```<code>1
2
8
4
3
</code>```

Then it would add the myCustomer into the dictionary with a key of 5 and it would return that key.

What do you think?

答:
Well... it's an old question, but I'd like to answer.

Nikhil Agrawal's code might be improved considering that, if you have an empty collection, you must specify what is your minimum value. So the code becomes:

```<code> public static int FirstFree(Dictionary<int, Guid> dict, int minumum)
    {
        int min = dict.Count == 0
            ? minumum                       //use passed minimum if needed
            : dict.Keys.Min();              //use real minimum
        int max = dict.Count > 1
            ? dict.Keys.Max() + 2           //two steps away from maximum, avoids exceptions
            : min + 2;                      //emulate data presence
        return Enumerable.Range(min, max).Except(dict.Keys).First();
    }
</code>```

But if you work in a defined range you should also know if you have space to store values. This can be the way:

```<code>public static int? FirstFree(Dictionary<int, Guid> dict, int min, int max)
    {
        if (max <= min)
            throw new Exception($"Specified range is invalid (must be max > min)");
        if (max - min + 1 == dict.Count)
            //no space left
            return null;
        return Enumerable.Range(min, max).Except(dict.Keys).First();
    }
</code>```

If you don't like nullable-int you can check if result is the minimum admitted.
Obviously it doesn't work if you specify min=int.MinValue, I know, but in this case the issue is the huge collection created by this method!

```<code>public static int FirstFree(Dictionary<int, Guid> dict, int min, int max)
    {
        if (max <= min)
            throw new Exception($"Specified range is invalid (must be max > min)");
        if (max - min + 1 == dict.Count)
            //no space left
            return int.MinValue;
        return Enumerable.Range(min, max).Except(dict.Keys).First();
    }
</code>```

Body:
I want to write an linq extension (or a custom dictionary, sorted list list or whatever solution is best) that will allow me to add a value to a collection with its key being the 'next available' one.

For example:

int CreatedKey = IncrementDictionary.AddNext(myCustomer);

If the currently existing keys are as follows:

1
2
8
4
3

Then it would add the myCustomer into the dictionary with a key of 5 and it would return that key.

What do you think?

Body:
Well... it's an old question, but I'd like to answer.

Nikhil Agrawal's code might be improved considering that, if you have an empty collection, you must specify what is your minimum value. So the code becomes:

 public static int FirstFree(Dictionary<int, Guid> dict, int minumum)
    {
        int min = dict.Count == 0
            ? minumum                       //use passed minimum if needed
            : dict.Keys.Min();              //use real minimum
        int max = dict.Count > 1
            ? dict.Keys.Max() + 2           //two steps away from maximum, avoids exceptions
            : min + 2;                      //emulate data presence
        return Enumerable.Range(min, max).Except(dict.Keys).First();
    }

But if you work in a defined range you should also know if you have space to store values. This can be the way:

public static int? FirstFree(Dictionary<int, Guid> dict, int min, int max)
    {
        if (max <= min)
            throw new Exception($"Specified range is invalid (must be max > min)");
        if (max - min + 1 == dict.Count)
            //no space left
            return null;
        return Enumerable.Range(min, max).Except(dict.Keys).First();
    }

If you don't like nullable-int you can check if result is the minimum admitted.
Obviously it doesn't work if you specify min=int.MinValue, I know, but in this case the issue is the huge collection created by this method!

public static int FirstFree(Dictionary<int, Guid> dict, int min, int max)
    {
        if (max <= min)
            throw new Exception($"Specified range is invalid (must be max > min)");
        if (max - min + 1 == dict.Count)
            //no space left
            return int.MinValue;
        return Enumerable.Range(min, max).Except(dict.Keys).First();
    }


问:
WriteableBitmap in .NET 4
I have got a problem: I would like to use a method Render() for WriteableBitmap object. However, as I noticed, the method is not available without using a Silverlight assembly System.Windows.dll. I need to use RenderTargetBitmap in my project (PresentationCore assembly for standard .net). Here is the problem - there are definitions of some classes in both assemblies, thus they are in conflict.

Basically, I need to add some stuff to Bgra32 bitmap. However, RenderTargetBitmap works only with Pbgra32 ones. I found that using WriteableBitmap to render would be nice. Maybe I am wrong?

Do you have any ideas?

Thank you in advance for the reply!

Cheers

答:
Convert your input to pre-multiplied alpha, do all your calculations in that color space, and convert your output back. Multiplying by alpha isn't hard to code.

Doing all calculations in pre-multiplied alpha color-space often results in better quality output(for example filtering works much better) and has some other advantages too.

Blog-entry on the numerous advantages of using PRGBA

Title: WriteableBitmap in .NET 4


问:
How to back our previous Activity after pressing cancel button in email?
I Have send emails from my Android application successfully,but I click on cancel(back button on gmail)button then my application goes into background,so
How can I comeback from gmail application to my application when I pressed the cancel button in gmail application.

below my code:

```<code>Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:abc@gmail.com")); intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject"); intent.putExtra(Intent.EXTRA_TEXT, "The message"); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(context, "Mail account not configured", Toast.LENGTH_SHORT).show();
</code>```

答:
You need change

```<code>context.startActivity(intent);
</code>```

to

```<code>context.startActivityForResult(intent,REQUEST_CODE);
</code>```

and add onActivityresult() to your Activity:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}
</code>```

Body:
I Have send emails from my Android application successfully,but I click on cancel(back button on gmail)button then my application goes into background,so
How can I comeback from gmail application to my application when I pressed the cancel button in gmail application.

below my code:

Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:abc@gmail.com")); intent.putExtra(Intent.EXTRA_SUBJECT, "Your Subject"); intent.putExtra(Intent.EXTRA_TEXT, "The message"); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(context, "Mail account not configured", Toast.LENGTH_SHORT).show();

Body:
You need change

context.startActivity(intent);

to

context.startActivityForResult(intent,REQUEST_CODE);

and add onActivityresult() to your Activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
}


问:
DJI Sdk will not connect when implemented as a standalone class
I cannot seem to get my standalone class to connect to the my phantom 4 no matter what i do, since it is implemented as a standalone class that can be spun up at will. The callbacks are never reached and data never seems to flow back from the device.

public class DjiManager {

```<code>private static DjiManager instance = null;

private Context mContext;
private DJIBaseProduct mProduct;
private SendData mData;
private DJIFlightController mFlightController = null;
private Handler mConnectHandler = null;
private Runnable mConnectRunnable = null;

public DjiManager(Context context) {
    mContext = context;
    //start eventbus
    EventBus.getDefault().register(this);
    //set reference to data storage
    mData = iOtManager.deviceData;
    //Initialize DJI SDK Manager
    initSdk();
}

public static DjiManager getIntance(Context context) {
    if (instance==null) {
        instance = new DjiManager(context);
    }
    return instance;
}

public void shutDown() {
    Log.d("DJI", "DGI Shutting down");
    //stop eventbus
    EventBus.getDefault().unregister(this);
    //stop the sdk
    stopSdk();
    //clear data buffer reference
    mData = null;
    //clear instance
    instance = null;
}

@Subscribe
public void usbAttached(UsbAttachedEvent event) {
    Log.d("DJI", "DGI Usb attached event");
    connectDrone();
}

@Subscribe
public void commandSent(SdkCommandSent event) {

}

private void stopSdk() {
    Log.d("DJI", "DGI stopSdk");
    //shutdown geo interface
    DJIFlyZoneManager.getInstance().setGEOSystemEnabled(false, new DJICommonCallbacks.DJICompletionCallback() {
        @Override
        public void onResult(DJIError djiError) {
            if (null != djiError) {
                Log.d("DJI", "Stopping Geo interface");
                Toast.showError((Activity) mContext, djiError.getDescription());
            }
        }
    });
    //stop connection
    DJISDKManager.getInstance().stopConnectionToProduct();
}

private void initSdk() {
    //Initialize DJI SDK Manager
    DJISDKManager.getInstance().initSDKManager(mContext, mDJISDKManagerCallback);
}

private void reInitSdk() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            initSdk();
        }
    },5000);
}

private void connectDrone() {
    if (mConnectHandler!=null && mConnectRunnable!=null) {
        mConnectHandler.removeCallbacks(mConnectRunnable);
    }
    mConnectHandler = new Handler();
    mConnectRunnable = new Runnable() {
        @Override
        public void run() {
            DJISDKManager.getInstance().startConnectionToProduct();
        }
    };
    mConnectHandler.postDelayed(mConnectRunnable,1000);
}

private void setupCallbacks() {
    //start geo sytem interface
    Log.d("DJI", "Setting up callbacks");
    DJIFlyZoneManager.getInstance().setGEOSystemEnabled(true, new DJICommonCallbacks.DJICompletionCallback() {
        @Override
        public void onResult(DJIError djiError) {
            if (null != djiError) {
                Log.d("DJI", "Error in callbacks: " + djiError.getDescription());
                Toast.showError((Activity) mContext, djiError.getDescription());
            } else {
                initFlightController();
            }
        }
    });
}

private void initFlightController() {
    if (isFlightControllerSupported()) {
        Log.d("DJI", "Flight controller supported");
        mFlightController = ((DJIAircraft) DJISDKManager.getInstance().getDJIProduct()).getFlightController();
        mFlightController.setUpdateSystemStateCallback(new DJIFlightControllerDelegate.FlightControllerUpdateSystemStateCallback() {
            @Override
            public void onResult(final DJIFlightControllerCurrentState state) {
                mData.sdk_speed_h = String.valueOf(state.getVelocityX());
                mData.sdk_speed_v = String.valueOf(state.getVelocityY());
                mData.sdk_lat = String.valueOf(state.getAircraftLocation().getLatitude());
                mData.sdk_lng = String.valueOf(state.getAircraftLocation().getLongitude());
                mData.sdk_altitude = String.valueOf(state.getUltrasonicHeight());
            }
        });
    } else {
        Log.d("DJI", "Flight controller not supported");
        connectDrone();
    }
}
private boolean isFlightControllerSupported() {
    return DJISDKManager.getInstance().getDJIProduct() != null &&
            DJISDKManager.getInstance().getDJIProduct() instanceof DJIAircraft &&
            ((DJIAircraft) DJISDKManager.getInstance().getDJIProduct()).getFlightController() != null;
}

//CALLBACKS

private DJISDKManager.DJISDKManagerCallback mDJISDKManagerCallback = new DJISDKManager.DJISDKManagerCallback() {
    @Override
    public void onGetRegisteredResult(DJIError error) {
        Log.d("DJI", error == null ? "success" : error.getDescription());
        if(error == DJISDKError.REGISTRATION_SUCCESS) {
            connectDrone();
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("DJI", "DGI Registration Succcessfull!");
                }
            });
        } else {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("DJI", "Register App Failed! Please enter your App Key and check the network.");
                    Toast.showError((Activity) mContext, "The purplebox failed to connect to a Dji Drone");
                    reInitSdk();
                }
            });
        }
    }
    @Override
    public void onProductChanged(DJIBaseProduct oldProduct, DJIBaseProduct newProduct) {
        mProduct = newProduct;
        if(mProduct != null) {
            Log.d("DJI", "Product found: " + newProduct.getModel());
            mProduct.setDJIBaseProductListener(mDJIBaseProductListener);
            //setup product
            setupCallbacks();
        } else {
            Log.d("DJI", "Product Not Found, reconnecting...");
            //connectDrone();
        }
    }
};

private DJIBaseProduct.DJIBaseProductListener mDJIBaseProductListener = new DJIBaseProduct.DJIBaseProductListener() {
    @Override
    public void onComponentChange(DJIBaseProduct.DJIComponentKey key, DJIBaseComponent oldComponent, DJIBaseComponent newComponent) {
        Log.d("DJI", "Component Changed");
    }
    @Override
    public void onProductConnectivityChanged(boolean isConnected) {
        Log.d("DJI", "DGI Connected: " + isConnected);
    }
};
</code>```

}

答:
It seems that you did not called registerApp.
Instead it looks like you look for USB connection.</p>

Body:
I cannot seem to get my standalone class to connect to the my phantom 4 no matter what i do, since it is implemented as a standalone class that can be spun up at will. The callbacks are never reached and data never seems to flow back from the device.

public class DjiManager {

private static DjiManager instance = null;

private Context mContext;
private DJIBaseProduct mProduct;
private SendData mData;
private DJIFlightController mFlightController = null;
private Handler mConnectHandler = null;
private Runnable mConnectRunnable = null;

public DjiManager(Context context) {
    mContext = context;
    //start eventbus
    EventBus.getDefault().register(this);
    //set reference to data storage
    mData = iOtManager.deviceData;
    //Initialize DJI SDK Manager
    initSdk();
}

public static DjiManager getIntance(Context context) {
    if (instance==null) {
        instance = new DjiManager(context);
    }
    return instance;
}

public void shutDown() {
    Log.d("DJI", "DGI Shutting down");
    //stop eventbus
    EventBus.getDefault().unregister(this);
    //stop the sdk
    stopSdk();
    //clear data buffer reference
    mData = null;
    //clear instance
    instance = null;
}

@Subscribe
public void usbAttached(UsbAttachedEvent event) {
    Log.d("DJI", "DGI Usb attached event");
    connectDrone();
}

@Subscribe
public void commandSent(SdkCommandSent event) {

}

private void stopSdk() {
    Log.d("DJI", "DGI stopSdk");
    //shutdown geo interface
    DJIFlyZoneManager.getInstance().setGEOSystemEnabled(false, new DJICommonCallbacks.DJICompletionCallback() {
        @Override
        public void onResult(DJIError djiError) {
            if (null != djiError) {
                Log.d("DJI", "Stopping Geo interface");
                Toast.showError((Activity) mContext, djiError.getDescription());
            }
        }
    });
    //stop connection
    DJISDKManager.getInstance().stopConnectionToProduct();
}

private void initSdk() {
    //Initialize DJI SDK Manager
    DJISDKManager.getInstance().initSDKManager(mContext, mDJISDKManagerCallback);
}

private void reInitSdk() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            initSdk();
        }
    },5000);
}

private void connectDrone() {
    if (mConnectHandler!=null && mConnectRunnable!=null) {
        mConnectHandler.removeCallbacks(mConnectRunnable);
    }
    mConnectHandler = new Handler();
    mConnectRunnable = new Runnable() {
        @Override
        public void run() {
            DJISDKManager.getInstance().startConnectionToProduct();
        }
    };
    mConnectHandler.postDelayed(mConnectRunnable,1000);
}

private void setupCallbacks() {
    //start geo sytem interface
    Log.d("DJI", "Setting up callbacks");
    DJIFlyZoneManager.getInstance().setGEOSystemEnabled(true, new DJICommonCallbacks.DJICompletionCallback() {
        @Override
        public void onResult(DJIError djiError) {
            if (null != djiError) {
                Log.d("DJI", "Error in callbacks: " + djiError.getDescription());
                Toast.showError((Activity) mContext, djiError.getDescription());
            } else {
                initFlightController();
            }
        }
    });
}

private void initFlightController() {
    if (isFlightControllerSupported()) {
        Log.d("DJI", "Flight controller supported");
        mFlightController = ((DJIAircraft) DJISDKManager.getInstance().getDJIProduct()).getFlightController();
        mFlightController.setUpdateSystemStateCallback(new DJIFlightControllerDelegate.FlightControllerUpdateSystemStateCallback() {
            @Override
            public void onResult(final DJIFlightControllerCurrentState state) {
                mData.sdk_speed_h = String.valueOf(state.getVelocityX());
                mData.sdk_speed_v = String.valueOf(state.getVelocityY());
                mData.sdk_lat = String.valueOf(state.getAircraftLocation().getLatitude());
                mData.sdk_lng = String.valueOf(state.getAircraftLocation().getLongitude());
                mData.sdk_altitude = String.valueOf(state.getUltrasonicHeight());
            }
        });
    } else {
        Log.d("DJI", "Flight controller not supported");
        connectDrone();
    }
}
private boolean isFlightControllerSupported() {
    return DJISDKManager.getInstance().getDJIProduct() != null &&
            DJISDKManager.getInstance().getDJIProduct() instanceof DJIAircraft &&
            ((DJIAircraft) DJISDKManager.getInstance().getDJIProduct()).getFlightController() != null;
}

//CALLBACKS

private DJISDKManager.DJISDKManagerCallback mDJISDKManagerCallback = new DJISDKManager.DJISDKManagerCallback() {
    @Override
    public void onGetRegisteredResult(DJIError error) {
        Log.d("DJI", error == null ? "success" : error.getDescription());
        if(error == DJISDKError.REGISTRATION_SUCCESS) {
            connectDrone();
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("DJI", "DGI Registration Succcessfull!");
                }
            });
        } else {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d("DJI", "Register App Failed! Please enter your App Key and check the network.");
                    Toast.showError((Activity) mContext, "The purplebox failed to connect to a Dji Drone");
                    reInitSdk();
                }
            });
        }
    }
    @Override
    public void onProductChanged(DJIBaseProduct oldProduct, DJIBaseProduct newProduct) {
        mProduct = newProduct;
        if(mProduct != null) {
            Log.d("DJI", "Product found: " + newProduct.getModel());
            mProduct.setDJIBaseProductListener(mDJIBaseProductListener);
            //setup product
            setupCallbacks();
        } else {
            Log.d("DJI", "Product Not Found, reconnecting...");
            //connectDrone();
        }
    }
};

private DJIBaseProduct.DJIBaseProductListener mDJIBaseProductListener = new DJIBaseProduct.DJIBaseProductListener() {
    @Override
    public void onComponentChange(DJIBaseProduct.DJIComponentKey key, DJIBaseComponent oldComponent, DJIBaseComponent newComponent) {
        Log.d("DJI", "Component Changed");
    }
    @Override
    public void onProductConnectivityChanged(boolean isConnected) {
        Log.d("DJI", "DGI Connected: " + isConnected);
    }
};

}


问:
Deleting an object declared on the stack
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

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

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}
</code>```

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??

答: You called the destructor of a. This does not delete the variable, it just call the destructor function. The variable will be remove from the stack at the exit of the function.</p>

Body:
I wanted to know what happens if we delete an object declared on the stack, two times. In order to test this I've written this simple program:

#include <iostream>
using namespace std;

class A {
public:
    A() {}
    virtual ~A() {
        cout << "test" << endl;
    }
};

int main()
{
    A a;
    a.~A();
}

I was actually expecting a segmentation fault, as I'm deleting A once explicitly in the code, and it will be deleted again when it goes out of scope, however suprisingly the program produces the following ouput:

"test"

    "test"

Can anybody explain why this code is working??


问:
Using one sub query result multiple times in the same mysql query
How can we use result set of one subquery multiple times in the same query

```<code>SELECT
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) be ON joa.referred_by = be.id
) AS applicationcount,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bf ON joa.referred_by = bf.id
    AND joa.admin_review = '3'
    AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bg ON joa.referred_by = bg.id
    AND joa. STATUS = '5'
    AND joa.admin_review = '2'
) AS employer_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bd ON joa.referred_by = bd.id
    AND joa.admin_review = '1'
) AS admin_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bc ON joa.referred_by = bc.id
    AND joa.admin_review = '5'
) AS accountmanager_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) ba ON joa.referred_by = ba.id
    AND joa.admin_review = '6'
) AS rp_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = 1
    ) bh ON joa.referred_by = bh.id
    AND joa.admin_review = '2'
    AND (
        joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa.    STATUS = 3 || joa. STATUS = 4
    )
) AS other_status
  FROM
game_applied ja
JOIN user_user u ON u.id = ja.applied_recruiter_id
INNER JOIN (
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
    JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
GROUP BY
applicationcount
</code>```

How can we use result set of one subquery multiple times in the same query

the sub query used mulitple times in this query to a single use

```<code>(
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
  ) bn ON ja.referred_by = bn.id
</code>```

答:
OK... I'll try to figure out what the query does first. I'll replace all instances of:

```<code>SELECT
    COUNT(joa.id)
FROM
    game_applied joa
INNER JOIN (
    SELECT
        jrmm.id
    FROM
        game_refer_to_member jrmm
    JOIN game_refer jrr ON jrr.id = jrmm.rid
    AND jrr.referby_user_id = 2551
    AND jrmm. STATUS = '1'
</code>```

with the phrase:

```<code>( SELECT count(*) FROM joa JOIN (subselect))
</code>```

...for clarity.

I also removed the GROUP BY, since it is useless and/or misguided, unless you can explain why it is there.

I assume ja.applied_recruiter_id is a foreign key, which means...

```<code>JOIN user_user u ON u.id = ja.applied_recruiter_id
</code>```

...always returns one row. Since no columns from user_user are actually selected, this join can be removed. Now, this part:

```<code>    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
            JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bn ON ja.referred_by = bn.id
</code>```

...it is unclear what this does. Since the subselect is the same as the one in the previous queries, it is unlikely that it would filter lines returned by the whole query. I'd say its only effect is to uselessly duplicate lines, which explains why there was a GROUP BY... So, off it goes.

We get:

```<code>SELECT
( SELECT count(*) FROM joa JOIN (subselect)) be ON joa.referred_by = be.id ) AS applicationcount,
( SELECT count(*) FROM joa JOIN (subselect)) bf ON joa.referred_by = bf.id
    AND joa.admin_review = '3'
    AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
( SELECT count(*) FROM joa JOIN (subselect)) bg ON joa.referred_by = bg.id
    AND joa. STATUS = '5'
    AND joa.admin_review = '2'
) AS employer_reject,
( SELECT count(*) FROM joa JOIN (subselect)) bd ON joa.referred_by = bd.id
    AND joa.admin_review = '1'
) AS admin_review,
( SELECT count(*) FROM joa JOIN (subselect)) bc ON joa.referred_by = bc.id
    AND joa.admin_review = '5'
) AS accountmanager_review,
( SELECT count(*) FROM joa JOIN (subselect)) ba ON joa.referred_by = ba.id
    AND joa.admin_review = '6'
) AS rp_review,
( SELECT count(*) FROM joa JOIN (subselect)) bh ON joa.referred_by = bh.id
    AND joa.admin_review = '2'
    AND (joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa.    STATUS = 3 || joa. STATUS = 4)
) AS other_status
  FROM
game_applied ja
</code>```

...And, using the same logic as Sarhash, we simplify this into:

```<code>SELECT COUNT(joa.id) AS applicationcount,
     SUM(joa.admin_review = '3' AND joa.rejection_reason = 'Admin Rejected your resume') AS admin_reject,
     SUM(joa.STATUS = '5' AND joa.admin_review = '2') AS employer_reject,
     SUM(joa.admin_review = '1') AS admin_review,
     SUM(joa.admin_review = '5') AS accountmanager_review,
     SUM(joa.admin_review = '6') AS rp_review,
     SUM(joa.admin_review = '2' AND joa.STATUS != '5') AS other_status,
FROM game_refer_to_member jrmm
INNER JOIN game_refer jrr ON jrr.id = jrmm.rid
INNER JOIN game_applied joa ON jrmm.id  = joa.referred_by
WHERE jrmm.STATUS = '1' AND jrr.referby_user_id = 2551
</code>```

(which is the same, minus the useless join to USER and a cleanup in the WHERE, thank you Sarhash, you get all the credit).

Body:
How can we use result set of one subquery multiple times in the same query

SELECT
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) be ON joa.referred_by = be.id
) AS applicationcount,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bf ON joa.referred_by = bf.id
    AND joa.admin_review = '3'
    AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bg ON joa.referred_by = bg.id
    AND joa. STATUS = '5'
    AND joa.admin_review = '2'
) AS employer_reject,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bd ON joa.referred_by = bd.id
    AND joa.admin_review = '1'
) AS admin_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bc ON joa.referred_by = bc.id
    AND joa.admin_review = '5'
) AS accountmanager_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) ba ON joa.referred_by = ba.id
    AND joa.admin_review = '6'
) AS rp_review,
(
    SELECT
        COUNT(joa.id)
    FROM
        game_applied joa
    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
        JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = 1
    ) bh ON joa.referred_by = bh.id
    AND joa.admin_review = '2'
    AND (
        joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa.    STATUS = 3 || joa. STATUS = 4
    )
) AS other_status
  FROM
game_applied ja
JOIN user_user u ON u.id = ja.applied_recruiter_id
INNER JOIN (
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
    JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
) bn ON ja.referred_by = bn.id
GROUP BY
applicationcount

How can we use result set of one subquery multiple times in the same query

the sub query used mulitple times in this query to a single use

(
SELECT
    jrmm.id
FROM
    game_refer_to_member jrmm
JOIN game_refer jrr ON jrr.id = jrmm.rid
AND jrr.referby_user_id = 2551
AND jrmm. STATUS = '1'
  ) bn ON ja.referred_by = bn.id

Body:
OK... I'll try to figure out what the query does first. I'll replace all instances of:

SELECT
    COUNT(joa.id)
FROM
    game_applied joa
INNER JOIN (
    SELECT
        jrmm.id
    FROM
        game_refer_to_member jrmm
    JOIN game_refer jrr ON jrr.id = jrmm.rid
    AND jrr.referby_user_id = 2551
    AND jrmm. STATUS = '1'

with the phrase:

( SELECT count(*) FROM joa JOIN (subselect))

...for clarity.

I also removed the GROUP BY, since it is useless and/or misguided, unless you can explain why it is there.

I assume ja.applied_recruiter_id is a foreign key, which means...

JOIN user_user u ON u.id = ja.applied_recruiter_id

...always returns one row. Since no columns from user_user are actually selected, this join can be removed. Now, this part:

    INNER JOIN (
        SELECT
            jrmm.id
        FROM
            game_refer_to_member jrmm
            JOIN game_refer jrr ON jrr.id = jrmm.rid
        AND jrr.referby_user_id = 2551
        AND jrmm. STATUS = '1'
    ) bn ON ja.referred_by = bn.id

...it is unclear what this does. Since the subselect is the same as the one in the previous queries, it is unlikely that it would filter lines returned by the whole query. I'd say its only effect is to uselessly duplicate lines, which explains why there was a GROUP BY... So, off it goes.

We get:

SELECT
( SELECT count(*) FROM joa JOIN (subselect)) be ON joa.referred_by = be.id ) AS applicationcount,
( SELECT count(*) FROM joa JOIN (subselect)) bf ON joa.referred_by = bf.id
    AND joa.admin_review = '3'
    AND joa.rejection_reason = 'Admin rejected your game'
) AS admin_reject,
( SELECT count(*) FROM joa JOIN (subselect)) bg ON joa.referred_by = bg.id
    AND joa. STATUS = '5'
    AND joa.admin_review = '2'
) AS employer_reject,
( SELECT count(*) FROM joa JOIN (subselect)) bd ON joa.referred_by = bd.id
    AND joa.admin_review = '1'
) AS admin_review,
( SELECT count(*) FROM joa JOIN (subselect)) bc ON joa.referred_by = bc.id
    AND joa.admin_review = '5'
) AS accountmanager_review,
( SELECT count(*) FROM joa JOIN (subselect)) ba ON joa.referred_by = ba.id
    AND joa.admin_review = '6'
) AS rp_review,
( SELECT count(*) FROM joa JOIN (subselect)) bh ON joa.referred_by = bh.id
    AND joa.admin_review = '2'
    AND (joa. STATUS = '' || joa. STATUS = 1 || joa. STATUS = 2 || joa.    STATUS = 3 || joa. STATUS = 4)
) AS other_status
  FROM
game_applied ja

...And, using the same logic as Sarhash, we simplify this into:

SELECT COUNT(joa.id) AS applicationcount,
     SUM(joa.admin_review = '3' AND joa.rejection_reason = 'Admin Rejected your resume') AS admin_reject,
     SUM(joa.STATUS = '5' AND joa.admin_review = '2') AS employer_reject,
     SUM(joa.admin_review = '1') AS admin_review,
     SUM(joa.admin_review = '5') AS accountmanager_review,
     SUM(joa.admin_review = '6') AS rp_review,
     SUM(joa.admin_review = '2' AND joa.STATUS != '5') AS other_status,
FROM game_refer_to_member jrmm
INNER JOIN game_refer jrr ON jrr.id = jrmm.rid
INNER JOIN game_applied joa ON jrmm.id  = joa.referred_by
WHERE jrmm.STATUS = '1' AND jrr.referby_user_id = 2551

(which is the same, minus the useless join to USER and a cleanup in the WHERE, thank you Sarhash, you get all the credit).


问:
Being notified with key of sub-property changed?
Vue let you have watchers that monitor a given property (even nested):

```<code>// keypath
vm.$watch('a.b.c', function (newVal, oldVal) {
  // do something
})
</code>```

However, given a vue instance like this:

```<code>var vm = new Vue({
  data: {
    options: {
      a: 1,
      b: 2,
      c: 3
    }
  },
})
</code>```

Is there a way to watch options such that I'm notified when any child property is changed with the key as well as the value?

Note: I'm looking to also obtain what key the changed value related to.

Something that would respond back with something like: function(key, value) {}
Possibly even: function(key, value, oldValue) {}?

答:
You can loop through the keys and make a watcher for each that calls a method with the key and values.

var vm = new Vue({
  el: '#app',
  data: {
    options: {
      a: 1,
      b: 2,
      c: 3
    }
  },
  created() {
    for (const k of Object.keys(this.options)) {
      this.$watch(`options.${k}`, (newVal, oldVal) => this.optionWatcher(k, newVal, oldVal));
    }
  },
  methods: {
    optionWatcher(key, newVal, oldVal) {
      console.log(`Updated ${key} from ${oldVal} to ${newVal}`);
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <div v-for="k in Object.keys(options)">{{k}}={{options[k]}}<button @click="++options[k]">Increment</button>
</div></code>```

Body:
Vue let you have watchers that monitor a given property (even nested):

// keypath
vm.$watch('a.b.c', function (newVal, oldVal) {
  // do something
})

However, given a vue instance like this:

var vm = new Vue({
  data: {
    options: {
      a: 1,
      b: 2,
      c: 3
    }
  },
})

Is there a way to watch options such that I'm notified when any child property is changed with the key as well as the value?

Note: I'm looking to also obtain what key the changed value related to.

Something that would respond back with something like: function(key, value) {}
Possibly even: function(key, value, oldValue) {}?

Body:
You can loop through the keys and make a watcher for each that calls a method with the key and values.

var vm = new Vue({
  el: '#app',
  data: {
    options: {
      a: 1,
      b: 2,
      c: 3
    }
  },
  created() {
    for (const k of Object.keys(this.options)) {
      this.$watch(`options.${k}`, (newVal, oldVal) => this.optionWatcher(k, newVal, oldVal));
    }
  },
  methods: {
    optionWatcher(key, newVal, oldVal) {
      console.log(`Updated ${key} from ${oldVal} to ${newVal}`);
    }
  }
});

<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<div id="app">
  <div v-for="k in Object.keys(options)">{{k}}={{options[k]}}<button @click="++options[k]">Increment</button>
</div>


问:
How to create base class for all my symfony controllers
I want to create a base controller class for all my controllers in Symfony, I am very new to Symfony, so don't be angry with dumb question. I am asking this question because I can't do something like this

```<code>    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    class AbstractController extends Controller
    {
        public function __construct()
        {
            //...... check access level
            $user = $this->getUser(); //This is not working, I don't have access to the Controller(the base class) properties
        }
    }
</code>```

Now one of my controllers

```<code>    class UserController extends AbstractController
    {
        public deleteUserAction(Request $request)
        {
          var_dump($this);// this will dump an empty class that is not instance of Symfony\Bundle\FrameworkBundle\Controller\Controller
          //.... delete user
        }
    }
</code>```

What is the best way to do this? please...
EDIT....
What I really want to do is to check whether a user privilege level is enough to access a particular action(e.g. deleteUserAction()) in a particular controller(e.g. UserController), I have a class that attach privilege level to all actions in all controllers. The check will be very efficient if it happens in a parent controller (e.g. BaseController's constructor) which is executed before UserController->deleteUserAction() but in the base controller I don't have access to $this.
I have tried voter and ACL none help my situation.
Thanks in advance.

答:
simply use service controller... is shared:

http://symfony.com/doc/current/controller/service.html

Body:
I want to create a base controller class for all my controllers in Symfony, I am very new to Symfony, so don't be angry with dumb question. I am asking this question because I can't do something like this

    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    class AbstractController extends Controller
    {
        public function __construct()
        {
            //...... check access level
            $user = $this->getUser(); //This is not working, I don't have access to the Controller(the base class) properties
        }
    }

Now one of my controllers

    class UserController extends AbstractController
    {
        public deleteUserAction(Request $request)
        {
          var_dump($this);// this will dump an empty class that is not instance of Symfony\Bundle\FrameworkBundle\Controller\Controller
          //.... delete user
        }
    }

What is the best way to do this? please...
EDIT....
What I really want to do is to check whether a user privilege level is enough to access a particular action(e.g. deleteUserAction()) in a particular controller(e.g. UserController), I have a class that attach privilege level to all actions in all controllers. The check will be very efficient if it happens in a parent controller (e.g. BaseController's constructor) which is executed before UserController->deleteUserAction() but in the base controller I don't have access to $this.
I have tried voter and ACL none help my situation.
Thanks in advance.


问:
Convert local IST time to unix timestamp using Moment.js
I want to convert the following datetime into unix timestamp.

```<code>Tue Feb 28 2017 00:00:00 GMT+0530 (IST)
</code>```

How can I do so using Moment.js

答:
To convert to unix timestamp use valueOf() (milliseconds) or unix() (seconds).

If your input is a JavaScript Date, you can just use moment(Date); (or simply use JS date getTime()).

If your input is a string you can parse it using moment(String, String):

```<code>var m = moment('Tue Feb 28 2017 00:00:00 GMT+0530 (IST)', 'ddd MMM DD YYYY HH:mm:ss Z');
</code>```

Here a working example:

var d = new Date(2017, 1, 28);
console.log(moment(d).valueOf());
console.log(moment(d).unix());
var s = 'Tue Feb 28 2017 00:00:00 GMT+0530 (IST)';
var m = moment(s, 'ddd MMM DD YYYY HH:mm:ss Z');
console.log(m.valueOf());
console.log(m.unix());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script></code>```

Body:
I want to convert the following datetime into unix timestamp.

Tue Feb 28 2017 00:00:00 GMT+0530 (IST)

How can I do so using Moment.js

Body:
To convert to unix timestamp use valueOf() (milliseconds) or unix() (seconds).

If your input is a JavaScript Date, you can just use moment(Date); (or simply use JS date getTime()).

If your input is a string you can parse it using moment(String, String):

var m = moment('Tue Feb 28 2017 00:00:00 GMT+0530 (IST)', 'ddd MMM DD YYYY HH:mm:ss Z');

Here a working example:

var d = new Date(2017, 1, 28);
console.log(moment(d).valueOf());
console.log(moment(d).unix());
var s = 'Tue Feb 28 2017 00:00:00 GMT+0530 (IST)';
var m = moment(s, 'ddd MMM DD YYYY HH:mm:ss Z');
console.log(m.valueOf());
console.log(m.unix());

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


问:
Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET
I have refresh my application page and getting this error in console
Failed to load resource: net::ERR_CONNECTION_RESET.

I have tried to re-install the XAMPP version but this doesnt work for me.

答:
I had a similar issue using Apache 2.4 and PHP 7.

My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:

GET http://example.com/api/v1/my/resource net::ERR_CONNECTION_RESET

It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.

The amount of threads can be easily raised by setting the ThreadsPerChild value for the module in question.

The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf and then editing the preset values in the file to desired values.

1) Uncomment the Server-pool management file

```<code># Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf
</code>```

2) Open and edit the file conf/extra/httpd-mpm.conf and raise the amount of threads

In my case I had to change the threads for the mpm_winnt_module:

```<code># raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
    ThreadsPerChild        250
    MaxConnectionsPerChild   0
</IfModule>
</code>```

A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.

Body:
I had a similar issue using Apache 2.4 and PHP 7.

My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:

GET http://example.com/api/v1/my/resource net::ERR_CONNECTION_RESET

It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.

The amount of threads can be easily raised by setting the ThreadsPerChild value for the module in question.

The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf and then editing the preset values in the file to desired values.

1) Uncomment the Server-pool management file

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

2) Open and edit the file conf/extra/httpd-mpm.conf and raise the amount of threads

In my case I had to change the threads for the mpm_winnt_module:

# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
    ThreadsPerChild        250
    MaxConnectionsPerChild   0
</IfModule>

A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.