问:
How come I see POST data when using CURL but not when I open the .php page in a web browser?
when I type in the command below I get the results from POST in the CLI but when I open the http://172.16.16.126:8089/Test.php I don't see any of those POST data just the other data.

I know I am missing something here right? Can somebody please tell me what I'm doing wrong?

```<code>pi@raspberrypi:~ $ curl -X POST -H 'Content-Type: application/json' -d '{"username":"saad","password":"something","Hello":"Hey"}' http://172.16.16.126:8089/Test.php

stdClass Object
(
    [username] => saad
    [password] => something
    [Hello] => Hey
)
```
stdClass Object
(
    [name] => John
    [age] => 42
)
Name: John Age: 42

JSON data: {"name":"John","age":42}

stdClass Object
(
    [name] => John
    [age] => 42
)
Array
(
    [name] => John
    [age] => 42
)
Name: John Age: 42
```

<hr>

```Test.php
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
  $data = json_decode(file_get_contents("php://input"));
  print_r($data);
}

echo "```\n";

$data = (object) array(
    'name' => 'John',
    'age' => 42
);

print_r($data);

printf("Name: %s Age: %s\n\n", $data->name, $data->age);

$data = json_encode($data);

echo "JSON data: $data\n\n";

$data = json_decode($data);

print_r($data);

$data = (array) $data; // cast (convert) the object to an array

print_r($data);

printf("Name: %s Age: %s\n\n", $data['name'], $data['age']);

?>
</code>```

答:
Each time you request the URL that is handled by the PHP program, you run the PHP program.

That program looks at the input from the request and then generates a response based on it.

If you make one request with cURL that includes a JSON body, and then another request from the browser which does not, then you will get different responses for each of them.

You could write your PHP program so that when it gets a POST request with a JSON body, it saves the data somewhere (e.g. in a database), and then when it gets a GET request (which could be the result of someone typing the URL into their browser's address bar) to fetch that data instead of reading the POST body.

That would give you the result you appear to be expecting.

Body:
when I type in the command below I get the results from POST in the CLI but when I open the http://172.16.16.126:8089/Test.php I don't see any of those POST data just the other data.

I know I am missing something here right? Can somebody please tell me what I'm doing wrong?

pi@raspberrypi:~ $ curl -X POST -H 'Content-Type: application/json' -d '{"username":"saad","password":"something","Hello":"Hey"}' http://172.16.16.126:8089/Test.php

stdClass Object
(
    [username] => saad
    [password] => something
    [Hello] => Hey
)

stdClass Object
(
    [name] => John
    [age] => 42
)
Name: John Age: 42

JSON data: {"name":"John","age":42}

stdClass Object
(
    [name] => John
    [age] => 42
)
Array
(
    [name] => John
    [age] => 42
)
Name: John Age: 42

Test.php
<?php

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
  $data = json_decode(file_get_contents("php://input"));
  print_r($data);
}

echo "
\n";

$data = (object) array(
    'name' => 'John',
    'age' => 42
);

print_r($data);

printf("Name: %s Age: %s\n\n", $data->name, $data->age);

$data = json_encode($data);

echo "JSON data: $data\n\n";

$data = json_decode($data);

print_r($data);

$data = (array) $data; // cast (convert) the object to an array

print_r($data);

printf("Name: %s Age: %s\n\n", $data['name'], $data['age']);

?>


来源: stackexchange

问:
jquery: how to open an url in new tab with passing post data to that url
I have a php file localhost/~user/sample.php file which gets data from post method.

```<code><?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;
</code>```

I want to write a jquery code which will open the url "localhost/~user/sample.php" in a separate window on button click inside my html page and also pass the arguments required for it.

I can use get method in php, but the number of variables are more

答:
Try this....

```<code><form id="myForm" action="sample.php" method="post">
<?php
     echo '<input type="hidden" name="'.htmlentities($you).'" value="'.htmlentities($start).'">';
?>
</form>
<script type="text/javascript">
    document.getElementById('myForm').submit();
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a php file localhost/~user/sample.php file which gets data from post method.

<?php
$you = $_POST["ids"];
$start= $_POST["start"];
echo $you."--".$start;

I want to write a jquery code which will open the url "localhost/~user/sample.php" in a separate window on button click inside my html page and also pass the arguments required for it.

I can use get method in php, but the number of variables are more

Body:
Try this....

<form id="myForm" action="sample.php" method="post">
<?php
     echo '<input type="hidden" name="'.htmlentities($you).'" value="'.htmlentities($start).'">';
?>
</form>
<script type="text/javascript">
    document.getElementById('myForm').submit();
</script>


问:
Iterate a certain number of times without storing the iteration number anywhere
I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere.

For instance, let's say I want to print two "hello" messages to the console. Right now I know I can do:

```<code>for i in range(2):
    print "hello"
</code>```

but then the i variable is going to take the values 0 and 1 (which I don't really need). Is there a way to achieve the same thing without storing those unwanted values anywhere?

Needless to say, using a variable is not a big deal at all... I'm just curious.

答:
You can simply do

print 2*'hello'
```

ContentLicense: CC BY-SA 4.0

Body:
I was wondering if it is possible to perform a certain number of operations without storing the loop iteration number anywhere.

For instance, let's say I want to print two "hello" messages to the console. Right now I know I can do:

for i in range(2):
    print "hello"

but then the i variable is going to take the values 0 and 1 (which I don't really need). Is there a way to achieve the same thing without storing those unwanted values anywhere?

Needless to say, using a variable is not a big deal at all... I'm just curious.

Body:
You can simply do

print 2*'hello'


问:
PyGObject GtkFileChooserDialog default button
When I create a GtkFileChooserDialog in Glade and then connect that to a Python class using Gtk.Builder, how do I tell it which is the default button?

Currently, my 'Open' button is the stock gtk-open button and when it's clicked, run() returns 0.  But double-clicking on a file or selecting a file and pressing Enter doesn't do anything.  As far as I can see, this is because the dialog doesn't know what the default button is in Glade, possibly because the 'Open' button isn't using one of GTK_RESPONSE_ACCEPT, GTK_RESPONSE_OK, GTK_RESPONSE_YES or GTK_RESPONSE_APPLY as its response code; but how do I set the response code to one of these when the button is created through Glade?

I'm using Gtk 3, Python 3 and PyGObject (ie gi.repository).

Edit: Here is the relevant bit of the Glade file:

```<code>  <object class="GtkFileChooserDialog" id="file_chooser">
    <property name="can_focus">False</property>
    <property name="modal">True</property>
    <property name="type_hint">dialog</property>
    <property name="select_multiple">True</property>
    <child internal-child="vbox">
      <object class="GtkBox">
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <property name="spacing">2</property>
        <child internal-child="action_area">
          <object class="GtkButtonBox">
            <property name="can_focus">False</property>
            <property name="layout_style">end</property>
            <child>
              <object class="GtkButton" id="button1">
                <property name="label">gtk-cancel</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="button2">
                <property name="label">gtk-open</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">False</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
    </child>
    <action-widgets>
      <action-widget response="-1">button1</action-widget>
      <action-widget response="-5">button2</action-widget>
    </action-widgets>
  </object>
</code>```

答:
Try

```<code>dialog.set_default_response(Gtk.ResponseType.YES)
</code>```

Can’t tell for sure how to change response code on Glade, but it shouldn't matter to you if you just write the handler for your`s Gtk.ResponseType.YES code

EDIT:

If you were not using glade things like that are wired already

```<code>dialog = builder.get_object("file_chooser")
dialog.connect('file-activated', self.file_selected)

def file_selected(self, dialog):
    dialog.emit('response', Gtk.ResponseType.OK)
</code>```

It is important to resume operations after You run() your dialog so emit this signal and do nothing more

Body:
When I create a GtkFileChooserDialog in Glade and then connect that to a Python class using Gtk.Builder, how do I tell it which is the default button?

Currently, my 'Open' button is the stock gtk-open button and when it's clicked, run() returns 0.  But double-clicking on a file or selecting a file and pressing Enter doesn't do anything.  As far as I can see, this is because the dialog doesn't know what the default button is in Glade, possibly because the 'Open' button isn't using one of GTK_RESPONSE_ACCEPT, GTK_RESPONSE_OK, GTK_RESPONSE_YES or GTK_RESPONSE_APPLY as its response code; but how do I set the response code to one of these when the button is created through Glade?

I'm using Gtk 3, Python 3 and PyGObject (ie gi.repository).

Edit: Here is the relevant bit of the Glade file:

  <object class="GtkFileChooserDialog" id="file_chooser">
    <property name="can_focus">False</property>
    <property name="modal">True</property>
    <property name="type_hint">dialog</property>
    <property name="select_multiple">True</property>
    <child internal-child="vbox">
      <object class="GtkBox">
        <property name="can_focus">False</property>
        <property name="orientation">vertical</property>
        <property name="spacing">2</property>
        <child internal-child="action_area">
          <object class="GtkButtonBox">
            <property name="can_focus">False</property>
            <property name="layout_style">end</property>
            <child>
              <object class="GtkButton" id="button1">
                <property name="label">gtk-cancel</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">0</property>
              </packing>
            </child>
            <child>
              <object class="GtkButton" id="button2">
                <property name="label">gtk-open</property>
                <property name="visible">True</property>
                <property name="can_focus">True</property>
                <property name="receives_default">True</property>
                <property name="use_stock">True</property>
              </object>
              <packing>
                <property name="expand">True</property>
                <property name="fill">True</property>
                <property name="position">1</property>
              </packing>
            </child>
          </object>
          <packing>
            <property name="expand">False</property>
            <property name="fill">False</property>
            <property name="position">0</property>
          </packing>
        </child>
        <child>
          <placeholder/>
        </child>
      </object>
    </child>
    <action-widgets>
      <action-widget response="-1">button1</action-widget>
      <action-widget response="-5">button2</action-widget>
    </action-widgets>
  </object>

Body:
Try

dialog.set_default_response(Gtk.ResponseType.YES)

Can’t tell for sure how to change response code on Glade, but it shouldn't matter to you if you just write the handler for your`s Gtk.ResponseType.YES code

EDIT:

If you were not using glade things like that are wired already

dialog = builder.get_object("file_chooser")
dialog.connect('file-activated', self.file_selected)

def file_selected(self, dialog):
    dialog.emit('response', Gtk.ResponseType.OK)

It is important to resume operations after You run() your dialog so emit this signal and do nothing more


问:
Printing a list after having removed adjacent duplicate elements
```<code>new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list
</code>```

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

答:
What you would want is a problem best solved by itertools.groupby

```<code>l
Out[35]: [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

from itertools import groupby
[k for k, _ in groupby(l)]
Out[36]: [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]
</code>```

What itertools.groupby does is, it groups consecutive keys together by generating a tuple of the element and the consecutive group as a list

To get a clear understanding of itertools.groupby, you can dump the resultant list of tuples generated by grouping the list of consecutive numbers

```<code>[(k, list(g)) for k, g in groupby(l)]
Out[40]:
[(1, [1]),
 (2, [2]),
 (3, [3]),
 (5, [5]),
 (4, [4, 4]),
 (5, [5, 5]),
 (6, [6]),
 (7, [7, 7, 7]),
 (8, [8, 8]),
 (9, [9]),
 (8, [8, 8])]
</code>```

Body:
new_list = []

i = 0

def remove_adjacent(nums):
    global i
    while i < len(nums) - 1:
        if nums[i] != nums[i+1]:
            new_list.append(nums[i])
        else:
            i += 1
            remove_adjacent(nums[i:])
            return
    i += 1

l = [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

remove_adjacent(l)

print new_list

Question: Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list.

Issue: The final list printed consists of [1, 2, 3, 5] instead of [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

Body:
What you would want is a problem best solved by itertools.groupby

l
Out[35]: [1, 2, 3, 5, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 8, 8]

from itertools import groupby
[k for k, _ in groupby(l)]
Out[36]: [1, 2, 3, 5, 4, 5, 6, 7, 8, 9, 8]

What itertools.groupby does is, it groups consecutive keys together by generating a tuple of the element and the consecutive group as a list

To get a clear understanding of itertools.groupby, you can dump the resultant list of tuples generated by grouping the list of consecutive numbers

[(k, list(g)) for k, g in groupby(l)]
Out[40]:
[(1, [1]),
 (2, [2]),
 (3, [3]),
 (5, [5]),
 (4, [4, 4]),
 (5, [5, 5]),
 (6, [6]),
 (7, [7, 7, 7]),
 (8, [8, 8]),
 (9, [9]),
 (8, [8, 8])]


问:
How to prevent Zero from appearing in Calculator?
I am writing a FreeCodeCamp Calculator. The problem that I am working on right now is repeating operators. For example, if I press "5" and then "+", but changed my mind and pressed "-", the history area should display "5-" instead of "5+". However, with my code, it display "5+0-". Therefore, I realize that I will need to fix the "Zero" problem as well.

The list I wanted to do for the "Zero" problem are:

If one press "0", allow it to appear in the history area. For example, if someone press "0" and then the operator, it should appear in the history area as "0-".

Otherwise, if someone press operator first without putting in any number, stop this method

Here is my code from this Codepen:

$(document).ready(function() {

  var mainMath = "0";
  var subMath = "0";
  var finalset = "";
  var subMatharray = [];
  var oppArray = [];
  var equalPressed = false;
  var prevKey = "";
  update();

  $("button").click(function(){
    calculate($(this).attr("value"));
  });

  function calculate(keyitem) {
    console.log("buttonpress: " + keyitem);
    switch(keyitem) {
      case "clear":
        clearScreen();
        break;
      case "%":
        percentageScreen();
        break;
      case "/":
      case "*":
      case "+":
      case "-":
        addOperator(keyitem);
        break;
      case "plusminus":
        plusminusScreen();
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        addNumber(keyitem);
        break;
      case ".":
        addDecimal(keyitem);
        break;
      case "=":
        solveEqual(keyitem);
        break;
    }
    update();
    };

  function clearScreen() {
     mainMath = "0";
     subMath = "0";
     prevKey = "";
     subMatharray = [];
     oppArray = [];
    if(mainMath.length > 0){
      $(".entry").css("font-size", "4em");
    }
    console.log("clearMain: " + mainMath);
    console.log("clearSub: " + subMath);
  };

  function plusminusScreen() {
     mainMath = -1 * mainMath;
    finalset = mainMath;
    console.log("plusminusMain: " + mainMath);
    console.log("plusminusFinal: " + finalset);
  };

  function addNumber(keyitem) {
    if (mainMath == "0"){
      mainMath = keyitem/*mainMath.replace("0", keyitem);*/
      finalset = mainMath;
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
    if (equalPressed == true){
      mainMath = keyitem;
      subMath = "0";
      subMatharray = [];
      equalPressed = false;
      console.log("addNumberEqualmain: " + mainMath);
    }
    mainMath+=keyitem;
    finalset = mainMath;

    console.log("addedMain: " + mainMath);
    console.log("addedFinalset: " + finalset);
    console.log("addedarray: " + subMatharray);

    if(mainMath.length > 8){
      $(".entry").css("font-size", "1.5em");
    }

  };

  function addOperator(keyitem){

    if (equalPressed == true){
      subMatharray = [];
      equalPressed = false;
      console.log("addOpEqualarray: " + subMatharray);
    }
    /*if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }*/

    oppArray.push(keyitem);
    console.log("addOpArray: " + oppArray);
    var opkeyitem = "";

    subMatharray.push(mainMath);
    prevKey = "numbertest";

    if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    } /*else if (oppArray.length > 1 && prevKey == "operatortest") {
      subMatharray.pop();
      subMatharray.push("droubletest");
      oppArray = [];
      console.log("addOpArraySubArray: " + subMatharray);
      console.log("addOpArrayPrevKey: " + prevKey);
    } /*else if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    }*/

    subMath = subMatharray.join("");
    mainMath = "0";
    prevKey = keyitem;
    console.log("addOpSub: " + subMath);
    console.log("addOpMain: " + mainMath);
    console.log("addOpMainarray: " + subMatharray);
    console.log("equaltrueTest: " + equalPressed);
  };

  function addDecimal(keyitem){
    if (mainMath.indexOf(keyitem) === -1){
      if(mainMath == "0") {
        mainMath = "0" + keyitem;
        return;
      }
    } else {
        return;
      }
    addNumber(keyitem);
  };

  function solveEqual(keyitem) {
    subMatharray.push(finalset);
    subMath = subMatharray.join("");
    mainMath = eval(subMath);
    console.log("solveEqualresult: " + mainMath);
    console.log("solveEqualhistory: " + subMath);
    console.log("solveEqualarray: " + subMatharray);
    var finalresult = mainMath.toString();
    if(finalresult.length > 8){
      $(".entry").css("font-size", "1.5em");
    }
    equalPressed = true;
  };

  function update(){
  $("#answer").html(mainMath);
  $("#history").html(subMath);
};

});

/*Problems
2. I need to work on percentage button soon...
3. fix the problem if someone click an operator more than one.
*/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
  font-family: 'Roboto', sans-serif;
}
html, body{
  height:100%;
  margin: 0;
  background-color: #ffffff;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  background-repeat: no-repeat;
    background-size: cover;
  background-position: center center;
  padding: 160px 0;
}
.calculatorbox {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #000000;
}
.calheader {
  text-align: center;
}
.calwindow {
  background: #000000;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
   -webkit-flex-direction: column; /* Safari */
  flex-direction:         column;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  -webkit-align-items: flex-end;
  align-items: flex-end;
  padding: 10px 0;
  box-sizing: border-box;
}
.entry {
  font-size: 4em;
  display: block;
  line-height: 1em;
}
.entryhistory {
  font-size: 1em;
  letter-spacing: 2px;
  padding-right: 5px;
}
.entry p, .entryhistory p {
  margin: 0;
  color: #ffffff;
}
sup {
  top: -0.5em;
}

sub {
  bottom: -0em;
}
.row {
  clear: both;
  width: 100%;
  display: flex;
}
button {
  display: inline-block;
  border: none;
  padding: 0;
  outline: none;
  cursor: pointer;
}
.key {
  width: 75px;
  height: 70px;
  font-size: 22px;
  border-top: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}
.key.btnspan {
  width: 150px;
}
.key.topcolor {
  background: #d9d9d9;
}
.key.orange {
  background: #ff8c00;
  color: #ffffff;
}</code>```

Simple Calculator

        <button class="key topcolor" value="clear">C</button>
        <button class="key topcolor" value="plusminus">+/−</button>
        <button class="key topcolor" value="%">%</button>
        <button class="key orange" value="/">÷</button>

        <button class="key" value="7">7</button>
        <button class="key" value="8">8</button>
        <button class="key" value="9">9</button>
        <button class="key orange" value="*">×</button>

        <button class="key" value="4">4</button>
        <button class="key" value="5">5</button>
        <button class="key" value="6">6</button>
        <button class="key orange" value="-">−</button>

        <button class="key" value="1">1</button>
        <button class="key" value="2">2</button>
        <button class="key" value="3">3</button>
        <button class="key orange" value="+">+</button>

        <button class="key btnspan" value="0">0</button>
        <button class="key" value=".">.</button>
        <button class="key orange" value="=">=</button>

```
</div>
</div>
</p>

<p>All the action is happening in <code>function addOperator(keyitem)</code>. I have attempt to fix the "Zero" problem, but I commented it out so you can see fully what I am talking about. Here is the code that I commented out.</p>

```if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
```

I look forward to any suggestions or code solutions that can help me fix the "Zero" problem.

答:
I would reconsider the inital value from "0" to null to be able to split zero-logic and init-logic:

```<code>var mainMath = null;
// ...

function clearScreen() {
  mainMath = null;
  // ...
}

function addNumber(keyitem) {
  if (mainMath === null) {
    mainMath = "0"; //hacky, I know, this requires more deep refactoring
  }
  // ...
}

function addOperator(keyitem){
  if(mainMath === null) {
    return; // this is the main point
  }
  // ...
  mainMath = null;
  // ...
}

$("#answer").html(mainMath === null ? "0" : mainMath);
</code>```

It's just an idea, and the approach should be improved, but the interim result you may try on your codepen fork.

Body:
I am writing a FreeCodeCamp Calculator. The problem that I am working on right now is repeating operators. For example, if I press "5" and then "+", but changed my mind and pressed "-", the history area should display "5-" instead of "5+". However, with my code, it display "5+0-". Therefore, I realize that I will need to fix the "Zero" problem as well.

The list I wanted to do for the "Zero" problem are:

If one press "0", allow it to appear in the history area. For example, if someone press "0" and then the operator, it should appear in the history area as "0-".

Otherwise, if someone press operator first without putting in any number, stop this method

Here is my code from this Codepen:

$(document).ready(function() {

  var mainMath = "0";
  var subMath = "0";
  var finalset = "";
  var subMatharray = [];
  var oppArray = [];
  var equalPressed = false;
  var prevKey = "";
  update();

  $("button").click(function(){
    calculate($(this).attr("value"));
  });

  function calculate(keyitem) {
    console.log("buttonpress: " + keyitem);
    switch(keyitem) {
      case "clear":
        clearScreen();
        break;
      case "%":
        percentageScreen();
        break;
      case "/":
      case "*":
      case "+":
      case "-":
        addOperator(keyitem);
        break;
      case "plusminus":
        plusminusScreen();
        break;
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9":
        addNumber(keyitem);
        break;
      case ".":
        addDecimal(keyitem);
        break;
      case "=":
        solveEqual(keyitem);
        break;
    }
    update();
    };

  function clearScreen() {
     mainMath = "0";
     subMath = "0";
     prevKey = "";
     subMatharray = [];
     oppArray = [];
    if(mainMath.length > 0){
      $(".entry").css("font-size", "4em");
    }
    console.log("clearMain: " + mainMath);
    console.log("clearSub: " + subMath);
  };

  function plusminusScreen() {
     mainMath = -1 * mainMath;
    finalset = mainMath;
    console.log("plusminusMain: " + mainMath);
    console.log("plusminusFinal: " + finalset);
  };

  function addNumber(keyitem) {
    if (mainMath == "0"){
      mainMath = keyitem/*mainMath.replace("0", keyitem);*/
      finalset = mainMath;
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }
    if (equalPressed == true){
      mainMath = keyitem;
      subMath = "0";
      subMatharray = [];
      equalPressed = false;
      console.log("addNumberEqualmain: " + mainMath);
    }
    mainMath+=keyitem;
    finalset = mainMath;

    console.log("addedMain: " + mainMath);
    console.log("addedFinalset: " + finalset);
    console.log("addedarray: " + subMatharray);

    if(mainMath.length > 8){
      $(".entry").css("font-size", "1.5em");
    }

  };

  function addOperator(keyitem){

    if (equalPressed == true){
      subMatharray = [];
      equalPressed = false;
      console.log("addOpEqualarray: " + subMatharray);
    }
    /*if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }*/

    oppArray.push(keyitem);
    console.log("addOpArray: " + oppArray);
    var opkeyitem = "";

    subMatharray.push(mainMath);
    prevKey = "numbertest";

    if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    } /*else if (oppArray.length > 1 && prevKey == "operatortest") {
      subMatharray.pop();
      subMatharray.push("droubletest");
      oppArray = [];
      console.log("addOpArraySubArray: " + subMatharray);
      console.log("addOpArrayPrevKey: " + prevKey);
    } /*else if(prevKey == "numbertest") {
      subMatharray.push(keyitem);
      prevKey = "operatortest";
      console.log("addOpArraySubArrayElse: " + subMatharray);
      console.log("addOpArrayPrevKeyElse: " + prevKey);
    }*/

    subMath = subMatharray.join("");
    mainMath = "0";
    prevKey = keyitem;
    console.log("addOpSub: " + subMath);
    console.log("addOpMain: " + mainMath);
    console.log("addOpMainarray: " + subMatharray);
    console.log("equaltrueTest: " + equalPressed);
  };

  function addDecimal(keyitem){
    if (mainMath.indexOf(keyitem) === -1){
      if(mainMath == "0") {
        mainMath = "0" + keyitem;
        return;
      }
    } else {
        return;
      }
    addNumber(keyitem);
  };

  function solveEqual(keyitem) {
    subMatharray.push(finalset);
    subMath = subMatharray.join("");
    mainMath = eval(subMath);
    console.log("solveEqualresult: " + mainMath);
    console.log("solveEqualhistory: " + subMath);
    console.log("solveEqualarray: " + subMatharray);
    var finalresult = mainMath.toString();
    if(finalresult.length > 8){
      $(".entry").css("font-size", "1.5em");
    }
    equalPressed = true;
  };

  function update(){
  $("#answer").html(mainMath);
  $("#history").html(subMath);
};

});

/*Problems
2. I need to work on percentage button soon...
3. fix the problem if someone click an operator more than one.
*/

@import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
  font-family: 'Roboto', sans-serif;
}
html, body{
  height:100%;
  margin: 0;
  background-color: #ffffff;
}
.wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display:flex;
  flex-direction:column;
  justify-content:center;
  align-items:center;
  background-repeat: no-repeat;
    background-size: cover;
  background-position: center center;
  padding: 160px 0;
}
.calculatorbox {
  width: 300px;
  margin: 0 auto;
  border: 1px solid #000000;
}
.calheader {
  text-align: center;
}
.calwindow {
  background: #000000;
  position: relative;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
   -webkit-flex-direction: column; /* Safari */
  flex-direction:         column;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  -webkit-align-items: flex-end;
  align-items: flex-end;
  padding: 10px 0;
  box-sizing: border-box;
}
.entry {
  font-size: 4em;
  display: block;
  line-height: 1em;
}
.entryhistory {
  font-size: 1em;
  letter-spacing: 2px;
  padding-right: 5px;
}
.entry p, .entryhistory p {
  margin: 0;
  color: #ffffff;
}
sup {
  top: -0.5em;
}

sub {
  bottom: -0em;
}
.row {
  clear: both;
  width: 100%;
  display: flex;
}
button {
  display: inline-block;
  border: none;
  padding: 0;
  outline: none;
  cursor: pointer;
}
.key {
  width: 75px;
  height: 70px;
  font-size: 22px;
  border-top: 1px solid rgba(0, 0, 0, 0.3);
  border-right: 1px solid rgba(0, 0, 0, 0.3);
  box-sizing: border-box;
}
.key.btnspan {
  width: 150px;
}
.key.topcolor {
  background: #d9d9d9;
}
.key.orange {
  background: #ff8c00;
  color: #ffffff;
}

Simple Calculator

        <button class="key topcolor" value="clear">C</button>
        <button class="key topcolor" value="plusminus">+/−</button>
        <button class="key topcolor" value="%">%</button>
        <button class="key orange" value="/">÷</button>

        <button class="key" value="7">7</button>
        <button class="key" value="8">8</button>
        <button class="key" value="9">9</button>
        <button class="key orange" value="*">×</button>

        <button class="key" value="4">4</button>
        <button class="key" value="5">5</button>
        <button class="key" value="6">6</button>
        <button class="key orange" value="-">−</button>

        <button class="key" value="1">1</button>
        <button class="key" value="2">2</button>
        <button class="key" value="3">3</button>
        <button class="key orange" value="+">+</button>

        <button class="key btnspan" value="0">0</button>
        <button class="key" value=".">.</button>
        <button class="key orange" value="=">=</button>

All the action is happening in function addOperator(keyitem). I have attempt to fix the "Zero" problem, but I commented it out so you can see fully what I am talking about. Here is the code that I commented out.

if (mainMath == "0" && finalset !== "0"){
      mainMath = "0";
      subMatharray.push(keyitem);
      return;
      console.log("addedMainZero: " + mainMath);
      console.log("addedFinalZero: " + finalset);
    }

I look forward to any suggestions or code solutions that can help me fix the "Zero" problem.

Body:
I would reconsider the inital value from "0" to null to be able to split zero-logic and init-logic:

var mainMath = null;
// ...

function clearScreen() {
  mainMath = null;
  // ...
}

function addNumber(keyitem) {
  if (mainMath === null) {
    mainMath = "0"; //hacky, I know, this requires more deep refactoring
  }
  // ...
}

function addOperator(keyitem){
  if(mainMath === null) {
    return; // this is the main point
  }
  // ...
  mainMath = null;
  // ...
}

$("#answer").html(mainMath === null ? "0" : mainMath);

It's just an idea, and the approach should be improved, but the interim result you may try on your codepen fork.


问:
PHP Associative Array Duplicate Keys
I have an associative array, however when I add values to it using the below function it seems to overwrite the same keys. Is there a way to have multiple of the same keys with different values? Or is there another form of array that has the same format?

I want to have:

```<code>42=>56
42=>86
42=>97
51=>64
51=>52
etc etc
</code>```

Code:

```<code>   function array_push_associative(&$arr) {
       $args = func_get_args();
       foreach ($args as $arg) {
           if (is_array($arg)) {
               foreach ($arg as $key => $value) {
                   $arr[$key] = $value;
                   $ret++;
               }
           }else{
               $arr[$arg] = "";
           }
       }
       return $ret;
    }
</code>```

答:
I found this question while researching the exact opposite intended outcome, I have an array of data that has duplicate keys! Here's how I did it (still trying to figure out where in my process things are messing up).

```<code>$session = time();
$a = array();
$a[(string)$session] = 0;
$j = json_encode($a,JSON_FORCE_OBJECT);
print_r($a);
/* output:
Array
(
    [1510768034] => 0
)
*/
var_dump($a);
/* output:
array(1)
(
    [1510768034] =>   int(0)
)
*/
print_r($j);
/* output:
{"1510768034":0}
*/
$a = (array)json_decode($j);
$session = @array_pop(array_keys($a));
$a[(string)$session] = 10;
$j = json_encode($a,JSON_FORCE_OBJECT);
print_r($a);
/* output:
Array
(
    [1510768034] => 0
    [1510768034] => 10
)
*/
var_dump($a);
/* output:
array(2)
(
    '1510768034' => int(0)
    [1510768034] => int(10)
)
*/
print_r($j);
/* output:
{"1510768034":0,"1510768034":10}
*/
</code>```

Yup....that just happened.

PHP 7.1

Edit: It's similar in PHP 7.2.10, except json_encode no longer entertains duplicate keys, encoded strings are correct.  The array, however, can have matching string and integer keys.

Title: PHP Associative Array Duplicate Keys

Body:
I have an associative array, however when I add values to it using the below function it seems to overwrite the same keys. Is there a way to have multiple of the same keys with different values? Or is there another form of array that has the same format?

I want to have:

42=>56
42=>86
42=>97
51=>64
51=>52
etc etc

Code:

   function array_push_associative(&$arr) {
       $args = func_get_args();
       foreach ($args as $arg) {
           if (is_array($arg)) {
               foreach ($arg as $key => $value) {
                   $arr[$key] = $value;
                   $ret++;
               }
           }else{
               $arr[$arg] = "";
           }
       }
       return $ret;
    }

Body:
I found this question while researching the exact opposite intended outcome, I have an array of data that has duplicate keys! Here's how I did it (still trying to figure out where in my process things are messing up).

$session = time();
$a = array();
$a[(string)$session] = 0;
$j = json_encode($a,JSON_FORCE_OBJECT);
print_r($a);
/* output:
Array
(
    [1510768034] => 0
)
*/
var_dump($a);
/* output:
array(1)
(
    [1510768034] =>   int(0)
)
*/
print_r($j);
/* output:
{"1510768034":0}
*/
$a = (array)json_decode($j);
$session = @array_pop(array_keys($a));
$a[(string)$session] = 10;
$j = json_encode($a,JSON_FORCE_OBJECT);
print_r($a);
/* output:
Array
(
    [1510768034] => 0
    [1510768034] => 10
)
*/
var_dump($a);
/* output:
array(2)
(
    '1510768034' => int(0)
    [1510768034] => int(10)
)
*/
print_r($j);
/* output:
{"1510768034":0,"1510768034":10}
*/

Yup....that just happened.

PHP 7.1

Edit: It's similar in PHP 7.2.10, except json_encode no longer entertains duplicate keys, encoded strings are correct.  The array, however, can have matching string and integer keys.


问:
Using a conditional statement IF to control whether a row is added or not
I'm currently learning how to use databases through PostgreSQL. I'm defining a function that will add rows from one table to another based on various conditions, one condition is that if the row already exists in the target table, it won't be added but no exception will be raised, the program will simply continue onto the next row. As you may have guessed all of this is taking place within LOOP...END LOOP; of a FOR.

The problem is that our professor considers ON CONFLICT DO NOTHING non-standard and insists we use another method. I have searched extensively but really don't understand how to apply some answers people have suggested in similar cases. My idea was indeed:

```<code>IF variable1, variable2, variable3 NOT IN (SELECT v1, v2, v3 FROM target_table) THEN INSERT INTO target_table VALUES(variable1, variable2, variable3);
END IF;
</code>```

But that is obviously not correct from a syntax point of view. Can anybody give me some guidance?

Thanks

答:
You can do something similar to:

```<code>INSERT INTO target_table (v1,v2,v3)
SELECT
    variable1,
    variable2,
    variable3
WHERE NOT EXISTS
(SELECT * FROM target_table
    WHERE v1 = variable1 and v2 = variable2 and v3 = variable3)
</code>```

However there are some caveats.

If one of your variables is nullable you can't just use "=".   You need to do something like:

```<code>(v1 = variable1 OR (v1 is null and variable1 is null))
</code>```

and it gets bulky pretty quickly and can be slow on large tables as it can prevent indices from being used.

You also need to worry about the concurrency aspects.  If you're issuing this statement where there are concurrent inserts/updates to the table you'll need to consider when rows become visible as rows may get inserted between the select and the insert.

Check out the transaction isolation settings in PostgreSQL for these details.

https://www.postgresql.org/docs/10/static/transaction-iso.html

Body:
I'm currently learning how to use databases through PostgreSQL. I'm defining a function that will add rows from one table to another based on various conditions, one condition is that if the row already exists in the target table, it won't be added but no exception will be raised, the program will simply continue onto the next row. As you may have guessed all of this is taking place within LOOP...END LOOP; of a FOR.

The problem is that our professor considers ON CONFLICT DO NOTHING non-standard and insists we use another method. I have searched extensively but really don't understand how to apply some answers people have suggested in similar cases. My idea was indeed:

IF variable1, variable2, variable3 NOT IN (SELECT v1, v2, v3 FROM target_table) THEN INSERT INTO target_table VALUES(variable1, variable2, variable3);
END IF;

But that is obviously not correct from a syntax point of view. Can anybody give me some guidance?

Thanks

Body:
You can do something similar to:

INSERT INTO target_table (v1,v2,v3)
SELECT
    variable1,
    variable2,
    variable3
WHERE NOT EXISTS
(SELECT * FROM target_table
    WHERE v1 = variable1 and v2 = variable2 and v3 = variable3)

However there are some caveats.

If one of your variables is nullable you can't just use "=".   You need to do something like:

(v1 = variable1 OR (v1 is null and variable1 is null))

and it gets bulky pretty quickly and can be slow on large tables as it can prevent indices from being used.

You also need to worry about the concurrency aspects.  If you're issuing this statement where there are concurrent inserts/updates to the table you'll need to consider when rows become visible as rows may get inserted between the select and the insert.

Check out the transaction isolation settings in PostgreSQL for these details.

https://www.postgresql.org/docs/10/static/transaction-iso.html


问:
3-way bind date format with AngularJS and Firebase
In all my projects I'm running into the same problem trying to figure out what the best way is to have a proper way of binding a timestamp (date) with my view and Firebase. I'm currently using the md-datepicker directive from Angular-Material but unfortunately this directive only supports a date object, and because Firebase won't accept a date object the value will always be empty.

In several projects I'm storing epoch timestamps in milliseconds in Firebase. Is there any possibility to have a proper 3-way data binding with epoch timestamps in Firebase and the md-datepicker?

Thanks!

答:
Solved it by creating my own bind function and converting to an ISO date string when saving it and converting it into a date object when fetching it.

It user $parse to evaluate expressions in the given scope and to update the local variable in that scope. Here is the service:

```<code>angular.module('symApp').service('realtimeService', function($rootScope, $q, $log, $window, $state,
                                                           $firebaseObject, $parse) {

// Utilities
var regexIso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
var convertDateStringsToDates = function (input) {
    // Ignore things that aren't objects.
    if (typeof input !== "object") return input;
    for (var key in input) {
        if (!input.hasOwnProperty(key)) continue;
        var value = input[key];
        var match;
        // Check for string properties which look like dates.
        if (typeof value === "string" && (match = value.match(regexIso8601))) {
            var milliseconds = Date.parse(match[0]);
            if (!isNaN(milliseconds)) {
                input[key] = new Date(milliseconds);
            }
        } else if (typeof value === "object") {
            // Recurse into object
            convertDateStringsToDates(value);
        }
    }
};

this.bindVar = function(scope, remote_path, local_var_name) {
// This function binds a local variable in scope to a remote variable in firebase
// and handles any dates by converting them into iso formatted strings.
// Note: Arrays inside the object are not supported

// Parse the local variable name so we can interact with the scope variable
var parsed = $parse(local_var_name);

// Grab the reference to the realtime database
var ref = firebase.database().ref().child(remote_path);

// Create the firebase object and set watchers to bind the data
var remote = $firebaseObject(ref);
remote.$loaded().then(function() {

    // Watch for changes and call $save on firebaseObject
    // Have to do this when loaded otherwise we'll get a change from nothing to null and write null to realtime database...

    // Local watcher
    scope.$watch(local_var_name,
        function(value) {
            // This is called when the local variable changes
            $log.debug(local_var_name, 'local value changed');

            // Convert to JSON to change dates to strings
            var local = angular.fromJson(angular.toJson(parsed(scope)));

            // Check if local has changed with respect to remote (stops us from saving when we don't need to)
            if(!angular.equals(remote.value, local)){
                remote.value = local;
                remote.$save();
                $log.debug(local_var_name, 'saved to remote with value: ', remote.value);
            }
        },
        true
    );

    // Remote watcher
    scope.$watch(
        function () {
            return remote.value;
        },
        function(value) {
            // If the firebase value has changed, then update the local value
            $log.debug(local_var_name, 'remote value changed');

            // Convert date strings from firebase into date objects before setting scope variable
            var remote_with_date_objects = $.extend(true,{},remote.value);
            convertDateStringsToDates(remote_with_date_objects);

            if(!angular.equals(remote_with_date_objects,parsed(scope))){
                parsed.assign(scope, remote_with_date_objects);
                $log.debug(local_var_name, 'updated with remote value: ', remote_with_date_objects);
            }
        },
        true
    );

    });
};
</code>```

});

And here is how you use it in your controller to bind a scope variable:

```<code>realtimeService.bindVar($scope, 'datum/charter', 'charter');
</code>```

My $scope.charter object has its own objects and arrays within it and everything seems to sync correctly. When saving data it uses angular.toJson and angular.fromJson to convert all the date objects to strings. When loading remote data it uses a custom function convertDateStringsToDates() to convert any date strings within the object to date objects whenever the remote is updated.

Body:
Solved it by creating my own bind function and converting to an ISO date string when saving it and converting it into a date object when fetching it.

It user $parse to evaluate expressions in the given scope and to update the local variable in that scope. Here is the service:

angular.module('symApp').service('realtimeService', function($rootScope, $q, $log, $window, $state,
                                                           $firebaseObject, $parse) {

// Utilities
var regexIso8601 = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
var convertDateStringsToDates = function (input) {
    // Ignore things that aren't objects.
    if (typeof input !== "object") return input;
    for (var key in input) {
        if (!input.hasOwnProperty(key)) continue;
        var value = input[key];
        var match;
        // Check for string properties which look like dates.
        if (typeof value === "string" && (match = value.match(regexIso8601))) {
            var milliseconds = Date.parse(match[0]);
            if (!isNaN(milliseconds)) {
                input[key] = new Date(milliseconds);
            }
        } else if (typeof value === "object") {
            // Recurse into object
            convertDateStringsToDates(value);
        }
    }
};

this.bindVar = function(scope, remote_path, local_var_name) {
// This function binds a local variable in scope to a remote variable in firebase
// and handles any dates by converting them into iso formatted strings.
// Note: Arrays inside the object are not supported

// Parse the local variable name so we can interact with the scope variable
var parsed = $parse(local_var_name);

// Grab the reference to the realtime database
var ref = firebase.database().ref().child(remote_path);

// Create the firebase object and set watchers to bind the data
var remote = $firebaseObject(ref);
remote.$loaded().then(function() {

    // Watch for changes and call $save on firebaseObject
    // Have to do this when loaded otherwise we'll get a change from nothing to null and write null to realtime database...

    // Local watcher
    scope.$watch(local_var_name,
        function(value) {
            // This is called when the local variable changes
            $log.debug(local_var_name, 'local value changed');

            // Convert to JSON to change dates to strings
            var local = angular.fromJson(angular.toJson(parsed(scope)));

            // Check if local has changed with respect to remote (stops us from saving when we don't need to)
            if(!angular.equals(remote.value, local)){
                remote.value = local;
                remote.$save();
                $log.debug(local_var_name, 'saved to remote with value: ', remote.value);
            }
        },
        true
    );

    // Remote watcher
    scope.$watch(
        function () {
            return remote.value;
        },
        function(value) {
            // If the firebase value has changed, then update the local value
            $log.debug(local_var_name, 'remote value changed');

            // Convert date strings from firebase into date objects before setting scope variable
            var remote_with_date_objects = $.extend(true,{},remote.value);
            convertDateStringsToDates(remote_with_date_objects);

            if(!angular.equals(remote_with_date_objects,parsed(scope))){
                parsed.assign(scope, remote_with_date_objects);
                $log.debug(local_var_name, 'updated with remote value: ', remote_with_date_objects);
            }
        },
        true
    );

    });
};

});

And here is how you use it in your controller to bind a scope variable:

realtimeService.bindVar($scope, 'datum/charter', 'charter');

My $scope.charter object has its own objects and arrays within it and everything seems to sync correctly. When saving data it uses angular.toJson and angular.fromJson to convert all the date objects to strings. When loading remote data it uses a custom function convertDateStringsToDates() to convert any date strings within the object to date objects whenever the remote is updated.


问:
How do i make my Mouse over(hover)and on click events while the program is running
I have made a program where you ask the number of ellipses and it makes them in a different window in c#,but I want to have a mouse over effect-which I understood is called : MouseEnter and an onclick event,which I understood is called MouseDown, but I made an array of ellipses and I tried  the following :

```<code>namespace WpfApp1
{
/// <summary>
/// Interaction logic for Window2.xaml
/// </summary>
public partial class Window2 : Window
{
    int numOfElipses;
    public Window2()
    {
        InitializeComponent();
        numOfElipses= MainWindow.numOfElipse;
        Ellipse[] ellipsePoints = new Ellipse[numOfElipses];
        Random rnd = new Random();
        for (int i=0;i<numOfElipses; i++)
        {
            SolidColorBrush brush =
                                new SolidColorBrush(
                                    Color.FromRgb(
                                    (byte)rnd.Next(255),
                                    (byte)rnd.Next(255),
                                    (byte)rnd.Next(255)
                                    ));
            var top = rnd.Next(0, 280);
            var left = rnd.Next(0, 450);
            ellipsePoints[i] = new Ellipse();
            ellipsePoints[i].Width = 40;
            ellipsePoints[i].Height = 40;
            Canvas.SetTop(ellipsePoints[i], i);
            Canvas.SetLeft(ellipsePoints[i], i*45);
            ellipsePoints[i].Fill = brush;
            c1.Children.Add(ellipsePoints[i]);
        }
    }
    private void E1_MouseEnter(object sender, MouseEventArgs e)
    {
        Random r = new Random();
        Ellipse ellipsePoints = (Ellipse)sender;
        ellipsePoints.Fill = new
        SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255),
        (byte)r.Next(255)));
    }
    private void E1_MouseDown(object sender, MouseButtonEventArgs e)
    {
        c1.Children.Remove((Ellipse)sender);
    }

}
}
</code>```

but it doesn't work.Can anyone explain why and how do I make it change color on a mouse over(hover) randomly,and disappear/be removed on a mouse click?
I would really appreciate any help!

答:
As mentioned in the comments, you need to actually hook up the events to the ellipses you are creating:

```<code>...
ellipsePoints[i].MouseEnter += E1_MouseEnter;    // "hook up" the Mouse Enter event
ellipsePoints[i].MouseDown += E1_MouseDown;      // "hook up" the Mouse Down event
c1.Children.Add(ellipsePoints[i]);
...
</code>```

Simply creating the E1_MouseEnter and E1_MouseDown methods does not automatically wire them up, and that makes sense when we think about it. There could be any number of objects on the Window that have those events - how is the code supposed to know who should listen to?

Body:
I have made a program where you ask the number of ellipses and it makes them in a different window in c#,but I want to have a mouse over effect-which I understood is called : MouseEnter and an onclick event,which I understood is called MouseDown, but I made an array of ellipses and I tried  the following :

namespace WpfApp1
{
///
/// Interaction logic for Window2.xaml
///
public partial class Window2 : Window
{
    int numOfElipses;
    public Window2()
    {
        InitializeComponent();
        numOfElipses= MainWindow.numOfElipse;
        Ellipse[] ellipsePoints = new Ellipse[numOfElipses];
        Random rnd = new Random();
        for (int i=0;i<numOfElipses; i++)
        {
            SolidColorBrush brush =
                                new SolidColorBrush(
                                    Color.FromRgb(
                                    (byte)rnd.Next(255),
                                    (byte)rnd.Next(255),
                                    (byte)rnd.Next(255)
                                    ));
            var top = rnd.Next(0, 280);
            var left = rnd.Next(0, 450);
            ellipsePoints[i] = new Ellipse();
            ellipsePoints[i].Width = 40;
            ellipsePoints[i].Height = 40;
            Canvas.SetTop(ellipsePoints[i], i);
            Canvas.SetLeft(ellipsePoints[i], i*45);
            ellipsePoints[i].Fill = brush;
            c1.Children.Add(ellipsePoints[i]);
        }
    }
    private void E1_MouseEnter(object sender, MouseEventArgs e)
    {
        Random r = new Random();
        Ellipse ellipsePoints = (Ellipse)sender;
        ellipsePoints.Fill = new
        SolidColorBrush(Color.FromRgb((byte)r.Next(255), (byte)r.Next(255),
        (byte)r.Next(255)));
    }
    private void E1_MouseDown(object sender, MouseButtonEventArgs e)
    {
        c1.Children.Remove((Ellipse)sender);
    }

}
}

but it doesn't work.Can anyone explain why and how do I make it change color on a mouse over(hover) randomly,and disappear/be removed on a mouse click?
I would really appreciate any help!

Body:
As mentioned in the comments, you need to actually hook up the events to the ellipses you are creating:

...
ellipsePoints[i].MouseEnter += E1_MouseEnter;    // "hook up" the Mouse Enter event
ellipsePoints[i].MouseDown += E1_MouseDown;      // "hook up" the Mouse Down event
c1.Children.Add(ellipsePoints[i]);
...

Simply creating the E1_MouseEnter and E1_MouseDown methods does not automatically wire them up, and that makes sense when we think about it. There could be any number of objects on the Window that have those events - how is the code supposed to know who should listen to?


问:
RequireJS Compilation in Maven project with external JS dependencies
I have a web project that's built with Maven and I'm trying to figure out the best way to compile the JavaScript files with the RequireJS compiler (this question could apply to any compiler/minifier as well).

I have a setup that works, but it needs improvement:

I've packaged the 3rd party JavaScript libraries and they are being downloaded as dependencies and then added with the WAR Overlay plugin.

I have an Exec plugin task that runs the RequireJS compiler inside the target directory. I currently manually run exec:exec after the package target runs (and therefore the WAR contents are placed in the target directory).

What I would like instead is to make JS compilation part of main (Java) compilation. The JS compiler itself (Require JS) is downloaded as a dependency during the WAR overlay phase which happens after compilation. So, I need the Require JS files to be downloaded and unpacked and I need to run the JS compilation using those files, before/during/after Java compilation.

I'm sure there could be several ways to achieve this. I'm looking for the most elegant solution.

Update: Existing POM snippets

I have JavaScript dependencies which I have zipped and added to our repository manager:

```<code>    <dependency>
        <groupId>org.requirejs</groupId>
        <artifactId>requirejs</artifactId>
        <version>0.22.0</version>
        <classifier>repackaged</classifier>
        <type>zip</type>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.jqueryui</groupId>
        <artifactId>jquery-ui</artifactId>
        <version>1.8.7</version>
        <classifier>repackaged</classifier>
        <type>zip</type>
        <scope>runtime</scope>
    </dependency>
</code>```

Take note that RequireJS itself (which is required for the compilation of the rest of libraries) is also loaded as an external dependency. So the first thing is, I need this dependency to be downloaded and unzipped before I can commence with RequireJS compilation.

These dependencies are being added to the WAR using the WAR Overlay plugin:

```<code>        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <overlays>
                    <overlay>
                        <groupId>org.requirejs</groupId>
                        <artifactId>requirejs</artifactId>
                        <classifier>repackaged</classifier>
                        <type>zip</type>
                        <targetPath>lib</targetPath>
                        <includes>
                            <include>requirejs/require.js</include>
                            <include>requirejs/require/*</include>
                            <include>requirejs/build/**</include>
                        </includes>
                    </overlay>
                    <overlay>
                        <groupId>com.jqueryui</groupId>
                        <artifactId>jquery-ui</artifactId>
                        <classifier>repackaged</classifier>
                        <type>zip</type>
                        <targetPath>lib</targetPath>
                    </overlay>
                </overlays>
            </configuration>
        </plugin>
</code>```

Even though I don't need requirejs/build/** to end up in the WAR, I'm including it as part of the overlay to get the unzipped RequireJS build scripts, simply because I haven't figured out a better way.

Then I have a Exec plugin task that performs the compilation. But note that this task hasn't been added to the normal compilation work flow: I have to manually invoke it with mvn exec:exec after the WAR packaging is done:

```<code>        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <executable>lib/requirejs/build/build.bat</executable>
                <workingDirectory>${project.build.directory}/${project.artifactId}</workingDirectory>
                <arguments>
                    <argument>name=bootstrap</argument>
                    <argument>out=combined.js</argument>
                    <argument>baseUrl=scripts</argument>
                    <argument>optimize=closure</argument>
                    <argument>excludeShallow=plugins/manifest</argument>
                </arguments>
            </configuration>
        </plugin>
</code>```

So, some questions are:

How can I extract different portions of a single zipped dependency for the compilation and WAR packaging steps? Or do I have to create two zip files, one with just the runtime stuff and the other for compilations scripts?

I would like to trigger exec:exec ideally during compilation, or if not, just prior to WAR packaging. How do I do that?

I have actually tried a bunch off stuff without success, so I hope I don't appear as lazily posting a huge chunk of code and waiting for answers :) It's just that I haven't quite wrapped my mind around how Maven targets/phases etc. work yet.

答:
I've come up with the following solution that works for me:

Instead of depending on the WAR overlay for the unpacking of the RequireJS files, I explicitly unpack them using the Dependency plugin:

```<code>  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <phase>compile</phase>
        <goals>
          <goal>unpack</goal>
        </goals>
        <configuration>
          <artifactItems>
            <artifactItem>
              <groupId>org.requirejs</groupId>
              <artifactId>requirejs</artifactId>
              <version>0.22.0</version>
              <type>zip</type>
              <classifier>repackaged</classifier>
              <overWrite>true</overWrite>
            </artifactItem>
          </artifactItems>
        </configuration>
      </execution>
    </executions>
  </plugin>
</code>```

The phase is set to "compile". This allows me to have the entire contents of the RequireJS package under the "dependency" folder, during compilation. So, the next thing I have is:

```<code>      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.1</version>
        <executions>
          <execution>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>
              ${project.build.directory}/dependency/requirejs/build/build.bat</executable>
              <workingDirectory>
              ${basedir}/src/main/webapp</workingDirectory>
              <arguments>
                <argument>name=bootstrap</argument>
                <argument>out=scripts/compiled.js</argument>
                <argument>baseUrl=scripts</argument>
                <argument>optimize=closure</argument>
                <argument>
                excludeShallow=plugins/manifest</argument>
              </arguments>
            </configuration>
          </execution>
        </executions>
      </plugin>
</code>```

This triggers RequireJS compilation inside the "dependency" folder, without touching either my source directory or the WAR directory. I then continue using the WAR overlay plugin to cherry pick the RequireJS files that want to go into the WAR.

Update

Since writing this solution, I've switched to using the "java" goal instead of "exec" because I had problems with using the RequireJS compiler's shell script + batch file through Hudson. I'm basically running the final Java command (generated by the scripts) that run the compiler through Rhino. The Node solution would be slightly different. For RequireJS 0.23.0, it goes something like this:

```<code><plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <id>compile-js</id>
            <phase>compile</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>java</executable>
                <workingDirectory>${basedir}/src/main/webapp</workingDirectory>
                <arguments>
                    <argument>-classpath</argument>
                    <!--argument>${project.build.directory}/dependency/requirejs/build/lib/rhino/js.jar${path.separator}${project.build.directory}/dependency/requirejs/build/lib/closure/compiler.jar</argument -->
                    <argument>${project.build.directory}/dependency/requirejs/build/lib/rhino/js.jar</argument>
                    <argument>org.mozilla.javascript.tools.shell.Main</argument>
                    <argument>${project.build.directory}/dependency/requirejs/bin/x.js</argument>
                    <argument>${project.build.directory}/dependency/requirejs/bin/</argument>
                    <argument>${project.build.directory}/dependency/requirejs/build/build.js</argument>
                    <argument>name=bootstrap</argument>
                    <argument>out=scripts/compiled.js</argument>
                    <argument>baseUrl=scripts</argument>
                    <argument>optimize=none</argument>
                </arguments>
            </configuration>
        </execution>
    </executions>
</plugin>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a web project that's built with Maven and I'm trying to figure out the best way to compile the JavaScript files with the RequireJS compiler (this question could apply to any compiler/minifier as well).

I have a setup that works, but it needs improvement:

I've packaged the 3rd party JavaScript libraries and they are being downloaded as dependencies and then added with the WAR Overlay plugin.

I have an Exec plugin task that runs the RequireJS compiler inside the target directory. I currently manually run exec:exec after the package target runs (and therefore the WAR contents are placed in the target directory).

What I would like instead is to make JS compilation part of main (Java) compilation. The JS compiler itself (Require JS) is downloaded as a dependency during the WAR overlay phase which happens after compilation. So, I need the Require JS files to be downloaded and unpacked and I need to run the JS compilation using those files, before/during/after Java compilation.

I'm sure there could be several ways to achieve this. I'm looking for the most elegant solution.

Update: Existing POM snippets

I have JavaScript dependencies which I have zipped and added to our repository manager:

    <dependency>
        <groupId>org.requirejs</groupId>
        <artifactId>requirejs</artifactId>
        <version>0.22.0</version>
        <classifier>repackaged</classifier>
        <type>zip</type>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.jqueryui</groupId>
        <artifactId>jquery-ui</artifactId>
        <version>1.8.7</version>
        <classifier>repackaged</classifier>
        <type>zip</type>
        <scope>runtime</scope>
    </dependency>

Take note that RequireJS itself (which is required for the compilation of the rest of libraries) is also loaded as an external dependency. So the first thing is, I need this dependency to be downloaded and unzipped before I can commence with RequireJS compilation.

These dependencies are being added to the WAR using the WAR Overlay plugin:

        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <overlays>
                    <overlay>
                        <groupId>org.requirejs</groupId>
                        <artifactId>requirejs</artifactId>
                        <classifier>repackaged</classifier>
                        <type>zip</type>
                        <targetPath>lib</targetPath>
                        <includes>
                            <include>requirejs/require.js</include>
                            <include>requirejs/require/*</include>
                            <include>requirejs/build/**</include>
                        </includes>
                    </overlay>
                    <overlay>
                        <groupId>com.jqueryui</groupId>
                        <artifactId>jquery-ui</artifactId>
                        <classifier>repackaged</classifier>
                        <type>zip</type>
                        <targetPath>lib</targetPath>
                    </overlay>
                </overlays>
            </configuration>
        </plugin>

Even though I don't need requirejs/build/** to end up in the WAR, I'm including it as part of the overlay to get the unzipped RequireJS build scripts, simply because I haven't figured out a better way.

Then I have a Exec plugin task that performs the compilation. But note that this task hasn't been added to the normal compilation work flow: I have to manually invoke it with mvn exec:exec after the WAR packaging is done:

        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>exec</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <executable>lib/requirejs/build/build.bat</executable>
                <workingDirectory>${project.build.directory}/${project.artifactId}</workingDirectory>
                <arguments>
                    <argument>name=bootstrap</argument>
                    <argument>out=combined.js</argument>
                    <argument>baseUrl=scripts</argument>
                    <argument>optimize=closure</argument>
                    <argument>excludeShallow=plugins/manifest</argument>
                </arguments>
            </configuration>
        </plugin>

So, some questions are:

How can I extract different portions of a single zipped dependency for the compilation and WAR packaging steps? Or do I have to create two zip files, one with just the runtime stuff and the other for compilations scripts?

I would like to trigger exec:exec ideally during compilation, or if not, just prior to WAR packaging. How do I do that?

I have actually tried a bunch off stuff without success, so I hope I don't appear as lazily posting a huge chunk of code and waiting for answers :) It's just that I haven't quite wrapped my mind around how Maven targets/phases etc. work yet.

Body:
I've come up with the following solution that works for me:

Instead of depending on the WAR overlay for the unpacking of the RequireJS files, I explicitly unpack them using the Dependency plugin:

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <phase>compile</phase>
        <goals>
          <goal>unpack</goal>
        </goals>
        <configuration>
          <artifactItems>
            <artifactItem>
              <groupId>org.requirejs</groupId>
              <artifactId>requirejs</artifactId>
              <version>0.22.0</version>
              <type>zip</type>
              <classifier>repackaged</classifier>
              <overWrite>true</overWrite>
            </artifactItem>
          </artifactItems>
        </configuration>
      </execution>
    </executions>
  </plugin>

The phase is set to "compile". This allows me to have the entire contents of the RequireJS package under the "dependency" folder, during compilation. So, the next thing I have is:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.1</version>
        <executions>
          <execution>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>
              ${project.build.directory}/dependency/requirejs/build/build.bat</executable>
              <workingDirectory>
              ${basedir}/src/main/webapp</workingDirectory>
              <arguments>
                <argument>name=bootstrap</argument>
                <argument>out=scripts/compiled.js</argument>
                <argument>baseUrl=scripts</argument>
                <argument>optimize=closure</argument>
                <argument>
                excludeShallow=plugins/manifest</argument>
              </arguments>
            </configuration>
          </execution>
        </executions>
      </plugin>

This triggers RequireJS compilation inside the "dependency" folder, without touching either my source directory or the WAR directory. I then continue using the WAR overlay plugin to cherry pick the RequireJS files that want to go into the WAR.

Update

Since writing this solution, I've switched to using the "java" goal instead of "exec" because I had problems with using the RequireJS compiler's shell script + batch file through Hudson. I'm basically running the final Java command (generated by the scripts) that run the compiler through Rhino. The Node solution would be slightly different. For RequireJS 0.23.0, it goes something like this:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <id>compile-js</id>
            <phase>compile</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>java</executable>
                <workingDirectory>${basedir}/src/main/webapp</workingDirectory>
                <arguments>
                    <argument>-classpath</argument>
                    <!--argument>${project.build.directory}/dependency/requirejs/build/lib/rhino/js.jar${path.separator}${project.build.directory}/dependency/requirejs/build/lib/closure/compiler.jar</argument -->
                    <argument>${project.build.directory}/dependency/requirejs/build/lib/rhino/js.jar</argument>
                    <argument>org.mozilla.javascript.tools.shell.Main</argument>
                    <argument>${project.build.directory}/dependency/requirejs/bin/x.js</argument>
                    <argument>${project.build.directory}/dependency/requirejs/bin/</argument>
                    <argument>${project.build.directory}/dependency/requirejs/build/build.js</argument>
                    <argument>name=bootstrap</argument>
                    <argument>out=scripts/compiled.js</argument>
                    <argument>baseUrl=scripts</argument>
                    <argument>optimize=none</argument>
                </arguments>
            </configuration>
        </execution>
    </executions>
</plugin>


问:
How to disable google maps dragging
How to disable the dragging in google maps in your website in order to freeze it like an image? I've just used basic Iframe code that gives me google maps.

答:
The draggable property has been deprecated.

To disable dragging on the map, you can now use the gestureHandling property, and set it to "none".

You can also disable the use of arrow keys, by setting keyboardShortcuts to false

ex: map.setOptions({gestureHandling: "none", keyboardShortcuts: false});

Title: How to disable google maps dragging


问:
docker exec bash behaves weirdly
When I do:

docker exec -ti myContainer /bin/bash

I have a new bash terminal on running container myContainer.

Now when I write

docker exec -ti lescompanions /bin/bash -c "echo youpi"

docker only outputs youpi and returns with no interactive terminal created. I was actually expecting docker to create the terminal and run echo youpi within the newly created terminal.

Where am I wrong?

---- EDIT ----

Now how shall I run echo youpi in the new terminal on the existing container and not have the terminal return to the host after the execution of echo youpi?

答:
You are not doing anything wrong, it's just how bash works. I've checked it on my Ubuntu (without Docker):</p>

```<code>$ /bin/bash
(no output, bash instance running)

$ /bin/bash -c "echo youpi"
youpi
(bash finished)
</code>```

Title: docker exec bash behaves weirdly

Body:
You are not doing anything wrong, it's just how bash works. I've checked it on my Ubuntu (without Docker):

$ /bin/bash
(no output, bash instance running)

$ /bin/bash -c "echo youpi"
youpi
(bash finished)


问:
Writing server-side handler for jquery file upload
I'm trying to get the blueimp jQuery-File-Upload component working in my MVC application.

Here's my code so far.

JavaScript:

```<code>$('#fileupload').fileupload({
    url: '@Url.Action("AddAttachment", "File")',
    dataType: 'json',
    progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        console.log(progress);
    },
    add: function(e, data) {
        data.submit();
    },
    done: function (e, data) {
        $.each(data.result.files, function (index, file) {
            $('<p/>').text(file.name).appendTo(document.body);
        });
    }
});
</code>```

Controller:

```<code>[HttpPost]
public JsonResult AddAttachment()
{
    var files = new List<FileAttachmentFileModel>();

    try
    {
        if (Request.Files.Count > 0)
        {
            using (var dbContext = new vegaEntities())
            using (var transaction = dbContext.Database.BeginTransaction())
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase file = Request.Files[i];

                    if (file.ContentLength > 0)
                    {
                        FileAttachment fileAttachment = new FileAttachment
                        {
                            Id = Guid.NewGuid(),
                            FileName = file.FileName,
                            ContentType = file.ContentType,
                            DateAdded = DateTime.UtcNow
                        };
                        // Load content
                        fileAttachment.Content = new byte[file.ContentLength];
                        file.InputStream.Read(fileAttachment.Content, 0, file.ContentLength);
                        // Add to database
                        dbContext.FileAttachments.Add(fileAttachment);
                        // Add to results
                        files.Add(new FileAttachmentFileModel
                        {
                            id = fileAttachment.Id.ToString(),
                            name = file.FileName,
                            size = file.ContentLength.FormatAsFileSize(),
                            //action = FileAttachmentFileModel.AddAction
                        });
                    }
                }
                dbContext.SaveChanges();
                transaction.Commit();
            }
        }
    }
    catch (Exception ex)
    {
        // TODO:
        return Json(new { message = ex.Message });
    }
    return Json(new { files = files });
}
</code>```

This code is working with smaller files. My C# method gets called, the file is retrieved, and the progressall handler is called showing 100%.

The problem is when I attempt to upload a large file (where the progressall handler gets called more than once). In that case, the handler gets called with incrementing progress values up to 100%, as expected. But my C# method never gets called and the browser reports the following error.

POST http://localhost:1290/File/AddAttachment 404 (Not Found)

I'm confused by this error because the C# method is the same in both cases. Why is it found in one and not found in the other. I assume the issue is that my controller method is expecting a complete file and that I must instead write code to handle the upload in chunks. Is this right? Can anyone point me to documentation on how to write an upload handler using C#/MVC?

答:
In fact, there is a trigger that depends on the incorrect opening of the high file which is not downloaded on its base.

The 404 error depends on the IIS security protocol

If you are going to examine the details of Request and Response, you can see it yourself

I do not recommend resolving it by the IIS administrator.

If you will set it at the application level

an example in web.config;

```<code><System.webServer>
    <Security>
      <RequestFiltering>
        <requestLimits maxAllowedContentLength = "30000000" />
      </ requestFiltering>
    </ security>
  </system.webServer>
</code>```

Body:
I'm trying to get the blueimp jQuery-File-Upload component working in my MVC application.

Here's my code so far.

JavaScript:

$('#fileupload').fileupload({
    url: '@Url.Action("AddAttachment", "File")',
    dataType: 'json',
    progressall: function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        console.log(progress);
    },
    add: function(e, data) {
        data.submit();
    },
    done: function (e, data) {
        $.each(data.result.files, function (index, file) {
            $('
').text(file.name).appendTo(document.body);
        });
    }
});

Controller:

[HttpPost]
public JsonResult AddAttachment()
{
    var files = new List<FileAttachmentFileModel>();

    try
    {
        if (Request.Files.Count > 0)
        {
            using (var dbContext = new vegaEntities())
            using (var transaction = dbContext.Database.BeginTransaction())
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    HttpPostedFileBase file = Request.Files[i];

                    if (file.ContentLength > 0)
                    {
                        FileAttachment fileAttachment = new FileAttachment
                        {
                            Id = Guid.NewGuid(),
                            FileName = file.FileName,
                            ContentType = file.ContentType,
                            DateAdded = DateTime.UtcNow
                        };
                        // Load content
                        fileAttachment.Content = new byte[file.ContentLength];
                        file.InputStream.Read(fileAttachment.Content, 0, file.ContentLength);
                        // Add to database
                        dbContext.FileAttachments.Add(fileAttachment);
                        // Add to results
                        files.Add(new FileAttachmentFileModel
                        {
                            id = fileAttachment.Id.ToString(),
                            name = file.FileName,
                            size = file.ContentLength.FormatAsFileSize(),
                            //action = FileAttachmentFileModel.AddAction
                        });
                    }
                }
                dbContext.SaveChanges();
                transaction.Commit();
            }
        }
    }
    catch (Exception ex)
    {
        // TODO:
        return Json(new { message = ex.Message });
    }
    return Json(new { files = files });
}

This code is working with smaller files. My C# method gets called, the file is retrieved, and the progressall handler is called showing 100%.

The problem is when I attempt to upload a large file (where the progressall handler gets called more than once). In that case, the handler gets called with incrementing progress values up to 100%, as expected. But my C# method never gets called and the browser reports the following error.

POST http://localhost:1290/File/AddAttachment 404 (Not Found)

I'm confused by this error because the C# method is the same in both cases. Why is it found in one and not found in the other. I assume the issue is that my controller method is expecting a complete file and that I must instead write code to handle the upload in chunks. Is this right? Can anyone point me to documentation on how to write an upload handler using C#/MVC?

Body:
In fact, there is a trigger that depends on the incorrect opening of the high file which is not downloaded on its base.

The 404 error depends on the IIS security protocol

If you are going to examine the details of Request and Response, you can see it yourself

I do not recommend resolving it by the IIS administrator.

If you will set it at the application level

an example in web.config;

<System.webServer>
    <Security>
      <RequestFiltering>
        <requestLimits maxAllowedContentLength = "30000000" />
      </ requestFiltering>
    </ security>
  </system.webServer>


问:
What are the review requirements regarding QUERY intents?
Due to hardware restrictions, we are unable to retrieve the current status of many of our lights (their color/brightness/etc.).

In the QA test cases spreadsheet found here, at the bottom under Deploying, a number of QUERY intents are listed to be tested. Does this mean our Smart Home application will not be able to pass certification?

Thank you for reading.

答: There is some expectation from the user to know the status of your their house at any time. If you cannot retrieve the state directly from devices, you should be able to use your cloud provider to store a virtual equivalent of the device. Then instead of querying the device directly you can return the state of the virtual device.</p>


问:
Does polymorphism exist in QML?
Does polymorphism and/or object pointers exist in QML? I have a class A that has five members of different classes of which exactly one is visible at any given moment. I also have properties in A that depend on properties in the visible member (which are called the same things in all members).

Currently, I'm calculating every such property in A using the following strategy:

```<code>import QtQuick 2.7

Rectangle {
    property int a: member1.visible ? member1.alpha + member1.beta :
                    member2.visible ? member2.alpha + member2.beta :
                    member3.visible ? member3.alpha + member3.beta :
                    member4.visible ? member4.alpha + member4.beta :
                    member5.visible ? member5.alpha + member5.beta :
                    0

    property int b: member1.visible ? member1.gamma * member1.delta :
                    member2.visible ? member2.gamma * member2.delta :
                    member3.visible ? member3.gamma * member3.delta :
                    member4.visible ? member4.gamma * member4.delta :
                    member5.visible ? member5.gamma * member5.delta :
                    0

    // Exactly one of these members have its visible-property set to true
    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}
</code>```

which feels both like it's using more code than necessary, and like it's not very maintenance friendly both since it's easy to make an error and since I have to update the expressions for all properties in A if I want to add or remove a member.

Ideally (comming from a background of doing a lot of C++ programming), I would like to be able to do something like this:

```<code>import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember:
        member1.visible ? member1 :
        member2.visible ? member2 :
        member3.visible ? member3 :
        member4.visible ? member4 :
        member5.visible ? member5 :
        0  // Shouldn't happen

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}
</code>```

in order to reduce the amount of code needed to be written and increase the maintainability, where visibleMember would then be a pointer or some kind of reference to an object. Or perhaps even:

```<code>import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember: NULL

    property int a: visibleMember !== NULL ? visibleMember.alpha + visibleMember.beta : 0
    property int b: visibleMember !== NULL ? visibleMember.gamma * visibleMember.delta : 0
}
</code>```

and set visibleMember from outside the class (for example by its parent) and in that way be able to create objects dynamically (if that is possible) which are then assigned to visibleMember, instead of having all possible objects that can be assigned to visibleMember existing as latent members in A.

However, I'm not sure what <property-type> would be, or whether you can assign an object pointer to visibleMember like this (i.e. whether object pointers/references exist), which can then be checked to see whether it is a NULL pointer. Is at least somethng of what I'm trying to do possible to achieve in some way?

答:
Why do you need to do that? It seems like you are abusing the QML language and you will surely run into performance issues.

Please spend some time trying to understand the QML language and how it differs from C++.

First note that

```<code>Rectangle {

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
}
</code>```

is absolutely not equivalent to:

```<code>struct MyStruct: public Rectangle
{
    MySubClass1 member1;
    MySubClass2 member2;
}
</code>```

but it is rather something like that:

```<code>struct MyStruct: public Rectangle
{
    MyStruct()
    {
        children.insert("member1", new MySubClass1);
        children.insert("member2", new MySubClass2);
    }
    map<string, void *> children;
}
</code>```

If you need only on member at a given time, you can do something like that:

```<code>// MyComponent.qml
Rectangle {
    id: root
    property var visibleMember: InitialMember{} // If you can, replace var by the closest fitting data type

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    function change1() {
        visibleMember.destroy();
        var component = Qt.createComponent("MySubClass1.qml");
        var object = component.createObject(root);
        visibleMember = object;
    }

    function change2() {
        visibleMember.destroy();
        var object = Qt.createQmlObject('import QtQuick 2.0; MySubClass2 {}', root);
        visibleMember = object;
    }
}
</code>```

And you can also set visibleMember from outside either statically or dynamically:

```<code>MyComponent { // Assumming the code above is in MyComponent.qml
    visibleMember: SomethingElse {}
}
</code>```

Note: If this is the way MyComponent is supposed to be used, the you can remove change1(), change2() and even maybe InitialMember{} from MyComponent.qml.

Edit

Same as above but using Loader instead of Qt.createComponent()

```<code>Rectangle {
    id: root
    property var visibleMember: loader.item // If you can replace var by the closest fitting data type
    property alias source: loader.source // If you want to expose the loader source

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    function change1() {
        loader.source = "MySubClass1.qml";
    }

    function change2() {
        loader.source = "MySubClass2.qml";
    }

    Loader {
        id: loader
    }
}
</code>```

Title: Does polymorphism exist in QML?

Body:
Does polymorphism and/or object pointers exist in QML? I have a class A that has five members of different classes of which exactly one is visible at any given moment. I also have properties in A that depend on properties in the visible member (which are called the same things in all members).

Currently, I'm calculating every such property in A using the following strategy:

import QtQuick 2.7

Rectangle {
    property int a: member1.visible ? member1.alpha + member1.beta :
                    member2.visible ? member2.alpha + member2.beta :
                    member3.visible ? member3.alpha + member3.beta :
                    member4.visible ? member4.alpha + member4.beta :
                    member5.visible ? member5.alpha + member5.beta :
                    0

    property int b: member1.visible ? member1.gamma * member1.delta :
                    member2.visible ? member2.gamma * member2.delta :
                    member3.visible ? member3.gamma * member3.delta :
                    member4.visible ? member4.gamma * member4.delta :
                    member5.visible ? member5.gamma * member5.delta :
                    0

    // Exactly one of these members have its visible-property set to true
    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}

which feels both like it's using more code than necessary, and like it's not very maintenance friendly both since it's easy to make an error and since I have to update the expressions for all properties in A if I want to add or remove a member.

Ideally (comming from a background of doing a lot of C++ programming), I would like to be able to do something like this:

import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember:
        member1.visible ? member1 :
        member2.visible ? member2 :
        member3.visible ? member3 :
        member4.visible ? member4 :
        member5.visible ? member5 :
        0  // Shouldn't happen

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
    MySubClass3 {id: member3}
    MySubClass4 {id: member4}
    MySubClass5 {id: member5}
}

in order to reduce the amount of code needed to be written and increase the maintainability, where visibleMember would then be a pointer or some kind of reference to an object. Or perhaps even:

import QtQuick 2.7

Rectangle {
    property <property-type> visibleMember: NULL

    property int a: visibleMember !== NULL ? visibleMember.alpha + visibleMember.beta : 0
    property int b: visibleMember !== NULL ? visibleMember.gamma * visibleMember.delta : 0
}

and set visibleMember from outside the class (for example by its parent) and in that way be able to create objects dynamically (if that is possible) which are then assigned to visibleMember, instead of having all possible objects that can be assigned to visibleMember existing as latent members in A.

However, I'm not sure what <property-type> would be, or whether you can assign an object pointer to visibleMember like this (i.e. whether object pointers/references exist), which can then be checked to see whether it is a NULL pointer. Is at least somethng of what I'm trying to do possible to achieve in some way?

Body:
Why do you need to do that? It seems like you are abusing the QML language and you will surely run into performance issues.

Please spend some time trying to understand the QML language and how it differs from C++.

First note that

Rectangle {

    MySubClass1 {id: member1}
    MySubClass2 {id: member2}
}

is absolutely not equivalent to:

struct MyStruct: public Rectangle
{
    MySubClass1 member1;
    MySubClass2 member2;
}

but it is rather something like that:

struct MyStruct: public Rectangle
{
    MyStruct()
    {
        children.insert("member1", new MySubClass1);
        children.insert("member2", new MySubClass2);
    }
    map<string, void *> children;
}

If you need only on member at a given time, you can do something like that:

// MyComponent.qml
Rectangle {
    id: root
    property var visibleMember: InitialMember{} // If you can, replace var by the closest fitting data type

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    function change1() {
        visibleMember.destroy();
        var component = Qt.createComponent("MySubClass1.qml");
        var object = component.createObject(root);
        visibleMember = object;
    }

    function change2() {
        visibleMember.destroy();
        var object = Qt.createQmlObject('import QtQuick 2.0; MySubClass2 {}', root);
        visibleMember = object;
    }
}

And you can also set visibleMember from outside either statically or dynamically:

MyComponent { // Assumming the code above is in MyComponent.qml
    visibleMember: SomethingElse {}
}

Note: If this is the way MyComponent is supposed to be used, the you can remove change1(), change2() and even maybe InitialMember{} from MyComponent.qml.

Edit

Same as above but using Loader instead of Qt.createComponent()

Rectangle {
    id: root
    property var visibleMember: loader.item // If you can replace var by the closest fitting data type
    property alias source: loader.source // If you want to expose the loader source

    property int a: visibleMember.alpha + visibleMember.beta
    property int b: visibleMember.gamma * visibleMember.delta

    function change1() {
        loader.source = "MySubClass1.qml";
    }

    function change2() {
        loader.source = "MySubClass2.qml";
    }

    Loader {
        id: loader
    }
}