问:
How I find numbers with repeating digits within a range
I'm trying to find all numbers within the range 000000000..999999999 that have at least 3 or more similar digits grouped together.

Here are examples of integers that pass: 112333678, 111234567, 122111876

Here are examples of integers that fail: 123456789, 122334455, 123123123

I ran this line in Ruby, and then my Macbook Pro with 16 GB of RAM ran out of memory: (000000000..999999999).to_a.select{|e| e.to_s =~ /(\d)\1+/}

答:
A recursive solution:

Generate all numbers from 000 to 999, and use n % 111 to check
whether each is a multiple of 111. If it is, set a flag to true.

To each of these numbers, add a digit in the range 0-9, and if the number's flag was false, use (n % 1000) % 111 to check whether the three last digits are now equal, and if so, set the flag to true.

Repeat the previous step recursively, until you've reached 7 digits.

Then, for each 7-digit number, if its flag is true, add the full
range of 00-99 as the final two digits (generating a hundred 9-digit
numbers).

If the flag is false, use (n % 100) % 11 the check whether the last
two digits are equal, and if they are, add a third equal digit and
then the range 0-9 for the last digit (generating ten 9-digit
numbers).

If the last two digits weren't equal, add two digits equal to the
last digit (generating one 9-digit number).

Here's a simple JavaScript implementation. It's quick if you only count the results, but if you switch on the printing, it takes minutes rather than seconds for anything over 6 digits.

function repeatingDigits(len) {
    for (var n = 0; n < 1000; n++) {
        var flag = n % 111 ? false: true;
        add_digit(10 * n, flag, len - 3);
    }
}
function add_digit(n, flag, len) {
    for (var d = 0; d < 10; n++, d++) {
        var f = (!flag && (n % 1000) % 111 == 0) ? true : flag;
        if (len > 3) add_digit(10 * n, f, len - 1)
        else add_final(100 * n, f);
    }
}
function add_final(n, flag) {
    if (flag) {
        for (var d = 0; d < 100; n++, d++) {
            ++count; // document.write(n + " ");
        }
    }
    else if ((n % 10000) % 1100 == 0) {
        n += (n % 1000) / 10;
        for (var d = 0; d < 10; n++, d++) {
            ++count; // document.write(n + " ");
        }
    }
    else {
        n += ((n % 1000) / 100) * 11;
        ++count; // document.write(n + " ");
    }
}

var count = 0;
repeatingDigits(9);
document.write(count);```
</div>
</div>
</p>

<p>The number of integers with repeating groups of 3 or more digits are:  </p>

``` 3 digits:             10
 4 digits:            190
 5 digits:          2,800
 6 digits:         36,910
 7 digits:        457,390
 8 digits:      5,448,700
 9 digits:     63,154,810
10 digits:    717,431,590
11 digits:  8,025,277,600
12 digits: 88,684,382,710
```

Body:
A recursive solution:

Generate all numbers from 000 to 999, and use n % 111 to check
whether each is a multiple of 111. If it is, set a flag to true.

To each of these numbers, add a digit in the range 0-9, and if the number's flag was false, use (n % 1000) % 111 to check whether the three last digits are now equal, and if so, set the flag to true.

Repeat the previous step recursively, until you've reached 7 digits.

Then, for each 7-digit number, if its flag is true, add the full
range of 00-99 as the final two digits (generating a hundred 9-digit
numbers).

If the flag is false, use (n % 100) % 11 the check whether the last
two digits are equal, and if they are, add a third equal digit and
then the range 0-9 for the last digit (generating ten 9-digit
numbers).

If the last two digits weren't equal, add two digits equal to the
last digit (generating one 9-digit number).

Here's a simple JavaScript implementation. It's quick if you only count the results, but if you switch on the printing, it takes minutes rather than seconds for anything over 6 digits.

function repeatingDigits(len) {
    for (var n = 0; n < 1000; n++) {
        var flag = n % 111 ? false: true;
        add_digit(10 * n, flag, len - 3);
    }
}
function add_digit(n, flag, len) {
    for (var d = 0; d < 10; n++, d++) {
        var f = (!flag && (n % 1000) % 111 == 0) ? true : flag;
        if (len > 3) add_digit(10 * n, f, len - 1)
        else add_final(100 * n, f);
    }
}
function add_final(n, flag) {
    if (flag) {
        for (var d = 0; d < 100; n++, d++) {
            ++count; // document.write(n + " ");
        }
    }
    else if ((n % 10000) % 1100 == 0) {
        n += (n % 1000) / 10;
        for (var d = 0; d < 10; n++, d++) {
            ++count; // document.write(n + " ");
        }
    }
    else {
        n += ((n % 1000) / 100) * 11;
        ++count; // document.write(n + " ");
    }
}

var count = 0;
repeatingDigits(9);
document.write(count);

The number of integers with repeating groups of 3 or more digits are:

 3 digits:             10
 4 digits:            190
 5 digits:          2,800
 6 digits:         36,910
 7 digits:        457,390
 8 digits:      5,448,700
 9 digits:     63,154,810
10 digits:    717,431,590
11 digits:  8,025,277,600
12 digits: 88,684,382,710


来源: stackexchange

问:
Sorting XML on the Basis of Numeric Data in Javascript
Can anyone show me how to sort an XML file containing numeric data as well as string data stored in separate tags? For example I have a Charges (numeric) and Network (string) elements. Now I want to sort the XML file on the basis of Charges in Javascript.

any simple examples?

```<code> <Results>
        <network>Wateen</network>
        <speed>2048</speed>
        <type>Fixed</type>
         <install_charges>500</install_charges>
         <charges>20</charges>
    </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>2000</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>200</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>3000</charges>
   </Results>
</code>```

How do I sort the above XML according to the charges? It will also be nice if it is non-XSL method because XSL give lots of trouble.

答:
If you don't like to use XSL you can make an array containing the Results-elements and use the native sort-method of arrays:</p>

```<code><Results>
        <network>Wateen</network>
        <speed>2048</speed>
        <type>Fixed</type>
         <install_charges>500</install_charges>
         <charges>20</charges>
    </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>2000</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>200</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>3000</charges>
   </Results>
<script>

var nodeArray=[];
var nodeList=document.getElementsByTagName('Results')

//fill array
for(var i=0;i<nodeList.length;++i)
{
  nodeArray.push(nodeList[i]);
}

//sort array
nodeArray.sort(function(a,b)
              {
                return (
                         Number(a.getElementsByTagName('charges')[0].firstChild.data)
                          -
                         Number(b.getElementsByTagName('charges')[0].firstChild.data)
                        );
              });

//reorder nodes
for(var i=nodeArray.length-1;i>=0;i--)
{
  nodeArray[i]
   .parentNode
     .insertBefore(nodeArray[i],
                   nodeArray[i].parentNode.getElementsByTagName('Results')[0]);
}
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can anyone show me how to sort an XML file containing numeric data as well as string data stored in separate tags? For example I have a Charges (numeric) and Network (string) elements. Now I want to sort the XML file on the basis of Charges in Javascript.

any simple examples?

 <Results>
        <network>Wateen</network>
        <speed>2048</speed>
        <type>Fixed</type>
         <install_charges>500</install_charges>
         <charges>20</charges>
    </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>2000</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>200</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>3000</charges>
   </Results>

How do I sort the above XML according to the charges? It will also be nice if it is non-XSL method because XSL give lots of trouble.

Body:
If you don't like to use XSL you can make an array containing the Results-elements and use the native sort-method of arrays:

<Results>
        <network>Wateen</network>
        <speed>2048</speed>
        <type>Fixed</type>
         <install_charges>500</install_charges>
         <charges>20</charges>
    </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>2000</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>200</charges>
   </Results>

   <Results>
        <network>PTCL</network>
        <speed>4096</speed>
        <type>Fixed</type>
       <install_charges>0</install_charges>
       <charges>3000</charges>
   </Results>
<script>

var nodeArray=[];
var nodeList=document.getElementsByTagName('Results')

//fill array
for(var i=0;i<nodeList.length;++i)
{
  nodeArray.push(nodeList[i]);
}

//sort array
nodeArray.sort(function(a,b)
              {
                return (
                         Number(a.getElementsByTagName('charges')[0].firstChild.data)
                          -
                         Number(b.getElementsByTagName('charges')[0].firstChild.data)
                        );
              });

//reorder nodes
for(var i=nodeArray.length-1;i>=0;i--)
{
  nodeArray[i]
   .parentNode
     .insertBefore(nodeArray[i],
                   nodeArray[i].parentNode.getElementsByTagName('Results')[0]);
}
</script>

ContentLicense: CC BY-SA 2.5


问:
The bitwise operators should not be used in place of logical operators
```<code>//  How does this program work with ternary operator
#include <stdio.h>
int main()
{
    int x = 2, y = 5;
    (x &  y) ? printf("True ") : printf("False "); // How do we get output
    (x && y) ? printf("True ") : printf("False ");
    return 0;
}
</code>```

How does this program work?
How do the logical and bitwise operators work?

答:
In this program & is a bitwise operator which will do bitwise and operation on 2 and 5.

0000 0010<=2
0000 0101<=5
0000 0000<=output
```

So the first line will print False,
whereas second one is normal and operator for which both values are true(non zero numbers ) so 2 && 5 will result in true and the output will be True.

Body:
//  How does this program work with ternary operator
#include <stdio.h>
int main()
{
    int x = 2, y = 5;
    (x &  y) ? printf("True ") : printf("False "); // How do we get output
    (x && y) ? printf("True ") : printf("False ");
    return 0;
}

How does this program work?
How do the logical and bitwise operators work?

Body:
In this program & is a bitwise operator which will do bitwise and operation on 2 and 5.

0000 0010<=2
0000 0101<=5
0000 0000<=output

So the first line will print False,
whereas second one is normal and operator for which both values are true(non zero numbers ) so 2 && 5 will result in true and the output will be True.


问:
Want to add Edit "Page # of #" footer in CRYSTAL REPORT
New to Crystal Reports.
Trying to add the Following text to the footer of Crystal Report
Text "Shipment" + "(pg.)N of M
without having the word "Page" in the footer</p>

答:
Suppress Formula field.
Check "Suppress Blank Section"
Check "Clamp Page Footer"</p>


问:
How to host a wordpress project htdocs to hostinger.com server
Hi Iam create new website in wordpress (event management)in my system (test run in localhost).and im trying to host my website in hostinger.com. iam create my domain ,username,password.and cpanel databse name,username,password..
then iam connect filezila and transfer my localhost wordpress files all to my new host domain folder. and also pass my database.
then run (host address is ipsr.esy.es) the first homepage is loaded ,but iam click the about link its go to(localhost/wordpress/about)object not found. wordpress is my local foldername(xampp/htdocs/wordpress)
how to solve this problem??
what is the changes of htaccess.exe page</p>

答: Go to Phpmyadmin>Wp-options> Edit-->> Site Address from localhost/wordpress to your domain name</p>


问:
ng-model for `<input type="file"/>` (with directive DEMO)
I tried to use ng-model on input tag with type file:

```<code><input type="file" ng-model="vm.uploadme" />
</code>```

But after selecting a file, in controller, $scope.vm.uploadme is still undefined.

How do I get the selected file in my controller?

答:
I had to modify Endy's directive so that I can get Last Modified, lastModifiedDate, name, size, type, and data as well as be able to get an array of files. For those of you that needed these extra features, here you go.

UPDATE:
I found a bug where if you select the file(s) and then go to select again but cancel instead, the files are never deselected like it appears. So I updated my code to fix that.

```<code> .directive("fileread", function () {
        return {
            scope: {
                fileread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    var readers = [] ,
                        files = changeEvent.target.files ,
                        datas = [] ;
                    if(!files.length){
                        scope.$apply(function () {
                            scope.fileread = [];
                        });
                        return;
                    }
                    for ( var i = 0 ; i < files.length ; i++ ) {
                        readers[ i ] = new FileReader();
                        readers[ i ].index = i;
                        readers[ i ].onload = function (loadEvent) {
                            var index = loadEvent.target.index;
                            datas.push({
                                lastModified: files[index].lastModified,
                                lastModifiedDate: files[index].lastModifiedDate,
                                name: files[index].name,
                                size: files[index].size,
                                type: files[index].type,
                                data: loadEvent.target.result
                            });
                            if ( datas.length === files.length ){
                                scope.$apply(function () {
                                    scope.fileread = datas;
                                });
                            }
                        };
                        readers[ i ].readAsDataURL( files[i] );
                    }
                });

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

ContentLicense: CC BY-SA 4.0

Body:
I tried to use ng-model on input tag with type file:

<input type="file" ng-model="vm.uploadme" />

But after selecting a file, in controller, $scope.vm.uploadme is still undefined.

How do I get the selected file in my controller?

Body:
I had to modify Endy's directive so that I can get Last Modified, lastModifiedDate, name, size, type, and data as well as be able to get an array of files. For those of you that needed these extra features, here you go.

UPDATE:
I found a bug where if you select the file(s) and then go to select again but cancel instead, the files are never deselected like it appears. So I updated my code to fix that.

 .directive("fileread", function () {
        return {
            scope: {
                fileread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    var readers = [] ,
                        files = changeEvent.target.files ,
                        datas = [] ;
                    if(!files.length){
                        scope.$apply(function () {
                            scope.fileread = [];
                        });
                        return;
                    }
                    for ( var i = 0 ; i < files.length ; i++ ) {
                        readers[ i ] = new FileReader();
                        readers[ i ].index = i;
                        readers[ i ].onload = function (loadEvent) {
                            var index = loadEvent.target.index;
                            datas.push({
                                lastModified: files[index].lastModified,
                                lastModifiedDate: files[index].lastModifiedDate,
                                name: files[index].name,
                                size: files[index].size,
                                type: files[index].type,
                                data: loadEvent.target.result
                            });
                            if ( datas.length === files.length ){
                                scope.$apply(function () {
                                    scope.fileread = datas;
                                });
                            }
                        };
                        readers[ i ].readAsDataURL( files[i] );
                    }
                });

            }
        }
    });


问:
Merge and split columns in pandas dataframe
I want to know how to merge multiple columns, and split them again.

Input data

```<code>A B C
1 3 5
2 4 6
</code>```

Merge A, B, C to one column X

```<code>X
1
2
3
4
5
6
</code>```

Process something with X, then split X into A, B, C again. The number of rows for A, B, C is same(2).

```<code>A B C
1 3 5
2 4 6
</code>```

Is there any simple way for this work?

答:
un unwind in the way you'd like, you need to either unstack or ravel with order='F'

Option 1

```<code>def proc1(df):
    v = df.values
    s = v.ravel('F')
    s = s * 2
    return pd.DataFrame(s.reshape(v.shape, order='F'), df.index, df.columns)

proc1(df)

   A  B   C
0  2  6  10
1  4  8  12
</code>```

Option 2

```<code>def proc2(df):
    return df.unstack().mul(2).unstack(0)

proc2(df)

   A  B   C
0  2  6  10
1  4  8  12
</code>```

Body:
I want to know how to merge multiple columns, and split them again.

Input data

A B C
1 3 5
2 4 6

Merge A, B, C to one column X

X
1
2
3
4
5
6

Process something with X, then split X into A, B, C again. The number of rows for A, B, C is same(2).

A B C
1 3 5
2 4 6

Is there any simple way for this work?

Body:
un unwind in the way you'd like, you need to either unstack or ravel with order='F'

Option 1

def proc1(df):
    v = df.values
    s = v.ravel('F')
    s = s * 2
    return pd.DataFrame(s.reshape(v.shape, order='F'), df.index, df.columns)

proc1(df)

   A  B   C
0  2  6  10
1  4  8  12

Option 2

def proc2(df):
    return df.unstack().mul(2).unstack(0)

proc2(df)

   A  B   C
0  2  6  10
1  4  8  12


问:
How do I reference a global variable from within an inline event handler?
JavaScript:

```<code> lang = {'edit': 'Edit'}; // global variable
</code>```

HTML:

```<code> <select onchange="alert(lang.edit)"> // alerts undefined
</code>```

Whenever the event fires, it alerts "undefined". The lang variable is global, so why can't the inline event handler code reference it?

答:
Every global object in javascript is a property of the window object. So you should write
window.lang = {'edit': 'Edit'};</p>

Body:
JavaScript:

 lang = {'edit': 'Edit'}; // global variable

HTML:

 <select onchange="alert(lang.edit)"> // alerts undefined

Whenever the event fires, it alerts "undefined". The lang variable is global, so why can't the inline event handler code reference it?


问:
UsernameToken with attribute wsu:Id="SecurityToken-..."
I am using WSS4J 1.6 and Axis 1.4.

I am creating the UsernameToken using org.apache.ws.security.message.WSSecUsernameToken.

What I do not understand is the wsu:Id attribute.
According to the web service specs it has to be in the form of "SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78".

No matter what I do the wsu:Id attribute contains "UsernameToken-123" but, according to the web service specs it has to be on the form "SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78".

I have absolutely no idea how to achieve this and Google has run dry.

So, can anyone tell me what I need to do?

The UsernameToken xml as it comes is now.

```<code><wsse:UsernameToken wsu:Id="UsernameToken-133"
     xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
     xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:Username>stan</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">secrit</wsse:Password>
  </wsse:UsernameToken>
</code>```

The UsernameToken xml as I want it to come out.

```<code><wsse:UsernameToken wsu:Id="SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78"
     xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
     xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:Username>stan</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">secrit</wsse:Password>
  </wsse:UsernameToken>
</code>```

Here is the code I use to create the soap message.

```<code>public String soapTest() throws Exception {
    MessageFactoryImpl messageFactory = new MessageFactoryImpl();
    SOAPMessage soapMessage = null;
    soapMessage = messageFactory.createMessage();
    Message message = (Message)soapMessage;
    SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
    unsignedEnvelope.addNamespaceDeclaration( "xsd", "http://www.w3.org/2001/XMLSchema" );
    unsignedEnvelope.addNamespaceDeclaration( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
    unsignedEnvelope.addNamespaceDeclaration( "enc", "http://schemas.xmlsoap.org/soap/encoding/" );
    unsignedEnvelope.addNamespaceDeclaration( "env", "http://schemas.xmlsoap.org/soap/envelop/" );
    unsignedEnvelope.addNamespaceDeclaration( "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
    unsignedEnvelope.addNamespaceDeclaration( "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" );
    unsignedEnvelope.addNamespaceDeclaration( "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" );
    unsignedEnvelope.addNamespaceDeclaration( "ws", "http://ws.stupidsoap.com" );

    SOAPBody soapMsgBody = (SOAPBody)soapMessage.getSOAPBody();
    org.apache.axis.message.SOAPEnvelope soapMsgEnvelope = ((Message)soapMessage).getSOAPEnvelope();

    SOAPBodyElement be = (SOAPBodyElement)soapMsgBody.addChildElement( soapMsgEnvelope.createName( "addTwoNumbers", "", "http://ws.stupidsoap.com" ) );
    be.addChildElement( "number1" ).addTextNode( "5" );
    be.addChildElement( "number2" ).addTextNode( "10" );

    org.w3c.dom.Document doc = (org.w3c.dom.Document)soapMsgEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader( doc );

    WSSecUsernameToken utBuilder = new WSSecUsernameToken();
    utBuilder.setPasswordType( WSConstants.PASSWORD_TEXT );
    utBuilder.setUserInfo( "stan", "secrit" );
    utBuilder.addNonce();
    utBuilder.addCreated();
    utBuilder.build( doc, secHeader );

    return org.apache.ws.security.util.XMLUtils.PrettyDocumentToString( doc );
}
</code>```

答:
Try this:</p>

```<code>WsuIdAllocator idAllocator = new WsuIdAllocator() {
    public String createId(String prefix, Object o) {
        return "SecurityToken-" + UUIDGenerator.getUUID();
    }

    public String createSecureId(String prefix, Object o) {
        return "SecurityToken-" + UUIDGenerator.getUUID();
    }
};

WSSecUsernameToken utBuilder = new WSSecUsernameToken();
WSSConfig wsConfig = new WSSConfig();
wsConfig.setIdAllocator(idAllocator);

utBuilder.setWsConfig(wsConfig);
utBuilder.setPasswordType( WSConstants.PASSWORD_TEXT );
utBuilder.setUserInfo( "stan", "secrit" );
</code>```

Body:
I am using WSS4J 1.6 and Axis 1.4.

I am creating the UsernameToken using org.apache.ws.security.message.WSSecUsernameToken.

What I do not understand is the wsu:Id attribute.
According to the web service specs it has to be in the form of "SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78".

No matter what I do the wsu:Id attribute contains "UsernameToken-123" but, according to the web service specs it has to be on the form "SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78".

I have absolutely no idea how to achieve this and Google has run dry.

So, can anyone tell me what I need to do?

The UsernameToken xml as it comes is now.

<wsse:UsernameToken wsu:Id="UsernameToken-133"
     xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
     xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:Username>stan</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">secrit</wsse:Password>
  </wsse:UsernameToken>

The UsernameToken xml as I want it to come out.

<wsse:UsernameToken wsu:Id="SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78"
     xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
     xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
    <wsse:Username>stan</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">secrit</wsse:Password>
  </wsse:UsernameToken>

Here is the code I use to create the soap message.

public String soapTest() throws Exception {
    MessageFactoryImpl messageFactory = new MessageFactoryImpl();
    SOAPMessage soapMessage = null;
    soapMessage = messageFactory.createMessage();
    Message message = (Message)soapMessage;
    SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
    unsignedEnvelope.addNamespaceDeclaration( "xsd", "http://www.w3.org/2001/XMLSchema" );
    unsignedEnvelope.addNamespaceDeclaration( "xsi", "http://www.w3.org/2001/XMLSchema-instance" );
    unsignedEnvelope.addNamespaceDeclaration( "enc", "http://schemas.xmlsoap.org/soap/encoding/" );
    unsignedEnvelope.addNamespaceDeclaration( "env", "http://schemas.xmlsoap.org/soap/envelop/" );
    unsignedEnvelope.addNamespaceDeclaration( "wsa", "http://schemas.xmlsoap.org/ws/2004/03/addressing" );
    unsignedEnvelope.addNamespaceDeclaration( "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" );
    unsignedEnvelope.addNamespaceDeclaration( "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" );
    unsignedEnvelope.addNamespaceDeclaration( "ws", "http://ws.stupidsoap.com" );

    SOAPBody soapMsgBody = (SOAPBody)soapMessage.getSOAPBody();
    org.apache.axis.message.SOAPEnvelope soapMsgEnvelope = ((Message)soapMessage).getSOAPEnvelope();

    SOAPBodyElement be = (SOAPBodyElement)soapMsgBody.addChildElement( soapMsgEnvelope.createName( "addTwoNumbers", "", "http://ws.stupidsoap.com" ) );
    be.addChildElement( "number1" ).addTextNode( "5" );
    be.addChildElement( "number2" ).addTextNode( "10" );

    org.w3c.dom.Document doc = (org.w3c.dom.Document)soapMsgEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader( doc );

    WSSecUsernameToken utBuilder = new WSSecUsernameToken();
    utBuilder.setPasswordType( WSConstants.PASSWORD_TEXT );
    utBuilder.setUserInfo( "stan", "secrit" );
    utBuilder.addNonce();
    utBuilder.addCreated();
    utBuilder.build( doc, secHeader );

    return org.apache.ws.security.util.XMLUtils.PrettyDocumentToString( doc );
}

Body:
Try this:

WsuIdAllocator idAllocator = new WsuIdAllocator() {
    public String createId(String prefix, Object o) {
        return "SecurityToken-" + UUIDGenerator.getUUID();
    }

    public String createSecureId(String prefix, Object o) {
        return "SecurityToken-" + UUIDGenerator.getUUID();
    }
};

WSSecUsernameToken utBuilder = new WSSecUsernameToken();
WSSConfig wsConfig = new WSSConfig();
wsConfig.setIdAllocator(idAllocator);

utBuilder.setWsConfig(wsConfig);
utBuilder.setPasswordType( WSConstants.PASSWORD_TEXT );
utBuilder.setUserInfo( "stan", "secrit" );


问:
Id selector is formatted weirdly
Sorry for the title, but I don't know how to call this question. I'm using id as selector to format my ajax. But one of my div have a special format, and I don't know why. Moreover, the format generated, can't be include into my js file.

Normally the div is formated as following:

```<code><div id= 'post_iter(<%=@post.id%>)'></div>
</code>```

And when I inspect the file, the div is marked as #post_iter(4)

But when I try to copy the path, I have something like that:

```<code>#post_iter\28 4\29
</code>```

答:
The special characters are taking because of the braces

Instead of the braces try using

```<code><div id= 'post_iter_<%=@post.id%>'></div>
</code>```

Title: Id selector is formatted weirdly

Body:
Sorry for the title, but I don't know how to call this question. I'm using id as selector to format my ajax. But one of my div have a special format, and I don't know why. Moreover, the format generated, can't be include into my js file.

Normally the div is formated as following:

<div id= 'post_iter(<%=@post.id%>)'>

And when I inspect the file, the div is marked as #post_iter(4)

But when I try to copy the path, I have something like that:

#post_iter\28 4\29

Body:
The special characters are taking because of the braces

Instead of the braces try using

<div id= 'post_iter_<%=@post.id%>'></div>


问:
Jenkins login issue
Just setup jenkins on Ubuntu v16 laptop.

I have followed the installation steps from this page

After I setup, I fetched the setup password from /var/logs/jenkins/jenkins.log & was able to setup the admin user/password. I made a note of the creds.

I was also able to access & setup a simple helloworld pipeline job.

I stepped out and came back to my desk after about 20mins. The session has logged me out & I am not able to log-in with the creds. I have tried removing jenkins & setting it back. It still seems to retain the creds somewhere & now I am getting to the login page with bad credentials error everytime.

```<code>Invalid login information. Please try again.
Try again
If you are a system administrator and suspect this to be a configuration problem, see the server console output for more details.
</code>```

Need help figuring out what is happening. My logs have no useful information related to this error.

答:
As stated in this answer, the quickest way to get around this would be to disable security altogether by making the following change to your Jenkins config.xml file:

```<code><useSecurity>true</useSecurity>
</code>```

After rebooting your Jenkins instance, you should be able to return to the admin page and set everything up from there.

An alternate solution to this is mentioned here, which should accomplish what you want whereby preserving the security of your Jenkins instance (thus making this a more ideal solution). You would instead update the passwordHash section of your Jenkins config.xml file:

```<code><passwordHash>#jbcrypt:$2a$10$razd3L1aXndFfBNHO95aj.IVrFydsxkcQCcLmujmFQzll3hcUrY7S</passwordHash>
</code>```

The passwordHash section of the config.xml file is a child tag under <hudson.security.HudsonPrivateSecurityRealm_-Details>.

You would again need to reboot Jenkins once this change has been made, and you would login using the password 'test'. Of course, you could provide your own hash of a different password which would be advisable.

Title: Jenkins login issue

Body:
Just setup jenkins on Ubuntu v16 laptop.

I have followed the installation steps from this page

After I setup, I fetched the setup password from /var/logs/jenkins/jenkins.log & was able to setup the admin user/password. I made a note of the creds.

I was also able to access & setup a simple helloworld pipeline job.

I stepped out and came back to my desk after about 20mins. The session has logged me out & I am not able to log-in with the creds. I have tried removing jenkins & setting it back. It still seems to retain the creds somewhere & now I am getting to the login page with bad credentials error everytime.

Invalid login information. Please try again.
Try again
If you are a system administrator and suspect this to be a configuration problem, see the server console output for more details.

Need help figuring out what is happening. My logs have no useful information related to this error.

Body:
As stated in this answer, the quickest way to get around this would be to disable security altogether by making the following change to your Jenkins config.xml file:

<useSecurity>true</useSecurity>

After rebooting your Jenkins instance, you should be able to return to the admin page and set everything up from there.

An alternate solution to this is mentioned here, which should accomplish what you want whereby preserving the security of your Jenkins instance (thus making this a more ideal solution). You would instead update the passwordHash section of your Jenkins config.xml file:

<passwordHash>#jbcrypt:$2a$10$razd3L1aXndFfBNHO95aj.IVrFydsxkcQCcLmujmFQzll3hcUrY7S</passwordHash>

The passwordHash section of the config.xml file is a child tag under <hudson.security.HudsonPrivateSecurityRealm_-Details>.

You would again need to reboot Jenkins once this change has been made, and you would login using the password 'test'. Of course, you could provide your own hash of a different password which would be advisable.


问:
Universal deeplinks do not open the app the first time they are tried
When the app installs, I see a request to https://example.com/.well-known/apple-app-site-association, which gets a 200 response with the proper json response.

Odd thing 1: the app then goes on to try to request /apple-app-site-association which fails as the file not there in the root. Why would it fall-back to this file if it already has the .well-known one?

After the app finishes opening, I can go into Notes or something and click on a deeplink e.g. https://example.com/some/path, this will open in safari.

Odd thing 2: before the site opens in safari, there are several requests to both .well-known/apple-app-site-association and /apple-app-site-association. I am pretty sure that the .well-known request comes first, and there is one more to the .well-known version than the root one.

After that, I can now go back to Notes and click on the deeplink and it now will correctly open the app. All is right with the world.

Any ideas what could be wrong with the first .well-known responses that causes them to not work and to generate the fallback requests? Anyone else with this problem or any ideas?

Below is a redacted screenshot from Charles (app install finishes at 11:24:18), and a redacted response from .well-known/apple-app-site-association.

```<code>HTTP/1.1 200 OK
Content-Type: application/json
Last-Modified: Tue, 06 Jun 2017 00:50:40 GMT
Accept-Ranges: bytes
ETag: "[redacted]"
Content-Length: 156
Connection: Keep-alive

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "[redacted].com.[redacted]",
                "paths": [ "*" ]
            }
        ]
    }
}
</code>```

答:
iOS scrapes both locations every time. I'm not sure if there is a defined order of preference if the two files don't match, but I know you run into strange behavior in that situation. Try to avoid it.

It appears you do indeed have some sort of configuration issue causing the file not to validate properly on the first attempt. Since you've redacted all the details that might let me look into that, unfortunately I can't be of much help there.

The re-scraping on link click after initial failure is new — I haven't seen this before. It must be a recent addition to help catch situations that would otherwise result in broken Universal Link behavior (network congestion during install, etc.). If you're able to debug your initial scrape error, this should stop occurring.

Body:
When the app installs, I see a request to https://example.com/.well-known/apple-app-site-association, which gets a 200 response with the proper json response.

Odd thing 1: the app then goes on to try to request /apple-app-site-association which fails as the file not there in the root. Why would it fall-back to this file if it already has the .well-known one?

After the app finishes opening, I can go into Notes or something and click on a deeplink e.g. https://example.com/some/path, this will open in safari.

Odd thing 2: before the site opens in safari, there are several requests to both .well-known/apple-app-site-association and /apple-app-site-association. I am pretty sure that the .well-known request comes first, and there is one more to the .well-known version than the root one.

After that, I can now go back to Notes and click on the deeplink and it now will correctly open the app. All is right with the world.

Any ideas what could be wrong with the first .well-known responses that causes them to not work and to generate the fallback requests? Anyone else with this problem or any ideas?

Below is a redacted screenshot from Charles (app install finishes at 11:24:18), and a redacted response from .well-known/apple-app-site-association.

HTTP/1.1 200 OK
Content-Type: application/json
Last-Modified: Tue, 06 Jun 2017 00:50:40 GMT
Accept-Ranges: bytes
ETag: "[redacted]"
Content-Length: 156
Connection: Keep-alive

{
    "applinks": {
        "apps": [],
        "details": [
            {
                "appID": "[redacted].com.[redacted]",
                "paths": [ "*" ]
            }
        ]
    }
}


问:
How to get TFS2015 Build (Build.vnext) and NuGet package restore to use custom package sources
I'm trying to get our TFS2015 Build (TFSBuild vnext) going along with VS Team Services.

Thus far most blogs and documentation has been helpful, except for when trying to build a project that uses custom package sources for NuGet automatic package restore.

I've successfully deployed an a Team Services Build Agent (the new mechanism for builds) and all seemed to go well until the build task to Restore NuGet packages failed.

The failure was due to custom/private package source not being picked up from the installed VS configuration, so those packages could not be found. The traditional packages from the default NuGet package feed did restore without issue.

How do I specify the additional package sources for NuGet to use when using an agent?

EDIT: vcastro asked about the NuGet Installer build step and defining paths in the configuration of that build step. The above is using the Visual Studio Build step and the integrated option to have NuGet restore packages. Refer this image for reference:

答:
If you are having trouble getting this to work on UWP ONLY, then ensure that you have the CASE of the package name spelt correctly. If the case is wrong, then (for UWP only) our build server fails the build.

for instance, if you have a package called Com.Company.Components and update the package using "install-package com.company.components" (note the case of the initial letter) then the UWP build on the build server may fail to find the package in your local store.


问:
Need help in JavaScript/JQuery
need some help.. i want the bin to hide on load and i have a draggable div, so when i drag the div the bin should show and when i leave the div the bin should hide again?</p>

```<code><html>
<head>
  <style>
  .box{
    border: 1px solid black;
  }
  </style>

  <script>
  window.onload = function() { document.getElementById('myDIV').style.display = 'none'; };
  function showImg(){
    var x = document.getElementById('myDIV');
    if (x.style.display === 'none') { x.style.display = 'block'; }
    else { x.style.display = 'none'; }
  }
  </script>

</head>

<body>
  <div id="show" onclick="showImg()" class="box">
    when this div is select and drag the bin should be shown
  </div>

  <div id="myDIV">
    <img src="img/upload.png"/>
  </div>

</body>
</html>
</code>```

答:
I think you need ondrag event instead of click event.

```<code>   ondrag="function()"
   ondrop="function()"
   ondragover="function()"
   ondragstart="function()"
</code>```

Title: Need help in JavaScript/JQuery

Body:
need some help.. i want the bin to hide on load and i have a draggable div, so when i drag the div the bin should show and when i leave the div the bin should hide again?

    when this div is select and drag the bin should be shown

Body:
I think you need ondrag event instead of click event.

   ondrag="function()"
   ondrop="function()"
   ondragover="function()"
   ondragstart="function()"


问:
XAML build not able to run Unit Test
I am trying to run Nunit Test using Visual Studio test Runner from XAML build in TFS,but i am getting error saying

TF900547: The directory containing the assemblies for the Visual Studio Test Runner is not valid ''.

答:
Based on your history, I assume you are using VSTS, you can refer to these steps to run Nunit test:

Create a unit test project via VS

Install NUnit and NUnit3TestAdapter packages

Add solution to source control (if the package files not added to the source control, you can refer to the steps below)

Open Source Control Explorer in VS

Add a new folder (e.g. Tools) and add Nuget.exe to the source control

Add bat file to your test project (For example: Tools\nuget35.exe restore NUTest2\NUTest2.sln)

Open XAML build definition and map Tools source folder to agent

Select Process section

Choose TfvcTemplate.12.xaml build template

In the Advance section of Build, specify Pre-build script path with previous bat file.

Title: XAML build not able to run Unit Test


问:
Extract data from fields which contains multiple values
I am new to python programming and data mining. I am trying to read data from .csv file and store them as the list of dictionaries for analysis. But my data has multiple alternatives for a single column of values.
Here is my Data sample

The screenshot of my data along with Highlighter

Since my column Fuels has Gas/Electricity I have City MPG as 16/81. However when I read this into my list of dictionaries, it isn't much of a problem, but if I want to compute an average or sum it gives an error.

I want to have such columns separated when I read the data into Python.

```<code>import csv

with open('mpg.csv') as f:
 a = [{k: (v) for k, v in row.items()}
  for row in csv.DictReader(f, skipinitialspace=True)]
print(a, '\n')
print(len(a))  # simply printing the data
print(a[0].keys()) # printing the Headers of the data
z = sum(float(d['City MPG']) for d in a) / len(a) # Error code
print(z)
</code>```

The error is ValueError: could not convert string to float: '33/81.
I understand the error.

I am thinking of inserting such values in a Map, but not sure about the code.

答:
You can split the MPG fields on the '/', float them, and then select the first one with [0], or the second with [1]:

```<code>z = sum(float(d['City MPG'].split('/')[0]) for d in a) / len(a)
</code>```

If you want the averages of both the first and the second values (for gas and electricity respecively), it could be done like this:

```<code>z = [d['City MPG'].split('/') for d in a]
city_mpg_gas, city_mpg_elec = [sum(float(values[i]) for values in z) / len(a)
                                    for i in range(len(a))]
print('city_mpg_gas:', city_mpg_gas)
print('city_mpg_elec:', city_mpg_elec)
</code>```

Although I've never heard of a gallon of electricity... ;-)

Body:
I am new to python programming and data mining. I am trying to read data from .csv file and store them as the list of dictionaries for analysis. But my data has multiple alternatives for a single column of values.
Here is my Data sample

The screenshot of my data along with Highlighter

Since my column Fuels has Gas/Electricity I have City MPG as 16/81. However when I read this into my list of dictionaries, it isn't much of a problem, but if I want to compute an average or sum it gives an error.

I want to have such columns separated when I read the data into Python.

import csv

with open('mpg.csv') as f:
 a = [{k: (v) for k, v in row.items()}
  for row in csv.DictReader(f, skipinitialspace=True)]
print(a, '\n')
print(len(a))  # simply printing the data
print(a[0].keys()) # printing the Headers of the data
z = sum(float(d['City MPG']) for d in a) / len(a) # Error code
print(z)

The error is ValueError: could not convert string to float: '33/81.
I understand the error.

I am thinking of inserting such values in a Map, but not sure about the code.

Body:
You can split the MPG fields on the '/', float them, and then select the first one with [0], or the second with [1]:

z = sum(float(d['City MPG'].split('/')[0]) for d in a) / len(a)

If you want the averages of both the first and the second values (for gas and electricity respecively), it could be done like this:

z = [d['City MPG'].split('/') for d in a]
city_mpg_gas, city_mpg_elec = [sum(float(values[i]) for values in z) / len(a)
                                    for i in range(len(a))]
print('city_mpg_gas:', city_mpg_gas)
print('city_mpg_elec:', city_mpg_elec)

Although I've never heard of a gallon of electricity... ;-)


问:
Splitting <dbl [2]> result of Sparklyr as a spark object
I have a problem with splitting the outcome of my random forest generated by Sparklyr.

I'm using the following code to generate a model, which predict a {0 | 1} value and predict the outcome for a specified validation set.

```<code>model <- ml_random_forest( tbl(sc,"train_set") , formulea)

prediction <- sdf_predict( model, tbl(sc,"validation_set") ) %>% select(account_no, probability , prediction)
</code>```

This generated prediction object looks like:

```<code>Source:   query [3.744e+06 x 3]
Database: spark connection master=yarn-client app=Dev - model v.11 local=FALSE

   account_no probability prediction
        <dbl>      <list>      <dbl>
1     5053177   <dbl [2]>          1
2     6508441   <dbl [2]>          1
3     7805527   <dbl [2]>          1
4    10001696   <dbl [2]>          1
5    10004230   <dbl [2]>          1
6    10005647   <dbl [2]>          1
7    10006029   <dbl [2]>          1
8    10018558   <dbl [2]>          0
9    10019161   <dbl [2]>          1
10   10031652   <dbl [2]>          1
# ... with 3.744e+06 more rows
</code>```

How can i split the  list in Spark, to get only the first number of the list. Something like this ...

```<code>   account_no probability
        <dbl>      <dbl>
1     5053177   <0.9726>
2     6508441   <0.1234>
</code>```

Hope someone can help to solve this issue.

Greetings, Jitske

答:
Install the latest devel version off GitHub and look up ?sdf_separate_column:

```<code>prediction %>%
  sdf_separate_column("probability", c("p0", "p1"))
</code>```

Body:
I have a problem with splitting the outcome of my random forest generated by Sparklyr.

I'm using the following code to generate a model, which predict a {0 | 1} value and predict the outcome for a specified validation set.

model <- ml_random_forest( tbl(sc,"train_set") , formulea)

prediction <- sdf_predict( model, tbl(sc,"validation_set") ) %>% select(account_no, probability , prediction)

This generated prediction object looks like:

Source:   query [3.744e+06 x 3]
Database: spark connection master=yarn-client app=Dev - model v.11 local=FALSE

   account_no probability prediction
        <dbl>      <list>      <dbl>
1     5053177   <dbl [2]>          1
2     6508441   <dbl [2]>          1
3     7805527   <dbl [2]>          1
4    10001696   <dbl [2]>          1
5    10004230   <dbl [2]>          1
6    10005647   <dbl [2]>          1
7    10006029   <dbl [2]>          1
8    10018558   <dbl [2]>          0
9    10019161   <dbl [2]>          1
10   10031652   <dbl [2]>          1
# ... with 3.744e+06 more rows

How can i split the  list in Spark, to get only the first number of the list. Something like this ...

   account_no probability
        <dbl>      <dbl>
1     5053177   <0.9726>
2     6508441   <0.1234>

Hope someone can help to solve this issue.

Greetings, Jitske

Body:
Install the latest devel version off GitHub and look up ?sdf_separate_column:

prediction %>%
  sdf_separate_column("probability", c("p0", "p1"))


答: <%=@post.id%> is ASP code, so theres that you have to take into consideration. So it gets prcessed to 4 from what you get.

Title: Id selector is formatted weirdly


答:
This will work.</p>

```<code>@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <style>
        .box {
            border: 1px solid black;
        }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        window.onload = function () { document.getElementById('myDIV').style.display = 'none'; };
        function showImg() {
            var x = document.getElementById('myDIV');
            if (x.style.display === 'none') {
                x.style.display = 'block';
            }
            else { x.style.display = 'none'; }
        }

        $(function () {
            $("#show").draggable();
        });
    </script>

</head>

<body>
    <div id="show" onclick="showImg()" class="box">
        when this div is select and drag the bin should be shown
    </div>

    <div id="myDIV">
        <img src="~/Images/untitled.gif" />
        @*<img src="img/upload.png" />*@
    </div>

</body>
</html>
</code>```

Title: Need help in JavaScript/JQuery

Body:
This will work.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <style>
        .box {
            border: 1px solid black;
        }
    </style>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        window.onload = function () { document.getElementById('myDIV').style.display = 'none'; };
        function showImg() {
            var x = document.getElementById('myDIV');
            if (x.style.display === 'none') {
                x.style.display = 'block';
            }
            else { x.style.display = 'none'; }
        }

        $(function () {
            $("#show").draggable();
        });
    </script>

</head>

<body>
    <div id="show" onclick="showImg()" class="box">
        when this div is select and drag the bin should be shown
    </div>

    <div id="myDIV">
        <img src="~/Images/untitled.gif" />
        @*<img src="img/upload.png" />*@
    </div>

</body>
</html>


问:
Passing a parameter that could be null to a method
I have the following method call and for some reason the syntax in C# is not working correctly. If the pkg.Library.description is null then set it to a string.."No Folder Selected". Is there another way to do this?</p>

```<code>SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}
</code>```

答:
I am not sure why what you have written wouldn't work, but another way to do this would be to use the null coalescing operator, represented with a double question mark, like so:

var x = y ?? z

If y is not null, x is set to y; if y is null, x is set to z.

Here is documentation on the operator.

Body:
I have the following method call and for some reason the syntax in C# is not working correctly. If the pkg.Library.description is null then set it to a string.."No Folder Selected". Is there another way to do this?

SendEmail (pkg.libraryfolder.description == null ? "No Folder Selected" :pkg.libraryfolder.description)

public void SendEmail(string folderdescription)
{
////
}


问:
Why my eclipse need to export v7.jar and v4.jar?
Now，I use  eclipse for android，but it has some questions if  not to export  v7.jar and v4.jar.Can you tell me why?</p>

答:
just read this

https://developer.android.com/topic/libraries/support-library/index.html

and Google already dropped support for Eclipse Android Developer Tool, so move to Android Studio


问:
NotRegistered Response from FCM even when the app is installed on a users mobile device
We just migrated from GCM to FCM. For tracking uninstalls we send a silent notification to all our users and if we get a "NotRegistered" response we treat the user as uninstalled. Since the last few days, we started getting "NotRegistered" for some of the users who have not uninstalled the app.

On querying the FCM diagnostics for the same Registration token the messages are being delivered but they are continuously in accepted state.Attached is the screenshot. The error code I received while sending the message is still "NotRegistered" . The user has not uninstalled the app.Attached is the screenshot.

We are getting "Not Registered" since 1st of June while messages are in accepted state till 4th of June. This image shows message Ids of notifications sent till 4th of June:

Would like a clarification on the following:

Why did the status of the FCM registration token change to NotRegistered. There was no upgrade since the last month and the user has been using the latest version since a long time?

Is checking FCM error code "NotRegistered" a full proof way to track uninstalls? Are there better mechanisms available?

答:
Reasons as to why a NotRegistered happens are stated in the docs, the third one, being a probable reason for your case (emphasis mine):

An existing registration token may cease to be valid in a number of scenarios, including:

If the client app unregisters with FCM.

If the client app is automatically unregistered, which can happen if the user uninstalls the application. For example, on iOS, if the APNS Feedback Service reported the APNS token as invalid.

If the registration token expires (for example, Google might decide to refresh registration tokens, or the APNS token has expired for iOS devices).

If the client app is updated but the new version is not configured to receive messages.

For all these cases, remove this registration token from the app server and stop using it to send messages.

Nope. As I linked above, the NotRegistered error doesn't only trigger during uninstalls. AFAIK, there is no standard way of doing this. Have a look at some of these posts.


问:
Error creating folder with OneDrive API - Javascript
I'm having issues creating a folder via the onedrive api. I am able to get at my main drive, access files, and get file information. When I try to create a folder, I am getting an error. I am developing this with Anuglar on top of Ionic. There error I am receiving is

```<code>"error": {
    "code": "BadRequest",
    "message": "Entity only allows writes with a JSON Content-Type header.",
    "innerError": {
      "request-id": "5773433a-bf81-4226-bdc0-12beda3e6b03",
      "date": "2017-06-05T23:49:57"
    }
  }
</code>```

I am have the correct token (I am using this in other functions and if I do not include the token in the header, I get a different error). Here is the code that is being called.

```<code>public createFolder(token) {
    this.http.post('https://graph.microsoft.com/v1.0/me/drive/root/children', {"name": "FolderA", "folder": {"childCount": 0}}, {"Authorization": "Bearer " + token, "Content-Type": "application/json"})
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error.status);
        console.log(error.error);
        console.log(error.headers);
      })
  }
</code>```

答:
According to docs Config should have headers under "headers" key:</p>

```<code>{"headers": {"Authorization": "Bearer " + token, "Content-Type": "application/json"}}
</code>```

Body:
I'm having issues creating a folder via the onedrive api. I am able to get at my main drive, access files, and get file information. When I try to create a folder, I am getting an error. I am developing this with Anuglar on top of Ionic. There error I am receiving is

"error": {
    "code": "BadRequest",
    "message": "Entity only allows writes with a JSON Content-Type header.",
    "innerError": {
      "request-id": "5773433a-bf81-4226-bdc0-12beda3e6b03",
      "date": "2017-06-05T23:49:57"
    }
  }

I am have the correct token (I am using this in other functions and if I do not include the token in the header, I get a different error). Here is the code that is being called.

public createFolder(token) {
    this.http.post('https://graph.microsoft.com/v1.0/me/drive/root/children', {"name": "FolderA", "folder": {"childCount": 0}}, {"Authorization": "Bearer " + token, "Content-Type": "application/json"})
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error.status);
        console.log(error.error);
        console.log(error.headers);
      })
  }

Body:
According to docs Config should have headers under "headers" key:

{"headers": {"Authorization": "Bearer " + token, "Content-Type": "application/json"}}


问:
Ajax call is not working in Django?
This is my ajax call:

```<code><script>
    $(document).ready(function(){
        $("#butt2").click(function(){
            $.ajax({
                url:'{% url 'task:deletetask' %}',
                data:{'id':2 },
                type:"GET",
                success:function(text){
                    $("#task2").hide();
                    alert(text);
            }});
        });
    });

</script>
</code>```

This is my view function:

```<code>class DeleteTaskView(generic.View):
    def get(self,request):
        id = request.GET.get('id',None)
        Task.objects.get(id=id).delete()
        return JsonResponse("Task Removed")
</code>```

This is the url:

```<code>url(r'user/task/delete/$',views.DeleteTaskView.as_view(),name='deletetask'),
</code>```

If I remove the ajax call, and simply add  alert function, then it is properly working, means jquery is working, there is some problem with ajax call only. Help !

Edit: I change the url function to :

```<code>url : "{% url 'task:deletetask' %}",
</code>```

Now the item is getting deleted from database but in success response hide and alert function is not working.

答:
make sure JS reloaded.

Try to test url (use full link)

Open Broswer and press F12 ~> console and show me the error... server or client bug?

Title: Ajax call is not working in Django?

Body:
This is my ajax call:

This is my view function:

class DeleteTaskView(generic.View):
    def get(self,request):
        id = request.GET.get('id',None)
        Task.objects.get(id=id).delete()
        return JsonResponse("Task Removed")

This is the url:

url(r'user/task/delete/$',views.DeleteTaskView.as_view(),name='deletetask'),

If I remove the ajax call, and simply add  alert function, then it is properly working, means jquery is working, there is some problem with ajax call only. Help !

Edit: I change the url function to :

url : "{% url 'task:deletetask' %}",

Now the item is getting deleted from database but in success response hide and alert function is not working.


问:
New Issue, defining Fields/RecordsWAS Why can't I use DAO in VBA Program written in Excel 2013
Please refer to latest comment by me as I have one more follow up question about column names/reassigning header row.  Thanks! KDL!

OK, I am able to Open the "database" so I can set up queries of recordsets using DAO, and I have figured out how to define a named range so I have a variable that can act as the "Field Name".  I am having an issue with VBA code to insert that Named range into the SELECT SQL statement.  This is the relevant section of code that I am still having a problem with

BEGIN CODE
'**********************************
Dim db as DAO.Database
Dim rst as DAO.Recordset

Dim refRngItemSKU As Excel.Range
Dim LastRowAsIngeger as Integer
Dim INVENTORYTABLE as String
Dim strSelectRS as String

' ************************

LastRowAsInteger = 1764    'Value set in code for now, will be formula later to make dynamic

Set refRngItemSKU = ThisWorkbook.Worksheets("Vendor Inventory").Range("A11:A" & LastRowAsInteger)

' ******* NOTE when I insert refRngItemSKU.select the correct range of cells are selected  **********

INVENTORYTABLE = "D:\My Documents\Leavers Switches And More\INVENTORY\COLLECTIONS AND DISTRIBUTOR  INVENTORY\Model Train Inventory - Updated 6-7-2017.xlsm"

Set db = DBEngine.OpenDatabase(INVENTORYTABLE, False, False, "Excel 12.0;")

strSelectRS = "SELECT * FROM [Vendor Inventory$] WHERE [refrngitemsku$] IS NOT NULL"

Set rst = db.OpenRecordset(strSelectRS)

'**********************************************
END OF CODE

Now everything up to the last line of code works.  When it reaches the "Set rst" line, Error 3061 comes up. The error states "Too Few Parameters. Expected 1".  When I am in Debug mode, I notice the "refrngitemsku" variable is not returning a value in the "strSelectRS" string where the actual value should be showing up.  So any help in correcting the Syntax so I can return a value, ie. the actual range of cells that the refrngItemSKU variable is supposed to return.  Thank you again.  Sorry for having to edit my Question, but the comment section does not allow for enough letters to type all this out.   To the moderators, I appreciate your patience with my posts.  But I am desperate for answers, and so far, this forum is the only one that have been willing to answer my questions! Thanks again.

Ken L.

POSTED EARLIER
GOOD NEWS! Thanks to the suggestion of using ACEDAO.DLL that seems to have resolved the first problem, but a new one has crept up.  I can't find a way to use DAO, in Excel 2013-64, using SQL to query the various tables.  It seems I can not define "Fields" and "Records" whereby the Columns are the "Fields" and the Rows are the "Records".  Though when I do a recordcount on the record set, it shows the total number of rows that have data on them.  But when I try to identify a column (I.e. Field) to set conditions on which records to select, I get syntax errors.  Any help would be much appreciated, and thanks again to all of the posts, they all have been helpful as it caused me to google specific terms to find solutions to my current project! THANK YOU THANK YOU THANK YOU!

Ken L
ORIGINAL POST:
I have searched using google to find a specific answer with no luck.  I keep getting error code 429 when trying to use DAO language "OpenDatabase" so I can use SQL Language to search various worksheets in one Excel 2013 Workbook.  I am running Windows 7-64 and Office 2013 64-bit.  From what I have read, it would appear DAO is not supported anymore by Microsoft, and even ADO doesn't look like it is looked favorably by the folks at Microsoft anymore.  I really don't care if I can't use DAO anymore as long as if there is a method where I can use similar functionality to find specific records based on specific criteria, amend certain records, create other records, and move amongst records  (i.e. .movefirst, .movelast, etc.).  If there is a different VBA language that is usable for 64 bit versions of my software, I will learn it.

I rather not use the workbook, worksheet functions and using IF-THEN statements going through the entire table trying to find certain "records" that match the criteria I am looking for.  It works, but its tedious and I much rather use SQL type language.

I realize using MS Access would be more appropriate, but I prefer using the Spreadsheet format. What I am trying to do is write a VBA program that converts certain cell values into a certain format to be converted to a csv file to upload to a website for my web-store.  The file is my inventory sheet, with tons of calculations/formulas in it.  I rather not use MS Access if I don't have to.

Thank you for any help that can be provided!

Thanks.

Ken L.

答:
Include a reference to Microsoft Office 15.0 Access database engine Object Library  (i.e use AceDAO instead of Jet DAO; drop any reference to DAO 3.6)

OpenDatabase([filepath], [Exclusive], [Read only], [Connect string])

OpenDatabase([filepath], False, True, "Excel 12.0 Xml;HDR=yes;")

Excel 12.0 Xml = .xlsx

https://msdn.microsoft.com/en-us/library/office/ff965871(v=office.14).aspx#DataProgrammingWithAccess2010_DirectDAOExample

ADDED:

OpenRecordset("SQL statement", ...)

In SQL statement:

Tables can be SheetName$ or SheetName$-plus-range-specifier or RangeName

Add a $ onto the end of sheet names (e.g. Sheet1$)

Tables (Excel lists) probably aren't recognized; you may need to explicitly define an overlapping range name using cell notation (e.g. a1:b10)

SQL example (you can enclose Table and Field names in brackets [] to escape characters that may conflict, e.g. spaces):

```<code>SELECT * FROM [Sheet1$] WHERE ([Field Name in Brackets] = SomeNumericValue)
SELECT * FROM [Sheet1$] WHERE ([Field Name in Brackets] = 'SomeTextValueInSingleQuote')
SELECT * FROM [Sheet1$] WHERE ([Field Name in Brackets] = #SomeDateInHashTags#)
</code>```

Syntax help:
https://msdn.microsoft.com/EN-US/library/office/dn123881.aspx

ADDED 2:

you can't define a range as a variable in your VBA and then pass along that variable name in the SQL statement; the range has to be defined as a named range in the Excel workbook itself (e.g. using the Name Manager dialog in Excel or VBA code), then on the database engine side it can look up that name from the SQL statement text against available table names;

you can use VBA to create a defined/stored named range using something like:

ActiveWorkBook.Names.Add(Name:= "MyRangeForSQL", RefersTo:= "=A11:E1764")

if no field names in the first row, then you need to change the connect string to indicate no header row by including "HDR=No;" ; Ace/Jet will then create some default field names: "F1" - first column, "F2" - second column, "F3" -etc. e.g.

strSelectRS = "SELECT * FROM [MyRangeForSQL] WHERE [F1] IS NOT NULL"

ADDED 3:

you can always alias the (table and) field names in the SQL statement: [FieldName] AS [FieldNameAlias]

strSelectRS = "SELECT [F1] As [Sku], [F2] As [Quantity], [F3] As [Price] FROM [MyRangeForSQL] WHERE [Sku] IS NOT NULL"

should probably mark this question as answered, getting outside of original scope; good luck

Body:
Include a reference to Microsoft Office 15.0 Access database engine Object Library  (i.e use AceDAO instead of Jet DAO; drop any reference to DAO 3.6)

OpenDatabase([filepath], [Exclusive], [Read only], [Connect string])

OpenDatabase([filepath], False, True, "Excel 12.0 Xml;HDR=yes;")

Excel 12.0 Xml = .xlsx

https://msdn.microsoft.com/en-us/library/office/ff965871(v=office.14).aspx#DataProgrammingWithAccess2010_DirectDAOExample

ADDED:

OpenRecordset("SQL statement", ...)

In SQL statement:

Tables can be SheetName$ or SheetName$-plus-range-specifier or RangeName

Add a $ onto the end of sheet names (e.g. Sheet1$)

Tables (Excel lists) probably aren't recognized; you may need to explicitly define an overlapping range name using cell notation (e.g. a1:b10)

SQL example (you can enclose Table and Field names in brackets [] to escape characters that may conflict, e.g. spaces):

SELECT * FROM [Sheet1$] WHERE ([Field Name in Brackets] = SomeNumericValue)
SELECT * FROM [Sheet1$] WHERE ([Field Name in Brackets] = 'SomeTextValueInSingleQuote')
SELECT * FROM [Sheet1$] WHERE ([Field Name in Brackets] = #SomeDateInHashTags#)

Syntax help:
https://msdn.microsoft.com/EN-US/library/office/dn123881.aspx

ADDED 2:

you can't define a range as a variable in your VBA and then pass along that variable name in the SQL statement; the range has to be defined as a named range in the Excel workbook itself (e.g. using the Name Manager dialog in Excel or VBA code), then on the database engine side it can look up that name from the SQL statement text against available table names;

you can use VBA to create a defined/stored named range using something like:

ActiveWorkBook.Names.Add(Name:= "MyRangeForSQL", RefersTo:= "=A11:E1764")

if no field names in the first row, then you need to change the connect string to indicate no header row by including "HDR=No;" ; Ace/Jet will then create some default field names: "F1" - first column, "F2" - second column, "F3" -etc. e.g.

strSelectRS = "SELECT * FROM [MyRangeForSQL] WHERE [F1] IS NOT NULL"

ADDED 3:

you can always alias the (table and) field names in the SQL statement: [FieldName] AS [FieldNameAlias]

strSelectRS = "SELECT [F1] As [Sku], [F2] As [Quantity], [F3] As [Price] FROM [MyRangeForSQL] WHERE [Sku] IS NOT NULL"

should probably mark this question as answered, getting outside of original scope; good luck


问:
How to read stringified JSON string in Java
Kindly need your help as this really taking me long time to try.
From JSP, I passed the stingnify JSON object as a String to the Java action, it like

```<code>String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"NPD STATION SDN BHD"},
{"dealerID":"VARSSTH008","dealerName":"Winjaya Teleshop"}]
</code>```

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help!!!

答:
using http://json-lib.sourceforge.net/ can be realy easy.

See http://json-lib.sourceforge.net/snippets.html

```<code>String str = "{'dealerName':'NPD STATION SDN BHD', 'dealerID': 1, 'dealerReputation': 2.0, 'dealerActive': true}";
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );
</code>```

and

```<code>String str = "['NPD STATION SDN BHD', 1, 2.0, true]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str );
</code>```

Body:
Kindly need your help as this really taking me long time to try.
From JSP, I passed the stingnify JSON object as a String to the Java action, it like

String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"NPD STATION SDN BHD"},
{"dealerID":"VARSSTH008","dealerName":"Winjaya Teleshop"}]

How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?

Thanks for all help!!!

Body:
using http://json-lib.sourceforge.net/ can be realy easy.

See http://json-lib.sourceforge.net/snippets.html

String str = "{'dealerName':'NPD STATION SDN BHD', 'dealerID': 1, 'dealerReputation': 2.0, 'dealerActive': true}";
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );

and

String str = "['NPD STATION SDN BHD', 1, 2.0, true]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str );


问:
Similarity between arrays of cirteria's ratings
I have a dictionary dataset with many items and it's ratings for a fixed set of criterias (in example, 3 criterias):

```<code>item1 = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 }
item2 = { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 }
item3 = { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }
</code>```

I must find the best way to define the most similar items to a user item.
For example:

```<code>useritem = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 2 }
</code>```

Could be result in:

```<code>similarity = { "item1": 0.95, "item2": 0.17, "item3": 0.91 }
</code>```

Cosine's similarity is a way to achieve this?
If so, i found scikit learn that do this in python. How can I transform the item's dictionary in a ndarray to use with cosine similarity?

Tks

答:
Yes cosine distance is a good metric to find similar items, I believe it is the most used metric for recommender systems.

For the data structure, I would recommend using pandas dataframe to hold your dataset. It is easy to create, flexible and can easily be converted to numpy arrays (df.values will give you the inner numpy array).

```<code>df = pd.DataFrame(
    data=[{ "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 },
          { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 },
          { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }],
    index=["item1", "item2", "item3"])
</code>```

Creates a dataframe as below.

```<code>       Criteria1  Criteria2  Criteria3
item1          5          2          1
item2          0          1          5
item3          4          2          1
</code>```

And you can use any distance metric from sklearn using dataframes.

```<code>>> from sklearn.metrics.pairwise import cosine_similarity
>> cosine_similarity(pd.Series(useritem), df)
array([[ 0.98524468,  0.40967325,  0.98765833]])
</code>```

Note: Using cosine similarity with a 1d array is deprecated so the code above will give you an error since useritem is (3,) shape. You can use pd.Series(useritem).values.reshape(1, -1) to reshape it to more appropriate (1, 3).

Body:
I have a dictionary dataset with many items and it's ratings for a fixed set of criterias (in example, 3 criterias):

item1 = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 }
item2 = { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 }
item3 = { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }

I must find the best way to define the most similar items to a user item.
For example:

useritem = { "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 2 }

Could be result in:

similarity = { "item1": 0.95, "item2": 0.17, "item3": 0.91 }

Cosine's similarity is a way to achieve this?
If so, i found scikit learn that do this in python. How can I transform the item's dictionary in a ndarray to use with cosine similarity?

Tks

Body:
Yes cosine distance is a good metric to find similar items, I believe it is the most used metric for recommender systems.

For the data structure, I would recommend using pandas dataframe to hold your dataset. It is easy to create, flexible and can easily be converted to numpy arrays (df.values will give you the inner numpy array).

df = pd.DataFrame(
    data=[{ "Criteria1" : 5, "Criteria2" : 2, "Criteria3" : 1 },
          { "Criteria1" : 0, "Criteria2" : 1, "Criteria3" : 5 },
          { "Criteria1" : 4, "Criteria2" : 2, "Criteria3" : 1 }],
    index=["item1", "item2", "item3"])

Creates a dataframe as below.

       Criteria1  Criteria2  Criteria3
item1          5          2          1
item2          0          1          5
item3          4          2          1

And you can use any distance metric from sklearn using dataframes.

>> from sklearn.metrics.pairwise import cosine_similarity
>> cosine_similarity(pd.Series(useritem), df)
array([[ 0.98524468,  0.40967325,  0.98765833]])

Note: Using cosine similarity with a 1d array is deprecated so the code above will give you an error since useritem is (3,) shape. You can use pd.Series(useritem).values.reshape(1, -1) to reshape it to more appropriate (1, 3).


问:
How can i upload files along with other model values in asp.net mvc using ajax?
All the articles i've found talks about either uploading both files and text values using non-ajax form post, or uploading only files with ajax post requests. Is there a way to upload both files and text values using ajax post to mvc action where i can get model binding as well as Request.Files?</p>

答:
After making some experiments, turns out the code doing this is also not that complicated:

```<code>var formData = new FormData($("form")[0]);

        $.post({
            url: "/Home/Upload",
            contentType: false,
            processData: false,
            data: formData,
            success: function () {
                alert("done");
            }
        });
</code>```

The tricky part is the construction of FormData object. There's actually no need to manually add files and other text values, as long as all the inputs are inside a form tag.

Body:
After making some experiments, turns out the code doing this is also not that complicated:

var formData = new FormData($("form")[0]);

        $.post({
            url: "/Home/Upload",
            contentType: false,
            processData: false,
            data: formData,
            success: function () {
                alert("done");
            }
        });

The tricky part is the construction of FormData object. There's actually no need to manually add files and other text values, as long as all the inputs are inside a form tag.


问:
Hide UIPageControl of UIPageControlViewController on certain page index
I want to hide the page control indicator on a certain VC and instead show a button with the text 'Get started'. The user has however still be able to navigate back into the page control.

I've tried this:

```<code>self.pageController = [UIPageControl appearance];
self.pageController.pageIndicatorTintColor = [UIColor redColor];
self.pageController.currentPageIndicatorTintColor = [UIColor greenColor];

if(self.pageIndex == 1){
    self.pageController.hidden = YES;
    NSLog(@"hide you!");
}
</code>```

However, this doesn't work. setting self.pageController.hidden = YES without the if statement works, and the nslog is triggered as well. It seems that somehow this can only be set once.

I also don't know how smooth this will be. I obviously don't want it to change when the user is fully arrived on the page itself, but in the transition toward it.

What is the best way to tackle this problem?

答: I guess you may set the hidesForSinglePage to YES, this will reset the hidden property when the numberOfPages is greater than one.</p>

Body:
I want to hide the page control indicator on a certain VC and instead show a button with the text 'Get started'. The user has however still be able to navigate back into the page control.

I've tried this:

self.pageController = [UIPageControl appearance];
self.pageController.pageIndicatorTintColor = [UIColor redColor];
self.pageController.currentPageIndicatorTintColor = [UIColor greenColor];

if(self.pageIndex == 1){
    self.pageController.hidden = YES;
    NSLog(@"hide you!");
}

However, this doesn't work. setting self.pageController.hidden = YES without the if statement works, and the nslog is triggered as well. It seems that somehow this can only be set once.

I also don't know how smooth this will be. I obviously don't want it to change when the user is fully arrived on the page itself, but in the transition toward it.

What is the best way to tackle this problem?


问:
How to find the cause of weird errors in my JavaScript program?
```<code>function wpnChs() {
  var p1 = prompt("Do you take a SWORD or a CLUB to battle?").toUpperCase();
  var HP = 1;
  var EHP = 1;
  var dmg = Math.floor(Math.random() * 1);
  var dmgT = Math.floor(Math.random() * 1);
  var first = Math.floor(Math.random() * 1);
  if (p1 === "SWORD") {
    HP = 10;
    EHP = 9;
    dmg = Math.floor(Math.random() * 8);
    dmgT = Math.floor(Math.random() * 6);
    first = Math.floor(Math.random() * 3);
  } else if (p1 === "CLUB") {
    HP = 11;
    EHP = 9;
    dmg = Math.floor(Math.random() * 6);
    dmgT = Math.floor(Math.random() * 5);
    first = Math.floor(Math.random() * 3);
  } else {
    wpnChs();
  }
}

function dmgD1() {
  EHP -= dmg;
}

function dmgD2() {
  HP -= dmgT;
}

function fR() {
  if (p1 === "SWORD") {
    dmg = Math.floor(Math.random() * 8);
    dmgT = Math.floor(Math.random() * 6);
    first = Math.floor(Math.random() * 3);
  } else {
    dmg = Math.floor(Math.random() * 6);
    dmgT = Math.floor(Math.random() * 5);
    first = Math.floor(Math.random() * 3);
  }
}

var fight = function() {
  if (first === 0 || 2) {
    dmgD1();
    if (dmg === 0) {
      alert("You attacked, but the enemy dodged it!");
      fR();
      fight();
    } else {
      alert("You attacked and did " + dmg + " damage. The enemy now has " + EHP
        +
        " health");
      if (EHP <= 0) {
        alert("You killed the enemy!")
      } else {
        fR();
        fight();
      }
    }
  } else {
    dmgD2();
    if (dmgT === 0) {
      alert("The enemy attacked, but you dodged it!");
      fR();
      fight();
    } else {
      alert("The enemy attacked and did " + dmgT + " damage. You now have " + HP
        +
        " health.");
      if (HP <= 0) {
        alert("You died!");
      } else {
        fR();
        fight();
      }
    }
  }
};

wpnChs();
fight();
</code>```

答:
Alright, so the first problem is the issues with scoping. You're trying to use variables declared in the first function through out the code when they are scoped for only the first function. You could fix this problem a few different ways.

You could declare them outside of the functions making them more
global.

You could still declare them inside the current function and pass
them as parameters. Like fight(first, dmg); I'd recommend this way.

I found this initial error by using the Chrome developer tools - try pushing F-12 while you're browsing and trying to run your code, you'll often get a console error - like the one below if somethings not working. These console errors often provide invaluable insight into what's going on in your application.

Try reading this to learn more about how to use dev tools: https://developers.google.com/web/tools/chrome-devtools/javascript/

I'd also recommend that you look here: https://www.w3schools.com/js/js_scope.asp to learn more about scoping in javascript.

Keep at it. The first steps can be a bit confusing but once you get it figured out it starts to all come together.


问:
javascript classes call function
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

```<code>class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

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

websocketModel.js

```<code>const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

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

答:
This could be a binding issue. Perhaps you want to use arrow function instead on your onConnMessage method:

onConnMessage = (message) => {
    let clients = this.clients;
    this.boardCastInit(1);
}```

This will ensure that this refers to the websocket class which has the boardCastInit method defined.

Title: javascript classes call function

Body:
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;

websocketModel.js

const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;

Body:
This could be a binding issue. Perhaps you want to use arrow function instead on your onConnMessage method:

onConnMessage = (message) => {
    let clients = this.clients;
    this.boardCastInit(1);
}

This will ensure that this refers to the websocket class which has the boardCastInit method defined.


问:
Angular $stateProvider - match no route or 'blank' route
I'm using $stateProvider with angular like this:

```<code>var stateConfig = function ($stateProvider, $urlRouterProvider) {

    // Redirect if no route
    $urlRouterProvider.otherwise("");

    $stateProvider.state("home.myState", {
        url: "",
        templateUrl: "/mytemplate.html",
        controller: "MyController"
    });
};
</code>```

... and this works fine for a .NET MVC url like this (with no angular route defined):

```<code>http://hostname/MvcController/id
</code>```

The issue is that sometimes the URL will be in this form:

```<code>http://hostname/MvcController/id#/
</code>```

... and I can change my state definition like this:

```<code>    $stateProvider.state("home.myState", {
        url: "/",
        ...
</code>```

, which matches the new URL, but no longer matches the original URL (without the trailing '#/'). How should I define the state, or configure my routing, so that it matches a URL which can either have a 'blank' route (i.e. with a trailing '#/'), or no route defined at all (no trailing '#/')

答:
As far as I know you need to turn on the HTML5 Mode in your app.config:

```<code>app.config(["$locationProvider", function($locationProvider) {
   $locationProvider.html5Mode(true);
}]);
</code>```

Also you must set a base url in your  tag :

```<code>< base href="/" >
</code>```

Body:
I'm using $stateProvider with angular like this:

var stateConfig = function ($stateProvider, $urlRouterProvider) {

    // Redirect if no route
    $urlRouterProvider.otherwise("");

    $stateProvider.state("home.myState", {
        url: "",
        templateUrl: "/mytemplate.html",
        controller: "MyController"
    });
};

... and this works fine for a .NET MVC url like this (with no angular route defined):

http://hostname/MvcController/id

The issue is that sometimes the URL will be in this form:

http://hostname/MvcController/id#/

... and I can change my state definition like this:

    $stateProvider.state("home.myState", {
        url: "/",
        ...

, which matches the new URL, but no longer matches the original URL (without the trailing '#/'). How should I define the state, or configure my routing, so that it matches a URL which can either have a 'blank' route (i.e. with a trailing '#/'), or no route defined at all (no trailing '#/')

Body:
As far as I know you need to turn on the HTML5 Mode in your app.config:

app.config(["$locationProvider", function($locationProvider) {
   $locationProvider.html5Mode(true);
}]);

Also you must set a base url in your  tag :

< base href="/" >


问:
PHP on Windows: How to use web services with the logged on user's identity?
I have a Windows 2008R2 based intranet server running a PHP based intranet application in IIS. We want to improve the intranet now and integrate data from external systems, for instance data retrieved from the Exchange web services or information from a Sharepoint webservice.

Log in for the users with their windows credentials works. And PHP running as FastCGI impersonates just fine.

The problem is now:
I cannot access web services with Windows authentication passing the credentials of the logged on user.

I could not find anything related to that problem on the internet. Am I the only one in the world who wants to federate content from certain windows servers into an existing PHP application?

I know that I could do this in .NET easily... but I just cannot recreate the whole intranet application.

Any pointers would help me very much!

Thank you,
Fabian

答:
Set PHP up in IIS and enable windows authentication. Then you'll get the user name in the header.
Or you can use mod_auth_kerb of apache to do that.</p>


问:
Entity Framework Core ignoring .Include(..) without .ToList(..) indirectly
As noted in "Loading Related Data" from EF Core Documentation we can use .Include(..) to Eagerly Load navigation properties from the DbSet (or generic IQueryable<T> linking back to an EF context).

This means that, given the following models:

```<code>public class TestEntityA
{
    public int Id { get; set; }
    public int TestEntityBId { get; set; }
    public TestEntityB TestEntityB { get; set; }

    public string BProperty { get { return TestEntityB.Property; } }
}

public class TestEntityB
{
    public int Id { get; set; }
    public string Property { get; set; }
}
</code>```

.. then code such as the following should work:

```<code>context.TestEntityAs
    .Include(m => m.TestEntityB)
    .Any(m => m.BProperty == "Hello World");
    /*
     * Note that the below DOES work by using the nav property directly
     * in the query, but that is not always going to be an option for
     * whatever reason. If it's .Included it should be available through
     * INNER JOINing it into the base query before the .Any runs.
     * .Any(m => m.TestEntityB.Property == "Hello World");
     */
</code>```

However it doesn't.

I note that there is a caveat where .Include() could be ignored should a query not return the type that is initially requested:

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored. [snip] By default, EF Core will log a warning when include operators are ignored.

I'm not sure how, in the above call to .Any() that is relevant. Yes, the query is not returning the original type (it's returning a bool of course) but at the same time, the Warning is also not logged to advise that it is being ignored.

My questions here are:

Is this a usage case that is expected to work? Should I raise a bug in EF Core?

If it's not expected, a workaround is as below (to call .ToList()) but that would obviously load everything, to find out if we have anything on a .Any() which could easily be a query (and would be as such in EF6). What is a workaround to get this .Any() to work on the server side thus not requiring the ToList to put it in memory?

Workaround:

```<code>context.TestEntityAs
    .Include(m => m.TestEntityB)
    .ToList()
    .Any(m => m.BProperty == "Hello World");
</code>```

Full reproducible sample: https://gist.github.com/rudiv/3aa3e1bb65b86ec78ec6f5620ee236ab

答:
The behaviour is expected but you can use explicit loading for more efficient query as shown below.

2 separate queries, but no need to load all of TestEntityBs

```<code>// First query
var testEntityAs = context.TestEntityAs.ToList();
var testEntityAsIds = testEntityAs.Select(t => t.Id);

// Second query, can apply filter of Hello World without loading all TestEntityBs
context.TestEntityBs
    .Where(t => testEntityAsIds.Contains(t.Id) && t.Property == "Hello World")
    .Load();

// In memory check
var isAny = testEntityAs.Any(t => !string.IsNullOrEmpty(t.BProperty));
</code>```

Body:
As noted in "Loading Related Data" from EF Core Documentation we can use .Include(..) to Eagerly Load navigation properties from the DbSet (or generic IQueryable<T> linking back to an EF context).

This means that, given the following models:

public class TestEntityA
{
    public int Id { get; set; }
    public int TestEntityBId { get; set; }
    public TestEntityB TestEntityB { get; set; }

    public string BProperty { get { return TestEntityB.Property; } }
}

public class TestEntityB
{
    public int Id { get; set; }
    public string Property { get; set; }
}

.. then code such as the following should work:

context.TestEntityAs
    .Include(m => m.TestEntityB)
    .Any(m => m.BProperty == "Hello World");
    /*
     * Note that the below DOES work by using the nav property directly
     * in the query, but that is not always going to be an option for
     * whatever reason. If it's .Included it should be available through
     * INNER JOINing it into the base query before the .Any runs.
     * .Any(m => m.TestEntityB.Property == "Hello World");
     */

However it doesn't.

I note that there is a caveat where .Include() could be ignored should a query not return the type that is initially requested:

If you change the query so that it no longer returns instances of the entity type that the query began with, then the include operators are ignored. [snip] By default, EF Core will log a warning when include operators are ignored.

I'm not sure how, in the above call to .Any() that is relevant. Yes, the query is not returning the original type (it's returning a bool of course) but at the same time, the Warning is also not logged to advise that it is being ignored.

My questions here are:

Is this a usage case that is expected to work? Should I raise a bug in EF Core?

If it's not expected, a workaround is as below (to call .ToList()) but that would obviously load everything, to find out if we have anything on a .Any() which could easily be a query (and would be as such in EF6). What is a workaround to get this .Any() to work on the server side thus not requiring the ToList to put it in memory?

Workaround:

context.TestEntityAs
    .Include(m => m.TestEntityB)
    .ToList()
    .Any(m => m.BProperty == "Hello World");

Full reproducible sample: https://gist.github.com/rudiv/3aa3e1bb65b86ec78ec6f5620ee236ab

Body:
The behaviour is expected but you can use explicit loading for more efficient query as shown below.

2 separate queries, but no need to load all of TestEntityBs

// First query
var testEntityAs = context.TestEntityAs.ToList();
var testEntityAsIds = testEntityAs.Select(t => t.Id);

// Second query, can apply filter of Hello World without loading all TestEntityBs
context.TestEntityBs
    .Where(t => testEntityAsIds.Contains(t.Id) && t.Property == "Hello World")
    .Load();

// In memory check
var isAny = testEntityAs.Any(t => !string.IsNullOrEmpty(t.BProperty));