问:
How do I Unit Test a method that returns IEnumerable
Please see the code below:

```<code>public IEnumerable<int> Numbers()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
    yield return 5;
}
</code>```

and the unit test below:

```<code>public void GetNumbers()
{
    ClassToTest c = new ClassToTest();
    var expected =
    var actual = c.Numbers();
    CollectionAssert.AreEqual(expected, actual);
}
</code>```

I need help populating the line that starts: var expected

Do I have to cast to a list for the assert to work.  Please notice that order is important i.e. the two collections must have numbers in the order of: 1,2,3,4,5.

Please note the code above is not a real test.  I have used it to explain my problem.

答:
Try:</p>

```<code>ClassToTest c = new ClassToTest();

var expected = int[] { 1, 2, 3, 4, 5 };
var actual = c.Numbers().ToArray();

CollectionAssert.AreEqual(expected, actual);
</code>```

Body:
Please see the code below:

public IEnumerable<int> Numbers()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
    yield return 5;
}

and the unit test below:

public void GetNumbers()
{
    ClassToTest c = new ClassToTest();
    var expected =
    var actual = c.Numbers();
    CollectionAssert.AreEqual(expected, actual);
}

I need help populating the line that starts: var expected

Do I have to cast to a list for the assert to work.  Please notice that order is important i.e. the two collections must have numbers in the order of: 1,2,3,4,5.

Please note the code above is not a real test.  I have used it to explain my problem.

Body:
Try:

ClassToTest c = new ClassToTest();

var expected = int[] { 1, 2, 3, 4, 5 };
var actual = c.Numbers().ToArray();

CollectionAssert.AreEqual(expected, actual);


来源: stackexchange

问:
Release bitmaps on pagetransform() method in viewpager
I have three fragment in viewpager each of which comprises of recyclerview showing images. As the images are large and also some of them are GIF, I am getting OOM errors in low devices. I also tried setting viewpageroffscreenlimit to one, but then page swiping lags because adapter is set again. Delaying setting adapter on pageselected gives bad user experience.

I am using glide in loading images. I just want that my content remains as it is, but image releases on page change and when user comes back to that page only images are loaded again. I read about Glide.clear but don't know where to implement it. Actually I want to retain all three fragments but simultaneously release all images when page is changed.

答:
You can change bitmap format: https://github.com/bumptech/glide/wiki/Configuration#bitmap-format

Also if I remember correctly Glide always tries to load best fitting image into ImageView. If your view is defined as wrap_content it loads as big image as possible, in such case you might define ImageView dimensions with precise dp or match_parent.

If you would share some XML and ViewHolders code I would be able to better pin point places for optimisation.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
How to limit a container's width to X when it contains a wider (>X) image?
I need my div element to be as wide as the screen even when its child image element is wider than that. Is that possible? I tried overflow: hidden on the div to no avail.

```<code><div>
    <img src="image.jpg">
</div>
</code>```

答:
In your CSS file</p>

```<code>img {
  height:auto;
  max-width:100%;
}
</code>```

Body:
In your CSS file

img {
  height:auto;
  max-width:100%;
}


问:
What is the impact of block report error?
Today,i find my datanode always throw block report exception.such as Unsuccessfully sent block report 0x706cd6d00df0e93f,  containing 1 storage report(s), of which we sent 0. The reports had 9011145 total blocks and used 0 RPC(s). This took 1775 msec to generate and 238 msecs for RPC and NN processing. Got back no commands.,But my hdfs's read/write all run very well.

I need to solve this problem?

答:
Data Node's send what blocks are there, how many are corrupted, how many are over/under replicated. Based on this block report information, NameNode will build the above mapping in FSimage. When clients request for a specificl file, Name Node will look into the FSimage (mapping) and give the path/Data Node to the client.

fsimage – An fsimage file contains the complete state of the file system at a point in time. Every file system modification is assigned a unique, monotonically increasing transaction ID. An fsimage file represents the file system state after all modifications up to a specific transaction ID.


问:
How can I get my counter to stop at a defined point?
I have built a counter that goes up by a number but I want it to stop when it gets to a defined point (end_value) and I'm not really sure where to even start with this.

My code currently looks like this:

```<code>var increment = 1;
var start_value = 1;
var count = 0;
var end_value = 10;

window.onload = function(){

    var interval_time = 1 * 1500;

    count = parseInt (start_value);
    document.getElementById('counter').innerHTML = count;

    setInterval("count += increment; document.getElementById('counter').innerHTML = count;", interval_time);
}
</code>```

Thanks guys

答:
Assign your interval to a variable.

var my_interval = setInterval(function(){}, interval_time);

Run a loop or use callback to clear the interval

clearInterval(my_interval)

Body:
I have built a counter that goes up by a number but I want it to stop when it gets to a defined point (end_value) and I'm not really sure where to even start with this.

My code currently looks like this:

var increment = 1;
var start_value = 1;
var count = 0;
var end_value = 10;

window.onload = function(){

    var interval_time = 1 * 1500;

    count = parseInt (start_value);
    document.getElementById('counter').innerHTML = count;

    setInterval("count += increment; document.getElementById('counter').innerHTML = count;", interval_time);
}

Thanks guys


问:
Having a single default argument in a controller action expecting multiple
My controller action expects several arguments, but only one can be nullable on POST. It is of type decimal. Based on the research I've done for default routing, it looks limited to setting a default value for an action expecting a single parameter.

This is the response message I get due to this:

MVC : The parameters dictionary contains a null entry for parameter 'z' of non-nullable type 'System.Decimal'

Here is the method signature in BarController.cs:

```<code>[HttpPost]
public PartialViewResult Bar(int x, string y, decimal z) {*/Etc*/}
</code>```

Here is the route I attempted but was not successful (RouteConfig.cs):

```<code>routes.MapRoute(name: "Bar", url: "Foo/Bar/z",
defaults: new {controller = "Foo", action = "Bar", z= 0 });
</code>```

My request body has values for x and z, but y can be nullable.

How do I refactor so that z can be nullable? Apart from literally making it a nullable decimal type. I already have algorithms that subscribe to the Decimal type, not the nullable variant.

答:
You can do your "int" or "decimal" parameters Nullable as well.

```<code>public PartialViewResult Bar(string y, decimal? z, int? x) {*/Etc*/}
</code>```

Notice that in this case, you will have to validate the input in order of checking if "x" or "y" have values. In Check an integer value is Null in c# you can find some ways of validating a Nullable integer variable. The same approach could be used for checking if the decimal parameter is null.

Body:
My controller action expects several arguments, but only one can be nullable on POST. It is of type decimal. Based on the research I've done for default routing, it looks limited to setting a default value for an action expecting a single parameter.

This is the response message I get due to this:

MVC : The parameters dictionary contains a null entry for parameter 'z' of non-nullable type 'System.Decimal'

Here is the method signature in BarController.cs:

[HttpPost]
public PartialViewResult Bar(int x, string y, decimal z) {*/Etc*/}

Here is the route I attempted but was not successful (RouteConfig.cs):

routes.MapRoute(name: "Bar", url: "Foo/Bar/z",
defaults: new {controller = "Foo", action = "Bar", z= 0 });

My request body has values for x and z, but y can be nullable.

How do I refactor so that z can be nullable? Apart from literally making it a nullable decimal type. I already have algorithms that subscribe to the Decimal type, not the nullable variant.

Body:
You can do your "int" or "decimal" parameters Nullable as well.

public PartialViewResult Bar(string y, decimal? z, int? x) {*/Etc*/}

Notice that in this case, you will have to validate the input in order of checking if "x" or "y" have values. In Check an integer value is Null in c# you can find some ways of validating a Nullable integer variable. The same approach could be used for checking if the decimal parameter is null.


问:
Ruby's open-uri and cookies
I would like to store the cookies from one open-uri call and pass them to the next one. I can't seem to find the right docs for doing this. I'd appreciate it if you could tell me the right way to do this.

NOTES: w3.org is not the actual url, but it's shorter; pretend cookies matter here.

```<code>h1 = open("http://www.w3.org/")
h2 = open("http://www.w3.org/People/Berners-Lee/", "Cookie" => h1.FixThisSpot)
</code>```

Update after 2 nays: While this wasn't intended as rhetorical question I guarantee that it's possible.
Update after tumbleweeds: See (the answer), it's possible. Took me a good while, but it works.

答:
Thanks Matthew Schinckel your answer was really useful. Using Net::HTTP I was successful </p>

```<code>        # Create a new connection object.
          site = "google.com"
          port = 80
          conn = Net::HTTP.new(site, port)

        # Get the response when we login, to set the cookie.
        # body is the encoded arguments to log in.
          resp, data = conn.post(login_path, body, {})
          cookie = resp.response['set-cookie']

        # Headers need to be in a hash.
          headers = { "Cookie" => cookie }

        # On a get, we don't need a body.
          resp, data = conn.get(path, headers)

          puts resp.body
</code>```

ContentLicense: CC BY-SA 2.5

Title: Ruby's open-uri and cookies

Body:
I would like to store the cookies from one open-uri call and pass them to the next one. I can't seem to find the right docs for doing this. I'd appreciate it if you could tell me the right way to do this.

NOTES: w3.org is not the actual url, but it's shorter; pretend cookies matter here.

h1 = open("http://www.w3.org/")
h2 = open("http://www.w3.org/People/Berners-Lee/", "Cookie" => h1.FixThisSpot)

Update after 2 nays: While this wasn't intended as rhetorical question I guarantee that it's possible.
Update after tumbleweeds: See (the answer), it's possible. Took me a good while, but it works.

Body:
Thanks Matthew Schinckel your answer was really useful. Using Net::HTTP I was successful

        # Create a new connection object.
          site = "google.com"
          port = 80
          conn = Net::HTTP.new(site, port)

        # Get the response when we login, to set the cookie.
        # body is the encoded arguments to log in.
          resp, data = conn.post(login_path, body, {})
          cookie = resp.response['set-cookie']

        # Headers need to be in a hash.
          headers = { "Cookie" => cookie }

        # On a get, we don't need a body.
          resp, data = conn.get(path, headers)

          puts resp.body


问:
Python: Convert packet object/inet object to 32 bit integer
I have IPv4 address and want to convert it to 32 bit integer.
i am able to convert IPv4 address into string using socket.inet_ntop and then convert that string to 32 bit integer<br>
but is there a direct way? </p>

答:
An IPv4 address in its basic form is a 32-bit integer in network byte order.
I'm assuming you have it as a sequence of bytes (because that is what you would normally hand off to inet_ntop).

What you will need to convert it into a python integer is the struct module and its unpack method along with the "!I" format specification (which means network byte order, unsigned 32-bit integer). See this code:

```<code>from socket import inet_ntop, inet_pton, AF_INET
from struct import unpack

ip = inet_pton(AF_INET, "192.168.1.42")
ip_as_integer = unpack("!I", ip)[0]
print("As string[{}] => As bytes[{}] => As integer[{}]".format(
      inet_ntop(AF_INET, ip), ip, ip_as_integer))
</code>```

You could of course also reconstruct the integer bytewise:

```<code>ip_as_integer = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3]
</code>```

Body:
I have IPv4 address and want to convert it to 32 bit integer.
i am able to convert IPv4 address into string using socket.inet_ntop and then convert that string to 32 bit integer

but is there a direct way?

Body:
An IPv4 address in its basic form is a 32-bit integer in network byte order.
I'm assuming you have it as a sequence of bytes (because that is what you would normally hand off to inet_ntop).

What you will need to convert it into a python integer is the struct module and its unpack method along with the "!I" format specification (which means network byte order, unsigned 32-bit integer). See this code:

from socket import inet_ntop, inet_pton, AF_INET
from struct import unpack

ip = inet_pton(AF_INET, "192.168.1.42")
ip_as_integer = unpack("!I", ip)[0]
print("As string[{}] => As bytes[{}] => As integer[{}]".format(
      inet_ntop(AF_INET, ip), ip, ip_as_integer))

You could of course also reconstruct the integer bytewise:

ip_as_integer = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3]


问:
Angular CLI rebuild process takes a long time
Issue:
i have an angular app with latest versions as of (June 2017)

once I make a small change or big changes in many files and save

the rebuild process kicks and 8 out of 10 times it takes more than 60 seconds. mostly in the assets folder.

I looked in SO and Github but none with a valid solution.

PS: assets folder being large should not have impacted the performance as per comments from github.

OS:
Windows 10

Versions:

```<code>@angular/cli: 1.1.0

node: 6.10.3

os: win32 x64

@angular/animations: 4.1.3

@angular/common: 4.1.3

@angular/compiler: 4.1.3

@angular/core: 4.1.3

@angular/forms: 4.1.3

@angular/http: 4.1.3

@angular/platform-browser: 4.1.3

@angular/platform-browser-dynamic: 4.1.3

@angular/router: 4.1.3

@angular/cli: 1.1.0

@angular/compiler-cli: 4.1.3
</code>```

答:
I guess you are using ng build and so I have checked and my project last 16 seconds to build. I would suggest to use this command to debug because it tells you the time that process take in your build.

```<code>ng build --verbose
</code>```

more info here https://github.com/angular/angular-cli/wiki/build

Body:
Issue:
i have an angular app with latest versions as of (June 2017)

once I make a small change or big changes in many files and save

the rebuild process kicks and 8 out of 10 times it takes more than 60 seconds. mostly in the assets folder.

I looked in SO and Github but none with a valid solution.

PS: assets folder being large should not have impacted the performance as per comments from github.

OS:
Windows 10

Versions:

@angular/cli: 1.1.0

node: 6.10.3

os: win32 x64

@angular/animations: 4.1.3

@angular/common: 4.1.3

@angular/compiler: 4.1.3

@angular/core: 4.1.3

@angular/forms: 4.1.3

@angular/http: 4.1.3

@angular/platform-browser: 4.1.3

@angular/platform-browser-dynamic: 4.1.3

@angular/router: 4.1.3

@angular/cli: 1.1.0

@angular/compiler-cli: 4.1.3

Body:
I guess you are using ng build and so I have checked and my project last 16 seconds to build. I would suggest to use this command to debug because it tells you the time that process take in your build.

ng build --verbose

more info here https://github.com/angular/angular-cli/wiki/build


问:
Get jar system path in scala
I'm trying to get system path, where jar is located in run time.

Below code works in REPL but, it fails if I assemble jar using sbt,

```<code>object tboj {
  def main(args: Array[String]) {
    def getCurrentDirectory = new java.io.File(".").getCanonicalPath
    val pwd = getCurrentDirectory
    println(pwd)
  }
}
</code>```

SBT error as below,

run
    java.lang.RuntimeException: No main class detected.
            at scala.sys.package$.error(package.scala:27)
    [trace] Stack trace suppressed: run last compile:run for the full output.
    [error] (compile:run) No main class detected.
    [error] Total time: 0 s, completed 13 Apr, 2016 5:15:40 PM

答:
If you want to find location of Jar using Class Name then use following way -

```<code>import org.apache.hadoop.fs.FileSystem
classOf[FileSystem].getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
</code>```

If you have instance, then use following way -

```<code>new ListBuffer[String]().getClass.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
</code>```

Title: Get jar system path in scala

Body:
I'm trying to get system path, where jar is located in run time.

Below code works in REPL but, it fails if I assemble jar using sbt,

object tboj {
  def main(args: Array[String]) {
    def getCurrentDirectory = new java.io.File(".").getCanonicalPath
    val pwd = getCurrentDirectory
    println(pwd)
  }
}

SBT error as below,

run
    java.lang.RuntimeException: No main class detected.
            at scala.sys.package$.error(package.scala:27)
    [trace] Stack trace suppressed: run last compile:run for the full output.
    [error] (compile:run) No main class detected.
    [error] Total time: 0 s, completed 13 Apr, 2016 5:15:40 PM

Body:
If you want to find location of Jar using Class Name then use following way -

import org.apache.hadoop.fs.FileSystem
classOf[FileSystem].getProtectionDomain().getCodeSource().getLocation().toURI().getPath())

If you have instance, then use following way -

new ListBuffer[String]().getClass.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()


问:
Method overriding not working
ok. i have a standard mergesort class.

```<code>public class Merge extends SortAlgorithm {

public static void sort(Comparable[] a) {
    Comparable[] aux = new Comparable[a.length];
    sort(a, aux, 0, a.length -1);
}

protected static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
    if(hi <= lo)
        return;
    int mid = (lo + hi)/2;
    sort(a, aux, lo, mid);
    sort(a, aux, mid+1, hi);
    if(less(a[mid+1], a[mid]))
        merge(a, aux, lo, mid, hi);
}

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] a = br.readLine().split(" ");
    sort(a);
    show(a);
}

protected static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
    int i = lo , j = mid+1;
    for(int k = lo ; k <= hi ; k++)
        aux[k] = a[k];
    for( int k = lo ; k <= hi ; k++ ) {
        if(i > mid)                       //Boundary Conditions
            a[k] = aux[j++];              //
        else if(j > hi)                   //
            a[k] = aux[i++];              //
        else if(less(aux[i] , aux[j]))
            a[k] = aux[i++];
        else
            a[k] = aux[j++];
    }
}

}
</code>```

I have extended this class to create a newer version of mergesort which uses less amount of auxiliary array. it has a different 'merge' and 'sort(Comparable[])' function

```<code>public class MergeSmallerAuxArray extends Merge {

public static void sort(Comparable[] a) {
    Comparable[] aux = new Comparable[a.length/2];
    sort(a, aux, 0, a.length - 1);
}

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] a = br.readLine().split(" ");
    sort(a);
    show(a);
}
//method overidden below
public static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {       int i = lo , j = mid+1;
    for(int k = lo ; k <= mid ; k++)
        aux[k] = a[k];
    for(int k = lo ; k <= hi ; k++) {
        if(i > mid)
            a[k] = a[j++];
        else if(j > hi)
            a[k] = aux[i++];
        else if(less(aux[i], a[j]))
            a[k] = aux[i++];
        else
            a[k] = a[j++];
    }
}

}
</code>```

but each time i run this class i am getting an error because the sort(Comparable[],Comparable[],int,int) method of the superclass is calling the merge function of the superclass instead of the one which i had overridden. Where did i went wrong?
Please Help.
Thank you.

答: The issue here is that you use static keyword. static doesn't work with polymorphism.

Title: Method overriding not working

Body:
ok. i have a standard mergesort class.

public class Merge extends SortAlgorithm {

public static void sort(Comparable[] a) {
    Comparable[] aux = new Comparable[a.length];
    sort(a, aux, 0, a.length -1);
}

protected static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) {
    if(hi <= lo)
        return;
    int mid = (lo + hi)/2;
    sort(a, aux, lo, mid);
    sort(a, aux, mid+1, hi);
    if(less(a[mid+1], a[mid]))
        merge(a, aux, lo, mid, hi);
}

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] a = br.readLine().split(" ");
    sort(a);
    show(a);
}

protected static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {
    int i = lo , j = mid+1;
    for(int k = lo ; k <= hi ; k++)
        aux[k] = a[k];
    for( int k = lo ; k <= hi ; k++ ) {
        if(i > mid)                       //Boundary Conditions
            a[k] = aux[j++];              //
        else if(j > hi)                   //
            a[k] = aux[i++];              //
        else if(less(aux[i] , aux[j]))
            a[k] = aux[i++];
        else
            a[k] = aux[j++];
    }
}

}

I have extended this class to create a newer version of mergesort which uses less amount of auxiliary array. it has a different 'merge' and 'sort(Comparable[])' function

public class MergeSmallerAuxArray extends Merge {

public static void sort(Comparable[] a) {
    Comparable[] aux = new Comparable[a.length/2];
    sort(a, aux, 0, a.length - 1);
}

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String[] a = br.readLine().split(" ");
    sort(a);
    show(a);
}
//method overidden below
public static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {       int i = lo , j = mid+1;
    for(int k = lo ; k <= mid ; k++)
        aux[k] = a[k];
    for(int k = lo ; k <= hi ; k++) {
        if(i > mid)
            a[k] = a[j++];
        else if(j > hi)
            a[k] = aux[i++];
        else if(less(aux[i], a[j]))
            a[k] = aux[i++];
        else
            a[k] = a[j++];
    }
}

}

but each time i run this class i am getting an error because the sort(Comparable[],Comparable[],int,int) method of the superclass is calling the merge function of the superclass instead of the one which i had overridden. Where did i went wrong?
Please Help.
Thank you.


问:
SQL Server: "Could not find the Database Engine startup handle"
When trying to install SQL Server Express 2016 from here for database related software projects, I get the error message as the loading bar finishes, stating:

"Could not find the Database Engine startup handle".

I've looked and tried solutions from other questions similar to this, but with no luck.

答:
I answered my question below as I found the answer out eventually and I feel people might be going through the same struggle! :)

The installation failed for me due to using the standard/default settings during installation. When doing this, the SQL Windows service will run under the NT Service\MSSQL$V2016 account.

After changing this login to a valid login (an existing local user), the server started correctly, and SQL Server Express 2016 installed and worked as it should..


答:
You need to store the id returned by setInterval and add logic to your callback to clearInterval when count === end_value:

var increment = 1;
var start_value = 1;
var count = 0;
var end_value = 10;

window.onload = function() {

  var interval_time = 1 * 1500;

  count = parseInt(start_value);
  document.getElementById('counter').innerHTML = count;

  var id = setInterval(function() {
    count += increment;
    if (count === end_value) {
      clearInterval(id);
    }
    document.getElementById('counter').innerHTML = count;

  }, interval_time);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="counter"></div></code>```

Title: How can I get my counter to stop at a defined point?

Body:
You need to store the id returned by setInterval and add logic to your callback to clearInterval when count === end_value:

var increment = 1;
var start_value = 1;
var count = 0;
var end_value = 10;

window.onload = function() {

  var interval_time = 1 * 1500;

  count = parseInt(start_value);
  document.getElementById('counter').innerHTML = count;

  var id = setInterval(function() {
    count += increment;
    if (count === end_value) {
      clearInterval(id);
    }
    document.getElementById('counter').innerHTML = count;

  }, interval_time);
}

<div id="counter"></div>


问:
Dropdown list selecting a filter
I'm trying to get every properties of a json object in order to create a dropdown list.

I'm going to explain myself, for example :

I've got 2 json objects :

```<code>{"name":"Paul","age":"18","sport":"Basket","color":"Green"}
{"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"}
</code>```

I've got a dropdown list within {name,age,sport,color,fruit,number}.
If I select name, I've got a second dropdown list within {Paul,Jhon}.

I'm using AngularJS, Node.js

I know that after getting every properties I have to apply unicity filter, to only have the differents properties but not the occurence

答:
Assuming ES6 is good and we can use Set to return unique values (if no - you can use some other techniques to get an array with unique elements) you can use ngChange directive to detect changes of the first select and populated options for the second select. So the controller and markup will look like:

angular.module('myApp', [])
.controller('MyCtrl', function MyCtrl($scope) {
  var ctrl = this;

  var data = [
    {"name":"Paul","age":"18","sport":"Basket","color":"Green"},
    {"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"},
    {"name":"Mark","age":"22","sport":"Football","color":"Red", "number":"5"}
  ];

  ctrl.objKeys = getUniqueKeys(data);
  ctrl.objVals = [];
  ctrl.keyChanged = keyChanged;

  function keyChanged(key) {
    ctrl.objVals = getUnique(data.map(function(obj) { return obj[key] }).filter(function(obj) { return !!obj; })); //get the values and filter only the ones are defined
  }

  function getUnique(arr) {
    return [...new Set(arr)]; //get array with unique values
  }

  function getUniqueKeys(arr) {
    return getUnique([].concat.apply([], arr.map(function(obj) { return Object.keys(obj); }))); //get the property names
  }

  return ctrl;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">

  <select ng-model="objKey" ng-change="$ctrl.keyChanged(objKey)"
    ng-options="k for k in $ctrl.objKeys track by k"></select>

  <select ng-if="$ctrl.objVals.length" ng-model="objVal"
    ng-options="k for k in $ctrl.objVals track by k"></select>

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

Title: Dropdown list selecting a filter

Body:
I'm trying to get every properties of a json object in order to create a dropdown list.

I'm going to explain myself, for example :

I've got 2 json objects :

{"name":"Paul","age":"18","sport":"Basket","color":"Green"}
{"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"}

I've got a dropdown list within {name,age,sport,color,fruit,number}.
If I select name, I've got a second dropdown list within {Paul,Jhon}.

I'm using AngularJS, Node.js

I know that after getting every properties I have to apply unicity filter, to only have the differents properties but not the occurence

Body:
Assuming ES6 is good and we can use Set to return unique values (if no - you can use some other techniques to get an array with unique elements) you can use ngChange directive to detect changes of the first select and populated options for the second select. So the controller and markup will look like:

angular.module('myApp', [])
.controller('MyCtrl', function MyCtrl($scope) {
  var ctrl = this;

  var data = [
    {"name":"Paul","age":"18","sport":"Basket","color":"Green"},
    {"name":"Jhon","age":"20","sport":"Basket","fruit":"banana", "number":"5"},
    {"name":"Mark","age":"22","sport":"Football","color":"Red", "number":"5"}
  ];

  ctrl.objKeys = getUniqueKeys(data);
  ctrl.objVals = [];
  ctrl.keyChanged = keyChanged;

  function keyChanged(key) {
    ctrl.objVals = getUnique(data.map(function(obj) { return obj[key] }).filter(function(obj) { return !!obj; })); //get the values and filter only the ones are defined
  }

  function getUnique(arr) {
    return [...new Set(arr)]; //get array with unique values
  }

  function getUniqueKeys(arr) {
    return getUnique([].concat.apply([], arr.map(function(obj) { return Object.keys(obj); }))); //get the property names
  }

  return ctrl;
});

<script src="//code.angularjs.org/1.6.2/angular.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">

  <select ng-model="objKey" ng-change="$ctrl.keyChanged(objKey)"
    ng-options="k for k in $ctrl.objKeys track by k"></select>

  <select ng-if="$ctrl.objVals.length" ng-model="objVal"
    ng-options="k for k in $ctrl.objVals track by k"></select>

  </div>
</div>


问:
How can I update a variable using Observable without render DOM in Angular 2, like a real-time page
I am new to Angular2 + and need to create a page in real time. When I load my component, I call a service using Observable and I save the result in a variable that I use in a ngFor in my model. After loading it, I need to refresh the data every minute and need to refine the changed data.

Does anyone know how to do this?

答:
you can start with Observable interval  it will do polling for every minute.

service

```<code>poll{
     return Observable
            .interval(1000)
            .flatMap(() => {
                //ur Observable from HTTP call
                return Observable
            });
}
</code>```

Component:-  before assigning latest value try to compare values it will avoid unnecessarily assignment

```<code>   this.service.poll().subscribe(
          data => {
             // if data same don't update
              if((JSON.stringify(this.models) === JSON.stringify(data) === false) ){
 this.models = data;
}

          }
       );
</code>```

Html code

```<code>< li *ngFor="let model of models ;trackBy: trackByFn " >
{{model}}
< li >
</code>```

trackBY will stop unnecessarily rendering
more info
https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html

Body:
you can start with Observable interval  it will do polling for every minute.

service

poll{
     return Observable
            .interval(1000)
            .flatMap(() => {
                //ur Observable from HTTP call
                return Observable
            });
}

Component:-  before assigning latest value try to compare values it will avoid unnecessarily assignment

   this.service.poll().subscribe(
          data => {
             // if data same don't update
              if((JSON.stringify(this.models) === JSON.stringify(data) === false) ){
 this.models = data;
}

          }
       );

Html code

< li *ngFor="let model of models ;trackBy: trackByFn " >
{{model}}
< li >

trackBY will stop unnecessarily rendering
more info
https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html


问:
I have text file with a 2D matrix in it. How do turn this into a grey scale image in python?
I'm fairly new with python so I'm not really sure where to start. All I have done is I imported the text file to python. I was suggested to use matshow.py but I don't know how I would use the text file to create the actual image.</p>

答:
If you can contrive to get your text file into a numpy array then this kind of code will work. Just research, or ask another question, about reading a text file into a numpy array.

```<code>>>> from PIL import Image
>>> import numpy as np
>>> pic = np.zeros((100,100), dtype=np.int8)
>>> image = Image.fromarray(pic)
>>> image.show()
</code>```

Here I import the Image class from the PIL library. Then I create a 100x100  array of zeroes in pic using numpy. I use a method from Image to make this into an Image object and then display the (utterly uninteresting, completely black) result.

Body:
If you can contrive to get your text file into a numpy array then this kind of code will work. Just research, or ask another question, about reading a text file into a numpy array.

>>> from PIL import Image
>>> import numpy as np
>>> pic = np.zeros((100,100), dtype=np.int8)
>>> image = Image.fromarray(pic)
>>> image.show()

Here I import the Image class from the PIL library. Then I create a 100x100  array of zeroes in pic using numpy. I use a method from Image to make this into an Image object and then display the (utterly uninteresting, completely black) result.


问:
Heatmap with customized color scale bar for values below and above thresholds
I would like to make an heatmap in R using pheatmap with the colors green, black and red and using a range in the legend from -2 to 2, here is the code that I used:

```<code>library(pheatmap)
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 201)
colors = c(seq(as.numeric(-2),-0.01,length=100), 0,
seq(0.01,as.numeric(2),length=100))

pheatmap(mFilt_annot_sort_matrix, color = my_palette, breaks = colors, scale =
"none", cluster_rows = F, cluster_cols = F, margin = c(5,5))
</code>```

The problem is that I would like the values less than -2 in green an greater than 2 in red while with my solution these values are white, could you help me?

答:
You need to set the break-point to be at -2 and +2 and make a gradient in between.  You also need to set the color for less than minimum and greater than maximum desired values. Look below;

```<code>library(pheatmap)

colors <- c(min(mFilt_annot_sort_matrix),seq(-2,2,by=0.01),max(mFilt_annot_sort_matrix))

my_palette <- c("green",colorRampPalette(colors = c("green", "black", "red"))
                                                   (n = length(colors)-3), "red")

pheatmap(mFilt_annot_sort_matrix, color = my_palette, breaks = colors, scale =
"none", cluster_rows = F, cluster_cols = F, margin = c(5,5))
</code>```

Example using a normal data;

Using rnorm.within function I make the following data-set:

```<code>#V1 is random between -4 and 4
#V2 is less than -2
#V3 is greater than 2

df <- data.frame(cbind(rnorm.within(1000, -4, 4)
,rnorm.within(1000,-4,-3), rnorm.within(1000,3,4)))
</code>```

and applying the procedure above (same breaks and color pallet) for making a heatmap will get:

```<code>pheatmap(df, color = my_palette, breaks = colors, scale =
                  "none", cluster_rows = F, cluster_cols = F, margin = c(5,5))
</code>```

```

   <img src="https://i.stack.imgur.com/BlWkc.png">

```

Body:
I would like to make an heatmap in R using pheatmap with the colors green, black and red and using a range in the legend from -2 to 2, here is the code that I used:

library(pheatmap)
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 201)
colors = c(seq(as.numeric(-2),-0.01,length=100), 0,
seq(0.01,as.numeric(2),length=100))

pheatmap(mFilt_annot_sort_matrix, color = my_palette, breaks = colors, scale =
"none", cluster_rows = F, cluster_cols = F, margin = c(5,5))

The problem is that I would like the values less than -2 in green an greater than 2 in red while with my solution these values are white, could you help me?

Body:
You need to set the break-point to be at -2 and +2 and make a gradient in between.  You also need to set the color for less than minimum and greater than maximum desired values. Look below;

library(pheatmap)

colors <- c(min(mFilt_annot_sort_matrix),seq(-2,2,by=0.01),max(mFilt_annot_sort_matrix))

my_palette <- c("green",colorRampPalette(colors = c("green", "black", "red"))
                                                   (n = length(colors)-3), "red")

pheatmap(mFilt_annot_sort_matrix, color = my_palette, breaks = colors, scale =
"none", cluster_rows = F, cluster_cols = F, margin = c(5,5))

Example using a normal data;

Using rnorm.within function I make the following data-set:

#V1 is random between -4 and 4
#V2 is less than -2
#V3 is greater than 2

df <- data.frame(cbind(rnorm.within(1000, -4, 4)
,rnorm.within(1000,-4,-3), rnorm.within(1000,3,4)))

and applying the procedure above (same breaks and color pallet) for making a heatmap will get:

pheatmap(df, color = my_palette, breaks = colors, scale =
                  "none", cluster_rows = F, cluster_cols = F, margin = c(5,5))


问:
Install Shapely: OSError: [WinError 126] The specified module could not be found
I have to install Shapely package (http://toblerity.org/shapely/project.html#installation).
But when I am using:

```<code>pip install Shapely
</code>```

I am getting this error:

```<code>Collecting Shapely
  Using cached Shapely-1.5.17.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\AppData\Local\Temp\pip-build-mwuxcain\Shapely\setup.py", line 38, in <module>
        from shapely._buildcfg import geos_version_string, geos_version, \
      File "C:\Users\AppData\Local\Temp\pip-build-mwuxcain\Shapely\shapely\_buildcfg.py", line 200, in <module>
        lgeos = CDLL("geos.dll")
      File "C:\Users\Anaconda3\lib\ctypes\__init__.py", line 344, in __init__
        self._handle = _dlopen(self._name, mode)
    OSError: [WinError 126] The specified module could not be found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\AppData\Local\Temp\pip-build-mwuxcain\Shapely\
</code>```

And, when I am using:

```<code>conda install shapely
</code>```

I am getting this error:

```<code>Fetching package metadata ...........

PackageNotFoundError: Package not found: Conda could not find '
</code>```

I am using Python 3.6.0 (Anaconda3) on Windows 10 (64-bit).

Please help. (nothing works)

答:
Download WHL file using http://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely

Install:

```<code>python -m pip install Shapely-1.5.17-cp36-cp36m-win_amd64.whl
</code>```

Ubuntu:

```<code>pip install shapely==1.6b2
</code>```

Body:
I have to install Shapely package (http://toblerity.org/shapely/project.html#installation).
But when I am using:

pip install Shapely

I am getting this error:

Collecting Shapely
  Using cached Shapely-1.5.17.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\AppData\Local\Temp\pip-build-mwuxcain\Shapely\setup.py", line 38, in <module>
        from shapely._buildcfg import geos_version_string, geos_version, \
      File "C:\Users\AppData\Local\Temp\pip-build-mwuxcain\Shapely\shapely\_buildcfg.py", line 200, in <module>
        lgeos = CDLL("geos.dll")
      File "C:\Users\Anaconda3\lib\ctypes\__init__.py", line 344, in __init__
        self._handle = _dlopen(self._name, mode)
    OSError: [WinError 126] The specified module could not be found

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\AppData\Local\Temp\pip-build-mwuxcain\Shapely\

And, when I am using:

conda install shapely

I am getting this error:

Fetching package metadata ...........

PackageNotFoundError: Package not found: Conda could not find '

I am using Python 3.6.0 (Anaconda3) on Windows 10 (64-bit).

Please help. (nothing works)

Body:
Download WHL file using http://www.lfd.uci.edu/~gohlke/pythonlibs/#shapely

Install:

python -m pip install Shapely-1.5.17-cp36-cp36m-win_amd64.whl

Ubuntu:

pip install shapely==1.6b2


问:
Explain this code I found on the internet to me?
I came across the following implementation ( https://discuss.leetcode.com/topic/40371/easy-dp-java-solution-with-detailed-explanation ), but not quiet understanding how it works — commented on how I got lost:

```<code>boolean isMatch(String s, String p) {
    if(s==null || p==null) {
        return false;
    }

    //  Why add an additional length to the string lengths?
    boolean[][] dp = new boolean[s.length()+1][p.length()+1];
    dp[0][0] = true;

            //  What’s the reason for this check? If p were to have ‘*’ at i=3, it would simply pass
    for(int i=0; i<p.length(); i++) {
        if(p.charAt(i)=='*' && dp[0][i-1]) {
            dp[0][i+1] = true;
        }
    }

    for(int i=0; i<s.length(); i++) {
        for(int j=0; j<p.length(); j++) {

            //  Shouldn’t dp[i][j] just equal to true? Why set a boolean value to characters ahead?
            if(p.charAt(j)=='.') {
                dp[i+1][j+1] = dp[i][j];
            }

            //  Same question as prior
            if(p.charAt(j)==s.charAt(i)) {
                dp[i+1][j+1] = dp[i][j];
            }

            if(p.charAt(j)=='*') {
                //  Not quiet understanding what the following checks are for and how they work
                if(p.charAt(j-1)!=s.charAt(i) && p.charAt(j-1)!='.') {
                    dp[i+1][j+1] = dp[i+1][j-1];
                } else {
                    dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
                }
            }
        }
    }

    return true;
}
</code>```

Thank you in advance and will be sure to vote up/accept answer

答:
Q:Why add an additional length to the string lengths?

A: For clearer code.

Q:What’s the reason for this check? If p were to have ‘’ at i=3, it would simply pass*

A:It stands for: if first character in the pattern has matched first character in the string, mark as many as possible characters of string as matching. It's greedy approach.

Q:Shouldn’t dp[i][j] just equal to true? Why set a boolean value to characters ahead?

A:Nope. It's because we don't want to indicate that character matches if something before didn't match. Simply, if 3 character of the input doesn't match, nothing following it, shouldn't be marked as matching.

Q:Not quiet understanding what the following checks are for and how they work

A:If the character differs from previous one, and the previous pattern character isn't a dot which has special meaning, keep the state, as we could have 0 length match. Otherwise, just keep going in one of three possible directions (look behind, above or in front).

Body:
I came across the following implementation ( https://discuss.leetcode.com/topic/40371/easy-dp-java-solution-with-detailed-explanation ), but not quiet understanding how it works — commented on how I got lost:

boolean isMatch(String s, String p) {
    if(s==null || p==null) {
        return false;
    }

    //  Why add an additional length to the string lengths?
    boolean[][] dp = new boolean[s.length()+1][p.length()+1];
    dp[0][0] = true;

            //  What’s the reason for this check? If p were to have ‘*’ at i=3, it would simply pass
    for(int i=0; i<p.length(); i++) {
        if(p.charAt(i)=='*' && dp[0][i-1]) {
            dp[0][i+1] = true;
        }
    }

    for(int i=0; i<s.length(); i++) {
        for(int j=0; j<p.length(); j++) {

            //  Shouldn’t dp[i][j] just equal to true? Why set a boolean value to characters ahead?
            if(p.charAt(j)=='.') {
                dp[i+1][j+1] = dp[i][j];
            }

            //  Same question as prior
            if(p.charAt(j)==s.charAt(i)) {
                dp[i+1][j+1] = dp[i][j];
            }

            if(p.charAt(j)=='*') {
                //  Not quiet understanding what the following checks are for and how they work
                if(p.charAt(j-1)!=s.charAt(i) && p.charAt(j-1)!='.') {
                    dp[i+1][j+1] = dp[i+1][j-1];
                } else {
                    dp[i+1][j+1] = (dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1]);
                }
            }
        }
    }

    return true;
}

Thank you in advance and will be sure to vote up/accept answer


问:
What's the right way to do counts in Rails?
I have a rails app with many following pieces of code:

```<code>Our active community of <%= Account.find_all_by_admin(false).count %>
</code>```

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

答:
You don't need a name scope to perform a count.

```<code>Account.where(:admin => false).count
</code>```

But named scopes are an excellent way to make your code more reusable.

Named scopes don't have any noticeable performance impact on your application.

Body:
I have a rails app with many following pieces of code:

Our active community of <%= Account.find_all_by_admin(false).count %>

My question is is this the right way to do counts on views? It seems so "dirty" is there a more railish, way to do counts? I'm thinking named scopes perhaps, but I just want to be sure that these type of things won't have  a greater impact in performance.

Thank You,

Body:
You don't need a name scope to perform a count.

Account.where(:admin => false).count

But named scopes are an excellent way to make your code more reusable.

Named scopes don't have any noticeable performance impact on your application.


问:
Converting into date-time format in pandas?
I need help converting into python/pandas date time format. For example, my times are saved like the following line:

```<code>2017-01-01 05:30:24.468911+00:00
.....
2017-05-05 01:51:31.351718+00:00
</code>```

and I want to know the simplest way to convert this into date time format for essentially performing operations with time (like what is the range in days of my dataset to split up my dataset into chunks by time, what's the time difference from one time to another)? I don't mind losing some of the significance for the times if that makes things easier. Thank you so much!

答:
Since the Pandas tag is there:</p>

```<code>df = pd.DataFrame(['2017-01-01 05:30:24.468911+00:00'])
df.columns = ['Datetime']
df['Datetime'] = pd.to_datetime(df['Datetime'], format='%Y-%m-%d %H:%M:%S.%f', utc=True)
print(df.dtypes)
</code>```

Body:
I need help converting into python/pandas date time format. For example, my times are saved like the following line:

2017-01-01 05:30:24.468911+00:00
.....
2017-05-05 01:51:31.351718+00:00

and I want to know the simplest way to convert this into date time format for essentially performing operations with time (like what is the range in days of my dataset to split up my dataset into chunks by time, what's the time difference from one time to another)? I don't mind losing some of the significance for the times if that makes things easier. Thank you so much!

Body:
Since the Pandas tag is there:

df = pd.DataFrame(['2017-01-01 05:30:24.468911+00:00'])
df.columns = ['Datetime']
df['Datetime'] = pd.to_datetime(df['Datetime'], format='%Y-%m-%d %H:%M:%S.%f', utc=True)
print(df.dtypes)


问:
Query on SQL Server stored procedure takes longer for specific data than for all data
I have a query in a stored procedure that is retrieving data from several tables of my SQL Server database. From my application I call this stored procedure with some parameters to filter the data.

The strange thing is that, for all data returned for "X" week of year (about 2600 records) it takes about 30 seconds to retrieve the data. But if I add a specific "center" filter for the same week of year (about 1800 records), it takes about 3 minutes to get the data!

If I run just the query, it works well (30 seconds for all data and about 22 seconds for filtered data). The issue is when I run the query through the stored procedure!

How is this possible? Why does filtered data is taking about x6 times than getting all data? Why am I missing? Am I writing the stored procedure correctly? How can I do this in a more efficient way?

My stored procedure code is something like this:

```<code>ALTER PROCEDURE EventMonitoring
    @EventType AS CHAR(1),
    @Year AS INT,
    @Week AS INT,
    @CenterID AS CHAR(2),
    @AreaID AS INT
AS
    DECLARE @SQLCommand AS VARCHAR(MAX)
    DECLARE @MessageError AS VARCHAR(MAX)

    SET @SQLCommand = ' SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = ' + CAST(@Year AS VARCHAR) +
                   ' And E.EventWeek = ' + CAST(@Week AS VARCHAR) +
                   ' And E.EventType = ' + CAST(@EventType AS VARCHAR)

    IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.CenterID = ''' + @CenterID + ''''
    END

    IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.AreaID = ' + CAST(@AreaID AS VARCHAR)
    END

    SET @SQLCommand = @SQLCommand + 'GROUP BY ....'

    BEGIN TRY
        EXEC(@SQLCommand)
    END TRY
    BEGIN CATCH
        ....
    END CATCH
</code>```

答:
I faced a situation like this at my work and we solve just adding the SET ARITHABORT ON parameter inside the proc because the ADO connections.

EDIT

When a procedure generates the script in runtime sql engine don't see the real parameters to build a good plan for the query. It's call Parameter Sniffing. So try something like this:

```<code>ALTER PROCEDURE EventMonitoring
    @EventType AS CHAR(1),
    @Year AS INT,
    @Week AS INT,
    @CenterID AS CHAR(2),
    @AreaID AS INT
AS
    DECLARE @MessageError AS VARCHAR(MAX)

    BEGIN TRY

    IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
    BEGIN
        SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = @Year
                    And E.EventWeek = @Week
                   And E.EventType =EventType  AND E.CenterID = @CenterID
                   GROUP BY ....
    END

    IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
    BEGIN

        SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = @Year
                    And E.EventWeek = @Week
                   And E.EventType =EventType  AND E.AreaID = @AreaID
                   GROUP BY ....
    END

    END TRY
    BEGIN CATCH
        ....
    END CATCH
</code>```

Another try

After a quickly read in the article pointed by SqlZim try this last one shot with  ARITHABORT ON and option(recompile)

```<code>    ALTER PROCEDURE EventMonitoring
        @EventType AS CHAR(1),
        @Year AS INT,
        @Week AS INT,
        @CenterID AS CHAR(2),
        @AreaID AS INT
    AS
SET ARITHABORT ON
        DECLARE @SQLCommand AS VARCHAR(MAX)
        DECLARE @MessageError AS VARCHAR(MAX)

        SET @SQLCommand = ' SELECT ....
                       ....
                       ....
                       ....
                       FROM   Event E
                       INNER JOIN ...
                       INNER JOIN ...
                       INNER JOIN ...
                       WHERE E.EventYear = ' + CAST(@Year AS VARCHAR) +
                       ' And E.EventWeek = ' + CAST(@Week AS VARCHAR) +
                       ' And E.EventType = ' + CAST(@EventType AS VARCHAR)

        IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
        BEGIN
            @SQLCommand = @SQLCommand + ' AND E.CenterID = ''' + @CenterID + ''''
        END

        IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
        BEGIN
            @SQLCommand = @SQLCommand + ' AND E.AreaID = ' + CAST(@AreaID AS VARCHAR)
        END

        SET @SQLCommand = @SQLCommand + 'GROUP BY .... OPTION (RECOMPILE)'

        BEGIN TRY
            EXEC(@SQLCommand)
        END TRY
        BEGIN CATCH
            ....
        END CATCH
</code>```

Body:
I have a query in a stored procedure that is retrieving data from several tables of my SQL Server database. From my application I call this stored procedure with some parameters to filter the data.

The strange thing is that, for all data returned for "X" week of year (about 2600 records) it takes about 30 seconds to retrieve the data. But if I add a specific "center" filter for the same week of year (about 1800 records), it takes about 3 minutes to get the data!

If I run just the query, it works well (30 seconds for all data and about 22 seconds for filtered data). The issue is when I run the query through the stored procedure!

How is this possible? Why does filtered data is taking about x6 times than getting all data? Why am I missing? Am I writing the stored procedure correctly? How can I do this in a more efficient way?

My stored procedure code is something like this:

ALTER PROCEDURE EventMonitoring
    @EventType AS CHAR(1),
    @Year AS INT,
    @Week AS INT,
    @CenterID AS CHAR(2),
    @AreaID AS INT
AS
    DECLARE @SQLCommand AS VARCHAR(MAX)
    DECLARE @MessageError AS VARCHAR(MAX)

    SET @SQLCommand = ' SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = ' + CAST(@Year AS VARCHAR) +
                   ' And E.EventWeek = ' + CAST(@Week AS VARCHAR) +
                   ' And E.EventType = ' + CAST(@EventType AS VARCHAR)

    IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.CenterID = ''' + @CenterID + ''''
    END

    IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
    BEGIN
        @SQLCommand = @SQLCommand + ' AND E.AreaID = ' + CAST(@AreaID AS VARCHAR)
    END

    SET @SQLCommand = @SQLCommand + 'GROUP BY ....'

    BEGIN TRY
        EXEC(@SQLCommand)
    END TRY
    BEGIN CATCH
        ....
    END CATCH

Body:
I faced a situation like this at my work and we solve just adding the SET ARITHABORT ON parameter inside the proc because the ADO connections.

EDIT

When a procedure generates the script in runtime sql engine don't see the real parameters to build a good plan for the query. It's call Parameter Sniffing. So try something like this:

ALTER PROCEDURE EventMonitoring
    @EventType AS CHAR(1),
    @Year AS INT,
    @Week AS INT,
    @CenterID AS CHAR(2),
    @AreaID AS INT
AS
    DECLARE @MessageError AS VARCHAR(MAX)

    BEGIN TRY

    IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
    BEGIN
        SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = @Year
                    And E.EventWeek = @Week
                   And E.EventType =EventType  AND E.CenterID = @CenterID
                   GROUP BY ....
    END

    IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
    BEGIN

        SELECT ....
                   ....
                   ....
                   ....
                   FROM   Event E
                   INNER JOIN ...
                   INNER JOIN ...
                   INNER JOIN ...
                   WHERE E.EventYear = @Year
                    And E.EventWeek = @Week
                   And E.EventType =EventType  AND E.AreaID = @AreaID
                   GROUP BY ....
    END

    END TRY
    BEGIN CATCH
        ....
    END CATCH

Another try

After a quickly read in the article pointed by SqlZim try this last one shot with  ARITHABORT ON and option(recompile)

    ALTER PROCEDURE EventMonitoring
        @EventType AS CHAR(1),
        @Year AS INT,
        @Week AS INT,
        @CenterID AS CHAR(2),
        @AreaID AS INT
    AS
SET ARITHABORT ON
        DECLARE @SQLCommand AS VARCHAR(MAX)
        DECLARE @MessageError AS VARCHAR(MAX)

        SET @SQLCommand = ' SELECT ....
                       ....
                       ....
                       ....
                       FROM   Event E
                       INNER JOIN ...
                       INNER JOIN ...
                       INNER JOIN ...
                       WHERE E.EventYear = ' + CAST(@Year AS VARCHAR) +
                       ' And E.EventWeek = ' + CAST(@Week AS VARCHAR) +
                       ' And E.EventType = ' + CAST(@EventType AS VARCHAR)

        IF @Centro <> '-' --If application sends - as the parameter, it gets all centers
        BEGIN
            @SQLCommand = @SQLCommand + ' AND E.CenterID = ''' + @CenterID + ''''
        END

        IF @Area <> 0 --If application sends 0 as the parameter, it gets all  areas
        BEGIN
            @SQLCommand = @SQLCommand + ' AND E.AreaID = ' + CAST(@AreaID AS VARCHAR)
        END

        SET @SQLCommand = @SQLCommand + 'GROUP BY .... OPTION (RECOMPILE)'

        BEGIN TRY
            EXEC(@SQLCommand)
        END TRY
        BEGIN CATCH
            ....
        END CATCH


问:
WebdriverIO automation testing when JavaScript is disabled
Is there a way in WebdriverIO framework to launch the browser with JavaScript disabled?

I want to automate a scenario with JavaScript being disabled. But, when I manually disable the JavaScript in Chrome, or Firefox and run the WDIO scripts, the browser always opens with JavaScript enabled.

答:
Not anymore. (but you have a workaround below)

This used to be easily achieved using the chromium switches. But considering all driver implementations (chromedriver, geckodriver, etc.) now require JavaScript to drive your spawned browser instance, it's no longer possible.

It was achieved via chromeOptions arguments/switches:

```<code>capabilities: [{

        maxInstances: 2,

        browserName: config[env].browser,
        chromeOptions: {

            args: ['--disable-javascript',
                   '--disable-javascript-harmony-shipping'
            ]
        }
    }]
</code>```

!!! LATER EDIT: You can achieve this by loading a custom profile.

Start your WebdriverIO test case, but add a browser.debug() after you load your page;

In the address bar, type chrome://settings/content and in the modal, check the Do not allow any site to run JavaScript. Click Done. Now go to a random page and notice JavaScript has been blocked on it:

Now we have to save this custom profile and load it each time you start a WebdriverIO test case. Type chrome://version in your address bar. Notice the Profile Path value. Copy the content of the folder (e.g.: For C:\Users\<yourUserName>\Desktop\scoped_dir18256_17319\Default, copy the scoped_dir18256_17319 folder on your Desktop). This folder contains all the actions (search history, extensions installed, accounts saved... in our case, JavaScript disabled option) on THIS current instance.

Now all we need to do, is add the path to that folder in your wdio.config.js file as a chromeOptions argument:

```<code>chromeOptions: {
    //extensions: ['./browserPlugins/Avira-SafeSearch-Plus_v1.5.1.crx'],
    args: [ '--user-data-dir=/Users/<yourUserName>/Desktop/scoped_dir18256_17319'
    ]
}
</code>```

Now all you have to do is run your test cases with this custom profile and JavaScript will be blocked on all websites. Hope this is the behavior you are looking for as there is no other way to achieve this behavior.

Cheers!

Body:
Not anymore. (but you have a workaround below)

This used to be easily achieved using the chromium switches. But considering all driver implementations (chromedriver, geckodriver, etc.) now require JavaScript to drive your spawned browser instance, it's no longer possible.

It was achieved via chromeOptions arguments/switches:

capabilities: [{

        maxInstances: 2,

        browserName: config[env].browser,
        chromeOptions: {

            args: ['--disable-javascript',
                   '--disable-javascript-harmony-shipping'
            ]
        }
    }]

!!! LATER EDIT: You can achieve this by loading a custom profile.

Start your WebdriverIO test case, but add a browser.debug() after you load your page;

In the address bar, type chrome://settings/content and in the modal, check the Do not allow any site to run JavaScript. Click Done. Now go to a random page and notice JavaScript has been blocked on it:

Now we have to save this custom profile and load it each time you start a WebdriverIO test case. Type chrome://version in your address bar. Notice the Profile Path value. Copy the content of the folder (e.g.: For C:\Users\<yourUserName>\Desktop\scoped_dir18256_17319\Default, copy the scoped_dir18256_17319 folder on your Desktop). This folder contains all the actions (search history, extensions installed, accounts saved... in our case, JavaScript disabled option) on THIS current instance.

Now all we need to do, is add the path to that folder in your wdio.config.js file as a chromeOptions argument:

chromeOptions: {
    //extensions: ['./browserPlugins/Avira-SafeSearch-Plus_v1.5.1.crx'],
    args: [ '--user-data-dir=/Users/<yourUserName>/Desktop/scoped_dir18256_17319'
    ]
}

Now all you have to do is run your test cases with this custom profile and JavaScript will be blocked on all websites. Hope this is the behavior you are looking for as there is no other way to achieve this behavior.

Cheers!


问:
Using <audio> tags in React app, playing chosen file onClick
I can map through an array and render some images (near the bottom in the generateWord function). I want to be able to click on the image, and play the associated audio file.  It plays the second (or last) audio file in the array.  I think I should attach some kind of key or index to the audio file so it knows which one to play, but I'm not sure how to exactly. The code below is the component. Part of the state is commented below it so you can see where the mapped array is coming from.

```<code>const debug = require("debug")("components:Displayletter")
const React = require("react")
const { connect } = require("react-redux")
const request = require("superagent")
const { Link } = require("react-router")

class Displayletter extends React.Component {

  constructor() {
    super()
    this.playSound = this.playSound.bind(this)
  }

  playSound() {
    this.playWord.play()
  }

  handleClick(e) {
    e.preventDefault()
    this.props.router.push("/")
  }

  render() {
    debug(this.props)
    const { dispatch, letters, letter } = this.props
    const wordsArr = letter.wordImage

    return (
      <div className="row letter-container">
        <div className="col-sm-12">
          {this.generateWord(wordsArr)}
        </div>
      </div>
    )
  }

  generateWord(wordsArr) {
    return wordsArr.map((word) => {
      return (
        <div>
          <audio
          key={word.sound}
          ref={(x) => { this.playWord = x; }}>
            <source src={word.sound} preload='auto'/>
          </audio>
          <img src={word.image} onClick={this.playSound} />
        </div>
      )
    })
  }
}

module.exports = connect(state => state)(Displayletter)

//STATE
  // letters: [
  //   {
  //     id: 1,
  //     capital: "A",
  //     lowercase: "a",
  //     capitalSound: "/sounds/capitalSounds/A.mp3",
  //     lowerSound: "/sounds/lowerSounds/a.mp3",
  //     wordImage: [
  //       {id:1, image:"images/words/aniwaniwa.png", sound: "sounds/ua.mp3"},
  //       {id:2, image:"images/words/anuhe.png", sound: "sounds/anuhe.mp3"},
  //     ],
  //     multimedia: "/multimedia/aniwaniwa.webm",
  //     mediaName: "Aniwaniwa Song",
  //   },
</code>```

Second iteration - have added an empty object in the constructor and passed a 'word' argument through the onClick and playSound.

```<code>generateWord(wordsArr) {
return wordsArr.map((word) => {
  return (
    <div>
    <audio
      key={word}
      ref={(x) => { this.playWords[word] = x; }}>
          <source src={word.sound} preload='auto'/>
    </audio>
      <img src={word.image} onClick={this.playSound.bind(this, word)} />
    </div>
  )
})

  playSound(word) {
    this.playWords[word].play()
  }

  constructor() {
    super()
    this.playCapital = this.playCapital.bind(this)
    this.playLower = this.playLower.bind(this)
    this.playSound = this.playSound.bind(this)
    this.playWords = {}
  }
</code>```

***************ROUND THREE*******************

```<code>const debug = require("debug")("components:Displayletter")
const React = require("react")
const { connect } = require("react-redux")
const request = require("superagent")
const { Link } = require("react-router")

class Displayletter extends React.Component {

  constructor() {
    super()
    this.playCapital = this.playCapital.bind(this)
    this.playLower = this.playLower.bind(this)
    this.playWords = {}
  }

  playCapital() {
    this.playCap.play()
  }

  playLower() {
    this.playLow.play()
  }

  playSound(word) {
    this.playWords[word].play()
  }

  handleClick(e) {
    e.preventDefault()
    this.props.router.push("/")
  }

  render() {
debug(this.props)
const { dispatch, letters, letter } = this.props
const wordsArr = letter.wordImage

    return (
  <div className="row letter-container">
    <div className="col-sm-12">

      <audio
      key={letter.capitalSound}
      ref={(cap) => { this.playCap = cap; }}>
        <source
          src={letter.capitalSound}
          preload="auto" />
        <track
          kind="captions"
          src=""
          srcLang="en" />
      </audio>

      <audio
      key={letter.lowerSound}
      ref={(low) => { this.playLow = low; }}>
        <source
          src={letter.lowerSound}
          preload="auto" />
        <track
          kind="captions"
          src=""
          srcLang="en" />
      </audio>

      <button
        type="button"
        className="btn btn-xl display"
        onClick={this.playCapital}>
        {letter.capital}
      </button>

      <button
        type="button"
        className="btn btn-xl display"
        onClick={this.playLower}>
        {letter.lowercase}
      </button>

    </div>

      <div className="col-sm-12">
    {this.generateWord(wordsArr)}
  </div>

        <div className="col-sm-12">
      <Link key={letter.id} to={`/media/${letter.capital}`}>
        <button
          type="button"
          className="btn"
          onClick={() =>
              dispatch({
                type: "RENDER_LETTER",
                payload: letter,
              })
          }>
          Watch: {letter.mediaName}
        </button>
      </Link>

    </div>
  </div>
)
  }

  generateWord(wordsArr) {
    return wordsArr.map((word) => {
      return (
    <div>
          <audio
        key={word}
        ref={(x) => { this.playWords[word] = x; }}>
          <source src={word.sound} preload='auto'/>
          </audio>
          <img src={word.image} onClick={this.playSound.bind(this, word)} />
        </div>
      )
    })
  }
}

module.exports = connect(state => state)(Displayletter)

  // letters: [
  //   {
  //     id: 1,
  //     capital: "A",
  //     lowercase: "a",
  //     capitalSound: "/sounds/capitalSounds/A.mp3",
  //     lowerSound: "/sounds/lowerSounds/a.mp3",
  //     wordImage: [
  //       {id:1, image:"images/words/aniwaniwa.png", sound: "sounds/ua.mp3"},
  //       {id:2, image:"images/words/anuhe.png", sound: "sounds/anuhe.mp3"},
  //     ],
  //     multimedia: "/multimedia/aniwaniwa.webm",
  //     mediaName: "Aniwaniwa Song",
  //   },
</code>```

答:
You're actually very close! The problem lies with how you're saving the reference to your audio elements: ref={(x) => { this.playWord = x; }}. Note that because this is inside a map, every element is saving itself, one after the other, as this.playWord, hence why only the last file is getting played when you click.

What you want to do instead is save all your words to an object or array, then reference in your click handler which one you want to play.

First, do something like this.playWords = {} in your constructor, then ref={(x) => { this.playWords[word] = x; }} in render. This will give you an object playWords that stores references to all the audio elements keyed by word.

Then, give playSound a word argument and make sure the onClick passes in that argument by binding it like onClick={this.playSound.bind(this, word)}.

I've put together a simple example that demonstrates that basic structure; you should be able to easily apply these principles to your component.

class Example extends React.Component {
  constructor() {
    super();
    this.words = {};
  }

  logClick(i) {
    console.log("user clicked on", this.words[i]);
  }

  render() {
    const wordsArr = "this is an example sentence".split(" ");
    return (

          {this.generateWord(wordsArr)}

    )
  }

  generateWord(wordsArr) {
    return wordsArr.map((word) => {
      return (

           { this.words[word] = x; }}
            onClick={this.logClick.bind(this, word)}
          >
            {word}

      );
    })
  }
}

ReactDOM.render(<Example />, document.getElementById("container"));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container"/></code>```

Body:
I can map through an array and render some images (near the bottom in the generateWord function). I want to be able to click on the image, and play the associated audio file.  It plays the second (or last) audio file in the array.  I think I should attach some kind of key or index to the audio file so it knows which one to play, but I'm not sure how to exactly. The code below is the component. Part of the state is commented below it so you can see where the mapped array is coming from.

const debug = require("debug")("components:Displayletter")
const React = require("react")
const { connect } = require("react-redux")
const request = require("superagent")
const { Link } = require("react-router")

class Displayletter extends React.Component {

  constructor() {
    super()
    this.playSound = this.playSound.bind(this)
  }

  playSound() {
    this.playWord.play()
  }

  handleClick(e) {
    e.preventDefault()
    this.props.router.push("/")
  }

  render() {
    debug(this.props)
    const { dispatch, letters, letter } = this.props
    const wordsArr = letter.wordImage

    return (

          {this.generateWord(wordsArr)}

    )
  }

  generateWord(wordsArr) {
    return wordsArr.map((word) => {
      return (

          <audio
          key={word.sound}
          ref={(x) => { this.playWord = x; }}>
            <source src={word.sound} preload='auto'/>
          </audio>

      )
    })
  }
}

module.exports = connect(state => state)(Displayletter)

//STATE
  // letters: [
  //   {
  //     id: 1,
  //     capital: "A",
  //     lowercase: "a",
  //     capitalSound: "/sounds/capitalSounds/A.mp3",
  //     lowerSound: "/sounds/lowerSounds/a.mp3",
  //     wordImage: [
  //       {id:1, image:"images/words/aniwaniwa.png", sound: "sounds/ua.mp3"},
  //       {id:2, image:"images/words/anuhe.png", sound: "sounds/anuhe.mp3"},
  //     ],
  //     multimedia: "/multimedia/aniwaniwa.webm",
  //     mediaName: "Aniwaniwa Song",
  //   },

Second iteration - have added an empty object in the constructor and passed a 'word' argument through the onClick and playSound.

generateWord(wordsArr) {
return wordsArr.map((word) => {
  return (

    <audio
      key={word}
      ref={(x) => { this.playWords[word] = x; }}>
          <source src={word.sound} preload='auto'/>
    </audio>

  )
})

  playSound(word) {
    this.playWords[word].play()
  }

  constructor() {
    super()
    this.playCapital = this.playCapital.bind(this)
    this.playLower = this.playLower.bind(this)
    this.playSound = this.playSound.bind(this)
    this.playWords = {}
  }

***************ROUND THREE*******************

const debug = require("debug")("components:Displayletter")
const React = require("react")
const { connect } = require("react-redux")
const request = require("superagent")
const { Link } = require("react-router")

class Displayletter extends React.Component {

  constructor() {
    super()
    this.playCapital = this.playCapital.bind(this)
    this.playLower = this.playLower.bind(this)
    this.playWords = {}
  }

  playCapital() {
    this.playCap.play()
  }

  playLower() {
    this.playLow.play()
  }

  playSound(word) {
    this.playWords[word].play()
  }

  handleClick(e) {
    e.preventDefault()
    this.props.router.push("/")
  }

  render() {
debug(this.props)
const { dispatch, letters, letter } = this.props
const wordsArr = letter.wordImage

    return (

      <audio
      key={letter.capitalSound}
      ref={(cap) => { this.playCap = cap; }}>
        <source
          src={letter.capitalSound}
          preload="auto" />
        <track
          kind="captions"
          src=""
          srcLang="en" />
      </audio>

      <audio
      key={letter.lowerSound}
      ref={(low) => { this.playLow = low; }}>
        <source
          src={letter.lowerSound}
          preload="auto" />
        <track
          kind="captions"
          src=""
          srcLang="en" />
      </audio>

      <button
        type="button"
        className="btn btn-xl display"
        onClick={this.playCapital}>
        {letter.capital}
      </button>

      <button
        type="button"
        className="btn btn-xl display"
        onClick={this.playLower}>
        {letter.lowercase}
      </button>

    {this.generateWord(wordsArr)}

      <Link key={letter.id} to={`/media/${letter.capital}`}>
        <button
          type="button"
          className="btn"
          onClick={() =>
              dispatch({
                type: "RENDER_LETTER",
                payload: letter,
              })
          }>
          Watch: {letter.mediaName}
        </button>
      </Link>

)
  }

  generateWord(wordsArr) {
    return wordsArr.map((word) => {
      return (

          <audio
        key={word}
        ref={(x) => { this.playWords[word] = x; }}>
          <source src={word.sound} preload='auto'/>
          </audio>

      )
    })
  }
}

module.exports = connect(state => state)(Displayletter)

  // letters: [
  //   {
  //     id: 1,
  //     capital: "A",
  //     lowercase: "a",
  //     capitalSound: "/sounds/capitalSounds/A.mp3",
  //     lowerSound: "/sounds/lowerSounds/a.mp3",
  //     wordImage: [
  //       {id:1, image:"images/words/aniwaniwa.png", sound: "sounds/ua.mp3"},
  //       {id:2, image:"images/words/anuhe.png", sound: "sounds/anuhe.mp3"},
  //     ],
  //     multimedia: "/multimedia/aniwaniwa.webm",
  //     mediaName: "Aniwaniwa Song",
  //   },

Body:
You're actually very close! The problem lies with how you're saving the reference to your audio elements: ref={(x) => { this.playWord = x; }}. Note that because this is inside a map, every element is saving itself, one after the other, as this.playWord, hence why only the last file is getting played when you click.

What you want to do instead is save all your words to an object or array, then reference in your click handler which one you want to play.

First, do something like this.playWords = {} in your constructor, then ref={(x) => { this.playWords[word] = x; }} in render. This will give you an object playWords that stores references to all the audio elements keyed by word.

Then, give playSound a word argument and make sure the onClick passes in that argument by binding it like onClick={this.playSound.bind(this, word)}.

I've put together a simple example that demonstrates that basic structure; you should be able to easily apply these principles to your component.

class Example extends React.Component {
  constructor() {
    super();
    this.words = {};
  }

  logClick(i) {
    console.log("user clicked on", this.words[i]);
  }

  render() {
    const wordsArr = "this is an example sentence".split(" ");
    return (
      <div className="row letter-container">
        <div className="col-sm-12">
          {this.generateWord(wordsArr)}
        </div>
      </div>
    )
  }

  generateWord(wordsArr) {
    return wordsArr.map((word) => {
      return (
        <div>
          <span
            key={word}
            ref={x => { this.words[word] = x; }}
            onClick={this.logClick.bind(this, word)}
          >
            {word}
          </span>
        </div>
      );
    })
  }
}

ReactDOM.render(<Example />, document.getElementById("container"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container"/>


问:
msdeploy 401 unauthorized error while msbuild works with same credentials
I am trying to deploy a website, initially I had the following command line

```<code>MSBuild.exe PortalWeb.sln
    /t:Rebuild
    /p:DeployOnBuild=True
    /p:DeployTarget=MsDeployPublish
    /p:MSDeployServiceURL=https://wwwt.mycompany.ru:8172/msdeploy.axd
    /p:DeployIISAppPath="Portal/test"
    /p:CreatePackageOnPublish=False
    /p:MsDeployPublishMethod=WMSVC
    /p:AllowUntrustedCertificate=True
    /p:UserName=DeployUser
    /p:Password=123pwd123
    /p:Configuration="Testing Env"
</code>```

Now I am using TFS build server and try to use a web step that generates the following command

```<code>"C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe"
    -verb:sync
    -source:package='PortalWeb.zip'
    -dest:auto,computerName='https://wwwt.mycompany.ru:8172/msdeploy.axd?site=Portal/test',userName='DeployUser',password='123pwd123',authType='WMSVC',includeAcls='False'
    -allowUntrusted
</code>```

And this command fails with 401 Unathorized error:

```<code>2017-06-06T16:00:12.7928227Z ##[error]System.Management.Automation.RemoteException: Error Code: ERROR_USER_UNAUTHORIZED

2017-06-06T16:00:12.7928227Z ##[error]System.Management.Automation.RemoteException: More Information: Connected to the remote computer ("wwwt.mycompany.ru") using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the creden

2017-06-06T16:00:12.7928227Z ##[error]System.Management.Automation.RemoteException: tials represent a user who has permissions to access the site.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_USER_UNAUTHORIZED.

2017-06-06T16:00:12.7928227Z Error: The remote server returned an error: (401) Unauthorized.

2017-06-06T16:00:12.7928227Z Error count: 1.
</code>```

Why one command works with these credentials and the other one fails?

答:
Make sure that the service account of the agent has the needed permission to deploy the website.

But a better way is to create a artifact package in your build process. That's means build and publish your package to a drop folder or inside the tfs.

After that you can deploy your site with release management. There are a lot of benefits if you do this practice.

Body:
I am trying to deploy a website, initially I had the following command line

MSBuild.exe PortalWeb.sln
    /t:Rebuild
    /p:DeployOnBuild=True
    /p:DeployTarget=MsDeployPublish
    /p:MSDeployServiceURL=https://wwwt.mycompany.ru:8172/msdeploy.axd
    /p:DeployIISAppPath="Portal/test"
    /p:CreatePackageOnPublish=False
    /p:MsDeployPublishMethod=WMSVC
    /p:AllowUntrustedCertificate=True
    /p:UserName=DeployUser
    /p:Password=123pwd123
    /p:Configuration="Testing Env"

Now I am using TFS build server and try to use a web step that generates the following command

"C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe"
    -verb:sync
    -source:package='PortalWeb.zip'
    -dest:auto,computerName='https://wwwt.mycompany.ru:8172/msdeploy.axd?site=Portal/test',userName='DeployUser',password='123pwd123',authType='WMSVC',includeAcls='False'
    -allowUntrusted

And this command fails with 401 Unathorized error:

2017-06-06T16:00:12.7928227Z ##[error]System.Management.Automation.RemoteException: Error Code: ERROR_USER_UNAUTHORIZED

2017-06-06T16:00:12.7928227Z ##[error]System.Management.Automation.RemoteException: More Information: Connected to the remote computer ("wwwt.mycompany.ru") using the Web Management Service, but could not authorize. Make sure that you are using the correct user name and password, that the site you are connecting to exists, and that the creden

2017-06-06T16:00:12.7928227Z ##[error]System.Management.Automation.RemoteException: tials represent a user who has permissions to access the site.  Learn more at: http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_USER_UNAUTHORIZED.

2017-06-06T16:00:12.7928227Z Error: The remote server returned an error: (401) Unauthorized.

2017-06-06T16:00:12.7928227Z Error count: 1.

Why one command works with these credentials and the other one fails?


问:
Checking constraints at runtime
I'm trying to define a function that detects whether the type of an input satisfies a given constraint:

```<code>satisfies :: (c a => a -> b) -> a -> Maybe b

-- or the more general
claim :: (c => a) -> Maybe a
</code>```

So the desired behaviour would be:

```<code>>>> :t satisfies @Show show
satisfies @Show show :: a -> Maybe String
>>> satisfies @Show show (0 :: Int)
Just "0"
>>> satisfies @Show show (id :: Int -> Int)
Nothing
</code>```

The goal is to make it easy to define fully polymorphic functions that take
advantage of specializations when possible:

```<code>showAny :: a -> String
showAny (satisfies @Show show -> Just str) = str
showAny (satisfies @Typeable showType -> Just str) = "_ :: " ++ str
showAny _ = "_"
</code>```

As the easiest thing I could try, my first attempt tried using -fdefer-to-runtime

```<code>{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
module Claim where
import System.IO.Unsafe (unsafePerformIO)
import System.IO.Error (catchIOError)

satisfies :: (c a => a -> b) -> a -> Maybe b
satisfies f a = unsafePerformIO $
  (return . Just $! f a) `catchIOError` \_ -> return Nothing
</code>```

This failed because -fdefer-type-errors doesn't defer the checking to
runtime, or allow further checking to be done in the context which it is
actually used (as I had hoped), but instead at compile time replaces found
type errors with the equivalent of error "MESSAGE".

Now I'm out of ideas. Is implementing satisfies even possible?

答:
You can't dispatch on instance availability at runtime. Remember, a constraint is translated by the compiler into a type class dictionary - a record of functions that is passed around explicitly and accessed explicitly at runtime. The "fat arrow" => is represented at runtime by a "thin arrow" ->, so the elaborator needs to know at compile time which dictionary to pass around.

That is, the following crude example:

```<code>class Show a where
    show :: a -> String

instance Show String where
    show = id

showTwice :: Show a => a -> String
showTwice x = show x ++ show x

main = putStrLn $ showTwice "foo"
</code>```

generates Core code which looks approximately like:

```<code>data Show_ a = Show_ { show :: a -> String }

showString_ :: Show_ String
showString_ = Show_ { show = id }

showTwice :: Show_ a -> a -> String
showTwice show_ x = show show_ x ++ show show_ x

main = putStrLn $ showTwice showString_ "foo"
</code>```

When generating code for main, the compiler needs to know where to find showString_.

You can imagine a system wherein you can look up a type class dictionary at runtime with some sort of introspection mechanism, but this would produce weird behaviour from a language design perspective. The problem is orphan instances. If I write a function which attempts to look up a given instance in module A, and define such an instance in an unrelated module B, then the behaviour of that function when called from some client module C depends on whether B was imported by some other part of the program. Pretty strange!

A more usual way of doing "fully polymorphic functions that take advantage of specializations when possible" would be to put the function in question into a type class itself and give it a default implementation (perhaps with a default signature if the default implementation depends on some superclass). Your showAny would then look like this:

```<code>{-# LANGUAGE DefaultSignatures #-}
import Data.Typeable

class ShowAny a where
    showAny :: a -> String
    default showAny :: Typeable a => a -> String
    showAny x = "_ :: " ++ show (typeOf x)
</code>```

You'd need to implement ShowAny for all of the types with which you want to use showAny, but that's usually a single line of code,

```<code>instance (Typeable a, Typeable b) => ShowAny (a -> b)
</code>```

and you can specialise an implementation for a given type just by overriding showAny.

```<code>instance ShowAny String where
    showAny = id
</code>```

You see this approach quite frequently in libraries which do generic programming. aeson, for example, can use GHC.Generics to serialise a given type to and from JSON (all you have to do is derive Generic and write two lines instance ToJSON MyType; instance FromJSON MyType), but you can also write your own instances of ToJSON and FromJSON if the generic code isn't fast enough or you need to customise the output.

Title: Checking constraints at runtime

Body:
I'm trying to define a function that detects whether the type of an input satisfies a given constraint:

satisfies :: (c a => a -> b) -> a -> Maybe b

-- or the more general
claim :: (c => a) -> Maybe a

So the desired behaviour would be:

>>> :t satisfies @Show show
satisfies @Show show :: a -> Maybe String
>>> satisfies @Show show (0 :: Int)
Just "0"
>>> satisfies @Show show (id :: Int -> Int)
Nothing

The goal is to make it easy to define fully polymorphic functions that take
advantage of specializations when possible:

showAny :: a -> String
showAny (satisfies @Show show -> Just str) = str
showAny (satisfies @Typeable showType -> Just str) = "_ :: " ++ str
showAny _ = "_"

As the easiest thing I could try, my first attempt tried using -fdefer-to-runtime

{-# OPTIONS_GHC -fdefer-type-errors -Wno-deferred-type-errors #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
module Claim where
import System.IO.Unsafe (unsafePerformIO)
import System.IO.Error (catchIOError)

satisfies :: (c a => a -> b) -> a -> Maybe b
satisfies f a = unsafePerformIO $
  (return . Just $! f a) `catchIOError` \_ -> return Nothing

This failed because -fdefer-type-errors doesn't defer the checking to
runtime, or allow further checking to be done in the context which it is
actually used (as I had hoped), but instead at compile time replaces found
type errors with the equivalent of error "MESSAGE".

Now I'm out of ideas. Is implementing satisfies even possible?

Body:
You can't dispatch on instance availability at runtime. Remember, a constraint is translated by the compiler into a type class dictionary - a record of functions that is passed around explicitly and accessed explicitly at runtime. The "fat arrow" => is represented at runtime by a "thin arrow" ->, so the elaborator needs to know at compile time which dictionary to pass around.

That is, the following crude example:

class Show a where
    show :: a -> String

instance Show String where
    show = id

showTwice :: Show a => a -> String
showTwice x = show x ++ show x

main = putStrLn $ showTwice "foo"

generates Core code which looks approximately like:

data Show_ a = Show_ { show :: a -> String }

showString_ :: Show_ String
showString_ = Show_ { show = id }

showTwice :: Show_ a -> a -> String
showTwice show_ x = show show_ x ++ show show_ x

main = putStrLn $ showTwice showString_ "foo"

When generating code for main, the compiler needs to know where to find showString_.

You can imagine a system wherein you can look up a type class dictionary at runtime with some sort of introspection mechanism, but this would produce weird behaviour from a language design perspective. The problem is orphan instances. If I write a function which attempts to look up a given instance in module A, and define such an instance in an unrelated module B, then the behaviour of that function when called from some client module C depends on whether B was imported by some other part of the program. Pretty strange!

A more usual way of doing "fully polymorphic functions that take advantage of specializations when possible" would be to put the function in question into a type class itself and give it a default implementation (perhaps with a default signature if the default implementation depends on some superclass). Your showAny would then look like this:

{-# LANGUAGE DefaultSignatures #-}
import Data.Typeable

class ShowAny a where
    showAny :: a -> String
    default showAny :: Typeable a => a -> String
    showAny x = "_ :: " ++ show (typeOf x)

You'd need to implement ShowAny for all of the types with which you want to use showAny, but that's usually a single line of code,

instance (Typeable a, Typeable b) => ShowAny (a -> b)

and you can specialise an implementation for a given type just by overriding showAny.

instance ShowAny String where
    showAny = id

You see this approach quite frequently in libraries which do generic programming. aeson, for example, can use GHC.Generics to serialise a given type to and from JSON (all you have to do is derive Generic and write two lines instance ToJSON MyType; instance FromJSON MyType), but you can also write your own instances of ToJSON and FromJSON if the generic code isn't fast enough or you need to customise the output.