问:
Jackson -- deserialize JavaFX StringProperty type field with custom deserializer
Let's say my POJO is limited to the following:

```<code>public class TestPojo {
    StringProperty myField;

    public TestPojo(){}

    public TestPojo(String myField) {
        this.myField = new SimpleStringProperty(myField);
    }

    public String getMyField() {
        return this.myField.get();
    }

    public StringProperty myFieldProperty() {
        return this.myField;
    }

    public void setMyField(String myField) {
        this.myField.set(myField);
    }
}
</code>```

I want to deserialize with Jackson. Jackson doesn't seem to like StringProperty, because as a normal String it works as expected. So I write a custom deserializer...

```<code>public class StringPropertyDeserializer extends JsonDeserializer<StringProperty> {

    public StringPropertyDeserializer() {}

    @Override
    public StringProperty deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        String value = jsonParser.readValueAs(String.class);
        return new SimpleStringProperty(value);
    }
}
</code>```

And I add this annotation to my StringProperty field...

```<code>@JsonDeserialize(using = StringPropertyDeserializer.class)
</code>```

I get the following error:

```<code>com.fasterxml.jackson.databind.JsonMappingException: Class com.test.example.TestPojo$StringPropertyDeserializer has no default (no arg) constructor
</code>```

I added a default constructor into the deserializer (as you can see above) and I get the same error regardless of it being there. Any solutions? This seems like it should be simple.

Edit here is the actual code where I'm making the call if that's helpful...

```<code>@GET("/api/test")
Call<List<TestPojo>> testPojoCall();
</code>```

And it's configured in Gradle like so:

```<code>compile group: 'com.squareup.retrofit2', name: 'converter-jackson', version: '2.1.0'
</code>```

That is everything related to this code.

答:
Your POJO implementation isn't correct: the no-arg constructor doesn't initialize the StringProperty. Consequently, if you use the no-arg constructor, then call setMyField(...) you'd get a null pointer exception. I'm guessing that trying to work around that was what led you to try creating the custom deserializer.

I'm not entirely sure why the custom deserializer is giving the error it's giving (maybe it doesn't like the fact that it's an inner class: that's just a guess).

The following works fine for me without any custom deserialization:

TestPojo.java:

```<code>package jxtest;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class TestPojo {

    private final StringProperty myField1 = new SimpleStringProperty();
    private final StringProperty myField2 = new SimpleStringProperty();
    private int myField3 ;

    public final StringProperty myField1Property() {
        return this.myField1;
    }

    public final String getMyField1() {
        return this.myField1Property().get();
    }

    public final void setMyField1(final String myField1) {
        this.myField1Property().set(myField1);
    }

    public final StringProperty myField2Property() {
        return this.myField2;
    }

    public final String getMyField2() {
        return this.myField2Property().get();
    }

    public final void setMyField2(final String myField2) {
        this.myField2Property().set(myField2);
    }

    public int getMyField3() {
        return myField3;
    }

    public void setMyField3(int myField3) {
        this.myField3 = myField3;
    }

}
</code>```

Test.java:

```<code>package jxtest;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    public static void main(String[] args) throws IOException {
        TestPojo item = new TestPojo();
        item.setMyField1("Test1");
        item.setMyField2("Test2");
        item.setMyField3(42);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(item);

        System.out.println(json);

        TestPojo readBackIn = mapper.readValue(json, TestPojo.class);
        System.out.println(readBackIn.getMyField1());
        System.out.println(readBackIn.getMyField2());
        System.out.println(readBackIn.getMyField3());
    }
}
</code>```

Output:

{"myField1":"Test1","myField2":"Test2","myField3":42}
Test1
Test2
42
```

Using jackson-databind 2.8.7.

Body:
Let's say my POJO is limited to the following:

public class TestPojo {
    StringProperty myField;

    public TestPojo(){}

    public TestPojo(String myField) {
        this.myField = new SimpleStringProperty(myField);
    }

    public String getMyField() {
        return this.myField.get();
    }

    public StringProperty myFieldProperty() {
        return this.myField;
    }

    public void setMyField(String myField) {
        this.myField.set(myField);
    }
}

I want to deserialize with Jackson. Jackson doesn't seem to like StringProperty, because as a normal String it works as expected. So I write a custom deserializer...

public class StringPropertyDeserializer extends JsonDeserializer<StringProperty> {

    public StringPropertyDeserializer() {}

    @Override
    public StringProperty deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException, JsonProcessingException {

        String value = jsonParser.readValueAs(String.class);
        return new SimpleStringProperty(value);
    }
}

And I add this annotation to my StringProperty field...

@JsonDeserialize(using = StringPropertyDeserializer.class)

I get the following error:

com.fasterxml.jackson.databind.JsonMappingException: Class com.test.example.TestPojo$StringPropertyDeserializer has no default (no arg) constructor

I added a default constructor into the deserializer (as you can see above) and I get the same error regardless of it being there. Any solutions? This seems like it should be simple.

Edit here is the actual code where I'm making the call if that's helpful...

@GET("/api/test")
Call<List<TestPojo>> testPojoCall();

And it's configured in Gradle like so:

compile group: 'com.squareup.retrofit2', name: 'converter-jackson', version: '2.1.0'

That is everything related to this code.

Body:
Your POJO implementation isn't correct: the no-arg constructor doesn't initialize the StringProperty. Consequently, if you use the no-arg constructor, then call setMyField(...) you'd get a null pointer exception. I'm guessing that trying to work around that was what led you to try creating the custom deserializer.

I'm not entirely sure why the custom deserializer is giving the error it's giving (maybe it doesn't like the fact that it's an inner class: that's just a guess).

The following works fine for me without any custom deserialization:

TestPojo.java:

package jxtest;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

public class TestPojo {

    private final StringProperty myField1 = new SimpleStringProperty();
    private final StringProperty myField2 = new SimpleStringProperty();
    private int myField3 ;

    public final StringProperty myField1Property() {
        return this.myField1;
    }

    public final String getMyField1() {
        return this.myField1Property().get();
    }

    public final void setMyField1(final String myField1) {
        this.myField1Property().set(myField1);
    }

    public final StringProperty myField2Property() {
        return this.myField2;
    }

    public final String getMyField2() {
        return this.myField2Property().get();
    }

    public final void setMyField2(final String myField2) {
        this.myField2Property().set(myField2);
    }

    public int getMyField3() {
        return myField3;
    }

    public void setMyField3(int myField3) {
        this.myField3 = myField3;
    }

}

Test.java:

package jxtest;

import java.io.IOException;

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    public static void main(String[] args) throws IOException {
        TestPojo item = new TestPojo();
        item.setMyField1("Test1");
        item.setMyField2("Test2");
        item.setMyField3(42);

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(item);

        System.out.println(json);

        TestPojo readBackIn = mapper.readValue(json, TestPojo.class);
        System.out.println(readBackIn.getMyField1());
        System.out.println(readBackIn.getMyField2());
        System.out.println(readBackIn.getMyField3());
    }
}

Output:

{"myField1":"Test1","myField2":"Test2","myField3":42}
Test1
Test2
42

Using jackson-databind 2.8.7.


来源: stackexchange

问:
Add User role in asp.net with database category
Sorry for my english i'm french.

Is possible to define role with database?

```<code>Class user
string name {get;set}
int cat {get; set}
</code>```

...

```<code>if (user.cat==1)
role= "Admin"
if (user.cat ==2)
role="members
</code>```

And after restricted access to a controler with

```<code>[Authorize( Role = "Admin")]
</code>```

Thanks!

答: if i understood it correctly, yes it's possible. check out this link - Extending ASP.NET Identity 2.0 Roles and Implementation of Role Based Authorization</p>

ContentLicense: CC BY-SA 3.0

Body:
Sorry for my english i'm french.

Is possible to define role with database?

Class user
string name {get;set}
int cat {get; set}

...

if (user.cat==1)
role= "Admin"
if (user.cat ==2)
role="members

And after restricted access to a controler with

[Authorize( Role = "Admin")]

Thanks!


问:
How to save Date Time without the time?
How would i save the date time, with no time or preferably with a time stamp of 12:00, no matter what the time is at that moment?

I dont want to use .ToString("dd/MM/yyyy");, because it will open up a whole lot of new  possible errors.

答:
DateTime struct has a Date property that should serve your needs:

```<code>DateTime dateOnly = dateTime.Date;
</code>```

Of course, it'll still inevitably contain a time part but you should be able to ignore it.

ContentLicense: CC BY-SA 2.5

Title: How to save Date Time without the time?

Body:
DateTime struct has a Date property that should serve your needs:

DateTime dateOnly = dateTime.Date;

Of course, it'll still inevitably contain a time part but you should be able to ignore it.


问:
How to get the topic-word probabilities of a given word in gensim LDA?
As I understand, if i'm training a LDA model over a corpus where the size of the dictionary is say 1000 and no of topics (K) = 10, for each word in the dictionary I should have a vector of size 10 where each position in the vector is the probability of that word belongs to that particular topic, right?

So my question is given a word, what is the probability of that word belongs to to topic k where k could be from 1 to 10, how do I get this value in the gensim lda model?

I was using get_term_topics method but it doesn't output all the probabilities for all the topics. For eg.,

```<code>lda_model1.get_term_topics("fun")
[(12, 0.047421702085626238)],
</code>```

but I want to see what is the prob that "fun" could be in all the other topics as well?

答:
For someone who is looking for the ans, i found it.

These prob values are in the xx.expElogbeta numpy array. Number of rows in this matrix is equivalent to the number of topics and the no of columns is the size of your dictionary (words). So if you get the values for a particular column, you get the prob of that word belonging to all the topics.

e.g.,

```<code>>>> data = np.load("model.expElogbeta.npy")
>>> data.shape
(20, 6481) # i have trained with 20 topics == no of rows
>>> dict = corpora.Dictionary.load(dictf)
>>> len(dict.keys())
6481 #columns of the npy array is the words in my dict
</code>```

src = https://groups.google.com/forum/?fromgroups=#!searchin/gensim/lda$20topic-word$20matrix/gensim/Qoj7Agkx3qE/r9lyfihC4b4J

Body:
As I understand, if i'm training a LDA model over a corpus where the size of the dictionary is say 1000 and no of topics (K) = 10, for each word in the dictionary I should have a vector of size 10 where each position in the vector is the probability of that word belongs to that particular topic, right?

So my question is given a word, what is the probability of that word belongs to to topic k where k could be from 1 to 10, how do I get this value in the gensim lda model?

I was using get_term_topics method but it doesn't output all the probabilities for all the topics. For eg.,

lda_model1.get_term_topics("fun")
[(12, 0.047421702085626238)],

but I want to see what is the prob that "fun" could be in all the other topics as well?

Body:
For someone who is looking for the ans, i found it.

These prob values are in the xx.expElogbeta numpy array. Number of rows in this matrix is equivalent to the number of topics and the no of columns is the size of your dictionary (words). So if you get the values for a particular column, you get the prob of that word belonging to all the topics.

e.g.,

>>> data = np.load("model.expElogbeta.npy")
>>> data.shape
(20, 6481) # i have trained with 20 topics == no of rows
>>> dict = corpora.Dictionary.load(dictf)
>>> len(dict.keys())
6481 #columns of the npy array is the words in my dict

src = https://groups.google.com/forum/?fromgroups=#!searchin/gensim/lda$20topic-word$20matrix/gensim/Qoj7Agkx3qE/r9lyfihC4b4J


问:
Proxies in Maven's settings.xml
Coming from this question I'm trying to get my setup to work, but the tests keep failing as they can't connect to the remote site. I upgraded to Maven 3.3.9.

This is my settings.xml that I want to get working:

```<code><settings>

  <proxies>
    <proxy>
      <id>httpProxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.local</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
    <proxy>
      <id>httpsProxy</id>
      <active>true</active>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
  </proxies>
:
</code>```

This is a small part, which already doesn't work:

```<code><settings>

  <proxies>
    <proxy>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
    </proxy>
  </proxies>
:
</code>```

I also tried to put IP-addresses in there.

I know that Maven picks that XML, because Maven says so in its debug messages and if I break the syntax of it Maven complains.

The only thing that really works is passing -Dhttps.proxyHost=proxy.local -Dhttps.proxyPort=3128 to Maven.

What is it that I'm doing wrong in my XML?

答:
Your tests are likely not going to read the settings.xml as that's for Maven as that's for the Maven build and their plugins.

You can double check this by adding in -X and see what properties are sent to your tests when surefire is running.

Title: Proxies in Maven's settings.xml

Body:
Coming from this question I'm trying to get my setup to work, but the tests keep failing as they can't connect to the remote site. I upgraded to Maven 3.3.9.

This is my settings.xml that I want to get working:

<settings>

  <proxies>
    <proxy>
      <id>httpProxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>proxy.local</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
    <proxy>
      <id>httpsProxy</id>
      <active>true</active>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
      <nonProxyHosts>localhost|*.local</nonProxyHosts>
    </proxy>
  </proxies>
:

This is a small part, which already doesn't work:

<settings>

  <proxies>
    <proxy>
      <protocol>https</protocol>
      <host>10.20.20.208</host>
      <port>3128</port>
    </proxy>
  </proxies>
:

I also tried to put IP-addresses in there.

I know that Maven picks that XML, because Maven says so in its debug messages and if I break the syntax of it Maven complains.

The only thing that really works is passing -Dhttps.proxyHost=proxy.local -Dhttps.proxyPort=3128 to Maven.

What is it that I'm doing wrong in my XML?


问:
Triangle in layout - Android UI
I need to add/design the next triangle in an Android layout.

Above the triangle the layout background is gray, and below is white.

Basically is a gray triangle with a dark border and a red border, but i dont know which is the best way to archieve this.

I dont want to add static images to the layout, and i dont know how to do this with shapes,xml,drawables.

答:
indeed you can, you can design in any vector design program like adobe illustrator and import it as SVG and later import it to the android studio as SVG android studio will automatically convert it to XML
right click on drawable folder >> Vector asset

if you want to know how to design it you can ask here https://graphicdesign.stackexchange.com/

Title: Triangle in layout - Android UI


问:
Javascript Avoiding Nested For Loops
I've noticed my algorithm solutions often include ugly nested for loops when better options are available. In the example below, how can I determine the prime numbers up to the given parameter without nested loops? One constraint of the assignment was to not utilize any external functions.

```<code>function sumPrimes(num) {
    var p = [];
    for (var i = 2; i <= num; i++)
    {
        p.push(i);
        for (var j = 2; j < i; j++)
        {
            if (i % j === 0) //not a prime
            {
                p.pop(i);
                break;
            }
        }
    }
    return p;
</code>```

答:
I don't know if there is any other good solution but I came up with this. There is still one for loop ;)

```<code>function primes(num) {
  return Array.apply(null, {length: (num + 1)}).map(Number.call, Number)
   .filter(function(n) {
     for(var i = 2; i < n; i++) {
       if(n % i === 0) return false;
     }
     return n !== 0 && n !== 1;
   })
 }
</code>```

Explanation:

```<code>Array.apply(null, {length: (num + 1)}).map(Number.call, Number)
</code>```

This line creates an Array with the range of the passed argument. If num would be 5 it would create the following Array: [0, 1, 2, 3, 4, 5]. I found this here.

Then I use the filter function to remove all non prime numbers. If the filter function returns false the number will be removed from the array. So inside the filter function we check if the current number is a prime number. If so, true is returned. As you can see I still use a normal for loop here.

No you can call the function as follows: primes(28);

This will return the following Array: [ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]

In this specific case I would say to use normal for loops is absolutely ok. But always consider functions like map, reduce or filter when you operate on arrays.

Title: Javascript Avoiding Nested For Loops

Body:
I've noticed my algorithm solutions often include ugly nested for loops when better options are available. In the example below, how can I determine the prime numbers up to the given parameter without nested loops? One constraint of the assignment was to not utilize any external functions.

function sumPrimes(num) {
    var p = [];
    for (var i = 2; i <= num; i++)
    {
        p.push(i);
        for (var j = 2; j < i; j++)
        {
            if (i % j === 0) //not a prime
            {
                p.pop(i);
                break;
            }
        }
    }
    return p;

Body:
I don't know if there is any other good solution but I came up with this. There is still one for loop ;)

function primes(num) {
  return Array.apply(null, {length: (num + 1)}).map(Number.call, Number)
   .filter(function(n) {
     for(var i = 2; i < n; i++) {
       if(n % i === 0) return false;
     }
     return n !== 0 && n !== 1;
   })
 }

Explanation:

Array.apply(null, {length: (num + 1)}).map(Number.call, Number)

This line creates an Array with the range of the passed argument. If num would be 5 it would create the following Array: [0, 1, 2, 3, 4, 5]. I found this here.

Then I use the filter function to remove all non prime numbers. If the filter function returns false the number will be removed from the array. So inside the filter function we check if the current number is a prime number. If so, true is returned. As you can see I still use a normal for loop here.

No you can call the function as follows: primes(28);

This will return the following Array: [ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]

In this specific case I would say to use normal for loops is absolutely ok. But always consider functions like map, reduce or filter when you operate on arrays.


问:
What is routing? Why is "routing" needed in single page web apps?
I understood that routing libraries for SPAs like https://github.com/ReactTraining/react-router help to parse the URL and put the app into a corresponding state of a state machine.

Is there more to routing than this?

Why is routing needed in the first place?

Why are URLs important? For example in a desktop app there are no URLs, so what's the big deal about them in a web app?

答:
I also have this problem: "Why do we need routing?". You can write apps without routing at all. The code can get messy but still, it is not impossible.

My biggest reason for having routing is because, if the user hits the Back button of the browser (Forward button as well, for that matter), they will not be navigating within the app. The user might expect to navigate within the app using the history of the different "pages" they loaded previously. Instead, they will be thrown out of the web app. Hitting the Refresh button would also throw them to the root of the app.

From the user's point of view, it is a regular web app (they doesn't need to know how it is designed: SPA or otherwise) and it should work as any web app/website should work. Routing ensures this, doesn't it?

ContentLicense: CC BY-SA 4.0


问:
Non-Standard Attributes on HTML Tags. Good Thing? Bad Thing? Your Thoughts?
HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant.

Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a popup, you can set the name of the popup in an attribute:

```<code><a href="#null" class="popup" title="See the Popup!"
   popup_title="Title for My Popup">click me</a>
</code>```

Alternatively, you can store the title for the popup in a hidden element, like a span:

```<code><style>
    .popup .title { display: none; }
</style>
<a href="#null" title="See the Popup!" class="popup">
    click me
    <span class="title">Title for My Popup</span>
</a>
</code>```

I am torn however as to which should be a preferred method. The first method is more concise and, I'm guessing, doesn't screw with search engines and screen readers as much. Conversely, the second option makes storing large amounts of data easier and is thus, more versatile. It is also standards compliant.

I am curious what this communities thoughts are. How do you handle a situation like this? Does the simplicity of the first method outweigh the potential downsides (if there are any)?

答:
You could nest hidden input elements INSIDE the anchor element

```<code><a id="anchor_id">
  <input type="hidden" class="articleid" value="5">
  Link text here
</a>
</code>```

Then you can easily pull the data out by

```<code>$('#anchor_id .articleid').val()
</code>```

OwnerDisplayName: dave mankoff

Body:
HTML (or maybe just XHTML?) is relatively strict when it comes to non-standard attributes on tags. If they aren't part of the spec, then your code is considered non-compliant.

Non-standard attributes can be fairly useful for passing along meta-data to Javascript however. For instance, if a link is suppose to show a popup, you can set the name of the popup in an attribute:

click me

Alternatively, you can store the title for the popup in a hidden element, like a span:

    click me
    Title for My Popup

I am torn however as to which should be a preferred method. The first method is more concise and, I'm guessing, doesn't screw with search engines and screen readers as much. Conversely, the second option makes storing large amounts of data easier and is thus, more versatile. It is also standards compliant.

I am curious what this communities thoughts are. How do you handle a situation like this? Does the simplicity of the first method outweigh the potential downsides (if there are any)?

LastEditorDisplayName: dave mankoff

Body:
You could nest hidden input elements INSIDE the anchor element

<a id="anchor_id">
  <input type="hidden" class="articleid" value="5">
  Link text here
</a>

Then you can easily pull the data out by

$('#anchor_id .articleid').val()


问:
Time-complexity of while loop in big-O
I'm having trouble indicating the time complexity of a simple while loop in terms of input n.

The while loop executes as long as i < n and i is incremented by one more than the number of previous iteration. For example, in the 2nd iteration, i is incremented by 1, in the 3rd iteration, by 2, and so on... Essentially, the loop executes "final value of t" times.

```<code>func(n):
    i = 1
    t = 1

    while (i < n):
        i = i + t
        t = t + 1
</code>```

My question is, how can I indicate the time complexity of this algorithm in big-O notation?

答:
Essentially, the loop executes "final value of t" times.

You're halfway there. You know that the loop executes t times, now you just need to solve for t.

Your loop will end when the sum of 1..t is greater than or equal to n. By solving the summation, we can express this as

```<code>t*(t-1)/2 >= n
</code>```

By rearranging the equation to show t in terms of n, we get

```<code>t >= 1/2 (1 - sqrt(1 + 8 n))
</code>```

But, we also know that the loop ends at the lowest (first) value of t that satisfies the inequality. Let us call that value tn. If tn is the first value that satisfies the inequality, then tn-1 is the last value that satisfies the opposite inequality.

```<code>tn - 1 <= 1/2 (1 - sqrt(1 + 8 n))
</code>```

From this, we know that t is bounded above and below by some function of sqrt(n) and some constants. So then t is Θ(sqrt(n)), which means t is also O(sqrt(n)).

Title: Time-complexity of while loop in big-O

Body:
I'm having trouble indicating the time complexity of a simple while loop in terms of input n.

The while loop executes as long as i < n and i is incremented by one more than the number of previous iteration. For example, in the 2nd iteration, i is incremented by 1, in the 3rd iteration, by 2, and so on... Essentially, the loop executes "final value of t" times.

func(n):
    i = 1
    t = 1

    while (i < n):
        i = i + t
        t = t + 1

My question is, how can I indicate the time complexity of this algorithm in big-O notation?

Body:
Essentially, the loop executes "final value of t" times.

You're halfway there. You know that the loop executes t times, now you just need to solve for t.

Your loop will end when the sum of 1..t is greater than or equal to n. By solving the summation, we can express this as

t*(t-1)/2 >= n

By rearranging the equation to show t in terms of n, we get

t >= 1/2 (1 - sqrt(1 + 8 n))

But, we also know that the loop ends at the lowest (first) value of t that satisfies the inequality. Let us call that value tn. If tn is the first value that satisfies the inequality, then tn-1 is the last value that satisfies the opposite inequality.

tn - 1 <= 1/2 (1 - sqrt(1 + 8 n))

From this, we know that t is bounded above and below by some function of sqrt(n) and some constants. So then t is Θ(sqrt(n)), which means t is also O(sqrt(n)).


问:
how do i make a badge notify disappear across all web pages after click
Please how do i make a badge notify icon hide after the user clicks on it and stay hidden across all pages when i navigate. here's my code

```<code><h:outputLink value="" id="but" class="closebtn" onclick="closeNav()" style="border-bottom:none">x</h:outputLink>
        <h:outputLink value="home.xhtml" id="ab" onclick="closeNav()"><span class="glyphicon glyphicon-home" style=" color: blue;"></span><span id="ab1">Home</span></h:outputLink>
        <h:outputLink value="profile.xhtml" id="ser" onclick="closeNav()"><span class="glyphicon glyphicon-user custom"></span><span id="ser1">Profile</span></h:outputLink>
        <h:outputLink value="transaction.xhtml" id="cl" onclick="closeNav()"><span class="glyphicon glyphicon-briefcase"></span><span class="badge badge-notify">!</span><span id="cl1">Transaction</span></h:outputLink>
</code>```

here's my css:

```<code>.badge-notify
    {
        background:red;
        position:absolute;

  }
</code>```

here's my javascript:

```<code> $(document).ready(function()
{
  $(".badge-notify").click(function()
   {
       $(".badge-notify").fadeOut("slow");
   });
});
</code>```

答:
The reason it keeps showing up on every page is because you aren't keeping track of whether it's been clicked before or not.

One solution is to set the display of the badge to none by default, like so:

```<code>.badge-notify {
    display: none;
    background:red;
    position:absolute;
}
</code>```

and to have a variable saved in their localStorage to see if they've clicked the badge before or not. So if we do something like:

```<code>localStorage.setItem("seen_badge", "false");
</code>```

then we've created a variable that will now work across all pages of your site. So, using some jQuery we check if the user has seen the badge before, and if not, we make it visible:

```<code>if(localStorage.seen_badge === "false") {
    $('.badge-notify').show();
}
</code>```

Next, if the user clicks on the badge to close/dismiss it, we change the value of seen_badge to true, and that way it won't show up again like so:

```<code>$('.badge-notify').on('click', function() {
    $(this).hide();
    localStorage.seen_badge = "true";
});
</code>```

Body:
Please how do i make a badge notify icon hide after the user clicks on it and stay hidden across all pages when i navigate. here's my code

<h:outputLink value="" id="but" class="closebtn" onclick="closeNav()" style="border-bottom:none">x</h:outputLink>
        <h:outputLink value="home.xhtml" id="ab" onclick="closeNav()">Home</h:outputLink>
        <h:outputLink value="profile.xhtml" id="ser" onclick="closeNav()">Profile</h:outputLink>
        <h:outputLink value="transaction.xhtml" id="cl" onclick="closeNav()">!Transaction</h:outputLink>

here's my css:

.badge-notify
    {
        background:red;
        position:absolute;

  }

here's my javascript:

 $(document).ready(function()
{
  $(".badge-notify").click(function()
   {
       $(".badge-notify").fadeOut("slow");
   });
});

Body:
The reason it keeps showing up on every page is because you aren't keeping track of whether it's been clicked before or not.

One solution is to set the display of the badge to none by default, like so:

.badge-notify {
    display: none;
    background:red;
    position:absolute;
}

and to have a variable saved in their localStorage to see if they've clicked the badge before or not. So if we do something like:

localStorage.setItem("seen_badge", "false");

then we've created a variable that will now work across all pages of your site. So, using some jQuery we check if the user has seen the badge before, and if not, we make it visible:

if(localStorage.seen_badge === "false") {
    $('.badge-notify').show();
}

Next, if the user clicks on the badge to close/dismiss it, we change the value of seen_badge to true, and that way it won't show up again like so:

$('.badge-notify').on('click', function() {
    $(this).hide();
    localStorage.seen_badge = "true";
});


问:
understanding the lower bound/ upper bound interface
I am having trouble grasping the semantics of the lower/ upper bound interface.

Consider this test snippet I wrote:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

int main() {

  // sorted vector
  std::vector<std::pair<size_t, std::vector<int>>> v = {
      std::make_pair(0, std::vector<int>()),
      std::make_pair(0, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(5, std::vector<int>()),
      std::make_pair(20, std::vector<int>())};

  auto key = 3;
  auto itr = std::lower_bound(
      v.begin(), v.end(), key,
      [](const auto &t1, const size_t d) -> bool { return t1.first < d; });

  std::cout << itr->first << "\n";
}
</code>```

Why do I not need two vector elements? Why do I need only one and a second argument (d) of the type of key? What is d anyway? The documentation sounded like it is a vector element cast to type of key. But why then not accept another vector element as the second argument? And why does no comparison against key happen?

Why does the interface not look like this:

```<code>auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});
</code>```

Can you explain the semantics behind the parameters, especially d?

答:
Lower bound guarantees it only passes key as the right hand argument.

It does a binary search, looking for the place where comp(e,key) changes from true to false.  If it is comp(e,key) is true at a specific element e, it searches the later elements, if false the earlier elements, until it has found the "edge" between the elements "kess than" key and the elements "greater than" key.  It does this via binary search: so first middle of the iterator range, then middle of the range it wants to search next, recursively.

It then returns the iterator to the earliest element e such that !comp(e,key) is true.

This only works if all the elements e such that comp(e,key) are at the start of the list.

Body:
I am having trouble grasping the semantics of the lower/ upper bound interface.

Consider this test snippet I wrote:

#include <algorithm>
#include <iostream>
#include <vector>

int main() {

  // sorted vector
  std::vector<std::pair<size_t, std::vector<int>>> v = {
      std::make_pair(0, std::vector<int>()),
      std::make_pair(0, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(3, std::vector<int>()),
      std::make_pair(5, std::vector<int>()),
      std::make_pair(20, std::vector<int>())};

  auto key = 3;
  auto itr = std::lower_bound(
      v.begin(), v.end(), key,
      [](const auto &t1, const size_t d) -> bool { return t1.first < d; });

  std::cout << itr->first << "\n";
}

Why do I not need two vector elements? Why do I need only one and a second argument (d) of the type of key? What is d anyway? The documentation sounded like it is a vector element cast to type of key. But why then not accept another vector element as the second argument? And why does no comparison against key happen?

Why does the interface not look like this:

auto itr = std::lower_bound(v.begin(), v.end(), 3, [](const auto& t1, const
  auto& t2) -> bool {return t1.first < t2.first;});

Can you explain the semantics behind the parameters, especially d?


问:
Should I add the async modifier if I return a Task in an expensive method?
The C# compiler already warns us if we have a method that has the async modifier but does not use the await operator.

According to this answer there's no point adding an await to the end of an async method (and in that case, just remove the async modifier).

But what if the method has an expensive synchronous operation it needs to perform before calling a subsequent true async method?

For example, if I'm using HttpClient:

```<code>private readonly HttpClient client = ...

public Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return this.client.SendAsync( request );
}
</code>```

This code would block the caller (due to SomeExpensiveButSynchronousMethod).

However, if I change the code to this:

```<code>public async Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return await this.client.SendAsync( request );
}
</code>```

and I call it like so:

```<code>HttpResponse response = await myWrapper.CallMyWebServiceMethod();
</code>```

...I understand the TPL would spin up a background thread immediately and then run CallMyWebServiceMethod in the background thread, resuming whatever the parent code wants, making the entire call non-blocking in the process, before resuming after the Task completes and returns the HttpResponse.

...if that's the case then it seems contradictory.

If I'm wrong, and the call is blocking until it gets to SendAsync then how can I execute SomeExpensiveButSynchronousMethod on the same background thread as the HttpClient uses for its request?

答:
According to this answer there's no point adding an await to the end of an async method (and in that case, just remove the async modifier).

That's an oversimplification. See my blog post on eliding async and await.

But what if the method has an expensive synchronous operation it needs to perform before calling a subsequent true async method?

This is a rare case, but the appropriate solution IMO is to execute the synchronous operation synchronously (i.e., not wrapped in a Task.Run) and be sure to document its behavior.

I understand the TPL would spin up a background thread immediately and then run CallMyWebServiceMethod in the background thread, resuming whatever the parent code wants, making the entire call non-blocking in the process, before resuming after the Task completes and returns the HttpResponse.

That is not at all what happens. You may find my async intro helpful. Quote:

The beginning of an async method is executed just like any other method. That is, it runs synchronously until it hits an “await” (or throws an exception).

In actuality, both of your examples synchronously block the caller while executing SomeExpensiveButSynchronousMethod.

If I'm wrong, and the call is blocking until it gets to SendAsync then how can I execute SomeExpensiveButSynchronousMethod on the same background thread as the HttpClient uses for its request?

HttpClient doesn't use a background thread for its request, so this part of the question doesn't make sense. For more information on how asynchronous I/O works, see my blog post There Is No Thread.

To answer the actual question:

Should I add the async modifier if I return a Task in an expensive method?

Yes. But the reason you should do so is not to "make it asynchronous"; it's so that any exceptions from SomeExpensiveButSynchronousMethod are captured and placed on the returned Task, which is the expected semantic for methods that follow the Task-based Asynchronous Pattern (TAP).

Body:
The C# compiler already warns us if we have a method that has the async modifier but does not use the await operator.

According to this answer there's no point adding an await to the end of an async method (and in that case, just remove the async modifier).

But what if the method has an expensive synchronous operation it needs to perform before calling a subsequent true async method?

For example, if I'm using HttpClient:

private readonly HttpClient client = ...

public Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return this.client.SendAsync( request );
}

This code would block the caller (due to SomeExpensiveButSynchronousMethod).

However, if I change the code to this:

public async Task<HttpResponseMessage> CallMyWebServiceMethod() {

    HttpRequestMessage request = this.SomeExpensiveButSynchronousMethod();

    return await this.client.SendAsync( request );
}

and I call it like so:

HttpResponse response = await myWrapper.CallMyWebServiceMethod();

...I understand the TPL would spin up a background thread immediately and then run CallMyWebServiceMethod in the background thread, resuming whatever the parent code wants, making the entire call non-blocking in the process, before resuming after the Task completes and returns the HttpResponse.

...if that's the case then it seems contradictory.

If I'm wrong, and the call is blocking until it gets to SendAsync then how can I execute SomeExpensiveButSynchronousMethod on the same background thread as the HttpClient uses for its request?


问:
Get rid of strings containing a pattern within a file
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

```<code>aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"
</code>```

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

答:
How about</p>

```<code>sed 's/aws:[^ ]*//g' filename
</code>```

Body:
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

Body:
How about

sed 's/aws:[^ ]*//g' filename


问:
Gridview scroll slow
I'm trying to create an gallery app, just to show images to the user.

The app is already working, but the grid scroll is slow and not smooth.

I don't know what else I can do to make performance better. I'm already using LruCache and Async task to load images.

GridAdapter

```<code>package abcde.xyz;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

/**
 * Created by Lucas on 25/03/2017.
 */

public class GridImagesAdapter extends ArrayAdapter {

    private Context context;
    private int layoutResourceId;
    private ArrayList data = new ArrayList();
    public static LruCache<Integer, Bitmap> mMemoryCache;

    public GridImagesAdapter(Context context, int layoutResourceId, ArrayList<Integer> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        final int cacheSize = maxMemory / 4;
        if(mMemoryCache == null){
            mMemoryCache = new LruCache<Integer, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(Integer key, Bitmap bitmap) {
                    return bitmap.getByteCount() / 1024;
                }
            };
        }
        mMemoryCache.evictAll();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            ImageView image = (ImageView)row.findViewById(R.id.image);
            final Integer item = (Integer)data.get(position);

            image.setImageBitmap(null);
            ImageGridHandler handler = new ImageGridHandler(context, image);
            handler.execute(item);
        }

        return row;
    }
}
</code>```

ImageGridHandler

```<code>package abcde.xyz;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import java.lang.ref.WeakReference;

/**
 * Created by Lucas on 29/03/2017.
 */

public class ImageGridHandler extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private Context context;
    public ImageGridHandler(Context context, ImageView img){
        imageViewReference = new WeakReference<ImageView>(img);
        this.context = context;
    }

    @Override
    protected Bitmap doInBackground(Integer... params) {

        return loadBitmap(params[0]);

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        final ImageView imageView = imageViewReference.get();

        if(imageView != null) {
            //imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageBitmap(result);
        }
    }

    public void addBitmapToMemoryCache(Integer key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            GridImagesAdapter.mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(Integer key) {
        return GridImagesAdapter.mMemoryCache.get(key);
    }

    public Bitmap loadBitmap(Integer resId) {

        Bitmap bitmap = getBitmapFromMemCache(resId);
        if (bitmap == null) {

           Log.d("ImageGridHandler", "Loading: " + resId);
            if(resId != null) {
                bitmap = MediaStore.Images.Thumbnails.getThumbnail(
                        context.getContentResolver(), resId,
                        MediaStore.Images.Thumbnails.MICRO_KIND,
                        null);
                if(bitmap != null) {
                    addBitmapToMemoryCache(resId, bitmap);
                }
            }

            Log.d("GRIDADAPTER", "ImageLoaded");
        }

        return bitmap;
    }

}
</code>```

Layouts

content_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="umdev.images24.MainActivity"
    tools:showIn="@layout/activity_main">
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipeRefresh"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp">

     <GridView
         android:id="@+id/gridView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_margin="0dp"
         android:drawSelectorOnTop="true"
         android:gravity="center"
         android:columnWidth="100dp"
         android:numColumns="auto_fit"
         android:stretchMode="columnWidth"
         android:verticalSpacing="0dp"
         android:focusable="true"
         android:clickable="true"
         android:fastScrollEnabled="true"/>

    </android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
</code>```

grid_item_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:background="#fff">

    <ImageView
        android:id="@+id/image"
        android:layout_width="120dp"
        android:layout_height="120dp" />

</LinearLayout>
</code>```

答:
Before load the image we have to resize it to avoid ImageView scale.

Load a Scaled Down Version into Memory

https://developer.android.com/topic/performance/graphics/load-bitmap.html

Thanks @GT

Title: Gridview scroll slow

Body:
I'm trying to create an gallery app, just to show images to the user.

The app is already working, but the grid scroll is slow and not smooth.

I don't know what else I can do to make performance better. I'm already using LruCache and Async task to load images.

GridAdapter

package abcde.xyz;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import java.util.ArrayList;

/**
 * Created by Lucas on 25/03/2017.
 */

public class GridImagesAdapter extends ArrayAdapter {

    private Context context;
    private int layoutResourceId;
    private ArrayList data = new ArrayList();
    public static LruCache<Integer, Bitmap> mMemoryCache;

    public GridImagesAdapter(Context context, int layoutResourceId, ArrayList<Integer> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        final int cacheSize = maxMemory / 4;
        if(mMemoryCache == null){
            mMemoryCache = new LruCache<Integer, Bitmap>(cacheSize) {
                @Override
                protected int sizeOf(Integer key, Bitmap bitmap) {
                    return bitmap.getByteCount() / 1024;
                }
            };
        }
        mMemoryCache.evictAll();

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;

        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            ImageView image = (ImageView)row.findViewById(R.id.image);
            final Integer item = (Integer)data.get(position);

            image.setImageBitmap(null);
            ImageGridHandler handler = new ImageGridHandler(context, image);
            handler.execute(item);
        }

        return row;
    }
}

ImageGridHandler

package abcde.xyz;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.ImageView;

import java.lang.ref.WeakReference;

/**
 * Created by Lucas on 29/03/2017.
 */

public class ImageGridHandler extends AsyncTask<Integer, Void, Bitmap> {
    private final WeakReference<ImageView> imageViewReference;
    private Context context;
    public ImageGridHandler(Context context, ImageView img){
        imageViewReference = new WeakReference<ImageView>(img);
        this.context = context;
    }

    @Override
    protected Bitmap doInBackground(Integer... params) {

        return loadBitmap(params[0]);

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        final ImageView imageView = imageViewReference.get();

        if(imageView != null) {
            //imageView.setScaleType(ImageView.ScaleType.CENTER);
            imageView.setImageBitmap(result);
        }
    }

    public void addBitmapToMemoryCache(Integer key, Bitmap bitmap) {
        if (getBitmapFromMemCache(key) == null) {
            GridImagesAdapter.mMemoryCache.put(key, bitmap);
        }
    }

    public Bitmap getBitmapFromMemCache(Integer key) {
        return GridImagesAdapter.mMemoryCache.get(key);
    }

    public Bitmap loadBitmap(Integer resId) {

        Bitmap bitmap = getBitmapFromMemCache(resId);
        if (bitmap == null) {

           Log.d("ImageGridHandler", "Loading: " + resId);
            if(resId != null) {
                bitmap = MediaStore.Images.Thumbnails.getThumbnail(
                        context.getContentResolver(), resId,
                        MediaStore.Images.Thumbnails.MICRO_KIND,
                        null);
                if(bitmap != null) {
                    addBitmapToMemoryCache(resId, bitmap);
                }
            }

            Log.d("GRIDADAPTER", "ImageLoaded");
        }

        return bitmap;
    }

}

Layouts

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="umdev.images24.MainActivity"
    tools:showIn="@layout/activity_main">
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swipeRefresh"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        tools:layout_editor_absoluteY="8dp"
        tools:layout_editor_absoluteX="8dp">

     <GridView
         android:id="@+id/gridView"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_margin="0dp"
         android:drawSelectorOnTop="true"
         android:gravity="center"
         android:columnWidth="100dp"
         android:numColumns="auto_fit"
         android:stretchMode="columnWidth"
         android:verticalSpacing="0dp"
         android:focusable="true"
         android:clickable="true"
         android:fastScrollEnabled="true"/>

    </android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>

grid_item_layout.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:background="#fff">

    <ImageView
        android:id="@+id/image"
        android:layout_width="120dp"
        android:layout_height="120dp" />

</LinearLayout>


问:
Trouble getting total count using .Take() and .Skip()
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

```<code>public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}
</code>```

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference

答:
You are setting pagedThings = things.  So you are working on the same object.  You would need to copy things to a new collection if you want to do what you're trying above, but I would recommend refactoring this code in general.

You can check out this SO post to get some ideas on how to get the count without enumerating the list:
How to COUNT rows within EntityFramework without loading contents?

Body:
I'm having some trouble implementing some paging using Linq and I've read the various questions (this and this for example) on here but I'm still getting the error;

System.InvalidOperationException: The result of a query cannot be enumerated more than once.

My (slightly obfuscated) code is;

public List<Thing> GetThings(ObjectParameter[] params, int count, int pageIndex)
{
    var things = from t in Context.ExecuteFunction<Something>("function", params)
                 select new Thing
                 {
                     ID = t.ID
                 });

    var pagedThings = things;

    if (pageIndex == 0)
        pagedThings = things.Take(count);
    else if (pageIndex > 0)
        pagedThings = things.Skip(count * pageIndex).Take(count);

    var countOfThings = things.Count();

    return pagedThings.ToList();
}

As soon as the final .ToList() is called, the error is thrown but I can't see why - are the calls to things.Count() and pagedThings.ToList() enumerating the same thing?

Edit: I'm using Entity Framework if that makes any difference


问:
How to create an array of references
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

```<code>Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a
</code>```

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].

答: What is the point of that? When you do c2[0] = c1[0] arrays will contain references to the same object at zero index, but those arrays are independent. There is no legal way (maybe sun.misc.Unsafe can do the trick) in Java to make some sort of dependent references to parts of an array.

Title: How to create an array of references

Body:
Create an array of references

I've read the link above and known how to create an array of references in Java. But it doesn't seem to work...

Here is my test:

Character []c1 = {'a', 'x'};
Character []c2 = new Character[1];
c2[0] = c1[0]; // I try to make c2[0] as the reference of c1[0]
c1[0] = 'b';

System.out.println(c1[0]);    // b
System.out.println(c2[0]);    // a

Is there any way such that I can make c2[0] as a reference of c1[0] so that any change in c1[0] will update the value in c2[0].


问:
ifelse in R to determine 2 conditions; one simple the other composite
Background:

I have two elements in an R function (see my R code below), type and width. The type element simply can be 1 or 2. But width can take any number.

Question:

Suppose there there two specific numbers that act as criteria for width. First number is 1. Second number is sqrt(2) / 2.

How can I say:

IF "type" is 1 AND "width" is NOT 1 AND ALSO (i.e., still type is 1) "width" is NOT sqrt(2) / 2,  THEN "do ..."?

Can I use:

```<code> type = 1
 width = sqrt(2)/ 2

ifelse(type == 1 & width != 1 & width != sqrt(2)/2, "do nothing", "the critera" )
</code>```

答:
There's nothing wrong with your logic (type must be 1 and width can't be 1 or sqrt(2)/2), but the ifelse statement complains that you haven't supplied an else.  Try:

```<code>if(type == 1 & width != 1 & width != sqrt(2)/2) cat("do ...")
</code>```

Body:
Background:

I have two elements in an R function (see my R code below), type and width. The type element simply can be 1 or 2. But width can take any number.

Question:

Suppose there there two specific numbers that act as criteria for width. First number is 1. Second number is sqrt(2) / 2.

How can I say:

IF "type" is 1 AND "width" is NOT 1 AND ALSO (i.e., still type is 1) "width" is NOT sqrt(2) / 2,  THEN "do ..."?

Can I use:

 type = 1
 width = sqrt(2)/ 2

ifelse(type == 1 & width != 1 & width != sqrt(2)/2, "do nothing", "the critera" )

Body:
There's nothing wrong with your logic (type must be 1 and width can't be 1 or sqrt(2)/2), but the ifelse statement complains that you haven't supplied an else.  Try:

if(type == 1 & width != 1 & width != sqrt(2)/2) cat("do ...")


问:
Bootstrap 3 merge rows and columns
I can't figure out what is the problem with my code. I'm very new in bootstrap my problem is kinda trivial. One of my field is out of position. I have tried a different route by making only one row and instead of increasing the div sizes I reduced them, but it had the exact same problem. (Run the code in full screen mode).

Please if you can help me out!

.row {
    background-color: yellow;
}

.col-sm-3, .col-sm-6 {
    border:solid 2px black;
}

div {
    height:200px;
}
.two-div {
    height:400px;
}
.three-div {
    height:600px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <div class="col-sm-3 three-div pull-left">Works</div>
            <div class="col-sm-6">Works</div>
            <div class="col-sm-3 two-div pull-right">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-3 two-div">Works</div>
            <div class="col-sm-3 three-div">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-3 two-div pull-right">Works</div>
        </div>
        <div class="row">
            <div class="col-sm-6">:(</div>
        </div>
    </div>
    </body>
</html></code>```

答:
With some nesting and pull-right on the appropriate columns you can reverse the float:left and make it work (albeit a hack!)...

http://www.codeply.com/go/rgHEL6DW12

```<code><div class="container">
    <div class="row">
        <div class="col-sm-9">
            <div class="row">
                <div class="col-sm-4 three-div">works</div>
                <div class="col-sm-8">works</div>
                <div class="col-sm-4 three-div pull-right">works</div>
                <div class="col-sm-4 two-div pull-right">works</div>
                <div class="col-sm-8 pull-right">
                    ;-)
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="row">
                <div class="col-sm-12 two-div">works</div>
                <div class="col-sm-12 two-div">works</div>
            </div>
        </div>
    </div>
</div>
</code>```

Think about it like this...

http://www.codeply.com/go/rgHEL6DW12

Title: Bootstrap 3 merge rows and columns

Body:
I can't figure out what is the problem with my code. I'm very new in bootstrap my problem is kinda trivial. One of my field is out of position. I have tried a different route by making only one row and instead of increasing the div sizes I reduced them, but it had the exact same problem. (Run the code in full screen mode).

Please if you can help me out!

.row {
    background-color: yellow;
}

.col-sm-3, .col-sm-6 {
    border:solid 2px black;
}

div {
    height:200px;
}
.two-div {
    height:400px;
}
.three-div {
    height:600px;
}

<!DOCTYPE html>

        <title>Bootstrap Example</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Works

Works

Works

Works

Works

Works

:(

Body:
With some nesting and pull-right on the appropriate columns you can reverse the float:left and make it work (albeit a hack!)...

http://www.codeply.com/go/rgHEL6DW12

<div class="container">
    <div class="row">
        <div class="col-sm-9">
            <div class="row">
                <div class="col-sm-4 three-div">works</div>
                <div class="col-sm-8">works</div>
                <div class="col-sm-4 three-div pull-right">works</div>
                <div class="col-sm-4 two-div pull-right">works</div>
                <div class="col-sm-8 pull-right">
                    ;-)
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="row">
                <div class="col-sm-12 two-div">works</div>
                <div class="col-sm-12 two-div">works</div>
            </div>
        </div>
    </div>
</div>

Think about it like this...

http://www.codeply.com/go/rgHEL6DW12


问:
Trying to get the sum of pairs that equal to a prime number
I am trying to get four input from the user and try to find pairs that equal to a prime number just by using user defined methods. i din reach the prime step yet. But before that i ran into a problem. So jus to check the sum I TRIED printing it out in the method called sumPair6 but it prints zero, so the sum is returning 0 for everything. don't know what mistake am i doing. I got rid of the initial 0 too but still doesn't not work </p>

```<code>import java.util.Scanner;
public class prime
{
    public static int  num1 = 0,  num2 = 0,  num3 = 0,  num4 = 0, sum1= 0,sum2,sum3,sum4,sum5,sum6,val1,stop;
    public static Scanner input = new Scanner(System.in);
    public static void main(String args[])
    {
        input();
        sumPair1(num1, num2, sum1);
        sumPair2(num1, num3, sum2);
        sumPair3(num1, num4, sum3);
        sumPair4(num2, num3, sum4);
        sumPair5(num2, num4, sum5);
        sumPair6(num3, num4, sum6);
       // Prime(sum1,sum2,sum3,sum4,sum5,sum6,val1,stop);
    }
    public static void input ()
    {
        System.out.print("Enter a positive integer: ");
        num1 = input.nextInt();
        if(num1==0 || num1 < 0)
            while(num1==0 || num1 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num1 = input.nextInt();
            }
        if(num1 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num2 = input.nextInt();
        if(num2==0 || num2 < 0)
            while(num2 == 0 || num2 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num2 = input.nextInt();
            }
        if(num2 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num3 = input.nextInt();
        while(num3 ==0 || num3 < 0)
        {
            System.out.print("Enter a positive integer: ");
            num3 = input.nextInt();
        }
        if(num3 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num4 = input.nextInt();
        if(num4==0 || num4 < 0)
            while(num4 == 0 || num4 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num4 = input.nextInt();
            }
        if(num4 > 0)

            System.out.println("Thank you.");

    }
    public static int sumPair1(int num1, int num2, int sum1)
     {
        sum1 = num1 + num2;
        return sum1;
    }

    public static int sumPair2(int num1,int num3,int sum2)
      {
        sum2 = num1 + num3;
         System.out.println(sum1);
        return sum2;
    }

    public static int sumPair3(int num1, int num4,int sum3)
    {
        sum3 = num1 + num4;
        return sum3;
    }

    public static int sumPair4(int num2, int num3,int sum4)
    {
        sum4 = num2 + num3;
        return sum4;
    }

    public static int sumPair5(int num2,int num4,int sum5)
    {
        sum5 = num2 + num4;
        return sum5;
    }

    public static int sumPair6(int num3, int num4,int sum6)
    {
        sum6 = num3 + num4;
        System.out.println(sum1);
        return sum6;
    }
}
</code>```

答:
the scope of the variables are only within a particular method. within input(), you take user inputs and assign them to your variables but as soon as the execution thread comes out of input, your variables num1, num2 etc. have same pre-defined values (all 0).

you can re-design your code in many ways. one simple way is to call sumpair method from within input() method, so you will need only one sumpair method, which can take different num values.

Body:
I am trying to get four input from the user and try to find pairs that equal to a prime number just by using user defined methods. i din reach the prime step yet. But before that i ran into a problem. So jus to check the sum I TRIED printing it out in the method called sumPair6 but it prints zero, so the sum is returning 0 for everything. don't know what mistake am i doing. I got rid of the initial 0 too but still doesn't not work

import java.util.Scanner;
public class prime
{
    public static int  num1 = 0,  num2 = 0,  num3 = 0,  num4 = 0, sum1= 0,sum2,sum3,sum4,sum5,sum6,val1,stop;
    public static Scanner input = new Scanner(System.in);
    public static void main(String args[])
    {
        input();
        sumPair1(num1, num2, sum1);
        sumPair2(num1, num3, sum2);
        sumPair3(num1, num4, sum3);
        sumPair4(num2, num3, sum4);
        sumPair5(num2, num4, sum5);
        sumPair6(num3, num4, sum6);
       // Prime(sum1,sum2,sum3,sum4,sum5,sum6,val1,stop);
    }
    public static void input ()
    {
        System.out.print("Enter a positive integer: ");
        num1 = input.nextInt();
        if(num1==0 || num1 < 0)
            while(num1==0 || num1 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num1 = input.nextInt();
            }
        if(num1 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num2 = input.nextInt();
        if(num2==0 || num2 < 0)
            while(num2 == 0 || num2 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num2 = input.nextInt();
            }
        if(num2 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num3 = input.nextInt();
        while(num3 ==0 || num3 < 0)
        {
            System.out.print("Enter a positive integer: ");
            num3 = input.nextInt();
        }
        if(num3 > 0)

            System.out.println("Thank you.");

        System.out.print("Enter a positive integer: ");
        num4 = input.nextInt();
        if(num4==0 || num4 < 0)
            while(num4 == 0 || num4 < 0)
            {
                System.out.print("Enter a positive integer: ");
                num4 = input.nextInt();
            }
        if(num4 > 0)

            System.out.println("Thank you.");

    }
    public static int sumPair1(int num1, int num2, int sum1)
     {
        sum1 = num1 + num2;
        return sum1;
    }

    public static int sumPair2(int num1,int num3,int sum2)
      {
        sum2 = num1 + num3;
         System.out.println(sum1);
        return sum2;
    }

    public static int sumPair3(int num1, int num4,int sum3)
    {
        sum3 = num1 + num4;
        return sum3;
    }

    public static int sumPair4(int num2, int num3,int sum4)
    {
        sum4 = num2 + num3;
        return sum4;
    }

    public static int sumPair5(int num2,int num4,int sum5)
    {
        sum5 = num2 + num4;
        return sum5;
    }

    public static int sumPair6(int num3, int num4,int sum6)
    {
        sum6 = num3 + num4;
        System.out.println(sum1);
        return sum6;
    }
}


问:
Stale Element reference error on finding the element -> when navigates back to previous page
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.

It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.

Code is :

```<code>public class EcommerceSearchResult {

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
        for(int i = 0 ; i<count ; i++)
        {
            List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
            System.out.println(gridrow.get(i).getText());
            listingelementinloop.get(i).click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

    }
}
</code>```

答:
The problem is that you are looping through a collection of elements that you collected from the page. Once you leave that page or reload it, the element references you were storing become stale, thus the error. One way to get around this is to use an index into the collection and loop over that. I've rewritten your code to make use of functions to take care of repeated actions. I've tested this code and it works.

Part of main

```<code>driver.get("http://store.demoqa.com/");
Search("iphone");
for (int i = 0; i < GetProductCount(); i++)
{
    ClickProduct(i);
    driver.navigate().back();
}
</code>```

and supporting functions

```<code>public void Search(String searchTerm)
{
    driver.findElement(By.cssSelector("input[value='Search Products']")).sendKeys(searchTerm + "\n");
}

public void ClickProduct(int index)
{
    driver.findElements(By.cssSelector("h2 > a")).get(index).click();
}

public int GetProductCount()
{
    return driver.findElements(By.cssSelector("h2 > a")).size();
}
</code>```

Body:
My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.

It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.

Code is :

public class EcommerceSearchResult {

public static WebDriver driver ;

public static void main(String[] args) throws InterruptedException {

    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
    driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("http://store.demoqa.com/");
    WebElement searchBox = driver.findElement(By.xpath("//input[contains(@class,'search')]"));
    searchBox.sendKeys("iphone"+"\n");
    List<WebElement>  gridrow
    = driver.findElements
    (By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
    int count = gridrow.size();
    System.out.print(count);
        for(int i = 0 ; i<count ; i++)
        {
            List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[@id='grid_view_products_page_container']/div/div"));
            System.out.println(gridrow.get(i).getText());
            listingelementinloop.get(i).click();
            driver.navigate().back();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        }

    }
}

Body:
The problem is that you are looping through a collection of elements that you collected from the page. Once you leave that page or reload it, the element references you were storing become stale, thus the error. One way to get around this is to use an index into the collection and loop over that. I've rewritten your code to make use of functions to take care of repeated actions. I've tested this code and it works.

Part of main

driver.get("http://store.demoqa.com/");
Search("iphone");
for (int i = 0; i < GetProductCount(); i++)
{
    ClickProduct(i);
    driver.navigate().back();
}

and supporting functions

public void Search(String searchTerm)
{
    driver.findElement(By.cssSelector("input[value='Search Products']")).sendKeys(searchTerm + "\n");
}

public void ClickProduct(int index)
{
    driver.findElements(By.cssSelector("h2 > a")).get(index).click();
}

public int GetProductCount()
{
    return driver.findElements(By.cssSelector("h2 > a")).size();
}


问:
How to save Date Time without the time?
How would i save the date time, with no time or preferably with a time stamp of 12:00, no matter what the time is at that moment?

I dont want to use .ToString("dd/MM/yyyy");, because it will open up a whole lot of new  possible errors.

答:
Use

```<code> DateTime.Now.Date
</code>```

or for myDate:

```<code> myDate.Date
</code>```

Title: How to save Date Time without the time?

Body:
Use

 DateTime.Now.Date

or for myDate:

 myDate.Date


问:
Reading into hashmap in c++
I'm working on a markov chain and have created a 2d hashmap that calculates the weighted probabilities.  The output of this works fine.

I'm looking to find the best way to output the next value.  The way I have it at the moment isn't working properly.  Ent1.first is the incoming midiNote.  Ent2.first is the potential outgoing value and Ent2.second is the weighted probability.

When midiNotecomes in, I need to look into the table and find the weighted probabilities and using rand() pick the next value.  One problem is that I only need this to happen once, not for every time in the for loop.  Here is a snippet of my table calculation for simplicity's sake, but if you'd like me to post the entire code let me know.

```<code>void getCountTable(int midiNote) {
    for(auto const &ent1: cdf) {
        midiNote = ent1.first;
        for (auto const &ent2: ent1.second) {
            //console out all resulting note transition weights
            //std::cout << "Note: " << ent1.first << std::endl <<"Next note: " << ent2.first <<std::endl << "Weight: " << ent2.second << std::endl << std::endl;

            //TRYING TO FIGURE HOW TO HANDLE THIS.  JUST WANT TO HAPPEN ONCE FOR EACH INCOMING VALUE

            //psuedo-random values between 0-1
            float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);

            //calculate next value
            if (r < ent2.second) {
                int output = ent2.first;
                std::cout << ent1.first << " " << output << std::endl;
            }
        }
    }
}
</code>```

答:
Currently you are creating a new random number each time around your inner loop and comparing it with the chance for that possibility. This will mean that sometimes one item will match (good), but sometimes you will get zero or two or more items matching (it is random).

One way to pick the just one possibility out of all the options is to generate one random number, then loop through the possibilities until the sum of all the possibilities so far is greater than the random number that you have generated.

Rearranging your code (untested)

```<code>    midiNote = ent1.first;
    //psuedo-random values between 0-1
    float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);
    float sum = 0;
    int output = 0;

    for (auto const &ent2: ent1.second){
       sum += ent2.second;
       if (sum >= r) {
          output = ent2.first;
          std::cout << ent1.first << " " << output << std::endl;
          break;
       }
   }
</code>```

This should work, although given the inexactness of floating point additions, it might be worth defaulting output to the last item of ent1.second if nothing is found (e.g. this might happen if sum ends up at 0.999, but r was 0.9999)

Title: Reading into hashmap in c++

Body:
I'm working on a markov chain and have created a 2d hashmap that calculates the weighted probabilities.  The output of this works fine.

I'm looking to find the best way to output the next value.  The way I have it at the moment isn't working properly.  Ent1.first is the incoming midiNote.  Ent2.first is the potential outgoing value and Ent2.second is the weighted probability.

When midiNotecomes in, I need to look into the table and find the weighted probabilities and using rand() pick the next value.  One problem is that I only need this to happen once, not for every time in the for loop.  Here is a snippet of my table calculation for simplicity's sake, but if you'd like me to post the entire code let me know.

void getCountTable(int midiNote) {
    for(auto const &ent1: cdf) {
        midiNote = ent1.first;
        for (auto const &ent2: ent1.second) {
            //console out all resulting note transition weights
            //std::cout << "Note: " << ent1.first << std::endl <<"Next note: " << ent2.first <<std::endl << "Weight: " << ent2.second << std::endl << std::endl;

            //TRYING TO FIGURE HOW TO HANDLE THIS.  JUST WANT TO HAPPEN ONCE FOR EACH INCOMING VALUE

            //psuedo-random values between 0-1
            float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);

            //calculate next value
            if (r < ent2.second) {
                int output = ent2.first;
                std::cout << ent1.first << " " << output << std::endl;
            }
        }
    }
}

Body:
Currently you are creating a new random number each time around your inner loop and comparing it with the chance for that possibility. This will mean that sometimes one item will match (good), but sometimes you will get zero or two or more items matching (it is random).

One way to pick the just one possibility out of all the options is to generate one random number, then loop through the possibilities until the sum of all the possibilities so far is greater than the random number that you have generated.

Rearranging your code (untested)

    midiNote = ent1.first;
    //psuedo-random values between 0-1
    float r = static_cast <float> (rand()) / static_cast<float> (RAND_MAX);
    float sum = 0;
    int output = 0;

    for (auto const &ent2: ent1.second){
       sum += ent2.second;
       if (sum >= r) {
          output = ent2.first;
          std::cout << ent1.first << " " << output << std::endl;
          break;
       }
   }

This should work, although given the inexactness of floating point additions, it might be worth defaulting output to the last item of ent1.second if nothing is found (e.g. this might happen if sum ends up at 0.999, but r was 0.9999)


问:
Scala Spark - How reduce a dataframe with many couple columns in a single couple columns?
i have a dataframe with many couple (count and score) columns.
This situation is not a pivot, but similar an unpivot.
Example:

```<code>|house_score | house_count | mobile_score | mobile_count | sport_score | sport_count | ....<other couple columns>.....|
|   20            2              48              6             6             78     |
|   40            78             47              74            69             6     |
</code>```

I want a new dateframe with only two columns, score e count. The new dataframe reduce all couple columns in a only couple columns.

```<code>_________________
| score | count |
|   20  |   2   |
|   40  |   78  |
|   48  |   6   |
|   47  |   74  |
|   6   |   78  |
|   69  |   6   |
|_______________|
</code>```

What's the best solution (elegant code/performance)?

答:
Using unionAlls as suggested in another answer will require you to scan the data multiple times and on each scan project the df to only 2 columns. From a performance perspective scanning the data multiple times should be avoided if you can do the work in 1 pass especially if you have large datasets that are not cacheable or you need to do many scans.

You can do it in 1 pass, by generating all the tuples (score, count) and then flat mapping them. I let you decide how elegant it is:

```<code>scala> :paste
// Entering paste mode (ctrl-D to finish)

val df = List((20,2,48,6,6,78), (40,78,47,74,69,6))
    .toDF("house_score", "house_count", "mobile_score", "mobile_count", "sport_score", "sport_count")

df.show

val result = df
    .flatMap(r => Range(0, 5, 2).map(i => (r.getInt(i), r.getInt(i + 1))))
    .toDF("score", "count")

result.show

// Exiting paste mode, now interpreting.

+-----------+-----------+------------+------------+-----------+-----------+
|house_score|house_count|mobile_score|mobile_count|sport_score|sport_count|
+-----------+-----------+------------+------------+-----------+-----------+
|         20|          2|          48|           6|          6|         78|
|         40|         78|          47|          74|         69|          6|
+-----------+-----------+------------+------------+-----------+-----------+

+-----+-----+
|score|count|
+-----+-----+
|   20|    2|
|   48|    6|
|    6|   78|
|   40|   78|
|   47|   74|
|   69|    6|
+-----+-----+

df: org.apache.spark.sql.DataFrame = [house_score: int, house_count: int ... 4 more fields]
result: org.apache.spark.sql.DataFrame = [score: int, count: int]
</code>```

Body:
i have a dataframe with many couple (count and score) columns.
This situation is not a pivot, but similar an unpivot.
Example:

|house_score | house_count | mobile_score | mobile_count | sport_score | sport_count | ....<other couple columns>.....|
|   20            2              48              6             6             78     |
|   40            78             47              74            69             6     |

I want a new dateframe with only two columns, score e count. The new dataframe reduce all couple columns in a only couple columns.

_________________
| score | count |
|   20  |   2   |
|   40  |   78  |
|   48  |   6   |
|   47  |   74  |
|   6   |   78  |
|   69  |   6   |
|_______________|

What's the best solution (elegant code/performance)?

Body:
Using unionAlls as suggested in another answer will require you to scan the data multiple times and on each scan project the df to only 2 columns. From a performance perspective scanning the data multiple times should be avoided if you can do the work in 1 pass especially if you have large datasets that are not cacheable or you need to do many scans.

You can do it in 1 pass, by generating all the tuples (score, count) and then flat mapping them. I let you decide how elegant it is:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val df = List((20,2,48,6,6,78), (40,78,47,74,69,6))
    .toDF("house_score", "house_count", "mobile_score", "mobile_count", "sport_score", "sport_count")

df.show

val result = df
    .flatMap(r => Range(0, 5, 2).map(i => (r.getInt(i), r.getInt(i + 1))))
    .toDF("score", "count")

result.show

// Exiting paste mode, now interpreting.

+-----------+-----------+------------+------------+-----------+-----------+
|house_score|house_count|mobile_score|mobile_count|sport_score|sport_count|
+-----------+-----------+------------+------------+-----------+-----------+
|         20|          2|          48|           6|          6|         78|
|         40|         78|          47|          74|         69|          6|
+-----------+-----------+------------+------------+-----------+-----------+

+-----+-----+
|score|count|
+-----+-----+
|   20|    2|
|   48|    6|
|    6|   78|
|   40|   78|
|   47|   74|
|   69|    6|
+-----+-----+

df: org.apache.spark.sql.DataFrame = [house_score: int, house_count: int ... 4 more fields]
result: org.apache.spark.sql.DataFrame = [score: int, count: int]


问:
Is there an equivalent to ALIAS/ANAME?
I am trying to get an SSL certificate on my custom domain on Heroku and the last thing it told me to do is add the following records:

```<code>Domain               Record Type  DNS Target
───────────────────  ───────────  ─────────────────────────────────
www.gethomesync.com  CNAME        www.gethomesync.com.herokudns.com
gethomesync.com      ALIAS/ANAME  gethomesync.com.herokudns.com
</code>```

But my domain registrar GoDaddy doesn't have an option to add ALIAS or ANAME. I don't know much about DNS having only done quite basic tasks as and when I've needed them, is there an equivalent to ALIAS/ANAME that I can use through GoDaddy?

Thanks

答:
You don't need to set up ALIAS/A record, just create a CNAME record pointing to gethomesync.herokussl.com (you can check the endpoint name with heroku certs Heroku Documentation):

Type  Name  Value

CNAME   www   gethomesync.com.herokudns.com

To create a naked domain (removes the need to write www) you need to forward your gethomesync.com to wwww.gethomesync.com:

Under Forwarding click on Domain -> 'Manage' -> then click 'Add Forwarding'

'Forward to' should be wwww.gethomesync.com (your domain)
'Redirect type' should be '301
'Forward settings' should be 'Forward only'

Title: Is there an equivalent to ALIAS/ANAME?

Body:
I am trying to get an SSL certificate on my custom domain on Heroku and the last thing it told me to do is add the following records:

Domain               Record Type  DNS Target
───────────────────  ───────────  ─────────────────────────────────
www.gethomesync.com  CNAME        www.gethomesync.com.herokudns.com
gethomesync.com      ALIAS/ANAME  gethomesync.com.herokudns.com

But my domain registrar GoDaddy doesn't have an option to add ALIAS or ANAME. I don't know much about DNS having only done quite basic tasks as and when I've needed them, is there an equivalent to ALIAS/ANAME that I can use through GoDaddy?

Thanks


问:
Calculate time between onLocationChanged method
I need to calculate time difference between every location change(onLocationChanged). What is a proper way to do that?

My code for getting user's location:

```<code>public class LocationService extends Service implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private DatabaseHelpers mDatabaseHelpers;

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
    mDatabaseHelpers = new DatabaseHelpers(LocationService.this);
}

public void buildGoogleApiClient() {
    createLocationRequest();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

private String getCurrentTimeStamp() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm");
    String format = simpleDateFormat.format(new Date());
    return format;
}

public void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("Location Service", "Started");
    buildGoogleApiClient();
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    // The service is no longer used and is being destroyed
    stopLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    startLocationUpdates();
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
</code>```

In the above code i am getting user's location just fine but i need to calculate time difference when onLocationChanged method gets called.

答:
Proper way ? Just use getTime() method of Location object.

Compare new and previous locations, then take the difference.

```<code>private Location mPrevLocation;

@Override
public void onLocationChanged(Location location) {
    if(mPrevLocation != null){
        long prevTime = mPrevLocation.getTime();
        long currentTime = location.getTime();

        // This is exactly what you want
        long diffTime = currentTime - prevTime ;
    }

    mPrevLocation = location;
}
</code>```

Body:
I need to calculate time difference between every location change(onLocationChanged). What is a proper way to do that?

My code for getting user's location:

public class LocationService extends Service implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private DatabaseHelpers mDatabaseHelpers;

private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }
}

@Override
public void onCreate() {
    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
    mDatabaseHelpers = new DatabaseHelpers(LocationService.this);
}

public void buildGoogleApiClient() {
    createLocationRequest();
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
}

protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

private String getCurrentTimeStamp() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy-HH-mm");
    String format = simpleDateFormat.format(new Date());
    return format;
}

public void startLocationUpdates() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
    mGoogleApiClient.disconnect();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("Location Service", "Started");
    buildGoogleApiClient();
    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    // The service is no longer used and is being destroyed
    stopLocationUpdates();
}

@Override
public void onLocationChanged(Location location) {
}
@Override
public void onConnected(@Nullable Bundle bundle) {
    startLocationUpdates();
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}

In the above code i am getting user's location just fine but i need to calculate time difference when onLocationChanged method gets called.

Body:
Proper way ? Just use getTime() method of Location object.

Compare new and previous locations, then take the difference.

private Location mPrevLocation;

@Override
public void onLocationChanged(Location location) {
    if(mPrevLocation != null){
        long prevTime = mPrevLocation.getTime();
        long currentTime = location.getTime();

        // This is exactly what you want
        long diffTime = currentTime - prevTime ;
    }

    mPrevLocation = location;
}