问:
Elasticsearch: Get distinct record by a specified field
I want to search some results by fields and sort them by other field ("myscore"), here is the ES (5.2.2) query:

```<code>{
  "sort": [
    {"myscore": {"order" :"desc"}}
  ],
  "query": {
    "query_string" : {
       "query" : "(field1:foo) AND (field2:bar)"
    }
  }
}
</code>```

then, I can get this:

```<code>{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 3,
        "max_score": null,
        "hits": [
            {
                "_index": "fooindex",
                "_type": "footype",
                "_id": "1",
                "_score": null,
                "_source": {
                    "field1": "foo",
                    "field2": "bar",
                    "x_id": "x001",
                    "myscore": 0.9
                },
                "sort": [
                    0.9
                ]
            },
            {
                "_index": "fooindex",
                "_type": "footype",
                "_id": "2",
                "_score": null,
                "_source": {
                    "field1": "foo",
                    "field2": "bar",
                    "x_id": "x001",
                    "myscore": 0.8
                },
                "sort": [
                    0.8
                ]
            },
            {
                "_index": "fooindex",
                "_type": "footype",
                "_id": "3",
                "_score": null,
                "_source": {
                    "field1": "foo",
                    "field2": "bar",
                    "x_id": "x002",
                    "myscore": 0.7
                },
                "sort": [
                    0.7
                ]
            }
        ]
    }
}
</code>```

However, I want to get distinct results according to the field "x_id", like this:

```<code>{
    "_index": "fooindex",
    "_type": "footype",
    "_id": "1",
    "_score": null,
    "_source": {
        "field1": "foo",
        "field2": "bar",
        "x_id": "x001",
        "myscore": 0.9
    },
    "sort": [
        0.9
    ]
},
{
    "_index": "fooindex",
    "_type": "footype",
    "_id": "3",
    "_score": null,
    "_source": {
        "field1": "foo",
        "field2": "bar",
        "x_id": "x002",
        "myscore": 0.7
    },
    "sort": [
        0.7
    ]
}
</code>```

The similar SQL would be "select * from footype group by x_id";

I've tried aggregation:

```<code>"aggs": {
    "unique_xid": {
     "terms": {
       "field": "x_id"
     }
    }
},
</code>```

The result would be:

```<code>"aggregations": {
   "unique_ids": {
      "buckets": [
         {
            "key": "x001",
            "doc_count": 2
         },
         {
            "key": "x002",
            "doc_count": 1
         }
      ]
   }
}
</code>```

The problem is that the aggregation results leak field information and they are sorted by "count" not "myscore". Is there any way to get distinct results by a specified field?

答:
Since your buckets might contain more than one document and you want to use the maximum value of myscore within those documents in order to sort your buckets, then you can do it like this:

```<code>"aggs": {
   "unique_xid": {
      "terms": {
         "field": "x_id",
         "order": {
            "score": "desc"
         }
      },
      "aggs": {
         "score": {
            "max": {
               "field": "myscore"
            }
         }
      }
   }
},
</code>```

Body:
I want to search some results by fields and sort them by other field ("myscore"), here is the ES (5.2.2) query:

{
  "sort": [
    {"myscore": {"order" :"desc"}}
  ],
  "query": {
    "query_string" : {
       "query" : "(field1:foo) AND (field2:bar)"
    }
  }
}

then, I can get this:

{
    "took": 1,
    "timed_out": false,
    "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
    },
    "hits": {
        "total": 3,
        "max_score": null,
        "hits": [
            {
                "_index": "fooindex",
                "_type": "footype",
                "_id": "1",
                "_score": null,
                "_source": {
                    "field1": "foo",
                    "field2": "bar",
                    "x_id": "x001",
                    "myscore": 0.9
                },
                "sort": [
                    0.9
                ]
            },
            {
                "_index": "fooindex",
                "_type": "footype",
                "_id": "2",
                "_score": null,
                "_source": {
                    "field1": "foo",
                    "field2": "bar",
                    "x_id": "x001",
                    "myscore": 0.8
                },
                "sort": [
                    0.8
                ]
            },
            {
                "_index": "fooindex",
                "_type": "footype",
                "_id": "3",
                "_score": null,
                "_source": {
                    "field1": "foo",
                    "field2": "bar",
                    "x_id": "x002",
                    "myscore": 0.7
                },
                "sort": [
                    0.7
                ]
            }
        ]
    }
}

However, I want to get distinct results according to the field "x_id", like this:

{
    "_index": "fooindex",
    "_type": "footype",
    "_id": "1",
    "_score": null,
    "_source": {
        "field1": "foo",
        "field2": "bar",
        "x_id": "x001",
        "myscore": 0.9
    },
    "sort": [
        0.9
    ]
},
{
    "_index": "fooindex",
    "_type": "footype",
    "_id": "3",
    "_score": null,
    "_source": {
        "field1": "foo",
        "field2": "bar",
        "x_id": "x002",
        "myscore": 0.7
    },
    "sort": [
        0.7
    ]
}

The similar SQL would be "select * from footype group by x_id";

I've tried aggregation:

"aggs": {
    "unique_xid": {
     "terms": {
       "field": "x_id"
     }
    }
},

The result would be:

"aggregations": {
   "unique_ids": {
      "buckets": [
         {
            "key": "x001",
            "doc_count": 2
         },
         {
            "key": "x002",
            "doc_count": 1
         }
      ]
   }
}

The problem is that the aggregation results leak field information and they are sorted by "count" not "myscore". Is there any way to get distinct results by a specified field?

Body:
Since your buckets might contain more than one document and you want to use the maximum value of myscore within those documents in order to sort your buckets, then you can do it like this:

"aggs": {
   "unique_xid": {
      "terms": {
         "field": "x_id",
         "order": {
            "score": "desc"
         }
      },
      "aggs": {
         "score": {
            "max": {
               "field": "myscore"
            }
         }
      }
   }
},


来源: stackexchange

问:
Cannot install @angular/cli
I am trying to work on angular2 for which I have installed nodeJS. I have followed the steps given here https://github.com/angular/angular-cli#prerequisites but there seems to be an issue. Here's what I did in the Command Prompt(Admin):

```<code>C:\WINDOWS\system32>node -v
v6.10.1

C:\WINDOWS\system32>npm -v
3.10.10

C:\WINDOWS\system32>npm install -g @angular/cli
[ ..............] / loadRequestedDeps: sill install loadAllDepsIntoIdealTree
</code>```

My command prompt is stuck at this command and shows no sign of response. I will be glad if there are any suggestions on solving this issue of mine. Is there anything I am missing here?

答:
Try this -

Global Package :

```<code>npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
</code>```

Local Package :

```<code>rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install
</code>```

ContentLicense: CC BY-SA 3.0

Title: Cannot install @angular/cli

Body:
I am trying to work on angular2 for which I have installed nodeJS. I have followed the steps given here https://github.com/angular/angular-cli#prerequisites but there seems to be an issue. Here's what I did in the Command Prompt(Admin):

C:\WINDOWS\system32>node -v
v6.10.1

C:\WINDOWS\system32>npm -v
3.10.10

C:\WINDOWS\system32>npm install -g @angular/cli
[ ..............] / loadRequestedDeps: sill install loadAllDepsIntoIdealTree

My command prompt is stuck at this command and shows no sign of response. I will be glad if there are any suggestions on solving this issue of mine. Is there anything I am missing here?

Body:
Try this -

Global Package :

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local Package :

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install


问:
How to combine hash in PHP
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

```<code>checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345
</code>```

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

答:
I would implode and then explode it.  It's great for storing hashes in files and etc:</p>

```<code><?php

$checkSums = Array(
    "b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1",
    "dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34",
    "4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345"
);
//simply combine via $checksum1 . '|' . $checksum2 . '|' . $checksum3, and then explode it the way listed bellow

$combined = implode('|', $checkSums);

$notCombined = explode('|', $combined);

?>
</code>```

Title: How to combine hash in PHP

Body:
I would like to ask if how to combine hash codes in PHP?

For example I have some checksums here (just sample checksums):

checksum1:b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1
checksum2:dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34
checksum3:4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345

If I have these sample checksums of a file which will be split into 3 parts, I have to combine the first 2 checksums and then combine the last checksum after.

Edit: Combine means if I combine 2 checksums, it will generate new checksum.

I would like to achieve through the code what was stated in here:

Combine the first two hashes and take the binary hash of the result.

$ cat hash1 hash2 > hash12

$ openssl dgst -sha256 -binary hash12 > hash12hash

This is in the command line interface. The binary result was later on converted to hexadecimal.
How is it possible for PHP?

Body:
I would implode and then explode it.  It's great for storing hashes in files and etc:

<?php

$checkSums = Array(
    "b62e146dbc34b6f7dd0d7b1dc4e6c93ebc2a0016793e3af701fe4f3eab3299d1",
    "dsfhsdf8s6f87e4r34ijtr5i34u5934534534ij5340598348534095834095j34",
    "4324298sdfhsdhfsdhf387455hsdfhsdf9358903485jsdfjsdjfsiuf03458345"
);
//simply combine via $checksum1 . '|' . $checksum2 . '|' . $checksum3, and then explode it the way listed bellow

$combined = implode('|', $checkSums);

$notCombined = explode('|', $combined);

?>


问:
Why StreamReader returns string instead of byte array
Two related questions:

Why did they choose to return string from StreamReader.ReadToEnd() instead of byte[]?

I know I can convert it using System.Text.Encoding, but exactly which encoding should I use? UTF8, UTF7, ASCII or Unicode? I'm dealing with binary files.

Note: I was asked for clarification. It is just that the word stream gives an impression of byte-level...well...stream of data (think network stream, file stream, buffer, none of them is supposed to be a char-type concept). As correctly indicated by Joel in his answer, this is more of a naming issue than anything else.

答:
You have a number of alternatives to StreamReader, which is used mostly for reading in character data. If you are reading in binary file data, then a better option is to use FileStream.Read. It returns the data in a byte array.

According to my benchmarks, it is faster than BinaryReader and File.ReadAllBytes. But, File.ReadAllBytes is easier to use.


问:
display properties of an object with event target
I have written code that creates boxes based on user input in a form. I use a constructor function to give the boxes these values; name, color, id and number. I am supposed to make it so that when the user clicks on the box in the page, an alert box comes up that says what those values are for that individual box. I'm having trouble figuring out how to display most of those properties correctly.

Here is the function where I assign property values to the boxes, and also add them to the page:

```<code>function addBox(newbox) {
   for (var i = 0; i < newbox.number; i++) {
   counter++;
   var scene = document.getElementById("scene");
   var div = document.createElement("div");
   div.setAttribute("id", counter);
   div.className += " " + "box";
   div.innerHTML += newbox.name;
   div.style.backgroundColor = newbox.color;
   var x = Math.floor(Math.random() * (scene.offsetWidth-101));
   var y = Math.floor(Math.random() * (scene.offsetHeight-101));
   div.style.left = x + "px";
   div.style.top = y + "px";
   scene.appendChild(div);
   div.onclick = display;
    }
  }
</code>```

Here is the function I have for displaying the info about the boxes:

```<code>function display(e) {
   var a = e.target.attributes;
   var b = e.target;
   console.log(b.name);     //shows "undefined"
   alert("id:" + "" + a[0].value);
  }
</code>```

My alert message works correctly, it shows an individual number for each box, based on the value of the counter. I don't understand why I can't get e.target to work to show name, color or number. I am a beginner, so any thoughts are much appreciated.

答:
Working in IE

$(document).click(function (e) {
     var element = e.target || window.event.target;
        console.log(element.getAttribute('id')+":"+element.getAttribute('name'));
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
I have written code that creates boxes based on user input in a form. I use a constructor function to give the boxes these values; name, color, id and number. I am supposed to make it so that when the user clicks on the box in the page, an alert box comes up that says what those values are for that individual box. I'm having trouble figuring out how to display most of those properties correctly.

Here is the function where I assign property values to the boxes, and also add them to the page:

function addBox(newbox) {
   for (var i = 0; i < newbox.number; i++) {
   counter++;
   var scene = document.getElementById("scene");
   var div = document.createElement("div");
   div.setAttribute("id", counter);
   div.className += " " + "box";
   div.innerHTML += newbox.name;
   div.style.backgroundColor = newbox.color;
   var x = Math.floor(Math.random() * (scene.offsetWidth-101));
   var y = Math.floor(Math.random() * (scene.offsetHeight-101));
   div.style.left = x + "px";
   div.style.top = y + "px";
   scene.appendChild(div);
   div.onclick = display;
    }
  }

Here is the function I have for displaying the info about the boxes:

function display(e) {
   var a = e.target.attributes;
   var b = e.target;
   console.log(b.name);     //shows "undefined"
   alert("id:" + "" + a[0].value);
  }

My alert message works correctly, it shows an individual number for each box, based on the value of the counter. I don't understand why I can't get e.target to work to show name, color or number. I am a beginner, so any thoughts are much appreciated.

Body:
Working in IE

$(document).click(function (e) {
     var element = e.target || window.event.target;
        console.log(element.getAttribute('id')+":"+element.getAttribute('name'));
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Copy External Folder to Target While Building Jar(Using Maven)
First of all sincere apologies if my question is duplicate, I tried searching but couldn’t find relevant answer to my question

Question: I am creating a Fat jar out of my project using Maven “maven-shade-plugin“, now addition to that I have another Config folder(having some .dll , properties, .init etc files) , which I am referring from project.

Now what I want is, somehow while jar creation(preferably at Maven Build Time),my “config” folder also get copied parallel to the jar.

Using : Maven 3.3.9

Current project Structure:

ProjectParentFolder
     --.git
     --.idea
     --src
     --config
     --pom.xml

Desired output

TargetFolder
        --ProjectParentFolder.jar
        --Config

Note** If this requires to copy config folder to inside some src folder , I can do that ,but after build I want it to be outside jar(preferably parallel to jar).

Please advise, as I have to automate this process in TeamCity/uDeploy as well.

答:
maven-shade-plugin is mostly used to package uber-jar. I would advise to use maven-assembly-plugin instead. You can configure your config folder (using fileSet element) anywhere you would like it to in assembly.xml. For example:

```<code>   <fileSets>
    <fileSet>
        <directory>${project.build.directory}</directory>
        <outputDirectory>/Config</outputDirectory>
        <includes>
            <include>...</include>
        </includes>
    </fileSet>
</code>```

maven-assembly-pluginjarpackaging

Body:
maven-shade-plugin is mostly used to package uber-jar. I would advise to use maven-assembly-plugin instead. You can configure your config folder (using fileSet element) anywhere you would like it to in assembly.xml. For example:

   <fileSets>
    <fileSet>
        <directory>${project.build.directory}</directory>
        <outputDirectory>/Config</outputDirectory>
        <includes>
            <include>...</include>
        </includes>
    </fileSet>

maven-assembly-pluginjarpackaging


问:
Get text between two elements JQUERY
I have the following code in my application.

```<code> <div title="Please Click Here to Expand" class="technology3 closedlanguage" headerindex="0h">
<span class="accordprefix">
<img src="http:www.test.com/expanded.gif" style="width:13px; height:13px; margin-Right:20px">
</span>
  Need this text<span class="accordsuffix"></span></div>
</code>```

I need to get text between "accordprefix" and "accordsuffix" classes which is "Need this text"

for this i did following code.

```<code>$(window).load(function(){
$(".accordprefix").each(function(){
alert($(this).next().html());
});
});
</code>```

but its not working.Please give any suggestions.

答:
You can achieve this using jQuery .nextUntil()

```<code>$("#id_of_first_ele").nextUntil("#id_of_second_ele").text().trim()
</code>```

So in your case it will be

```<code>$(".accordprefix").nextUntil(".accordsuffix").text().trim()
</code>```

This will work jQuery 1.4 onwards.

Title: Get text between two elements JQUERY

Body:
I have the following code in my application.

  Need this text

I need to get text between "accordprefix" and "accordsuffix" classes which is "Need this text"

for this i did following code.

$(window).load(function(){
$(".accordprefix").each(function(){
alert($(this).next().html());
});
});

but its not working.Please give any suggestions.

Body:
You can achieve this using jQuery .nextUntil()

$("#id_of_first_ele").nextUntil("#id_of_second_ele").text().trim()

So in your case it will be

$(".accordprefix").nextUntil(".accordsuffix").text().trim()

This will work jQuery 1.4 onwards.


问:
Java enhanced enhanced for loop
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

```<code>int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}
</code>```

答:
Why would they need to provide yet another way of accessing elements by index?

The enhanced for loop was created as a shortcut for when you don't need the index of the element. It streamlined things.

If you still need the index, fall back to a regular for loop. That's one of the reasons they're there.

Title: Java enhanced enhanced for loop

Body:
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}

ContentLicense: CC BY-SA 2.5


问:
Docker: Run an arbitrary command from inside a priveleged container on the host
I'm trying to run a command from a priveleged docker. Specifically the command nmcli.

When I try to add nmcli as a volume, it complains that it's missing other files.

When I add the entire /usr/bin it complains about python being unable to add site-packages.

Is there a way, I can run a command on the host machine from a child container

答:
The majority of tools that are installed with a package manager like yum or apt will make use of shared libraries to reduce the overall size of the install.

The container would either need to be the same distro and have the same package dependencies installed, or mount all the dependencies of the binary into the container.

Something like this should work:

```<code>docker run \
  -v /lib:/lib \
  -v /usr/lib/:/usr/lib \
  -v /usr/bin/nmcli:/usr/bin/nmcli \
  busybox \
  /usr/bin/nmcli
</code>```

But you might need to be more specific about the library mounts if you want the container to use it's own shared libraries as well.

Some packages can provide a "static binary" that include's all their dependencies in the executable. I doubt this exists for nmcli as it's a RHEL specific tool to manage a RHEL box, whose policy is to use yum to manage shared libraries.

Body:
The majority of tools that are installed with a package manager like yum or apt will make use of shared libraries to reduce the overall size of the install.

The container would either need to be the same distro and have the same package dependencies installed, or mount all the dependencies of the binary into the container.

Something like this should work:

docker run \
  -v /lib:/lib \
  -v /usr/lib/:/usr/lib \
  -v /usr/bin/nmcli:/usr/bin/nmcli \
  busybox \
  /usr/bin/nmcli

But you might need to be more specific about the library mounts if you want the container to use it's own shared libraries as well.

Some packages can provide a "static binary" that include's all their dependencies in the executable. I doubt this exists for nmcli as it's a RHEL specific tool to manage a RHEL box, whose policy is to use yum to manage shared libraries.


问:
NodeJS socket.io socket does not emit
I'm working using socket.io on NodeJS to create bots for MooMoo.io. Everything seems to work fine except the bots will not accept a clan invitation.

Here is the part that is broken:

```<code>socket.emit("11", a, 1); // a = player ID
</code>```

Here's my code:

```<code>const io = require("socket.io-client");
var socket = io.connect("http://52.39.43.139:" + (5006) + '', {
    reconnection: false,
    query: "man=1"
});
var n = 0;

function spawn(i) {
    n++;
    if (n >= 10) return null;
    socket = io.connect("http://52.39.43.139:" + (5000 + i % 11) + '', {
        reconnection: false,
        query: "man=1"
    });
    socket.once("connect", () => {
        socket.emit("1", {name: "ME"}); // spawn
        socket.emit("10", "ME"); // request to join clan
    });
}
socket.once("connect", () => {
    socket.emit("1", {
        name: "ME"
    }); // spawn
    socket.emit("8", "ME"); // create clan
    console.log("Clan created");
});

team = [];

var i = 0;
setInterval(() => spawn(i), 3000);
socket.on("an", (a, name) => { // player requests to join clan event
    socket.emit("11", a, 1); // accept invite
    console.log(`${name} successfully joined :)`);
    team.push(a);
    console.log(team);
});
socket.on("ad", (a) => { // player leaves clan event
    for (var c = team.length - 1; c >= 0; c--)
        if (team[c].sid == a) {
            team.splice(c, 1);
            console.log(team[c].name + ' has left');
        }
    console.log(team);
});
socket.on("11", () => { // respawn event
    console.log("I have died, respawning...")
    socket.emit("1", { // spawn event
        name: "ME"
    });
});
</code>```

答:
According to the part you described as being broke you shouldn't pass extra variables like this:

```<code>socket.emit("11", a, 1); // a = player ID
</code>```

But rather it should look like this;

```<code>socket.emit("11", {
   playerID:a,
   otherVariable:1
});
</code>```

Which you can acess in your server code by using:

```<code>socket.on('11', function(data){
   console.log(data.playerID);
   console.log(data.otherVariable);
});
</code>```

If you can provide more detail about other problems your having I can try to help you further, but you only highlighted that that emit didn't work and we don't have your backend code to reference here.

Another note, You shouldn't be passing anything but either a single variable (which the documentation still doesn't link and prefers passing via object) or an object. You also shouldn't be using socket.once in this context as it's not needed in my opinion

Title: NodeJS socket.io socket does not emit

Body:
I'm working using socket.io on NodeJS to create bots for MooMoo.io. Everything seems to work fine except the bots will not accept a clan invitation.

Here is the part that is broken:

socket.emit("11", a, 1); // a = player ID

Here's my code:

const io = require("socket.io-client");
var socket = io.connect("http://52.39.43.139:" + (5006) + '', {
    reconnection: false,
    query: "man=1"
});
var n = 0;

function spawn(i) {
    n++;
    if (n >= 10) return null;
    socket = io.connect("http://52.39.43.139:" + (5000 + i % 11) + '', {
        reconnection: false,
        query: "man=1"
    });
    socket.once("connect", () => {
        socket.emit("1", {name: "ME"}); // spawn
        socket.emit("10", "ME"); // request to join clan
    });
}
socket.once("connect", () => {
    socket.emit("1", {
        name: "ME"
    }); // spawn
    socket.emit("8", "ME"); // create clan
    console.log("Clan created");
});

team = [];

var i = 0;
setInterval(() => spawn(i), 3000);
socket.on("an", (a, name) => { // player requests to join clan event
    socket.emit("11", a, 1); // accept invite
    console.log(`${name} successfully joined :)`);
    team.push(a);
    console.log(team);
});
socket.on("ad", (a) => { // player leaves clan event
    for (var c = team.length - 1; c >= 0; c--)
        if (team[c].sid == a) {
            team.splice(c, 1);
            console.log(team[c].name + ' has left');
        }
    console.log(team);
});
socket.on("11", () => { // respawn event
    console.log("I have died, respawning...")
    socket.emit("1", { // spawn event
        name: "ME"
    });
});

Body:
According to the part you described as being broke you shouldn't pass extra variables like this:

socket.emit("11", a, 1); // a = player ID

But rather it should look like this;

socket.emit("11", {
   playerID:a,
   otherVariable:1
});

Which you can acess in your server code by using:

socket.on('11', function(data){
   console.log(data.playerID);
   console.log(data.otherVariable);
});

If you can provide more detail about other problems your having I can try to help you further, but you only highlighted that that emit didn't work and we don't have your backend code to reference here.

Another note, You shouldn't be passing anything but either a single variable (which the documentation still doesn't link and prefers passing via object) or an object. You also shouldn't be using socket.once in this context as it's not needed in my opinion


问:
How to write watchman-make command?
I am wishing to use watchman to rebuild my directory when a change happens.
I am using watchman--make command to initialize the command :

```<code>$ babel ./src/ -d ./lib/
</code>```

Currently I am using:

```<code>$ watchman-make -p "./src/**" -r 'babel ./src/ -d ./lib/'
</code>```

to watch any file change inside src and run the build command.

Watchman is outputting :

```<code># Relative to /home/marc/workspace/abnb
# Changes to files matching ./src/** will execute `babel ./src/ -d ./lib/`
# waiting for changes
</code>```

But nothing seems to happen when I change the files within my direcoty src/

答:
You probably want to rewrite your pattern as src/**/*
Watchman name resolution doesn't (and won't) know to resolve . or .. in path names.  The ** operator matches any directory depth, so you also should specify * to match any file in any directory under the src dir.

Title: How to write watchman-make command?

Body:
I am wishing to use watchman to rebuild my directory when a change happens.
I am using watchman--make command to initialize the command :

$ babel ./src/ -d ./lib/

Currently I am using:

$ watchman-make -p "./src/**" -r 'babel ./src/ -d ./lib/'

to watch any file change inside src and run the build command.

Watchman is outputting :

# Relative to /home/marc/workspace/abnb
# Changes to files matching ./src/** will execute `babel ./src/ -d ./lib/`
# waiting for changes

But nothing seems to happen when I change the files within my direcoty src/


问:
Check for ascending order of a list in Racket
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

```<code>(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))
</code>```

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

答:
Some things to consider when writing functions:

Avoid using built in functions as variable names. For example, list is a built in procedure that returns a newly allocated list, so don't use it as an argument to your function, or as a variable. A common convention/alternative is to use lst as a variable name for lists, so you could have (define (ascending? lst) ...).

Don't quote your variable names. For example, you would have (define lst '(1 2 3 ...)) and not (define 'lst '(1 2 3 ...)).

If you have multiple conditions to test (ie. more than 2), it may be cleaner to use cond rather than nesting multiple if statements.

To fix your implementation of ascending? (after replacing 'list), note on line 3 where you have (> first (first (rest list))). Here you are comparing first with (first (rest list)), but what you really want is to compare (first lst) with (first (rest lst)), so it should be (>= (first lst) (first (rest lst))).

Here is a sample implementation:

```<code>(define (ascending? lst)
  (cond
    [(null? lst) #t]
    [(null? (cdr lst)) #t]
    [(>= (car lst) (cadr lst)) #f]
    [else
     (ascending? (cdr lst))]))
</code>```

or if you want to use first/rest and true/false you can do:

```<code>(define (ascending? lst)
  (cond
    [(empty? lst) true]
    [(empty? (rest lst)) true]
    [(>= (first lst) (first (rest lst))) false]
    [else
     (ascending? (rest lst))]))
</code>```

For example,

```<code>> (ascending? '(1 2 3))
#t
> (ascending? '(1 1 2))
#f
> (ascending? '(3 2 4))
#f
</code>```

Body:
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

Body:
Some things to consider when writing functions:

Avoid using built in functions as variable names. For example, list is a built in procedure that returns a newly allocated list, so don't use it as an argument to your function, or as a variable. A common convention/alternative is to use lst as a variable name for lists, so you could have (define (ascending? lst) ...).

Don't quote your variable names. For example, you would have (define lst '(1 2 3 ...)) and not (define 'lst '(1 2 3 ...)).

If you have multiple conditions to test (ie. more than 2), it may be cleaner to use cond rather than nesting multiple if statements.

To fix your implementation of ascending? (after replacing 'list), note on line 3 where you have (> first (first (rest list))). Here you are comparing first with (first (rest list)), but what you really want is to compare (first lst) with (first (rest lst)), so it should be (>= (first lst) (first (rest lst))).

Here is a sample implementation:

(define (ascending? lst)
  (cond
    [(null? lst) #t]
    [(null? (cdr lst)) #t]
    [(>= (car lst) (cadr lst)) #f]
    [else
     (ascending? (cdr lst))]))

or if you want to use first/rest and true/false you can do:

(define (ascending? lst)
  (cond
    [(empty? lst) true]
    [(empty? (rest lst)) true]
    [(>= (first lst) (first (rest lst))) false]
    [else
     (ascending? (rest lst))]))

For example,

> (ascending? '(1 2 3))
#t
> (ascending? '(1 1 2))
#f
> (ascending? '(3 2 4))
#f


问:
Xcode 8 generates broken NSManagedObject subclasses for iOS 10
I updated my iOS app project recently to iOS 10. Now I'm trying to change the Core Data Model of my app but the new NSManagedObject subclasses which Xcode generates are broken. I also tried to fix the subclasses manual but this doesn't work.

The minimum tools version for the Core Data Model is set to Xcode 7.0 and code generation language is set to Swift.

This is the code which Xcode generates:

```<code>import Foundation
import CoreData
import

extension Group {

    @nonobjc public class func fetchRequest() -> NSFetchRequest {
        return NSFetchRequest(entityName: "Group");
    }

    @NSManaged public var name: String?
    @NSManaged public var platform: NSNumber?
    @NSManaged public var profiles: NSOrderedSet?

}

// MARK: Generated accessors for profiles
extension Group {

    @objc(insertObject:inProfilesAtIndex:)
    @NSManaged public func insertIntoProfiles(_ value: SavedProfile, at idx: Int)

    @objc(removeObjectFromProfilesAtIndex:)
    @NSManaged public func removeFromProfiles(at idx: Int)

    @objc(insertProfiles:atIndexes:)
    @NSManaged public func insertIntoProfiles(_ values: [SavedProfile], at indexes: NSIndexSet)

    @objc(removeProfilesAtIndexes:)
    @NSManaged public func removeFromProfiles(at indexes: NSIndexSet)

    @objc(replaceObjectInProfilesAtIndex:withObject:)
    @NSManaged public func replaceProfiles(at idx: Int, with value: SavedProfile)

    @objc(replaceProfilesAtIndexes:withProfiles:)
    @NSManaged public func replaceProfiles(at indexes: NSIndexSet, with values: [SavedProfile])

    @objc(addProfilesObject:)
    @NSManaged public func addToProfiles(_ value: SavedProfile)

    @objc(removeProfilesObject:)
    @NSManaged public func removeFromProfiles(_ value: SavedProfile)

    @objc(addProfiles:)
    @NSManaged public func addToProfiles(_ values: NSOrderedSet)

    @objc(removeProfiles:)
    @NSManaged public func removeFromProfiles(_ values: NSOrderedSet)

}</code>```

Edit: These are the specific errors which Xcode gives:

```<code>1. Group+CoreDataProperties.swift:13:1: Expected identifier in import declaration (the empty import)
2. Group+CoreDataProperties.swift:13:11: 'Group' is ambiguous for type lookup in this context
3. Group+CoreDataProperties.swift:15:16: Cannot specialize non-generic type 'NSFetchRequest'
4. Group+CoreDataProperties.swift:26:11: 'Group' is ambiguous for type lookup in this context
4. Group+CoreDataProperties.swift:43:82: 'SavedProfile' is ambiguous for type lookup in this context
</code>```

答:
After I renamed the following:

From: YourEntity+CoreDataClass.swift
  To:   YourEntity.swift

and

From: YourEntity+CoreDataProperties.swift
  To: YourEntityCoreDataProperties.swift

then it works.  It looks like "+" is causing the problem.

Body:
I updated my iOS app project recently to iOS 10. Now I'm trying to change the Core Data Model of my app but the new NSManagedObject subclasses which Xcode generates are broken. I also tried to fix the subclasses manual but this doesn't work.

The minimum tools version for the Core Data Model is set to Xcode 7.0 and code generation language is set to Swift.

This is the code which Xcode generates:

import Foundation
import CoreData
import

extension Group {

    @nonobjc public class func fetchRequest() -> NSFetchRequest {
        return NSFetchRequest(entityName: "Group");
    }

    @NSManaged public var name: String?
    @NSManaged public var platform: NSNumber?
    @NSManaged public var profiles: NSOrderedSet?

}

// MARK: Generated accessors for profiles
extension Group {

    @objc(insertObject:inProfilesAtIndex:)
    @NSManaged public func insertIntoProfiles(_ value: SavedProfile, at idx: Int)

    @objc(removeObjectFromProfilesAtIndex:)
    @NSManaged public func removeFromProfiles(at idx: Int)

    @objc(insertProfiles:atIndexes:)
    @NSManaged public func insertIntoProfiles(_ values: [SavedProfile], at indexes: NSIndexSet)

    @objc(removeProfilesAtIndexes:)
    @NSManaged public func removeFromProfiles(at indexes: NSIndexSet)

    @objc(replaceObjectInProfilesAtIndex:withObject:)
    @NSManaged public func replaceProfiles(at idx: Int, with value: SavedProfile)

    @objc(replaceProfilesAtIndexes:withProfiles:)
    @NSManaged public func replaceProfiles(at indexes: NSIndexSet, with values: [SavedProfile])

    @objc(addProfilesObject:)
    @NSManaged public func addToProfiles(_ value: SavedProfile)

    @objc(removeProfilesObject:)
    @NSManaged public func removeFromProfiles(_ value: SavedProfile)

    @objc(addProfiles:)
    @NSManaged public func addToProfiles(_ values: NSOrderedSet)

    @objc(removeProfiles:)
    @NSManaged public func removeFromProfiles(_ values: NSOrderedSet)

}

Edit: These are the specific errors which Xcode gives:

1. Group+CoreDataProperties.swift:13:1: Expected identifier in import declaration (the empty import)
2. Group+CoreDataProperties.swift:13:11: 'Group' is ambiguous for type lookup in this context
3. Group+CoreDataProperties.swift:15:16: Cannot specialize non-generic type 'NSFetchRequest'
4. Group+CoreDataProperties.swift:26:11: 'Group' is ambiguous for type lookup in this context
4. Group+CoreDataProperties.swift:43:82: 'SavedProfile' is ambiguous for type lookup in this context


问:
Difference between {Binding PropertyName} and {Binding Path=PropertyName}
I've seen both styles used in the same project, and I wonder if there's any semantic difference between them, or if any would be recommended over the other and why.</p>

答:
They mean the same thing. Where they differ is in how the Binding object is instantiated and populated.

```<code>{Binding Path=Foo}
</code>```

creates a Binding instance using its parameterless constructor, and then sets the instance's Path property.

```<code>{Binding Foo}
</code>```

creates a Binding instance using its single-parameter constructor, and passes the value "Foo" to that constructor parameter. The single-parameter constructor just sets the Path property, which is why the two syntaxes are equivalent.

It's very much like the syntax for custom attributes, where you can also pass constructor parameters and/or set property values.

Body:
They mean the same thing. Where they differ is in how the Binding object is instantiated and populated.

{Binding Path=Foo}

creates a Binding instance using its parameterless constructor, and then sets the instance's Path property.

{Binding Foo}

creates a Binding instance using its single-parameter constructor, and passes the value "Foo" to that constructor parameter. The single-parameter constructor just sets the Path property, which is why the two syntaxes are equivalent.

It's very much like the syntax for custom attributes, where you can also pass constructor parameters and/or set property values.


问:
How to replace a string in a SQL Server Table Column
I have a table (SQL Sever) which references paths (UNC or otherwise), but now the path is going to change.

In the path column, I have many records and I need to change just a portion of the path, but not the entire path. And I need to change the same string to the new one, in every record.

How can I do this with a simple update?

答:
You also can replace large text for email template at run time, here is an simple example for that.

DECLARE @xml NVARCHAR(MAX)
SET @xml = CAST((SELECT [column] AS 'td','',
        ,[StartDate] AS 'td'
         FROM [table]
         FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
select REPLACE((EmailTemplate), '[@xml]', @xml) as Newtemplate
FROM [dbo].[template] where id = 1
```


问:
python: how to get information about a function?
When information about a type is needed you can use:

```<code>my_list = []
dir(my_list)
</code>```

gets:

```<code>['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
</code>```

or:

```<code>dir(my_list)[36:]
</code>```

gets:

```<code>['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
</code>```

Now, in the documentation of Python information can be found about these functions, but I would like to get info about these functions in the terminal/command-line.
How should this be done?

答:
Or

```<code>help(list.append)
</code>```

if you're generally poking around.

Body:
When information about a type is needed you can use:

my_list = []
dir(my_list)

gets:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

or:

dir(my_list)[36:]

gets:

['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Now, in the documentation of Python information can be found about these functions, but I would like to get info about these functions in the terminal/command-line.
How should this be done?

Body:
Or

help(list.append)

if you're generally poking around.


问:
I want to Insert RadioButton Value in SQL Database using Classes
I created a Class name EmployeeDAta write this code here  and i want to Insert Radiobutton value in SQL Database </p>

```<code> public static void AddEmployee(Employee employee)
        {
            string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);

            using (conn)
            {
                SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = employee.Name;
                cmd.Parameters.Add("@FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
                cmd.Parameters.Add("@Address", SqlDbType.NVarChar, 50).Value = employee.Address;
                cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = employee.Email;
                cmd.Parameters.Add("@Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
                cmd.Parameters.Add("@Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
                cmd.Parameters.AddWithValue("@VB", SqlDbType.Bit).Value = employee.VB;
                cmd.Parameters.AddWithValue("@ASP", SqlDbType.Bit).Value = employee.ASP;
                cmd.Parameters.AddWithValue("@Gender", SqlDbType.Int).Value = employee.Gender;
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }
</code>```

答:
add a parameter to your stored procedure call:

```<code>cmd.Parameters.AddWithValue("@ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;
</code>```

In the stored procedure on the database, make sure you handle the extra parameter.

Body:
I created a Class name EmployeeDAta write this code here  and i want to Insert Radiobutton value in SQL Database

 public static void AddEmployee(Employee employee)
        {
            string connString = ConfigurationManager.ConnectionStrings["Employee"].ConnectionString;
            SqlConnection conn = new SqlConnection(connString);

            using (conn)
            {
                SqlCommand cmd = new SqlCommand("ADDEMPLOYEE", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50).Value = employee.Name;
                cmd.Parameters.Add("@FName", SqlDbType.NVarChar, 50).Value = employee.Fname;
                cmd.Parameters.Add("@Address", SqlDbType.NVarChar, 50).Value = employee.Address;
                cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 50).Value = employee.Email;
                cmd.Parameters.Add("@Mobile", SqlDbType.NVarChar, 50).Value = employee.Mobile;
                cmd.Parameters.Add("@Pincode", SqlDbType.NVarChar, 50).Value = employee.Pincode;
                cmd.Parameters.AddWithValue("@VB", SqlDbType.Bit).Value = employee.VB;
                cmd.Parameters.AddWithValue("@ASP", SqlDbType.Bit).Value = employee.ASP;
                cmd.Parameters.AddWithValue("@Gender", SqlDbType.Int).Value = employee.Gender;
                conn.Open();
                cmd.ExecuteNonQuery();
            }
        }

Body:
add a parameter to your stored procedure call:

cmd.Parameters.AddWithValue("@ValueOfRadioButtonr", SqlDbType.Int).Value = MyRadioButton.Value;

In the stored procedure on the database, make sure you handle the extra parameter.


问:
Microsoft Office Document's Viewer Component
We need a user control that can show Microsoft Office files (Word, Excel..). There is no need for editing them.

As I can see, there are available standalone viewer applications that can be downloaded from Microsoft site, but I am wondering if it could be embedded within an user control.

I think that there could be a COM/ActiveX component, but I cannot check that because I have Office installed, so I have to install viewers on the clean machine.

Does anyone have any experience regarding this?

答:
I would avoid considering the use of the Office viewers as COM object providers (even if they do register the Office COM components.) As far as I can interpret the license (I'm not a lawyer but have had to read and discuss my share of EULAs over the years), you are NOT allowed to use anything provided by the Office viewers in your application. The relevant clause of the license (right at the start):

INSTALLATION AND USE RIGHTS.

a.  General.  You may install and use any  number of copies of the software on your devices.  You may use the software only to view and print files created with Microsoft Office software.  You may not use the software for any other purpose.

I'd steer clear of gray areas in Microsoft licensing. What you want might not be expressly forbidden ($deity knows EULAs are a pain to interpret), but it's definitely not allowed by the spirit of the license. Since you might get taken to court if they want to, and since clarifying gray areas costs a lot of money, and since they have deep pockets... I think you see where I'm going with this.

If you're going to lock your users into Office, you typically have to bite the bullet and require your users to buy Office licenses.

OwnerDisplayName: Nenad

LastEditorDisplayName: moocha

OwnerDisplayName: moocha


问:
How to set the tool tip on jqGrid mouse over?
How can you set the "tool tip" that appears when you hover your mouse over a jqGrid row/cell?

Currently the tool tip appears to just be the cell contents.

答:
In general I agree with Justin, that jqGrid get you no direct way to set tooltip on the row, you can do this only on the cell basis. So you have to do this manually.

First of all you should set title:false property on all cells to have no tooltip for the cells. Then you have to set your custom tooltips of every row. You can do this for example inside of loadComplete event handle. The corresponding code can be about following:

```<code>loadComplete: function() {
    var ids = grid.jqGrid('getDataIDs');
    for (var i=0;i<ids.length;i++) {
        var id=ids[i];
        var rowData = grid.jqGrid('getRowData',id);
        $('#'+id,grid[0]).attr('title', rowData.Name + ' (' +
                                        rowData.Category + ', ' +
                                        rowData.Subcategory + ')');
    }
}
</code>```

You can see the corresponding example you can see live here.

UPDATED: In more late versions of jqGrid there are much more effective way to set custom title. It's the usage of cellattr (see the answer for an example) or the usage of rowattr (see the answer). I recommend to use gridview: true option of jqGrid always. The usage of cellattr or rowattr together with gridview: true allows to create full grid body inclusive of all tooltips which one need in one modification of the page (the full HTML fragment of grid body inclusive of all tooltips will be assigned to innerHTML property). The usage of .attr in the loop follows at least to reflow which is expansive (see here). So the usage of cellattr and rowattr in combination with gridview: true allow to achieve the best performance.

Body:
In general I agree with Justin, that jqGrid get you no direct way to set tooltip on the row, you can do this only on the cell basis. So you have to do this manually.

First of all you should set title:false property on all cells to have no tooltip for the cells. Then you have to set your custom tooltips of every row. You can do this for example inside of loadComplete event handle. The corresponding code can be about following:

loadComplete: function() {
    var ids = grid.jqGrid('getDataIDs');
    for (var i=0;i<ids.length;i++) {
        var id=ids[i];
        var rowData = grid.jqGrid('getRowData',id);
        $('#'+id,grid[0]).attr('title', rowData.Name + ' (' +
                                        rowData.Category + ', ' +
                                        rowData.Subcategory + ')');
    }
}

You can see the corresponding example you can see live here.

UPDATED: In more late versions of jqGrid there are much more effective way to set custom title. It's the usage of cellattr (see the answer for an example) or the usage of rowattr (see the answer). I recommend to use gridview: true option of jqGrid always. The usage of cellattr or rowattr together with gridview: true allows to create full grid body inclusive of all tooltips which one need in one modification of the page (the full HTML fragment of grid body inclusive of all tooltips will be assigned to innerHTML property). The usage of .attr in the loop follows at least to reflow which is expansive (see here). So the usage of cellattr and rowattr in combination with gridview: true allow to achieve the best performance.


问:
Inconsistant results: "select * from sysobjects where ID = object_ID(N'TableName') and OBJECTPROPERTY(ID, N'IsUserTable') = 1"
I scripted our development database locally. The Stored procedures in our app has code all over the place that checks to see if a table exists and if so, drops the table and recreates it. I noticed that when I run the code in my local database that the check to see if the table exists does not work the same as when running in development. In particular, I noticed that the OBJECTPROPERTY(ID, N'IsUserTable') returns NULL when running locally but returns 1 in DEV.

```<code>if exists (select * from [CLASS].DBO.sysobjects where ID = object_ID(N'[CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
    PRINT 'EXISTS!'
    drop table [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]
END
    ELSE PRINT 'NO!'
GO

CREATE TABLE [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT] (
    [CLIENT_ID] [bigint] NULL ,
    [CLIENT_Name] [char] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [GOC] [char] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [AC_DATE] [datetime] NULL ,
    [EFF_Date] [datetime] NULL ,
    [AC_STATUS] [char] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [REPORTING_DATE] [datetime] NULL,
    [V2V_IND] [char] (1) NULL,  --2017.10
    [LAST_OPER_ID] [char] (8) NULL,
    [LAST_TIMESTAMP] [datetime] NULL
) ON [PRIMARY]
GO
</code>```

```<code>NO!
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'CDB_SCRB_CLIENT_ACCOUNT' in the database.
.
</code>```

I know that if I change the check as follows

```<code>if exists (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CDB_SCRB_CLIENT_ACCOUNT]') AND type in (N'U'))
drop table [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]
</code>```

that it will work, but I do not want to change many occurences of this code just to run the app on my local database.

```<code>SELECT @@version --on dev server
Microsoft SQL Server 2012 (SP3-CU7) (KB3205051) - 11.0.6579.0 (X64)
    Dec 22 2016 11:18:09
    Copyright (c) Microsoft Corporation
    Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)

SELECT @@version --on local workstation
Microsoft SQL Server 2012 (SP1) - 11.0.3156.0 (X64)
    May  4 2015 18:48:09
    Copyright (c) Microsoft Corporation
    Developer Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
</code>```

When I script the tables in each table, they appear to be same same.  What could explain the difference?

答:
The problem you are experiencing is that OBJECTPROPERTY is scoped to the current database. Rather than use that you could use the object_type option in your OBJECT_ID call (so OBJECT_ID(N'Database.Schema.ObjectName', 'U') where U represents a user table (you can check the relevant object_type value from the type column in sys.objects).

You can also simplify your query by just checking for the existence of the object_id, so no need to query again sys.objects in that database.

This would make your query look like the following:

```<code>IF (SELECT object_ID(N'[CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]', 'U')) IS NOT NULL
BEGIN
    PRINT 'EXISTS!'
    drop table [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]
END
    ELSE PRINT 'NO!'
GO

CREATE TABLE [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT] (
    [CLIENT_ID] [bigint] NULL ,
    [CLIENT_Name] [char] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [GOC] [char] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [AC_DATE] [datetime] NULL ,
    [EFF_Date] [datetime] NULL ,
    [AC_STATUS] [char] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [REPORTING_DATE] [datetime] NULL,
    [V2V_IND] [char] (1) NULL,  --2017.10
    [LAST_OPER_ID] [char] (8) NULL,
    [LAST_TIMESTAMP] [datetime] NULL
) ON [PRIMARY]
GO
</code>```

Body:
I scripted our development database locally. The Stored procedures in our app has code all over the place that checks to see if a table exists and if so, drops the table and recreates it. I noticed that when I run the code in my local database that the check to see if the table exists does not work the same as when running in development. In particular, I noticed that the OBJECTPROPERTY(ID, N'IsUserTable') returns NULL when running locally but returns 1 in DEV.

if exists (select * from [CLASS].DBO.sysobjects where ID = object_ID(N'[CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]') and OBJECTPROPERTY(ID, N'IsUserTable') = 1)
BEGIN
    PRINT 'EXISTS!'
    drop table [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]
END
    ELSE PRINT 'NO!'
GO

CREATE TABLE [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT] (
    [CLIENT_ID] [bigint] NULL ,
    [CLIENT_Name] [char] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [GOC] [char] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [AC_DATE] [datetime] NULL ,
    [EFF_Date] [datetime] NULL ,
    [AC_STATUS] [char] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [REPORTING_DATE] [datetime] NULL,
    [V2V_IND] [char] (1) NULL,  --2017.10
    [LAST_OPER_ID] [char] (8) NULL,
    [LAST_TIMESTAMP] [datetime] NULL
) ON [PRIMARY]
GO

NO!
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'CDB_SCRB_CLIENT_ACCOUNT' in the database.
.

I know that if I change the check as follows

if exists (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CDB_SCRB_CLIENT_ACCOUNT]') AND type in (N'U'))
drop table [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]

that it will work, but I do not want to change many occurences of this code just to run the app on my local database.

SELECT @@version --on dev server
Microsoft SQL Server 2012 (SP3-CU7) (KB3205051) - 11.0.6579.0 (X64)
    Dec 22 2016 11:18:09
    Copyright (c) Microsoft Corporation
    Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)

SELECT @@version --on local workstation
Microsoft SQL Server 2012 (SP1) - 11.0.3156.0 (X64)
    May  4 2015 18:48:09
    Copyright (c) Microsoft Corporation
    Developer Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)

When I script the tables in each table, they appear to be same same.  What could explain the difference?

Body:
The problem you are experiencing is that OBJECTPROPERTY is scoped to the current database. Rather than use that you could use the object_type option in your OBJECT_ID call (so OBJECT_ID(N'Database.Schema.ObjectName', 'U') where U represents a user table (you can check the relevant object_type value from the type column in sys.objects).

You can also simplify your query by just checking for the existence of the object_id, so no need to query again sys.objects in that database.

This would make your query look like the following:

IF (SELECT object_ID(N'[CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]', 'U')) IS NOT NULL
BEGIN
    PRINT 'EXISTS!'
    drop table [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT]
END
    ELSE PRINT 'NO!'
GO

CREATE TABLE [CLASS].DBO.[CDB_SCRB_CLIENT_ACCOUNT] (
    [CLIENT_ID] [bigint] NULL ,
    [CLIENT_Name] [char] (70) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [GOC] [char] (3) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [AC_DATE] [datetime] NULL ,
    [EFF_Date] [datetime] NULL ,
    [AC_STATUS] [char] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [REPORTING_DATE] [datetime] NULL,
    [V2V_IND] [char] (1) NULL,  --2017.10
    [LAST_OPER_ID] [char] (8) NULL,
    [LAST_TIMESTAMP] [datetime] NULL
) ON [PRIMARY]
GO


问:
Log when a website is published
Does VS Teams services have an agent to log when a website is published in Visual Studio 2015? I am new to Team Services. I have a small team of developers, 4 including myself. We have recently migrated from TFS 2010 to Team Services. Part of our PCI compliance, we need to log when our sites are published. We currently publish to an IIS server.</p>

答:
No, all actions are in local and not related to VS Team Services, so VS Team Service can’t log anything.

You can build and publish/deploy the web app to IIS through VS Team Service build and release system, then you can check the related information of that build/release (e.g. detail build/release log)

More information, you can refer to this article: Deploy your Web Deploy package to IIS servers

Title: Log when a website is published


问:
Functions using tuple in Swift 3.1
I have a sample code(following).
It works very well in Swift 3.0.2 but Swift 3.1 does not.

What kind of problems?

How to resolve this problem?

```<code>typealias abcTuple = (a: CGFloat, b: CGFloat, c: CGFloat)
class SomeClass: NSObject {

    var a: CGFloat = 0.0
    var b: CGFloat = 0.0
    var c: CGFloat = 0.0

    func setValues(a: CGFloat, b: CGFloat, c: CGFloat) {
        self.a = a
        self.b = b
        self.c = c
    }

    func setValues(_ values: abcTuple) {
        self.a = values.a
        self.b = values.b
        self.c = values.c
    }

    func showValues() {
        print("a: \(self.a) b: \(self.b) c: \(self.c)")
    }
}
</code>```

答:
If you change the name of the second setValues method to something different like setTuple, the code will compile fine. For example, I defined the second method as:

```<code>func setTuple(_ values: abcTuple) {
    self.a = values.a
    self.b = values.b
    self.c = values.c
}
</code>```

And everything compiles fine.

Title: Functions using tuple in Swift 3.1

Body:
I have a sample code(following).
It works very well in Swift 3.0.2 but Swift 3.1 does not.

What kind of problems?

How to resolve this problem?

typealias abcTuple = (a: CGFloat, b: CGFloat, c: CGFloat)
class SomeClass: NSObject {

    var a: CGFloat = 0.0
    var b: CGFloat = 0.0
    var c: CGFloat = 0.0

    func setValues(a: CGFloat, b: CGFloat, c: CGFloat) {
        self.a = a
        self.b = b
        self.c = c
    }

    func setValues(_ values: abcTuple) {
        self.a = values.a
        self.b = values.b
        self.c = values.c
    }

    func showValues() {
        print("a: \(self.a) b: \(self.b) c: \(self.c)")
    }
}

Body:
If you change the name of the second setValues method to something different like setTuple, the code will compile fine. For example, I defined the second method as:

func setTuple(_ values: abcTuple) {
    self.a = values.a
    self.b = values.b
    self.c = values.c
}

And everything compiles fine.


问:
report filename that is being checked
How to make pylint print filename (and maybe counter) of that it checks at the moment?

Documentation shows how to format messages if a problem is found, but not how to report progress. https://pylint.readthedocs.io/en/latest/user_guide/output.html

答:
This currently isn't possible. It's easy to add to pylint's code:

```<code>index 258bfdc3..30bac9f1 100644
--- a/pylint/lint.py
+++ b/pylint/lint.py
@@ -839,6 +839,8 @@ class PyLinter(config.OptionsManagerMixIn,
             if not self.should_analyze_file(modname, filepath, is_argument=is_arg):
                 continue

+            print(modname)
+
             self.set_current_module(modname, filepath)
             # get the module representation
             ast_node = self.get_ast(filepath, modname)
</code>```

but I never got to making this a proper pull request with an option and all.

Title: report filename that is being checked

Body:
This currently isn't possible. It's easy to add to pylint's code:

index 258bfdc3..30bac9f1 100644
--- a/pylint/lint.py
+++ b/pylint/lint.py
@@ -839,6 +839,8 @@ class PyLinter(config.OptionsManagerMixIn,
             if not self.should_analyze_file(modname, filepath, is_argument=is_arg):
                 continue

+            print(modname)
+
             self.set_current_module(modname, filepath)
             # get the module representation
             ast_node = self.get_ast(filepath, modname)

but I never got to making this a proper pull request with an option and all.


问:
Yii2 Kartik Grid View Export Config
Summary: Trying to add export in the for csv & pdf download.

Followed documantation to install. Grid view is otherwise working.

Also added as module in config/web.php's $config array -

```<code>'modules' => [
        'gridview' =>  [
            'class' => '\kartik\grid\Module',
            // enter optional module parameters below - only if you need to
            // use your own export download action or custom translation
            // message source
             'downloadAction' => 'gridview/export/download',
             'i18n' => [
                 //'class' => 'yii\i18n\PhpMessageSource',
                 //'basePath' => '@kvgrid/messages',
                 //'forceTranslation' => false
             ]
        ]
    ],
</code>```

N.B: I am using basic template and new in yii2. I have tried other fixes like composer update etc as suggested in various posts but really stuck with the problem.

the thing causing problem is - Yii::t('kvgrid', 'Reset Grid')

Can somene give me a direction here. I guess it is very simple issue :(

答: I suggest better to generate CRUD using the Ajax Crud Generator, it will do all the required task for CRUD and export as well...try this</p>

Title: Yii2 Kartik Grid View Export Config

Body:
Summary: Trying to add export in the for csv & pdf download.

Followed documantation to install. Grid view is otherwise working.

Also added as module in config/web.php's $config array -

'modules' => [
        'gridview' =>  [
            'class' => '\kartik\grid\Module',
            // enter optional module parameters below - only if you need to
            // use your own export download action or custom translation
            // message source
             'downloadAction' => 'gridview/export/download',
             'i18n' => [
                 //'class' => 'yii\i18n\PhpMessageSource',
                 //'basePath' => '@kvgrid/messages',
                 //'forceTranslation' => false
             ]
        ]
    ],

N.B: I am using basic template and new in yii2. I have tried other fixes like composer update etc as suggested in various posts but really stuck with the problem.

the thing causing problem is - Yii::t('kvgrid', 'Reset Grid')

Can somene give me a direction here. I guess it is very simple issue :(


问:
jQuery - header flashes on and off
Hello guys here is my jQuery:

```<code><script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
    $( document ).ready(function() {
        $(window).scroll(function(){
            scroll = $(window).scrollTop();
            if (scroll > 100 && scroll < 300){
                $('#header').fadeOut();
            }

            if (scroll > 300){
                $('#header').fadeIn();
            }
        });
    });
</script>
</code>```

The #header is hidden by default, and I want it to unhide further down the page, but if I change any of the numbers in that jQuery the header will just flash on and off. I don't understand the code well enough to understand why that's happening.

答:
The on and off effect (blinking efffect) is mainly due to 1 pixel that your fade effect is missing. So just use :
scroll >= 300 instead of : scroll > 300

Title: jQuery - header flashes on and off

Body:
Hello guys here is my jQuery:

The #header is hidden by default, and I want it to unhide further down the page, but if I change any of the numbers in that jQuery the header will just flash on and off. I don't understand the code well enough to understand why that's happening.


问:
Calculate the percentage for python dictionary
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

```<code>from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()
</code>```

答: You probably want to use len(d.values()) to get the number of items, unless I'm missing something. Can you please share what the dictionary (d) looks like? (i.e. the output of print d?)</p>

Body:
I want to calculate the percentage of the occurrences of the values in a dictionary. d.values/sum(d.values)*100 it gives error: unsupported operand type(s) for /: 'list' and 'int' you cannot divide the whole list with any integer. I think, and I tried with  d=(Counter([Counter(i)['1'] for i in  f.readlines()])) at the time of counting you can calculate the percentage but it didn't work. If anyone has an idea, please let me known.

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
import pylab as pl
with open("data_binary.txt") as f:
    d=(Counter([Counter(i)['1'] for i in  f.readlines()]))
    print d

    p = d.values()
    X = np.arange(len(d))
    pl.bar(X, p, align='center',width=0.25)
    a = np.array(d.items())
    pl.xticks(X,d.keys())
    a = a[np.argsort(a[:,0])]
    #print a
    ymax=max(d.values())+1
    pl.ylim(0, 70000)
    plt.xlabel ("Number of ones")
    plt.ylabel ("Number of Signatures")
    plt.title("Adder@1")
    pl.show()


问:
Getting error in button position change in swift 3
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here</p>

```<code>if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }
</code>```

答:
origin is a CGPoint, not a CGRect

You'd need to do something like:

```<code>button.frame.origin = CGPoint(x: 0, y: 0)
</code>```

Body:
I'm using the below-mentioned code for changing the position of button in swift 3 for 6s but I got the error like this Value of type '(Any) -> ()' has no member 'frame'. I'm stuck here

if screenHeight == 667{

  //  self.forgetPasswordBtn.frame = CGRect(x: 0, y: 25, width: screenWidth, height: 30)
        nextBtn.frame.origin = CGRect(x:0,y:0)

    }

Body:
origin is a CGPoint, not a CGRect

You'd need to do something like:

button.frame.origin = CGPoint(x: 0, y: 0)


问:
Where does Selenium store the DOM, if at all?
I'm trying to understand the performance impacts of things like WebDriver.findBy(...). For example if I was using Selenium to drive a local Chrome instance:

```<code>WebElement betty = webDriver.findBy(By.id("betty"));
</code>```

Does the Selenium library

a) have the DOM within the JVM to evaluate?

b) go to the local Chrome driver binary to evaluate?

c) go to the browser instance to evaluate?

And does the answer change for a Grid situation?

答:
I found a nice technical guide that explains this.

The browser driver uses an HTTP SERVER which waits continuously for
new Selenium commands.

It has the following purposes:

read HTTP requests coming from the client (client = computer that executes the test automation scripts)

determines the series of steps needed for implementing the Selenium command

sends the implementation steps to the browser

gets the execution status from the browser

send the execution status back to the client

For each Selenium command of the automation script, a http request with a specific path is created.

When the automation script is executed, the first http request generates a new session that is specific to the browser where the automation scripts run.

The session id will be used for the http requests that correspond to all other
Selenium commands from the automation script.

Body:
I'm trying to understand the performance impacts of things like WebDriver.findBy(...). For example if I was using Selenium to drive a local Chrome instance:

WebElement betty = webDriver.findBy(By.id("betty"));

Does the Selenium library

a) have the DOM within the JVM to evaluate?

b) go to the local Chrome driver binary to evaluate?

c) go to the browser instance to evaluate?

And does the answer change for a Grid situation?


问:
Skip JavaScript 'Sys.WebForms..' function when a page doesn't have a ScriptManager
I'm using one JavaScript binds in Master Page for the entire project, and the Master Page doesn't include a ScriptManager, that is, some pages include Ajax components, like UpdatePanel, but some not. The 'Sys.WebForms..' functions set in the 'Global' JavaScript works fine with the page has a ScriptManager, but it will cause JS errors in non-ajax page, e.g. 'Sys is undefined, $find is undefined.'

The message is very annoying, though the it doesn't effect anything.

So any smart solutions?

Is adding ScriptManager to Master Page the best solution? (but need to remove all the ScriptManager in child pages).

Regards

答: If you're going to reference Sys in your global Javascript libraries, then put the ScriptManager on the master page and remove it from the child pages.</p>


问:
Display Customer Firstname and User Meta to New Woocomerce account email
I want to get the the new registrant first name and display it on my email template:

```<code>$firstname = get_user_meta($userid,'first_name',true);
echo '```';
print_r($firstname);
echo '```'
</code>```

But it is not returning the value. Any ideas?

Thanks

答:
The issue was how the user is created and this is my code for creating the user:

```<code>$user = wc_create_new_customer($email,$email,$password);
</code>```

In order to fix that I change the code to:

```<code>$new_customer_data = apply_filters( 'woocommerce_new_customer_data', array(
    'user_login'  => $email,
    'user_pass' => $password  ,
    'first_name'  =>  $firstname ,
    'last_name' =>  $lastname ,
    'user_email'  =>$email ,
    'display_name'  =>  $firstname . ' ' . $lastname  ,
    'nickname'  => $firstname . ' ' . $lastname ,
    'role'    => 'customer'
) );
$user_id = wp_insert_user( $new_customer_data );
</code>```

Body:
I want to get the the new registrant first name and display it on my email template:

$firstname = get_user_meta($userid,'first_name',true);
echo '
';
print_r($firstname);
echo '
'

But it is not returning the value. Any ideas?

Thanks

Body:
The issue was how the user is created and this is my code for creating the user:

$user = wc_create_new_customer($email,$email,$password);

In order to fix that I change the code to:

$new_customer_data = apply_filters( 'woocommerce_new_customer_data', array(
    'user_login'  => $email,
    'user_pass' => $password  ,
    'first_name'  =>  $firstname ,
    'last_name' =>  $lastname ,
    'user_email'  =>$email ,
    'display_name'  =>  $firstname . ' ' . $lastname  ,
    'nickname'  => $firstname . ' ' . $lastname ,
    'role'    => 'customer'
) );
$user_id = wp_insert_user( $new_customer_data );


问:
XSLT split single xml into multiple xmls preserving parent elements
I am trying to split a huge xml(around 300MB) into smaller files based on a repeated child element.

Example below to illustrate the scenario

input.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
            <d id="2">
                <x></x>
                <y></y>
            </d>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

As mentioned above this has a repeated child element . Based on this element, separate output files are expected by keeping its parent elements and attributes intact.

Expected output out_1_a.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

Expected output out_2_a.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="2">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

Expected output out_3_a.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<a>
   <b></b>
   <bb></bb>
   <bbb>
        <c>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>
</a>
</code>```

My xsl - sample.xsl

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">

<xsl:output indent="yes"/>

<xsl:template match="/">
    <xsl:for-each select="a/bbb/c/d">
    <xsl:variable name="i" select="position()" />
    <xsl:result-document method="xml" href="out_{$i}_a.xml">
    <a>
        <b></b>
        <bb></bb>
        <bbb>
            <c>
                <xsl:copy-of select="../@* | ." />
            </c>
        </bbb>
        <e></e>
        <f></f>
    </a>
    </xsl:result-document>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
</code>```

This works ok and I get the output that I desire.
However, I am sure there is a better way to achieve this than hardcoding those parent elements like a, b, bb etc. Also in some cases these parent elements contains attributes and they are dynamic. So hardcoding is something I want to avoid. Any better way to solve this?

答:
You can use this:</p>

```<code><xsl:template match="d">
    <xsl:variable name="name" select="generate-id()"/>
    <xsl:variable name="outputposition"><xsl:value-of select="count(preceding::d)+1"></xsl:value-of></xsl:variable>
    <xsl:result-document method="xml" href="out_{$outputposition}_a.xml" indent="yes">
        <xsl:call-template name="spilit">
            <xsl:with-param name="name" select="$name"/>
            <xsl:with-param name="element" select="root()"/>
        </xsl:call-template>
    </xsl:result-document>
</xsl:template>

<xsl:template name="spilit">
    <xsl:param name="name"/>
    <xsl:param name="element"/>
    <xsl:for-each select="$element[descendant-or-self::d[generate-id() eq $name]]">
        <xsl:choose>
            <xsl:when test="self::d[generate-id() = $name]">
                <xsl:copy>
                    <xsl:copy-of select="@*"></xsl:copy-of>
                    <xsl:copy-of select="node()"></xsl:copy-of>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="preceding-sibling::*"/>
                <xsl:copy>
                    <xsl:call-template name="spilit">
                        <xsl:with-param name="name" select="$name"/>
                        <xsl:with-param name="element" select="child::*[descendant-or-self::d[generate-id() eq $name]]"/>
                    </xsl:call-template>
                </xsl:copy>
                <xsl:copy-of select="following-sibling::*"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>
</code>```

Body:
I am trying to split a huge xml(around 300MB) into smaller files based on a repeated child element.

Example below to illustrate the scenario

input.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
            <d id="2">
                <x></x>
                <y></y>
            </d>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

As mentioned above this has a repeated child element . Based on this element, separate output files are expected by keeping its parent elements and attributes intact.

Expected output out_1_a.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="1">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

Expected output out_2_a.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="2">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

Expected output out_3_a.xml

<?xml version="1.0" encoding="UTF-8"?>

   <bb></bb>
   <bbb>
        <c>
            <d id="3">
                <x></x>
                <y></y>
            </d>
        </c>
    </bbb>
    <e></e>
    <f></f>

My xsl - sample.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">

<xsl:output indent="yes"/>

<xsl:template match="/">
    <xsl:for-each select="a/bbb/c/d">
    <xsl:variable name="i" select="position()" />
    <xsl:result-document method="xml" href="out_{$i}_a.xml">

        <bb></bb>
        <bbb>
            <c>
                <xsl:copy-of select="../@* | ." />
            </c>
        </bbb>
        <e></e>
        <f></f>

    </xsl:result-document>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>

This works ok and I get the output that I desire.
However, I am sure there is a better way to achieve this than hardcoding those parent elements like a, b, bb etc. Also in some cases these parent elements contains attributes and they are dynamic. So hardcoding is something I want to avoid. Any better way to solve this?

Body:
You can use this:

<xsl:template match="d">
    <xsl:variable name="name" select="generate-id()"/>
    <xsl:variable name="outputposition"><xsl:value-of select="count(preceding::d)+1"></xsl:value-of></xsl:variable>
    <xsl:result-document method="xml" href="out_{$outputposition}_a.xml" indent="yes">
        <xsl:call-template name="spilit">
            <xsl:with-param name="name" select="$name"/>
            <xsl:with-param name="element" select="root()"/>
        </xsl:call-template>
    </xsl:result-document>
</xsl:template>

<xsl:template name="spilit">
    <xsl:param name="name"/>
    <xsl:param name="element"/>
    <xsl:for-each select="$element[descendant-or-self::d[generate-id() eq $name]]">
        <xsl:choose>
            <xsl:when test="self::d[generate-id() = $name]">
                <xsl:copy>
                    <xsl:copy-of select="@*"></xsl:copy-of>
                    <xsl:copy-of select="node()"></xsl:copy-of>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy-of select="preceding-sibling::*"/>
                <xsl:copy>
                    <xsl:call-template name="spilit">
                        <xsl:with-param name="name" select="$name"/>
                        <xsl:with-param name="element" select="child::*[descendant-or-self::d[generate-id() eq $name]]"/>
                    </xsl:call-template>
                </xsl:copy>
                <xsl:copy-of select="following-sibling::*"/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>


问:
Find shortest path in maze with landmines and limited lives
I've encountered a problem I'm having a bit of trouble solving. I am trying to write a program that solves an m by n grid maze that has landmines in it. The tricky part is that the player/maze runner has a L >= 1 number of lives, meaning they can step on a maximum of L - 1 landmines before they will die on the next landmine.

Further details:

-Each cell can be connected to any of the adjacent cells. All connections are two-way.

-We can assume that the maze has a correct path from start to end given the number of lives.

-The maze can contain loops or 'islands' where two paths from a given cell lead to the same cell.

My current thoughts:

I have tried a variety of approaches to this problem. There is the obvious brute force solution which involves traversing every possible path and taking the one with the lowest distance. But that is exponential time. I feel that there may be a Dijkstra-like or A*-like solution that leads to O(n + vlogv) time. Vanilla Dijkstra or A* do not lead to solutions for this problem since the state of the graph effectively changes depending on how it is traversed. I have also tried a variety of breadth first search + tracing back to start using priority queue. These schemes, after further investigation, can lead to exponential time.

The most promising idea I've come up with so far involves parsing each maze into a graph and performing a modified Dijkstra. Each cell with three or more connections will be a node. Each cell with two connections is part of a path. Each cell with one connection can be discarded. The end result is a graph. You then perform something similar to Dijkstra, but I have not yet clarified a solution.

I can only guess that this solution requires an algorithm that is efficient in the best case but can become exponential in the worst case.

答:
You should definitely go for Dynamic Programming(DP) style of algorithms.

If you would have added an example maze matrix here then it would have made easy for me to understand the problem.

You problem is quite similar to this. So have a read at it. But before going directly to the solution read this tutorial.


问:
How to get a scatter plot of mixture data with different shape and colour for each distribution?
I am running a simulation of mixture data. My function is harder than Gaussian distribution. Hence, here, I simplified my question to be in Gaussian form. That is, if I simulated a mixture data like this:

```<code>  N=2000
 U=runif(N, min=0,max=1)
 X = matrix(NA, nrow=N, ncol=2)
         for (i in 1:N){
              if(U[i] < 0.7){
               X[i,] <-   rnorm(1,0.5,1)
                    } else {
               X[i,] <- rnorm(1,3,5)
      }
 }
</code>```

How can I have a scatter plot with different colour and shape (type of the plot point) for each cluster or distribution? I would like to have this manually since my function is hard  and complex.  I tried plot(X[,1],X[,2],col=c("red","blue")) but it does not work.

答:
I think this is what you want. Note that I had to do a bit of guesswork here to figure out what was going on, because your example code seems to have an error in it, you weren't generating different x1 and x2 values in each row:

```<code>N=2000
U=runif(N, min=0,max=1)
X = matrix(NA, nrow = N, ncol=2)
for (i in 1:N){
    if(U[i] < 0.7){
        # You had rnorm(n=1, ...) which gives 2 identical values in each row
        # Change that to 2 and you get different X1 and X2 values
        X[i,] <-   rnorm(2, 0.5, 1)
    } else {
        X[i,] <- rnorm(2, 3, 5)
    }
}

df = data.frame(
    source = ifelse(U < 0.7, "dist1", "dist2"),
    x = X[, 1],
    y = X[, 2]
)

library(ggplot2)
ggplot(df, aes(x = x, y = y, colour = source, shape = source)) +
    geom_point()
</code>```

Result:

Body:
I am running a simulation of mixture data. My function is harder than Gaussian distribution. Hence, here, I simplified my question to be in Gaussian form. That is, if I simulated a mixture data like this:

  N=2000
 U=runif(N, min=0,max=1)
 X = matrix(NA, nrow=N, ncol=2)
         for (i in 1:N){
              if(U[i] < 0.7){
               X[i,] <-   rnorm(1,0.5,1)
                    } else {
               X[i,] <- rnorm(1,3,5)
      }
 }

How can I have a scatter plot with different colour and shape (type of the plot point) for each cluster or distribution? I would like to have this manually since my function is hard  and complex.  I tried plot(X[,1],X[,2],col=c("red","blue")) but it does not work.

Body:
I think this is what you want. Note that I had to do a bit of guesswork here to figure out what was going on, because your example code seems to have an error in it, you weren't generating different x1 and x2 values in each row:

N=2000
U=runif(N, min=0,max=1)
X = matrix(NA, nrow = N, ncol=2)
for (i in 1:N){
    if(U[i] < 0.7){
        # You had rnorm(n=1, ...) which gives 2 identical values in each row
        # Change that to 2 and you get different X1 and X2 values
        X[i,] <-   rnorm(2, 0.5, 1)
    } else {
        X[i,] <- rnorm(2, 3, 5)
    }
}

df = data.frame(
    source = ifelse(U < 0.7, "dist1", "dist2"),
    x = X[, 1],
    y = X[, 2]
)

library(ggplot2)
ggplot(df, aes(x = x, y = y, colour = source, shape = source)) +
    geom_point()

Result:


问:
Selenium IDE select window issue
I'm having difficulty selecting a window that pops up using Selenium IDE.  I've tried

```<code>selectWindow(title)
</code>```

and

```<code>selectPopup(title)
</code>```

but they don't seem to work.  Once the window is selected, the

```<code>verifyTitle(title)
</code>```

works just fine, so I started doing some testing and the tests were able to match to objects on the background window.  So it seems that I'm failing to match to the window by title.  I've also tried just using selectWindow / selectPopup with no parameters, but there's no change.

It is important to note that the window is launched through the click of a button, which also creates the name of the window based on its id which isn't available to Selenium, hence we need to launch based on title, not name, and I'm unable to use openWindow or similar since the url etc are generated by the underlying system.  I just need a consistent way to select the popup.

Does anyone know how I can resolve this?

答: I can see this issue was popular in Selenium IDE ...for now, i have an easy way to solve this issue . Why you don't create a new Test Case ? it will select New Window or Popup as you want</p>

Title: Selenium IDE select window issue

Body:
I'm having difficulty selecting a window that pops up using Selenium IDE.  I've tried

selectWindow(title)

and

selectPopup(title)

but they don't seem to work.  Once the window is selected, the

verifyTitle(title)

works just fine, so I started doing some testing and the tests were able to match to objects on the background window.  So it seems that I'm failing to match to the window by title.  I've also tried just using selectWindow / selectPopup with no parameters, but there's no change.

It is important to note that the window is launched through the click of a button, which also creates the name of the window based on its id which isn't available to Selenium, hence we need to launch based on title, not name, and I'm unable to use openWindow or similar since the url etc are generated by the underlying system.  I just need a consistent way to select the popup.

Does anyone know how I can resolve this?


问:
Java sorting parallel arrays, help needed (NullPointerException Error)
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

```<code>    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }
</code>```

It has to be done in java. I am getting an error in the 15th line consisting of

```<code>if(a.compareTo(b) != 0)
</code>```

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.

答:
After your second loop (the for (int j=... one), you have the following code:

```<code>       sDeptArr[i] = sTemp;
       sDeptArr[i] = sDeptArr[iPosMin];
       sDeptArr[iPosMin] = sTemp;
</code>```

From perusing the code, my understanding is that you are trying to swap the elements in sDeptArr[i] and sDeptArr[iPosMin], however, your assignments are incorrect.

Given that it's homework, I think you should try to work out why this code won't work, and gives you the result that it does.  You could step through the code in a debugger, or (given that it's fairly straightforward) step through the code in your head.

Body:
Ok I am trying to finish this program for my into to java class and I am having trouble with this one part. Everything else is working except this. I have 3 arrays, 1 string, 2 type int, all parallel. I have to sort these into alphabetical order by name then by number (using the string array first, then the first int array, sorting is not affected by the third array, it is there to practice parallel in 3 dimensions)

This is the code I have so far.

    public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("Sort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i;
           for(int j=i+1; j<numRecords; j++)
           {
               String a = sDeptArr[j];
               String b = sDeptArr[iPosMin];
               if(a.compareTo(b) != 0)
                   iPosMin = j;
               else if(!sDeptArr[j].equals(sDeptArr[iPosMin]) && iCourseNumArr[j] < iCourseNumArr[iPosMin])
                   iPosMin = j;
           }
           sDeptArr[i] = sTemp;
           sDeptArr[i] = sDeptArr[iPosMin];
           sDeptArr[iPosMin] = sTemp;
           iCourseNumArr[i] = iTemp;
           iCourseNumArr[i] = iCourseNumArr[iPosMin];
           iCourseNumArr[iPosMin] = iTemp;
           iEnrollmentArr[i] = eTemp;
           iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
           iEnrollmentArr[iPosMin] = eTemp;
       }
   }

It has to be done in java. I am getting an error in the 15th line consisting of

if(a.compareTo(b) != 0)

and I am getting a NullPointerException.

Basically I am sorting fake class names and course numbers while keeping the number of people enrolled parallel with its corresponding index to the course name and number.

Body:
After your second loop (the for (int j=... one), you have the following code:

       sDeptArr[i] = sTemp;
       sDeptArr[i] = sDeptArr[iPosMin];
       sDeptArr[iPosMin] = sTemp;

From perusing the code, my understanding is that you are trying to swap the elements in sDeptArr[i] and sDeptArr[iPosMin], however, your assignments are incorrect.

Given that it's homework, I think you should try to work out why this code won't work, and gives you the result that it does.  You could step through the code in a debugger, or (given that it's fairly straightforward) step through the code in your head.