问:
The pd.Series.prod() function
This should be probably elementary but still I can not figure it out.

I am reading the documentation on pd.Series and doing simple exercises.

My code is the following:

```<code>import pandas as pd
import numpy as np
pd.Series([2, 4, 6]).prod()
Out[7]: 48

a = pd.Series(np.arange(1, 100, 3))

a
Out[9]:
0      1
1      4
2      7
3     10
4     13
5     16
6     19
7     22
8     25
9     28
10    31
11    34
12    37
13    40
14    43
15    46
16    49
17    52
18    55
19    58
20    61
21    64
22    67
23    70
24    73
25    76
26    79
27    82
28    85
29    88
30    91
31    94
32    97
dtype: int32

a.prod()
Out[10]: 0

a = pd.Series(np.arange(1, 100, 2))

a.prod()
Out[15]: -373459037

type(a)
Out[18]: pandas.core.series.Series
</code>```

My question is why this erratic -to my eyes-- behavior?  Why a.prod() the first time evaluates to 0 and then evaluates to a negative integer?

Your advice will be appreciated.

Title: The pd.Series.prod() function

Body:
This should be probably elementary but still I can not figure it out.

I am reading the documentation on pd.Series and doing simple exercises.

My code is the following:

import pandas as pd
import numpy as np
pd.Series([2, 4, 6]).prod()
Out[7]: 48

a = pd.Series(np.arange(1, 100, 3))

a
Out[9]:
0      1
1      4
2      7
3     10
4     13
5     16
6     19
7     22
8     25
9     28
10    31
11    34
12    37
13    40
14    43
15    46
16    49
17    52
18    55
19    58
20    61
21    64
22    67
23    70
24    73
25    76
26    79
27    82
28    85
29    88
30    91
31    94
32    97
dtype: int32

a.prod()
Out[10]: 0

a = pd.Series(np.arange(1, 100, 2))

a.prod()
Out[15]: -373459037

type(a)
Out[18]: pandas.core.series.Series

My question is why this erratic -to my eyes-- behavior?  Why a.prod() the first time evaluates to 0 and then evaluates to a negative integer?

Your advice will be appreciated.

Body:
it's a int32 overflow:

In [340]: a = pd.Series(np.arange(1, 100, 3)).astype(np.int64)
#  NOTE:                 --------------->    ^^^^^^^^^^^^^^^^^

In [341]: a.prod()
Out[341]: 8624389262030143488


来源: stackexchange

问:
Akka scheduler not completing
I need to send a message to an actor at specific intervals. I am using the following code:

```<code>object SendToActor extends App {

  import Sender._

  val system: ActorSystem = ActorSystem("sender")

  try {
    val senderActor: ActorRef = system.actorOf(Sender.props, "sendActor")
    val sendSchedule =
      system.scheduler.schedule(0 milliseconds, 5 minutes, senderActor, doSomething())
  } finally {
    system.terminate()
  }
}
</code>```

Unfortunately, the scheduler doesn't seem to run unless I do one of the following:

Put a readLine() right after it:

```
val sendSchedule = system.scheduler.schedule(0 milliseconds, 5 minutes, senderActor, doSomething())
readLine()
```

Put a Thread.sleep() right after it:

```
val sendSchedule = system.scheduler.schedule(0 milliseconds, 5 minutes, senderActor, doSomething())
Thread.sleep(10000)
```

Is there a reason why the scheduler won't run as coded above? Why does it require the sleep in order to work?

答: Probably because you're terminating the actor system immediately after defining the scheduler.</p>

ContentLicense: CC BY-SA 3.0

Title: Akka scheduler not completing

Body:
I need to send a message to an actor at specific intervals. I am using the following code:

object SendToActor extends App {

  import Sender._

  val system: ActorSystem = ActorSystem("sender")

  try {
    val senderActor: ActorRef = system.actorOf(Sender.props, "sendActor")
    val sendSchedule =
      system.scheduler.schedule(0 milliseconds, 5 minutes, senderActor, doSomething())
  } finally {
    system.terminate()
  }
}

Unfortunately, the scheduler doesn't seem to run unless I do one of the following:

Put a readLine() right after it:

val sendSchedule = system.scheduler.schedule(0 milliseconds, 5 minutes, senderActor, doSomething())
readLine()

Put a Thread.sleep() right after it:

val sendSchedule = system.scheduler.schedule(0 milliseconds, 5 minutes, senderActor, doSomething())
Thread.sleep(10000)

Is there a reason why the scheduler won't run as coded above? Why does it require the sleep in order to work?


问:
Portability of binary serialization of double/float type in C++
The C++ standard does not discuss the underlying layout of float and double types, only the range of values they should represent.  (This is also true for signed types, is it two's compliment or something else)

My question is: What the are techniques used to serialize/deserialize POD types such as double and float in a portable manner? At the moment it seems the only way to do this is to have the value represented literally(as in "123.456"), The ieee754 layout for double is not standard on all architectures.

答:
Create an appropriate serializer/de-serializer interface for writing/reading this.

The interface can then have several implementations and you can test your options.

As said before, obvious options would be:

IEEE754 which writes / reads the binary chunk if directly supported by the architecture or parses it if not supported by the architecture

Text: always needs to parse.

Whatever you else you can think of.

Just remember - once you have this layer, you can always start with IEEE754 if you only support platforms that use this format internally. This way you'll have the additional effort only when you need to support a different platform! Don't do work you don't have to.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

ContentLicense: CC BY-SA 2.5


问:
How do I get the full text to show in Unity 3D UI?
I am trying to get the full text to display when entering play mode but its only showing the first few words.

I already set the Horizontal and Vertical overflow to wrap and truncate.

Any help is greatly appreciated.

答: You have given your font size as 24. But it seems there's a lot of text to show. I would suggest make the text box bigger. Then select the Best Fit option in the inspector.


问:
Have JS auto complete math equations for a calculator app
The issue I am having is that the math is not working as intended. I would like the calculator to auto evaluate the amount if the length of the fullAmount variable length is equal to 3 and then clear the num variable and the fullAmount variable but leave the current number that has been evaluated. So if you put 9 * 1 into the calculator I want it to leave num = [] and fullAmount = [9] but it is currently leaving the fullAmount with [9,*,1] and then adds on to it.

$(document).ready(function() {

  var fullAmount = []

  var num = []

  var func = null

  function evaluate(array) {
    if (array[1] === "+") {
      var complete = array[0] + array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "-") {
      var complete = array[0] - array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "X") {
      var complete = array[0] * array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "÷") {
      var complete = array[0] / array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  }

  $('.num').click(function() {
    num.push($(this).text())
    console.log(num)
    console.log(fullAmount)
    $("#res").val(num.join(''));
  });

  $('.action').click(function() {
    func = $(this).text();
    num = num.join("")
    fullAmount.push(parseInt(num))
    if (fullAmount.length >= 3) {
      evaluate(fullAmount)
    } else {
      fullAmount.push(func[0])
      console.log(func)
    }

    $("#res").val(fullAmount);
    func = null
    num = []
  });

  $('#equals').click(function() {
    if (fullAmount[1] === "+") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] + fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "-") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] - fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "X") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] * fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "÷") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] / fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  });

  $('#clear').click(function() {
    num = []
    fullAmount = []
    func = null
    $("#res").val("")
    console.log(num)
    console.log(fullAmount)
    console.log(func)

  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
  </script>
  <script src="calc.js"></script>
  <link rel="stylesheet" type="text/css" href="calc.css">
</head>

<body>
  <div id="calculator-container">
    <form class="show">
      <input type="text" id="res" name="numbers" disabled><br>
    </form>
    <center>
      <div class="calculator-view">
        <table>
          <tr>
            <td>
              <button id="clear" type="button">AC</button>
              <button id="sign" class="action" type="button">+/-</button>
              <button id="divide" class="action" type="button">÷</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="seven" class="num" type="button">7</button>
              <button id="eight" class="num" type="button">8</button>
              <button id="nine" class="num" type="button">9</button>
              <button id="multiply" class="action" type="button">X</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="four" class="num" type="button">4</button>
              <button id="five" class="num" type="button">5</button>
              <button id="six" class="num" class="num" type="button">6</button>
              <button id="minus" class="action" type="button">-</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="one" class="num" type="button">1</button>
              <button id="two" class="num" type="button">2</button>
              <button id="three" class="num" type="button">3</button>
              <button id="plus" class="action" type="button">+</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="zero" class="num" type="button">0</button>
              <button id="equals" type="button">=</button>
            </td>
          </tr>
        </table>
      </div>
</body>

</html></code>```

答:
I made some changes in your calculator code.

After each operation, the arrays num and fullAmount are reinitialized so that they can be used for new computation.

To get the value of the previous operation, the variable complete is declared global. Let's suppose the user typed in 2 + 3 = + 5. The result should be 10. By declaring the variable complete global, I can make some check on it after. See the snippet below:

$(document).ready(function() {

  var fullAmount = []

  var num = []

  var func = null

  var complete = null

  function evaluate(array) {
    if (array[1] === "+") {
      var complete = array[0] + array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else if (array[1] === "-") {
      var complete = array[0] - array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else if (array[1] === "X") {
      var complete = array[0] * array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else if (array[1] === "÷") {
      var complete = array[0] / array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  }

  $('.num').click(function() {
    num.push($(this).text())
    $("#res").val(num.join(''));
  });

  $('.action').click(function() {
    func = $(this).text();
    num = num.join("")

    if(parseInt(num)){
     fullAmount.push(parseInt(num))
    }
    //if there is no value before operator, the calculator will use previous value
    else if(complete && !fullAmount[0]){
      fullAmount.push(complete);
    }

    if (fullAmount.length >= 3) {
      evaluate(fullAmount)
    } else {
      fullAmount.push(func[0])
    }

    $("#res").val(fullAmount);
    func = null
    num = []
  });

  $('#equals').click(function() {
    if (fullAmount[1] === "+") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] + fullAmount[2]
      fullAmount = []
      num = []

    } else if (fullAmount[1] === "-") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] - fullAmount[2]
      fullAmount = []
      num = []

    } else if (fullAmount[1] === "X") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] * fullAmount[2]
      fullAmount = []
      num = []

    } else if (fullAmount[1] === "÷") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] / fullAmount[2]
      fullAmount = []
      num = []

    } else {
      console.log("error")
    }
    $("#res").val(complete);
  });

  $('#clear').click(function() {
    num = []
    fullAmount = []
    func = null
    complete = null
    $("#res").val("")

  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

<!DOCTYPE html>

  <title></title>

  <link rel="stylesheet" type="text/css" href="calc.css">

    <form class="show">
      <input type="text" id="res" name="numbers" disabled>

    </form>

              <button id="clear" type="button">AC</button>
              <button id="sign" class="action" type="button">+/-</button>
              <button id="divide" class="action" type="button">÷</button>

              <button id="seven" class="num" type="button">7</button>
              <button id="eight" class="num" type="button">8</button>
              <button id="nine" class="num" type="button">9</button>
              <button id="multiply" class="action" type="button">X</button>

              <button id="four" class="num" type="button">4</button>
              <button id="five" class="num" type="button">5</button>
              <button id="six" class="num" class="num" type="button">6</button>
              <button id="minus" class="action" type="button">-</button>

              <button id="one" class="num" type="button">1</button>
              <button id="two" class="num" type="button">2</button>
              <button id="three" class="num" type="button">3</button>
              <button id="plus" class="action" type="button">+</button>

              <button id="zero" class="num" type="button">0</button>
              <button id="equals" type="button">=</button>

```

Body:
The issue I am having is that the math is not working as intended. I would like the calculator to auto evaluate the amount if the length of the fullAmount variable length is equal to 3 and then clear the num variable and the fullAmount variable but leave the current number that has been evaluated. So if you put 9 * 1 into the calculator I want it to leave num = [] and fullAmount = [9] but it is currently leaving the fullAmount with [9,*,1] and then adds on to it.

$(document).ready(function() {

  var fullAmount = []

  var num = []

  var func = null

  function evaluate(array) {
    if (array[1] === "+") {
      var complete = array[0] + array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "-") {
      var complete = array[0] - array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "X") {
      var complete = array[0] * array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else if (array[1] === "÷") {
      var complete = array[0] / array[2]
      array = [complete]
      fullAmount.push(func[0])
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  }

  $('.num').click(function() {
    num.push($(this).text())
    console.log(num)
    console.log(fullAmount)
    $("#res").val(num.join(''));
  });

  $('.action').click(function() {
    func = $(this).text();
    num = num.join("")
    fullAmount.push(parseInt(num))
    if (fullAmount.length >= 3) {
      evaluate(fullAmount)
    } else {
      fullAmount.push(func[0])
      console.log(func)
    }

    $("#res").val(fullAmount);
    func = null
    num = []
  });

  $('#equals').click(function() {
    if (fullAmount[1] === "+") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] + fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "-") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] - fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "X") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] * fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else if (fullAmount[1] === "÷") {
      fullAmount.push(parseInt(num))
      var complete = fullAmount[0] / fullAmount[2]
      fullAmount = [complete]
      console.log(complete)
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  });

  $('#clear').click(function() {
    num = []
    fullAmount = []
    func = null
    $("#res").val("")
    console.log(num)
    console.log(fullAmount)
    console.log(func)

  });
});

<!DOCTYPE html>

  <title></title>

  <link rel="stylesheet" type="text/css" href="calc.css">

    <form class="show">
      <input type="text" id="res" name="numbers" disabled>

    </form>

              <button id="clear" type="button">AC</button>
              <button id="sign" class="action" type="button">+/-</button>
              <button id="divide" class="action" type="button">÷</button>

              <button id="seven" class="num" type="button">7</button>
              <button id="eight" class="num" type="button">8</button>
              <button id="nine" class="num" type="button">9</button>
              <button id="multiply" class="action" type="button">X</button>

              <button id="four" class="num" type="button">4</button>
              <button id="five" class="num" type="button">5</button>
              <button id="six" class="num" class="num" type="button">6</button>
              <button id="minus" class="action" type="button">-</button>

              <button id="one" class="num" type="button">1</button>
              <button id="two" class="num" type="button">2</button>
              <button id="three" class="num" type="button">3</button>
              <button id="plus" class="action" type="button">+</button>

              <button id="zero" class="num" type="button">0</button>
              <button id="equals" type="button">=</button>

Body:
I made some changes in your calculator code.

After each operation, the arrays num and fullAmount are reinitialized so that they can be used for new computation.

To get the value of the previous operation, the variable complete is declared global. Let's suppose the user typed in 2 + 3 = + 5. The result should be 10. By declaring the variable complete global, I can make some check on it after. See the snippet below:

$(document).ready(function() {

  var fullAmount = []

  var num = []

  var func = null

  var complete = null

  function evaluate(array) {
    if (array[1] === "+") {
      var complete = array[0] + array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else if (array[1] === "-") {
      var complete = array[0] - array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else if (array[1] === "X") {
      var complete = array[0] * array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else if (array[1] === "÷") {
      var complete = array[0] / array[2]
      array = [complete]
      fullAmount.push(func[0])
    } else {
      console.log("error")
    }
    $("#res").val(complete);
  }

  $('.num').click(function() {
    num.push($(this).text())
    $("#res").val(num.join(''));
  });

  $('.action').click(function() {
    func = $(this).text();
    num = num.join("")

    if(parseInt(num)){
     fullAmount.push(parseInt(num))
    }
    //if there is no value before operator, the calculator will use previous value
    else if(complete && !fullAmount[0]){
      fullAmount.push(complete);
    }

    if (fullAmount.length >= 3) {
      evaluate(fullAmount)
    } else {
      fullAmount.push(func[0])
    }

    $("#res").val(fullAmount);
    func = null
    num = []
  });

  $('#equals').click(function() {
    if (fullAmount[1] === "+") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] + fullAmount[2]
      fullAmount = []
      num = []

    } else if (fullAmount[1] === "-") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] - fullAmount[2]
      fullAmount = []
      num = []

    } else if (fullAmount[1] === "X") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] * fullAmount[2]
      fullAmount = []
      num = []

    } else if (fullAmount[1] === "÷") {
      fullAmount.push(parseInt(num))
      complete = fullAmount[0] / fullAmount[2]
      fullAmount = []
      num = []

    } else {
      console.log("error")
    }
    $("#res").val(complete);
  });

  $('#clear').click(function() {
    num = []
    fullAmount = []
    func = null
    complete = null
    $("#res").val("")

  });
});

.as-console-wrapper { max-height: 100% !important; top: 0; }

<!DOCTYPE html>
<html>

<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js">
  </script>
  <script src="calc.js"></script>
  <link rel="stylesheet" type="text/css" href="calc.css">
</head>

<body>
  <div id="calculator-container">
    <form class="show">
      <input type="text" id="res" name="numbers" disabled><br>
    </form>
    <center>
      <div class="calculator-view">
        <table>
          <tr>
            <td>
              <button id="clear" type="button">AC</button>
              <button id="sign" class="action" type="button">+/-</button>
              <button id="divide" class="action" type="button">÷</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="seven" class="num" type="button">7</button>
              <button id="eight" class="num" type="button">8</button>
              <button id="nine" class="num" type="button">9</button>
              <button id="multiply" class="action" type="button">X</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="four" class="num" type="button">4</button>
              <button id="five" class="num" type="button">5</button>
              <button id="six" class="num" class="num" type="button">6</button>
              <button id="minus" class="action" type="button">-</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="one" class="num" type="button">1</button>
              <button id="two" class="num" type="button">2</button>
              <button id="three" class="num" type="button">3</button>
              <button id="plus" class="action" type="button">+</button>
            </td>
          </tr>
          <tr>
            <td>
              <button id="zero" class="num" type="button">0</button>
              <button id="equals" type="button">=</button>
            </td>
          </tr>
        </table>
      </div>
</body>

</html>


问:
Apache 2.4 Fails to install on Windows 10
```<code>Windows 10
Apache 2.4-64 (httpd-2.4.27-Win64-VC15.zip)
</code>```

I downloaded httpd-2.4.27-Win64-VC15.zip and unpacked it to c:Apache24

I modified the httpd.conf file:

```<code>Listen *:80
ServerName localhost:80

cd \Apache24\bin

httpd -k shutdown
</code>```

response is:

```<code>The 'Apache2.4' service is not started

httpd -k install
</code>```

response is:

```<code>[Wed Aug 23 13:17:03.258023 2017] [mpm_winnt:error] [pid 1196:tid 412] AH00433: Apache2.4: Service is already installed.
</code>```

At one point, Apache 2.4 was installed to a directory called c:\localhost and may have been improperly removed.

I checked the services/processes, and killed the IIS server and there is no mention of an Apache 2.4 running. I also checked the startup folder, and there is no Apache 2.4

It seems that Apache 2.4, or some other ghost process, that thinks Apache 2.4 is still running in the non-existing c:\localhost folder. I've rebooted the system, to no avail. Any idea how to diagnose this problem?

答:
This may help:

Go to C:\Apache24\conf and open httpd.conf in notepad

Search for 'Listen 80'

Change port number to 85 i.e. 'Listen 85' or whatever you prefer

Body:
Windows 10
Apache 2.4-64 (httpd-2.4.27-Win64-VC15.zip)

I downloaded httpd-2.4.27-Win64-VC15.zip and unpacked it to c:Apache24

I modified the httpd.conf file:

Listen *:80
ServerName localhost:80

cd \Apache24\bin

httpd -k shutdown

response is:

The 'Apache2.4' service is not started

httpd -k install

response is:

[Wed Aug 23 13:17:03.258023 2017] [mpm_winnt:error] [pid 1196:tid 412] AH00433: Apache2.4: Service is already installed.

At one point, Apache 2.4 was installed to a directory called c:\localhost and may have been improperly removed.

I checked the services/processes, and killed the IIS server and there is no mention of an Apache 2.4 running. I also checked the startup folder, and there is no Apache 2.4

It seems that Apache 2.4, or some other ghost process, that thinks Apache 2.4 is still running in the non-existing c:\localhost folder. I've rebooted the system, to no avail. Any idea how to diagnose this problem?


问:
Rounded corner throughout the whole progress
I have a progress view and I see that if I change its corner radius I get rounded corners when the progress is 1.0 (full), however, I'd like to have rounded corner throughout the whole progress, for example, the image below shows a progress on half way, as you can see only the left end has rounded corners.

I already set these properties on the viewDidLoad:

```<code>progressView.clipsToBounds = true
progressView.layer.cornerRadius = 3
progressView.layer.masksToBounds = true
</code>```

答:
This is the correct answer</p>

```<code>// Set the rounded edge for the outer bar
self.layer.cornerRadius = 12
self.clipsToBounds = true

// Set the rounded edge for the inner bar
self.layer.sublayers![1].cornerRadius = 12
self.subviews[1].clipsToBounds = true
</code>```

Body:
I have a progress view and I see that if I change its corner radius I get rounded corners when the progress is 1.0 (full), however, I'd like to have rounded corner throughout the whole progress, for example, the image below shows a progress on half way, as you can see only the left end has rounded corners.

I already set these properties on the viewDidLoad:

progressView.clipsToBounds = true
progressView.layer.cornerRadius = 3
progressView.layer.masksToBounds = true

Body:
This is the correct answer

// Set the rounded edge for the outer bar
self.layer.cornerRadius = 12
self.clipsToBounds = true

// Set the rounded edge for the inner bar
self.layer.sublayers![1].cornerRadius = 12
self.subviews[1].clipsToBounds = true


问:
Is there a maximum limit for the value max_allowed_packet?
I am running a drupal site. I got an error in my site user warning: Got a packet bigger than 'max_allowed_packet' bytes query. I have set the value as high as 128M . Even after that same error is reported.

What is the issue here?? Why is it not working ??

Is there a maximum limit for the value max_allowed_packet ?

答:
You need to set the setting in all sections that apply to the action you are doing, and always in the [MySQLd] section. The setting applies to the buffer of the elements you are using. So under [MySQLd] is for your MySQL server proces deamon on linux / service on windows. And if you want to make a dump with MySQLDump add it as parameter on the command line or make a section [MySQLDump] in your my.ini as well for this tool with the same parameter to make it permanent. If you want to import the dump again with MySQL again use the parameter on the command line or make a section [MySQL] with again the same parameter in your my.ini to make the choice permanent for this tools also.

I kept on talking about my.ini because i am on windows but on linux that is my.cnf of course.

I decided to explain it here because it took me ages to figure this out because it is not explained anywhere. In examples however i noticed some ppl having the setting under multiple sections so i started to google more and found correlation between the sections and the actions they where doing. Now i never have this problem anymore and settings as high as the mentioned 128M here are not needed in most cases. However because it's the maximum the server will use for this buffer if you have the memory just set it high enough to never get into trouble with your actions. The size you actually need is a little bit larger than the largest record in your database.


问:
Modifying responses in service worker requests to be an image
Hello and thank you in advance.

My question is about responding to a network request using ServiceWorker. I am able to handle it in case of a text or html, but when I am trying to deal with an image I am failing, here is the code I have:

```<code>self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('The page wasn\'t found');
        }
        return response;
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });
</code>```

The snippet above is working when dealing with text and html but when I am trying with an image it brings a totally black screen. Here what I used but it didn't work.

```<code>self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});
        }
        return response;
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });
</code>```

Hopefully you can help me in knowing what I am missing. thanks.

答:
You need to replace your line :

```<code>return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});
</code>```

By :

```<code>return new Response("<img src='/imgs/sunset.gif'/>", {headers:{'Content-Type': 'text/html'}});
</code>```

You want to display a gif in your page, so you have to add a html content with  and tell its source src.

Or easier solution you can only write this :

```<code>return fetch('/imgs/sunset.gif');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello and thank you in advance.

My question is about responding to a network request using ServiceWorker. I am able to handle it in case of a text or html, but when I am trying to deal with an image I am failing, here is the code I have:

self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('The page wasn\'t found');
        }
        return response;
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });

The snippet above is working when dealing with text and html but when I am trying with an image it brings a totally black screen. Here what I used but it didn't work.

self.addEventListener('fetch', function(event){
event.respondWith(
    fetch(event.request).then(function(response){
        if(response.status === 404){
            return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});
        }
        return response;
     }).catch(function(){
            return new Response('The network is totally failed');
     })
    );
 });

Hopefully you can help me in knowing what I am missing. thanks.

Body:
You need to replace your line :

return new Response('/imgs/sunset.gif', {headers:{'Content-Type':'image/gif'}});

By :

return new Response("<img src='/imgs/sunset.gif'/>", {headers:{'Content-Type': 'text/html'}});

You want to display a gif in your page, so you have to add a html content with  and tell its source src.

Or easier solution you can only write this :

return fetch('/imgs/sunset.gif');


问:
Programmatically create entity/table using CoreData and insert values into that entity in Swift 3 for iOS
I have been trying to find a way to programmatically create the database entity/table at runtime in Swift 3 for iOS platform.
Please explain the process in detail. I have followed other links but nothing worked for me and I was unable to understand the process properly so please explain the whole process with working code instead of providing other existing links.

There is one more table which has been added from XCode and I can perform the database related operations (insert row, delete, update) on that table but I am unable to find a way to perform following operations on the table which will be created programmatically at run time.
There are following operations that need to be performed.

Add Entity - From interface, user can add entity name, number of columns, column names then on tapping a button the entity should be created into the database using CoreData. User can add any number of tables from the interface.

Insert Values - Then user will have interface to insert values into the entity. The name of the entity will be known and the values for a row in the entity will be entered by user. On tapping a button the row should be inserted into the entity/database-table.

Fetch Values - User will have an option to fetch all the saved values form the entity. To use them anytime when needed.

Update value - User will be able to update any value present in the table which was created programmatically.

Delete Entity - There will be an option to delete the database entity as well. On tapping a button, the name of the entity will be passed to the function and that entity/database-table will be deleted from the database.

I have tried the following code -:

```<code>    let model = NSManagedObjectModel()
    let entityName = "TestEntity"
    let entity = NSEntityDescription()
    entity.name = entityName
    entity.managedObjectClassName = entityName

    // Creating a attribute
    let remoteURLAttribute = NSAttributeDescription()
    remoteURLAttribute.name = "columnOne"
    remoteURLAttribute.attributeType = .stringAttributeType
    remoteURLAttribute.isOptional = true
    remoteURLAttribute.isIndexed = true

    var properties = Array<NSAttributeDescription>()
    properties.append(remoteURLAttribute)
    // Adding the attribute to the entity
    entity.properties = properties

    // Adding the entity into the model
    model.entities = [entity]

    do {
        try CoreDataManager.managedObjectContext.save()
    } catch {
        print(error)
    }

    // Inserting the data into the entity
    let testEntity = NSManagedObject(entity: entity, insertInto: CoreDataManager.managedObjectContext)
    testEntity.setValue("WHY SO SERIOUS?", forKey: "columnOne")

    do {
        try CoreDataManager.managedObjectContext.save()
    } catch {
        print(error)
    }

    // Fetching the data from the entity
    let request = NSFetchRequest<NSFetchRequestResult>()
    request.entity = entity
    request.propertiesToFetch = ["columnOne"]
    request.returnsDistinctResults = false
    do {
        let results = try CoreDataManager.managedObjectContext.fetch(request)
        print(results)
    } catch {

    }
</code>```

I am getting the following value in the results -:

▿ 1 element
    - 0 :  (entity: TestEntity; id: 0x600000422f80
   ;
  data: {
      columnOne = "WHY SO SERIOUS?"; })

But I don't have any way to get the values from this entity anywhere else and insert the values into the entity from other places as well by using entity name which is TestEntity in this case.

答:
Some of the steps you describe are simply not possible with Core Data. Or at least, not without making things extremely complex and difficult for you. Asking for complete working code is not reasonable because you have an extremely unusual and complex set of requirements for Core Data.

It's true that the NSManagedModel and all of the entities are mutable and can be changed in code. Except, all of these changes must be made before you use that model to load any data. You cannot make changes after you call loadPersistentStores(_:) (if you're using NSPersistentContainer) or addPersistentStore(ofType:configurationName:at:options:) (if you're not using NSPersistentContainer). Doing so is a run-time error that will crash your app.

Because of this, the idea of providing a user interface to dynamically create and delete Core Data entities is not really an option. You can create and delete instances of entities but not the entity descriptions.

If you're willing to do a lot of hard work, you might be able to get something close. The closest you could get with Core Data would be to create an entirely new managed object model any time you need a change. Then copy all of your data to a new persistent store file using this model (including whatever custom code you need to handle non-lightweight migration). Then delete the old model and persistent store file and all references to all objects that you previously fetched with them.

This will be very difficult to get right and may have unforeseen difficulties that I haven't thought of. I would strongly urge not attempting to do this with Core Data, because it was not designed to be used in this way.

Body:
I have been trying to find a way to programmatically create the database entity/table at runtime in Swift 3 for iOS platform.
Please explain the process in detail. I have followed other links but nothing worked for me and I was unable to understand the process properly so please explain the whole process with working code instead of providing other existing links.

There is one more table which has been added from XCode and I can perform the database related operations (insert row, delete, update) on that table but I am unable to find a way to perform following operations on the table which will be created programmatically at run time.
There are following operations that need to be performed.

Add Entity - From interface, user can add entity name, number of columns, column names then on tapping a button the entity should be created into the database using CoreData. User can add any number of tables from the interface.

Insert Values - Then user will have interface to insert values into the entity. The name of the entity will be known and the values for a row in the entity will be entered by user. On tapping a button the row should be inserted into the entity/database-table.

Fetch Values - User will have an option to fetch all the saved values form the entity. To use them anytime when needed.

Update value - User will be able to update any value present in the table which was created programmatically.

Delete Entity - There will be an option to delete the database entity as well. On tapping a button, the name of the entity will be passed to the function and that entity/database-table will be deleted from the database.

I have tried the following code -:

    let model = NSManagedObjectModel()
    let entityName = "TestEntity"
    let entity = NSEntityDescription()
    entity.name = entityName
    entity.managedObjectClassName = entityName

    // Creating a attribute
    let remoteURLAttribute = NSAttributeDescription()
    remoteURLAttribute.name = "columnOne"
    remoteURLAttribute.attributeType = .stringAttributeType
    remoteURLAttribute.isOptional = true
    remoteURLAttribute.isIndexed = true

    var properties = Array<NSAttributeDescription>()
    properties.append(remoteURLAttribute)
    // Adding the attribute to the entity
    entity.properties = properties

    // Adding the entity into the model
    model.entities = [entity]

    do {
        try CoreDataManager.managedObjectContext.save()
    } catch {
        print(error)
    }

    // Inserting the data into the entity
    let testEntity = NSManagedObject(entity: entity, insertInto: CoreDataManager.managedObjectContext)
    testEntity.setValue("WHY SO SERIOUS?", forKey: "columnOne")

    do {
        try CoreDataManager.managedObjectContext.save()
    } catch {
        print(error)
    }

    // Fetching the data from the entity
    let request = NSFetchRequest<NSFetchRequestResult>()
    request.entity = entity
    request.propertiesToFetch = ["columnOne"]
    request.returnsDistinctResults = false
    do {
        let results = try CoreDataManager.managedObjectContext.fetch(request)
        print(results)
    } catch {

    }

I am getting the following value in the results -:

▿ 1 element
    - 0 :  (entity: TestEntity; id: 0x600000422f80
   ;
  data: {
      columnOne = "WHY SO SERIOUS?"; })

But I don't have any way to get the values from this entity anywhere else and insert the values into the entity from other places as well by using entity name which is TestEntity in this case.


问:
How do I change background color of UITabItem when item is selected
I would like a different background color when the user selects a tab bar item than when it is unselected.</p>

答:
My answer is similar to @Mehul Thakkar but it is in Swift 4 and to improve on his answer I would say that if you place the code in viewDidAppear as he suggests users will see the change happening which is not good user experience.

So create the custom class for your tabbar controller and in viewDidLoad
place the following code:

```<code>let singleTabWidth: CGFloat = self.tabBar.frame.size.width / CGFloat((self.tabBar.items?.count)!)
let singleTabSize = CGSize(width:singleTabWidth , height: self.tabBar.frame.size.height)

let selectedTabBackgroundImage: UIImage = self.imageWithColor(color: .white, size: singleTabSize)
self.tabBar.selectionIndicatorImage = selectedTabBackgroundImage
</code>```

The imageWithColor function is below for you:

```<code>//image with color and size
    func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        context!.setFillColor(color.cgColor)
        context!.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }
</code>```

Hope this helps someone.

Body:
My answer is similar to @Mehul Thakkar but it is in Swift 4 and to improve on his answer I would say that if you place the code in viewDidAppear as he suggests users will see the change happening which is not good user experience.

So create the custom class for your tabbar controller and in viewDidLoad
place the following code:

let singleTabWidth: CGFloat = self.tabBar.frame.size.width / CGFloat((self.tabBar.items?.count)!)
let singleTabSize = CGSize(width:singleTabWidth , height: self.tabBar.frame.size.height)

let selectedTabBackgroundImage: UIImage = self.imageWithColor(color: .white, size: singleTabSize)
self.tabBar.selectionIndicatorImage = selectedTabBackgroundImage

The imageWithColor function is below for you:

//image with color and size
    func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()

        context!.setFillColor(color.cgColor)
        context!.fill(rect)

        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return image!
    }

Hope this helps someone.


问:
consecutive punctuation and alpha-numeric characters
Probably a simple question, but I don't have a lot of regex experience. I would like to take a string and select all the consecutive punctuation characters and all the consecutive alpha-numeric characters

This is as close as I could get

```<code>r="my9zza :)asax"
import re
re.findall(r'(\w+)|([^a-zA-Z0-9\s]+)', r)
</code>```

returns

```<code>[('my9zza', ''), ('', ':)'), ('asax', '')]
</code>```

but I would like

```<code>['my9zza', ':)', 'asax']
</code>```

答:
Simply use:

```<code>r = "my9zza :)asax"
import re
print(re.findall(r'\w+|[^a-zA-Z0-9\s]+', r))
</code>```

The problem was having two sets of parentheses in your original code, causing findall to return a 2-ple.

If you wanted to keep the original regex, you can also easily transform your result into the desired output with:

```<code>[x[0] or x[1] for x in result]
</code>```

Body:
Probably a simple question, but I don't have a lot of regex experience. I would like to take a string and select all the consecutive punctuation characters and all the consecutive alpha-numeric characters

This is as close as I could get

r="my9zza :)asax"
import re
re.findall(r'(\w+)|([^a-zA-Z0-9\s]+)', r)

returns

[('my9zza', ''), ('', ':)'), ('asax', '')]

but I would like

['my9zza', ':)', 'asax']

Body:
Simply use:

r = "my9zza :)asax"
import re
print(re.findall(r'\w+|[^a-zA-Z0-9\s]+', r))

The problem was having two sets of parentheses in your original code, causing findall to return a 2-ple.

If you wanted to keep the original regex, you can also easily transform your result into the desired output with:

[x[0] or x[1] for x in result]


问:
Firestore how to get the collection value from another collection document id is referenced
I have two fire store collection with following reference image
.
I want to get the firstName and title. Here signup_id is referenced from coll-signup document id. Following code given below what i did.

Model feed.ts

```<code>export interface Feed {
    firstName? : string;
    signup_id? : string;
    title? : string;
}
</code>```

news feed.component template

```<code>    <ul *ngFor="let feed of feeds">
<!-- <li>{{feed.firstName}}</li> --> // Here I want to print my first name
      <li>{{feed.title}}</li>
      <li>{{feed.signup_id}}</li>
    </ul>
</code>```

news-feed.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Feed } from '../../models/feed';
import { FeedService } from '../../services/feed.service';
@Component({
  selector: 'app-news-feed',
  templateUrl: './news-feed.component.html',
  styleUrls: ['./news-feed.component.css']
})
export class NewsFeedComponent implements OnInit {
  feeds : Feed[];
  constructor(private feedService: FeedService) { }

  ngOnInit() {
    this.feedService.sellectAllNews().subscribe(feeds => {
      this.feeds = feeds;
    })
  }

}
</code>```

feed.service.ts

```<code>    import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
    import { Observable } from 'rxjs/Observable';
    import { Feed } from '../models/feed';
    @Injectable()
    export class FeedService {
      feedCollection : AngularFirestoreCollection<Feed>;
      feedItem : Observable<Feed[]>;

      constructor(private afs : AngularFirestore) {
        this.collectionInitialization();
      }

      collectionInitialization() {
// I think here I have to modify or add next collection to will get the output
        this.feedCollection = this.afs.collection('col-challange');
        this.feedItem = this.feedCollection.stateChanges().map(changes => {
          return changes.map(a => {
            const data = a.payload.doc.data() as Feed;
            return data;
          })
        })

      }
      sellectAllNews() {
        this.collectionInitialization();
        return this.feedItem;
      }
    }
</code>```

this is possible to do fire store?
I'm newbie in fire store.Please help me. Thanks!

答:
You need to combine two collections.

try this code

```<code>this.feedCollection = this.afs.collection('col-challange');
this.feedItem = this.feedCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        //here you get the data without first name
        const data = a.payload.doc.data() as Feed;
        //get the signup_id for getting doc from coll-signup
        const signupId = data.signup_id;
        //get the related document
        return afs.collection('coll-signup').doc(signupId).snapshotChanges().take(1).map(actions => {
          return actions.payload.data();
        }).map(signup => {
          //export the data in feeds interface format
          return { firstName: signup.firstName, ...data };
        });
      })
    }).flatMap(feeds => Observable.combineLatest(feeds));
</code>```

Body:
I have two fire store collection with following reference image
.
I want to get the firstName and title. Here signup_id is referenced from coll-signup document id. Following code given below what i did.

Model feed.ts

export interface Feed {
    firstName? : string;
    signup_id? : string;
    title? : string;
}

news feed.component template

 // Here I want to print my first name

{{feed.title}}

{{feed.signup_id}}

news-feed.component.ts

import { Component, OnInit } from '@angular/core';
import { Feed } from '../../models/feed';
import { FeedService } from '../../services/feed.service';
@Component({
  selector: 'app-news-feed',
  templateUrl: './news-feed.component.html',
  styleUrls: ['./news-feed.component.css']
})
export class NewsFeedComponent implements OnInit {
  feeds : Feed[];
  constructor(private feedService: FeedService) { }

  ngOnInit() {
    this.feedService.sellectAllNews().subscribe(feeds => {
      this.feeds = feeds;
    })
  }

}

feed.service.ts

    import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
    import { Observable } from 'rxjs/Observable';
    import { Feed } from '../models/feed';
    @Injectable()
    export class FeedService {
      feedCollection : AngularFirestoreCollection<Feed>;
      feedItem : Observable<Feed[]>;

      constructor(private afs : AngularFirestore) {
        this.collectionInitialization();
      }

      collectionInitialization() {
// I think here I have to modify or add next collection to will get the output
        this.feedCollection = this.afs.collection('col-challange');
        this.feedItem = this.feedCollection.stateChanges().map(changes => {
          return changes.map(a => {
            const data = a.payload.doc.data() as Feed;
            return data;
          })
        })

      }
      sellectAllNews() {
        this.collectionInitialization();
        return this.feedItem;
      }
    }

this is possible to do fire store?
I'm newbie in fire store.Please help me. Thanks!

Body:
You need to combine two collections.

try this code

this.feedCollection = this.afs.collection('col-challange');
this.feedItem = this.feedCollection.snapshotChanges().map(changes => {
      return changes.map(a => {
        //here you get the data without first name
        const data = a.payload.doc.data() as Feed;
        //get the signup_id for getting doc from coll-signup
        const signupId = data.signup_id;
        //get the related document
        return afs.collection('coll-signup').doc(signupId).snapshotChanges().take(1).map(actions => {
          return actions.payload.data();
        }).map(signup => {
          //export the data in feeds interface format
          return { firstName: signup.firstName, ...data };
        });
      })
    }).flatMap(feeds => Observable.combineLatest(feeds));


问:
Matching root route in webpack-dev-server's historyApiFallback`
Sample repo demonstrating the issue is here.

I'm trying to set up webpack dev server so that:

Requests to / are served by public/landing.html (a static landing page)

Requests to anything else are served by my React app

Using create-react-app, and based on webpack-dev-server's options, I've set up my webpackDevServer.config.js as follows:

    historyApiFallback: {
      // Paths with dots should still use the history fallback.
      // See https://github.com/facebookincubator/create-react-app/issues/387.
      disableDotRule: true,
      rewrites: [
        // shows views/landing.html as the landing page
        { from: /^\/$/, to: 'landing.html' },
        // shows views/subpage.html for all routes starting with /subpage
        { from: /^\/subpage/, to: 'subpage.html' },
        // shows views/404.html on all other pages
        { from: /./, to: '404.html' },
      ],
    },

And when I start webpack here's what I see:

Requests to /subpage are routed correctly to subpage.html

Requests to /foo are routed correctly to 404.html. Eventually, these would be handled by my React app.

Requests to / are routed incorrectly to my React app.

How can I get landing.html to respond to requests at /?

答:
I ended up opening a bug request with webpack-dev-middleware and discovered it was not a bug but a failure of configuration.

Specifically, the issue is using HtmlWebpackPlugin alongside historyApiFallback. I believe plugins are processed before the regex matching, and HtmlWebpackPlugin's default file output is index.html; this means that out of the box, / will always be routed to the HtmlWebpackPlugin output file.

The solution to this is to set a custom filename in HtmlWebpackPlugin, which allows you to control the matching again. Here's a sample repo demonstrating the fix and here's the webpack config:

```<code>module.exports = {
  context: __dirname,
  entry: [
    './app.js',
  ],
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  devServer: {
    publicPath: "/",
    // contentBase: "./public",
    // hot: true,
    historyApiFallback: {
      // disableDotRule: true,
      rewrites: [
        { from: /^\/$/, to: '/public/index.html' },
        { from: /^\/foo/, to: '/public/foo.html' },
        { from: /(.*)/, to: '/test.html' },
      ],
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "Html Webpack html",
      hash: true,
      filename: 'test.html',
      template: 'public/plugin.html',
    }),
  ],
};
</code>```

Body:
I ended up opening a bug request with webpack-dev-middleware and discovered it was not a bug but a failure of configuration.

Specifically, the issue is using HtmlWebpackPlugin alongside historyApiFallback. I believe plugins are processed before the regex matching, and HtmlWebpackPlugin's default file output is index.html; this means that out of the box, / will always be routed to the HtmlWebpackPlugin output file.

The solution to this is to set a custom filename in HtmlWebpackPlugin, which allows you to control the matching again. Here's a sample repo demonstrating the fix and here's the webpack config:

module.exports = {
  context: __dirname,
  entry: [
    './app.js',
  ],
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  devServer: {
    publicPath: "/",
    // contentBase: "./public",
    // hot: true,
    historyApiFallback: {
      // disableDotRule: true,
      rewrites: [
        { from: /^\/$/, to: '/public/index.html' },
        { from: /^\/foo/, to: '/public/foo.html' },
        { from: /(.*)/, to: '/test.html' },
      ],
    }
  },
  plugins: [
    new HtmlWebpackPlugin({
      title: "Html Webpack html",
      hash: true,
      filename: 'test.html',
      template: 'public/plugin.html',
    }),
  ],
};


问:
edge detection using python
```<code>import cv2
import numpy as np

cap = cv2.VideoCapture()

while True:
    _, frame = cap.read()

    laplacia = cv2.Laplacian(frame, cv2.CV_64F)

    cv2.imshow('original', frame)
    cv2.imshow('laplacian', laplacia)

    k = cv2.waitKey(5) & 0xFF
    if k==27:
        break

cv2.destroyAllWindows()
cap.release()
</code>```

I am getting this error

```<code>#laplacia = cv2.Laplacian(frame, cv2.CV_64F)
cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\core\src\matrix.cpp:981: error: (-215) dims <= 2 && step[0] > 0 in function cv::Mat::locateROI
</code>```

答:
cv2.Laplacian() won't work with Color images.

You can go through OpenCV Documentation for knowing more..Image Gradients

You must convert the frame you have captured to gray scale and then apply Laplacian

```<code>gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
</code>```

You can convert to gray scale as shown above..

Title: edge detection using python

Body:
import cv2
import numpy as np

cap = cv2.VideoCapture()

while True:
    _, frame = cap.read()

    laplacia = cv2.Laplacian(frame, cv2.CV_64F)

    cv2.imshow('original', frame)
    cv2.imshow('laplacian', laplacia)

    k = cv2.waitKey(5) & 0xFF
    if k==27:
        break

cv2.destroyAllWindows()
cap.release()

I am getting this error

#laplacia = cv2.Laplacian(frame, cv2.CV_64F)
cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\core\src\matrix.cpp:981: error: (-215) dims <= 2 && step[0] > 0 in function cv::Mat::locateROI

Body:
cv2.Laplacian() won't work with Color images.

You can go through OpenCV Documentation for knowing more..Image Gradients

You must convert the frame you have captured to gray scale and then apply Laplacian

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

You can convert to gray scale as shown above..


问:
Handling various message with IDialog
Let's say you have a ContactUsDialog, PizzaOrderDialog as well as a MyOrderDialog. The user sends a message like: 'how far along is my pizza order' - How would you know which dialog to start?

```<code>    public async Task<HttpResponseMessage> Post([FromBody] Activity activity)
    {
        if (activity != null)
        {
            switch (activity.GetActivityType())
            {
                case ActivityTypes.Message:
                    await Conversation.SendAsync(activity, () => new ContactUsDialg());
                    await Conversation.SendAsync(activity, () => new PizzaOrderDialog());
                    await Conversation.SendAsync(activity, () => new MyOrderDialog());
                    break;
        }
        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
    }
</code>```

答:
You can't do that in the way you are trying to. You need decide which one will be the root dialog and the re-route messages to other dialogs.

A few samples that might help you:

core-MultiDialogs: to understand how to call/forward messages to child dialogs

intelligence-LUIS: to understand how to use LUIS

And yes, you can use LUIS as root dialog and then call child dialogs. Some posts that might help too:

LUIS / Bot Framework multiple dialog, move intent handling to another dialog

How to forward from RootDialog to LuisDialog in Bot Framework

How does navigation work with LUIS subdialogs?

Title: Handling various message with IDialog

Body:
Let's say you have a ContactUsDialog, PizzaOrderDialog as well as a MyOrderDialog. The user sends a message like: 'how far along is my pizza order' - How would you know which dialog to start?

    public async Task<HttpResponseMessage> Post([FromBody] Activity activity)
    {
        if (activity != null)
        {
            switch (activity.GetActivityType())
            {
                case ActivityTypes.Message:
                    await Conversation.SendAsync(activity, () => new ContactUsDialg());
                    await Conversation.SendAsync(activity, () => new PizzaOrderDialog());
                    await Conversation.SendAsync(activity, () => new MyOrderDialog());
                    break;
        }
        return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
    }


问:
HTML table output to excel using javascript: numbers output as octal with missing leading zero
I have a html table, which I'm passing to an Excel file with javascript.
I'm using excellentexport library which I downloaded from https://github.com/jmaister/excellentexport .
The data in the table transferring well to the excel file, except the numbers  column, which some rows starting with zero and when the data is transferring to excel the numbers treated as octal. Numbers that not starting with zero are transferring well. so for example 0001 will be 1 in the excel file, and I do need it to be output as 0001 as original.
attached my live sample code: http://jsfiddle.net/mv4ooc7m/1/ and I need that the excel output will be same as the HTML table.
Anybody can help me how to fix the javascript code and to send the data as string? I'll be very glad to find a solution, thank you so much for your help!

HTML:

```<code>    <div id="itemRowsList2">
<table class="table table-hover" name="ItemsList" border="2">
<tbody>
<tr class="active" id="rowNum1"><td class="active">0001</td></tr>
<tr class="active" id="rowNum2"><td class="active">0002 </td></tr>
<tr class="active" id="rowNum3"><td class="active">1001 </td></tr>
<tr class="active" id="rowNum4"><td class="active">1002 </td></tr>
</tbody></table>
</div>
</code>```

Javascript:

```<code>/**
 * ExcellentExport.
 * A client side Javascript export to Excel.
 *
 * @author: Jordi Burgos (jordiburgos@gmail.com)
 *
 * Based on:
 * https://gist.github.com/insin/1031969
 * http://jsfiddle.net/insin/cmewv/
 *
 * CSV: http://en.wikipedia.org/wiki/Comma-separated_values
 */

/*
 * Base64 encoder/decoder from: http://jsperf.com/base64-optimized
 */

/*jslint browser: true, bitwise: true, plusplus: true, vars: true, white: true */

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var fromCharCode = String.fromCharCode;
var INVALID_CHARACTER_ERR = (function () {
        "use strict";
        // fabricate a suitable error object
        try {
            document.createElement('$');
        } catch (error) {
            return error;
        }
    }());

// encoder
if (!window.btoa) {
    window.btoa = function (string) {
        "use strict";
        var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, max = Math.max, result = '';

        while (i < len) {
            a = string.charCodeAt(i++) || 0;
            b = string.charCodeAt(i++) || 0;
            c = string.charCodeAt(i++) || 0;

            if (max(a, b, c) > 0xFF) {
                throw INVALID_CHARACTER_ERR;
            }

            b1 = (a >> 2) & 0x3F;
            b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
            b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
            b4 = c & 0x3F;

            if (!b) {
                b3 = b4 = 64;
            } else if (!c) {
                b4 = 64;
            }
            result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4);
        }
        return result;
    };
}

// decoder
if (!window.atob) {
    window.atob = function(string) {
        "use strict";
        string = string.replace(new RegExp("=+$"), '');
        var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, chars = [];

        if (len % 4 === 1) {
            throw INVALID_CHARACTER_ERR;
        }

        while (i < len) {
            b1 = characters.indexOf(string.charAt(i++));
            b2 = characters.indexOf(string.charAt(i++));
            b3 = characters.indexOf(string.charAt(i++));
            b4 = characters.indexOf(string.charAt(i++));

            a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3);
            b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF);
            c = ((b3 & 0x3) << 6) | (b4 & 0x3F);

            chars.push(fromCharCode(a));
            b && chars.push(fromCharCode(b));
            c && chars.push(fromCharCode(c));
        }
        return chars.join('');
    };
}

ExcellentExport = (function() {
    "use strict";
    var version = "1.3";
    var csvSeparator = ',';
    var uri = {excel: 'data:application/vnd.ms-excel;base64,', csv: 'data:application/csv;base64,'};
    var template = {excel: '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'};
    var csvDelimiter = ",";
    var csvNewLine = "\r\n";
    var base64 = function(s) {
        return window.btoa(window.unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(new RegExp("{(\\w+)}", "g"), function(m, p) {
            return c[p];
        });
    };

    var get = function(element) {
        if (!element.nodeType) {
            return document.getElementById(element);
        }
        return element;
    };

    var fixCSVField = function(value) {
        var fixedValue = value;
        var addQuotes = (value.indexOf(csvDelimiter) !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
        var replaceDoubleQuotes = (value.indexOf('"') !== -1);

        if (replaceDoubleQuotes) {
            fixedValue = fixedValue.replace(/"/g, '""');
        }
        if (addQuotes || replaceDoubleQuotes) {
            fixedValue = '"' + fixedValue + '"';
        }
        return fixedValue;
    };

    var tableToCSV = function(table) {
        var data = "";
        var i, j, row, col;
        for (i = 0; i < table.rows.length; i++) {
            row = table.rows[i];
            for (j = 0; j < row.cells.length; j++) {
                col = row.cells[j];
                data = data + (j ? csvDelimiter : '') + fixCSVField(col.textContent.trim());
            }
            data = data + csvNewLine;
        }
        return data;
    };

    var ee = {
        /** @expose */
        excel: function(anchor, table, name) {
            table = get(table);
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
            var hrefvalue = uri.excel + base64(format(template.excel, ctx));
            anchor.href = hrefvalue;
            // Return true to allow the link to work
            return true;
        },
        /** @expose */
        csv: function(anchor, table, delimiter, newLine) {
            if (delimiter !== undefined && delimiter) {
                csvDelimiter = delimiter;
            }
            if (newLine !== undefined && newLine) {
                csvNewLine = newLine;
            }
            table = get(table);
            var csvData = tableToCSV(table);
            var hrefvalue = uri.csv + base64(csvData);
            anchor.href = hrefvalue;
            return true;
        }
    };

    return ee;
}());
</code>```

答:
x:str didn't work for me, but prefixing the number with   did for exmaple  09876	.

Source: http://www.tek-tips.com/viewthread.cfm?qid=821266

Body:
I have a html table, which I'm passing to an Excel file with javascript.
I'm using excellentexport library which I downloaded from https://github.com/jmaister/excellentexport .
The data in the table transferring well to the excel file, except the numbers  column, which some rows starting with zero and when the data is transferring to excel the numbers treated as octal. Numbers that not starting with zero are transferring well. so for example 0001 will be 1 in the excel file, and I do need it to be output as 0001 as original.
attached my live sample code: http://jsfiddle.net/mv4ooc7m/1/ and I need that the excel output will be same as the HTML table.
Anybody can help me how to fix the javascript code and to send the data as string? I'll be very glad to find a solution, thank you so much for your help!

HTML:

0001

0002

1001

1002

Javascript:

/**
 * ExcellentExport.
 * A client side Javascript export to Excel.
 *
 * @author: Jordi Burgos (jordiburgos@gmail.com)
 *
 * Based on:
 * https://gist.github.com/insin/1031969
 * http://jsfiddle.net/insin/cmewv/
 *
 * CSV: http://en.wikipedia.org/wiki/Comma-separated_values
 */

/*
 * Base64 encoder/decoder from: http://jsperf.com/base64-optimized
 */

/*jslint browser: true, bitwise: true, plusplus: true, vars: true, white: true */

var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var fromCharCode = String.fromCharCode;
var INVALID_CHARACTER_ERR = (function () {
        "use strict";
        // fabricate a suitable error object
        try {
            document.createElement('$');
        } catch (error) {
            return error;
        }
    }());

// encoder
if (!window.btoa) {
    window.btoa = function (string) {
        "use strict";
        var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, max = Math.max, result = '';

        while (i < len) {
            a = string.charCodeAt(i++) || 0;
            b = string.charCodeAt(i++) || 0;
            c = string.charCodeAt(i++) || 0;

            if (max(a, b, c) > 0xFF) {
                throw INVALID_CHARACTER_ERR;
            }

            b1 = (a >> 2) & 0x3F;
            b2 = ((a & 0x3) << 4) | ((b >> 4) & 0xF);
            b3 = ((b & 0xF) << 2) | ((c >> 6) & 0x3);
            b4 = c & 0x3F;

            if (!b) {
                b3 = b4 = 64;
            } else if (!c) {
                b4 = 64;
            }
            result += characters.charAt(b1) + characters.charAt(b2) + characters.charAt(b3) + characters.charAt(b4);
        }
        return result;
    };
}

// decoder
if (!window.atob) {
    window.atob = function(string) {
        "use strict";
        string = string.replace(new RegExp("=+$"), '');
        var a, b, b1, b2, b3, b4, c, i = 0, len = string.length, chars = [];

        if (len % 4 === 1) {
            throw INVALID_CHARACTER_ERR;
        }

        while (i < len) {
            b1 = characters.indexOf(string.charAt(i++));
            b2 = characters.indexOf(string.charAt(i++));
            b3 = characters.indexOf(string.charAt(i++));
            b4 = characters.indexOf(string.charAt(i++));

            a = ((b1 & 0x3F) << 2) | ((b2 >> 4) & 0x3);
            b = ((b2 & 0xF) << 4) | ((b3 >> 2) & 0xF);
            c = ((b3 & 0x3) << 6) | (b4 & 0x3F);

            chars.push(fromCharCode(a));
            b && chars.push(fromCharCode(b));
            c && chars.push(fromCharCode(c));
        }
        return chars.join('');
    };
}

ExcellentExport = (function() {
    "use strict";
    var version = "1.3";
    var csvSeparator = ',';
    var uri = {excel: 'data:application/vnd.ms-excel;base64,', csv: 'data:application/csv;base64,'};
    var template = {excel: '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
{table}
'};
    var csvDelimiter = ",";
    var csvNewLine = "\r\n";
    var base64 = function(s) {
        return window.btoa(window.unescape(encodeURIComponent(s)));
    };
    var format = function(s, c) {
        return s.replace(new RegExp("{(\\w+)}", "g"), function(m, p) {
            return c[p];
        });
    };

    var get = function(element) {
        if (!element.nodeType) {
            return document.getElementById(element);
        }
        return element;
    };

    var fixCSVField = function(value) {
        var fixedValue = value;
        var addQuotes = (value.indexOf(csvDelimiter) !== -1) || (value.indexOf('\r') !== -1) || (value.indexOf('\n') !== -1);
        var replaceDoubleQuotes = (value.indexOf('"') !== -1);

        if (replaceDoubleQuotes) {
            fixedValue = fixedValue.replace(/"/g, '""');
        }
        if (addQuotes || replaceDoubleQuotes) {
            fixedValue = '"' + fixedValue + '"';
        }
        return fixedValue;
    };

    var tableToCSV = function(table) {
        var data = "";
        var i, j, row, col;
        for (i = 0; i < table.rows.length; i++) {
            row = table.rows[i];
            for (j = 0; j < row.cells.length; j++) {
                col = row.cells[j];
                data = data + (j ? csvDelimiter : '') + fixCSVField(col.textContent.trim());
            }
            data = data + csvNewLine;
        }
        return data;
    };

    var ee = {
        /** @expose */
        excel: function(anchor, table, name) {
            table = get(table);
            var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
            var hrefvalue = uri.excel + base64(format(template.excel, ctx));
            anchor.href = hrefvalue;
            // Return true to allow the link to work
            return true;
        },
        /** @expose */
        csv: function(anchor, table, delimiter, newLine) {
            if (delimiter !== undefined && delimiter) {
                csvDelimiter = delimiter;
            }
            if (newLine !== undefined && newLine) {
                csvNewLine = newLine;
            }
            table = get(table);
            var csvData = tableToCSV(table);
            var hrefvalue = uri.csv + base64(csvData);
            anchor.href = hrefvalue;
            return true;
        }
    };

    return ee;
}());

Body:
x:str didn't work for me, but prefixing the number with &nbsp; did for exmaple <td>&nbsp;09876</td>.

Source: http://www.tek-tips.com/viewthread.cfm?qid=821266


问:
Mapping objects
Does anyone know about any third party .NET libraries which could map objects between different layers of a project like view and model.</p>

答: Sounds like AutoMapper is what you're looking for</p>

Title: Mapping objects


问:
How to make rounded corner progress bar in swift?
Here I Have tried to make Rounded Rect corner progress bar but I have some problem to create it, here I have post my code what I am tried?

Any one Give idea to customize the progress bar to rounded rect corner progress bar.

```<code>self.progressView.frame=CGRectMake(55, 490, 200, 15)
self.progressView.layer.cornerRadius = 15.0
self.progressView.transform=CGAffineTransformMakeScale(1.0, 7.0)
</code>```

答:
And if you want to have rounded edges for the inner bar too, you can also add this code:</p>

```<code>// Set the rounded edge for the outer bar
self.layer.cornerRadius = 12
self.clipsToBounds = true

// Set the rounded edge for the inner bar
self.layer.sublayers![1].cornerRadius = 12
self.subviews[1].clipsToBounds = true
</code>```

Body:
Here I Have tried to make Rounded Rect corner progress bar but I have some problem to create it, here I have post my code what I am tried?

Any one Give idea to customize the progress bar to rounded rect corner progress bar.

self.progressView.frame=CGRectMake(55, 490, 200, 15)
self.progressView.layer.cornerRadius = 15.0
self.progressView.transform=CGAffineTransformMakeScale(1.0, 7.0)

Body:
And if you want to have rounded edges for the inner bar too, you can also add this code:

// Set the rounded edge for the outer bar
self.layer.cornerRadius = 12
self.clipsToBounds = true

// Set the rounded edge for the inner bar
self.layer.sublayers![1].cornerRadius = 12
self.subviews[1].clipsToBounds = true


问:
RxJS emit array items over time?
I'm trying to emit simple array values one after another with 500ms in between:

```<code>var a = Rx.Observable.from([1,2,3]);
a.interval(500).subscribe(function(b) { console.log(b); });
</code>```

However, this throws an exception:

```<code>Uncaught TypeError: a.interval is not a function.
</code>```

答:
I find Weichhold technique to be the best but that it would gain in clarity of intent by extracting the zipped value outside of the zip: </p>

```<code>// assume some input stream of values:
var inputs = Obs.of(1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8);
// emit each value from stream at a given interval:
var events = Obs.zip(inputs, Obs.interval(1000))
    .map(val => val[0])
    .forEach(console.log);
</code>```

Title: RxJS emit array items over time?

Body:
I'm trying to emit simple array values one after another with 500ms in between:

var a = Rx.Observable.from([1,2,3]);
a.interval(500).subscribe(function(b) { console.log(b); });

However, this throws an exception:

Uncaught TypeError: a.interval is not a function.

Body:
I find Weichhold technique to be the best but that it would gain in clarity of intent by extracting the zipped value outside of the zip:

// assume some input stream of values:
var inputs = Obs.of(1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8);
// emit each value from stream at a given interval:
var events = Obs.zip(inputs, Obs.interval(1000))
    .map(val => val[0])
    .forEach(console.log);


答:
You can try this:

```<code>s = [('my9zza', ''), ('', ':)'), ('asax', '')]
final_s = [[b for b in i if b][0] for i in s]
</code>```

Output:

```<code>['my9zza', ':)', 'asax']
</code>```

Title: consecutive punctuation and alpha-numeric characters

Body:
You can try this:

s = [('my9zza', ''), ('', ':)'), ('asax', '')]
final_s = [[b for b in i if b][0] for i in s]

Output:

['my9zza', ':)', 'asax']


问:
Can I access the stored favicons for bookmarks using the Firefox extension API?
I'm writing an extension for Firefox 57+ (using the WebExtensions API). Is it possible to access the locally stored favicon for a given URL/bookmark? I'm thinking something like file://{%PROFILE%}/favicons/{% URL %}

答: No, that's currently not possible. https://bugzilla.mozilla.org/show_bug.cgi?id=1411120 tracks this feature request.</p>


问:
How do I force the debugged app to open in a secondary monitor with Visual Studio 2010
When I debug an application in VS2010 I want it to open in my secondary monitor, but it always  opens in the primary monitor. How do I force it to open in the secondary monitor?

I have read elsewhere on SO that I need to move the app to the secondary window and close it (not shift-F5) and it will open there the next time. This doesn't work.

答:
For VS2017, simply do this:
1. select your Visual Studio main window
2. hover mouse over the monitor where you want the app to run
3. Press  to run

App starts wherever mouse was hovering.


问:
Cloudformation template error - Template validation error: Template format error: Every Mappings member Type must be a map
I have a cloudformation template.

It should create an EC2 instance, change the Adminstrator password and rename the server.

I am passing couple of parameters to the stack template.  When I run it, it gives "Template format error: Every Mappings member Type must be a map".

I made sure whatever I am referring in the template, are in the "Mappings" section. Not sure why I am getting this error.

Any suggestions are very helpful.

```<code>{
   "AWSTemplateFormatVersion": "2010-09-09",

   "Parameters": {

"LocalAdminPassword" :
{
  "Type": "String",
  "NoEcho" : "true",
  "Description": "Password for the local server administrator account."
   }
},

 "Mappings": {

"EnvironmentTypeName" :
{
  "PlatformName" : {"Dev" : "D", "Test" : "T", "Prod" : "P"}
},
"QRMEnvironmentType" :
{
  "Description"   :   "QRM Dev, test, or Prod Platform",
  "Type"          :   "String",
  "AllowedValues" :  ["Dev", "Test", "Prod"],
  "Default" : "Dev",
  "ConstraintDescription" : "must be either Dev, test, or Prod"
},
"QRMAvailabilityZoneIndex" :
{
  "Description"   :   "QRM Platform AZ letter A,B, or C for Dev, Test, or Prod",
  "Type"          :   "String",
  "AllowedValues" :  ["A", "B", "C"],
  "Default" : "A",
  "ConstraintDescription" : "Must be a letter of the AZ in the specified Region"
  }
},

 "Resources": {
      "MyInstance": {
      "Type": "AWS::EC2::Instance",
      "Metadata" : {
          "AWS::CloudFormation::Init" : {
         "config" : {
           "files" : {
             "c:\\cfn\\cfn-hup.conf" : {
               "content" : { "Fn::Join" : ["", [
                 "[main]\n",
                 "stack=", { "Ref" : "AWS::StackId" }, "\n",
                 "region=", { "Ref" : "AWS::Region" }, "\n"
                 ]]}
             },
             "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf" : {
               "content": { "Fn::Join" : ["", [
                 "[cfn-auto-reloader-hook]\n",
                 "triggers=post.update\n",
           "path=Resources.MyInstance.Metadata.AWS::CloudFormation::Init\n",
                "action=cfn-init.exe -v -s ", { "Ref" : "AWS::StackId" },
                                                 " -r MyInstance",
                                                 " --region ", { "Ref" : "AWS::Region" }, "\n"
               ]]}
            },
            "c:\\scripts\\test.ps1" : {
               "content": { "Fn::Join" : ["", [
                 "Write-Host Hello World!\n"
               ]]}
             }
           },
           "commands" : {

           "1-run-script" :
            {
                "command" :
                    {
                      "Fn::Join" :
                      [
                        "",
                        [
                          "Powershell.exe  ([adsi]\\\"WinNT://$env:computername/Administrator\\\").SetPassword('",{ "Ref": "LocalAdminPassword"},"')"
                        ]
                      ]
                    }
            },
            "02-rename-server" :
                  {
                    "command" :
                    {
                      "Fn::Join" :
                      [
                        "",
                        [
                          "powershell.exe Rename-Computer -NewName ",  {"Fn::Join"  : [ "",[ "AW", {"Fn::FindInMap" : [ "EnvironmentTypeName", "PlatformName", {"Ref" : "QRMEnvironmentType"} ]},"W",{"Ref": "QRMAvailabilityZoneIndex"},"QRMHEAD"]] }    ," -force -restart"
                        ]
                      ]
                    },
                    "WaitAfterCompletion" : "forever"
                  },
              "3-run-script" : {
                    "command" : { "Fn::Join" : [ "", [
                        "Powershell.exe Set-ExecutionPolicy Unrestricted -force \n",
                        "Powershell.exe C:\\scripts\\test.ps1 \n",
                        "Powershell.exe Start-Sleep -s 60; . C:\\PowershellScripts\\WindowsServiceManager.ps1;StopWindowsService Dnscache" , "\n"
                        ]]}}
                },
            "services": {
               "windows": {
                  "cfn-hup": {
                            "enabled": "true",
                            "ensureRunning": "true",
                            "files": ["c:\\cfn\\cfn-hup.conf", "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf"]
                                                            }
                                 }
                                            }
     }
                            }
   },
 "Properties": {
   "DisableApiTermination": "FALSE",
   "ImageId": "ami-3723c04f",
   "InstanceType": "t2.micro",
   "KeyName": "EC2Instances",
   "Monitoring": "false",
   "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
     "<script>\n",
     "cfn-init.exe -v -s ", { "Ref" : "AWS::StackName" },
     " -r MyInstance",
     " --region ", { "Ref" : "AWS::Region" }, "\n",

     "cfn-signal.exe -e 0 ", { "Fn::Base64" : { "Ref" : "WindowsServerWaitHandle" }}, "\n",

     "</script>\n"
     ]]}},
   "Tags": [
     {
       "Key": "Name",
       "Value": "MyEC2Instance"
     }
   ],

     }
  ,
    "WindowsServerWaitHandle": {
         "Type": "AWS::CloudFormation::WaitConditionHandle"
    },
     "WindowsServerWaitCondition": {
          "Type": "AWS::CloudFormation::WaitCondition",
          "DependsOn": "MyInstance",
      "Properties": {
     "Handle": { "Ref": "WindowsServerWaitHandle" },
     "Timeout": "1800"
   }
   }
 }
}
</code>```

答:
I had the same problem with yaml template.
It looks like only 2-level mappings are supported in the template, so you need to add another level where relevant, eg,</p>

```<code>...
"QRMEnvironmentType" :
{
  "Description"   :   {"Value": "QRM Dev, test, or Prod Platform"},
  "Type"          :   {"Value": "String"},
  ...
}
...
</code>```

Body:
I have a cloudformation template.

It should create an EC2 instance, change the Adminstrator password and rename the server.

I am passing couple of parameters to the stack template.  When I run it, it gives "Template format error: Every Mappings member Type must be a map".

I made sure whatever I am referring in the template, are in the "Mappings" section. Not sure why I am getting this error.

Any suggestions are very helpful.

{
   "AWSTemplateFormatVersion": "2010-09-09",

   "Parameters": {

"LocalAdminPassword" :
{
  "Type": "String",
  "NoEcho" : "true",
  "Description": "Password for the local server administrator account."
   }
},

 "Mappings": {

"EnvironmentTypeName" :
{
  "PlatformName" : {"Dev" : "D", "Test" : "T", "Prod" : "P"}
},
"QRMEnvironmentType" :
{
  "Description"   :   "QRM Dev, test, or Prod Platform",
  "Type"          :   "String",
  "AllowedValues" :  ["Dev", "Test", "Prod"],
  "Default" : "Dev",
  "ConstraintDescription" : "must be either Dev, test, or Prod"
},
"QRMAvailabilityZoneIndex" :
{
  "Description"   :   "QRM Platform AZ letter A,B, or C for Dev, Test, or Prod",
  "Type"          :   "String",
  "AllowedValues" :  ["A", "B", "C"],
  "Default" : "A",
  "ConstraintDescription" : "Must be a letter of the AZ in the specified Region"
  }
},

 "Resources": {
      "MyInstance": {
      "Type": "AWS::EC2::Instance",
      "Metadata" : {
          "AWS::CloudFormation::Init" : {
         "config" : {
           "files" : {
             "c:\\cfn\\cfn-hup.conf" : {
               "content" : { "Fn::Join" : ["", [
                 "[main]\n",
                 "stack=", { "Ref" : "AWS::StackId" }, "\n",
                 "region=", { "Ref" : "AWS::Region" }, "\n"
                 ]]}
             },
             "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf" : {
               "content": { "Fn::Join" : ["", [
                 "[cfn-auto-reloader-hook]\n",
                 "triggers=post.update\n",
           "path=Resources.MyInstance.Metadata.AWS::CloudFormation::Init\n",
                "action=cfn-init.exe -v -s ", { "Ref" : "AWS::StackId" },
                                                 " -r MyInstance",
                                                 " --region ", { "Ref" : "AWS::Region" }, "\n"
               ]]}
            },
            "c:\\scripts\\test.ps1" : {
               "content": { "Fn::Join" : ["", [
                 "Write-Host Hello World!\n"
               ]]}
             }
           },
           "commands" : {

           "1-run-script" :
            {
                "command" :
                    {
                      "Fn::Join" :
                      [
                        "",
                        [
                          "Powershell.exe  ([adsi]\\\"WinNT://$env:computername/Administrator\\\").SetPassword('",{ "Ref": "LocalAdminPassword"},"')"
                        ]
                      ]
                    }
            },
            "02-rename-server" :
                  {
                    "command" :
                    {
                      "Fn::Join" :
                      [
                        "",
                        [
                          "powershell.exe Rename-Computer -NewName ",  {"Fn::Join"  : [ "",[ "AW", {"Fn::FindInMap" : [ "EnvironmentTypeName", "PlatformName", {"Ref" : "QRMEnvironmentType"} ]},"W",{"Ref": "QRMAvailabilityZoneIndex"},"QRMHEAD"]] }    ," -force -restart"
                        ]
                      ]
                    },
                    "WaitAfterCompletion" : "forever"
                  },
              "3-run-script" : {
                    "command" : { "Fn::Join" : [ "", [
                        "Powershell.exe Set-ExecutionPolicy Unrestricted -force \n",
                        "Powershell.exe C:\\scripts\\test.ps1 \n",
                        "Powershell.exe Start-Sleep -s 60; . C:\\PowershellScripts\\WindowsServiceManager.ps1;StopWindowsService Dnscache" , "\n"
                        ]]}}
                },
            "services": {
               "windows": {
                  "cfn-hup": {
                            "enabled": "true",
                            "ensureRunning": "true",
                            "files": ["c:\\cfn\\cfn-hup.conf", "c:\\cfn\\hooks.d\\cfn-auto-reloader.conf"]
                                                            }
                                 }
                                            }
     }
                            }
   },
 "Properties": {
   "DisableApiTermination": "FALSE",
   "ImageId": "ami-3723c04f",
   "InstanceType": "t2.micro",
   "KeyName": "EC2Instances",
   "Monitoring": "false",
   "UserData" : { "Fn::Base64" : { "Fn::Join" : ["", [
     "\n"
     ]]}},
   "Tags": [
     {
       "Key": "Name",
       "Value": "MyEC2Instance"
     }
   ],

     }
  ,
    "WindowsServerWaitHandle": {
         "Type": "AWS::CloudFormation::WaitConditionHandle"
    },
     "WindowsServerWaitCondition": {
          "Type": "AWS::CloudFormation::WaitCondition",
          "DependsOn": "MyInstance",
      "Properties": {
     "Handle": { "Ref": "WindowsServerWaitHandle" },
     "Timeout": "1800"
   }
   }
 }
}

Body:
I had the same problem with yaml template.
It looks like only 2-level mappings are supported in the template, so you need to add another level where relevant, eg,

...
"QRMEnvironmentType" :
{
  "Description"   :   {"Value": "QRM Dev, test, or Prod Platform"},
  "Type"          :   {"Value": "String"},
  ...
}
...


问:
Prolog bidirectional predicate
I have to create family relations in Prolog for an assignment and I stumbled upon this problem.

```<code>man(john).
woman(lisa).
married(john,lisa).

?- married(john,X).
X = lisa.

?- married(X,john).
false.
</code>```

How to make this predicate work in two ways?
If john is married to lisa, then lisa is married to john.

For facts I can only use gender, parent, and married:

```<code>man(john).
woman(lisa).
parent(john,steve).
parent(lisa,steve).
married(john,lisa).
</code>```

That requirement makes this solution unusable for me. I can't just add relation wife(lisa,john). because I have to define wife, husband etc. by myself, like.

```<code>wife(X,Y) :- woman(X),married(X,Y).
</code>```

答:
Instead of trying to make married/2 bidirectional, you could define your predicate wife/2 accordingly. If the first argument of married/2 is always the husband and the second always the wife, just flip the arguments of the second goal:

```<code>wife(X,Y) :-
   woman(X),
   married(Y,X).      % <- changed to Y,X instead of X,Y
</code>```

With your given facts this yields the desired result:

```<code>?- wife(X,Y).
X = lisa,
Y = john.
</code>```

If your facts also include pairs the other way around, e.g.:

```<code>woman(ann).
man(anton).
married(ann, anton).
</code>```

you can include a second rule (namely your original rule) for wife/2 to deal with such pairs as well:

```<code>wife(X,Y) :-
   woman(X),
   married(Y,X).
wife(X,Y) :-          % <- new rule
   woman(X),
   married(X,Y).
</code>```

With the additional rule and facts the above query now yields:

```<code>?- wife(X,Y).
X = lisa,
Y = john ;
X = ann,
Y = anton.
</code>```

Title: Prolog bidirectional predicate

Body:
I have to create family relations in Prolog for an assignment and I stumbled upon this problem.

man(john).
woman(lisa).
married(john,lisa).

?- married(john,X).
X = lisa.

?- married(X,john).
false.

How to make this predicate work in two ways?
If john is married to lisa, then lisa is married to john.

For facts I can only use gender, parent, and married:

man(john).
woman(lisa).
parent(john,steve).
parent(lisa,steve).
married(john,lisa).

That requirement makes this solution unusable for me. I can't just add relation wife(lisa,john). because I have to define wife, husband etc. by myself, like.

wife(X,Y) :- woman(X),married(X,Y).

Body:
Instead of trying to make married/2 bidirectional, you could define your predicate wife/2 accordingly. If the first argument of married/2 is always the husband and the second always the wife, just flip the arguments of the second goal:

wife(X,Y) :-
   woman(X),
   married(Y,X).      % <- changed to Y,X instead of X,Y

With your given facts this yields the desired result:

?- wife(X,Y).
X = lisa,
Y = john.

If your facts also include pairs the other way around, e.g.:

woman(ann).
man(anton).
married(ann, anton).

you can include a second rule (namely your original rule) for wife/2 to deal with such pairs as well:

wife(X,Y) :-
   woman(X),
   married(Y,X).
wife(X,Y) :-          % <- new rule
   woman(X),
   married(X,Y).

With the additional rule and facts the above query now yields:

?- wife(X,Y).
X = lisa,
Y = john ;
X = ann,
Y = anton.


问:
Continuous Integration Builds - Versioning
I had a question regarding the use of version numbers, RELEASE versions and continuous integration.

So far in our builds we have been using RELEASE as the version for all the components in every build.

```<code><dependency>
    <groupId>com.mycompany</groupId>
    <artifactId>mydependency</artifactId>
    <version>RELEASE</version>
</dependency>
</code>```

This has the advantage that we always use the most up to date release of every dependency but has the major drawback that our builds are not reproducible as you don't know what dependencies were supposed to be used at a point in the past (as the versions says RELEASE not 1.3.2 for example).

If we switch to using fixed release numbers, we get reproducible builds, but don't we lose the advantage of Continuous Integration telling us what has now broken? Isn't this the point of Continuous Integration?

What is the standard way of doing this?

Regards,
D

答:
If we switch to using fixed release
  numbers, we get reproducible builds,
  but don't we lose the advantage of
  Continuous Integration telling us what
  has now broken? Isn't this the point
  of Continuous Integration?

No, I disagree. Every referenced project should have it's own CI build, and that should report what's broken.

If your CI project is project a and has a dependency to project b, the build a is supposed to test the validity of project a, not b. So the only thing interesting to Build a is that Project a works together with the specified version of Project b. (What the most current version of Project b does is irrelevant)

Body:
I had a question regarding the use of version numbers, RELEASE versions and continuous integration.

So far in our builds we have been using RELEASE as the version for all the components in every build.

<dependency>
    <groupId>com.mycompany</groupId>
    <artifactId>mydependency</artifactId>
    <version>RELEASE</version>
</dependency>

This has the advantage that we always use the most up to date release of every dependency but has the major drawback that our builds are not reproducible as you don't know what dependencies were supposed to be used at a point in the past (as the versions says RELEASE not 1.3.2 for example).

If we switch to using fixed release numbers, we get reproducible builds, but don't we lose the advantage of Continuous Integration telling us what has now broken? Isn't this the point of Continuous Integration?

What is the standard way of doing this?

Regards,
D


问:
Generic Types and Object in Java
I just have learned that there is a problem with generic types in Java.
The problem occurs if I want to write a method that uses a generic class.
With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

```<code>public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}
</code>```

Main.java

```<code>public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}
</code>```

Error Message

```<code>Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
</code>```

答:
You need to use a wildcard.

```<code>static void printPartsOfTriplet(Triplet<?> triplet) {
    System.out.println(triplet.a);
    System.out.println(triplet.b);
    System.out.println(triplet.c);
}
</code>```

There's a very simple rule here—the type of the variable
declaration must match the type you pass to the actual object type.

http://www.thejavageek.com/2013/08/27/generics-polymorphism-with-generics/

Title: Generic Types and Object in Java

Body:
I just have learned that there is a problem with generic types in Java.
The problem occurs if I want to write a method that uses a generic class.
With the explicit specification of a type I will lose the flexibility that generic classes offer to me. I also cant use "Object" for the generic data type in the Method. But why not? "Object" is the basic class of every class in Java and this language has polymorphism so why this doesnt work?

Own Example to demonstrate:

Triplet.java

public class Triplet <T> {
    public T a, b, c;

    Triplet(T a, T b, T c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Triplet<String> triplet = new Triplet<>("Hello", "Guten Tag", "Bonjour");
        printPartsOfTriplet(triplet);
    }

    static void printPartsOfTriplet(Triplet<Object> triplet) {
        System.out.println(triplet.a);
        System.out.println(triplet.b);
        System.out.println(triplet.c);
    }
}

Error Message

Main.java:4: error: incompatible types: Triplet<String> cannot be converted to Triplet<Object>
        printPartsOfTriplet(triplet);
                            ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

Body:
You need to use a wildcard.

static void printPartsOfTriplet(Triplet<?> triplet) {
    System.out.println(triplet.a);
    System.out.println(triplet.b);
    System.out.println(triplet.c);
}

There's a very simple rule here—the type of the variable
declaration must match the type you pass to the actual object type.

http://www.thejavageek.com/2013/08/27/generics-polymorphism-with-generics/