问:
Python - Write for loop output to file
I have a function that outputs a list of IPs.

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))
</code>```

The output usually looks like
Below are the IPs for CSDP_LAB_STAGING

```<code>172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51
</code>```

Now I want to write this output to file.

What I have done is

```<code>def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()
</code>```

But the above code only writes the very last IP to test.txt. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ?

P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.

答:
```<code>def convertHostNamesToIps(hostnames):
ip = server.system.search.hostname(sessionKey, hostnames )
iplist = [] # Make a temporal list.
for ips in ip:
    print (ips.get('ip')) # This only print your ips, it isn't necesary.
    iplist.append(ips.get('ip')) # Add the current ip in the list.
with open("test.txt","w") as txt: # Open the file but when you finish to use the file it will automatically close.
    txt.writelines(iplist)
</code>```

I hope this will help you.

Title: Python - Write for loop output to file

Body:
I have a function that outputs a list of IPs.

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    for ips in ip:
        print (ips.get('ip'))

The output usually looks like
Below are the IPs for CSDP_LAB_STAGING

172.29.219.123
172.29.225.5
172.29.240.174
172.29.225.46
172.29.240.171
172.29.240.175
172.29.219.119
172.29.219.117
172.29.219.33
172.29.219.35
.
.
.
172.29.219.40
172.29.219.35
172.29.219.40
172.29.219.118
172.29.219.121
172.29.219.115
172.29.225.51

Now I want to write this output to file.

What I have done is

def convertHostNamesToIps(hostnames):
    ip = server.system.search.hostname(sessionKey, hostnames )
    sys.stdout=open("test.txt","w")
    for ips in ip:
        print (ips.get('ip'))
    sys.stdout.close()

But the above code only writes the very last IP to test.txt. I thought I might be messing up the indentation but that hasent helped me. Is there something else I am missing ?

P.S. This is my first ever python script so forgive me if Ive done something extremely stupid.

Body:
def convertHostNamesToIps(hostnames):
ip = server.system.search.hostname(sessionKey, hostnames )
iplist = [] # Make a temporal list.
for ips in ip:
    print (ips.get('ip')) # This only print your ips, it isn't necesary.
    iplist.append(ips.get('ip')) # Add the current ip in the list.
with open("test.txt","w") as txt: # Open the file but when you finish to use the file it will automatically close.
    txt.writelines(iplist)

I hope this will help you.


来源: stackexchange

问:
What do C# event parameters do?
I don't understand what event parameters do in C#. Let's say we have a button called CoffeeButton, and clicking on it takes you to another Page called Coffee using a Frame called myFrame.
This is my code:

```<code>private void CoffeButton_Click(object sender, RoutedEventArgs e)
{
     MyFrame.Navigate(typeof(Coffee));
}
</code>```

What does object sender and RoutedEventArgs e do in this case?

Examples would be great!

答:
Normally, "sender" will be a reference to whatever object fired the event.  So if, for example, you have more than one Button that all wire into the same button_Click handler function, the sender object would be a reference to whichever actual Button object was clicked.

The EventArgs object that's normally passed in as the second parameter is used for different things depending on the context.  Generally, it's used to pass you additional information related to the event that happened.  For example, in this case, the RouteEventArgs object provides a RoutedEvent property that you can look at if you need to.

ContentLicense: CC BY-SA 3.0

Title: What do C# event parameters do?

Body:
I don't understand what event parameters do in C#. Let's say we have a button called CoffeeButton, and clicking on it takes you to another Page called Coffee using a Frame called myFrame.
This is my code:

private void CoffeButton_Click(object sender, RoutedEventArgs e)
{
     MyFrame.Navigate(typeof(Coffee));
}

What does object sender and RoutedEventArgs e do in this case?

Examples would be great!


问:
Sort numbers then strings C#
I want to this list

```<code>A
B
C
111
11
123
1
42
5
</code>```

To be sorted

```<code>1
5
11
42
111
123
A
B
C
</code>```

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

答:
I've created a solution for this. I've divided the list into two part then sort and concat. Please check below:

```<code>public List<ListItem> getSortedList()
{
    int dummy = 0;

    List<ListItem> list = new List<ListItem>();
    list.Add(new ListItem() { Item = "A" });
    list.Add(new ListItem() { Item = "B" });
    list.Add(new ListItem() { Item = "C" });
    list.Add(new ListItem() { Item = "111" });
    list.Add(new ListItem() { Item = "11" });
    list.Add(new ListItem() { Item = "123" });
    list.Add(new ListItem() { Item = "1" });
    list.Add(new ListItem() { Item = "42" });
    list.Add(new ListItem() { Item = "5" });

    var listNumber = list.Where(m => int.TryParse(m.Item, out dummy)).ToList().OrderBy(m => Convert.ToInt16(m.Item)).ToList();
    var listString = list.Where(m => !int.TryParse(m.Item, out dummy)).ToList().OrderBy(m => m.Item).ToList();

    var sortedList = listNumber.Concat(listString).ToList();

    return sortedList;
}
</code>```

You can run this in DotNetFiddle.

Title: Sort numbers then strings C#

Body:
I want to this list

A
B
C
111
11
123
1
42
5

To be sorted

1
5
11
42
111
123
A
B
C

By default, it sorts numbers like strings (So, it goes 1,11,111,123,42,5),
But I want to sort numbers like numbers, and than strings that are not numbers.

Is there clean solution to sort it like above?

It is a list of objects, and object has several properties, one of which is a this string.

Body:
I've created a solution for this. I've divided the list into two part then sort and concat. Please check below:

public List<ListItem> getSortedList()
{
    int dummy = 0;

    List<ListItem> list = new List<ListItem>();
    list.Add(new ListItem() { Item = "A" });
    list.Add(new ListItem() { Item = "B" });
    list.Add(new ListItem() { Item = "C" });
    list.Add(new ListItem() { Item = "111" });
    list.Add(new ListItem() { Item = "11" });
    list.Add(new ListItem() { Item = "123" });
    list.Add(new ListItem() { Item = "1" });
    list.Add(new ListItem() { Item = "42" });
    list.Add(new ListItem() { Item = "5" });

    var listNumber = list.Where(m => int.TryParse(m.Item, out dummy)).ToList().OrderBy(m => Convert.ToInt16(m.Item)).ToList();
    var listString = list.Where(m => !int.TryParse(m.Item, out dummy)).ToList().OrderBy(m => m.Item).ToList();

    var sortedList = listNumber.Concat(listString).ToList();

    return sortedList;
}

You can run this in DotNetFiddle.


问:
Why are Rails scopes preferable, if messy controllers are faster?
I've been trying to chain Arel queries using scopes, instead of just using some long-winded logic I wrote in the controller. But the scopes are slower than just getting all the records and then sifting through them with some logic. I'm wondering, then, why scopes are better.

Here's what I'm doing:

a question has many answers

an answer belongs to one question

a question has a "question_type" column that I use to sort it

First, the scopes way...

in question.rb:

```<code>scope :answered, joins(:answers).order('answers.created_at desc')
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")
</code>```

in questions_controller.rb:

```<code>@dogs_recently_answered = Question.answered.dogs.uniq[0..9]
@cats_recently_answered = Question.answered.cats.uniq[0..9]
@mermaids_recently_answered = Question.answered.mermaids.uniq[0..9]
</code>```

Then in the view, I cycle through those instance variables (which are now arrays containing at most 10 elements) and display the results.

Here are the times it takes to load the page (five different times):

Completed 200 OK in 535ms (Views: 189.6ms | ActiveRecord: 46.2ms)

Completed 200 OK in 573ms (Views: 186.0ms | ActiveRecord: 46.3ms)

Completed 200 OK in 577ms (Views: 189.0ms | ActiveRecord: 45.6ms)

Completed 200 OK in 532ms (Views: 182.9ms | ActiveRecord: 46.1ms)

Completed 200 OK in 577ms (Views: 186.7ms | ActiveRecord: 46.9ms)

Now, the messy controller way...

```<code>@answers = Answer.order("created_at desc")
@all_answered = []
@answers.each {|answer| @all_answered << answer.question}
@recently_answered = @all_answered.uniq
@dogs_all_answered = []
@cats_all_answered = []
@mermaids_all_answered = []
@recently_answered.each do |q|
  if q.question_type == "dogs"
    @dogs_all_answered << q
    @dogs_recently_answered = @dogs_all_answered[0..9]
  elsif q.question_type == "cats"
    @cats_all_answered << q
    @cats_recently_answered = @cats_all_answered[0..9]
  elsif q.question_type == "mermaids"
    @mermaids_all_answered << q
    @mermaids_recently_answered = @mermaids_all_answered[0..9]
  end
end
</code>```

And here are the times it takes to load the page now (five different times):

Completed 200 OK in 475ms (Views: 196.5ms | ActiveRecord: 34.5ms)

Completed 200 OK in 480ms (Views: 200.4ms | ActiveRecord: 36.4ms)

Completed 200 OK in 434ms (Views: 198.2ms | ActiveRecord: 35.8ms)

Completed 200 OK in 475ms (Views: 194.2ms | ActiveRecord: 36.4ms)

Completed 200 OK in 475ms (Views: 195.0ms | ActiveRecord: 35.4ms)

So...

Aside from readability, what's to be won by honing the query with a scope? Does it eventually become quicker when there are more records?

答:
First, I'm not sure I understand how a question can be other than unique, so I'd look at trying to remove that. I don't know the logic of your data, so that might not be applicable, but it's an extra step that you might be able to avoid.

Here's how I would approach it:

```<code>scope :answered, joins(:answers).order('answers.created_at desc')
scope :recent, take(10)
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")

@dogs_recently_answered = Question.answered.dogs.recent
@cats_recently_answered = Question.answered.dogs.recent
@mermaids_recently_answered = Question.answered.dogs.recent
</code>```

This shifts the TOP portion of the query to the database where it belongs rather than fetching all of the rows and then discarding all but 10. Depending on your uniquing criteria, you might also use a scope like

```<code>scope :unique, select('DISTINCT column_name')
</code>```

and then you can use Question.cats.unique.recent and get it all in one fast query that leverages the relational algebra that database systems are designed for.

ContentLicense: CC BY-SA 2.5

Body:
I've been trying to chain Arel queries using scopes, instead of just using some long-winded logic I wrote in the controller. But the scopes are slower than just getting all the records and then sifting through them with some logic. I'm wondering, then, why scopes are better.

Here's what I'm doing:

a question has many answers

an answer belongs to one question

a question has a "question_type" column that I use to sort it

First, the scopes way...

in question.rb:

scope :answered, joins(:answers).order('answers.created_at desc')
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")

in questions_controller.rb:

@dogs_recently_answered = Question.answered.dogs.uniq[0..9]
@cats_recently_answered = Question.answered.cats.uniq[0..9]
@mermaids_recently_answered = Question.answered.mermaids.uniq[0..9]

Then in the view, I cycle through those instance variables (which are now arrays containing at most 10 elements) and display the results.

Here are the times it takes to load the page (five different times):

Completed 200 OK in 535ms (Views: 189.6ms | ActiveRecord: 46.2ms)

Completed 200 OK in 573ms (Views: 186.0ms | ActiveRecord: 46.3ms)

Completed 200 OK in 577ms (Views: 189.0ms | ActiveRecord: 45.6ms)

Completed 200 OK in 532ms (Views: 182.9ms | ActiveRecord: 46.1ms)

Completed 200 OK in 577ms (Views: 186.7ms | ActiveRecord: 46.9ms)

Now, the messy controller way...

@answers = Answer.order("created_at desc")
@all_answered = []
@answers.each {|answer| @all_answered << answer.question}
@recently_answered = @all_answered.uniq
@dogs_all_answered = []
@cats_all_answered = []
@mermaids_all_answered = []
@recently_answered.each do |q|
  if q.question_type == "dogs"
    @dogs_all_answered << q
    @dogs_recently_answered = @dogs_all_answered[0..9]
  elsif q.question_type == "cats"
    @cats_all_answered << q
    @cats_recently_answered = @cats_all_answered[0..9]
  elsif q.question_type == "mermaids"
    @mermaids_all_answered << q
    @mermaids_recently_answered = @mermaids_all_answered[0..9]
  end
end

And here are the times it takes to load the page now (five different times):

Completed 200 OK in 475ms (Views: 196.5ms | ActiveRecord: 34.5ms)

Completed 200 OK in 480ms (Views: 200.4ms | ActiveRecord: 36.4ms)

Completed 200 OK in 434ms (Views: 198.2ms | ActiveRecord: 35.8ms)

Completed 200 OK in 475ms (Views: 194.2ms | ActiveRecord: 36.4ms)

Completed 200 OK in 475ms (Views: 195.0ms | ActiveRecord: 35.4ms)

So...

Aside from readability, what's to be won by honing the query with a scope? Does it eventually become quicker when there are more records?

Body:
First, I'm not sure I understand how a question can be other than unique, so I'd look at trying to remove that. I don't know the logic of your data, so that might not be applicable, but it's an extra step that you might be able to avoid.

Here's how I would approach it:

scope :answered, joins(:answers).order('answers.created_at desc')
scope :recent, take(10)
scope :dogs, where(:question_type => "dogs")
scope :cats, where(:question_type => "cats")
scope :mermaids, where(:question_type => "mermaids")

@dogs_recently_answered = Question.answered.dogs.recent
@cats_recently_answered = Question.answered.dogs.recent
@mermaids_recently_answered = Question.answered.dogs.recent

This shifts the TOP portion of the query to the database where it belongs rather than fetching all of the rows and then discarding all but 10. Depending on your uniquing criteria, you might also use a scope like

scope :unique, select('DISTINCT column_name')

and then you can use Question.cats.unique.recent and get it all in one fast query that leverages the relational algebra that database systems are designed for.


问:
triplet sum using binary search
I was thinking of various approaches for finding the triplet sum and I came across this finding a triplet having a given sum. So I thought of giving it a try.

```<code>My algorithm:
1) Sort the numbers //O(nlogn)
2) Initialize low=0 and high=size-1
3) loop till low<high
   a) if sum-arr[high]-arr[low]< 0 , then decrement high
   b) if third number is not in range of (low,high) then break the loop
   c) else search for third number using binary search
</code>```

But I am not getting correct output. I don't know where my logic is wrong because its pretty much simple binary search. Below is what I have implemented.
Please let me know my mistake

```<code>static boolean isTriplet(int a[], int size, int sum)
    {
       Arrays.sort(a);  //sort the numbers

        int low = 0;
        int high = size-1;
        while(low<high)
        {

            int third = sum - a[high] - a[low];
            if(third<0)
                high--;
            else if(!(sum - a[high] - a[low]>a[low] && sum - a[high] - a[low]< a[high]))  //if the number is not within the range then no need to find the index
                break;
            else
            {
                int index = binarySearch(a,low+1,high-1,third);
                if(index != -1)
                {
                    System.out.println(a[low]+" "+a[index]+" "+a[high]);
                    return true;
                }
                else
                low++;

            }

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

I tried it with input {1,2,3,4,5,6}  and sum=6 but it returns false and when input was {3,4,8,1,2,7,5} and sum=20 it returned true

答:
I partially understood your idea, not completely. It seems like you are trying to solve the problem in O(n log(n)) time complexity and I am not confident that it is possible. I am not sure how you decide to do this:

```<code>           else
            low++;
</code>```

I doubt that in some cases maybe you should do

```<code>high--
</code>```

there. Also I am not sure about this piece of code:

```<code>if(third<0)
   high--;
</code>```

What if third > 0, but it's less than low?

I read the other question and it proposes a O(n^2 logn) solution, so I provided here such a solution (in Java).

The idea is: iterate with 2 nested for loops (i, j) through all pairs of elements and look up for the third element which would complement the triplet in the rest of the array (that lookup is done using binary search - the while loop.

```<code>public class TripletSum {
    static boolean solve(int[] a, int k) {
        Arrays.sort(a);
        int n = a.length;

        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                int low = j + 1, high = n - 1;

                while(low <= high) {
                    int middle = (low + high) / 2;
                    int sum = a[middle] + a[i] + a[j];
                    if(sum == k) {
                        return true;
                    }
                    if(sum > k) {
                        high = middle - 1;
                    }
                    if(sum < k) {
                        low = middle + 1;
                    }
                }

            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6};

        System.out.println(solve(a, 20));
    }
}
</code>```

EDIT:
I did some research and couldn't find a O(N logN) solution for this problem. Turns out this problem is popular as 3SUM. You can see on the Wiki page there is a Quadratic solution which beats the O(N^2 logN).

Title: triplet sum using binary search

Body:
I was thinking of various approaches for finding the triplet sum and I came across this finding a triplet having a given sum. So I thought of giving it a try.

My algorithm:
1) Sort the numbers //O(nlogn)
2) Initialize low=0 and high=size-1
3) loop till low<high
   a) if sum-arr[high]-arr[low]< 0 , then decrement high
   b) if third number is not in range of (low,high) then break the loop
   c) else search for third number using binary search

But I am not getting correct output. I don't know where my logic is wrong because its pretty much simple binary search. Below is what I have implemented.
Please let me know my mistake

static boolean isTriplet(int a[], int size, int sum)
    {
       Arrays.sort(a);  //sort the numbers

        int low = 0;
        int high = size-1;
        while(low<high)
        {

            int third = sum - a[high] - a[low];
            if(third<0)
                high--;
            else if(!(sum - a[high] - a[low]>a[low] && sum - a[high] - a[low]< a[high]))  //if the number is not within the range then no need to find the index
                break;
            else
            {
                int index = binarySearch(a,low+1,high-1,third);
                if(index != -1)
                {
                    System.out.println(a[low]+" "+a[index]+" "+a[high]);
                    return true;
                }
                else
                low++;

            }

        }
        return false;
    }

I tried it with input {1,2,3,4,5,6}  and sum=6 but it returns false and when input was {3,4,8,1,2,7,5} and sum=20 it returned true

Body:
I partially understood your idea, not completely. It seems like you are trying to solve the problem in O(n log(n)) time complexity and I am not confident that it is possible. I am not sure how you decide to do this:

           else
            low++;

I doubt that in some cases maybe you should do

high--

there. Also I am not sure about this piece of code:

if(third<0)
   high--;

What if third > 0, but it's less than low?

I read the other question and it proposes a O(n^2 logn) solution, so I provided here such a solution (in Java).

The idea is: iterate with 2 nested for loops (i, j) through all pairs of elements and look up for the third element which would complement the triplet in the rest of the array (that lookup is done using binary search - the while loop.

public class TripletSum {
    static boolean solve(int[] a, int k) {
        Arrays.sort(a);
        int n = a.length;

        for(int i = 0; i < n; i++) {
            for(int j = i + 1; j < n; j++) {
                int low = j + 1, high = n - 1;

                while(low <= high) {
                    int middle = (low + high) / 2;
                    int sum = a[middle] + a[i] + a[j];
                    if(sum == k) {
                        return true;
                    }
                    if(sum > k) {
                        high = middle - 1;
                    }
                    if(sum < k) {
                        low = middle + 1;
                    }
                }

            }
        }

        return false;
    }

    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6};

        System.out.println(solve(a, 20));
    }
}

EDIT:
I did some research and couldn't find a O(N logN) solution for this problem. Turns out this problem is popular as 3SUM. You can see on the Wiki page there is a Quadratic solution which beats the O(N^2 logN).


问:
EJS Tags with ChartJS?
Is it possible to use EJS tags to add data to a graph? Here is my current graph's data:

```<code>var canvas = document.getElementById('myChart');
var data = {
    labels: ["One", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [10, 20, 81, 56, 55, 40],
        }
    ]
};
</code>```

I'm wanting to do something like this:

```<code>labels: ["<%= currentUser.datapoint1 %>", "<%= currentUser.datapoint2 %>", "<%= currentUser.datapoint3 %>"]

data: [<%= currentUser.datapoint10 %>, <%= currentUser.datapoint11 %>]
</code>```

How would I accomplish using EJS tags to populate the graphs data? (NOTE: The EJS tag info would have already been saved the user before the chart needs to be generated)

答:
The easiest way is to use JSON.stringify() in EJS tags. You can do

```<code>labels: <%- JSON.stringify(data.labels); %>,
data: <%- JSON.stringify(data.datasets.data); %>
</code>```

It's based on your data variable. So, you may need to adjust this code accordingly.

Title: EJS Tags with ChartJS?

Body:
Is it possible to use EJS tags to add data to a graph? Here is my current graph's data:

var canvas = document.getElementById('myChart');
var data = {
    labels: ["One", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            backgroundColor: "rgba(255,99,132,0.2)",
            borderColor: "rgba(255,99,132,1)",
            borderWidth: 2,
            hoverBackgroundColor: "rgba(255,99,132,0.4)",
            hoverBorderColor: "rgba(255,99,132,1)",
            data: [10, 20, 81, 56, 55, 40],
        }
    ]
};

I'm wanting to do something like this:

labels: ["<%= currentUser.datapoint1 %>", "<%= currentUser.datapoint2 %>", "<%= currentUser.datapoint3 %>"]

data: [<%= currentUser.datapoint10 %>, <%= currentUser.datapoint11 %>]

How would I accomplish using EJS tags to populate the graphs data? (NOTE: The EJS tag info would have already been saved the user before the chart needs to be generated)

Body:
The easiest way is to use JSON.stringify() in EJS tags. You can do

labels: <%- JSON.stringify(data.labels); %>,
data: <%- JSON.stringify(data.datasets.data); %>

It's based on your data variable. So, you may need to adjust this code accordingly.


问:
how to write java 8 Comparator for Map values inside Map.Entry
Here is what I have, I want to sort in descending a the value in the entry.

```<code>Map<String, Outer> outer = Input
                          .entrySet()
                          .stream
                          .collect(toMap(Map.Entry::getKey, entry->{
                           List<Outer> inner = entry
                                    .getValue()
                                    .stream()
                                    .sorted(Comparator.comparingDouble(???))
                              })) ... (more lines of code.)
</code>```

How to write a Comparator with sorted.
If want to do the following inside sorted

```<code>if (o1.getSomething() > o2.getSomething())
     return -1;
if (o1.getSomething() < o2.getSomething())
     return 1;
return 0;
</code>```

After getting the List and sorting it works for me.

```<code>inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
         return -1;
    if (o1.getSomething() < o2.getSomething())
         return 1;
    return 0;
});
</code>```

But is there a way to use stream.sorted( " use the same comparator logic here") inside entry.

Entry is an ArrayList, with bunch of values.

```<code>entry:[{w:1},{w:2},{w:3},{w:4}];
</code>```

So I want to reverse sort this, to be as follows:

```<code>entry:[{w:4},{w:3},{w:2},{w:1}];
</code>```

so the final list I get is a sorted in reverse order one.

sry for the confusion.

答:
So here is the answer that worked for me.

```<code>.sorted(reverseOrder(comparingDouble(Input::getSomething)))
</code>```

Thanks everyone,

Body:
Here is what I have, I want to sort in descending a the value in the entry.

Map<String, Outer> outer = Input
                          .entrySet()
                          .stream
                          .collect(toMap(Map.Entry::getKey, entry->{
                           List<Outer> inner = entry
                                    .getValue()
                                    .stream()
                                    .sorted(Comparator.comparingDouble(???))
                              })) ... (more lines of code.)

How to write a Comparator with sorted.
If want to do the following inside sorted

if (o1.getSomething() > o2.getSomething())
     return -1;
if (o1.getSomething() < o2.getSomething())
     return 1;
return 0;

After getting the List and sorting it works for me.

inner.sort((Outer o1, Outer o2) -> {
if (o1.getSomething() > o2.getSomething())
         return -1;
    if (o1.getSomething() < o2.getSomething())
         return 1;
    return 0;
});

But is there a way to use stream.sorted( " use the same comparator logic here") inside entry.

Entry is an ArrayList, with bunch of values.

entry:[{w:1},{w:2},{w:3},{w:4}];

So I want to reverse sort this, to be as follows:

entry:[{w:4},{w:3},{w:2},{w:1}];

so the final list I get is a sorted in reverse order one.

sry for the confusion.

Body:
So here is the answer that worked for me.

.sorted(reverseOrder(comparingDouble(Input::getSomething)))

Thanks everyone,


问:
Spring boot + Jersey parse Response JSON data
I am trying to build a simple page the will display some places on the map. I'm really new to rest in Java and i'm using Spring boot + jersey framework.

I'm using google places api to search for places, i made the GET respond for a lat/lng that i'm passing thru PostMan:

```<code>http://localhost:9000/res/-23.558712/-46.592235
</code>```

Inside the code im calling:

```<code>@GET
@Path("/{lat}/{lng}")
@Produces("application/json")
public void getBook(@PathParam("lat") String lat,@PathParam("lng") String lng) {
    this.lat = lat;
    this.lng = lng;
    getdata();
}
public static void getdata(){
    Client client = ClientBuilder.newClient();
    String entity = client.target("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+ lat + "," + lng + "&radius=5000&types=market&name=dia&key=MY_KEY")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .header("some-header", "true")
            .get(String.class);
    System.out.println(entity);
}
</code>```

And i get a really big Json in the response:

```<code>"results" : [
  {
     "geometry" : {
        "location" : {
           "lat" : -23.5703071,
           "lng" : -46.58153289999999
        },
        "viewport" : {
           "northeast" : {
              "lat" : -23.56895811970849,
              "lng" : -46.5801839197085
           },
           "southwest" : {
              "lat" : -23.5716560802915,
              "lng" : -46.58288188029149
           }
        }
     },....
</code>```

And much more, my question is, how do i parse this JSON response to away that i can manage data? I want to get, name, location... to plot on the map.
I will have to create a model class with all response parameters?

I really don't know if this is all wrong.

答: This resource falls under reverse geocoding and if you need name of the location you should get it from "fromatted_address" attiribute, and address components will give you exact address. The following link has some information which might help you further.   [reverse geocoding] https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding</p>

Body:
I am trying to build a simple page the will display some places on the map. I'm really new to rest in Java and i'm using Spring boot + jersey framework.

I'm using google places api to search for places, i made the GET respond for a lat/lng that i'm passing thru PostMan:

http://localhost:9000/res/-23.558712/-46.592235

Inside the code im calling:

@GET
@Path("/{lat}/{lng}")
@Produces("application/json")
public void getBook(@PathParam("lat") String lat,@PathParam("lng") String lng) {
    this.lat = lat;
    this.lng = lng;
    getdata();
}
public static void getdata(){
    Client client = ClientBuilder.newClient();
    String entity = client.target("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+ lat + "," + lng + "&radius=5000&types=market&name=dia&key=MY_KEY")
            .request(MediaType.TEXT_PLAIN_TYPE)
            .header("some-header", "true")
            .get(String.class);
    System.out.println(entity);
}

And i get a really big Json in the response:

"results" : [
  {
     "geometry" : {
        "location" : {
           "lat" : -23.5703071,
           "lng" : -46.58153289999999
        },
        "viewport" : {
           "northeast" : {
              "lat" : -23.56895811970849,
              "lng" : -46.5801839197085
           },
           "southwest" : {
              "lat" : -23.5716560802915,
              "lng" : -46.58288188029149
           }
        }
     },....

And much more, my question is, how do i parse this JSON response to away that i can manage data? I want to get, name, location... to plot on the map.
I will have to create a model class with all response parameters?

I really don't know if this is all wrong.


问:
Arrange two full sized divs below each other
I have two divs like following:

```<code><div class="div-one">
 <p>Div 1</p>
</div>
<div class="div-two">
 <p>Div 2</p>
</div>
</code>```

And in my css:

```<code>.div-one{
  position: fixed;
  width: 100%;
  min-height: 100%;
}
.div-two{
  position: relative;
  width: 100%;
  min-height: 100%;
}
</code>```

I want to arrange these two divs bellow each other and each one of them occupies full screen (imagine a landing page). At a time only one div is visible on the screen and then user can scroll to see the other.

How can I achieve this?

答:
On way you can do this is with viewport relative units:

```<code>.div-one {
  min-height: 100vh;
}
.div-two {
  min-height: 100vh;
}
</code>```

1vh is equal to 1% of the viewport height. 1vw is equal to 1% of the viewport width. (also vmin is the lesser of the two vmax for the greater.) These are supported in most but not all modern browsers. So you might want to provide a reasonable fallback value:

```<code>.div-one {
  min-height: 500px;
  min-height: 100vh;
}
.div-two {
  min-height: 500px;
  min-height: 100vh;
}
</code>```

You don’t need the widths, as block-level elements are already width auto (which will basically be 100%), and you probably don’t want to use positioning if they are to flow normally in the page, one after the other.

Body:
I have two divs like following:

Div 1

Div 2

And in my css:

.div-one{
  position: fixed;
  width: 100%;
  min-height: 100%;
}
.div-two{
  position: relative;
  width: 100%;
  min-height: 100%;
}

I want to arrange these two divs bellow each other and each one of them occupies full screen (imagine a landing page). At a time only one div is visible on the screen and then user can scroll to see the other.

How can I achieve this?

Body:
On way you can do this is with viewport relative units:

.div-one {
  min-height: 100vh;
}
.div-two {
  min-height: 100vh;
}

1vh is equal to 1% of the viewport height. 1vw is equal to 1% of the viewport width. (also vmin is the lesser of the two vmax for the greater.) These are supported in most but not all modern browsers. So you might want to provide a reasonable fallback value:

.div-one {
  min-height: 500px;
  min-height: 100vh;
}
.div-two {
  min-height: 500px;
  min-height: 100vh;
}

You don’t need the widths, as block-level elements are already width auto (which will basically be 100%), and you probably don’t want to use positioning if they are to flow normally in the page, one after the other.


问:
Buttons not visible on the application. What's wrong?
I created an empty activity for 'My Testing App' and it looks like the following in the preview section:

But when I generated a build apk and used the same in my cell phone the result was like the following:

I can only view the exit button on the very top left but the two other buttons, that should be above it are missing.
I tried to rearrange the icons on the screen as well. I made them to go to the bottom, to the right most, but I see no change when the apk is reinstalled.

How do I make them visible on the hardware?

Here is the snap of the code for this activity:

答:
https://developer.android.com/training/constraint-layout/index.html

Start by reading this. Most of what you need is answered here. The problem is that your views are not properly constrained (basically they aren't linked to anything so when you run your app it doesn't know where to place them and just defaults to the upper left).


问:
Getting 'too many parameters passed' to stored procedure on ASPX page
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

```<code>"Procedure or function <sp_name> has too many arguments specified."
</code>```

Here is the code for the grid and the datasource:

```<code><asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>
</code>```

Here's the code from the stored procedure:

```<code>ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END
</code>```

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

```<code>        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }
</code>```

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?

答:
Try adding a SQLDataSource.Selecting event handler and check what parameters are passed to the stored procedure. The parameters can be found in SqlDataSourceSelectingEventArgs.Arguments.

The GridView might be passing unexpected parameters to the SP.

Body:
I'm having trouble figuring this error out. I have a grid on an ASPX page that displays data from a stored procedure in an SQL Server 2008 database. When the page loads, I get the following error:

"Procedure or function <sp_name> has too many arguments specified."

Here is the code for the grid and the datasource:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        DataSourceID="SqlDataSource1" ShowFooter="True" OnRowDataBound="GridView1_RowDataBound"
        AllowSorting="True">
        <Columns>
            <asp:BoundField DataField="MerchantID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
                SortExpression="MerchantID" />
            <asp:BoundField DataField="MerchantName" HeaderText="Merchant" SortExpression="MerchantName" />
            <asp:BoundField DataField="RapidTuitionID" HeaderText="RapidTuition ID" SortExpression="RapidTuitionID" />
            <asp:BoundField DataField="DateCreated" HeaderText="Enrolled" SortExpression="DateCreated" />
            <asp:TemplateField HeaderText="Commands">
                <ItemTemplate>
                    <asp:LinkButton ID="ImpersonateUserLinkButton" runat="server" OnClick="Command_Click"
                        CommandName="impersonate" CommandArgument='<%# Eval("MerchantID") %>' CssClass="table_command">Impersonate</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EmptyDataTemplate>
            No data to display.
        </EmptyDataTemplate>
        <PagerStyle CssClass="pager" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Development %>"
        SelectCommand="sp_GatewayMerchants" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StartDate" Name="StartDate"
                DefaultValue="1/1/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$EndDate" Name="EndDate"
                DefaultValue="12/31/2010" PropertyName="Text" Type="DateTime" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusActive" DefaultValue="true"
                Name="StatusActive" PropertyName="Checked" Type="Boolean" />
            <asp:ControlParameter ControlID="PromotionPlaceHolderTop$StatusDeactive" DefaultValue="true"
                Name="StatusDeactive" PropertyName="Checked" Type="Boolean" />
        </SelectParameters>
    </asp:SqlDataSource>

Here's the code from the stored procedure:

ALTER PROCEDURE [dbo].[sp_GatewayMerchants]
    -- Add the parameters for the stored procedure here
    @StartDate DateTime,
    @EndDate DateTime,
    @StatusActive bit,
    @StatusDeactive bit
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    SELECT
        m.MerchantID AS [ID],
        m.MerchantName,
        CASE m.StatusFlag WHEN 1 THEN 'Active' ELSE 'Deactive' END AS [Status],
        m.RapidTuitionID,
        m.DateCreated
    FROM
        Merchant m
    WHERE
        (CONVERT(varchar,m.DateCreated,112) BETWEEN CONVERT(varchar,CONVERT(DATETIME,@StartDate,101),112) AND CONVERT(varchar,CONVERT(DATETIME,@EndDate,101),112))
        AND
        (
            (@StatusActive = 1 AND m.StatusFlag = 1)
            OR
            (@StatusDeactive = 1 AND m.StatusFlag = 0)
        )
    ORDER BY
        m.MerchantName
END

The datasource is passing 4 parameters, and the stored procedure is accepting 4, but when the page displays I get the error mentioned above. Am I missing something here?

EDIT: Here's the code behind for the template column. But I'm not sure how this could be causing extra parameters to the SP.

        protected void Command_Click(object sender, EventArgs e)
    {
        var merchantID = Convert.ToInt32(((LinkButton)sender).CommandArgument);

        switch (((LinkButton)sender).CommandName)
        {
            case "impersonate":
                var gs = GatewaySession.Parse(Page.User.Identity.Name);
                gs.Role = GatewaySession.RoleEnum.Merchant;
                gs.MerchantID = merchantID;
                gs.CustomerID = -1;

                FormsAuthentication.SetAuthCookie(gs.ToString(), false);

                Page.Session["MerchantID"] = gs.MerchantID;

                Response.Redirect("/Merchant/Default.aspx");
                break;
        }
    }

If I remove the ASP:LINKBUTTON the code works. So why would a LINKBUTTON be causing this?


问:
Android Espresso doesn't wait for fragments to load
I'm just getting started with Espresso for testing Android apps, but I'm having some trouble. I have an Activity with a button that replaces a fragment in the usual way:

```<code>public void onClick(View v) {
    final FragmentTransaction t = getFragmentManager().beginTransaction();
    t.setCustomAnimations(R.animator.fragment_slide_in_up, 0);
    t.replace(R.id.fragment_container,
        LogInFragment.newInstance(), LogInFragment.TAG)
        .addToBackStack(LogInFragment.TAG);
    t.commit();
}
</code>```

In my test, I click the button that sends in the new fragment, and then just check that the new fragment is visible.

```<code>onView(withId(R.id.login_btn))
    .perform(click());
Thread.sleep(500);
onView(withId(R.id.email_input))
    .check(matches(isDisplayed()));
</code>```

If I remove the Thread.sleep() from the test, the test fails, even if I remove the setCustomAnimations() from the Activity code.

All animations are turned off on my phone, as per the instructions.  My understanding is that Espresso knows about the UI thread status and will wait until everything is ready.  But if I do a onView(withId(R.id.widgetOnNewFragment)) it blows up every time.  I need to add a Thread.sleep(500) every time I show a new fragment.

Am I missing something?  I think I should not have to add dozens of Thread.sleep() to my test code.

答:
While the Espresso framework 'waits' for certain main UI thread activities, animations require the IdlingResource approach (as Honza suggests).

There are good tutorials on this concept, even detailed implementations.

In reality, because animations rarely factor in to functional testing of the UI, most developers disable animations. IMO, this is an anti-pattern because it doesn't map to the real user experience (most people buy a phone and use it with default settings). This is a decision you'll have to make yourself. If you want to include animations as part of your functional requirements, there are ways, but it requires you to reimplement and rewrite your tests.

Body:
I'm just getting started with Espresso for testing Android apps, but I'm having some trouble. I have an Activity with a button that replaces a fragment in the usual way:

public void onClick(View v) {
    final FragmentTransaction t = getFragmentManager().beginTransaction();
    t.setCustomAnimations(R.animator.fragment_slide_in_up, 0);
    t.replace(R.id.fragment_container,
        LogInFragment.newInstance(), LogInFragment.TAG)
        .addToBackStack(LogInFragment.TAG);
    t.commit();
}

In my test, I click the button that sends in the new fragment, and then just check that the new fragment is visible.

onView(withId(R.id.login_btn))
    .perform(click());
Thread.sleep(500);
onView(withId(R.id.email_input))
    .check(matches(isDisplayed()));

If I remove the Thread.sleep() from the test, the test fails, even if I remove the setCustomAnimations() from the Activity code.

All animations are turned off on my phone, as per the instructions.  My understanding is that Espresso knows about the UI thread status and will wait until everything is ready.  But if I do a onView(withId(R.id.widgetOnNewFragment)) it blows up every time.  I need to add a Thread.sleep(500) every time I show a new fragment.

Am I missing something?  I think I should not have to add dozens of Thread.sleep() to my test code.


问:
Vue.js dom not updating.. 2 way binding
I'm using Vue.js for two-way binding.

I have an edit button, which should change the text field to an input field on click. This works not as I expected, it is not updating the dom immediately.

Example:

when I click on the edit button nothing changes, vie wthe screenshot below:

but when I delete the other image, the dom updates, and I get the input field as I want.

I hope anyone can help me, I'm struggling to long for this now..

This is my code for so far:

```<code>    <div class="row" id="app">
        <div v-for="image in images" class="col-md-3">
            <div class="well">
                <div class="card">
                    <div class="text-center">
                        <img class="card-img-top"
                             :src="image.data"
                             alt="Card image cap"
                             height="100">
                    </div>
                    <div class="card-block">

                        <template v-if="image.editing">
                            <h4 class="card-title">
                                <input type='text' v-model="image.title" class="form-control input-sm">
                            </h4>
                        </template>

                        <template v-else>
                            <h4 class="card-title">Image title</h4>
                        </template>

                        <p class="card-text">Some quick example text to build on the card title and make up
                            the
                            bulk of the card's content.</p>

                        <template v-if="image.editing">
                            <a @click.prevent="update(image)" href="#" class="btn btn-primary">
                                <i class="fa fa-floppy-o"></i>
                            </a>

                            <a @click.prevent="cancel(image)" class="btn btn-default" href="#">
                                <span class="btn-label-icon left fa fa-ban"></span>
                            </a>
                        </template>

                        <template v-else>
                            <a @click.prevent="edit(image)" href="#" class="btn btn-info"><i
                                        class="fa fa-pencil"></i></a>

                            <a @click.prevent="destroy(image)" href="#" class="btn btn-danger">
                                <i class="fa fa-trash"></i>
                            </a>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue@2.2.6"></script>
<script>
    var vm = new Vue({
        el: '#app',
        data: {
            url: '/users/<%= user._id %>/images?token=<%= user.token %>',
            image: {},
            images: []
        },
        mounted: function () {
            this.fetch();
        },
        methods: {
            fetch(){
                axios.get(this.url)
                    .then(function (response) {
                        this.images = response.data;
                    }.bind(this));
            },
            edit(image){
               image.editing = true;
            },
            toggle(){
            },
            destroy(image){
                axios.delete('/users/<%= user._id %>/images/' + image._id + '?token=<%= user.token %>')
                    .then((response) => {
                        this.images.splice(this.images.indexOf(image), 1);
                    }, (response) => {

                    });
            },
            update(image){

            },
            cancel(image){
                image.editing = false;
            }
        }
    })
</script>
</code>```

答:
The problem was that the JSON didn't have an editing property.

Solution:

```<code> axios.get(this.url).then((response) => {

                    this.images = response.data.map(function (image) {
                        image.editing = false;
                        return image
                    })

                }, (response) => {

                });
</code>```

Title: Vue.js dom not updating.. 2 way binding

Body:
I'm using Vue.js for two-way binding.

I have an edit button, which should change the text field to an input field on click. This works not as I expected, it is not updating the dom immediately.

Example:

when I click on the edit button nothing changes, vie wthe screenshot below:

but when I delete the other image, the dom updates, and I get the input field as I want.

I hope anyone can help me, I'm struggling to long for this now..

This is my code for so far:

                        <template v-if="image.editing">

                                <input type='text' v-model="image.title" class="form-control input-sm">

                        </template>

                        <template v-else>

Image title

                        </template>

Some quick example text to build on the card title and make up
                            the
                            bulk of the card's content.

                        <template v-if="image.editing">

                        </template>

                        <template v-else>

                        </template>

Body:
The problem was that the JSON didn't have an editing property.

Solution:

 axios.get(this.url).then((response) => {

                    this.images = response.data.map(function (image) {
                        image.editing = false;
                        return image
                    })

                }, (response) => {

                });


问:
send CTRL-Z through C++ program
I am trying to write a simple C++ program that sends an SMS message out based on its input from the user. The simple C++ program fails to do the job:

```<code>#include<stdio.h>
#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */

#include<iostream>
#define CTRL(x) (#x[0]-'a'+1)

using namespace std;
int main()
{
    char buffer[128];
    sprintf(buffer, "/opt/modemcli AT+CMGC=\"+112345678\"\rTEST%c", CTRL(z));
    printf (buffer);
    system(buffer);
    return 0;
}
</code>```

modemcli is just a simple C++ program that writes messages to the USB port and reads the response.

```<code>modemcli is simple, here is a test:
/opt/modemcli AT
Received AT
OK
</code>```

My guess is CMGC is not formed properly. The format is:

```<code>AT+CMGC="PHONE_NUMBER"<CR>SMS MESSAGE BODY.<Ctrl+z>
</code>```

Can someone please help me figure this out?

答:
First of all, I think you want to use the AT+CMGS command, not AT+CMGC. Check out the description of each command in 27.005 to see if you really want AT+CMGC. But before reading that document, read all of chapter 5 in V.250, that will teach you all the basics for AT command handling you need.

What you are attempting is impossible to do by using a generic command line program for sending AT command like modemcli or my atinout program. In order to run AT+CMGS on a modem, the program issuing it must have explicitly support for this specific AT command's behaviour.

This is because the need to wait for the "ready to receive" prompt from the modem before sending the payload. See the first part of this answer for details.

I have started working on a companion program to atinout specifically to handle AT+CMGS, but it is not done yet and do not hold your breath, the development is currently on hold.

Title: send CTRL-Z through C++ program

Body:
I am trying to write a simple C++ program that sends an SMS message out based on its input from the user. The simple C++ program fails to do the job:

#include<stdio.h>
#include <stdlib.h>     /* system, NULL, EXIT_FAILURE */

#include<iostream>
#define CTRL(x) (#x[0]-'a'+1)

using namespace std;
int main()
{
    char buffer[128];
    sprintf(buffer, "/opt/modemcli AT+CMGC=\"+112345678\"\rTEST%c", CTRL(z));
    printf (buffer);
    system(buffer);
    return 0;
}

modemcli is just a simple C++ program that writes messages to the USB port and reads the response.

modemcli is simple, here is a test:
/opt/modemcli AT
Received AT
OK

My guess is CMGC is not formed properly. The format is:

AT+CMGC="PHONE_NUMBER"<CR>SMS MESSAGE BODY.<Ctrl+z>

Can someone please help me figure this out?


问:
unindent does not match any outer indentation level in my maths game
I'm creating a maths quiz to help get my self started with Python since I'm very new to the language and it comes up with a unindent does not match any outer indentation level error message? Could someone inform me on what this means and where my mistake lies.

Here is my code:

```<code>import random

questions = 0
correct = 0

print ("Welcome to the maths challenge")
print ("Out of these 10 questions how many can you get right?")

while True :
questions += 1
numberA = random.randint(0,12)
question = "What is {0}**2".format(numberA)

print(question)

response = input("Your Answer : ")

answer = numberA**2

if(int(response) == answer) :
    print("Correct!")

else :
    print("Wrong!")

 if(questions == 10) :
     print("You got {0}/{1} questions correct.").format(correct, questions)

 if correct == ("5>")
     print ("Better luck next time")

 if correct == ("5<")
     print ("You got a great score Well done!")
     break
</code>```

答:
```<code> if(questions == 10) :
</code>```

and all successive lines are indented one space farther than their predecessors.  The one-space indentation doesn't match the prior block (zero spaces indented).

Body:
I'm creating a maths quiz to help get my self started with Python since I'm very new to the language and it comes up with a unindent does not match any outer indentation level error message? Could someone inform me on what this means and where my mistake lies.

Here is my code:

import random

questions = 0
correct = 0

print ("Welcome to the maths challenge")
print ("Out of these 10 questions how many can you get right?")

while True :
questions += 1
numberA = random.randint(0,12)
question = "What is {0}**2".format(numberA)

print(question)

response = input("Your Answer : ")

answer = numberA**2

if(int(response) == answer) :
    print("Correct!")

else :
    print("Wrong!")

 if(questions == 10) :
     print("You got {0}/{1} questions correct.").format(correct, questions)

 if correct == ("5>")
     print ("Better luck next time")

 if correct == ("5<")
     print ("You got a great score Well done!")
     break

Body:
 if(questions == 10) :

and all successive lines are indented one space farther than their predecessors.  The one-space indentation doesn't match the prior block (zero spaces indented).


问:
Bootstrap in xpages
I have Domino Designer version 9.0.1 FP4 installed on my computer. I downloaded an nsf database with xpages and demo bootstrap. How much do I try to load any xpages the error below is displayed in the browser. The library org.openntf.xsp.bootstrap.library is enabled in the xsp property file. Do I have to do any procedure for the bootstrap to work? Does it no longer come in the Domino Designer extension library?

Error 500
HTTP Web Server: Command Not Handled Exception

答:
Bootstrap is not part of the Extension Lib that IBM provides unless you install FP8. You have to get that feature pack 8 or get the Ext. Lib. from OpenNTF.

Are you trying to view the demo on the local web preview or on a server? If a server use the update site database to import in the Ext. Lib. from OpenNTF and set the notes.ini setting. If using a local web preview than you can copy the files like Paul mentioned.

Title: Bootstrap in xpages


问:
Error installing Rtools - devtools::has_devel() fails
I want to create an R package and downloaded Rtools and packages c("devtools", "roxygen2", "testthat", "knitr"). Now I check if everything is alright:

library(devtools)
has_devel()

and it's not, I get the error:

```<code>"C:/Users/xxx/DOCUME~1/R/R-33~1.1/bin/x64/R" --no-site-file --no-environ --no-save --no-restore  \
  --quiet CMD SHLIB foo.c

Warning message:
running command 'make -f "C:/Users/XYZ/DOCUME~1/R/R-33~1.1/etc/x64/Makeconf" -f "C:/Users/XYZ/DOCUME~1/R/R-33~1.1/share/make/winshlib.mk" SHLIB="foo.dll" WIN=64 TCLBIN=64 OBJECTS="foo.o"' had status 127
Error: Command failed (1)
</code>```

I use Windows and the freshest RStudio.

Do you know what it means or how to repair it?

答:
lol I have just ran this code:

```<code>install.packages("devtools")
library(devtools)
install_github("hadley/devtools")
devtools::build_github_devtools()
find_rtools()
has_devel()
build_github_devtools()
</code>```

from
https://github.com/hadley/devtools/issues/1219

and now has_devel returns TRUE :O :D

Body:
I want to create an R package and downloaded Rtools and packages c("devtools", "roxygen2", "testthat", "knitr"). Now I check if everything is alright:

library(devtools)
has_devel()

and it's not, I get the error:

"C:/Users/xxx/DOCUME~1/R/R-33~1.1/bin/x64/R" --no-site-file --no-environ --no-save --no-restore  \
  --quiet CMD SHLIB foo.c

Warning message:
running command 'make -f "C:/Users/XYZ/DOCUME~1/R/R-33~1.1/etc/x64/Makeconf" -f "C:/Users/XYZ/DOCUME~1/R/R-33~1.1/share/make/winshlib.mk" SHLIB="foo.dll" WIN=64 TCLBIN=64 OBJECTS="foo.o"' had status 127
Error: Command failed (1)

I use Windows and the freshest RStudio.

Do you know what it means or how to repair it?

Body:
lol I have just ran this code:

install.packages("devtools")
library(devtools)
install_github("hadley/devtools")
devtools::build_github_devtools()
find_rtools()
has_devel()
build_github_devtools()

from
https://github.com/hadley/devtools/issues/1219

and now has_devel returns TRUE :O :D


问:
Calculating cumulative values for every 12 months on tables with possibly null values
I have this table:

```<code>Month       Year         MV                    MI         fullDate
-----------------------------------------------------------------
...
5           2015         1                      5         2015-05-01
6           2015         1                     10         2015-06-01
7           2015         3                     10         2015-07-01
8           2015         2                     10         2015-08-01
11          2015         1                     10         2015-11-01
1           2016         4                     10         2016-01-01
6           2016         1                     20         2016-06-01
7           2016         null                  10         2016-07-01
8           2016         2                      5         2016-08-01
...
</code>```

I need to create another table with cumulative values:

```<code>Month       Year         AMV                  AMI
-----------------------------------------------------------------
...
7           2015         3                     10
8           2015         5                     20
11          2015         6                     30
1           2016         10                    40
6           2016         11                    60
7           2016         0                     10
8           2016         2                     15
...
</code>```

The cumulative calculations must start on a July and end on June of the next year. In this example, the cumulative fields started "accumulating" from July, 2015 and ended on June, 2016. These calculations re-started on July, 2016 getting another cycle for cumulative values to "calculate"

I made a similar question before but I just found out this "periodicity" for calculations of cumulative. One more thing... some values on the first table could be null and need to be considered as 0.

Please, tell me how can this be done?

Body:
I have this table:

Month       Year         MV                    MI         fullDate
-----------------------------------------------------------------
...
5           2015         1                      5         2015-05-01
6           2015         1                     10         2015-06-01
7           2015         3                     10         2015-07-01
8           2015         2                     10         2015-08-01
11          2015         1                     10         2015-11-01
1           2016         4                     10         2016-01-01
6           2016         1                     20         2016-06-01
7           2016         null                  10         2016-07-01
8           2016         2                      5         2016-08-01
...

I need to create another table with cumulative values:

Month       Year         AMV                  AMI
-----------------------------------------------------------------
...
7           2015         3                     10
8           2015         5                     20
11          2015         6                     30
1           2016         10                    40
6           2016         11                    60
7           2016         0                     10
8           2016         2                     15
...

The cumulative calculations must start on a July and end on June of the next year. In this example, the cumulative fields started "accumulating" from July, 2015 and ended on June, 2016. These calculations re-started on July, 2016 getting another cycle for cumulative values to "calculate"

I made a similar question before but I just found out this "periodicity" for calculations of cumulative. One more thing... some values on the first table could be null and need to be considered as 0.

Please, tell me how can this be done?

Body:
I have modified the quer from @Sebastian. The init is also in the query. the counter will reset each year and the where is not necessary

SELECT
  (@amv:=IF(MONTH(fulldate)=7,MV, IF(ISNULL(MV), 0, @amv+MV))) AS AMV,
  (@ami:=IF(MONTH(fulldate)=7,MI, IF(ISNULL(MI), 0, @ami+MI))) AS AMI,
  fullDate
FROM
  input
CROSS JOIN ( SELECT @amv := 0, @ami := 0) AS init
ORDER BY fullDate ASC;

sample

mysql> select * from input;
+----+------+------+------------+
| id | MV   | MI   | fullDate   |
+----+------+------+------------+
|  1 |    1 |   10 | 2015-08-01 |
|  2 |    2 |   20 | 2015-09-01 |
|  3 |    3 |   30 | 2015-07-01 |
|  4 |    8 |   33 | 2016-07-01 |
|  5 |    2 |    8 | 2016-08-01 |
+----+------+------+------------+
5 rows in set (0,00 sec)

mysql>     SELECT
    ->       (@amv:=IF(MONTH(fulldate)=7,MV, IF(ISNULL(MV), 0, @amv+MV))) AS AMV,
    ->       (@ami:=IF(MONTH(fulldate)=7,MI, IF(ISNULL(MI), 0, @ami+MI))) AS AMI,
    ->       fullDate
    ->     FROM
    ->       input
    ->     CROSS JOIN ( SELECT @amv := 0, @ami := 0) AS init
    ->     ORDER BY fullDate ASC;
+------+------+------------+
| AMV  | AMI  | fullDate   |
+------+------+------------+
|    3 |   30 | 2015-07-01 |
|    4 |   40 | 2015-08-01 |
|    6 |   60 | 2015-09-01 |
|    8 |   33 | 2016-07-01 |
|   10 |   41 | 2016-08-01 |
+------+------+------------+
5 rows in set (0,00 sec)

mysql>


问:
UTF8, Unicode and Binary data reading troubles
I have been working in a script to read files, extract and index some strings. Everything is going fine, except for one problem with file encoding.

I will try to resume:

My script read chunk of data from files, convert these chunks to lowercase and normalize to remove replace special characters (ç, á, é, ã, etc) using unicodedata.normalize:

```<code>unicodedata.normalize("NFKD",chunk.decode("utf8","ignore")).encode("ascii","ignore").lower()
</code>```

In this case, the string "Olá, como vai você? Vamos caçar?" will result in "Ola, como vai voce? Vamos cacar?" It is working fine with UTF8 encoded text files, but it fails when trying to retrieve strings from binary files (like MS .doc files). Using the same code from above, will return me a string "Ol, como vai voc? Vamos caar?"

I have managed to get it working with MS .doc files using the unicode-escape (but it will fail with the UTF8 files).

```<code>unicodedata.normalize("NFKD",chunk.decode("unicode-escape","ignore")).encode("ascii","ignore").lower()
</code>```

After 20+ hours of research I have no solution yet to get my script running in both cases.

Unfortunatelly I cant use external modules.

答:
You need to parametrize your script. You should specify the encoding as an argument you call it. If you already specify the file name as an argument, it would look like this:

```<code>$ python your_script.py input-file.txt utf8
</code>```

Read the arguments like this:

```<code>input_file, encoding = sys.argv[1:]
</code>```

Then change the encoding-mangling line to:

```<code>unicodedata.normalize("NFKD", chunk.decode(encoding, "ignore")).encode("ascii", "ignore").lower()
</code>```

Maybe there's a way to guess the encoding in some other way (eg. if all files of one kind end with ".doc"), then you can skip the command-line argument.

Body:
I have been working in a script to read files, extract and index some strings. Everything is going fine, except for one problem with file encoding.

I will try to resume:

My script read chunk of data from files, convert these chunks to lowercase and normalize to remove replace special characters (ç, á, é, ã, etc) using unicodedata.normalize:

unicodedata.normalize("NFKD",chunk.decode("utf8","ignore")).encode("ascii","ignore").lower()

In this case, the string "Olá, como vai você? Vamos caçar?" will result in "Ola, como vai voce? Vamos cacar?" It is working fine with UTF8 encoded text files, but it fails when trying to retrieve strings from binary files (like MS .doc files). Using the same code from above, will return me a string "Ol, como vai voc? Vamos caar?"

I have managed to get it working with MS .doc files using the unicode-escape (but it will fail with the UTF8 files).

unicodedata.normalize("NFKD",chunk.decode("unicode-escape","ignore")).encode("ascii","ignore").lower()

After 20+ hours of research I have no solution yet to get my script running in both cases.

Unfortunatelly I cant use external modules.

Body:
You need to parametrize your script. You should specify the encoding as an argument you call it. If you already specify the file name as an argument, it would look like this:

$ python your_script.py input-file.txt utf8

Read the arguments like this:

input_file, encoding = sys.argv[1:]

Then change the encoding-mangling line to:

unicodedata.normalize("NFKD", chunk.decode(encoding, "ignore")).encode("ascii", "ignore").lower()

Maybe there's a way to guess the encoding in some other way (eg. if all files of one kind end with ".doc"), then you can skip the command-line argument.


问:
changing constraints at runtime in swift
I'm really very weak in constraints part of ios. I have gone through many reference link as shown below but still not able solve my issue.

Hide autolayout UIView : How to get existing NSLayoutConstraint to update this one

In case , i need to change the y-axis of UIView2 based on some condition. The storyboard.png shows the layout.

If condition fails UIView2 with step1, step 2 and step3 should be visible and it's position should also change as shown in condition1.png

If condition pass UIView2 with step1, step 2 and step3 should not be visible as shown in condition1.png

Please provide me steps for how to achieve the above scenario. I tried it doing but if set the constraint for UIView1 the height remains same and does not change at runtime.

答:
I use outlets for constraints set on the storyboard, for divs between buttons (using old ways to set dynamic layouts). So, for large screens (iPhone 6 and above), I update the values of fixed heights (app only viewed in portrait mode). What worked for me is:

```<code>constHeightlogo.constant = 140 //old value = 72
///set any other updates here then force the view
self.view.layoutIfNeeded()
</code>```

Worked like a charm.

See related here:

Update the constant property of a constraint programmatically in Swift?

Body:
I use outlets for constraints set on the storyboard, for divs between buttons (using old ways to set dynamic layouts). So, for large screens (iPhone 6 and above), I update the values of fixed heights (app only viewed in portrait mode). What worked for me is:

constHeightlogo.constant = 140 //old value = 72
///set any other updates here then force the view
self.view.layoutIfNeeded()

Worked like a charm.

See related here:

Update the constant property of a constraint programmatically in Swift?


问:
SQL Server - Remove all non-printable ASCII characters
We recently migrated from SQL Server 2012 to SQL Server 2014 and all our FOR XML code started throwing errors about non-printable ASCII characters.
I wrote this horrible function to remove non-printable ASCII characters as a quick fix. I want to replace it with something cleaner. Is there a way to do this?

```<code>ALTER FUNCTION [dbo].[remove_non_printable_chars]
(@input_string nvarchar(max))
RETURNS nvarchar(max)
BEGIN
    RETURN
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(@input_string,
        CHAR(1), ''),CHAR(2), ''),CHAR(3), ''),CHAR(4), ''),CHAR(5), ''),CHAR(6), ''),CHAR(7), ''),CHAR(8), ''),CHAR(9), ''),CHAR(10), ''),
        CHAR(11), ''),CHAR(12), ''),CHAR(13), ''),CHAR(14), ''),CHAR(15), ''),CHAR(16), ''),CHAR(17), ''),CHAR(18), ''),CHAR(19), ''),CHAR(20), ''),
        CHAR(21), ''),CHAR(22), ''),CHAR(23), ''),CHAR(24), ''),CHAR(25), ''),CHAR(26), ''),CHAR(27), ''),CHAR(28), ''),CHAR(29), ''),CHAR(30), ''),
        CHAR(31), ''), NCHAR(0) COLLATE Latin1_General_100_BIN2, '')
END
</code>```

Here's the FOR XML code that broke. (I did not write this. It was already in the code base).

```<code>SELECT @HTMLTableData =
(
    SELECT  HTMLRows
    FROM (
        SELECT N'<tr>' + HTMLRow + N'</tr>' AS HTMLRows
        FROM @HTMLRowData
    ) mi
    FOR XML PATH(''), TYPE
).value('/', 'NVARCHAR(MAX)')
</code>```

答:
In-line version:

```<code>create function [dbo].[remove_non_printable_chars] (@input_string nvarchar(max))
returns table with schemabinding as return (
  select
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
    replace(replace(@input_string collate latin1_general_100_bin2,
        char(1), ''),char(2), ''),char(3), ''),char(4), ''),char(5), ''),char(6), ''),char(7), ''),char(8), ''),char(9), ''),char(10), ''),
        char(11), ''),char(12), ''),char(13), ''),char(14), ''),char(15), ''),char(16), ''),char(17), ''),char(18), ''),char(19), ''),char(20), ''),
        char(21), ''),char(22), ''),char(23), ''),char(24), ''),char(25), ''),char(26), ''),char(27), ''),char(28), ''),char(29), ''),char(30), ''),
        char(31), ''), char(0) , '')
     as clean_string
);
go
</code>```

And use it like so:

```<code>select c.clean_string
from dbo.remove_non_printable_chars(@dirtystring) c
</code>```

or

```<code>select ...
  , c.clean_string
from t
  cross apply dbo.remove_non_printable_chars(t.dirty_string) c
</code>```

Reference:

When is a SQL function not a function? "If it’s not inline, it’s rubbish." - Rob Farley

Inline Scalar Functions - Itzik Ben-Gan

Scalar functions, inlining, and performance: An entertaining title for a boring post - Adam Machanic

TSQL User-Defined Functions: Ten Questions You Were Too Shy To Ask - Robert Sheldon

Body:
We recently migrated from SQL Server 2012 to SQL Server 2014 and all our FOR XML code started throwing errors about non-printable ASCII characters.
I wrote this horrible function to remove non-printable ASCII characters as a quick fix. I want to replace it with something cleaner. Is there a way to do this?

ALTER FUNCTION [dbo].[remove_non_printable_chars]
(@input_string nvarchar(max))
RETURNS nvarchar(max)
BEGIN
    RETURN
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
    REPLACE(REPLACE(@input_string,
        CHAR(1), ''),CHAR(2), ''),CHAR(3), ''),CHAR(4), ''),CHAR(5), ''),CHAR(6), ''),CHAR(7), ''),CHAR(8), ''),CHAR(9), ''),CHAR(10), ''),
        CHAR(11), ''),CHAR(12), ''),CHAR(13), ''),CHAR(14), ''),CHAR(15), ''),CHAR(16), ''),CHAR(17), ''),CHAR(18), ''),CHAR(19), ''),CHAR(20), ''),
        CHAR(21), ''),CHAR(22), ''),CHAR(23), ''),CHAR(24), ''),CHAR(25), ''),CHAR(26), ''),CHAR(27), ''),CHAR(28), ''),CHAR(29), ''),CHAR(30), ''),
        CHAR(31), ''), NCHAR(0) COLLATE Latin1_General_100_BIN2, '')
END

Here's the FOR XML code that broke. (I did not write this. It was already in the code base).

SELECT @HTMLTableData =
(
    SELECT  HTMLRows
    FROM (
        SELECT N'
' + HTMLRow + N'
' AS HTMLRows
        FROM @HTMLRowData
    ) mi
    FOR XML PATH(''), TYPE
).value('/', 'NVARCHAR(MAX)')

Body:
In-line version:

create function [dbo].[remove_non_printable_chars] (@input_string nvarchar(max))
returns table with schemabinding as return (
  select
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
    replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(
    replace(replace(@input_string collate latin1_general_100_bin2,
        char(1), ''),char(2), ''),char(3), ''),char(4), ''),char(5), ''),char(6), ''),char(7), ''),char(8), ''),char(9), ''),char(10), ''),
        char(11), ''),char(12), ''),char(13), ''),char(14), ''),char(15), ''),char(16), ''),char(17), ''),char(18), ''),char(19), ''),char(20), ''),
        char(21), ''),char(22), ''),char(23), ''),char(24), ''),char(25), ''),char(26), ''),char(27), ''),char(28), ''),char(29), ''),char(30), ''),
        char(31), ''), char(0) , '')
     as clean_string
);
go

And use it like so:

select c.clean_string
from dbo.remove_non_printable_chars(@dirtystring) c

or

select ...
  , c.clean_string
from t
  cross apply dbo.remove_non_printable_chars(t.dirty_string) c

Reference:

When is a SQL function not a function? "If it’s not inline, it’s rubbish." - Rob Farley

Inline Scalar Functions - Itzik Ben-Gan

Scalar functions, inlining, and performance: An entertaining title for a boring post - Adam Machanic

TSQL User-Defined Functions: Ten Questions You Were Too Shy To Ask - Robert Sheldon


问:
selectize js with json not working
I am trying to use selectize.js with json data from json file to append "options" to "select" tag, but I can't do it.please help me.

below is my code.

```<code>  <script type="text/javascript">
$(function() {
    $.getJSON( "dist/cc.json", function( data ) {
                  data = data.smp_country_code;
                  alert(JSON.stringify(data));
                  $.each( data, function( key, val ) {
                     $(".cc").append( "<option value='" + key + "'>" + val + "</option>" );
               });
            });
});
</script>

<select id="select-state" class=""></select>

<script>
$('#select-state').selectize({
  valueField: 'country',
  labelField: 'country',
  searchField: 'country',
  options: [],
  load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: 'http://localhost/maya/dist/country.json',
        type: 'GET',
        dataType: 'json',
        data: {
            country: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
  }
});
</script>
</code>```

here is my json file "cc.json"

```<code>{
"smp_country_code": {
        "0": "Select a state...",
        "AL":"Alabama",
        "AK":"Alaska",
        "AZ":"Arizona",
        "AR":"Arkansas",
        "CA":"California",
        "CO":"Colorado",
        "CT":"Connecticut",
        "DE":"Delaware",
        "DC":"District of Columbia",
        "FL":"Florida",
        "GA":"Georgia",
        "HI":"Hawaii",
        "ID":"Idaho",
        "IL":"Illinois",
        "IN":"Indiana",
        "IA":"Iowa",
        "KS":"Kansas",
        "KY":"Kentucky",
        "LA":"Louisiana",
        "ME":"Maine",
        "MD":"Maryland",
        "MA":"Massachusetts",
        "MI":"Michigan",
        "MN":"Minnesota",
        "MS":"Mississippi",
        "MO":"Missouri",
        "MT":"Montana",
        "NE":"Nebraska",
        "NV":"Nevada",
        "NH":"New Hampshire",
        "NJ":"New Jersey",
        "NM":"New Mexico",
        "NY":"New York",
        "NC":"North Carolina",
        "ND":"North Dakota",
        "OH":"Ohio",
        "OK":"Oklahoma",
        "OR":"Oregon",
        "PA":"Pennsylvania",
        "RI":"Rhode Island",
        "SC":"South Carolina",
        "SD":"South Dakota",
        "TN":"Tennessee",
        "TX":"Texas",
        "UT":"Utah",
        "VT":"Vermont",
        "VA":"Virginia",
        "WA":"Washington",
        "WV":"West Virginia",
        "WI":"Wisconsin",
        "WY":"Wyoming"
         }
}
</code>```

it not work please see in the picture

when i don't use json, it's works.
below code is normal usage without using json data.

```<code><select id="select-state">
        <option value="">Select a state...</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
      </select>
</code>```

here is normal usage without json and

I am trying the code to work as shown in the picture please help me.

答:
It looks like you have access to change the cc.json output? If so, you can format it to output something like

```<code>[{"code":"AL","name":"Alabama"}, ... ,{"code":"WY","name":"Wyoming"}]
</code>```

and then your selectize call would be something like

```<code>$('#select-state').selectize({
  valueField: 'code',
  labelField: 'name',
  searchField: 'name',
  options: [],
  load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: 'http://localhost/maya/dist/cc.json',
        type: 'GET',
        dataType: 'json',
        data: {
            country: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
  }
});
</code>```

You don't need to add the options manually with $.getJSON

Title: selectize js with json not working

Body:
I am trying to use selectize.js with json data from json file to append "options" to "select" tag, but I can't do it.please help me.

below is my code.

<select id="select-state" class=""></select>

here is my json file "cc.json"

{
"smp_country_code": {
        "0": "Select a state...",
        "AL":"Alabama",
        "AK":"Alaska",
        "AZ":"Arizona",
        "AR":"Arkansas",
        "CA":"California",
        "CO":"Colorado",
        "CT":"Connecticut",
        "DE":"Delaware",
        "DC":"District of Columbia",
        "FL":"Florida",
        "GA":"Georgia",
        "HI":"Hawaii",
        "ID":"Idaho",
        "IL":"Illinois",
        "IN":"Indiana",
        "IA":"Iowa",
        "KS":"Kansas",
        "KY":"Kentucky",
        "LA":"Louisiana",
        "ME":"Maine",
        "MD":"Maryland",
        "MA":"Massachusetts",
        "MI":"Michigan",
        "MN":"Minnesota",
        "MS":"Mississippi",
        "MO":"Missouri",
        "MT":"Montana",
        "NE":"Nebraska",
        "NV":"Nevada",
        "NH":"New Hampshire",
        "NJ":"New Jersey",
        "NM":"New Mexico",
        "NY":"New York",
        "NC":"North Carolina",
        "ND":"North Dakota",
        "OH":"Ohio",
        "OK":"Oklahoma",
        "OR":"Oregon",
        "PA":"Pennsylvania",
        "RI":"Rhode Island",
        "SC":"South Carolina",
        "SD":"South Dakota",
        "TN":"Tennessee",
        "TX":"Texas",
        "UT":"Utah",
        "VT":"Vermont",
        "VA":"Virginia",
        "WA":"Washington",
        "WV":"West Virginia",
        "WI":"Wisconsin",
        "WY":"Wyoming"
         }
}

it not work please see in the picture

when i don't use json, it's works.
below code is normal usage without using json data.

<select id="select-state">
        <option value="">Select a state...</option>
        <option value="AL">Alabama</option>
        <option value="AK">Alaska</option>
        <option value="AZ">Arizona</option>
        <option value="AR">Arkansas</option>
        <option value="CA">California</option>
        <option value="CO">Colorado</option>
        <option value="CT">Connecticut</option>
        <option value="DE">Delaware</option>
        <option value="DC">District of Columbia</option>
        <option value="FL">Florida</option>
        <option value="GA">Georgia</option>
        <option value="HI">Hawaii</option>
        <option value="ID">Idaho</option>
        <option value="IL">Illinois</option>
        <option value="IN">Indiana</option>
        <option value="IA">Iowa</option>
        <option value="KS">Kansas</option>
        <option value="KY">Kentucky</option>
        <option value="LA">Louisiana</option>
        <option value="ME">Maine</option>
        <option value="MD">Maryland</option>
        <option value="MA">Massachusetts</option>
        <option value="MI">Michigan</option>
        <option value="MN">Minnesota</option>
        <option value="MS">Mississippi</option>
        <option value="MO">Missouri</option>
        <option value="MT">Montana</option>
        <option value="NE">Nebraska</option>
        <option value="NV">Nevada</option>
        <option value="NH">New Hampshire</option>
        <option value="NJ">New Jersey</option>
        <option value="NM">New Mexico</option>
        <option value="NY">New York</option>
        <option value="NC">North Carolina</option>
        <option value="ND">North Dakota</option>
        <option value="OH">Ohio</option>
        <option value="OK">Oklahoma</option>
        <option value="OR">Oregon</option>
        <option value="PA">Pennsylvania</option>
        <option value="RI">Rhode Island</option>
        <option value="SC">South Carolina</option>
        <option value="SD">South Dakota</option>
        <option value="TN">Tennessee</option>
        <option value="TX">Texas</option>
        <option value="UT">Utah</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WA">Washington</option>
        <option value="WV">West Virginia</option>
        <option value="WI">Wisconsin</option>
        <option value="WY">Wyoming</option>
      </select>

here is normal usage without json and

I am trying the code to work as shown in the picture please help me.

Body:
It looks like you have access to change the cc.json output? If so, you can format it to output something like

[{"code":"AL","name":"Alabama"}, ... ,{"code":"WY","name":"Wyoming"}]

and then your selectize call would be something like

$('#select-state').selectize({
  valueField: 'code',
  labelField: 'name',
  searchField: 'name',
  options: [],
  load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: 'http://localhost/maya/dist/cc.json',
        type: 'GET',
        dataType: 'json',
        data: {
            country: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
  }
});

You don't need to add the options manually with $.getJSON


问:
Job configurations are missing when copied from folders in Jenkins
This is reproducible 100%.
We are working on different branches of the release, but each branch should run the same jobs, with some minor change.  So ideally I want to copy all the jobs from one working branch to a new branch.

I select a New item -> folder and select copy from another folder.

The new folder contains the all the jobs from source folder, but all the job configurations are missing. In another word, I have jobs created just with job names, I need to refill everything else.  This is essentially useless.

I googled and did not see any related errors. Anyone have any good advice on copy jenkins folders ?  I am jenkins 1.651.3, ubuntu 14.04

答: I should also mentioned it turns out just our computer issue. Lack of ram. After we added more ram, it' all working perfectly!</p>


问:
How expensive is it to dereference a pointer?
How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want to know how expensive the dereference operation part is.

答:
Dereferencing, when translated into machine code, can mean different things depending on what you do with the dereferenced object. Accessing a single member of a class through a pointer is typically cheap. For example if c is a pointer to an instance of class C with an int member n then something like this:

```<code>int n = c->n;
</code>```

Might translate into one or two machine instructions and might load a register with a single memory access.

On the other hand this implies making a complete copy of the object pointed to by c:

```<code>C d = *c;
</code>```

The cost of this will depend on the size of C, but note that it is the copy that is the major expense and the 'dereference' part is really just 'using' the pointer address in the copy instructions.

Note that accessing members of large objects typically requires pointer offset calculation and memory access whether or not the object is a local object or not. Typically only very small objects are optimized to live only in registers.

If you are concerned about the cost of pointers over references then don't be. The difference between these are a language semantics difference and by the time the machine code is generated pointer and reference access look exactly the same.

OwnerDisplayName: Tunnuz

LastEditorDisplayName: ChrisN

Body:
Dereferencing, when translated into machine code, can mean different things depending on what you do with the dereferenced object. Accessing a single member of a class through a pointer is typically cheap. For example if c is a pointer to an instance of class C with an int member n then something like this:

int n = c->n;

Might translate into one or two machine instructions and might load a register with a single memory access.

On the other hand this implies making a complete copy of the object pointed to by c:

C d = *c;

The cost of this will depend on the size of C, but note that it is the copy that is the major expense and the 'dereference' part is really just 'using' the pointer address in the copy instructions.

Note that accessing members of large objects typically requires pointer offset calculation and memory access whether or not the object is a local object or not. Typically only very small objects are optimized to live only in registers.

If you are concerned about the cost of pointers over references then don't be. The difference between these are a language semantics difference and by the time the machine code is generated pointer and reference access look exactly the same.

OwnerDisplayName: Charles Bailey

LastEditorDisplayName: Charles Bailey


问:
How to mark an issue as resolved from the commit log?
I noted that in BitBucket when your commit log contains a number like #12 this number is linked to the bug number 12.

I found this feature interesting, and I wonder if there is any keyword that would allow me to mark the issue as resolved from the commit log instead of going to the web interface each time.

If BitBucket doesn't do it, could you point a system that does?

答:
Trac does it as well, of course. It's easily configurable:</p>

```<code>   _supported_cmds = {
                       'closed':     '_cmdClose',
                       'fix':        '_cmdClose',
                       'addresses':  '_cmdRefs',
                       're':         '_cmdRefs',
</code>```

Body:
Trac does it as well, of course. It's easily configurable:

   _supported_cmds = {
                       'closed':     '_cmdClose',
                       'fix':        '_cmdClose',
                       'addresses':  '_cmdRefs',
                       're':         '_cmdRefs',