问:
Splitting a list in half
trying to write code that splits a list in half for even numbers of elements, eg. split([1,2,3,4],A,B) would give A = [1,2] and B = [3,4].

And behave like Java list.length()/2 would for odd numbers of elements, so split([1,2,3,4,5],A,B) would give A = [1,2] and B = [3,4,5].

The closest I can get is something like this, but this isn't quite right, and  only works for even numbers.

```<code>split(L, A, B) :-
  append(A, B, L),
  length(A, N),
  length(B, N).
</code>```

Title: Splitting a list in half

Body:
trying to write code that splits a list in half for even numbers of elements, eg. split([1,2,3,4],A,B) would give A = [1,2] and B = [3,4].

And behave like Java list.length()/2 would for odd numbers of elements, so split([1,2,3,4,5],A,B) would give A = [1,2] and B = [3,4,5].

The closest I can get is something like this, but this isn't quite right, and  only works for even numbers.

split(L, A, B) :-
  append(A, B, L),
  length(A, N),
  length(B, N).

Body:
One way to split a list in half in Prolog is to do so using append/3 and the same_length/2 predicates:

split(List, Left, Right) :-
    same_length(Left, Right),
    append(Left, Right, List).
split(List, Left, [R|Rs]) :-
    same_length(Left, Rs),
    append(Left, [R|Rs], List).

This gives you:

| ?- split(L, A, B).
A = B, B = L, L = [] ;
A = [_1038],
B = [_1048],
L = [_1038, _1048] ;
A = [_1038, _1044],
B = [_1054, _1060],
L = [_1038, _1044, _1054, _1060] ;
A = [_1038, _1044, _1050],
B = [_1060, _1066, _1072],
L = [_1038, _1044, _1050, _1060, _1066, _1072] ;
...


来源: stackexchange

问:
How do you copy properties of an object into another without adding properties using Javascript or jQuery?
I want to copy the right object into the left object without copy properties that are in the right object into the left. In the end, I only want the properties that exist in the left object. I can use JavaScript and jQuery

```<code>var left = { "id": "123" };
var right = { "id": "456", "no": "false" };

$.each(left, function (l1_key, l1Value) {
  if (typeof l1Value === 'object') {
    const left_l2 = left[l1_key];
    const right_l1_properties = right[l1_key];
    $.each(left_l2, function (l2_key, l2Value) {
      l2Value = right_l1_properties[l2_key];
    });
  }
});
</code>```

left need to be:

```<code>{ "id": "456" };
</code>```

答:
You could use Object.getOwnPropertyNames() on left and Array.forEach to iterate over the array of left properties. That way you could exclude properties from right that don't match. The complete logic is implemented in the snippet below.

function changeMatchingProps(left, right) {
if (typeof left === 'object' && typeof right === 'object') {
Object.getOwnPropertyNames(left).forEach(function (val, idx, array) {
    if(right.hasOwnProperty(val)) {
          left[val] = right[val];
    }
});
}
}
var left = { "id": "123" };
var right = { "id": "456", "no": "false" };
changeMatchingProps(left, right);
console.log(left);
var left = { "id": "123", "no": "false", "yes": "true" };
var right = { "id": "456", "no": "true" };
changeMatchingProps(left, right);
console.log(left);
var left = { "id": "123", "pid": "" };
var right = { "id": "456", "no": "false", "pid": "afd39cb123df" };
changeMatchingProps(left, right);
console.log(left);
var left = { "id": "123" };
var right = {};
changeMatchingProps(left, right);
console.log(left);```

ContentLicense: CC BY-SA 3.0

Body:
I want to copy the right object into the left object without copy properties that are in the right object into the left. In the end, I only want the properties that exist in the left object. I can use JavaScript and jQuery

var left = { "id": "123" };
var right = { "id": "456", "no": "false" };

$.each(left, function (l1_key, l1Value) {
  if (typeof l1Value === 'object') {
    const left_l2 = left[l1_key];
    const right_l1_properties = right[l1_key];
    $.each(left_l2, function (l2_key, l2Value) {
      l2Value = right_l1_properties[l2_key];
    });
  }
});

left need to be:

{ "id": "456" };


问:
How can I show a form without any controls focused?
I want to show a form, but I don't want any of the controls focused. For example, right now when the form is shown, the button with tabindex 0 is focused. I want the form itself, not a button, to be focused, so that if the user accidentally hits a key it won't do anything. Is this possible? Thanks!</p>

答:
The simplest solution is:

```<code>protected override void OnShown(EventArgs e)
{
    base.OnShown(e);

    ActiveControl = null;
}
</code>```

Alternatively, if all the controls are inside a panel docked to fill, you can focus the panel:

```<code>protected override void OnShown(EventArgs e)
{
    base.OnShown(e);

    pnlMain.Focus();
}
</code>```

With either approach, pressing the tab key will then focus the first control in the tab order.

ContentLicense: CC BY-SA 2.5

Body:
The simplest solution is:

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);

    ActiveControl = null;
}

Alternatively, if all the controls are inside a panel docked to fill, you can focus the panel:

protected override void OnShown(EventArgs e)
{
    base.OnShown(e);

    pnlMain.Focus();
}

With either approach, pressing the tab key will then focus the first control in the tab order.


问:
Converting OkHttp to use the Gradle build system
I have an Android project where I need to modify the source for OkHttp library. Right now they are using Maven. I ran into problems trying to use the default conversion into a Gradle project, specifically around the maven templating plugin. Has anyone had any success converting OkHttp to Gradle from maven?</p>

答:
I was able to convert this to Gradle. There was a maven plugin for creating Java classes from a java-templates folder in one of the projects. I am using a specific version of OkHttp, so I created a new class based on the version.

There were also a number of failing tests around the MockHttpService and http2/Spdy. I either commented out those tests or altered them so they would pass. I am not using http2 or Spdy. Here is a link to the fork I created;

https://github.com/Swyft/okhttp/tree/swyftdev


问:
Using junit @Rule, expectCause() and hamcrest matchers
I have a test:

```<code>@Rule
public ExpectedException thrown = ExpectedException.none();
...
@Test
public void testMethod()
{
    final String error = "error message";
    Throwable expectedCause = new IllegalStateException(error);
    thrown.expectCause(org.hamcrest.Matchers.<Throwable>equalTo(expectedCause));
    someServiceThatTrowsException.foo();
}
</code>```

When run via mvn the test method, I'm getting the error:

java.lang.NoSuchMethodError:
  org.junit.rules.ExpectedException.expectCause(Lorg/hamcrest/Matcher;)V

Test compiles fine.

Please help me, cannot understand how to test the cause of the exception?

答:
To summarize all.

With JUnit 4 ( hamcrest 1.3 , and be careful, JUnit 4 depend on hamcrest-core which not include org.hamcrest.beans package)

So, you need to import:

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-all</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>
```

<p>Code:</p>

<pre class="lang-java prettyprint-override"><code>import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testThatThrowsNiceExceptionWithCauseAndMessages(){

  expectedException.expect(RuntimeException.class );
  expectedException.expectMessage("Exception message");
  expectedException.expectCause(
    allOf(
      isA(IllegalStateException.class),
      hasProperty("message", is("Cause message"))
    )
  );

  throw
    new RuntimeException("Exception message",
      new IllegalStateException("Cause message"));
}
</code>```

Body:
I have a test:

@Rule
public ExpectedException thrown = ExpectedException.none();
...
@Test
public void testMethod()
{
    final String error = "error message";
    Throwable expectedCause = new IllegalStateException(error);
    thrown.expectCause(org.hamcrest.Matchers.<Throwable>equalTo(expectedCause));
    someServiceThatTrowsException.foo();
}

When run via mvn the test method, I'm getting the error:

java.lang.NoSuchMethodError:
  org.junit.rules.ExpectedException.expectCause(Lorg/hamcrest/Matcher;)V

Test compiles fine.

Please help me, cannot understand how to test the cause of the exception?

Body:
To summarize all.

With JUnit 4 ( hamcrest 1.3 , and be careful, JUnit 4 depend on hamcrest-core which not include org.hamcrest.beans package)

So, you need to import:

<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>hamcrest-all</artifactId>
  <version>1.3</version>
  <scope>test</scope>
</dependency>

Code:

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;

@Rule
public ExpectedException expectedException = ExpectedException.none();

@Test
public void testThatThrowsNiceExceptionWithCauseAndMessages(){

  expectedException.expect(RuntimeException.class );
  expectedException.expectMessage("Exception message");
  expectedException.expectCause(
    allOf(
      isA(IllegalStateException.class),
      hasProperty("message", is("Cause message"))
    )
  );

  throw
    new RuntimeException("Exception message",
      new IllegalStateException("Cause message"));
}


问:
how to sort dictionary by value alphabeticallly?
So I have a dictionary, with keys and values, and the values are letters. I want to sort the dictionary so that it prints alphabetically according to the values, but I just can't figure out how to go about it.

For example, I have this dictionary:

```<code>dict = {5 : 'B', 7 : 'A', 9 : 'C'}
</code>```

How do I get this to be sorted so that it prints out as follows?:

```<code>{7 : 'A', 5 : 'B', 9 : 'C'}
</code>```

答:
Dicts are unsorted, if you need something in a certain order for sure, use a list. Also, you can't duplicate keys.

to make a list:

```<code>your_list=['B','A','C']
#yay, now sort
your_list.sort()
</code>```

Body:
So I have a dictionary, with keys and values, and the values are letters. I want to sort the dictionary so that it prints alphabetically according to the values, but I just can't figure out how to go about it.

For example, I have this dictionary:

dict = {5 : 'B', 7 : 'A', 9 : 'C'}

How do I get this to be sorted so that it prints out as follows?:

{7 : 'A', 5 : 'B', 9 : 'C'}

Body:
Dicts are unsorted, if you need something in a certain order for sure, use a list. Also, you can't duplicate keys.

to make a list:

your_list=['B','A','C']
#yay, now sort
your_list.sort()


问:
Removing strings from another string in java
Lets say I have this list of words:

```<code> String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};
</code>```

Than I have text

```<code> String text = "I would like to do a nice novel about nature AND people"
</code>```

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

```<code> String noStopWordsText = remove(text, stopWords);
</code>```

Result:

```<code> " would like do nice novel nature people"
</code>```

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

```<code> private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);
</code>```

答: Split text on whilespace. Then loop through the array and keep appending to a StringBuilder only if it is not one of the stop words.

Body:
Lets say I have this list of words:

 String[] stopWords = new String[]{"i","a","and","about","an","are","as","at","be","by","com","for","from","how","in","is","it","not","of","on","or","that","the","this","to","was","what","when","where","who","will","with","the","www"};

Than I have text

 String text = "I would like to do a nice novel about nature AND people"

Is there method that matches the stopWords and removes them while ignoring case; like this somewhere out there?:

 String noStopWordsText = remove(text, stopWords);

Result:

 " would like do nice novel nature people"

If you know about regex that wold work great but I would really prefer something like commons solution that is bit more performance oriented.

BTW, right now I'm using this commons method which is lacking proper insensitive case handling:

 private static final String[] stopWords = new String[]{"i", "a", "and", "about", "an", "are", "as", "at", "be", "by", "com", "for", "from", "how", "in", "is", "it", "not", "of", "on", "or", "that", "the", "this", "to", "was", "what", "when", "where", "who", "will", "with", "the", "www", "I", "A", "AND", "ABOUT", "AN", "ARE", "AS", "AT", "BE", "BY", "COM", "FOR", "FROM", "HOW", "IN", "IS", "IT", "NOT", "OF", "ON", "OR", "THAT", "THE", "THIS", "TO", "WAS", "WHAT", "WHEN", "WHERE", "WHO", "WILL", "WITH", "THE", "WWW"};
 private static final String[] blanksForStopWords = new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};

 noStopWordsText = StringUtils.replaceEach(text, stopWords, blanksForStopWords);


问:
Get everything before dot or comma c#
how can I get a substring of everything before dot or comma?

For example:

```<code>    string input = "2.1";
int charLocation = text.IndexOf(".", StringComparison.Ordinal);
    string test = input.Substring(0, charLocation );
</code>```

but what if I have an input = "2,1" ?

I would like to do it in one method, not using twice a substring (once for dot and once for comma)?

答:
This will split the string for either comma or period...    </p>

```<code>input.Split(',','.');
</code>```

Title: Get everything before dot or comma c#

Body:
how can I get a substring of everything before dot or comma?

For example:

    string input = "2.1";
int charLocation = text.IndexOf(".", StringComparison.Ordinal);
    string test = input.Substring(0, charLocation );

but what if I have an input = "2,1" ?

I would like to do it in one method, not using twice a substring (once for dot and once for comma)?

Body:
This will split the string for either comma or period...

input.Split(',','.');


问:
Formatting the output from a text file - Java
How can I change the code so that it prints out like the way I want it to be printed out? I want the userNameGenerator to be printed out first, with an arrow (->) in front of it, and the personName to be displayed with open and close square brackets ([]) beside it. I also want to remove the commas at the end. I've done a bit of it already as you can see below:

Code that needs changing:

```<code>Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++) {
    String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
    for(int j = 0; j < regionSplit.length; j++) {
    newStrSet.add(regionSplit[j]);
    }
}

for (String p: newStrSet) {
    System.out.printf("%s -> [", p);
    for (Codes2 s: personFile) {
        if (s.getUserNameGenerator().contains(p)) {
            System.out.printf("%s, ", s.getPersonName());
        }
    }
    System.out.println("]");
}
</code>```

Full code:

```<code>import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++) {
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++) {
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> [", p);
            for (Codes2 s: personFile) {
            if (s.getUserNameGenerator().contains(p)) {
                System.out.printf("%s, ", s.getPersonName());
            }
        }
        System.out.println("]");
    }
}
</code>```

Java Class:

```<code>public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }
}
</code>```

Output:

```<code>Dompteuse -> [Imran Sullivan, ]
Deservedness -> [Eadie Jefferson, ]
Ostracize -> [Eadie Jefferson, ]
Abattoir -> [Angel Whitehouse, ]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver, ]
</code>```

How I want the output to look like:

```<code>Dompteuse -> [Imran Sullivan]
Deservedness -> [Eadie Jefferson]
Ostracize -> [Eadie Jefferson]
Abattoir -> [Angel Whitehouse]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver]
</code>```

答:
You need to change the for loop that handles the printing so that it only prints the comma if there is another element in the personFile.

Here's what I would try (note that I can't test this code since I don't have access to your data file):

```<code>for (String p: newStrSet) {
    System.out.printf("%s -> [", p);
    boolean needComma = false;

    // Use indices instead of a for-each so you can
    // check if there's a next element
    for (int i = 0; i < personFile.size(); ++i) {
        Codes2 s = personFile.get(i);

        if (s.getUserNameGenerator().contains(p)) {
            // Only print out the comma and space if there's a preceding element
            if (needComma) {
                System.out.print(", ");
            }

            System.out.printf("%s", s.getPersonName());

            needComma = true;
        }
    }

    System.out.println("]");
}
</code>```

Body:
How can I change the code so that it prints out like the way I want it to be printed out? I want the userNameGenerator to be printed out first, with an arrow (->) in front of it, and the personName to be displayed with open and close square brackets ([]) beside it. I also want to remove the commas at the end. I've done a bit of it already as you can see below:

Code that needs changing:

Set<String> newStrSet = new HashSet<>();
for(int i = 0; i < personFile.size(); i++) {
    String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
    for(int j = 0; j < regionSplit.length; j++) {
    newStrSet.add(regionSplit[j]);
    }
}

for (String p: newStrSet) {
    System.out.printf("%s -> [", p);
    for (Codes2 s: personFile) {
        if (s.getUserNameGenerator().contains(p)) {
            System.out.printf("%s, ", s.getPersonName());
        }
    }
    System.out.println("]");
}

Full code:

import java.util.*;
import java.io.*;

public class Codes {
    public static void main(String[] args) {
        List<Codes2> personFile = new ArrayList<>();

        try {
            BufferedReader br = new BufferedReader(new FileReader("person-data.txt"));
            String fileRead = br.readLine();
            while (fileRead != null) {
                String[] personData = fileRead.split(":");
                String personName = personData[0];
                String userNameGenerator = personData[1];
                Codes2 personObj = new Codes2(personName, userNameGenerator);
                personFile.add(personObj);
                fileRead = br.readLine();
            }
            br.close();
        }

        catch (FileNotFoundException ex) {
            System.out.println("File not found!");
        }

        Set<String> newStrSet = new HashSet<>();
        for(int i = 0; i < personFile.size(); i++) {
            String[] regionSplit = personFile.get(i).getUserNameGenerator().split(", ");
            for(int j = 0; j < regionSplit.length; j++) {
                newStrSet.add(regionSplit[j]);
            }
        }

        for (String p: newStrSet) {
            System.out.printf("%s -> [", p);
            for (Codes2 s: personFile) {
            if (s.getUserNameGenerator().contains(p)) {
                System.out.printf("%s, ", s.getPersonName());
            }
        }
        System.out.println("]");
    }
}

Java Class:

public class Codes2 implements Comparable<Codes2> {

    private String personName;
    private String userNameGenerator;

    public Codes2(String personName, String userNameGenerator) {
        this.personName = personName;
        this.userNameGenerator = userNameGenerator;
    }

    public String getPersonName() {
        return personName;
    }

    public String getUserNameGenerator() {
        return userNameGenerator;
    }

    @Override
    public int compareTo(Codes2 o) {
        return getUserNameGenerator().compareTo(o.getUserNameGenerator());
    }

    public int compare(Object lOCR1, Object lOCR2) {
        return ((Codes2)lOCR1).userNameGenerator
                .compareTo(((Codes2)lOCR2).userNameGenerator);
    }
}

Output:

Dompteuse -> [Imran Sullivan, ]
Deservedness -> [Eadie Jefferson, ]
Ostracize -> [Eadie Jefferson, ]
Abattoir -> [Angel Whitehouse, ]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver, ]

How I want the output to look like:

Dompteuse -> [Imran Sullivan]
Deservedness -> [Eadie Jefferson]
Ostracize -> [Eadie Jefferson]
Abattoir -> [Angel Whitehouse]
Choreography -> [Imran Sullivan, Taylor Vargas, Priya Oliver]

Body:
You need to change the for loop that handles the printing so that it only prints the comma if there is another element in the personFile.

Here's what I would try (note that I can't test this code since I don't have access to your data file):

for (String p: newStrSet) {
    System.out.printf("%s -> [", p);
    boolean needComma = false;

    // Use indices instead of a for-each so you can
    // check if there's a next element
    for (int i = 0; i < personFile.size(); ++i) {
        Codes2 s = personFile.get(i);

        if (s.getUserNameGenerator().contains(p)) {
            // Only print out the comma and space if there's a preceding element
            if (needComma) {
                System.out.print(", ");
            }

            System.out.printf("%s", s.getPersonName());

            needComma = true;
        }
    }

    System.out.println("]");
}


问:
Chrome Print Dialog won't execute a separate JavaScript function until the dialog is cancelled or printed
I'm trying to execute a tracking call on on a click event that also executes window.print(). I've put the tracking call first but it won't execute until the dialog box is closed.

Firefox and IE execute everything in order. The issue seems unique to Chrome.
I've consoled some text and they show up in the right order, but the network doesn't show the tracking call until I close the dialog box.

Anyone know how to get around this?

```<code><script>
function printTrack(){
    _satellite.track('something');
    window.print();
}
</script>

<button id="print-button" onclick="javascript:printTrack()">Print</button>
</code>```

答:
I was able to resolve this by using a promise:</p>

```<code>function printTrack(pn) {
        return new Promise(function (resolve, reject) {
            resolve(_satellite.setVar('pdf_name', pn),
            _satellite.track('pdf_print'));
        });
    }

    printTrack(printName).then(function (result) {
        window.print();
    });
</code>```

Body:
I'm trying to execute a tracking call on on a click event that also executes window.print(). I've put the tracking call first but it won't execute until the dialog box is closed.

Firefox and IE execute everything in order. The issue seems unique to Chrome.
I've consoled some text and they show up in the right order, but the network doesn't show the tracking call until I close the dialog box.

Anyone know how to get around this?

<button id="print-button" onclick="javascript:printTrack()">Print</button>

Body:
I was able to resolve this by using a promise:

function printTrack(pn) {
        return new Promise(function (resolve, reject) {
            resolve(_satellite.setVar('pdf_name', pn),
            _satellite.track('pdf_print'));
        });
    }

    printTrack(printName).then(function (result) {
        window.print();
    });


问:
Is it possible to create HTML element attribute only in case of some condition?
Is it possible to decide on html element creation time excluding or including an elements attribute like setup a callback or not?

When using the ng-repeat flow I have some condition where I want to create the html element with a close-callback handler and in some cases the element should not contain a close handler definition.

```<code><div ng-repeat="item in ctrl.items"
close="ctrl.close()">XYZ</div>
</code>```

... or without callback ..

```<code><div ng-repeat="item in ctrl.items">XYZ</div>
</code>```

... maybe something like ng-if? Is something like that possible? The check condition is in the item itself. So during ng-repeat I need to check some items internal state like:

```<code>item.state === 'state1' ? add close handler : do nothing ...
</code>```

Where I can add this condition check and how i perform the close handler adding or not?

Cheers

答:
Take advantage of Logical Operator Short Circuit Evaluation:

```<code><div ng-repeat="item in ctrl.items"
     close="item.closable && ctrl.close()">XYZ</div>
</code>```

When item.closable is false, the ctrl.close() function will not be evaluated. Thus the function is conditionally evaluated based on the value of item.closable.

Body:
Is it possible to decide on html element creation time excluding or including an elements attribute like setup a callback or not?

When using the ng-repeat flow I have some condition where I want to create the html element with a close-callback handler and in some cases the element should not contain a close handler definition.

XYZ

... or without callback ..

XYZ

... maybe something like ng-if? Is something like that possible? The check condition is in the item itself. So during ng-repeat I need to check some items internal state like:

item.state === 'state1' ? add close handler : do nothing ...

Where I can add this condition check and how i perform the close handler adding or not?

Cheers

Body:
Take advantage of Logical Operator Short Circuit Evaluation:

<div ng-repeat="item in ctrl.items"
     close="item.closable && ctrl.close()">XYZ</div>

When item.closable is false, the ctrl.close() function will not be evaluated. Thus the function is conditionally evaluated based on the value of item.closable.


问:
NHibernate Linq. Querying associations and multiple sql queries
I just started playing with NHibernate Linq and found a strange behavior. I have a class Category and a class Product. Category has a list of Products with one to many association. Here's mappings:

```<code>  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="none" lazy="false" inverse="true" fetch="join">
      <key column="CategoryId" />
      <one-to-many class="Product" />
      <!--<filter name="IdFilter" />-->
    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>
</code>```

When I query categories with this query

```<code>var cs = session.Query<Category>().Where(c => c.Products.Any(p => p.Price == 13.3392)).ToList();
</code>```

I look at NHibernate profiler and see this results

```<code>select category0_.Id   as Id1_,
       category0_.Name as Name1_
from   Category category0_
where  exists (select products1_.Id
               from   Product products1_
               where  category0_.Id = products1_.CategoryId
                      and products1_.Price = 13.3392 /* @p0 */)

SELECT products0_.CategoryId   as CategoryId1_,
       products0_.Id           as Id1_,
       products0_.Id           as Id0_0_,
       products0_.Name         as Name0_0_,
       products0_.Discontinued as Disconti3_0_0_,
       products0_.Price        as Price0_0_,
       products0_.CategoryId   as CategoryId0_0_
FROM   Product products0_
WHERE  products0_.CategoryId = 131073 /* @p0 */

SELECT products0_.CategoryId   as CategoryId1_,
       products0_.Id           as Id1_,
       products0_.Id           as Id0_0_,
       products0_.Name         as Name0_0_,
       products0_.Discontinued as Disconti3_0_0_,
       products0_.Price        as Price0_0_,
       products0_.CategoryId   as CategoryId0_0_
FROM   Product products0_
WHERE  products0_.CategoryId = 32768 /* @p0 */
</code>```

The category is fetched one by one from database. So the amount of roundtrips to database equals to the amount of category objects matched by where clause.

Is there a way to tell NHibernate to optimize the query? I'm completely lost.

Thank you very much for your support.

答:
on your bag mapping class try adding batch-size

```<code><bag name="Products" batch-size="25" ...>
</code>```

Body:
I just started playing with NHibernate Linq and found a strange behavior. I have a class Category and a class Product. Category has a list of Products with one to many association. Here's mappings:

  <class name="Category">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" length="20" />

    <bag name="Products" cascade="none" lazy="false" inverse="true" fetch="join">
      <key column="CategoryId" />
      <one-to-many class="Product" />

    </bag>
  </class>

  <class name="Product">
    <id name="Id">
      <generator class="hilo" />
    </id>
    <property name="Name" lazy="false" />
    <property name="Discontinued" lazy="false" />
    <property name="Price" lazy="false" />
    <many-to-one name="Category"
             class="Category"
             column="CategoryId"
             cascade="none" />
  </class>

When I query categories with this query

var cs = session.Query<Category>().Where(c => c.Products.Any(p => p.Price == 13.3392)).ToList();

I look at NHibernate profiler and see this results

select category0_.Id   as Id1_,
       category0_.Name as Name1_
from   Category category0_
where  exists (select products1_.Id
               from   Product products1_
               where  category0_.Id = products1_.CategoryId
                      and products1_.Price = 13.3392 /* @p0 */)

SELECT products0_.CategoryId   as CategoryId1_,
       products0_.Id           as Id1_,
       products0_.Id           as Id0_0_,
       products0_.Name         as Name0_0_,
       products0_.Discontinued as Disconti3_0_0_,
       products0_.Price        as Price0_0_,
       products0_.CategoryId   as CategoryId0_0_
FROM   Product products0_
WHERE  products0_.CategoryId = 131073 /* @p0 */

SELECT products0_.CategoryId   as CategoryId1_,
       products0_.Id           as Id1_,
       products0_.Id           as Id0_0_,
       products0_.Name         as Name0_0_,
       products0_.Discontinued as Disconti3_0_0_,
       products0_.Price        as Price0_0_,
       products0_.CategoryId   as CategoryId0_0_
FROM   Product products0_
WHERE  products0_.CategoryId = 32768 /* @p0 */

The category is fetched one by one from database. So the amount of roundtrips to database equals to the amount of category objects matched by where clause.

Is there a way to tell NHibernate to optimize the query? I'm completely lost.

Thank you very much for your support.

Body:
on your bag mapping class try adding batch-size

<bag name="Products" batch-size="25" ...>


问:
Handlebarsjs check if a string is equal to a value
Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can't seem to find anything relevant to this in the Handlebars reference.

For example:

```<code>{{#if sampleString == "This is a string"}}
...do something
{{/if}}
</code>```

答:
A common case for a simple, re-usable helper function is to cause a return of string1 if values are equal and string2 if they are not.

Example:

Helper (let's call it "ifEqual" and send 4 parameters):

```<code>helpers: {

    ifEqual: function (obj, value, trueString, falseString) {
            return ( (obj===value) ? trueString : falseString );
}
</code>```

Template Use:

For this example, assume the template receives a "transaction" object with a "transactionType" property: { transactionType: "expense", description: "Copies" }

Let's say our template has a <select> for the Transaction Type, with various <option>s as shown.  We want to use Handlebars to pre-select the option which coincides with the value of transactionType.

Our new {{ ifEqual }} helper is used to insert "selected" for the <option> with the matching value of "expense."

```<code><select required id="selTransactionType" name="selTransactionType" class="form-control" onchange='transactionTypeChanged()'>
   <option value='hourly' {{ ifEqual transaction.transactionType "hourly" "selected" "" }} >Hourly fee</option>
   <option value='flat' {{ ifEqual transaction.transactionType "flat" "selected" "" }} >Flat fee</option>
   <option value='expense' {{ ifEqual transaction.transactionType "expense" "selected" "" }} >Expense</option>
   <option value='payment' {{ ifEqual transaction.transactionType "payment" "selected" "" }} >Payment</option>
   <option value='credit' {{ ifEqual transaction.transactionType "credit" "selected" "" }} >Credit</option>
   <option value='debit' {{ ifEqual transaction.transactionType "debit" "selected" "" }} >Debit</option>
</select>
</code>```

Body:
Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can't seem to find anything relevant to this in the Handlebars reference.

For example:

{{#if sampleString == "This is a string"}}
...do something
{{/if}}

Body:
A common case for a simple, re-usable helper function is to cause a return of string1 if values are equal and string2 if they are not.

Example:

Helper (let's call it "ifEqual" and send 4 parameters):

helpers: {

    ifEqual: function (obj, value, trueString, falseString) {
            return ( (obj===value) ? trueString : falseString );
}

Template Use:

For this example, assume the template receives a "transaction" object with a "transactionType" property: { transactionType: "expense", description: "Copies" }

Let's say our template has a <select> for the Transaction Type, with various <option>s as shown.  We want to use Handlebars to pre-select the option which coincides with the value of transactionType.

Our new {{ ifEqual }} helper is used to insert "selected" for the <option> with the matching value of "expense."

<select required id="selTransactionType" name="selTransactionType" class="form-control" onchange='transactionTypeChanged()'>
   <option value='hourly' {{ ifEqual transaction.transactionType "hourly" "selected" "" }} >Hourly fee</option>
   <option value='flat' {{ ifEqual transaction.transactionType "flat" "selected" "" }} >Flat fee</option>
   <option value='expense' {{ ifEqual transaction.transactionType "expense" "selected" "" }} >Expense</option>
   <option value='payment' {{ ifEqual transaction.transactionType "payment" "selected" "" }} >Payment</option>
   <option value='credit' {{ ifEqual transaction.transactionType "credit" "selected" "" }} >Credit</option>
   <option value='debit' {{ ifEqual transaction.transactionType "debit" "selected" "" }} >Debit</option>
</select>


问:
Dapper UpdateAsync ignore column
I am trying to update with Dapper.Contrib this table:

```<code>public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}
</code>```

I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.

I tried using [NotMapped] and [UpdateIgnore] attributes but no help.

Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.

Can someone help me figure out how to ignore this column when updating the table in the database?

答:
Well, it's just not supported. Here is related issue, and solution is expected only in Dapper v2. You can also inspect source code (it's pretty simple) and see that updated properties are searched as follows:

```<code> var allProperties = TypePropertiesCache(type);
 keyProperties.AddRange(explicitKeyProperties);
 var computedProperties = ComputedPropertiesCache(type);
 var nonIdProps = allProperties.Except(keyProperties.Union(computedProperties)).ToList();
</code>```

So all properties not marked with Key\ExplicitKey\Computed and which are writable are included. The same happens for InsertAsync (except properties with ExplicitKey are also included in insert, but you cannot use this attribute in your situtaion, because your property is not key after all).

So you have to either wait for this to be implemented, fork and implement yourself, or just write your own UpdateAsync method. You can see from source code that it's very simple and is not hard to reimplement.

ContentLicense: CC BY-SA 4.0

Title: Dapper UpdateAsync ignore column

Body:
I am trying to update with Dapper.Contrib this table:

public class MyTable
{
    public int ID { get; set; }
    public int SomeColumn1 { get; set; }
    public int SomeColumn2 { get; set; }
    public int CreateUserID { get; set; }
    public int UpdateUserID { get; set; }
}

I don't want to update the CreateUserID column because it is an update method so that I want to ignore this column while calling the Dapper - Update.Async(entity) method.

I tried using [NotMapped] and [UpdateIgnore] attributes but no help.

Note: I still want this column to be passed on insert operations, therefore, [Computed] and [Write(false)] is not appropriate.

Can someone help me figure out how to ignore this column when updating the table in the database?

Body:
Well, it's just not supported. Here is related issue, and solution is expected only in Dapper v2. You can also inspect source code (it's pretty simple) and see that updated properties are searched as follows:

 var allProperties = TypePropertiesCache(type);
 keyProperties.AddRange(explicitKeyProperties);
 var computedProperties = ComputedPropertiesCache(type);
 var nonIdProps = allProperties.Except(keyProperties.Union(computedProperties)).ToList();

So all properties not marked with Key\ExplicitKey\Computed and which are writable are included. The same happens for InsertAsync (except properties with ExplicitKey are also included in insert, but you cannot use this attribute in your situtaion, because your property is not key after all).

So you have to either wait for this to be implemented, fork and implement yourself, or just write your own UpdateAsync method. You can see from source code that it's very simple and is not hard to reimplement.


问:
Remove Margin AndroidPlot
I'm trying to remove the margins of my Plot on Android. I've implemented AndroidPlot 1.5.1 Library.

That's my xml-Code

```<code>        <com.androidplot.xy.XYPlot
        style="@style/APDefacto.Dark"
        android:id="@+id/plot"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@id/CubeView"
        android:layout_alignParentBottom="true"
        ap:renderMode="use_background_thread"
        ap:domainLineColor="@color/ap_transparent"
        ap:rangeLineColor="@color/ap_transparent"
        ap:domainOriginLineColor="@color/ap_transparent"
        ap:rangeOriginLineColor="@color/ap_transparent"
        ap:lineLabelTextColorBottom="@color/ap_transparent"
        ap:lineLabelTextColorLeft="@color/ap_transparent"

        />
</code>```

And that's my java Code

```<code>    plot = (XYPlot) findViewById(R.id.plot);

    ecg = new ECGModel(2000);
    MyFadeFormatter formatter =new MyFadeFormatter(2000);
    formatter.setLegendIconEnabled(false);
    plot.addSeries(ecg, formatter);

    plot.setRangeBoundaries(0, 800, BoundaryMode.FIXED);
    plot.setDomainBoundaries(0, 2000, BoundaryMode.FIXED);
    redrawer = new Redrawer(plot, 30, true);
</code>```

答: You can replace style="@style/APDefacto.Dark" with style="@style/FullScreenGraph".  That should get you pretty close.

Title: Remove Margin AndroidPlot

Body:
I'm trying to remove the margins of my Plot on Android. I've implemented AndroidPlot 1.5.1 Library.

That's my xml-Code

        <com.androidplot.xy.XYPlot
        style="@style/APDefacto.Dark"
        android:id="@+id/plot"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@id/CubeView"
        android:layout_alignParentBottom="true"
        ap:renderMode="use_background_thread"
        ap:domainLineColor="@color/ap_transparent"
        ap:rangeLineColor="@color/ap_transparent"
        ap:domainOriginLineColor="@color/ap_transparent"
        ap:rangeOriginLineColor="@color/ap_transparent"
        ap:lineLabelTextColorBottom="@color/ap_transparent"
        ap:lineLabelTextColorLeft="@color/ap_transparent"

        />

And that's my java Code

    plot = (XYPlot) findViewById(R.id.plot);

    ecg = new ECGModel(2000);
    MyFadeFormatter formatter =new MyFadeFormatter(2000);
    formatter.setLegendIconEnabled(false);
    plot.addSeries(ecg, formatter);

    plot.setRangeBoundaries(0, 800, BoundaryMode.FIXED);
    plot.setDomainBoundaries(0, 2000, BoundaryMode.FIXED);
    redrawer = new Redrawer(plot, 30, true);


问:
Bootstrap Collapse - No Animation
I am implementing Bootstrap Collapse to my website by clicking an icon from the Font Awesome library. When I press it, the content collapses, but there is no animation, it just pops up. What am I doing wrong?

Here's my code

```<code><div class="container col-sm-12 banner">
    <i class="fa fa-plus" aria-hidden="true" data-toggle="collapse" data-target="#moreInfo"></i>
</div>
<div id="moreInfo" class="collapse">
    <div class="hiddenInfo">
                123
    </div>
</div>
</code>```

答:
You're running into a conflict due to your improper implementation of Bootstrap's Grid system.  .container and .col-sm-12 cannot be combined in this fashion; it results in a series of floating errors that conflicts with the transition effect.

Once you correctly implement Bootstrap's Grid (and address clear issues with your other float) the transition animates as expected.

.banner {
  background-color: #1194f0;
  padding: 20px;
}

.banner i {
  font-size: 40px;
  float: right;
  line-height: 50px;
}

.hiddenInfo {
  background-color: black;
  color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <div class="banner clearfix">
        <i class="fa fa-plus" aria-hidden="true" data-toggle="collapse" data-target="#moreInfo"></i>
      </div>
    </div>

    <div class="col-sm-12">
      <div id="moreInfo" class="collapse">
        <div class="hiddenInfo">
          123
        </div>
      </div>
    </div>
  </div>
</div></code>```

Title: Bootstrap Collapse - No Animation

Body:
I am implementing Bootstrap Collapse to my website by clicking an icon from the Font Awesome library. When I press it, the content collapses, but there is no animation, it just pops up. What am I doing wrong?

Here's my code

                123

Body:
You're running into a conflict due to your improper implementation of Bootstrap's Grid system.  .container and .col-sm-12 cannot be combined in this fashion; it results in a series of floating errors that conflicts with the transition effect.

Once you correctly implement Bootstrap's Grid (and address clear issues with your other float) the transition animates as expected.

.banner {
  background-color: #1194f0;
  padding: 20px;
}

.banner i {
  font-size: 40px;
  float: right;
  line-height: 50px;
}

.hiddenInfo {
  background-color: black;
  color: white;
}

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-sm-12">
      <div class="banner clearfix">
        <i class="fa fa-plus" aria-hidden="true" data-toggle="collapse" data-target="#moreInfo"></i>
      </div>
    </div>

    <div class="col-sm-12">
      <div id="moreInfo" class="collapse">
        <div class="hiddenInfo">
          123
        </div>
      </div>
    </div>
  </div>
</div>


问:
implement vlookup like function in javascript
I have an object in my React component's state that looks like this:

```<code>const elementPositions =  {
  "0": 180.2,
  "1": 350.8666666666667,
  "2": 521.5333333333333,
  "3": 692.2,
  "4": 862.8666666666667,
  "5": 1033.5333333333333,
  "6": 1204.2
}
</code>```

I have scroll listener that returns a scroll position value, let's say const scrollY = 466 in this instance.

I need to create a function that returns the corresponding index for the scroll position - i.e. 466 would return 1 since it is greater than 350 but less than 521. What's the best way to achieve this? I was thinking something along the lines of this but am not sure it's the best approach:

```<code>const values = Object.values(elementPositions)
values.push(scrollY)
values.sort((a, b) => {return a-b})
const newIndex = values.indexOf(scrollY) - 1
</code>```

答:
Assuming elementPositions is an array:

```<code>[180.2, 350.866, ...]
</code>```

This will return the value in O(n) (better than sorting):

```<code>// Get all values smaller than current scrollY
positions = elementPositions.filter(e => e <= scrollY);

// The last element will be the one closest
value = positions.length ? positions[positions.length - 1] : elementPositions[0];
</code>```

You can then use .indexOf to get the index if you want.

By no means this is considered efficient, and you should not do this on every scroll event.

The most efficient way is probably doing a binary search which is O(log n):

function rec_search(array, value, left, right) {
    if (right - left == 1) return left;
    var middle = Math.floor((left + right) / 2),
        middleValue = array[middle];
    if (value < middleValue) return rec_search(array, value, left, middle);
    else return rec_search(array, value, middle, right);
}

function search(array, value) {
    if (array.length == 0) return -1;
    if (value < array[0]) return -1;
    if (value > array[array.length - 1]) return array.length - 1;
    return rec_search(array, value, 0, array.length - 1);
}

var positions = [1, 2, 4, 8, 16, 32];  // sorted array
console.log(search(positions, 7));```

You can also compute an index algebraically if you know the function that generated the numbers.

Body:
I have an object in my React component's state that looks like this:

const elementPositions =  {
  "0": 180.2,
  "1": 350.8666666666667,
  "2": 521.5333333333333,
  "3": 692.2,
  "4": 862.8666666666667,
  "5": 1033.5333333333333,
  "6": 1204.2
}

I have scroll listener that returns a scroll position value, let's say const scrollY = 466 in this instance.

I need to create a function that returns the corresponding index for the scroll position - i.e. 466 would return 1 since it is greater than 350 but less than 521. What's the best way to achieve this? I was thinking something along the lines of this but am not sure it's the best approach:

const values = Object.values(elementPositions)
values.push(scrollY)
values.sort((a, b) => {return a-b})
const newIndex = values.indexOf(scrollY) - 1

Body:
Assuming elementPositions is an array:

[180.2, 350.866, ...]

This will return the value in O(n) (better than sorting):

// Get all values smaller than current scrollY
positions = elementPositions.filter(e => e <= scrollY);

// The last element will be the one closest
value = positions.length ? positions[positions.length - 1] : elementPositions[0];

You can then use .indexOf to get the index if you want.

By no means this is considered efficient, and you should not do this on every scroll event.

The most efficient way is probably doing a binary search which is O(log n):

function rec_search(array, value, left, right) {
    if (right - left == 1) return left;
    var middle = Math.floor((left + right) / 2),
        middleValue = array[middle];
    if (value < middleValue) return rec_search(array, value, left, middle);
    else return rec_search(array, value, middle, right);
}

function search(array, value) {
    if (array.length == 0) return -1;
    if (value < array[0]) return -1;
    if (value > array[array.length - 1]) return array.length - 1;
    return rec_search(array, value, 0, array.length - 1);
}

var positions = [1, 2, 4, 8, 16, 32];  // sorted array
console.log(search(positions, 7));

You can also compute an index algebraically if you know the function that generated the numbers.


答:
Use the IndexOfAny function. It allows you to specify a list of characters to look for, rather than just a single character. You could then make a substring up to the return value of that function.

e.g.

```<code>char[] chars = { '.', ',' }
String out = s.Substring(0,s.IndexOfAny(chars));
</code>```

Title: Get everything before dot or comma c#

Body:
how can I get a substring of everything before dot or comma?

For example:

    string input = "2.1";
int charLocation = text.IndexOf(".", StringComparison.Ordinal);
    string test = input.Substring(0, charLocation );

but what if I have an input = "2,1" ?

I would like to do it in one method, not using twice a substring (once for dot and once for comma)?

Body:
Use the IndexOfAny function. It allows you to specify a list of characters to look for, rather than just a single character. You could then make a substring up to the return value of that function.

e.g.

char[] chars = { '.', ',' }
String out = s.Substring(0,s.IndexOfAny(chars));


问:
Celebrate Joi validation with Express using Router
The documentation shows how to use celebrate in the app's main file. My routes are already handled by express Router and it is separated from the index file where I have my app's setup.

I would like to set up a validation for the request body on a post route. The example in the docs shows how to do the setup in the main file, and this part confuses me because I have the routes separated in a different file and I'm using router.post('/') instead of app.post('/') due to the usage of Express Router.

Where should I put

```<code>const { celebrate, Joi, errors } = require('celebrate');
</code>```

and

```<code>app.use(errors());
</code>```

To the main index file or to my routes file?

Thanks for your help.

答:
You need to put const { celebrate, Joi} = require('celebrate'); at the top of your routes file

Then you can use celebrate in your routes for validation

```<code>router.post('/', celebrate({
  body: Joi.object().keys({
    name: Joi.string().required(),
    age: Joi.number().integer(),
    role: Joi.string().default('admin')
  })
}), (req, res) => {});
</code>```

In your index file add to the top of your index file

```<code>const { errors } = require('celebrate');
</code>```

then at the end

```<code>app.use(errors())
</code>```

Body:
The documentation shows how to use celebrate in the app's main file. My routes are already handled by express Router and it is separated from the index file where I have my app's setup.

I would like to set up a validation for the request body on a post route. The example in the docs shows how to do the setup in the main file, and this part confuses me because I have the routes separated in a different file and I'm using router.post('/') instead of app.post('/') due to the usage of Express Router.

Where should I put

const { celebrate, Joi, errors } = require('celebrate');

and

app.use(errors());

To the main index file or to my routes file?

Thanks for your help.

Body:
You need to put const { celebrate, Joi} = require('celebrate'); at the top of your routes file

Then you can use celebrate in your routes for validation

router.post('/', celebrate({
  body: Joi.object().keys({
    name: Joi.string().required(),
    age: Joi.number().integer(),
    role: Joi.string().default('admin')
  })
}), (req, res) => {});

In your index file add to the top of your index file

const { errors } = require('celebrate');

then at the end

app.use(errors())


问:
Contour plot or heatmap from three continuous variables
I have a model which has told me there is an interaction between two variables: a and b, which is significantly influencing my response variable: c. All three are continuous numeric variables.  For detail c is the rate in change my response variable, b is the rate of change in my predictor and a is mean annual rainfall. The unit of analysis is pixels in a raster. So my model is telling me mean annual rainfall modifies how my predictor affects my response.

To visualise this interaction I would like to use a contour plot/heat map/level plot with a and b on the x and y axes and c providing the colour to show me how my response variable changes within the space described by a and b.  I can do this with a scatter plot but its not very pretty or easy to interpret:

```<code>qplot(b, a, colour = c) +
  scale_colour_gradient(low="green", high="red") +
</code>```

When I try to plot a contour plot/heat map/level plot though all I get is errors, blank plots or ugly plots.

geom_contour gives me an error:

```<code>ggplot(data = Mod, aes(x = Rain, y = Bomas, z = Fire)) +
  geom_contour()

Warning message:
Not possible to generate contour data
</code>```

geom_raster initially gives me Error: cannot allocate vector of size 81567.2 Gb but when I round my data it produces:

```<code>ggplot(data = df, aes(x = a, y = b, z = c)) +
  geom_raster(aes(fill = c))
</code>```

Adding interpolate = TRUE to the geom_raster code just makes the lines a little blurry.

geom_tile produces a blank graph but with a scale bar for c:

```<code>ggplot(data = df, aes(x = a, y = b, z = c)) +
  geom_tile(aes(color = c))
</code>```

I've also tried using stat_density2d and setting the fill and/or the colour to c, but just got an error, and I've tried using levelplot in the lattice package as well but that produces this:

```<code>levelplot(c ~ a * b, data = df,
          aspect = "asp", contour = TRUE,
          xlab = "a",
          ylab = "b")
</code>```

I suspect the problems I'm encountering are because the functions are not set up to deal with continuous x and y variables, all the examples seem to use factors.  I would have thought I could compensate for that by changing bin widths but that doesn't seem to work either. Is there a function that allows you to make a heat map with 3 continuous variables?  Or do I need to treat my a and b variables as factors and manually make a dataframe with bins appropriate for my data?

If you want to experiment for yourself then you get similar problems to what I'm having with:

```<code>df<- as.data.frame(rnorm(1:1068))
df[,2] <- rnorm(1:1068)
df[,3] <- rnorm(1:1068)
names(df) <- c("a", "b", "c")
</code>```

答:
You can get automatic bins, and for example calculate the means by using stat_summary_2d:

```<code>ggplot(df, aes(a, b, z = c)) +
  stat_summary_2d() +
  geom_point(shape = 1, col = 'white') +
  viridis::scale_fill_viridis()
</code>```

Another good option is to slice your data by the third variable, and plot small multiples. This doesn't really show very well for random data though:

```<code>library(ggplot2)
ggplot(df, aes(a, b)) +
  geom_point() +
  facet_wrap(~cut_number(c, 4))
</code>```

Body:
I have a model which has told me there is an interaction between two variables: a and b, which is significantly influencing my response variable: c. All three are continuous numeric variables.  For detail c is the rate in change my response variable, b is the rate of change in my predictor and a is mean annual rainfall. The unit of analysis is pixels in a raster. So my model is telling me mean annual rainfall modifies how my predictor affects my response.

To visualise this interaction I would like to use a contour plot/heat map/level plot with a and b on the x and y axes and c providing the colour to show me how my response variable changes within the space described by a and b.  I can do this with a scatter plot but its not very pretty or easy to interpret:

qplot(b, a, colour = c) +
  scale_colour_gradient(low="green", high="red") +

When I try to plot a contour plot/heat map/level plot though all I get is errors, blank plots or ugly plots.

geom_contour gives me an error:

ggplot(data = Mod, aes(x = Rain, y = Bomas, z = Fire)) +
  geom_contour()

Warning message:
Not possible to generate contour data

geom_raster initially gives me Error: cannot allocate vector of size 81567.2 Gb but when I round my data it produces:

ggplot(data = df, aes(x = a, y = b, z = c)) +
  geom_raster(aes(fill = c))

Adding interpolate = TRUE to the geom_raster code just makes the lines a little blurry.

geom_tile produces a blank graph but with a scale bar for c:

ggplot(data = df, aes(x = a, y = b, z = c)) +
  geom_tile(aes(color = c))

I've also tried using stat_density2d and setting the fill and/or the colour to c, but just got an error, and I've tried using levelplot in the lattice package as well but that produces this:

levelplot(c ~ a * b, data = df,
          aspect = "asp", contour = TRUE,
          xlab = "a",
          ylab = "b")

I suspect the problems I'm encountering are because the functions are not set up to deal with continuous x and y variables, all the examples seem to use factors.  I would have thought I could compensate for that by changing bin widths but that doesn't seem to work either. Is there a function that allows you to make a heat map with 3 continuous variables?  Or do I need to treat my a and b variables as factors and manually make a dataframe with bins appropriate for my data?

If you want to experiment for yourself then you get similar problems to what I'm having with:

df<- as.data.frame(rnorm(1:1068))
df[,2] <- rnorm(1:1068)
df[,3] <- rnorm(1:1068)
names(df) <- c("a", "b", "c")

Body:
You can get automatic bins, and for example calculate the means by using stat_summary_2d:

ggplot(df, aes(a, b, z = c)) +
  stat_summary_2d() +
  geom_point(shape = 1, col = 'white') +
  viridis::scale_fill_viridis()

Another good option is to slice your data by the third variable, and plot small multiples. This doesn't really show very well for random data though:

library(ggplot2)
ggplot(df, aes(a, b)) +
  geom_point() +
  facet_wrap(~cut_number(c, 4))


问:
Is there a way to implement a trait on top of another trait?
I am trying to create a base trait that will implement other operator traits (Add, Subtract, Multiply, Divide, etc...) for me.

This fails to compile, it looks like an issued with Sized, but even when Measurement is set to require Sized it does not work. Is this even possible?

```<code>use std::ops::Add;

#[derive(Copy, Clone, Debug)]
struct Unit {
    value: f64,
}

impl Unit {
    fn new(value: f64) -> Unit {
        Unit { value: value }
    }
}

trait Measurement: Sized {
    fn get_value(&self) -> f64;
    fn from_value(value: f64) -> Self;
}

impl Measurement for Unit {
    fn get_value(&self) -> f64 {
        self.value
    }
    fn from_value(value: f64) -> Self {
        Unit::new(value)
    }
}

// This explicit implementation works
/*
impl Add for Unit {
    type Output = Unit;

    fn add(self, rhs: Unit) -> Unit {
        let a = self.get_value();
        let b = rhs.get_value();
        Unit::from_value(a + b)
    }
}
*/

// This trait implementation does not
impl Add for Measurement {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        let a = self.get_value();
        let b = rhs.get_value();
        Self::from_value(a + b)
    }
}

fn main() {
    let a = Unit::new(1.5);
    let b = Unit::new(2.0);
    let c = a + b;

    println!("{}", c.get_value());
}
</code>```

(playground)

error[E0277]: the trait bound `Measurement + 'static: std::marker::Sized` is not satisfied
  --> src/main.rs:42:6
   |
42 | impl Add for Measurement {
   |      ^^^ `Measurement + 'static` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `Measurement + 'static`

error[E0038]: the trait `Measurement` cannot be made into an object
  --> src/main.rs:42:6
   |
42 | impl Add for Measurement {
   |      ^^^ the trait `Measurement` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

error[E0038]: the trait `Measurement` cannot be made into an object
  --> src/main.rs:43:5
   |
43 |     type Output = Self;
   |     ^^^^^^^^^^^^^^^^^^^ the trait `Measurement` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

error[E0038]: the trait `Measurement` cannot be made into an object
  --> src/main.rs:45:5
   |
45 |     fn add(self, rhs: Self) -> Self {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Measurement` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`
```

答:
Here's a working version with macros, as suggested:</p>

```<code>use std::ops::Add;

#[derive(Copy, Clone, Debug)]
struct Unit {
    value: f64,
}

impl Unit {
    fn new(value: f64) -> Unit {
        Unit { value: value }
    }
}

trait Measurement: Sized {
    fn get_value(&self) -> f64;
    fn from_value(value: f64) -> Self;
}

impl Measurement for Unit {
    fn get_value(&self) -> f64 {
        self.value
    }
    fn from_value(value: f64) -> Self {
        Unit::new(value)
    }
}

macro_rules! add_impl {
    ($($t:ty)*) => ($(
        impl Add for $t {
            type Output = $t;

            fn add(self, other: $t) -> $t {
                let a = self.get_value();
                let b = other.get_value();
                let r = a + b;
                Self::from_value(r)
            }
        }
    )*)
}

add_impl! { Unit }

fn main() {
    let a = Unit::new(1.5);
    let b = Unit::new(2.0);
    let c = a + b;

    println!("{}", c.get_value());
}
</code>```

Body:
I am trying to create a base trait that will implement other operator traits (Add, Subtract, Multiply, Divide, etc...) for me.

This fails to compile, it looks like an issued with Sized, but even when Measurement is set to require Sized it does not work. Is this even possible?

use std::ops::Add;

#[derive(Copy, Clone, Debug)]
struct Unit {
    value: f64,
}

impl Unit {
    fn new(value: f64) -> Unit {
        Unit { value: value }
    }
}

trait Measurement: Sized {
    fn get_value(&self) -> f64;
    fn from_value(value: f64) -> Self;
}

impl Measurement for Unit {
    fn get_value(&self) -> f64 {
        self.value
    }
    fn from_value(value: f64) -> Self {
        Unit::new(value)
    }
}

// This explicit implementation works
/*
impl Add for Unit {
    type Output = Unit;

    fn add(self, rhs: Unit) -> Unit {
        let a = self.get_value();
        let b = rhs.get_value();
        Unit::from_value(a + b)
    }
}
*/

// This trait implementation does not
impl Add for Measurement {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        let a = self.get_value();
        let b = rhs.get_value();
        Self::from_value(a + b)
    }
}

fn main() {
    let a = Unit::new(1.5);
    let b = Unit::new(2.0);
    let c = a + b;

    println!("{}", c.get_value());
}

(playground)

error[E0277]: the trait bound `Measurement + 'static: std::marker::Sized` is not satisfied
  --> src/main.rs:42:6
   |
42 | impl Add for Measurement {
   |      ^^^ `Measurement + 'static` does not have a constant size known at compile-time
   |
   = help: the trait `std::marker::Sized` is not implemented for `Measurement + 'static`

error[E0038]: the trait `Measurement` cannot be made into an object
  --> src/main.rs:42:6
   |
42 | impl Add for Measurement {
   |      ^^^ the trait `Measurement` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

error[E0038]: the trait `Measurement` cannot be made into an object
  --> src/main.rs:43:5
   |
43 |     type Output = Self;
   |     ^^^^^^^^^^^^^^^^^^^ the trait `Measurement` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

error[E0038]: the trait `Measurement` cannot be made into an object
  --> src/main.rs:45:5
   |
45 |     fn add(self, rhs: Self) -> Self {
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Measurement` cannot be made into an object
   |
   = note: the trait cannot require that `Self : Sized`

Body:
Here's a working version with macros, as suggested:

use std::ops::Add;

#[derive(Copy, Clone, Debug)]
struct Unit {
    value: f64,
}

impl Unit {
    fn new(value: f64) -> Unit {
        Unit { value: value }
    }
}

trait Measurement: Sized {
    fn get_value(&self) -> f64;
    fn from_value(value: f64) -> Self;
}

impl Measurement for Unit {
    fn get_value(&self) -> f64 {
        self.value
    }
    fn from_value(value: f64) -> Self {
        Unit::new(value)
    }
}

macro_rules! add_impl {
    ($($t:ty)*) => ($(
        impl Add for $t {
            type Output = $t;

            fn add(self, other: $t) -> $t {
                let a = self.get_value();
                let b = other.get_value();
                let r = a + b;
                Self::from_value(r)
            }
        }
    )*)
}

add_impl! { Unit }

fn main() {
    let a = Unit::new(1.5);
    let b = Unit::new(2.0);
    let c = a + b;

    println!("{}", c.get_value());
}


问:
Why not always build a release with debug info?
If debug information is stored in a program database (not as part of an executable), is there any reason not to always build with it (e.g., MSVC's /Zi)?

In CMake, the default configurations are, "Release", "Debug", "RelWithDebInfo", and "MinSizeRel". Is there a reason not to only use "Debug" and "RelWithDebInfo" (perhaps renamed to "Release")?

Does it have any impacts on the size or performance of the code? Is the answer different for gcc or clang than it is for Visual C++?

Update

I did come across these posts that are similar:

Anything wrong with releasing software in debug mode?

Debug vs. RelWithDebInfo

However, neither of these get to the question of Release vs. RelWithDebInfo.

Yes. I could do a test on an executable with Release vs. RelWithDebInfo. That would definitely give me the answer about the size of the code, but would be very difficult to conclude that it has NO impact on performance if my test case showed similar performance. How would I know if I exercised aspects of the language that might be impacted by the change? That is, empirical testing could produce a false negative.

答:
Releasing with debug info is mandatory for real-life development. When shit happens your primary tool would be a crash dump analysis that would be rather pointless without debug information. Note that this does not imply shipping debug info with product.

As for "little differences" between vc++ and gcc I would like to mention that by default vc++ emits debug information in a separate file while gcc will squeeze it into executable. It is possible to separate debug information on gcc as well, however doing so is not as convenient and requires some extra steps.


问:
Deprecated function: require_once()
Recently, I started converting my Drupal 6 module on PHP 5.2.x to Drupal 7 on PHP 5.3.x, and now I get following warning

Deprecated function: Assigning the
  return value of new by reference is
  deprecated in require_once() (line
  27 of
  C:\Users\ajinkya\Desktop\xampp\php\PEAR\SOAP\WSDL.php).

Line 27 of WSDL.php is : require_once 'HTTP/Request.php';

I am not able to figure out what is the cause of this warning.  Has the behavior of require_once() changed in PHP 5.3.x?

file.inc in Drupal 7 has a line : require_once DRUPAL_ROOT . '/includes/stream_wrappers.inc; and it does not throw any warning. Why?

If I put error_reporting(E_ALL & ~E_DEPRECATED); in a setting.php of Drupal 7, the warning goes away. Is it good to suppress a warning like that?

答: I don't see anything on the PHP site indicating that require_once is deprecated. Perhaps something inside of HTTP/Request.php is deprecated instead? This is a pretty odd warning.

Title: Deprecated function: require_once()


问:
utf8mb4 character set for Rails application
I am using MySQL version 5.7.12; I am trying to add emoji support in a text field. I found this article. It states to alter the table and column to enable utf8mb4, which supports true unicode, including 4 byte unicode characters. I have a table comments and text field content, so I perform the following operation:

```<code>class ConvertCommentsToUtf8mb4 < ActiveRecord::Migration
  def change
    # for each table that will store unicode execute:
    execute "ALTER TABLE comments CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"
    # for each string/text column with unicode content execute:
    execute "ALTER TABLE comments CHANGE content TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"
  end
end
</code>```

When I try to run a migration, I get the following error:

Mysql2::Error: You have an error in your SQL syntax; check the manual
  that corresponds to your MySQL server version for the right syntax to
  use near 'SET utf8mb4 COLLATE utf8mb4_bin' at line 1: ALTER TABLE
  comments CHANGE content TEXT CHARACTER SET utf8mb4 COLLATE
  utf8mb4_bin/Users/myuser/.rvm/gems/ruby-2.1.2@core/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in
  `_query'

What might I be doing wrong?

答:
When you use ALTER TABLE...CHANGE you need to give the column name twice, because CHANGE allows you to change the column name.

```<code>ALTER TABLE comments CHANGE content TEXT CHARACTER SET ...
</code>```

In this case, it thought you were changing the column name to TEXT, with data type CHARACTER (which is a legit data type, it's a synonym for CHAR(1)), and then it got confused when it found the word SET.

So you can fix it in either of two ways:

```<code>ALTER TABLE comments CHANGE content content TEXT CHARACTER SET ...

ALTER TABLE comments MODIFY content TEXT CHARACTER SET ...
</code>```

MODIFY is just like CHANGE but can't change the name of the column, so you don't need to spell out the column name twice.

That's the explanation for the syntax error, but FWIW you don't need to modify your text column after using CONVERT TO CHARACTER SET for the whole table. MySQL automatically changes the character set and collation for all string columns in the table.

Demo:

```<code>mysql> create table comments ( content text ) character set utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> alter table comments convert to character set utf8mb4;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> insert into comments set content = 0xF09F92A9;
Query OK, 1 row affected (0.01 sec)

mysql> select * from comments;
+---------+
| content |
+---------+
|         |
+---------+
</code>```

Body:
I am using MySQL version 5.7.12; I am trying to add emoji support in a text field. I found this article. It states to alter the table and column to enable utf8mb4, which supports true unicode, including 4 byte unicode characters. I have a table comments and text field content, so I perform the following operation:

class ConvertCommentsToUtf8mb4 < ActiveRecord::Migration
  def change
    # for each table that will store unicode execute:
    execute "ALTER TABLE comments CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"
    # for each string/text column with unicode content execute:
    execute "ALTER TABLE comments CHANGE content TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"
  end
end

When I try to run a migration, I get the following error:

Mysql2::Error: You have an error in your SQL syntax; check the manual
  that corresponds to your MySQL server version for the right syntax to
  use near 'SET utf8mb4 COLLATE utf8mb4_bin' at line 1: ALTER TABLE
  comments CHANGE content TEXT CHARACTER SET utf8mb4 COLLATE
  utf8mb4_bin/Users/myuser/.rvm/gems/ruby-2.1.2@core/gems/mysql2-0.3.21/lib/mysql2/client.rb:80:in
  `_query'

What might I be doing wrong?

Body:
When you use ALTER TABLE...CHANGE you need to give the column name twice, because CHANGE allows you to change the column name.

ALTER TABLE comments CHANGE content TEXT CHARACTER SET ...

In this case, it thought you were changing the column name to TEXT, with data type CHARACTER (which is a legit data type, it's a synonym for CHAR(1)), and then it got confused when it found the word SET.

So you can fix it in either of two ways:

ALTER TABLE comments CHANGE content content TEXT CHARACTER SET ...

ALTER TABLE comments MODIFY content TEXT CHARACTER SET ...

MODIFY is just like CHANGE but can't change the name of the column, so you don't need to spell out the column name twice.

That's the explanation for the syntax error, but FWIW you don't need to modify your text column after using CONVERT TO CHARACTER SET for the whole table. MySQL automatically changes the character set and collation for all string columns in the table.

Demo:

mysql> create table comments ( content text ) character set utf8;
Query OK, 0 rows affected (0.03 sec)

mysql> alter table comments convert to character set utf8mb4;
Query OK, 0 rows affected (0.03 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> insert into comments set content = 0xF09F92A9;
Query OK, 1 row affected (0.01 sec)

mysql> select * from comments;
+---------+
| content |
+---------+
|         |
+---------+


问:
Quantmod getSymbols error
I'm trying to get symbol data with quantmod using this code.

```<code>    getSymbols(c("^DJI"),src='yahoo',from='2014-11-24',to='2017-11-24')
</code>```

And I get the error

```<code>    Error in 'colnames<-'('*tmp(', value = c("DJI.open", "DJI.High", "DJI.Low", :
    length of 'dimnames' [2] not equal to array extent
</code>```

Thanks for any help.

Edit: I get the same error with normal tickers.

```<code>    getSymbols(c("DWDP","AAPL","MCD","MRK","IBM","MMM","KO","DIS","CSCO","PG","TRV","UTX","HD","PFE","MSFT","VZ","GS","WMT","GE","INTC","BA","JPM","AXP","XOM","NKE","CAT","CVX","JNJ","UNH","V"),src='yahoo',from='2014-11-24',to='2017-11-24')
</code>```

答:
Without the c. Just do

```<code>getSymbols('^DJI', src = 'yahoo', from = '2014-11-24', to = '2017-11-24')
</code>```

Reply to Edit:

Maybe your package and/or R is outdated. I ran your exact code

getSymbols(c("DWDP","AAPL","MCD","MRK","IBM","MMM","KO","DIS","CSCO","PG","TRV","UTX","HD","PFE","MSFT","VZ","GS","WMT","GE","INTC","BA","JPM","AXP","XOM","NKE","CAT","CVX","JNJ","UNH","V"),src='yahoo',from='2014-11-24',to='2017-11-24')

and was able to get all the prices.

Title: Quantmod getSymbols error

Body:
I'm trying to get symbol data with quantmod using this code.

    getSymbols(c("^DJI"),src='yahoo',from='2014-11-24',to='2017-11-24')

And I get the error

    Error in 'colnames<-'('*tmp(', value = c("DJI.open", "DJI.High", "DJI.Low", :
    length of 'dimnames' [2] not equal to array extent

Thanks for any help.

Edit: I get the same error with normal tickers.

    getSymbols(c("DWDP","AAPL","MCD","MRK","IBM","MMM","KO","DIS","CSCO","PG","TRV","UTX","HD","PFE","MSFT","VZ","GS","WMT","GE","INTC","BA","JPM","AXP","XOM","NKE","CAT","CVX","JNJ","UNH","V"),src='yahoo',from='2014-11-24',to='2017-11-24')

Body:
Without the c. Just do

getSymbols('^DJI', src = 'yahoo', from = '2014-11-24', to = '2017-11-24')

Reply to Edit:

Maybe your package and/or R is outdated. I ran your exact code

getSymbols(c("DWDP","AAPL","MCD","MRK","IBM","MMM","KO","DIS","CSCO","PG","TRV","UTX","HD","PFE","MSFT","VZ","GS","WMT","GE","INTC","BA","JPM","AXP","XOM","NKE","CAT","CVX","JNJ","UNH","V"),src='yahoo',from='2014-11-24',to='2017-11-24')

and was able to get all the prices.


问:
How do I insert data with Room and RxJava?
```<code>db.activitiesDao().insertStep(step);
</code>```

This returns the infamous error:

```<code>java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
</code>```

I am kind new to RxJava and don't want to use AsyncTask.

答:
Try something like this.

```<code>Observable.fromCallable(() -> db.activitiesDao().insertStep(step))
        .subscribeOn(Schedulers.io())
        .subscribe(...);
</code>```

Or if there is void return you can do:

```<code>Completable.fromRunnable(new Runnable(){
        db.activitiesDao().insertStep(step)
    })
    .subscribeOn(Schedulers.io())
    .subscribe(...);
</code>```

Body:
db.activitiesDao().insertStep(step);

This returns the infamous error:

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

I am kind new to RxJava and don't want to use AsyncTask.

Body:
Try something like this.

Observable.fromCallable(() -> db.activitiesDao().insertStep(step))
        .subscribeOn(Schedulers.io())
        .subscribe(...);

Or if there is void return you can do:

Completable.fromRunnable(new Runnable(){
        db.activitiesDao().insertStep(step)
    })
    .subscribeOn(Schedulers.io())
    .subscribe(...);


问:
Getting aggregate from Pandas for other categories
I am trying to perform an aggregate calculation, but I want the calculation to apply to every other category.

So,

```<code> df.groupby(['index']).agg({data : [func1,func2]})
</code>```

Will perform the aggregate calculations func1 and func2 on the data grouped by index, but I want to perform the calculations on all the data that isn't in the index.

For example:

```<code>index data
A      1
A      2
A      1
B      2
B      2
B      4
B      4
C      1
C      3
D      4
D      1
</code>```

I would want the results for A to be performed on the data in B,C,D.

Is there a novel way to accomplish this?

答:
Well, I actually think I figured this out. Basically, I created a new dataframe and re-index'd it.

```<code>                value
original_index
A                  44
A                  65
A                  88
B                  69
B                  11
B                  52
C                  56
C                  42
C                  85
D                  66
D                  77
D                   9
</code>```

Loop through each index and and copy everything not in that index to a new dataframe. Then concat them all together.

```<code>l = []
for i in df.index.unique():
    d = df[~df.index.isin([i])].copy()
    d['new_index'] = i
    d.drop('original_index',axis=0,inplace=True)
    d.set_index('new_index',inplace=True)
    l.append(d)
df2 = pd.concat(l,axis=0)
</code>```

Ouput:

```<code>           value
new_index
A             69
A             11
A             52
A             56
A             42
A             85
A             66
A             77
A              9
B             44
B             65
B             88
B             56
B             42
B             85
B             66
B             77
B              9
C             44
C             65
C             88
C             69
C             11
C             52
C             66
C             77
C              9
D             44
D             65
D             88
D             69
D             11
D             52
D             56
D             42
D             85
</code>```

Now we can apply our groupby function on the new index and it will return results from values that were originally not in the index.

```<code>group_df = df2.groupby(['new_index']).agg({'value' :[func1,func2]})[['value']]
</code>```

It works, but I'm sure there must be a better way.

Body:
I am trying to perform an aggregate calculation, but I want the calculation to apply to every other category.

So,

 df.groupby(['index']).agg({data : [func1,func2]})

Will perform the aggregate calculations func1 and func2 on the data grouped by index, but I want to perform the calculations on all the data that isn't in the index.

For example:

index data
A      1
A      2
A      1
B      2
B      2
B      4
B      4
C      1
C      3
D      4
D      1

I would want the results for A to be performed on the data in B,C,D.

Is there a novel way to accomplish this?

Body:
Well, I actually think I figured this out. Basically, I created a new dataframe and re-index'd it.

                value
original_index
A                  44
A                  65
A                  88
B                  69
B                  11
B                  52
C                  56
C                  42
C                  85
D                  66
D                  77
D                   9

Loop through each index and and copy everything not in that index to a new dataframe. Then concat them all together.

l = []
for i in df.index.unique():
    d = df[~df.index.isin([i])].copy()
    d['new_index'] = i
    d.drop('original_index',axis=0,inplace=True)
    d.set_index('new_index',inplace=True)
    l.append(d)
df2 = pd.concat(l,axis=0)

Ouput:

           value
new_index
A             69
A             11
A             52
A             56
A             42
A             85
A             66
A             77
A              9
B             44
B             65
B             88
B             56
B             42
B             85
B             66
B             77
B              9
C             44
C             65
C             88
C             69
C             11
C             52
C             66
C             77
C              9
D             44
D             65
D             88
D             69
D             11
D             52
D             56
D             42
D             85

Now we can apply our groupby function on the new index and it will return results from values that were originally not in the index.

group_df = df2.groupby(['new_index']).agg({'value' :[func1,func2]})[['value']]

It works, but I'm sure there must be a better way.


问:
Background does not show properly
For my Sign In form I have added buttons Sign In with facebook and google.

Basically, copy/pasted from codepen.
HTML:

```<code><button class="loginBtn loginBtn--facebook">   Login with Facebook </button>

<button class="loginBtn loginBtn--google">   Login with Google </button>
</code>```

CSS:

```<code>body { padding: 2em; }

/* Shared */
.loginBtn {
  box-sizing: border-box;
  position: relative;
  /* width: 13em;  - apply for fixed size */
  margin: 0.2em;
  padding: 0 15px 0 46px;
  border: none;
  text-align: left;
  line-height: 34px;
  white-space: nowrap;
  border-radius: 0.2em;
  font-size: 16px;
  color: #FFF;
}
.loginBtn:before {
  content: "";
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  width: 34px;
  height: 100%;
}
.loginBtn:focus {
  outline: none;
}
.loginBtn:active {
  box-shadow: inset 0 0 0 32px rgba(0,0,0,0.1);
}

/* Facebook */
.loginBtn--facebook {
  background-color: #4C69BA;
  background-image: linear-gradient(#4C69BA, #3B55A0);
  /*font-family: "Helvetica neue", Helvetica Neue, Helvetica, Arial, sans-serif;*/
  text-shadow: 0 -1px 0 #354C8C;
}
.loginBtn--facebook:before {
  border-right: #364e92 1px solid;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_facebook.png') 6px 6px no-repeat;
}
.loginBtn--facebook:hover,
.loginBtn--facebook:focus {
  background-color: #5B7BD5;
  background-image: linear-gradient(#5B7BD5, #4864B1);
}

/* Google */
.loginBtn--google {
  /*font-family: "Roboto", Roboto, arial, sans-serif;*/
  background: #DD4B39;
}
.loginBtn--google:before {
  border-right: #BB3F30 1px solid;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_google.png') 6px 6px no-repeat;
}
.loginBtn--google:hover,
.loginBtn--google:focus {
  background: #E74B37;
}
</code>```

Using the same code above I decided to add Twitter button as well. I changed the color etc., however when I change background to the TWITTER logo, I does not show on the page and I can't understand why. My code for twitter button:
HTML

```<code><button class="loginBtn loginBtn--twitter"><%= link_to "Sign in with Twitter", sign_in_with_twitter_path, class: 'text-light' %></button>
</code>```

CSS:

```<code>    /* Twitter */
.loginBtn--twitter {
  background-color: #53ADE9;
  background-image: linear-gradient(#53ADE9, #53ADE9);
  text-shadow: 0 -1px 0 #53ADE9;
}
.loginBtn--twitter:before {
  border-right: #3a90c9 1px solid;
  background: url('http://p10cdn4static.sharpschool.com/UserFiles/Servers/Server_208743/Image/twitter2.png') 6px 6px no-repeat;
}
.loginBtn--twitter:hover,
.loginBtn--twitter:focus {
  background-color: #70bcef;
  background-image: linear-gradient(#70bcef, #70bcef);
}
</code>```

Why background property with my URL does not apply?

答:
Your twitter picture is big. really big.

Check my example here - https://jsfiddle.net/ta0emnmh/

Your twitter style should be like this:

```<code>.loginBtn--twitter:before {
    border-right: #3a90c9 1px solid;
    background: url(http://p10cdn4static.sharpschool.com/UserFiles/Servers/Server_208743/Image/twitter2.png) 1px 4px no-repeat;
    background-size: contain;
}
</code>```

Title: Background does not show properly

Body:
For my Sign In form I have added buttons Sign In with facebook and google.

Basically, copy/pasted from codepen.
HTML:

<button class="loginBtn loginBtn--facebook">   Login with Facebook </button>

<button class="loginBtn loginBtn--google">   Login with Google </button>

CSS:

body { padding: 2em; }

/* Shared */
.loginBtn {
  box-sizing: border-box;
  position: relative;
  /* width: 13em;  - apply for fixed size */
  margin: 0.2em;
  padding: 0 15px 0 46px;
  border: none;
  text-align: left;
  line-height: 34px;
  white-space: nowrap;
  border-radius: 0.2em;
  font-size: 16px;
  color: #FFF;
}
.loginBtn:before {
  content: "";
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  width: 34px;
  height: 100%;
}
.loginBtn:focus {
  outline: none;
}
.loginBtn:active {
  box-shadow: inset 0 0 0 32px rgba(0,0,0,0.1);
}

/* Facebook */
.loginBtn--facebook {
  background-color: #4C69BA;
  background-image: linear-gradient(#4C69BA, #3B55A0);
  /*font-family: "Helvetica neue", Helvetica Neue, Helvetica, Arial, sans-serif;*/
  text-shadow: 0 -1px 0 #354C8C;
}
.loginBtn--facebook:before {
  border-right: #364e92 1px solid;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_facebook.png') 6px 6px no-repeat;
}
.loginBtn--facebook:hover,
.loginBtn--facebook:focus {
  background-color: #5B7BD5;
  background-image: linear-gradient(#5B7BD5, #4864B1);
}

/* Google */
.loginBtn--google {
  /*font-family: "Roboto", Roboto, arial, sans-serif;*/
  background: #DD4B39;
}
.loginBtn--google:before {
  border-right: #BB3F30 1px solid;
  background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/14082/icon_google.png') 6px 6px no-repeat;
}
.loginBtn--google:hover,
.loginBtn--google:focus {
  background: #E74B37;
}

Using the same code above I decided to add Twitter button as well. I changed the color etc., however when I change background to the TWITTER logo, I does not show on the page and I can't understand why. My code for twitter button:
HTML

<button class="loginBtn loginBtn--twitter"><%= link_to "Sign in with Twitter", sign_in_with_twitter_path, class: 'text-light' %></button>

CSS:

    /* Twitter */
.loginBtn--twitter {
  background-color: #53ADE9;
  background-image: linear-gradient(#53ADE9, #53ADE9);
  text-shadow: 0 -1px 0 #53ADE9;
}
.loginBtn--twitter:before {
  border-right: #3a90c9 1px solid;
  background: url('http://p10cdn4static.sharpschool.com/UserFiles/Servers/Server_208743/Image/twitter2.png') 6px 6px no-repeat;
}
.loginBtn--twitter:hover,
.loginBtn--twitter:focus {
  background-color: #70bcef;
  background-image: linear-gradient(#70bcef, #70bcef);
}

Why background property with my URL does not apply?

Body:
Your twitter picture is big. really big.

Check my example here - https://jsfiddle.net/ta0emnmh/

Your twitter style should be like this:

.loginBtn--twitter:before {
    border-right: #3a90c9 1px solid;
    background: url(http://p10cdn4static.sharpschool.com/UserFiles/Servers/Server_208743/Image/twitter2.png) 1px 4px no-repeat;
    background-size: contain;
}


问:
Numpy value error - the truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
Edit: Question updated - I should have asked:

Why is this:

```<code>new_x = x[(0<x<10) & (20<x<40)]
</code>```

giving me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"?

The original question I posted did not reflect the problem I was having (apologies - my actual conditions are more complicated and I had oversimplified it). Original question below:

I have a numpy array x and I want to create a new array of x elements
  satisfying x>0 and x<10. I have tried all the following:

```<code>new_x = x[(x>0) and (x<10)]

new_x = x[(x>0) & (x<10)]

new_x = x[np.logical_and(x>0, x<10)]

new_x = x[np.where(x>0, x<10)]

new_x = x[np.all(x>0, x<10)]

new_x = x[np.all((x>0) and (x<10))]

new_x = x[np.all(x>0) and np.all(x<10)]

new_x = x[np.any(x>0, x<10)]
</code>```

and they all give the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have ran out of ideas. I realise this may be a duplicate question
  but I have consulted
  this
  and
  this
  and many others which did not help as I keep getting the same value
  error.

Edit: Fixed typo (x<0 and x>10) --> (x>0 and x<10)

答: The issue was that I was using conditions like x[(0<x<10) & (20<x<40)] (I should have guessed from the error message "more than one element") and it is solved by using separating statements i.e. x[(0<x) & (x<10) & (20<x) & (x<40)].

Body:
Edit: Question updated - I should have asked:

Why is this:

new_x = x[(0<x<10) & (20<x<40)]

giving me "ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"?

The original question I posted did not reflect the problem I was having (apologies - my actual conditions are more complicated and I had oversimplified it). Original question below:

I have a numpy array x and I want to create a new array of x elements
  satisfying x>0 and x<10. I have tried all the following:

new_x = x[(x>0) and (x<10)]

new_x = x[(x>0) & (x<10)]

new_x = x[np.logical_and(x>0, x<10)]

new_x = x[np.where(x>0, x<10)]

new_x = x[np.all(x>0, x<10)]

new_x = x[np.all((x>0) and (x<10))]

new_x = x[np.all(x>0) and np.all(x<10)]

new_x = x[np.any(x>0, x<10)]

and they all give the following error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I have ran out of ideas. I realise this may be a duplicate question
  but I have consulted
  this
  and
  this
  and many others which did not help as I keep getting the same value
  error.

Edit: Fixed typo (x<0 and x>10) --> (x>0 and x<10)


问:
Spring Boot tomcat basedir completely empty
In my application.yml I set

```<code>server:
  tomcat:
    basedir: /home/user/TOMCAT
</code>```

when I run the application with mvn spring-boot:run I see that the folder is created and it has this structure

/TOMCAT/work/Tomcat/localhost/ROOT

and it is completely empty.

I was expecting to find here a webapps folder and so on. It may sound stupid but, where are all tomcat-related files?

答: Your tomcat related files are in you spring-boot jar. The directory from which that jar is executed is treated as "catalina.home", while the "basedir" is treated as "catalina.base". The basedir may contain any type of "work" that your application will do that might require writing to disk, such as buffering large files or acting as the relative location for local application logs.</p>

Body:
In my application.yml I set

server:
  tomcat:
    basedir: /home/user/TOMCAT

when I run the application with mvn spring-boot:run I see that the folder is created and it has this structure

/TOMCAT/work/Tomcat/localhost/ROOT

and it is completely empty.

I was expecting to find here a webapps folder and so on. It may sound stupid but, where are all tomcat-related files?


问:
Entry widget won't clear upon function
I'm trying to get the Entry to widget to clear (clearTextBox()) but also run newQuote(). since I added the second bind it won't clear out. Any ideas?</p>

```<code>from random import *
from tkinter import *

def clearTextBox(event):
    textBox.delete(0, END)
    textBox.insert(0, "")

def newQuote(event):
    rightLabel.config(text=quotes[randint(0,10)])

textBox = Entry(leftFrame, width=60)
textBox.pack(ipady=10, side=LEFT)
textBox.bind("<Return>", clearTextBox)
textBox.bind("<Return>", newQuote)

root.mainloop()
</code>```

答:
Your second call to bind overwrites the first.

To fix this, you can add the keyword argument add="+", to call both functions:

```<code>textBox.bind("<Return>", newQuote, add="+")
</code>```

Title: Entry widget won't clear upon function

Body:
I'm trying to get the Entry to widget to clear (clearTextBox()) but also run newQuote(). since I added the second bind it won't clear out. Any ideas?

from random import *
from tkinter import *

def clearTextBox(event):
    textBox.delete(0, END)
    textBox.insert(0, "")

def newQuote(event):
    rightLabel.config(text=quotes[randint(0,10)])

textBox = Entry(leftFrame, width=60)
textBox.pack(ipady=10, side=LEFT)
textBox.bind("<Return>", clearTextBox)
textBox.bind("<Return>", newQuote)

root.mainloop()

Body:
Your second call to bind overwrites the first.

To fix this, you can add the keyword argument add="+", to call both functions:

textBox.bind("<Return>", newQuote, add="+")