问:
InitalValues don't change even though the state they are set to does
I have a Semantic-UI modal that contains a redux-form as it's content. When opening the modal, I pass the form to it's content prop. The form element has an initialValues prop set to a prop mapped to state.

```<code>                <FormModal
                    handleSubmit={ this.sortSubmit }
                    size='small'
                    formName='sortForm'
                    header='Sort'
                    headerIcon='sort'
                    content={
                        <SortForm table={ this.props.table } initialValues={ { orderBy: this.props.search.orderBy, orderDirection: this.props.search.orderDirection } } />
                    }
                    trigger={
                        <Button icon floated='right' size="mini">
                            <Icon name='sort' />
                        </Button>
                    }
                />
</code>```

I then change this.props.search.orderBy by changing the redux state. Everything in the app updates to reflect the change, except this redux-form's initialValues, which should change when the state changes. I open the modal again, and the fields are reset to the old initialValues instead of the newly set values.

Any ideas why this would happen?

On a possibly related note, re-rendering the modal JSX does not seem to close the modal. Since the modal's initial state is closed, I would have assumed a re-render of it would re-close it.

答:
You need to pass enableReinitialize={true} to your form.

Because enableReinitialize defaults to false. In this case, initialValues is only applied at componentWillMount.

Here is the part of doc about enableReinitialize:

When set to true, the form will reinitialize every time the
  initialValues prop changes. Defaults to false. If the
  keepDirtyOnReinitialize option is also set, the form will retain the
  value of dirty fields when reinitializing.

For more info, please read reduxForm

Body:
I have a Semantic-UI modal that contains a redux-form as it's content. When opening the modal, I pass the form to it's content prop. The form element has an initialValues prop set to a prop mapped to state.

                <FormModal
                    handleSubmit={ this.sortSubmit }
                    size='small'
                    formName='sortForm'
                    header='Sort'
                    headerIcon='sort'
                    content={
                        <SortForm table={ this.props.table } initialValues={ { orderBy: this.props.search.orderBy, orderDirection: this.props.search.orderDirection } } />
                    }
                    trigger={
                        <Button icon floated='right' size="mini">
                            <Icon name='sort' />
                        </Button>
                    }
                />

I then change this.props.search.orderBy by changing the redux state. Everything in the app updates to reflect the change, except this redux-form's initialValues, which should change when the state changes. I open the modal again, and the fields are reset to the old initialValues instead of the newly set values.

Any ideas why this would happen?

On a possibly related note, re-rendering the modal JSX does not seem to close the modal. Since the modal's initial state is closed, I would have assumed a re-render of it would re-close it.


来源: stackexchange

问:
How do I check for CSS styling with JavaScript?
Why am I unable to test for CSS styling like this:

```<code>if (document.getElementById("myText").style.outline == "10px solid black")
{
  // Do something
}
</code>```

or

```<code>if (document.getElementById("myText").style.match("outline: 10px solid
black"))
{
  // Do something;
}
</code>```

when I have:

```<code>#myText
{
  outline: 10px solid black;
}
</code>```

答:
The style property will only return styles that are set on the element's style attribute or in javascript, so you won't see styles that applied separately by CSS.

Furthermore, there are multiple ways of expressing the same set of CSS properties, and the browser is generating a string that describes the current properties (rather than returning whatever string you used to set them). Therefore the browser can and will reorder the property values and/or convert them to other units (e.g. black -> rgb(0,0,0)) so testing for a particular string is never going to be reliable. E.g.

document.body.style.outline = "10px solid black"
console.log(document.body.style.outline)```

ContentLicense: CC BY-SA 3.0

Body:
Why am I unable to test for CSS styling like this:

if (document.getElementById("myText").style.outline == "10px solid black")
{
  // Do something
}

or

if (document.getElementById("myText").style.match("outline: 10px solid
black"))
{
  // Do something;
}

when I have:

#myText
{
  outline: 10px solid black;
}


问:
Only PHP Code Calculator with Clickable Buttons as Input
I am trying to code a calculator with only PHP and HTML code.

The Calculator should look like a real one and the buttons should be clickable.

Right now, I am stuck at combining 2 numbers, this means I press one button the number will be shown. But after I press the second button the first value disappears because of the type="submit".

My Question is: How can I save the value and show all pressed buttons together?

I know I can do that with a hidden input, but I don't know how to use them properly.

Also how am I able to calculate the whole expression after doing that?

I know javascript or any other client-side language would be better, but I want to find a way to do it purely with PHP and HTML.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Taschenrechner</title>
        <link href="Stylesheets/Stylesheets.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
if(isset($_POST['zahl'])){
    $zahl1 = $_POST['zahl'];
}else{
    $zahl1 = 0;
}
?>

<form name="rechner" action="rechner.php" method="post">
    <input id="feld1" type="hidden" name="zahl1" value="">
    <input id="feld2" type="hidden" name="opera" value="">
    <input id="feld3" type="hidden" name="zahl2" value="">
    <input id="feld4" type="hidden" name="zwischerg" value=>
    <table align="center" style="width:300px; height:450px; border:solid thick black;">
        <tr>
            <td align="center">
                <input id="display" type="text" name="bildschirm" readonly="readonly" style="text-align: center; height: 50px; width: 216px;" value=<?php echo $zahl1; $op; $zahl2 ?>>
            </td>
        </tr>
        <tr>
            <td>
                <table align="center">
                    <tr>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="1" >
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="2">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="3">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="operator" value="+">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="4">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="5">
                        </td>
                        <td >
                            <input class="taste" type="submit" name="zahl" value="6">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="operator" value="-">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="7">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="8">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="9">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="operator" value="*">
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input class="taste" type="submit" name="clear" value="C">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value="0">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="zahl" value=".">
                        </td>
                        <td>
                            <input class="taste" type="submit" name="operator" value="/">
                        </td>
                    </tr>
                    <tr>
                        <td colspan="4">
                            <input type="submit" name="gleich" value="=" style=" width: 215px; height: 50px;">
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</form>
</body>
</html>
</code>```

答:
This is my truly basic, almost style-less, pure-PHP calculator form:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Basic PHP Calculator</title>
</head>
<body>
<?php
//var_export($_POST);
//echo "<br>";
$buttons = [1,2,3,'+',4,5,6,'-',7,8,9,'*','C',0,'.','/','='];
$pressed = '';
if (isset($_POST['pressed']) && in_array($_POST['pressed'], $buttons)) {
    $pressed = $_POST['pressed'];
}
$stored = '';
if (isset($_POST['stored']) && preg_match('~^(?:[\d.]+[*/+-]?)+$~', $_POST['stored'], $out)) {
    $stored = $out[0];
}
$display = $stored . $pressed;
//echo "$pressed & $stored & $display<br>";
if ($pressed == 'C') {
    $display = '';
} elseif ($pressed == '=' && preg_match('~^\d*\.?\d+(?:[*/+-]\d*\.?\d+)*$~', $stored)) {
    $display .= eval("return $stored;");
}

echo "<form action=\"\" method=\"POST\">";
    echo "<table style=\"width:300px;border:solid thick black;\">";
        echo "<tr>";
            echo "<td colspan=\"4\">$display</td>";
        echo "</tr>";
        foreach (array_chunk($buttons, 4) as $chunk) {
            echo "<tr>";
                foreach ($chunk as $button) {
                    echo "<td",(count($chunk) != 4 ? " colspan=\"4\"" : "") , "><button name=\"pressed\" value=\"$button\">$button</button></td>";
                }
            echo "</tr>";
        }
    echo "</table>";
    echo "<input type=\"hidden\" name=\"stored\" value=\"$display\">";
echo "</form>";
?>
</body>
</html>
</code>```

Here is a screenshot while I was testing:

You can see that I've made every button a submit button with the same name, but different values.  I use a single hidden input to preserve built expression.  There will be many enhancements and considerations beyond this demo, it is up to you how far to go down this rabbit hole.

P.S. For anyone who just unholstered their sidearm, squinted one eye, and sternly uttered "Hey, we don't take kindly to folks like you callin' eval() in these here parts!".  Well, I've endeavored to adequately validate the string to be evaluated.  If there is a known hole, please let me know and I'll try to fix it.  Alternatively, this is my attempt to re-invent the eval() process with BOMDAS in mind:

Code: (Demo)

```<code>$stored = "2+3*4/6";
$components = preg_split('~([*/+-])~', $stored, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
while (($index = array_search('*', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] * $components[$index + 1]);
}
while (($index = array_search('/', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] / $components[$index + 1]);
}
while (($index = array_search('+', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] + $components[$index + 1]);
}
while (($index = array_search('-', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] - $components[$index + 1]);
}
echo current($components);  // 4
</code>```

Body:
I am trying to code a calculator with only PHP and HTML code.

The Calculator should look like a real one and the buttons should be clickable.

Right now, I am stuck at combining 2 numbers, this means I press one button the number will be shown. But after I press the second button the first value disappears because of the type="submit".

My Question is: How can I save the value and show all pressed buttons together?

I know I can do that with a hidden input, but I don't know how to use them properly.

Also how am I able to calculate the whole expression after doing that?

I know javascript or any other client-side language would be better, but I want to find a way to do it purely with PHP and HTML.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Taschenrechner</title>
        <link href="Stylesheets/Stylesheets.css" rel="stylesheet" type="text/css">

<?php
if(isset($_POST['zahl'])){
    $zahl1 = $_POST['zahl'];
}else{
    $zahl1 = 0;
}
?>

<form name="rechner" action="rechner.php" method="post">
    <input id="feld1" type="hidden" name="zahl1" value="">
    <input id="feld2" type="hidden" name="opera" value="">
    <input id="feld3" type="hidden" name="zahl2" value="">
    <input id="feld4" type="hidden" name="zwischerg" value=>

                <input id="display" type="text" name="bildschirm" readonly="readonly" style="text-align: center; height: 50px; width: 216px;" value=<?php echo $zahl1; $op; $zahl2 ?>>

                            <input class="taste" type="submit" name="zahl" value="1" >

                            <input class="taste" type="submit" name="zahl" value="2">

                            <input class="taste" type="submit" name="zahl" value="3">

                            <input class="taste" type="submit" name="operator" value="+">

                            <input class="taste" type="submit" name="zahl" value="4">

                            <input class="taste" type="submit" name="zahl" value="5">

                            <input class="taste" type="submit" name="zahl" value="6">

                            <input class="taste" type="submit" name="operator" value="-">

                            <input class="taste" type="submit" name="zahl" value="7">

                            <input class="taste" type="submit" name="zahl" value="8">

                            <input class="taste" type="submit" name="zahl" value="9">

                            <input class="taste" type="submit" name="operator" value="*">

                            <input class="taste" type="submit" name="clear" value="C">

                            <input class="taste" type="submit" name="zahl" value="0">

                            <input class="taste" type="submit" name="zahl" value=".">

                            <input class="taste" type="submit" name="operator" value="/">

                            <input type="submit" name="gleich" value="=" style=" width: 215px; height: 50px;">

</form>

Body:
This is my truly basic, almost style-less, pure-PHP calculator form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Basic PHP Calculator</title>
</head>
<body>
<?php
//var_export($_POST);
//echo "<br>";
$buttons = [1,2,3,'+',4,5,6,'-',7,8,9,'*','C',0,'.','/','='];
$pressed = '';
if (isset($_POST['pressed']) && in_array($_POST['pressed'], $buttons)) {
    $pressed = $_POST['pressed'];
}
$stored = '';
if (isset($_POST['stored']) && preg_match('~^(?:[\d.]+[*/+-]?)+$~', $_POST['stored'], $out)) {
    $stored = $out[0];
}
$display = $stored . $pressed;
//echo "$pressed & $stored & $display<br>";
if ($pressed == 'C') {
    $display = '';
} elseif ($pressed == '=' && preg_match('~^\d*\.?\d+(?:[*/+-]\d*\.?\d+)*$~', $stored)) {
    $display .= eval("return $stored;");
}

echo "<form action=\"\" method=\"POST\">";
    echo "<table style=\"width:300px;border:solid thick black;\">";
        echo "<tr>";
            echo "<td colspan=\"4\">$display</td>";
        echo "</tr>";
        foreach (array_chunk($buttons, 4) as $chunk) {
            echo "<tr>";
                foreach ($chunk as $button) {
                    echo "<td",(count($chunk) != 4 ? " colspan=\"4\"" : "") , "><button name=\"pressed\" value=\"$button\">$button</button></td>";
                }
            echo "</tr>";
        }
    echo "</table>";
    echo "<input type=\"hidden\" name=\"stored\" value=\"$display\">";
echo "</form>";
?>
</body>
</html>

Here is a screenshot while I was testing:

You can see that I've made every button a submit button with the same name, but different values.  I use a single hidden input to preserve built expression.  There will be many enhancements and considerations beyond this demo, it is up to you how far to go down this rabbit hole.

P.S. For anyone who just unholstered their sidearm, squinted one eye, and sternly uttered "Hey, we don't take kindly to folks like you callin' eval() in these here parts!".  Well, I've endeavored to adequately validate the string to be evaluated.  If there is a known hole, please let me know and I'll try to fix it.  Alternatively, this is my attempt to re-invent the eval() process with BOMDAS in mind:

Code: (Demo)

$stored = "2+3*4/6";
$components = preg_split('~([*/+-])~', $stored, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
while (($index = array_search('*', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] * $components[$index + 1]);
}
while (($index = array_search('/', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] / $components[$index + 1]);
}
while (($index = array_search('+', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] + $components[$index + 1]);
}
while (($index = array_search('-', $components)) !== false) {
    array_splice($components, $index - 1, 3, $components[$index - 1] - $components[$index + 1]);
}
echo current($components);  // 4

ContentLicense: CC BY-SA 4.0


问:
unable to loop through array using ng-repeat
I am using Angular to consume nodejs web-service.

But I am unable to loop through the data.

Json Data:

```<code>  [
  {
    "_id": "595fbe940eaeda0b387568fc",
    "randomId": "0001",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 28,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fbe940eaeda0b387568ff",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 28,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fbe940eaeda0b387568fe",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fbe940eaeda0b387568fd",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  },
  {
    "_id": "595fc0b60eaeda0b38756900",
    "randomId": "0002",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 38,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fc0b60eaeda0b38756903",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 26,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fc0b60eaeda0b38756902",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fc0b60eaeda0b38756901",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  }
]
</code>```

HTML Page

```<code><div class="panel panel-default" ng-init="getProducts()">
    <!-- Default panel contents -->
    <div class="panel-heading">Products</div>
    <div class="panel-body">
        <div class="row">
            <div ng-repeat="product in products">
             <p>{{product.randomId}}</p>
             <p>{{product.os.od}}</p>
             <p>{{product.otherProductAttributes.l}}</p>
             <p>{{prooduct.productStock.size}} </p>
             <p>{{prooduct.productStock.imagePaths}}</p>

              </div>
            </div>
        </div>
    </div>
</code>```

I am trying to access above mentioned data fields, but html page is rendering nothing.

I printed products array on console, and it's printing entire array.So I HTML page is having data but it's not rendering according to my requirements.

Please help.

答:
You need to have nested ng-repeat to generate images from the stockPath.

```<code> <div ng-repeat="images in product.productStock">
             <p>{{images.imagePaths}}</p>
 </div>
</code>```

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
   $scope.products = [
  {
    "_id": "595fbe940eaeda0b387568fc",
    "randomId": "0001",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 28,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fbe940eaeda0b387568ff",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 28,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fbe940eaeda0b387568fe",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fbe940eaeda0b387568fd",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  },
  {
    "_id": "595fc0b60eaeda0b38756900",
    "randomId": "0002",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 38,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fc0b60eaeda0b38756903",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 26,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fc0b60eaeda0b38756902",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fc0b60eaeda0b38756901",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  }
];
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
  <div class="panel panel-default" ng-init="getProducts()">
    <!-- Default panel contents -->
    <div class="panel-heading">Products</div>
    <div class="panel-body">
        <div class="row">
            <div ng-repeat="product in products">
             <p>{{product.randomId}}</p>
             <p>{{product.os.od}}</p>
             <p>{{product.otherProductAttributes.l}}</p>
              <div ng-repeat="images in product.productStock">
             <p>{{images.size}} </p>
             <p>{{images.imagePaths}}</p>
              </div>
              </div>
            </div>
        </div>
    </div>

  </div>
</body>

</html></code>```

Body:
I am using Angular to consume nodejs web-service.

But I am unable to loop through the data.

Json Data:

  [
  {
    "_id": "595fbe940eaeda0b387568fc",
    "randomId": "0001",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 28,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fbe940eaeda0b387568ff",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 28,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fbe940eaeda0b387568fe",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fbe940eaeda0b387568fd",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  },
  {
    "_id": "595fc0b60eaeda0b38756900",
    "randomId": "0002",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 38,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fc0b60eaeda0b38756903",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 26,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fc0b60eaeda0b38756902",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fc0b60eaeda0b38756901",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  }
]

HTML Page

Products

{{product.randomId}}

{{product.os.od}}

{{product.otherProductAttributes.l}}

{{prooduct.productStock.size}}

{{prooduct.productStock.imagePaths}}

I am trying to access above mentioned data fields, but html page is rendering nothing.

I printed products array on console, and it's printing entire array.So I HTML page is having data but it's not rendering according to my requirements.

Please help.

Body:
You need to have nested ng-repeat to generate images from the stockPath.

 <div ng-repeat="images in product.productStock">
             <p>{{images.imagePaths}}</p>
 </div>

DEMO

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
   $scope.products = [
  {
    "_id": "595fbe940eaeda0b387568fc",
    "randomId": "0001",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 28,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fbe940eaeda0b387568ff",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 28,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fbe940eaeda0b387568fe",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fbe940eaeda0b387568fd",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  },
  {
    "_id": "595fc0b60eaeda0b38756900",
    "randomId": "0002",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 38,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fc0b60eaeda0b38756903",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 26,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fc0b60eaeda0b38756902",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fc0b60eaeda0b38756901",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  }
];
});

<!DOCTYPE html>
<html>
<head>
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <div ng-app="myApp" ng-controller="AppCtrl">
  <div class="panel panel-default" ng-init="getProducts()">
    <!-- Default panel contents -->
    <div class="panel-heading">Products</div>
    <div class="panel-body">
        <div class="row">
            <div ng-repeat="product in products">
             <p>{{product.randomId}}</p>
             <p>{{product.os.od}}</p>
             <p>{{product.otherProductAttributes.l}}</p>
              <div ng-repeat="images in product.productStock">
             <p>{{images.size}} </p>
             <p>{{images.imagePaths}}</p>
              </div>
              </div>
            </div>
        </div>
    </div>

  </div>
</body>

</html>


问:
Restart Delphi Application Programmatically
It should not be possible to run multiple instances of my application. Therefore the project source contains:

```<code>CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;
</code>```

Now I want to restart my application programmatically. The usual way would be:

```<code>AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;
</code>```

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.

答:
EDIT...

OK. Now I belive that I know where is your problem...
You have problems with program units finalization!

Try to add at program section as first unit my bottom  RestartMutex unit.

```<code>program MyProgramName;
uses
  Mutex,
  Forms,
...
</code>```

;

```<code>unit RestartMutex;
interface

var
  Restart: boolean = false;

implementation

uses
  windows,
  ShellApi;

var
  MutexHandle: cardinal;
  AppName: PChar;
const
  ID = 'MyProgram';

initialization
  MutexHandle := CreateMutex (nil, False, PChar (ID));
  if (GetLastError = ERROR_ALREADY_EXISTS) then
    Halt;

finalization
  ReleaseMutex(MutexHandle);
  if Restart then
  begin
    AppName := PChar('MyProgramName.exe') ;
    ShellExecute(0,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
  end:
end.
</code>```

When you want to restart application just set variable Restart to true and than terminate an application.

So, because is RestartMutex added as first in program section, this will couse that finalisation of unit RestartMutex will hepped nearly at the end of closing an application and all other units will do finalization before unit RestartMutex, that mean the Application can start safe again!

ContentLicense: CC BY-SA 2.5

Body:
It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;

Now I want to restart my application programmatically. The usual way would be:

AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.

Body:
EDIT...

OK. Now I belive that I know where is your problem...
You have problems with program units finalization!

Try to add at program section as first unit my bottom  RestartMutex unit.

program MyProgramName;
uses
  Mutex,
  Forms,
...

;

unit RestartMutex;
interface

var
  Restart: boolean = false;

implementation

uses
  windows,
  ShellApi;

var
  MutexHandle: cardinal;
  AppName: PChar;
const
  ID = 'MyProgram';

initialization
  MutexHandle := CreateMutex (nil, False, PChar (ID));
  if (GetLastError = ERROR_ALREADY_EXISTS) then
    Halt;

finalization
  ReleaseMutex(MutexHandle);
  if Restart then
  begin
    AppName := PChar('MyProgramName.exe') ;
    ShellExecute(0,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
  end:
end.

When you want to restart application just set variable Restart to true and than terminate an application.

So, because is RestartMutex added as first in program section, this will couse that finalisation of unit RestartMutex will hepped nearly at the end of closing an application and all other units will do finalization before unit RestartMutex, that mean the Application can start safe again!


问:
PHP Warning: Module already loaded in Unknown on line 0
On Mac OSX Mavericks using homebrew php55 whenever I run a a php command I get the following error message (everything runs fine it's just annoying)

```<code>PHP Warning:  Module 'intl' already loaded in Unknown on line 0
</code>```

I ran

```<code>php --ini
</code>```

and the output was

```<code>php --ini
PHP Warning:  Module 'intl' already loaded in Unknown on line 0

Warning: Module 'intl' already loaded in Unknown on line 0
Configuration File (php.ini) Path: /usr/local/etc/php/5.5
Loaded Configuration File:         /usr/local/etc/php/5.5/php.ini
Scan for additional .ini files in: /usr/local/etc/php/5.5/conf.d
Additional .ini files parsed:      /usr/local/etc/php/5.5/conf.d/ext-apcu.ini,
/usr/local/etc/php/5.5/conf.d/ext-igbinary.ini,
/usr/local/etc/php/5.5/conf.d/ext-intl.ini,
/usr/local/etc/php/5.5/conf.d/ext-memcached.ini,
/usr/local/etc/php/5.5/conf.d/ext-mongo.ini,
/usr/local/etc/php/5.5/conf.d/ext-uuid.ini,
/usr/local/etc/php/5.5/conf.d/ext-xdebug.ini
</code>```

Checked in the php.ini file and the only place intl is loaded is at the top and it's commented out. The other files contents look something like:

```<code>extension="/usr/local/Cellar/php55/5.5.23/lib/php/extensions/no-debug-non-zts-20121212/intl.so"
</code>```

where the contents after the last slash is the extension.

I'm not sure where else to look.

Any help is appreciated

答: I deleted the 20-mongo.ini file in /etc/php5/cli/conf.d and this solved the problem.</p>

Body:
On Mac OSX Mavericks using homebrew php55 whenever I run a a php command I get the following error message (everything runs fine it's just annoying)

PHP Warning:  Module 'intl' already loaded in Unknown on line 0

I ran

php --ini

and the output was

php --ini
PHP Warning:  Module 'intl' already loaded in Unknown on line 0

Warning: Module 'intl' already loaded in Unknown on line 0
Configuration File (php.ini) Path: /usr/local/etc/php/5.5
Loaded Configuration File:         /usr/local/etc/php/5.5/php.ini
Scan for additional .ini files in: /usr/local/etc/php/5.5/conf.d
Additional .ini files parsed:      /usr/local/etc/php/5.5/conf.d/ext-apcu.ini,
/usr/local/etc/php/5.5/conf.d/ext-igbinary.ini,
/usr/local/etc/php/5.5/conf.d/ext-intl.ini,
/usr/local/etc/php/5.5/conf.d/ext-memcached.ini,
/usr/local/etc/php/5.5/conf.d/ext-mongo.ini,
/usr/local/etc/php/5.5/conf.d/ext-uuid.ini,
/usr/local/etc/php/5.5/conf.d/ext-xdebug.ini

Checked in the php.ini file and the only place intl is loaded is at the top and it's commented out. The other files contents look something like:

extension="/usr/local/Cellar/php55/5.5.23/lib/php/extensions/no-debug-non-zts-20121212/intl.so"

where the contents after the last slash is the extension.

I'm not sure where else to look.

Any help is appreciated


问:
Spring Security Java Config same url allowed for anonymous user and for others authentication needed
In Spring Security Java Config

```<code>protected void configure(HttpSecurity http) throws Exception {

      http.antMatcher("/guest/**").authenticated;

}
</code>```

What if I want this same url to be allowed access to a particular principal or a User.

And others Authentication needed. Is it possible?

答:
Two approaches; first, use HttpSecurity#not() like this to block anonymous users;

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/guest/**")
            .not().hasRole("ANONYMOUS");
    // more config
}
</code>```

Or use something like ROLE_VIEW_GUEST_PAGES that gets added depending on the user type from your UserDetailsService.  This, IMO gives you better control over who sees guest pages.

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/guest/**")
            .hasRole("VIEW_GUEST_PAGES");
    // more config
}
</code>```

Body:
In Spring Security Java Config

protected void configure(HttpSecurity http) throws Exception {

      http.antMatcher("/guest/**").authenticated;

}

What if I want this same url to be allowed access to a particular principal or a User.

And others Authentication needed. Is it possible?

Body:
Two approaches; first, use HttpSecurity#not() like this to block anonymous users;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/guest/**")
            .not().hasRole("ANONYMOUS");
    // more config
}

Or use something like ROLE_VIEW_GUEST_PAGES that gets added depending on the user type from your UserDetailsService.  This, IMO gives you better control over who sees guest pages.

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/guest/**")
            .hasRole("VIEW_GUEST_PAGES");
    // more config
}


问:
PHP wordpress get a multidimensional array of category objects
am trying to get all the categories on my wordpress as a heirarchial multidimensional array of objects of type category.
There are 2 functions in wordpress that kind of do what I want, but not exactly :

1) get_categories() - This one does return an array of category objects, which is great, but then the array is a flat one, where there is no differentiation between which category is a parent or which one is a child.

2) wp_list_categories() - which can return the categories with the herarchy intact, but problem is that the return value is html, and I need the categories to still be objects.

For example, if I had the following 3 trees as my parent-less categories :

```<code>/*
tree_stump

tree1
    branch1

tree2
    branch2
        twig2
            leaves2
            flowers2
            fruits2
*/
</code>```

I am trying to get a return value which could be something like:

```<code>$cat_tree=array( 1=>$tree_stump,2=>array(1=>$tree1,2=>$branch1),3=>array(1=>$tree2,2=>array(1=>$branch2,2=>array($twig2,$leaves2,$flowers2,$fruits2  ) ) ) );
</code>```

where each member of the multi dim array is still an object, and in all the child arrays, the first one is the parent of the rest of the members. I guess this would need some kinda recursive stuff - the stuff that gives me jitters !

Not sure if I made sense, please do let me know if I need to be more clear..
Thanks for reading.

答:
```<code><?php
$args = array(
    'taxonomy' => 'category',
    'orderby' => 'name',
    'order' => 'ASC',
    'hierarchical'  => true,
    'hide_empty' => false,
);
$the_query = new WP_Term_Query($args);
$categories = $the_query->get_terms();

function get_cat_tree($parent,$categories) {
    $result = array();
    foreach($categories as $category){
        if ($parent == $category->parent) {
            $category->children = get_cat_tree($category->term_id,$categories);
            $result[] = $category;
        }
    }
    return $result;
}
$cats_tree = get_cat_tree(0,$categories);
</code>```

Body:
am trying to get all the categories on my wordpress as a heirarchial multidimensional array of objects of type category.
There are 2 functions in wordpress that kind of do what I want, but not exactly :

1) get_categories() - This one does return an array of category objects, which is great, but then the array is a flat one, where there is no differentiation between which category is a parent or which one is a child.

2) wp_list_categories() - which can return the categories with the herarchy intact, but problem is that the return value is html, and I need the categories to still be objects.

For example, if I had the following 3 trees as my parent-less categories :

/*
tree_stump

tree1
    branch1

tree2
    branch2
        twig2
            leaves2
            flowers2
            fruits2
*/

I am trying to get a return value which could be something like:

$cat_tree=array( 1=>$tree_stump,2=>array(1=>$tree1,2=>$branch1),3=>array(1=>$tree2,2=>array(1=>$branch2,2=>array($twig2,$leaves2,$flowers2,$fruits2  ) ) ) );

where each member of the multi dim array is still an object, and in all the child arrays, the first one is the parent of the rest of the members. I guess this would need some kinda recursive stuff - the stuff that gives me jitters !

Not sure if I made sense, please do let me know if I need to be more clear..
Thanks for reading.


问:
Form is not showing the btn bootstrap class in Laravel Blade
I imported "laravelcollective/html":"^5.4.0" and my form is working fine but I have this issue with the btn bootstrap class, it is not showing at all, but labels, text and textarea are.

```<code>{!!
...

{{ Form::submit('Create Post', null, array('class' => 'btn btn-success btn-lg btn-block')) }}

...
!!}
</code>```

I am using Laravel 5.4.

What am I doing wrong? Thanks.

答: Never mind. I had null as an argument. Working now!

Body:
I imported "laravelcollective/html":"^5.4.0" and my form is working fine but I have this issue with the btn bootstrap class, it is not showing at all, but labels, text and textarea are.

{!!
...

{{ Form::submit('Create Post', null, array('class' => 'btn btn-success btn-lg btn-block')) }}

...
!!}

I am using Laravel 5.4.

What am I doing wrong? Thanks.


问:
ggplot2: boxplot with facet_grid and free scale
I am trying to have free scales on a Boxplot image with faceting.

Using this example dataset, if I try this:

```<code>ggplot(data=mpg) +
geom_boxplot(aes(x=cty, y=model))+
facet_grid(manufacturer ~ drv, scales = "free", space = "free")
</code>```

Plot incorrect boxplot http://dl.dropbox.com/u/9788680/plot1.png

Here, the free scales are implemented exactly as I would like, with the different scales for the y-axis depending on the number of available factors for a horizontal facet rule. The boxplots are however not correctly depicted (i.e. as solid lines instead of boxplots).
When searching for a solution, I found that I should use coord_flip() in order to make the boxplot be depicted correctly, i.e.

```<code>ggplot(data=mpg) +
geom_boxplot(aes(x=model,y=cty))+
facet_grid(manufacturer ~ drv, scales = "free", space = "free")+
coord_flip()
</code>```

Plot correct boxplot, but no scaling http://dl.dropbox.com/u/9788680/plot2.png

In above picture, the boxplots are now correct. However, the free scale for the factors (so on the y-axis) are removed. Now, for each horizontal facet line, ALL the available factors across the dataset are now included, instead of only the factors available for each facet (as in Figure 1).

I would like to know how I can get the correct facetting with a free scale on both axes, correctly depicting the boxplot.

If somebody could point me in the right direction, I would be grateful.

Thanks.

答:
The desired behavior is supported at least as of ggplot2 2.2.1.

library(ggplot2)
ggplot(data=mpg[which(mpg$manufacturer %in% c('audi', 'hyundai', 'jeep')),]) +
  geom_boxplot(aes(x=model,y=cty)) +
  facet_grid(manufacturer ~ drv, scales = "free", space = "free") +
  coord_flip()
```

<p><img src="https://i.imgur.com/jqb0lNA.png" alt=""></p>

<pre class="lang-r prettyprint-override"><code>sessionInfo()
#> R version 3.3.2 (2016-10-31)
#> Platform: x86_64-apple-darwin13.4.0 (64-bit)
#> Running under: OS X El Capitan 10.11.6
#>
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> other attached packages:
#> [1] ggplot2_2.2.1
#>
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_0.12.11         digest_0.6.12        rprojroot_1.2
#>  [4] plyr_1.8.4           grid_3.3.2           gtable_0.2.0
#>  [7] backports_1.0.5      magrittr_1.5         evaluate_0.10.1
#> [10] scales_0.4.1.9002    rlang_0.1.1.9000     stringi_1.1.5
#> [13] reshape2_1.4.2       lazyeval_0.2.0       rmarkdown_1.6.0.9001
#> [16] labeling_0.3         tools_3.3.2          stringr_1.2.0
#> [19] munsell_0.4.3        yaml_2.1.14          colorspace_1.3-2
#> [22] htmltools_0.3.6      knitr_1.16           tibble_1.3.3
</code>```

Body:
I am trying to have free scales on a Boxplot image with faceting.

Using this example dataset, if I try this:

ggplot(data=mpg) +
geom_boxplot(aes(x=cty, y=model))+
facet_grid(manufacturer ~ drv, scales = "free", space = "free")

Plot incorrect boxplot http://dl.dropbox.com/u/9788680/plot1.png

Here, the free scales are implemented exactly as I would like, with the different scales for the y-axis depending on the number of available factors for a horizontal facet rule. The boxplots are however not correctly depicted (i.e. as solid lines instead of boxplots).
When searching for a solution, I found that I should use coord_flip() in order to make the boxplot be depicted correctly, i.e.

ggplot(data=mpg) +
geom_boxplot(aes(x=model,y=cty))+
facet_grid(manufacturer ~ drv, scales = "free", space = "free")+
coord_flip()

Plot correct boxplot, but no scaling http://dl.dropbox.com/u/9788680/plot2.png

In above picture, the boxplots are now correct. However, the free scale for the factors (so on the y-axis) are removed. Now, for each horizontal facet line, ALL the available factors across the dataset are now included, instead of only the factors available for each facet (as in Figure 1).

I would like to know how I can get the correct facetting with a free scale on both axes, correctly depicting the boxplot.

If somebody could point me in the right direction, I would be grateful.

Thanks.

Body:
The desired behavior is supported at least as of ggplot2 2.2.1.

library(ggplot2)
ggplot(data=mpg[which(mpg$manufacturer %in% c('audi', 'hyundai', 'jeep')),]) +
  geom_boxplot(aes(x=model,y=cty)) +
  facet_grid(manufacturer ~ drv, scales = "free", space = "free") +
  coord_flip()

sessionInfo()
#> R version 3.3.2 (2016-10-31)
#> Platform: x86_64-apple-darwin13.4.0 (64-bit)
#> Running under: OS X El Capitan 10.11.6
#>
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> other attached packages:
#> [1] ggplot2_2.2.1
#>
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_0.12.11         digest_0.6.12        rprojroot_1.2
#>  [4] plyr_1.8.4           grid_3.3.2           gtable_0.2.0
#>  [7] backports_1.0.5      magrittr_1.5         evaluate_0.10.1
#> [10] scales_0.4.1.9002    rlang_0.1.1.9000     stringi_1.1.5
#> [13] reshape2_1.4.2       lazyeval_0.2.0       rmarkdown_1.6.0.9001
#> [16] labeling_0.3         tools_3.3.2          stringr_1.2.0
#> [19] munsell_0.4.3        yaml_2.1.14          colorspace_1.3-2
#> [22] htmltools_0.3.6      knitr_1.16           tibble_1.3.3


问:
Node js express static not receiving post response on the client side
Hi guys i'm from mobile development and trying to know more about the node js runtime, so i've already a simple "app" js client-side and i'am trying to use it with the node js express server.

For my purpose i've used a static file because all my html it's generated by js with DOM.

The problem:

When i'm doing a post with ajax to store values in the DB it's always redirects me to the index.html and do not execute my client-side callback code to create the table.

app.js

```<code>let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');

let index = require('./routes/index');
let cups = require('./routes/route-cup');
let leagues = require('./routes/route-league');
let players = require('./routes/route-player');
let teams = require('./routes/route-team');

let app = express();

app.use(favicon(path.join(__dirname, 'public', '/images/favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());

app.use('/cups', cups);
app.use('/leagues', leagues);
app.use('/players', players);
app.use('/teams', teams);
app.use(express.static("public", {
    "index": "index.html"
}));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
</code>```

route:

```<code>let express = require('express');
let router = express.Router();
let mysql = require("mysql");
let executeSql = require("../scripts/execute-sql");

router.get('/', function (req, res, next) {
    executeSql.executeSelect(res, function (rows, fields) {
        res.json(rows);
    }, "SELECT * FROM `footTour-sgbd`.player;")
});

router.post('/submit-player', function (req, res, next) {
    let obj = req.body;
    let keys = Object.keys(obj);
    let placeHolders = new Array(keys.length).fill("?");
    let values = Object.keys(obj).map(key => obj[key]);
    let sql = "INSERT INTO `footTour-sgbd`.`player` (" + keys.toString() + ") VALUES (" + placeHolders.toString() + ")";

    sql = mysql.format(sql, values);
    executeSql.executeSelect(res, function (rows, fields) {
        // res.json(rows);
        res.end('{"success" : "Updated Successfully", "status" : 200}');

    }, sql);
});

module.exports = router;
</code>```

js client-side request:

```<code> let formPlayer = createForm(formName, formName);
    formPlayer.addEventListener("submit", function (response) {

        let playerName = document.getElementById("name").value;
        let playerHeight = document.getElementById("height").value;
        let playerBirthdate = document.getElementById("birthDate").value;
        let playerCountry = document.getElementById("countryEnum").value;
        let playerPosition = document.getElementById("positionTypeEnum").value;

        // let player = formToJson(formPlayer);
        let player = new Player(playerName, playerBirthdate, playerCountry, playerHeight, playerPosition)
        insertPlayer(
            function (response) {
                createPlayersTable();

            }, function (status, response) {

                showSnackBar(`Error creating player (${status})`, 3000);
                createPlayersTable();
            }, player);
    });

function insertPlayer(onSuccess, onError, data) {

    ajaxHelper("/players/submit-player", onSuccess, onError, "POST", data);
}

function ajaxHelper(url, onSuccess, onError, verb, data) {
    verb = verb || "GET";
    let xhr = new XMLHttpRequest();
    xhr.open(verb, url);
    xhr.responseType = "json";
    xhr.addEventListener("load", function () {
        if (this.status === 200) {
            onSuccess && onSuccess(xhr.response);
        } else {
            onError && onError(this.status, xhr.response);
        }
    });
    if (data) {
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.send(JSON.stringify(data));
    } else {
        xhr.send();
    }
}
</code>```

答:
try to add preventDefault() in a form EventListener:</p>

```<code>formPlayer.addEventListener("submit", function (evt) {
    evt.preventDefault(); //<-- THIS

    let playerName = document.getElementById("name").value;
    let playerHeight = document.getElementById("height").value;
    let playerBirthdate = document.getElementById("birthDate").value;
    let playerCountry = document.getElementById("countryEnum").value;
    let playerPosition = document.getElementById("positionTypeEnum").value;

    // let player = formToJson(formPlayer);
    let player = new Player(playerName, playerBirthdate, playerCountry, playerHeight, playerPosition)
    insertPlayer(
        function (response) {
            createPlayersTable();

        }, function (status, response) {

            showSnackBar(`Error creating player (${status})`, 3000);
            createPlayersTable();
        }, player);
});
</code>```

Body:
Hi guys i'm from mobile development and trying to know more about the node js runtime, so i've already a simple "app" js client-side and i'am trying to use it with the node js express server.

For my purpose i've used a static file because all my html it's generated by js with DOM.

The problem:

When i'm doing a post with ajax to store values in the DB it's always redirects me to the index.html and do not execute my client-side callback code to create the table.

app.js

let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');

let index = require('./routes/index');
let cups = require('./routes/route-cup');
let leagues = require('./routes/route-league');
let players = require('./routes/route-player');
let teams = require('./routes/route-team');

let app = express();

app.use(favicon(path.join(__dirname, 'public', '/images/favicon.png')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());

app.use('/cups', cups);
app.use('/leagues', leagues);
app.use('/players', players);
app.use('/teams', teams);
app.use(express.static("public", {
    "index": "index.html"
}));

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;

route:

let express = require('express');
let router = express.Router();
let mysql = require("mysql");
let executeSql = require("../scripts/execute-sql");

router.get('/', function (req, res, next) {
    executeSql.executeSelect(res, function (rows, fields) {
        res.json(rows);
    }, "SELECT * FROM `footTour-sgbd`.player;")
});

router.post('/submit-player', function (req, res, next) {
    let obj = req.body;
    let keys = Object.keys(obj);
    let placeHolders = new Array(keys.length).fill("?");
    let values = Object.keys(obj).map(key => obj[key]);
    let sql = "INSERT INTO `footTour-sgbd`.`player` (" + keys.toString() + ") VALUES (" + placeHolders.toString() + ")";

    sql = mysql.format(sql, values);
    executeSql.executeSelect(res, function (rows, fields) {
        // res.json(rows);
        res.end('{"success" : "Updated Successfully", "status" : 200}');

    }, sql);
});

module.exports = router;

js client-side request:

 let formPlayer = createForm(formName, formName);
    formPlayer.addEventListener("submit", function (response) {

        let playerName = document.getElementById("name").value;
        let playerHeight = document.getElementById("height").value;
        let playerBirthdate = document.getElementById("birthDate").value;
        let playerCountry = document.getElementById("countryEnum").value;
        let playerPosition = document.getElementById("positionTypeEnum").value;

        // let player = formToJson(formPlayer);
        let player = new Player(playerName, playerBirthdate, playerCountry, playerHeight, playerPosition)
        insertPlayer(
            function (response) {
                createPlayersTable();

            }, function (status, response) {

                showSnackBar(`Error creating player (${status})`, 3000);
                createPlayersTable();
            }, player);
    });

function insertPlayer(onSuccess, onError, data) {

    ajaxHelper("/players/submit-player", onSuccess, onError, "POST", data);
}

function ajaxHelper(url, onSuccess, onError, verb, data) {
    verb = verb || "GET";
    let xhr = new XMLHttpRequest();
    xhr.open(verb, url);
    xhr.responseType = "json";
    xhr.addEventListener("load", function () {
        if (this.status === 200) {
            onSuccess && onSuccess(xhr.response);
        } else {
            onError && onError(this.status, xhr.response);
        }
    });
    if (data) {
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.send(JSON.stringify(data));
    } else {
        xhr.send();
    }
}

Body:
try to add preventDefault() in a form EventListener:

formPlayer.addEventListener("submit", function (evt) {
    evt.preventDefault(); //<-- THIS

    let playerName = document.getElementById("name").value;
    let playerHeight = document.getElementById("height").value;
    let playerBirthdate = document.getElementById("birthDate").value;
    let playerCountry = document.getElementById("countryEnum").value;
    let playerPosition = document.getElementById("positionTypeEnum").value;

    // let player = formToJson(formPlayer);
    let player = new Player(playerName, playerBirthdate, playerCountry, playerHeight, playerPosition)
    insertPlayer(
        function (response) {
            createPlayersTable();

        }, function (status, response) {

            showSnackBar(`Error creating player (${status})`, 3000);
            createPlayersTable();
        }, player);
});


问:
How do you fix a MySQL "Incorrect key file" error when you can't repair the table?
I'm trying to run a rather large query that is supposed to run nightly to populate a table.  I'm getting an error saying Incorrect key file for table '/var/tmp/#sql_201e_0.MYI'; try to repair it but the storage engine I'm using (whatever the default is, I guess?) doesn't support repairing tables.

how do I fix this so I can run the query?

答:
REPAIR TABLE tbl_name USE_FRM;

Command only run when MySQL 'Storage Engine' type should be 'MyISAM'

Hope this helps


问:
Library for polynomial calculus in Java?
Are there any (preferably open source) library for Java that allows one to do calculus with polynomial e.g. addition, multiplying, dividing by constans etc. ?

Also if it would be capable to interpolate several 2D points in a polynomial with Lagrange polynomial interpolation, it will be a plus.

答:
The following library could be of interest, if one would be interested in a more CAS like approach to polynomials in Java:

Java Algebra System (JAS) Project

http://krum.rz.uni-mannheim.de/jas/


问:
When I delete an item from the database and updatethe datagrid, I still see this object
I have two windows wpf.
On the first window I see data from DataGrid, on the second window I delete object from database.

First window:

```<code>private void mnRemoveProduct_Click(object sender, RoutedEventArgs e)
{
   RemoveProduct window = new RemoveProduct();
   window.ShowDialog();
   ShowWatchTable();
} // mnRemoveProduct_Click
</code>```

Second window:

```<code>private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (cmbNameOfWatch.SelectedIndex > 0)
    {
        var value =
            (from watch in obj.Watch.Where(w => w.mark == cmbNameOfWatch.SelectedValue.ToString())
             select new { watch.id }).ToArray().First();

        Watch watchObj = obj.Watch.Find(value.id);
        obj.Watch.Remove(watchObj);
        obj.SaveChanges();

        this.Close();
    }
} // btnDelete_Click
</code>```

and function ShowTable

```<code>public void ShowWatchTable()
{
    obj.Watch.ToList();
    dataGrid.ItemsSource =
        from watch in obj.Watch.Local
        select new
        {
            ID = watch.id,
            Brand = watch.mark,
            Typ = watch.TypeWatch.typeName,
            Price = watch.price + " $".ToString(),
            Quantity = watch.number,
            Fabricator = watch.Fabricator.fName,
            Country = watch.Fabricator.Country.countryName
        };
}
</code>```

When I delete value from database, I still see this value in DataGrid. Only when I close and open this form then I no longer see this object. When I add an element, the same logic is used. Datagrid is updated with the ShowTable function and I see the updated database. But when deleting it it does not work. Please help

答:
You should make sure the collection backing the source of your data items implements INotifyCollectionChanged.

MSDN link to docs, also copied relevant section here.

Binding to Data

To bind the DataGrid to data, set the ItemsSource property to an IEnumerable implementation. Each row in the data grid is bound to an object in the data source, and each column in the data grid is bound to a property of the data object. In order for the DataGrid user interface to update automatically when items are added to or removed from the source data, the DataGrid must be bound to a collection that implements the INotifyCollectionChanged interface, such as an ObservableCollection. To automatically reflect property changes, the objects in the source collection must implement the INotifyPropertyChanged interface. For more information, see Data Binding (WPF).

Body:
I have two windows wpf.
On the first window I see data from DataGrid, on the second window I delete object from database.

First window:

private void mnRemoveProduct_Click(object sender, RoutedEventArgs e)
{
   RemoveProduct window = new RemoveProduct();
   window.ShowDialog();
   ShowWatchTable();
} // mnRemoveProduct_Click

Second window:

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    if (cmbNameOfWatch.SelectedIndex > 0)
    {
        var value =
            (from watch in obj.Watch.Where(w => w.mark == cmbNameOfWatch.SelectedValue.ToString())
             select new { watch.id }).ToArray().First();

        Watch watchObj = obj.Watch.Find(value.id);
        obj.Watch.Remove(watchObj);
        obj.SaveChanges();

        this.Close();
    }
} // btnDelete_Click

and function ShowTable

public void ShowWatchTable()
{
    obj.Watch.ToList();
    dataGrid.ItemsSource =
        from watch in obj.Watch.Local
        select new
        {
            ID = watch.id,
            Brand = watch.mark,
            Typ = watch.TypeWatch.typeName,
            Price = watch.price + " $".ToString(),
            Quantity = watch.number,
            Fabricator = watch.Fabricator.fName,
            Country = watch.Fabricator.Country.countryName
        };
}

When I delete value from database, I still see this value in DataGrid. Only when I close and open this form then I no longer see this object. When I add an element, the same logic is used. Datagrid is updated with the ShowTable function and I see the updated database. But when deleting it it does not work. Please help


问:
how to get 1000 number of records in phpmyadmin ui
[how to see after 500 records in phpmyadmin user interface.if any one give answer][1][1]: https://i.stack.imgur.com/Ktk6Y.png</p>

答: There is a Show all rows option also provided in phpmyadmin you can see that from, the first where you click on dropdown of per page record show.


问:
How to call protected function?
How to call function lmn() without touching class B from class A

```<code> class A extends B{
     public function abc(){
         return "abc";
     }
     ...
 }

 class B{
     public function xyz(){
         return "xyz";
     }
     ...
 }

 class C{
     protected function lmn(){
         return "lmn";
     }
     ...
 }
</code>```

please guide me for this

答:
You can make some kind of proxy class that extends from C and provides a public method for access:</p>

```<code>class ProcyForC extends C {
  public function getLmn() {
    return $this->lmn();
  }
}

echo (new ProxyForC())->getLmn();
</code>```

Title: How to call protected function?

Body:
How to call function lmn() without touching class B from class A

 class A extends B{
     public function abc(){
         return "abc";
     }
     ...
 }

 class B{
     public function xyz(){
         return "xyz";
     }
     ...
 }

 class C{
     protected function lmn(){
         return "lmn";
     }
     ...
 }

please guide me for this

Body:
You can make some kind of proxy class that extends from C and provides a public method for access:

class ProcyForC extends C {
  public function getLmn() {
    return $this->lmn();
  }
}

echo (new ProxyForC())->getLmn();


答:
Look well you have an inner array productStock in the object you are looping,so the way you are looping won't never work.

Assuming you have something in controller initialization-

```<code>$scope.products = [];

Service.getData().then(function(response){
       $scope.products = response;
});
</code>```

In html part introduce another ng-repeat to loop all stocks

```<code><div ng-repeat="product in products">
   <p>{{product.randomId}}</p>
   <p>{{product.os.od}}</p>
   <p>{{product.otherProductAttributes.l}}</p>
    <div ng-repeat="pstock in product.productStock">
        <p>{{pstock.size}} </p>
        <p>{{pstock.imagePaths}}</p>
   </div>
</div>
</code>```

Title: unable to loop through array using ng-repeat

Body:
Look well you have an inner array productStock in the object you are looping,so the way you are looping won't never work.

Assuming you have something in controller initialization-

$scope.products = [];

Service.getData().then(function(response){
       $scope.products = response;
});

In html part introduce another ng-repeat to loop all stocks

<div ng-repeat="product in products">
   <p>{{product.randomId}}</p>
   <p>{{product.os.od}}</p>
   <p>{{product.otherProductAttributes.l}}</p>
    <div ng-repeat="pstock in product.productStock">
        <p>{{pstock.size}} </p>
        <p>{{pstock.imagePaths}}</p>
   </div>
</div>


问:
How to calculate weight to minimize variance?
given several vectors:

```<code>x1 = [3 4 6]
x2 = [2 8 1]
x3 = [5 5 4]
x4 = [6 2 1]
</code>```

I wanna find weight w1, w2, w3 to each item, and get the weighted sum of each vector: yi = w1*i1 + w2*i2 + w3*i3. for example, y1 = 3*w1 + 4*w2 + 6*w3
to make the variance of these values(y1, y2, y3, y4) to be minimized.

notice: w1, w2, w3 should > 0, and w1 + w2 + w3 = 1

I don't know what kind of problems it should be... and how to solve it in python or matlab?

答:
My full solution can be viewed in PDF.

The trick is to put the vectors x_i as columns of a matrix X.

Then writing the problem becomes a Convex Problem with constrain of the solution to be on the Unit Simplex.

I solved it using Projected Sub Gradient Method.

I calculated the Gradient of the objective function and created a projection to the Unit Simplex.

Now all needed is to iterate them.

I validated my solution using CVX.

```<code>% StackOverflow 44984132
% How to calculate weight to minimize variance?
% Remarks:
%   1.  sa
% TODO:
%   1.  ds
% Release Notes
% - 1.0.000     08/07/2017
%   *   First release.

%% General Parameters

run('InitScript.m');

figureIdx           = 0; %<! Continue from Question 1
figureCounterSpec   = '%04d';

generateFigures = OFF;

%% Simulation Parameters

dimOrder    = 3;
numSamples = 4;

mX = randi([1, 10], [dimOrder, numSamples]);
vE = ones([dimOrder, 1]);

%% Solve Using CVX

cvx_begin('quiet')
    cvx_precision('best');
    variable vW(numSamples)
    minimize( (0.5 * sum_square_abs( mX * vW - (1 / numSamples) * (vE.' * mX * vW) * vE )) )
    subject to
        sum(vW) == 1;
        vW >= 0;
cvx_end

disp([' ']);
disp(['CVX Solution -                       [ ', num2str(vW.'), ' ]']);

%% Solve Using Projected Sub Gradient

numIterations   = 20000;
stepSize        = 0.001;
simplexRadius   = 1; %<! Unit Simplex Radius
stopThr         = 1e-6;

hKernelFun  = @(vW) ((mX * vW) - ((1 / numSamples) * ((vE.' * mX * vW) * vE)));
hObjFun     = @(vW) 0.5 * sum(hKernelFun(vW) .^ 2);
hGradFun    = @(vW) (mX.' * hKernelFun(vW)) - ((1 / numSamples) * vE.' * (hKernelFun(vW)) * mX.' * vE);

vW = rand([numSamples, 1]);
vW = vW(:) / sum(vW);

for ii = 1:numIterations
    vGradW = hGradFun(vW);
    vW = vW - (stepSize * vGradW);

    % Projecting onto the Unit Simplex
    % sum(vW) == 1, vW >= 0.
    vW = ProjectSimplex(vW, simplexRadius, stopThr);
end

disp([' ']);
disp(['Projected Sub Gradient Solution -    [ ', num2str(vW.'), ' ]']);

%% Restore Defaults

% set(0, 'DefaultFigureWindowStyle', 'normal');
% set(0, 'DefaultAxesLooseInset', defaultLoosInset);
</code>```

You can see the full code in StackOverflow Q44984132 (PDF is available as well).

Body:
given several vectors:

x1 = [3 4 6]
x2 = [2 8 1]
x3 = [5 5 4]
x4 = [6 2 1]

I wanna find weight w1, w2, w3 to each item, and get the weighted sum of each vector: yi = w1*i1 + w2*i2 + w3*i3. for example, y1 = 3*w1 + 4*w2 + 6*w3
to make the variance of these values(y1, y2, y3, y4) to be minimized.

notice: w1, w2, w3 should > 0, and w1 + w2 + w3 = 1

I don't know what kind of problems it should be... and how to solve it in python or matlab?

Body:
My full solution can be viewed in PDF.

The trick is to put the vectors x_i as columns of a matrix X.

Then writing the problem becomes a Convex Problem with constrain of the solution to be on the Unit Simplex.

I solved it using Projected Sub Gradient Method.

I calculated the Gradient of the objective function and created a projection to the Unit Simplex.

Now all needed is to iterate them.

I validated my solution using CVX.

% StackOverflow 44984132
% How to calculate weight to minimize variance?
% Remarks:
%   1.  sa
% TODO:
%   1.  ds
% Release Notes
% - 1.0.000     08/07/2017
%   *   First release.

%% General Parameters

run('InitScript.m');

figureIdx           = 0; %<! Continue from Question 1
figureCounterSpec   = '%04d';

generateFigures = OFF;

%% Simulation Parameters

dimOrder    = 3;
numSamples = 4;

mX = randi([1, 10], [dimOrder, numSamples]);
vE = ones([dimOrder, 1]);

%% Solve Using CVX

cvx_begin('quiet')
    cvx_precision('best');
    variable vW(numSamples)
    minimize( (0.5 * sum_square_abs( mX * vW - (1 / numSamples) * (vE.' * mX * vW) * vE )) )
    subject to
        sum(vW) == 1;
        vW >= 0;
cvx_end

disp([' ']);
disp(['CVX Solution -                       [ ', num2str(vW.'), ' ]']);

%% Solve Using Projected Sub Gradient

numIterations   = 20000;
stepSize        = 0.001;
simplexRadius   = 1; %<! Unit Simplex Radius
stopThr         = 1e-6;

hKernelFun  = @(vW) ((mX * vW) - ((1 / numSamples) * ((vE.' * mX * vW) * vE)));
hObjFun     = @(vW) 0.5 * sum(hKernelFun(vW) .^ 2);
hGradFun    = @(vW) (mX.' * hKernelFun(vW)) - ((1 / numSamples) * vE.' * (hKernelFun(vW)) * mX.' * vE);

vW = rand([numSamples, 1]);
vW = vW(:) / sum(vW);

for ii = 1:numIterations
    vGradW = hGradFun(vW);
    vW = vW - (stepSize * vGradW);

    % Projecting onto the Unit Simplex
    % sum(vW) == 1, vW >= 0.
    vW = ProjectSimplex(vW, simplexRadius, stopThr);
end

disp([' ']);
disp(['Projected Sub Gradient Solution -    [ ', num2str(vW.'), ' ]']);

%% Restore Defaults

% set(0, 'DefaultFigureWindowStyle', 'normal');
% set(0, 'DefaultAxesLooseInset', defaultLoosInset);

You can see the full code in StackOverflow Q44984132 (PDF is available as well).


答:
You have to use one more ng-repeat since productStock is an array of objects

```<code> <div class="row">
    <div ng-repeat="product in products">
        <p>{{product.randomId}}</p>
        <p>{{product.os.od}}</p>
        <p>{{product.otherProductAttributes.l}}</p>
        <div ng-repeat="value in product.productStock">
            <p>{{value.size}} </p>
            <div ng-repeat="image in value.imagePaths">
                <img ng-src="{{image}}">
            </div>
        </div>
    </div>
</div>
</code>```

Body:
I am using Angular to consume nodejs web-service.

But I am unable to loop through the data.

Json Data:

  [
  {
    "_id": "595fbe940eaeda0b387568fc",
    "randomId": "0001",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 28,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fbe940eaeda0b387568ff",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 28,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fbe940eaeda0b387568fe",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fbe940eaeda0b387568fd",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  },
  {
    "_id": "595fc0b60eaeda0b38756900",
    "randomId": "0002",
    "sName": "xyz abc",
    "des": "A wide variety of xyz abc",
    "__v": 0,
    "os": {
      "od": "2017-07-06T18:30:00.000Z",
      "ok": "2017-07-06T18:30:00.000Z",
      "dp": 10
    },
    "otherProductAttributes": {
      "l": "23",
      "mt": "fabricType"
    },
    "productStock": [
      {
        "size": 38,
        "color": "Red",
        "quantity": "120",
        "inStock": "true",
        "price": 234.56,
        "_id": "595fc0b60eaeda0b38756903",
        "imagePaths": [
          "https://image.jpg",
          "https://image.jpg",
          "https://image.jpg"
        ]
      },
      {
        "size": 26,
        "color": "Black",
        "quantity": "10",
        "inStock": "true",
        "price": 89,
        "_id": "595fc0b60eaeda0b38756902",
        "imagePaths": [
          "https://image.jpg"
        ]
      },
      {
        "size": 30,
        "color": "Red",
        "quantity": "999",
        "inStock": "true",
        "price": 999.99,
        "_id": "595fc0b60eaeda0b38756901",
        "imagePaths": [
          "https://image.jpg"
        ]
      }
    ],
    "uploadDate": "2017-07-06T18:30:00.000Z"
  }
]

HTML Page

Products

{{product.randomId}}

{{product.os.od}}

{{product.otherProductAttributes.l}}

{{prooduct.productStock.size}}

{{prooduct.productStock.imagePaths}}

I am trying to access above mentioned data fields, but html page is rendering nothing.

I printed products array on console, and it's printing entire array.So I HTML page is having data but it's not rendering according to my requirements.

Please help.

Body:
You have to use one more ng-repeat since productStock is an array of objects

 <div class="row">
    <div ng-repeat="product in products">
        <p>{{product.randomId}}</p>
        <p>{{product.os.od}}</p>
        <p>{{product.otherProductAttributes.l}}</p>
        <div ng-repeat="value in product.productStock">
            <p>{{value.size}} </p>
            <div ng-repeat="image in value.imagePaths">
                <img ng-src="{{image}}">
            </div>
        </div>
    </div>
</div>


问:
Rewrite base domain to index.php
I'm trying to create a dynamic system on my PHP project and this is what my .htaccess looks like:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^pages/?$ resources/pages/page.php [NC,L]
    RewriteRule ^([A-Za-z0-9-]+)?$ resources/pages/post-or-category.php?tcs=$1 [NC,L]
</IfModule>
</code>```

/pages/ and dynamic post or category page works but the second rule redirects all if the above doesn't redirect. Since it's a PHP script for getting posts and categories, I don't want to make index check on that. Is there a way to rewrite if there is nothing on the domain (ex: www.domain.com or domain.com).

Also, I distinguish posts and categories in the script with the last world on URL (ex: P435345 for posts, C935943 for categories [numbers are id's]). Is it possible to check if URL's last word starts with P or C in .htaccess to redirect other URL's to 404?

答:
Use directives RewriteCond before RewriteRule as this will not redirect if any file or directory exists. For eg. It will not redirect domain.com/index.php to resources/pages/post-or-category.php

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
</code>```

Title: Rewrite base domain to index.php

Body:
I'm trying to create a dynamic system on my PHP project and this is what my .htaccess looks like:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^pages/?$ resources/pages/page.php [NC,L]
    RewriteRule ^([A-Za-z0-9-]+)?$ resources/pages/post-or-category.php?tcs=$1 [NC,L]
</IfModule>

/pages/ and dynamic post or category page works but the second rule redirects all if the above doesn't redirect. Since it's a PHP script for getting posts and categories, I don't want to make index check on that. Is there a way to rewrite if there is nothing on the domain (ex: www.domain.com or domain.com).

Also, I distinguish posts and categories in the script with the last world on URL (ex: P435345 for posts, C935943 for categories [numbers are id's]). Is it possible to check if URL's last word starts with P or C in .htaccess to redirect other URL's to 404?

Body:
Use directives RewriteCond before RewriteRule as this will not redirect if any file or directory exists. For eg. It will not redirect domain.com/index.php to resources/pages/post-or-category.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d


问:
How to implement multiple screens within an App
I am currently working on an Android App which has different service dimensions, such as " service order", "route planning", "photo gallery" and a central login.
so far i implemented each "screen" (and by screen i mean actually the layout of a screen) as a seperate class, which loads a specific layout and handles all listeners and core functionalities such as calling webservices in a thread, receiving answers etc.
I am not quite sure if this is the best way to implemnt mulitiple layout-screens.

The Android dev guideline proposes to use single activities for each "screen layout". However I doubt that this is the most effective way of doing things. Since i need information for each "layout" which are retrieved by the central login (here: a  user object). Since an activity (as far as i understand) is a seperate thread, the passing and retrieving of information seems not very practical.

I would like to get your oppinions/feedback on that and thanks for any hint or tip.

So far my structure looks like :

Activity

loads login layout (res/layout/login.xml with setlContentView)

depending on buttonclick other resources are loaded and initialized (means listeners are added etc.)

Greets
 Peter

答: Don't know if this would be suitable for your app, but another option could be to split off the core data handling into a Service, and have your app be just a UI frontend which communicates with that service.</p>


问:
How to output simple wikipedia row data?
I am doing this:

```<code><div id="results">
  <ul></ul>
</div>
</code>```

JS

```<code>  jQuery.getJSON("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&list=search&format=json&rvsection=0&srsearch=World_War_II&rvparse",
  function(data, item) {
      jQuery("#results ul").append("<li>" + item.title + "</li>");
  });
</code>```

That gives me No 'Access-Control-Allow-Origin so i tried using jsonp but I get the same error.

I would like to retrieve the whole data just as if I clicked on

https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=World_War_II&rvsection=0&rvparse

Here it is the jsFiddle

答:
Check out the Wikipedia api document.
http://en.wikipedia.org/w/api.php</p>

Body:
I am doing this:

JS

  jQuery.getJSON("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&list=search&format=json&rvsection=0&srsearch=World_War_II&rvparse",
  function(data, item) {
      jQuery("#results ul").append("
" + item.title + "
");
  });

That gives me No 'Access-Control-Allow-Origin so i tried using jsonp but I get the same error.

I would like to retrieve the whole data just as if I clicked on

https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=World_War_II&rvsection=0&rvparse

Here it is the jsFiddle


问:
Avoiding exhausting GPU resources in convNN Tensorflow
I'm trying to run a hyperparameter optimization  script, for a convNN using Tensorflow.
As you may know, TF handling of the GPU-Memory isn't that fancy(don't think it will ever be, thanks to the TPU). So my question is how do I know to choose the filter dimensions and the batchsize, so that the GPU-memory don't get exhausted.
Here's the equation that I'm thinking of:

```<code>image_shape =128x128x3(3 color channel)
batchSitze  = 20 ( is the smallest possible batchsize, since I got 20 klasses)
filter_shape= fw_fh_fd[filter_width=4, filter_height=4, filter_depth=32]
</code>```

As far as understood, using tf.conv2d function will need the following amount of memory:

```<code>image_width * image_height *numerofchannel*batchSize*filter_height*filter_width*filter_depth*32bit
</code>```

since we're tf.float32 type  for each pixel.
in the given example, the needed memory, will be :
128x128x3x20x4x4x32x32 =16106127360  (bits), which is all most 16GB of memory.

I'm not the formula is correct, so I hope to get a validation or the a correction of what I'm missing.

答:
Actually, this will take only about 44MB of memory, mostly taken by the output.

Your input is 20x128x128x3

The convolution kernel is 4x4x3x32

The output is 20x128x128x32

When you sum up the total, you get

```<code>(20*128*128*3 + 4*4*3*32 + 20*128*128*32) * 4 / 1024**2 ≈ 44MB
</code>```

(In the above, 4 is for the size in bytes of float32 and 1024**2 is to get the result in MB).

Your batch size can be smaller than your number of classes. Think about ImageNet and its 1000 classes: people are training with batch sizes 10 times smaller.

EDIT

Here is a tensorboard screenshot of the net — it reports 40MB rather than 44MB, probably because it excludes the input — and you also have all the tensor sizes I mentioned earlier.

Body:
I'm trying to run a hyperparameter optimization  script, for a convNN using Tensorflow.
As you may know, TF handling of the GPU-Memory isn't that fancy(don't think it will ever be, thanks to the TPU). So my question is how do I know to choose the filter dimensions and the batchsize, so that the GPU-memory don't get exhausted.
Here's the equation that I'm thinking of:

image_shape =128x128x3(3 color channel)
batchSitze  = 20 ( is the smallest possible batchsize, since I got 20 klasses)
filter_shape= fw_fh_fd[filter_width=4, filter_height=4, filter_depth=32]

As far as understood, using tf.conv2d function will need the following amount of memory:

image_width * image_height *numerofchannel*batchSize*filter_height*filter_width*filter_depth*32bit

since we're tf.float32 type  for each pixel.
in the given example, the needed memory, will be :
128x128x3x20x4x4x32x32 =16106127360  (bits), which is all most 16GB of memory.

I'm not the formula is correct, so I hope to get a validation or the a correction of what I'm missing.

Body:
Actually, this will take only about 44MB of memory, mostly taken by the output.

Your input is 20x128x128x3

The convolution kernel is 4x4x3x32

The output is 20x128x128x32

When you sum up the total, you get

(20*128*128*3 + 4*4*3*32 + 20*128*128*32) * 4 / 1024**2 ≈ 44MB

(In the above, 4 is for the size in bytes of float32 and 1024**2 is to get the result in MB).

Your batch size can be smaller than your number of classes. Think about ImageNet and its 1000 classes: people are training with batch sizes 10 times smaller.

EDIT

Here is a tensorboard screenshot of the net — it reports 40MB rather than 44MB, probably because it excludes the input — and you also have all the tensor sizes I mentioned earlier.