问:
How to get the select value into the controller
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<h3>Hello</h3>
<div ng-controller='calcCtrl' >
Number 1::<input Type="text" name="number1" ng-model="n1"/ required> <br/>
Number 2::<input Type="text" name="number2" ng-model="n2"/ required> <br/>
operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select></p> <br/>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>
</div>
  </body>
</html></code>```

So, The output I get is -

```<code>calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0
</code>```

the operator values are undefined here..

答:
You can use $scope variables directly instead of using extra variables for that. Then there will be no need to take them as parameters. And add value to all options in select.

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    var ans = 0;
    $scope.singleSelect = "+";             // + will be selected by default
    $scope.calculateNums = function() {    // no parameters required
        console.log($scope.n1);
        console.log($scope.n2);
        console.log($scope.singleSelect);
        if ($scope.singleSelect == "+") {
            ans = (parseInt($scope.n1) + parseInt($scope.n2));
        } else if ($scope.singleSelect == "-") {
            ans = (parseInt($scope.n1) - parseInt($scope.n2));
        } else if ($scope.singleSelect == "*") {
            ans = (parseInt($scope.n1) * parseInt($scope.n2));
        } else if ($scope.singleSelect == "/") {
            ans = (parseInt($scope.n1) / parseInt($scope.n2));
        }
        console.log(ans);
        return ans;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="myApp">

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="app.js"></script>
</head>

<body>
    <h3>Hello</h3>
    <div ng-controller='calcCtrl'>
        Number 1::
        <input Type="text" name="number1" ng-model="n1" / required>
        <br/> Number 2::
        <input Type="text" name="number2" ng-model="n2" / required>
        <br/> operator::
        <select ng-model="singleSelect">
            <option value="+">+</option>
            <option value="*">*</option>
            <option value="-">-</option>
            <option value="/">/</option>
        </select>
        <br/>
        <button ng-click="calculateNums()">Calculate Now</button>
    </div>
</body>

</html></code>```

Body:
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});

Hello

Number 1::<input Type="text" name="number1" ng-model="n1"/ required>

Number 2::<input Type="text" name="number2" ng-model="n2"/ required>

operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>

So, The output I get is -

calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0

the operator values are undefined here..

Body:
You can use $scope variables directly instead of using extra variables for that. Then there will be no need to take them as parameters. And add value to all options in select.

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    var ans = 0;
    $scope.singleSelect = "+";             // + will be selected by default
    $scope.calculateNums = function() {    // no parameters required
        console.log($scope.n1);
        console.log($scope.n2);
        console.log($scope.singleSelect);
        if ($scope.singleSelect == "+") {
            ans = (parseInt($scope.n1) + parseInt($scope.n2));
        } else if ($scope.singleSelect == "-") {
            ans = (parseInt($scope.n1) - parseInt($scope.n2));
        } else if ($scope.singleSelect == "*") {
            ans = (parseInt($scope.n1) * parseInt($scope.n2));
        } else if ($scope.singleSelect == "/") {
            ans = (parseInt($scope.n1) / parseInt($scope.n2));
        }
        console.log(ans);
        return ans;
    }
});

<html ng-app="myApp">

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
    <script src="app.js"></script>
</head>

<body>
    <h3>Hello</h3>
    <div ng-controller='calcCtrl'>
        Number 1::
        <input Type="text" name="number1" ng-model="n1" / required>
        <br/> Number 2::
        <input Type="text" name="number2" ng-model="n2" / required>
        <br/> operator::
        <select ng-model="singleSelect">
            <option value="+">+</option>
            <option value="*">*</option>
            <option value="-">-</option>
            <option value="/">/</option>
        </select>
        <br/>
        <button ng-click="calculateNums()">Calculate Now</button>
    </div>
</body>

</html>


来源: stackexchange

问:
apksigner not accepting password
Up until now I had been signing my apks with the following method:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore {keystore-file} {apk-file} {keystore-alias}

However I am trying to use the new apksigner tool and I cannot get it to work since it always tells me the password is invalid. Which is impossible because I have done it multiple times, with the jarsigner works and with the apksigner doesn't. The commands I have tried are the following:

apksigner sign --ks {keystore-file} {apk-file}

apksigner sign --ks {keystore-file} --ks-key-alias {keystore-alias} {apk-file}

Now the weirdest part comes when I created a new keystore to test this, and with this new keystore it's working. So I don't understand what is the difference. Here's the information obtained from calling "keytool -v -list -keystore {keystore-file}" on both.

Production keystore (I have removed some text in case this is dangerous):

```<code>Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: {keystore-alias}
Creation date: Apr 4, 2016
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN={removed-text}, OU={removed-text}, O={removed-text}, L=Unknown, ST=Unknown, C=Unknown
Issuer: CN={removed-text}, OU={removed-text}, O={removed-text}, L=Unknown, ST=Unknown, C=Unknown
Serial number: {removed-text}
Valid from: Mon Apr 04 12:39:50 CEST 2016 until: Fri Aug 21 12:39:50 CEST 2043
Certificate fingerprints:
     MD5:  {removed-text}
     SHA1: {removed-text}
     SHA256: {removed-text}
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: {removed-text}
0010: {removed-text} {removed-text}                                        ....
]
]

*******************************************
*******************************************
</code>```

New test keystore:

```<code>Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: app
Creation date: Nov 17, 2016
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Foobar, OU=Foobar, O=foobar, L=Unknown, ST=Unknown, C=Unknown
Issuer: CN=Foobar, OU=Foobar, O=foobar, L=Unknown, ST=Unknown, C=Unknown
Serial number: 448c7afc
Valid from: Thu Nov 17 11:40:26 CET 2016 until: Mon Apr 04 12:40:26 CEST 2044
Certificate fingerprints:
     MD5:  3E:29:C0:3C:30:B4:DC:E0:A5:94:1D:2E:E9:86:58:CA
     SHA1: 3D:09:B4:42:A2:7C:14:C7:3E:54:33:0E:AB:75:2E:F1:19:23:00:FA
     SHA256: 7F:E0:51:F1:6A:53:45:56:42:B9:F9:38:92:69:81:7A:DA:71:FF:44:51:15:7F:F9:B4:1C:AA:2B:53:4A:89:72
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: BC 1B E6 C4 6D 25 01 70   CA AC 81 34 81 4B AE 41  ....m%.p...4.K.A
0010: 10 DF D8 13                                        ....
]
]

*******************************************
*******************************************
</code>```

答:
use it this way      </p>

```<code>./apksigner sign --ks test.jks --ks-key-alias test --ks-pass pass:testtest --key-pass pass:testtest Test_Aligned.apk
</code>```

ContentLicense: CC BY-SA 3.0

Title: apksigner not accepting password

Body:
Up until now I had been signing my apks with the following method:

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore {keystore-file} {apk-file} {keystore-alias}

However I am trying to use the new apksigner tool and I cannot get it to work since it always tells me the password is invalid. Which is impossible because I have done it multiple times, with the jarsigner works and with the apksigner doesn't. The commands I have tried are the following:

apksigner sign --ks {keystore-file} {apk-file}

apksigner sign --ks {keystore-file} --ks-key-alias {keystore-alias} {apk-file}

Now the weirdest part comes when I created a new keystore to test this, and with this new keystore it's working. So I don't understand what is the difference. Here's the information obtained from calling "keytool -v -list -keystore {keystore-file}" on both.

Production keystore (I have removed some text in case this is dangerous):

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: {keystore-alias}
Creation date: Apr 4, 2016
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN={removed-text}, OU={removed-text}, O={removed-text}, L=Unknown, ST=Unknown, C=Unknown
Issuer: CN={removed-text}, OU={removed-text}, O={removed-text}, L=Unknown, ST=Unknown, C=Unknown
Serial number: {removed-text}
Valid from: Mon Apr 04 12:39:50 CEST 2016 until: Fri Aug 21 12:39:50 CEST 2043
Certificate fingerprints:
     MD5:  {removed-text}
     SHA1: {removed-text}
     SHA256: {removed-text}
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: {removed-text}
0010: {removed-text} {removed-text}                                        ....
]
]

*******************************************
*******************************************

New test keystore:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: app
Creation date: Nov 17, 2016
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Foobar, OU=Foobar, O=foobar, L=Unknown, ST=Unknown, C=Unknown
Issuer: CN=Foobar, OU=Foobar, O=foobar, L=Unknown, ST=Unknown, C=Unknown
Serial number: 448c7afc
Valid from: Thu Nov 17 11:40:26 CET 2016 until: Mon Apr 04 12:40:26 CEST 2044
Certificate fingerprints:
     MD5:  3E:29:C0:3C:30:B4:DC:E0:A5:94:1D:2E:E9:86:58:CA
     SHA1: 3D:09:B4:42:A2:7C:14:C7:3E:54:33:0E:AB:75:2E:F1:19:23:00:FA
     SHA256: 7F:E0:51:F1:6A:53:45:56:42:B9:F9:38:92:69:81:7A:DA:71:FF:44:51:15:7F:F9:B4:1C:AA:2B:53:4A:89:72
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: BC 1B E6 C4 6D 25 01 70   CA AC 81 34 81 4B AE 41  ....m%.p...4.K.A
0010: 10 DF D8 13                                        ....
]
]

*******************************************
*******************************************

Body:
use it this way

./apksigner sign --ks test.jks --ks-key-alias test --ks-pass pass:testtest --key-pass pass:testtest Test_Aligned.apk


问:
How to keep alive socket.io connection when app is in Background in iOS?
How to keep alive socket.io connection when app is in Background in iOS</p>

答: I don't think iOS allows you to connect Socket.io in background mode. You can establish a connection once your app comes into foreground or app becomes active.</p>


答:
```<code>SELECT  t1.listid
FROM    t1
WHERE   type = 'a'
        AND id NOT IN
        (
        SELECT  listid
        FROM    t2
        WHERE   code NOT IN ('ax', 'bx')
        )
</code>```

This will also match records from t1 which have no corresponding records in t2 at all.

ContentLicense: CC BY-SA 2.5

Title: mysql, joining 2 tables, and checking for 2 conditions

Body:
MySQL

table1:

+--------+------+
| listid | type |
+--------+------+
|    1   |  a   |
+--------+------+
|    2   |  a   |
+--------+------+
|    3   |  b   |
+--------+------+

table2:

+----+--------+------+
| id | listid | code |
+----+--------+------+
|  1 |    1   |  ax  |
+----+--------+------+
|  2 |    1   |  bx  |
+----+--------+------+
|  3 |    2   |  ax  |
+----+--------+------+
|  4 |    2   |  bx  |
+----+--------+------+
|  5 |    2   |  cx  |
+----+--------+------+
|  6 |    3   |  ax  |
+----+--------+------+
|  7 |    3   |  bx  |
+----+--------+------+

Task

In one query, I want to check if:

1) in the table table2 only "ax" & "bx" are listed as code

2) the type of the listid I get in 1) is "a" in the table table1

PHP

$a = mysql_query("SELECT t1.listid FROM table1 AS t1, table2 AS t2......");
$b = mysql_fetch_assoc($a);

if($b['listid'])
{
    echo $b['listid'];
}
else
{
    echo 'nothing found';
}

Output

listid = 1

listid = 2 is false, because "cx" is also included in table2

listid = 3 is false, because it has type "b" in table1

I hope this makes sense :)

Body:
SELECT  t1.listid
FROM    t1
WHERE   type = 'a'
        AND id NOT IN
        (
        SELECT  listid
        FROM    t2
        WHERE   code NOT IN ('ax', 'bx')
        )

This will also match records from t1 which have no corresponding records in t2 at all.


问:
How can i use count to see the "messages" column count on "hours" Column between a month in SQL?
I want to count the messages on each hours separated with column date, I write this query but it shows 1 messages for each duplicate hour, could anyone help? Thanks</p>

```<code>Select MsgCount,ReadTime
From (Select Count(MsgID) MsgCount,
      LTRIM(RIGHT(CONVERT(VARCHAR(20), mDate, 100), 7)) as ReadTime
      FROM (Select  ReadDate as mDate,
            Convert (TIME, ReadDate) as ReadTime,MessageID as MsgID
            From QUEUE_BOOKINGQUEUE
            WHERE MessageID like '%Transaction%'
            AND ReadDate BETWEEN '2017-11-01' AND '2017-11-30')
      s1
      Group by mDate
) A
Group by MsgCount,ReadTime
Order by 2
</code>```

答:
it worked with me as this picture there is no duplication
so, if you want to remove the grouping it will be like this:

```<code>Select MsgCount,ReadTime
From (Select Count(MsgID) MsgCount,
      LTRIM(RIGHT(CONVERT(VARCHAR(20), mDate, 100), 7)) as ReadTime
      FROM (Select  ReadDate as mDate,
            Convert (TIME, ReadDate) as ReadTime,MsgID as MsgID
            From QUEUE_BOOKINGQUEUE
    )  s1
      Group by mDate,s1.MsgID
) A
</code>```

Body:
I want to count the messages on each hours separated with column date, I write this query but it shows 1 messages for each duplicate hour, could anyone help? Thanks

Select MsgCount,ReadTime
From (Select Count(MsgID) MsgCount,
      LTRIM(RIGHT(CONVERT(VARCHAR(20), mDate, 100), 7)) as ReadTime
      FROM (Select  ReadDate as mDate,
            Convert (TIME, ReadDate) as ReadTime,MessageID as MsgID
            From QUEUE_BOOKINGQUEUE
            WHERE MessageID like '%Transaction%'
            AND ReadDate BETWEEN '2017-11-01' AND '2017-11-30')
      s1
      Group by mDate
) A
Group by MsgCount,ReadTime
Order by 2

Body:
it worked with me as this picture there is no duplication
so, if you want to remove the grouping it will be like this:

Select MsgCount,ReadTime
From (Select Count(MsgID) MsgCount,
      LTRIM(RIGHT(CONVERT(VARCHAR(20), mDate, 100), 7)) as ReadTime
      FROM (Select  ReadDate as mDate,
            Convert (TIME, ReadDate) as ReadTime,MsgID as MsgID
            From QUEUE_BOOKINGQUEUE
    )  s1
      Group by mDate,s1.MsgID
) A


问:
Check if element is visible in DOM
Is there any way that I can check if an element is visible in pure JS (no jQuery) ?

So, given a DOM element, how can I check if it is visible or not? I tried:

```<code>window.getComputedStyle(my_element)['display']);
</code>```

but it doesn't seem to be working.  I wonder which attributes should I check. It comes to my mind:

```<code>display !== 'none'
visibility !== 'hidden'
</code>```

Any others that I might be missing?

答:
A little addition to ohad navon's answer.

If the center of the element belongs to the another element we won't find it.

So to make sure that one of the points of the element is found to be visible

```<code>function isElementVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity === 0) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    var elementPoints = {
        'center': {
            x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
            y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
        },
        'top-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().top
        },
        'top-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().top
        },
        'bottom-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().bottom
        },
        'bottom-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().bottom
        }
    }

    for(index in elementPoints) {
        var point = elementPoints[index];
        if (point.x < 0) return false;
        if (point.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
        if (point.y < 0) return false;
        if (point.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
        let pointContainer = document.elementFromPoint(point.x, point.y);
        if (pointContainer !== null) {
            do {
                if (pointContainer === elem) return true;
            } while (pointContainer = pointContainer.parentNode);
        }
    }
    return false;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Check if element is visible in DOM

Body:
Is there any way that I can check if an element is visible in pure JS (no jQuery) ?

So, given a DOM element, how can I check if it is visible or not? I tried:

window.getComputedStyle(my_element)['display']);

but it doesn't seem to be working.  I wonder which attributes should I check. It comes to my mind:

display !== 'none'
visibility !== 'hidden'

Any others that I might be missing?

Body:
A little addition to ohad navon's answer.

If the center of the element belongs to the another element we won't find it.

So to make sure that one of the points of the element is found to be visible

function isElementVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity === 0) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    var elementPoints = {
        'center': {
            x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
            y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
        },
        'top-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().top
        },
        'top-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().top
        },
        'bottom-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().bottom
        },
        'bottom-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().bottom
        }
    }

    for(index in elementPoints) {
        var point = elementPoints[index];
        if (point.x < 0) return false;
        if (point.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
        if (point.y < 0) return false;
        if (point.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
        let pointContainer = document.elementFromPoint(point.x, point.y);
        if (pointContainer !== null) {
            do {
                if (pointContainer === elem) return true;
            } while (pointContainer = pointContainer.parentNode);
        }
    }
    return false;
}


问:
Changing variables
I am sure this is just something simple but I am just getting into C# and this isn't clicking in my mind.

I basically need to assign to a button of mine the function of changing the variable offsets that my tool uses to write data to my 3DS.

I have both variables but I don't really know how to tell it to switch from using 1 set to the other when I press it and then waterfall back if I press it again.

This is my code here showing my variables that are called upon throughout my tool

```<code>public partial class MainForm : Form
{

    public delegate void LogDelegate(string l);
    public LogDelegate delLastLog;
    public string lastlog = "";
    public int pid = 0;
    public PKHeX dumpedPKHeX = new PKHeX();
    //Possibly Ultra box layout Offset? 0x33015AB0
    //Possibly Ultra Wondercard Offset? 0x33075BF4
    public uint boxOff = 0x330D9838;
    public uint wcOff = 0x331397E4;
    public uint partyOff = 0x34195E10;
</code>```

Then this is my button I have started.

```<code>private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    MessageBox.Show("Ultra Support Mode Activated!", "WonderInjection", MessageBoxButtons.OK);
    return;
}
</code>```

Any idea guys? Basically the boxoff and wcoff offsets I need to be able to be switched to the ones I have commented out one the command of the button.

答:
You can make two queues that would store the possible data and just dequeue and enqueue them, that would work exactly like a toggle button if there are only two values in a queue.

I would declare the queues in a class like this

```<code>Queue<string> qbox;
Queue<string> qwc;
</code>```

Then I would initiate the queues like this in constructor or some other method.

```<code>qbox = new Queue<string>
{
    "0x330D9838", "0x33015AB0"
};
qwc = new Queue<string>
{
    "0x331397E4", "0x33075BF4"
};
</code>```

then i would use them like this:

```<code>private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    qbox.Enqueue(box);
    box = qbox.Dequeue();

    qwc.Enqueue(wc); //puts wc value to the back of the queue
    wc= qbox.Dequeue(); //removes first value from a queue and puts it in wc variable
}
</code>```

qbox would add box value to the end of a queue and box would get the value from the start of a queue. Dequeued objects get removed from the queue.
Same for wc. I think this approach is very readable and managable because you dont have to deal with multiple if...thens. You just toggle between values.

You have to remember that box and wc variables also need to be initialised with some initial value.

Title: Changing variables

Body:
I am sure this is just something simple but I am just getting into C# and this isn't clicking in my mind.

I basically need to assign to a button of mine the function of changing the variable offsets that my tool uses to write data to my 3DS.

I have both variables but I don't really know how to tell it to switch from using 1 set to the other when I press it and then waterfall back if I press it again.

This is my code here showing my variables that are called upon throughout my tool

public partial class MainForm : Form
{

    public delegate void LogDelegate(string l);
    public LogDelegate delLastLog;
    public string lastlog = "";
    public int pid = 0;
    public PKHeX dumpedPKHeX = new PKHeX();
    //Possibly Ultra box layout Offset? 0x33015AB0
    //Possibly Ultra Wondercard Offset? 0x33075BF4
    public uint boxOff = 0x330D9838;
    public uint wcOff = 0x331397E4;
    public uint partyOff = 0x34195E10;

Then this is my button I have started.

private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    MessageBox.Show("Ultra Support Mode Activated!", "WonderInjection", MessageBoxButtons.OK);
    return;
}

Any idea guys? Basically the boxoff and wcoff offsets I need to be able to be switched to the ones I have commented out one the command of the button.

Body:
You can make two queues that would store the possible data and just dequeue and enqueue them, that would work exactly like a toggle button if there are only two values in a queue.

I would declare the queues in a class like this

Queue<string> qbox;
Queue<string> qwc;

Then I would initiate the queues like this in constructor or some other method.

qbox = new Queue<string>
{
    "0x330D9838", "0x33015AB0"
};
qwc = new Queue<string>
{
    "0x331397E4", "0x33075BF4"
};

then i would use them like this:

private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    qbox.Enqueue(box);
    box = qbox.Dequeue();

    qwc.Enqueue(wc); //puts wc value to the back of the queue
    wc= qbox.Dequeue(); //removes first value from a queue and puts it in wc variable
}

qbox would add box value to the end of a queue and box would get the value from the start of a queue. Dequeued objects get removed from the queue.
Same for wc. I think this approach is very readable and managable because you dont have to deal with multiple if...thens. You just toggle between values.

You have to remember that box and wc variables also need to be initialised with some initial value.


问:
get error while file upload in laravel
I am trying to upload image in laravel. But when i upload it gives error.

Call to a member function getClientOriginalExtension() on null

Here is my Blade file form

```<code>{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
   'method' => 'post','class'=>'form-row','files'=>true,
   "enctype"=>"multipart/form-data"))}}
</code>```

And here is controller

```<code> $imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
 $destinationPath = public_path('/uploads/blog');
 $thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
 $thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
 $photo->move($destinationPath, $imagename_bg);
</code>```

Please help me how to resolve this problem.

答:
You only need to use this:

```<code>$photo = $request->file("blogimage");
</code>```

instead of:

```<code>$photo = $request->input("blogimage")
</code>```

Hope this will fixed your problem!

Title: get error while file upload in laravel

Body:
I am trying to upload image in laravel. But when i upload it gives error.

Call to a member function getClientOriginalExtension() on null

Here is my Blade file form

{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
   'method' => 'post','class'=>'form-row','files'=>true,
   "enctype"=>"multipart/form-data"))}}

And here is controller

 $imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
 $destinationPath = public_path('/uploads/blog');
 $thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
 $thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
 $photo->move($destinationPath, $imagename_bg);

Please help me how to resolve this problem.

Body:
You only need to use this:

$photo = $request->file("blogimage");

instead of:

$photo = $request->input("blogimage")

Hope this will fixed your problem!


问:
npm bootstrap 4.0.0-beta.2, where is jquery, tether and popper?
I'm surprised to see the js removed from the bootstrap 4 beta 2 version. Why is that? Bootstrap 4 relies on jquery.js, tether.js and popper.js doesn't it? </p>

答:
They are now listed as peer dependencies, which means that you'll need to install them separately.

Tether is not being used anymore, it got replaced by Popper.


问:
How to extract base URL from a string in JavaScript?
I'm trying to find a relatively easy and reliable method to extract the base URL from a string variable using JavaScript (or jQuery).

For example, given something like:

```http://www.sitename.com/article/2009/09/14/this-is-an-article/```

I'd like to get:

```http://www.sitename.com/```

Is a regular expression the best bet? If so, what statement could I use to assign the base URL extracted from a given string to a new variable?

I've done some searching on this, but everything I find in the JavaScript world seems to revolve around gathering this information from the actual document URL using location.host or similar.

答:
```<code>var tilllastbackslashregex = new RegExp(/^.*\//);
baseUrl = tilllastbackslashregex.exec(window.location.href);
</code>```

window.location.href   gives the current url address from browser address bar

it can be any thing like  https://stackoverflow.com/abc/xyz or https://www.google.com/search?q=abc   tilllastbackslashregex.exec() run regex and retun the matched string till last backslash ie https://stackoverflow.com/abc/ or https://www.google.com/ respectively

Body:
I'm trying to find a relatively easy and reliable method to extract the base URL from a string variable using JavaScript (or jQuery).

For example, given something like:

http://www.sitename.com/article/2009/09/14/this-is-an-article/

I'd like to get:

http://www.sitename.com/

Is a regular expression the best bet? If so, what statement could I use to assign the base URL extracted from a given string to a new variable?

I've done some searching on this, but everything I find in the JavaScript world seems to revolve around gathering this information from the actual document URL using location.host or similar.

Body:
var tilllastbackslashregex = new RegExp(/^.*\//);
baseUrl = tilllastbackslashregex.exec(window.location.href);

window.location.href   gives the current url address from browser address bar

it can be any thing like  https://stackoverflow.com/abc/xyz or https://www.google.com/search?q=abc   tilllastbackslashregex.exec() run regex and retun the matched string till last backslash ie https://stackoverflow.com/abc/ or https://www.google.com/ respectively


问:
Calculating the trajectory arc of a projectile
I am trying to move an image across the screen in an arc... think flappy birds launcher. The image starts at the bottom left of the screen. When 'launched' I want it to move / animate in an arc across the screen as if launched.

I can animate the image in a linear (up and right) trajectory but cannot figure out how to get it to curve and start dropping.

The image is placed at the bottom left of the screen.

Inside a setTimeout method that runs every 0.01 seconds I have:

```<code>left += 10;
top -= 10;
$image.animate({left: '' + left + 'px', top: '' + top + 'px' });
</code>```

答:
Track velocity as well as position.</p>

```<code>const GRAVITY = 2; // acceleration due to gravity, in pixels/tick
x = 0;
y = 0;
deltaX = 10;
deltaY = -10;

function tick() { // your setTimeout method
  x += deltaX;
  y += deltaY;
  deltaY += GRAVITY;
  $image.animate({left: `${x}px`, top: `${y}px` });
}
</code>```

Body:
I am trying to move an image across the screen in an arc... think flappy birds launcher. The image starts at the bottom left of the screen. When 'launched' I want it to move / animate in an arc across the screen as if launched.

I can animate the image in a linear (up and right) trajectory but cannot figure out how to get it to curve and start dropping.

The image is placed at the bottom left of the screen.

Inside a setTimeout method that runs every 0.01 seconds I have:

left += 10;
top -= 10;
$image.animate({left: '' + left + 'px', top: '' + top + 'px' });

Body:
Track velocity as well as position.

const GRAVITY = 2; // acceleration due to gravity, in pixels/tick
x = 0;
y = 0;
deltaX = 10;
deltaY = -10;

function tick() { // your setTimeout method
  x += deltaX;
  y += deltaY;
  deltaY += GRAVITY;
  $image.animate({left: `${x}px`, top: `${y}px` });
}


问:
Directions API Live tracking in android app
I am trying to use google maps directions API with continuous hitting to the API and updating the directions by getting a current location on location changed listener and it works perfectly.

But Instead of hitting multiple times I need to get directions API for the single instance and write an algorithm by getting the directions using segments start point and update on google map, Find a way to know the user is traveling in the wrong distance and re-route map by calling API.I tried these ways and working but there are a lot of cases to be handled for these scenarios.

I don't understand what to follow and why this is required is, we have a display cycle and the user starts the navigation and directions should be shown on cycle hardware display via BLE.

Please help me solving this issue.

答:
You can try using the Google Maps Util Library. The PolyUtils class has methods to check if a LatLng lies on a polygon/polyline.

Maybe try using the method isLocationOnPath. And if it's outside the polyline, make the request to directions API and re-plot the route.

Docs: http://googlemaps.github.io/android-maps-utils/javadoc/


问:
Sending mail to both sender and receiver using PHPmailer
I am using phpmailer in live server for sending emails for both sender and receiver. Its working fine but I want to include additional message in sender copy  as "thanks for registering with us". I am unable to do it.
Could you please help with this ?
Code I tried So far:</p>

```<code><?php
$msg = "";

if (isset($_POST['submit'])) {

    require 'phpmailer/PHPMailerAutoload.php';

    function sendemail($to, $from, $fromName, $body) {
        $mail = new PHPMailer();
        $mail->setFrom($from, $fromName);
        $mail->addAddress($to);

        $mail->Subject = 'Contact Form - Email';
        $mail->Body = $body;
        $mail->isHTML(false);
        return $mail->send();
    }
    function sender_mail($to, $from, $fromName, $body) {
        $mail = new PHPMailer();
        $mail->setFrom($from, $fromName);
        $mail->addAddress($to);

        $mail->Subject = 'Copy Contact Form - Email';
        $mail->Body = $body . 'Thanks for registering with us';
        $mail->isHTML(false);

        return $mail->send();
    }
    $name = $_POST['username'];
    $email = $_POST['email'];
    $body = $_POST['body'];
   sendemail('abc@domain.com', 'xyz@domain.com', $name, $body);
    sender_mail('abc@domain.com', $email, $name, $body);
}?>
</code>```

答:
I always create different mail object for sending another email. So it will always pick new message.

For sending another email you can update like below:

```<code>    $mail2 = new PHPMailer();
    $mail2->setFrom($from, $fromName);
    $mail2->addAddress($to);

    $mail2->Subject = 'Copy Contact Form - Email';
    $mail2->Body = $body . 'Thanks for registering with us';
    $mail2->isHTML(false);

    return $mail2->send();
</code>```

2nd option to use clearAddresses above your second email to clear your earlier messages like below:

```<code>    $mail->clearAddresses();

    $mail = new PHPMailer();
    $mail->setFrom($from, $fromName);
    $mail->addAddress($to);

    $mail->Subject = 'Copy Contact Form - Email';
    $mail->Body = $body . 'Thanks for registering with us';
    $mail->isHTML(false);

    return $mail->send();
</code>```

Body:
I am using phpmailer in live server for sending emails for both sender and receiver. Its working fine but I want to include additional message in sender copy  as "thanks for registering with us". I am unable to do it.
Could you please help with this ?
Code I tried So far:

<?php
$msg = "";

if (isset($_POST['submit'])) {

    require 'phpmailer/PHPMailerAutoload.php';

    function sendemail($to, $from, $fromName, $body) {
        $mail = new PHPMailer();
        $mail->setFrom($from, $fromName);
        $mail->addAddress($to);

        $mail->Subject = 'Contact Form - Email';
        $mail->Body = $body;
        $mail->isHTML(false);
        return $mail->send();
    }
    function sender_mail($to, $from, $fromName, $body) {
        $mail = new PHPMailer();
        $mail->setFrom($from, $fromName);
        $mail->addAddress($to);

        $mail->Subject = 'Copy Contact Form - Email';
        $mail->Body = $body . 'Thanks for registering with us';
        $mail->isHTML(false);

        return $mail->send();
    }
    $name = $_POST['username'];
    $email = $_POST['email'];
    $body = $_POST['body'];
   sendemail('abc@domain.com', 'xyz@domain.com', $name, $body);
    sender_mail('abc@domain.com', $email, $name, $body);
}?>

Body:
I always create different mail object for sending another email. So it will always pick new message.

For sending another email you can update like below:

    $mail2 = new PHPMailer();
    $mail2->setFrom($from, $fromName);
    $mail2->addAddress($to);

    $mail2->Subject = 'Copy Contact Form - Email';
    $mail2->Body = $body . 'Thanks for registering with us';
    $mail2->isHTML(false);

    return $mail2->send();

2nd option to use clearAddresses above your second email to clear your earlier messages like below:

    $mail->clearAddresses();

    $mail = new PHPMailer();
    $mail->setFrom($from, $fromName);
    $mail->addAddress($to);

    $mail->Subject = 'Copy Contact Form - Email';
    $mail->Body = $body . 'Thanks for registering with us';
    $mail->isHTML(false);

    return $mail->send();


问:
Groovy script keeps running when running a test suite
I've encountered a wierd behaviour of a groovy script when running the whole suite. I have a script which orders my testcases alphabetically before they run and it seems to be running forever even when the whole test suite finishes.

After I click on it to see details and immediately go back to test suite it shows that it's finished and no longer running.

Is there something wrong with my script please? I don't see any infinite loops or anything like that. Is it just a bug in the ReadyAPI? Thanks for advice.

My sorting script:

```<code>ArrayList<String> testCaseList = new ArrayList<String>();
for (testCase in testRunner.testCase.testSuite.getTestCaseList()) {
 testCaseList.add(testCase.getName());
}
testCaseList.sort();
int i = 0;
for (tCase in testCaseList) {
 def curCase = testRunner.testCase.testSuite.getTestCaseByName(tCase);
 curIndex = testRunner.testCase.testSuite.getIndexOfTestCase(curCase);
 testRunner.testCase.testSuite.moveTestCase(curIndex,i-curIndex);
 i++;
}
</code>```

答:
Currently, looks you have separate test case for sorting. But actually, that is not a valid test case of yours.

So, the first change to be made is that the script should be moved from test case to Setup Script of test suite.

Here is the Test Suite's Setup Script which does it alphabetical order. Should be paid special attention in case if the test case names have numbers in it, have to do natural order. Otherwise, it should be ok.

Please follow the in-line comments.

```<code>//Get the sorted order of the test case which is expected order
def newList = testSuite.testCaseList.name.sort()
log.info "Expected order of test cases: ${newList}"

//Get the current index of the test case
def getTestCaseIndex = { name -> testSuite.getIndexOfTestCase(testSuite.getTestCaseByName(name))}

//Closure definition and this is being called recursively to make the desired order
def rearrange
rearrange = {
    def testCaseNames = testSuite.testCaseList.name
    if (testCaseNames != newList) {
        log.info testCaseNames
        newList.eachWithIndex { tc, index ->
            def existingIndex = getTestCaseIndex(tc)
            if (index != existingIndex) {
                testSuite.moveTestCase(index, existingIndex-index)
                rearrange()
            }
        }
    } else {
        log.info 'All cases sorted'
    }
}

//Call the closure
rearrange()
</code>```

With that Setup Script, when test suite is executed, automatically the test cases are moved alphabetically. Hence, no separate test case required for just ordering.

Now, the suite gets executed with desired test cases and the current issue mentioned in the question should not be there at all.

Body:
I've encountered a wierd behaviour of a groovy script when running the whole suite. I have a script which orders my testcases alphabetically before they run and it seems to be running forever even when the whole test suite finishes.

After I click on it to see details and immediately go back to test suite it shows that it's finished and no longer running.

Is there something wrong with my script please? I don't see any infinite loops or anything like that. Is it just a bug in the ReadyAPI? Thanks for advice.

My sorting script:

ArrayList<String> testCaseList = new ArrayList<String>();
for (testCase in testRunner.testCase.testSuite.getTestCaseList()) {
 testCaseList.add(testCase.getName());
}
testCaseList.sort();
int i = 0;
for (tCase in testCaseList) {
 def curCase = testRunner.testCase.testSuite.getTestCaseByName(tCase);
 curIndex = testRunner.testCase.testSuite.getIndexOfTestCase(curCase);
 testRunner.testCase.testSuite.moveTestCase(curIndex,i-curIndex);
 i++;
}

Body:
Currently, looks you have separate test case for sorting. But actually, that is not a valid test case of yours.

So, the first change to be made is that the script should be moved from test case to Setup Script of test suite.

Here is the Test Suite's Setup Script which does it alphabetical order. Should be paid special attention in case if the test case names have numbers in it, have to do natural order. Otherwise, it should be ok.

Please follow the in-line comments.

//Get the sorted order of the test case which is expected order
def newList = testSuite.testCaseList.name.sort()
log.info "Expected order of test cases: ${newList}"

//Get the current index of the test case
def getTestCaseIndex = { name -> testSuite.getIndexOfTestCase(testSuite.getTestCaseByName(name))}

//Closure definition and this is being called recursively to make the desired order
def rearrange
rearrange = {
    def testCaseNames = testSuite.testCaseList.name
    if (testCaseNames != newList) {
        log.info testCaseNames
        newList.eachWithIndex { tc, index ->
            def existingIndex = getTestCaseIndex(tc)
            if (index != existingIndex) {
                testSuite.moveTestCase(index, existingIndex-index)
                rearrange()
            }
        }
    } else {
        log.info 'All cases sorted'
    }
}

//Call the closure
rearrange()

With that Setup Script, when test suite is executed, automatically the test cases are moved alphabetically. Hence, no separate test case required for just ordering.

Now, the suite gets executed with desired test cases and the current issue mentioned in the question should not be there at all.


问:
'ng' is not recognized as an internal or external command, Angular tutorial
I"m doing this tutorial for Azure. It's when I come to running the following

```<code>ng new angular-cosmosdb -sd src/client --minimal --style scss
</code>```

I get the error message "'ng' is not recognized as an internal or external command," when I can confirm that Angular has been installed globally - as below

I've tried solutions here,

'ng' is not recognized as an internal or external command

namely

o reinstall the angular with -g argument (even though this was already installed globally)
o restart, restart, restart laptop again and again and again
o my suspicion is that an local variable might need to be set? But other than that..

output from the list command is:

```<code>C:\2017\12 December\04122017\project>npm list -g --depth=0
D:\Users\useradmin\AppData\Roaming\npm
+-- @angular/cli@1.5.5
`-- typescript@2.6.2
</code>```

答:
If you are experiencing this in Windows, Try setting the PATH as,

```<code>set PATH=%PATH%;C:\Users\[YOUR_WINDOWS_USER_NAME\AppData\Roaming\npm;
</code>```

In case if you are using it in OSX,

```<code>export PATH=/usr/local/share/npm/bin:$PATH
</code>```

which will make the ng command work.

Body:
I"m doing this tutorial for Azure. It's when I come to running the following

ng new angular-cosmosdb -sd src/client --minimal --style scss

I get the error message "'ng' is not recognized as an internal or external command," when I can confirm that Angular has been installed globally - as below

I've tried solutions here,

'ng' is not recognized as an internal or external command

namely

o reinstall the angular with -g argument (even though this was already installed globally)
o restart, restart, restart laptop again and again and again
o my suspicion is that an local variable might need to be set? But other than that..

output from the list command is:

C:\2017\12 December\04122017\project>npm list -g --depth=0
D:\Users\useradmin\AppData\Roaming\npm
+-- @angular/cli@1.5.5
`-- typescript@2.6.2

Body:
If you are experiencing this in Windows, Try setting the PATH as,

set PATH=%PATH%;C:\Users\[YOUR_WINDOWS_USER_NAME\AppData\Roaming\npm;

In case if you are using it in OSX,

export PATH=/usr/local/share/npm/bin:$PATH

which will make the ng command work.


问:
Crash with GoogleMaps on Xcode 9
I use GoogleMaps lib on my application since a long time but since I updated Xcode with Swift 4, when I go to the map, my application crash.

Error :

WARNING: Unable to find and load 'GoogleMaps.bundle' for Google Maps SDK for iOS. This may be a sign that you've forgotten to include a resources bundle in your 'Copy Bundle Resources' build phase. As this bundle contains important resources, you may encounter missing images, translations and other incorrect behavior.

Why ?

答: I have the same issue. just clean the Build: (Window Button)Command + alt option + Shift + K then run the project. Now its working fine.</p>

Title: Crash with GoogleMaps on Xcode 9


问:
Cropping image By selecting Object and color matching
We are developing an app where we need to crop an image according to the selecting object area. User will draw a line and we need to select the object and crop it .This crop need to be like the app: YourMoji

So far we have tried to get the color of the pixels along the line and then comparing those with the color of every pixel in the image and making a path from it to clip the image. But the almost going no where.

Is it possible through this way to crop an image or we are going in the wrong way? Can anyone provide a way to do this Or suggest a way to modify the way we have worked so far?
Any advice and suggestions will be greatly appreciated!

Thanks in advance.

答:
I guess what you want is the image segmentation algorithm called Graph Cut.

Here are two Github repositories, hope these would help:

GraphCut

GrabCutIOS


问:
How to set siteSpeedSampleRate value in google analytics using angular js
I have used this link https://github.com/revolunet/angular-google-analytics to add a google analytics to my Angularjs 1.5 project but I didn't find a way to set siteSpeedSampleRate.I have added AnalyticsProvider dependency injection and tried this to set the value like this AnalyticsProvider.setAccount({ tracker: UA-XXXX-12, siteSpeedSampleRate: 100 }); but didn't work. Is there any other way to do this?

Thank you in advance.

答:
The right syntax to do it is:</p>

```<code>AnalyticsProvider.setAccount({
    tracker: 'UA-XXXX-12',
    fields: {
      siteSpeedSampleRate: 100
    }
});
</code>```

Body:
The right syntax to do it is:

AnalyticsProvider.setAccount({
    tracker: 'UA-XXXX-12',
    fields: {
      siteSpeedSampleRate: 100
    }
});


问:
Detecting that Angular 2 is done running
We use Selenium WebDriver to automate our UI based tests.  One of our challenges is to detect when a page is truly done loading, and Angular 1 was a challenge in that regard as well.  We ended up executing this piece of code specifically to detect if Angular 1 is done:

```<code>if(typeof window.angular !== \"undefined\")
{
  var injector = window.angular.element(\"*[ng-app]\").eq(0).injector();

  if(injector)
  {
    var $rootScope = injector.get(\"$rootScope\");
    var $http = injector.get(\"$http\");

    if($rootScope.$$phase === \"$apply\" || $rootScope.$$phase === \"$digest\" || $http.pendingRequests.length !== 0)
    {
      return false;
    }
  }
}
</code>```

The app that we are testing recently switched over to use Angular 2.  The code snippet above does not wait for Angular 2 to finish.  Any suggestions?

答:
Using @alecxe answer i ended up with following javascript one liner to check if all Angular Testabilities are stable </p>

```<code>window.getAllAngularTestabilities().findIndex(x=>!x.isStable()) === -1
</code>```

Body:
We use Selenium WebDriver to automate our UI based tests.  One of our challenges is to detect when a page is truly done loading, and Angular 1 was a challenge in that regard as well.  We ended up executing this piece of code specifically to detect if Angular 1 is done:

if(typeof window.angular !== \"undefined\")
{
  var injector = window.angular.element(\"*[ng-app]\").eq(0).injector();

  if(injector)
  {
    var $rootScope = injector.get(\"$rootScope\");
    var $http = injector.get(\"$http\");

    if($rootScope.$$phase === \"$apply\" || $rootScope.$$phase === \"$digest\" || $http.pendingRequests.length !== 0)
    {
      return false;
    }
  }
}

The app that we are testing recently switched over to use Angular 2.  The code snippet above does not wait for Angular 2 to finish.  Any suggestions?

Body:
Using @alecxe answer i ended up with following javascript one liner to check if all Angular Testabilities are stable

window.getAllAngularTestabilities().findIndex(x=>!x.isStable()) === -1


问:
Batch File Programming with Findstr and Regex
First off, I am not a batch file and/or regex programmer.  ;)

Using batch file programming to parse filenames beginning with "T" that may be immediately followed by "2" AND "2" may be immediately followed by any of the integers 0-9.  All the files in the folder will be named the same beginning with "T" and followed by integers 1-29.  For example:
T1_... or T12_... or T2_... or T22_....

In this particular case ...

a) Filenames with T2 should fail the regex.  Errorlevel should be 1.

b) Filenames with T12 should fail the regex.  Errorlevel should be 1.

c) Filenames with T20 - T29 should pass the regex.  Errorlevel should be 0.

Problem: These results are not seen.  Errorlevel appears to be 0, always.

```<code>echo on

dir *.bin /b | findstr /r /c:"^[T][2][?=0123456789]*"
if errorlevel 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0
</code>```

Two web based regex evaluators say my regex is valid as written when tested against all combinations, pass and fail.

What is going on with the "findstr" regex that it does not produce the outlined behavior (a-c)?  Or, am I not using errorlevel correctly?

Thanks for any insight.

答:
findstr uses a regex subset to find a string in a file.

Hence, your command is probably yielding errorlevel of 0 because the question being asked is "is there a string matching this anwhere in the 'file' generated by dir?"

What you appear to be attempting to do is to show those files that do and those that do not match your pattern.

So - if you just want a list of the files, then

```<code>dir /b /A-D |findstr /R "regex"
</code>```

should accomplish that task, noting:

/a-d means "don't show directorynames"

/r is the default hence is redundant

/r /v could replace /r meaning "do not match the regex"

switches are case-insensitive.

Another approach would be

```<code>for /f "delims=" %%a in ('dir /b /a-d') do (
 echo %%a|findstr /r "regex" >nul
 if errorlevel 1 (call :nonmatch "%%a"
 ) else (
  call :match "%%a"
 )
)
</code>```

where [non]match are subroutines:

```<code>....
goto :eof

:match
echo %~1 matches
goto :eof
</code>```

%%a is assigned each name from the dir command in turn, and is then examined by findstr, outputting to nul and setting errorlevel to 0 if the regex is passed, 1 if not. The errorlevel is then examined and one of the two subroutines is executed, with the first parameter %1 being the (quoted) filename.

Note:

The metavariable %%a is case-sensitive

findstr could also have the /i switch to make the regex analysis case-insensitive.

The construct goto :eof (case-insensitive) is defined in cmd as "go to end of file"

Now - as for regex itself, as I said, it's a subset. I'd use T2[0-9]_ and add the /b switch to the findstr, yielding findstr /r /i /b "T2[0-9]_" meaning "begins, case-insensitive, with regex T2a_digitunderscore"

You could also omit the /b and use "^T2[0-9]_" in theory - I have a personal preference for the /b version.

Body:
First off, I am not a batch file and/or regex programmer.  ;)

Using batch file programming to parse filenames beginning with "T" that may be immediately followed by "2" AND "2" may be immediately followed by any of the integers 0-9.  All the files in the folder will be named the same beginning with "T" and followed by integers 1-29.  For example:
T1_... or T12_... or T2_... or T22_....

In this particular case ...

a) Filenames with T2 should fail the regex.  Errorlevel should be 1.

b) Filenames with T12 should fail the regex.  Errorlevel should be 1.

c) Filenames with T20 - T29 should pass the regex.  Errorlevel should be 0.

Problem: These results are not seen.  Errorlevel appears to be 0, always.

echo on

dir *.bin /b | findstr /r /c:"^[T][2][?=0123456789]*"
if errorlevel 0 goto :regular

:special
   echo special
   pause
   exit /B 0

:regular
   echo regular
   pause
   exit /B 0

Two web based regex evaluators say my regex is valid as written when tested against all combinations, pass and fail.

What is going on with the "findstr" regex that it does not produce the outlined behavior (a-c)?  Or, am I not using errorlevel correctly?

Thanks for any insight.

Body:
findstr uses a regex subset to find a string in a file.

Hence, your command is probably yielding errorlevel of 0 because the question being asked is "is there a string matching this anwhere in the 'file' generated by dir?"

What you appear to be attempting to do is to show those files that do and those that do not match your pattern.

So - if you just want a list of the files, then

dir /b /A-D |findstr /R "regex"

should accomplish that task, noting:

/a-d means "don't show directorynames"

/r is the default hence is redundant

/r /v could replace /r meaning "do not match the regex"

switches are case-insensitive.

Another approach would be

for /f "delims=" %%a in ('dir /b /a-d') do (
 echo %%a|findstr /r "regex" >nul
 if errorlevel 1 (call :nonmatch "%%a"
 ) else (
  call :match "%%a"
 )
)

where [non]match are subroutines:

....
goto :eof

:match
echo %~1 matches
goto :eof

%%a is assigned each name from the dir command in turn, and is then examined by findstr, outputting to nul and setting errorlevel to 0 if the regex is passed, 1 if not. The errorlevel is then examined and one of the two subroutines is executed, with the first parameter %1 being the (quoted) filename.

Note:

The metavariable %%a is case-sensitive

findstr could also have the /i switch to make the regex analysis case-insensitive.

The construct goto :eof (case-insensitive) is defined in cmd as "go to end of file"

Now - as for regex itself, as I said, it's a subset. I'd use T2[0-9]_ and add the /b switch to the findstr, yielding findstr /r /i /b "T2[0-9]_" meaning "begins, case-insensitive, with regex T2a_digitunderscore"

You could also omit the /b and use "^T2[0-9]_" in theory - I have a personal preference for the /b version.


问:
cross validation and early stopping
I'm trying to make sure I am not confused with how h2o works with a cross validation and a validation dataset.   I'm sure I am just getting confused on the verbiage that is used to describe this

```<code>    library(mlbench)
   library(h2o)

data(Sonar)
dfh2o = as.h2o(Sonar)
splits=h2o.splitFrame(dfh2o)

train = splits[[1]]
valid = splits[[2]]

gbm_no_val_frame <- h2o.gbm(x = colnames(df), y = "Class", training_frame = train,
                         nfolds = 5, seed = 1234, ntrees  = 4000, stopping_rounds = 5)

gbm_val_frame <- h2o.gbm(x = colnames(df), y = "Class", training_frame = train, validation_frame = valid,
                    nfolds = 5, seed = 1234, ntrees  = 4000, stopping_rounds = 5)

   h2o.flow()  ### to see the validation frame stopping under models.
</code>```

What is the validation frame that is used for early stopping in gbm_no_val_frame?   How does this stop to prevent overfitting exactly?

I think I understand how gbm_val_frame works - it stops overfitting when the scores stop improving when the trained fold/final model hits against the 'valid' frame?

Just want to eliminate any doubts I have here..

答:
How does early stopping work here exactly?

Your assumption is correct. Early stopping will be used for each of the CV models, and then for the final model.

If I remove the validation_set here, ...

You are not specifying a validation data set in your example. Instead you are requesting cross-validation, by setting nfolds.

If you remove nfolds and don't specify validation_frame, it will use the score on the training data set to evaluate when early stopping should stop. As you are using GBM, that effectively means it will not stop early: GBM will always get better after adding each additional tree.

So, yes, always specify either validation_frame, or nfolds.

UPDATE BASED ON CODE EDIT

gbm_no_val_frame: for each of the 5-folds, 1/5th of the data is used as the validation frame. The final model is built using all the data. It will only indirectly use early stopping: it will ignore the value of ntrees that you give, and instead use the average number of trees that the 5 cv models ended up using.  (Source: the top of p.102 of my book, but it is also in the GBM FAQ.)

As for your second question, my reading of the FAQ suggests that the above is still how early stopping works, and that the validation set is only used to give you additional statistics.

(For GBM I think this is fine; for deep learning, where progress is stochastic and can be a lot noisier, I find the early stopping point of each fold can be quite different, and less useful to decide early stopping of the final model; so I generally prefer not to use nfolds, and just use a validation_frame)

Title: cross validation and early stopping

Body:
I'm trying to make sure I am not confused with how h2o works with a cross validation and a validation dataset.   I'm sure I am just getting confused on the verbiage that is used to describe this

    library(mlbench)
   library(h2o)

data(Sonar)
dfh2o = as.h2o(Sonar)
splits=h2o.splitFrame(dfh2o)

train = splits[[1]]
valid = splits[[2]]

gbm_no_val_frame <- h2o.gbm(x = colnames(df), y = "Class", training_frame = train,
                         nfolds = 5, seed = 1234, ntrees  = 4000, stopping_rounds = 5)

gbm_val_frame <- h2o.gbm(x = colnames(df), y = "Class", training_frame = train, validation_frame = valid,
                    nfolds = 5, seed = 1234, ntrees  = 4000, stopping_rounds = 5)

   h2o.flow()  ### to see the validation frame stopping under models.

What is the validation frame that is used for early stopping in gbm_no_val_frame?   How does this stop to prevent overfitting exactly?

I think I understand how gbm_val_frame works - it stops overfitting when the scores stop improving when the trained fold/final model hits against the 'valid' frame?

Just want to eliminate any doubts I have here..


问:
What is ownProps in react-redux?
I am reading the API on react-redux and looking at one of Redux' github examples: Redux todo app

One of the containers, FilterLink, has mapDispatchToProps (and mapStateToProps) to accept two arguments, one of them being ownprops.

```<code>const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: () => {
    dispatch(setVisibilityFilter(ownProps.filter))
  }
})
</code>```

The API docs says:

"If your mapStateToProps function is declared as taking two parameters, it will be called with the store state as the first parameter and the props passed to the connected component as the second parameter, and will also be re-invoked whenever the connected component receives new props as determined by shallow equality comparisons. (The second parameter is normally referred to as ownProps by convention.)"

I still can't fully grasp what it does. Can someone explain what ownProps does with a different example?

答:
ownProps are the attributes that are passed when the component is used. In plain React these would be just called props.

for example in Footer.js the FilterLink is used as:

```<code><FilterLink filter="SHOW_ALL">
  All
</FilterLink>
</code>```

So mapStateToProps method would be called with ownProps having the value:

```<code>{
  "filter": "SHOW_ALL",
  "children": ...
}
</code>```

The mapStateToProps method is used in a Redux-wrapped component to combine the explicitly passed properties (ownProps) with the state handled by the Redux store into the props of the wrapped component.

So in your linked example of FilterLink

```<code>const mapStateToProps = (state, ownProps) => ({
  active: ownProps.filter === state.visibilityFilter
})
</code>```

the component is active (this.props.active == true) if the filter attribute (e.g. SHOW_ALL) matches the visibiltyFilter in state, i.e. if it is currently filtered by this value.

Title: What is ownProps in react-redux?

Body:
I am reading the API on react-redux and looking at one of Redux' github examples: Redux todo app

One of the containers, FilterLink, has mapDispatchToProps (and mapStateToProps) to accept two arguments, one of them being ownprops.

const mapDispatchToProps = (dispatch, ownProps) => ({
  onClick: () => {
    dispatch(setVisibilityFilter(ownProps.filter))
  }
})

The API docs says:

"If your mapStateToProps function is declared as taking two parameters, it will be called with the store state as the first parameter and the props passed to the connected component as the second parameter, and will also be re-invoked whenever the connected component receives new props as determined by shallow equality comparisons. (The second parameter is normally referred to as ownProps by convention.)"

I still can't fully grasp what it does. Can someone explain what ownProps does with a different example?

Body:
ownProps are the attributes that are passed when the component is used. In plain React these would be just called props.

for example in Footer.js the FilterLink is used as:

<FilterLink filter="SHOW_ALL">
  All
</FilterLink>

So mapStateToProps method would be called with ownProps having the value:

{
  "filter": "SHOW_ALL",
  "children": ...
}

The mapStateToProps method is used in a Redux-wrapped component to combine the explicitly passed properties (ownProps) with the state handled by the Redux store into the props of the wrapped component.

So in your linked example of FilterLink

const mapStateToProps = (state, ownProps) => ({
  active: ownProps.filter === state.visibilityFilter
})

the component is active (this.props.active == true) if the filter attribute (e.g. SHOW_ALL) matches the visibiltyFilter in state, i.e. if it is currently filtered by this value.


问:
How to change Logo Company size
I want to change Logo company size in Sale Order and Custommer Invoice, I code with this but haven't changed that logo size.

here's my code:

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<template id="co_report_saleorder_document">
    <t t-call="report.external_layout">
        <t t-set="docs" t-value="docs.with_context({'lang':docs.partner_id.lang})" />

        <!-- Multicompany -->
        <t t-if="not o and doc">
            <t t-set="o" t-value="doc"/>
        </t>
        <t t-if="o and 'company_id' in o">
            <t t-set="company" t-value="o.company_id"></t>
        </t>
        <t t-if="not o or not 'company_id' in o">
            <t t-set="company" t-value="res_company"></t>
        </t>

        <div class="header">
            <div class="row">
                <div class="col-xs-3">
                    <img t-if="company.logo" t-att-src="'data:image/png;base64,%s' % company.logo" style="max-width: 200px; max-height: 150px;"/>
                </div>
                <div class="col-xs-9 text-right" style="margin-top:20px;" t-field="company.rml_header1"/>
            </div>
            <div class="row zero_min_height">
                <div class="col-xs-12">
                    <div style="border-bottom: 1px solid black;"></div>
                </div>
            </div>
        </div>

</template>

<template id="report_saleorder">
    <t t-call="report.html_container">
        <t t-foreach="docs" t-as="docs">
            <t t-call="sale.fal_report_saleorder_document" t-lang="docs.partner_id.lang"/>
        </t>
    </t>
</template>

<report
    string="Cetak Sales"
    id="co_view_sale"
    model="sale.order"
    report_type="qweb-pdf"
    name="co_sale_report.co_report_saleorder_document"
    file="co_sale_report.co_report_saleorder_document"
/>

</odoo>
</code>```

I have add code in style="max-width: 200px; max-height: 150px;" but haven't change. somebody can help me?

答:
Try adding below width block css</p>

```<code>style="max-width: 200px; max-height: 150px; display: block;"
</code>```

Title: How to change Logo Company size

Body:
I want to change Logo company size in Sale Order and Custommer Invoice, I code with this but haven't changed that logo size.

here's my code:

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<template id="co_report_saleorder_document">
    <t t-call="report.external_layout">
        <t t-set="docs" t-value="docs.with_context({'lang':docs.partner_id.lang})" />

        <t t-if="not o and doc">
            <t t-set="o" t-value="doc"/>
        </t>
        <t t-if="o and 'company_id' in o">
            <t t-set="company" t-value="o.company_id"></t>
        </t>
        <t t-if="not o or not 'company_id' in o">
            <t t-set="company" t-value="res_company"></t>
        </t>

</template>

<template id="report_saleorder">
    <t t-call="report.html_container">
        <t t-foreach="docs" t-as="docs">
            <t t-call="sale.fal_report_saleorder_document" t-lang="docs.partner_id.lang"/>
        </t>
    </t>
</template>

<report
    string="Cetak Sales"
    id="co_view_sale"
    model="sale.order"
    report_type="qweb-pdf"
    name="co_sale_report.co_report_saleorder_document"
    file="co_sale_report.co_report_saleorder_document"
/>

</odoo>

I have add code in style="max-width: 200px; max-height: 150px;" but haven't change. somebody can help me?

Body:
Try adding below width block css

style="max-width: 200px; max-height: 150px; display: block;"


问:
Getting black screen for remote video: WebRTC
I'm developing video calling functionality with WebRTC and facing a very strange problem.

When I make a call everything is fine and I'm getting a remote video stream, but when I receive a call, I get a black screen with no remote video. The strange part is that when I refresh the page I get the remote video!

In the console, I'm getting the following thing:

Video constraints false

But when I refresh the page I get the video object.

This is my video container in index.html,

```<code><video id="video-container" autoplay="autoplay" class="video-style"></video>
</code>```

Main.js:

```<code>(function() {
var vertoHandle, vertoCallbacks, currentCall;

document.getElementById("make-call").addEventListener("click", makeCall);
document.getElementById("hang-up-call").addEventListener("click", hangupCall);
document.getElementById("answer-call").addEventListener("click", answerCall);

$.verto.init({}, bootstrap);

function bootstrap(status) {
    vertoHandle = new jQuery.verto({
        // ID of HTML video tag where the video feed is placed.
        tag: "video-container",
        deviceParams: {
          // Asking for camera permissions and devices.
          useCamera: 'any',
          useMic: 'any',
          useSpeak: 'any',
        },

        login: '1008@127.0.0.1',
        passwd: '1234',
        socketUrl: 'wss://127.0.0.1:8082',
        ringFile: '',
        iceServers: true,
    }, vertoCallbacks);
};

vertoCallbacks = {
    onWSLogin : onWSLogin,
    onWSClose : onWSClose,
    onDialogState: onDialogState,
}

function onWSLogin(verto, success) {
    console.log('onWSLogin', success);
}

function onWSClose(verto, success) {
    console.log('onWSClose', success);
}

function onDialogState(d) {
    console.debug('onDialogState', d);

    if(!currentCall) {
        currentCall = d;
    }

    switch (d.state.name) {
        case 'trying':
            //
            break;
        case 'ringing':
            alert('Someone is calling you, answer!');
            break;
        case 'answering':
            //
            break;
        case 'active':
            //
            break;
        case 'hangup':
            //
            break;
        case 'destroy':
            //
            break;
    }
}

function makeCall() {
    vertoHandle.videoParams({
        minWidth: 320,
        minHeight: 240,
        maxWidth: 640,
        maxHeight: 480,
        // The minimum frame rate of the client camera, Verto will fail if it's
        // less than this.
        minFrameRate: 15,
        // The maximum frame rate to send from the camera.
        vertoBestFrameRate: 30,
    });

    currentCall = vertoHandle.newCall({
        useVideo: true,
        mirrorInput: true,

        destination_number : '3520',
        caller_id_name : 'Test Caller',
        caller_id_number: '1008',
        outGoingBandwidth: 'default',
        inComingBandwidth: 'default',

        useStereo: true,
        useMic: true,
        useSpeak: true,

        userVariables: {
            email: 'test@test.com'
        },

        dedEnc: false,
    });
}

function hangupCall() {
    currentCall.hangup();
};

function answerCall() {
    currentCall.answer();
}
})();
</code>```

What's wrong with this code?

Thanks in advance!

答:
So after some research, I've found the solution.

I was getting the error Video constraints false because they were set at the time of making a call, not at the time of receiving. So I manually set the property,

```<code>useVideo: true
</code>```

after deviceParams.

Just like,

```<code>tag: "video-container",
deviceParams: {
      // Asking for camera permissions and devices.
      useCamera: 'any',
      useMic: 'any',
      useSpeak: 'any',
},
useVideo: true,
//other properties
</code>```

Now I'm getting the video at the time of making a call too.

Body:
I'm developing video calling functionality with WebRTC and facing a very strange problem.

When I make a call everything is fine and I'm getting a remote video stream, but when I receive a call, I get a black screen with no remote video. The strange part is that when I refresh the page I get the remote video!

In the console, I'm getting the following thing:

Video constraints false

But when I refresh the page I get the video object.

This is my video container in index.html,

<video id="video-container" autoplay="autoplay" class="video-style"></video>

Main.js:

(function() {
var vertoHandle, vertoCallbacks, currentCall;

document.getElementById("make-call").addEventListener("click", makeCall);
document.getElementById("hang-up-call").addEventListener("click", hangupCall);
document.getElementById("answer-call").addEventListener("click", answerCall);

$.verto.init({}, bootstrap);

function bootstrap(status) {
    vertoHandle = new jQuery.verto({
        // ID of HTML video tag where the video feed is placed.
        tag: "video-container",
        deviceParams: {
          // Asking for camera permissions and devices.
          useCamera: 'any',
          useMic: 'any',
          useSpeak: 'any',
        },

        login: '1008@127.0.0.1',
        passwd: '1234',
        socketUrl: 'wss://127.0.0.1:8082',
        ringFile: '',
        iceServers: true,
    }, vertoCallbacks);
};

vertoCallbacks = {
    onWSLogin : onWSLogin,
    onWSClose : onWSClose,
    onDialogState: onDialogState,
}

function onWSLogin(verto, success) {
    console.log('onWSLogin', success);
}

function onWSClose(verto, success) {
    console.log('onWSClose', success);
}

function onDialogState(d) {
    console.debug('onDialogState', d);

    if(!currentCall) {
        currentCall = d;
    }

    switch (d.state.name) {
        case 'trying':
            //
            break;
        case 'ringing':
            alert('Someone is calling you, answer!');
            break;
        case 'answering':
            //
            break;
        case 'active':
            //
            break;
        case 'hangup':
            //
            break;
        case 'destroy':
            //
            break;
    }
}

function makeCall() {
    vertoHandle.videoParams({
        minWidth: 320,
        minHeight: 240,
        maxWidth: 640,
        maxHeight: 480,
        // The minimum frame rate of the client camera, Verto will fail if it's
        // less than this.
        minFrameRate: 15,
        // The maximum frame rate to send from the camera.
        vertoBestFrameRate: 30,
    });

    currentCall = vertoHandle.newCall({
        useVideo: true,
        mirrorInput: true,

        destination_number : '3520',
        caller_id_name : 'Test Caller',
        caller_id_number: '1008',
        outGoingBandwidth: 'default',
        inComingBandwidth: 'default',

        useStereo: true,
        useMic: true,
        useSpeak: true,

        userVariables: {
            email: 'test@test.com'
        },

        dedEnc: false,
    });
}

function hangupCall() {
    currentCall.hangup();
};

function answerCall() {
    currentCall.answer();
}
})();

What's wrong with this code?

Thanks in advance!

Body:
So after some research, I've found the solution.

I was getting the error Video constraints false because they were set at the time of making a call, not at the time of receiving. So I manually set the property,

useVideo: true

after deviceParams.

Just like,

tag: "video-container",
deviceParams: {
      // Asking for camera permissions and devices.
      useCamera: 'any',
      useMic: 'any',
      useSpeak: 'any',
},
useVideo: true,
//other properties

Now I'm getting the video at the time of making a call too.


问:
What are some software and techniques for extracting proper names from a text?
I have a large corpus of text-based documents (100,000+) from which I want to extract proper names (e.g. a person's name).

Could anyone recommend techniques and/or software that would be useful in accomplishing this goal. I'm not particularly interested in low-level text parsing, so much as I am in more high-level things such as recognizing and/or ranking.

答: What if you made a list of all of the unique words, then removed all of the words that are in a dictionary?</p>


问:
How to get width of absolute positioned element in Angular
I'm trying to get the width off a component but it is 0. I've also tried putting the code in ngOnChanges().

```<code>constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}
</code>```

Element style:

```<code>display: block;
position: absolute;
left: 100;
</code>```

I tried using clientWidth() but it is 0 too. How can I get the width of an element in angular 2?

Update:

I don't use position absolute and the width is correct, so I suppose the question is how do I get the width of an absolute positioned element?

答:
Try to use: </p>

```<code>const rect = this.element.nativeElement.getBoundingClientRect();
const width = rect.width;
</code>```

Body:
I'm trying to get the width off a component but it is 0. I've also tried putting the code in ngOnChanges().

constructor(private element: ElementRef) {
  this.htmlElement = this.element.nativeElement;
  let width = this.htmlElement.offsetWidth;
}

Element style:

display: block;
position: absolute;
left: 100;

I tried using clientWidth() but it is 0 too. How can I get the width of an element in angular 2?

Update:

I don't use position absolute and the width is correct, so I suppose the question is how do I get the width of an absolute positioned element?

Body:
Try to use:

const rect = this.element.nativeElement.getBoundingClientRect();
const width = rect.width;


问:
Angular 4 Nuget Package
I am looking to try out the new Angular release (4.1.x), however the Angular package on Nuget states that this is version 1.6.x - which was released in April coinciding with when Angular 4 was released. Does anybody know if this is the package I'm looking for if I wanted to work with the latest release of Angular 4? </p>

答:
If You want to install you can use Install-Package Angular4 -Version 1.1.0  and follow these steps:

```<code>Angular 4
*********

Prerequisites
`````````````
1. Download and Install Node js
2. Install Visual studio 2015 update 3 or above
3. Download and Install TypeScript 2.6.1 for Visual Studio 2015 (https://www.typescriptlang.org/#download-links)

Follow the steps to install package.
````````````````````````````````````
1. Create an new project with empty template and include dependencies for MVC and WebApi to the project
2. Install the package using command 'Install-Package Angular4 -Version 1.1.0'

Follow the steps after package installation
```````````````````````````````````````````
1. Open Node.js Command Prompt
2. Navigate to project location(use commands such as pushd,cd etc)
3. Run the command 'npm install'
</code>```

Title: Angular 4 Nuget Package

Body:
If You want to install you can use Install-Package Angular4 -Version 1.1.0  and follow these steps:

Angular 4
*********

Prerequisites
`````````````
1. Download and Install Node js
2. Install Visual studio 2015 update 3 or above
3. Download and Install TypeScript 2.6.1 for Visual Studio 2015 (https://www.typescriptlang.org/#download-links)

Follow the steps to install package.
````````````````````````````````````
1. Create an new project with empty template and include dependencies for MVC and WebApi to the project
2. Install the package using command 'Install-Package Angular4 -Version 1.1.0'

Follow the steps after package installation
```````````````````````````````````````````
1. Open Node.js Command Prompt
2. Navigate to project location(use commands such as pushd,cd etc)
3. Run the command 'npm install'


Title: pandas pct_change() in reverse

Body:
Suppose we have a dataframe and we calculate as percent change between rows

y_axis = [1,2,3,4,5,6,7,8,9]
x_axis = [100,105,115,95,90,88,110,100,0]

DF = pd.DataFrame({'Y':y_axis, 'X':x_axis})

DF = DF[['Y','X']]
DF['PCT'] = DF['X'].pct_change()

    Y   X   PCT
0   1   100 NaN
1   2   105 0.050000
2   3   115 0.095238
3   4   95  -0.173913
4   5   90  -0.052632
5   6   88  -0.022222
6   7   110 0.250000
7   8   100 -0.090909
8   9   0   -1.000000

That way it starts from the first row.
I want calculate pct_change() starting from the last row.

One way to do it

DF['Reverse'] = list(reversed(x_axis))
DF['PCT_rev'] = DF['Reverse'].pct_change()
pct_rev = DF.PCT_rev.tolist()

DF['_PCT_'] = list(reversed(pct_rev))
DF2 = DF[['Y','X','PCT','_PCT_']]

    Y   X   PCT         _PCT_
0   1   100 NaN         -0.047619
1   2   105 0.050000    -0.086957
2   3   115 0.095238    0.210526
3   4   95  -0.173913   0.055556
4   5   90  -0.052632   0.022727
5   6   88  -0.022222   -0.200000
6   7   110 0.250000    0.100000
7   8   100 -0.090909   inf
8   9   0   -1.000000   NaN

But that is a very ugly and inefficient solution.
I was wondering if there are more elegant solutions?

Body:
I deleted my other answer because @su79eu7k 's is way better.

You can cut your time in half by using the underlying arrays.  But you also have to suppress a warning.

a = DF.X.values
DF.assign(_PCT_=np.append((a[:-1] - a[1:]) / a[1:], np.nan))

   Y    X       PCT     _PCT_
0  1  100       NaN -0.047619
1  2  105  0.050000 -0.086957
2  3  115  0.095238  0.210526
3  4   95 -0.173913  0.055556
4  5   90 -0.052632  0.022727
5  6   88 -0.022222 -0.200000
6  7  110  0.250000  0.100000
7  8  100 -0.090909       inf
8  9    0 -1.000000       NaN


问:
Cancel button is not shown in UISearchBar
I have UICollectionView. On clicking search button in UINavigationBar, I am adding the UISearchController's searchbar as titleview for UINavigationItem. For iPhone it is working properly. For iPad the cancel button is not shown. The Searchbar alone takes the entire width.

Can anyone help me out on this?. Thanks in advance.

答:
```<code>Added rightBarButtonItem with selector will work fine for me. And adding searchBar inside view before setting to navigation title view was not showing properly.
Code:-
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.dismissView))
func dismissView() {
        if self.controller?.navigationController?.popViewController(animated: true) == nil {
            self.controller?.dismiss(animated: true, completion: nil)
        }
    }
</code>```


问:
cannot check(select) radio button inside a modal dialog
In my page I am using custom modal dialog and inside that modal I am using a form. I have put two radio button inside that form but I cannot check either one.</p>

```<code><div id="user_modal" class="modal modal__bg" role="dialog" aria-hidden="true">
    <div class="modal__dialog">
        <div class="modal__content">
            <h1>User registration</h1>

            <form action="" id="u_register_form">

                <div class="form-group">
                  <input type="text" class="form-control" id="fullname" placeholder="Full name" required/>
                </div>

                <div class="form-group">
                    <label class="radio-inline"><input type="radio" value="w" name="optradio"/>Worker</label>
                    <label class="radio-inline"><input type="radio" value="e" name="optradio"/>Engineer</label>
                </div>

                <div class="form-group">
                  <input type="text" class="form-control" id="username" required placeholder="Username">
                </div>

                <div class="form-group">
                  <input type="password" class="form-control" id="u_pwd1" pattern=".{8,}" required placeholder="Password"/>
                </div>

                <div class="form-group submit_btn">
                    <input class="btn btn-success" id="u_register_btn" type="submit" value="SAVE">
                </div>

            </form>

            <!-- modal close button -->
            <a href="" class="modal__close demo-close">
                <svg class="" viewBox="0 0 24 24"><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/><path d="M0 0h24v24h-24z" fill="none"/></svg>
            </a>

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

答: Definitely check your console for errors. The code loads fine on its own in a simple notepad .html file. The error is probably before this or with the "radio-inline" class.</p>

Body:
In my page I am using custom modal dialog and inside that modal I am using a form. I have put two radio button inside that form but I cannot check either one.

User registration

            <form action="" id="u_register_form">

                  <input type="text" class="form-control" id="fullname" placeholder="Full name" required/>

                    <input type="radio" value="w" name="optradio"/>Worker
                    <input type="radio" value="e" name="optradio"/>Engineer

                  <input type="text" class="form-control" id="username" required placeholder="Username">

                  <input type="password" class="form-control" id="u_pwd1" pattern=".{8,}" required placeholder="Password"/>

                    <input class="btn btn-success" id="u_register_btn" type="submit" value="SAVE">

            </form>

                <svg class="" viewBox="0 0 24 24"><path d="M19 6.41l-1.41-1.41-5.59 5.59-5.59-5.59-1.41 1.41 5.59 5.59-5.59 5.59 1.41 1.41 5.59-5.59 5.59 5.59 1.41-1.41-5.59-5.59z"/><path d="M0 0h24v24h-24z" fill="none"/></svg>


问:
Display resized image with good quality on every screen
When I am trying to resize the image in PHP, it gets blurry on some screens. Is there any way to display resized image with good quality on every screen ?

Here is what I have tried so far:

```<code>if($thumb == TRUE)
    {
        $thumbnail = $thumb_path.$fileName;
        list($width,$height) = getimagesize($upload_image);
        $thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
        switch($file_ext){
            case 'jpg':
                $source = imagecreatefromjpeg($upload_image);
                break;
            case 'jpeg':
                $source = imagecreatefromjpeg($upload_image);
                break;

            case 'png':
                $source = imagecreatefrompng($upload_image);
                break;
            case 'gif':
                $source = imagecreatefromgif($upload_image);
                break;
            default:
                $source = imagecreatefromjpeg($upload_image);
        }

        imagecopyresized($thumb_create,$source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
        switch($file_ext){
            case 'jpg' || 'jpeg':
                imagejpeg($thumb_create,$thumbnail,100);
                break;
            case 'png':
                imagepng($thumb_create,$thumbnail,100);
                break;

            case 'gif':
                imagegif($thumb_create,$thumbnail,100);
                break;
            default:
                imagejpeg($thumb_create,$thumbnail,100);
        }
</code>```

答:
Use image with high quality or you can even use srcsetattribute for that.

Example

```<code><picture>
  <source media="(min-width: 650px)" srcset="big.jpg">
  <source media="(min-width: 465px)" srcset="medium.jpg">
  <img src="small.jpg" alt="Flowers" style="width:auto;">
</picture>
</code>```

Try it

Body:
When I am trying to resize the image in PHP, it gets blurry on some screens. Is there any way to display resized image with good quality on every screen ?

Here is what I have tried so far:

if($thumb == TRUE)
    {
        $thumbnail = $thumb_path.$fileName;
        list($width,$height) = getimagesize($upload_image);
        $thumb_create = imagecreatetruecolor($thumb_width,$thumb_height);
        switch($file_ext){
            case 'jpg':
                $source = imagecreatefromjpeg($upload_image);
                break;
            case 'jpeg':
                $source = imagecreatefromjpeg($upload_image);
                break;

            case 'png':
                $source = imagecreatefrompng($upload_image);
                break;
            case 'gif':
                $source = imagecreatefromgif($upload_image);
                break;
            default:
                $source = imagecreatefromjpeg($upload_image);
        }

        imagecopyresized($thumb_create,$source,0,0,0,0,$thumb_width,$thumb_height,$width,$height);
        switch($file_ext){
            case 'jpg' || 'jpeg':
                imagejpeg($thumb_create,$thumbnail,100);
                break;
            case 'png':
                imagepng($thumb_create,$thumbnail,100);
                break;

            case 'gif':
                imagegif($thumb_create,$thumbnail,100);
                break;
            default:
                imagejpeg($thumb_create,$thumbnail,100);
        }

Body:
Use image with high quality or you can even use srcsetattribute for that.

Example

<picture>
  <source media="(min-width: 650px)" srcset="big.jpg">
  <source media="(min-width: 465px)" srcset="medium.jpg">
  <img src="small.jpg" alt="Flowers" style="width:auto;">
</picture>

Try it


问:
Getting Image Height with FancyBox 3
I'm having trouble creating an If/then in fancybox, using the height of an image that will be going into the fancybox.

```<code>setBigImage : function ( slide ) {
var self = this;
var $img = $('<img />');

slide.$image = $img
.one('error', function() {

self.setError( slide );

})
.one('load', function() {

slide.width  = this.naturalWidth;
slide.height = this.naturalHeight;

.addClass( 'fancybox-image ' )
.attr('src', slide.src)
.appendTo( slide.$content );
</code>```

In essence, I'm looking to add an if/then before the .addClass call that checks to see if the image's height is greater than 500px. I have tried to use:

```<code>if ( slide.Width > 500)
and if ( this.NaturalHeight > 500)
</code>```

Neither worked. I tried both slide.Width and this.NaturalHeight inside of p tags to see what text they were putting out. Unfortunately, they created a second instance of the image. What would be the best way to get the image's height?

Thank you for your patience and help.

答:
First, let the clarify this misunderstanding - " Unfortunately, they created a second instance of the image". When using some basic lightbox script, user would see black overlay with loading icon right after clicking thumbnail and then the image would just pop in. But fancybox displays thumbnail (first image) while actual image is still loading. Then real image (2nd image) gradually appears over the first one and user most likely will not see or notice loading indicator.

The answer to your question is also simple, just replace

if ( slide.Width > 500)

with

if ( slide.width > 500)

btw, next version of fancybox will allow more customization based on image size, see these demos - https://codepen.io/anon/pen/mqQLVm?editors=1010 and https://codepen.io/anon/pen/yPQjbw?editors=1010

Title: Getting Image Height with FancyBox 3

Body:
I'm having trouble creating an If/then in fancybox, using the height of an image that will be going into the fancybox.

setBigImage : function ( slide ) {
var self = this;
var $img = $('');

slide.$image = $img
.one('error', function() {

self.setError( slide );

})
.one('load', function() {

slide.width  = this.naturalWidth;
slide.height = this.naturalHeight;

.addClass( 'fancybox-image ' )
.attr('src', slide.src)
.appendTo( slide.$content );

In essence, I'm looking to add an if/then before the .addClass call that checks to see if the image's height is greater than 500px. I have tried to use:

if ( slide.Width > 500)
and if ( this.NaturalHeight > 500)

Neither worked. I tried both slide.Width and this.NaturalHeight inside of p tags to see what text they were putting out. Unfortunately, they created a second instance of the image. What would be the best way to get the image's height?

Thank you for your patience and help.


问:
How to reload the page while moving from tab bar in swift 3?
Here after running the application i had clicked on cart in tab bar at that time there was no items added in cart so it shown your shopping cart is empty but after adding items in cart then I clicked on cart icon on tab bar also it is showing like as in previous and the cart page was not reloading can anyone help me how to resolve this ?

I had used this code in my home view controller

```<code>func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 1 {
            let  navController = self.tabBarController?.viewControllers![1] as! UINavigationController
            let secondViewController = navController.viewControllers[0] as! AddToCartViewController
            secondViewController.firstTimeTableSkip = true
            self.tabBarController?.selectedIndex = 1
        }
    }
</code>```

in my cart view controller I used this code

```<code>override func viewWillAppear(_ animated: Bool) {
        if firstLoginCheck == true {
        checkOutButton.isHidden = false
        checkOutButton.layer.cornerRadius = 5
        if conditonCheck == true || conditonCheck == nil{
        checkOutButton.isHidden = true
        checkOutButton.layer.cornerRadius = 5
        tableDetails.isHidden = true
        emptyView.isHidden = true
        tableDetails.separatorInset = UIEdgeInsets.zero
        loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        activityIndicator.startAnimating()
        emptyView.isHidden = true
        if loginCheck == 1 {
            let token = UserDefaults.standard.value(forKey: "CustomerLoginToken")
            self.customerKeyToken = token!
            print(self.customerKeyToken!)
            if itemCode != nil {
                self.customerAddToCartItemsDownloadJsonWithURl(cartApi: customerAddtoCartApi)
       customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
            else {
                customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
        }else if (loginCheck == 0) || (loginCheck == nil) {
            if let token = UserDefaults.standard.value(forKey: "user_token")  {
                self.key = token as? String
                let defaultValue = UserDefaults.standard.value(forKey: "MenuButton") as? String
                if (defaultValue == "Tab" && itemCode == nil) {
                    check = true
           cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                }
            } else {
                gettingKeyFromJsonWithURL(keyApi: keygettingApi)
            }
            if itemCode != nil && key != nil {
                self.PostingKeyFromJsonWithURL(PostingApi: postingKeyApi)
            }
            if key != nil {
                cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                emptyView.isHidden = true
            }
            }
        }
</code>```

答: you can set notification whenever your cart view will appear and set method for reloading when notification fire.</p>

Body:
Here after running the application i had clicked on cart in tab bar at that time there was no items added in cart so it shown your shopping cart is empty but after adding items in cart then I clicked on cart icon on tab bar also it is showing like as in previous and the cart page was not reloading can anyone help me how to resolve this ?

I had used this code in my home view controller

func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let tabBarIndex = tabBarController.selectedIndex
        if tabBarIndex == 1 {
            let  navController = self.tabBarController?.viewControllers![1] as! UINavigationController
            let secondViewController = navController.viewControllers[0] as! AddToCartViewController
            secondViewController.firstTimeTableSkip = true
            self.tabBarController?.selectedIndex = 1
        }
    }

in my cart view controller I used this code

override func viewWillAppear(_ animated: Bool) {
        if firstLoginCheck == true {
        checkOutButton.isHidden = false
        checkOutButton.layer.cornerRadius = 5
        if conditonCheck == true || conditonCheck == nil{
        checkOutButton.isHidden = true
        checkOutButton.layer.cornerRadius = 5
        tableDetails.isHidden = true
        emptyView.isHidden = true
        tableDetails.separatorInset = UIEdgeInsets.zero
        loginCheck = UserDefaults.standard.integer(forKey: "CustomerLogin")
        activityIndicator.startAnimating()
        emptyView.isHidden = true
        if loginCheck == 1 {
            let token = UserDefaults.standard.value(forKey: "CustomerLoginToken")
            self.customerKeyToken = token!
            print(self.customerKeyToken!)
            if itemCode != nil {
                self.customerAddToCartItemsDownloadJsonWithURl(cartApi: customerAddtoCartApi)
       customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
            else {
                customerCartItemsDownloadJsonWithURl(cartApi: customerCartApi)
            }
        }else if (loginCheck == 0) || (loginCheck == nil) {
            if let token = UserDefaults.standard.value(forKey: "user_token")  {
                self.key = token as? String
                let defaultValue = UserDefaults.standard.value(forKey: "MenuButton") as? String
                if (defaultValue == "Tab" && itemCode == nil) {
                    check = true
           cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                }
            } else {
                gettingKeyFromJsonWithURL(keyApi: keygettingApi)
            }
            if itemCode != nil && key != nil {
                self.PostingKeyFromJsonWithURL(PostingApi: postingKeyApi)
            }
            if key != nil {
                cartCountApiDownloadJsonWithURL(cartCountApi: getCartApi)
                emptyView.isHidden = true
            }
            }
        }