问:
Java Generics: Error when using innerclass
Based on the answer: https://stackoverflow.com/a/47693998/8760211

Following Compile Error occurs, when I try to sort a list with elements of Type Student from within the class Invoker.
Student is an innerclass of class University:

```<code>Type mismatch: cannot convert from ToIntFunction<University.Student> to ToIntFunction<? super T>
</code>```

Code:

```<code>public class University implements Serializable {
    private List<Student> values = new ArrayList<Student>();

    public static final class Student implements Serializable {
        private int id;
        private String name;
        private String location;
        private Date date;

        Student(int id, String name, String location, Date date) {
            this.id = id;
            this.name = name;
            this.location = location;
            this.date = date;
        }

        // Problem occurs even with getters!!
}

public class Invoker implements Serializable {
    public static void main(String[] args) {
        List<University.Student> students = new ArrayList<>();

        Map<String, Integer> locationOrder = students.stream().collect(HashMap::new,
                (m, s) -> m.putIfAbsent(s.getName(), m.size()),
                (m1, m2) -> m2.keySet().forEach(l -> m1.putIfAbsent(l, m1.size())));

        students.sort(Comparator.comparingInt((University.Student s) -> locationOrder.get(s.name)).thenComparing(s -> s.id));
    }
}
</code>```

The following code snippet is marked in IDE as cause of the Compiler error:
comparingInt((University.Student s) -> locationOrder.get(s.name)

If I move the innerclass into the class Invoker everything works fine!!

Any help would be much appreciated.
Thanks in advance.

答:
This is a strange error to get, but the reason is just that s.name is not accessible in the Invoker: it's private. Neither is s.id. So you should add getter methods to Student like

```<code>public String getName() {
    return name;
}
</code>```

and use them instead. Enclosing classes can access the inner classes' private members which is why it works if moved to Invoker.

Body:
Based on the answer: https://stackoverflow.com/a/47693998/8760211

Following Compile Error occurs, when I try to sort a list with elements of Type Student from within the class Invoker.
Student is an innerclass of class University:

Type mismatch: cannot convert from ToIntFunction<University.Student> to ToIntFunction<? super T>

Code:

public class University implements Serializable {
    private List<Student> values = new ArrayList<Student>();

    public static final class Student implements Serializable {
        private int id;
        private String name;
        private String location;
        private Date date;

        Student(int id, String name, String location, Date date) {
            this.id = id;
            this.name = name;
            this.location = location;
            this.date = date;
        }

        // Problem occurs even with getters!!
}

public class Invoker implements Serializable {
    public static void main(String[] args) {
        List<University.Student> students = new ArrayList<>();

        Map<String, Integer> locationOrder = students.stream().collect(HashMap::new,
                (m, s) -> m.putIfAbsent(s.getName(), m.size()),
                (m1, m2) -> m2.keySet().forEach(l -> m1.putIfAbsent(l, m1.size())));

        students.sort(Comparator.comparingInt((University.Student s) -> locationOrder.get(s.name)).thenComparing(s -> s.id));
    }
}

The following code snippet is marked in IDE as cause of the Compiler error:
comparingInt((University.Student s) -> locationOrder.get(s.name)

If I move the innerclass into the class Invoker everything works fine!!

Any help would be much appreciated.
Thanks in advance.

Body:
This is a strange error to get, but the reason is just that s.name is not accessible in the Invoker: it's private. Neither is s.id. So you should add getter methods to Student like

public String getName() {
    return name;
}

and use them instead. Enclosing classes can access the inner classes' private members which is why it works if moved to Invoker.


来源: stackexchange

问:
iOS 11.2 - Search Controller Bar background is clear when inside Navigation Bar with Large Title
so I just updated to iOS 11.2, and now my UISearchController's search bar is messed up. When search is active, the background behind the search bar area goes invisible / clear / transparent.

I built a test project to make sure I wasn't crazy. Here's the original setup:

```<code>navigationBar.translucent = YES;
navigationBar.barTintColor = [UIColor orangeColor];

self.navigationItem.searchController = myUISearchController;
</code>```

Here's how it should appear:

<img src="https://i.stack.imgur.com/vhZNW.png" alt="With prefersLargeTitles off">

But if I use large titles and a background image, then the result is this:

```<code>navigationBar.prefersLargeTitles = YES;
[navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];
</code>```

<img src="https://i.stack.imgur.com/YYJJE.png" alt="With prefersLargeTitles on">

If anyone finds a solution to this, I'd really appreciate the help.

✌

答:
Aside from just bailing on the background image or large title, here's the only solution I've come up with.

Disable large titles before search appears, and enable it again when it dismisses. Kind of sucks but seems to do the trick.

```<code>self.navigationItem.searchController.delegate = self;

...

- (void)willPresentSearchController:(UISearchController *)searchController {
    self.navigationController.navigationBar.prefersLargeTitles = NO;
}

- (void)willDismissSearchController:(UISearchController *)searchController {
    self.navigationController.navigationBar.prefersLargeTitles = YES;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
so I just updated to iOS 11.2, and now my UISearchController's search bar is messed up. When search is active, the background behind the search bar area goes invisible / clear / transparent.

I built a test project to make sure I wasn't crazy. Here's the original setup:

navigationBar.translucent = YES;
navigationBar.barTintColor = [UIColor orangeColor];

self.navigationItem.searchController = myUISearchController;

Here's how it should appear:

<img src="https://i.stack.imgur.com/vhZNW.png" alt="With prefersLargeTitles off">

But if I use large titles and a background image, then the result is this:

navigationBar.prefersLargeTitles = YES;
[navigationBar setBackgroundImage:bgImage forBarMetrics:UIBarMetricsDefault];

<img src="https://i.stack.imgur.com/YYJJE.png" alt="With prefersLargeTitles on">

If anyone finds a solution to this, I'd really appreciate the help.

✌

Body:
Aside from just bailing on the background image or large title, here's the only solution I've come up with.

Disable large titles before search appears, and enable it again when it dismisses. Kind of sucks but seems to do the trick.

self.navigationItem.searchController.delegate = self;

...

- (void)willPresentSearchController:(UISearchController *)searchController {
    self.navigationController.navigationBar.prefersLargeTitles = NO;
}

- (void)willDismissSearchController:(UISearchController *)searchController {
    self.navigationController.navigationBar.prefersLargeTitles = YES;
}


问:
Looking for good bonus quiz to test efficiency (specifically efficiency related to time)
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

```<code>public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}
</code>```

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.

答:
Two things.

First, efficiency is about more than execution time.  It also is about memory usage, memory access, file-system/resource access, etc.  There are tons of things that go into efficiency.  So please be explicit that you're looking for the routine with the shortest run-time.  Otherwise you are sending a mixed message...

Second, I heard this problem about 15 years ago, and I can't forget it:

Produce a list of all 5-digit number pairs that sum to 121212.  However, neither of the 2 numbers can repeat a decimal digit.  So 1 can only appear once in either number.  So an example result pair is 98167 + 23045.  There are a fair number, and it's easy to build a brute-force solution, but an efficient solution requires some thought.  There are 192 unique pairs...

Body:
I am doing a Introductory to Computer Science lab once a week.  I was hoping to have a quick contest at the end of my next lab.  I want to give them a block of code like this:

public class EfficientCode{

    public static void main(){
        long startTime, endTime, executionTime;
        startTime = System.currentTimeMillis();

        yourEfficientMethod():
        endTime = System.currentTimeMillis();
        executionTime = endTime – startTime;

    }

    public static void doSomething(){
        // you do this part.
    }

}

They will implement the doSomething method and the person with the fastest code will get a handful of bonus marks.

The problem is that the question needs to be somewhat simple.  The students have a good grasp of: loops, if/else, Strings, adding, arrays, etc.

Here are my ideas for what the question could be:

find all the perfect numbers between 1 and 1,000,000.  (A perfect number is a number where all of the number's factors add up to the number.  Ie: 6 = 3 + 2 + 1)

find all prime numbers between 1 and 1,000,000

I think in order for there to be a measurable difference in performance between methods you must do something many times.

ContentLicense: CC BY-SA 2.5


问:
Microsoft Excel get Count of Distinct Values
I am trying to use excel to get a count of distinct values, the following screenshot will illustrate what I am trying to do. Data Screenshot

Given data in the form on the left column I would like a way to display the occurrences of each distinct value on the right.
I have used the Outline Subtotal grouping to do this but it does not present the data in a form I can work with. I am by all means an Excel novice, any help would be appreciated
Thanks!

答: Use a pivot Table.  Put the column in both the Rows and Values:


问:
Using AJAX to send data to FormCollection
I'm trying to using FormCollection instead of a model.
I created my AJAX request:

```<code>myData = {
        id: '1',
        name: $("#name").val()
    };
    $.ajax({
        type: "GET",
        url: '/testController/Test',
        data: JSON.stringify(myData),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            // do something
        },
        error: function (erro) {
            console.debug(erro);
        }
    });
</code>```

My controller with FormCollection

```<code>[HttpGet, ValidateInput(false)]
    public JsonResult Test(FormCollection formData)
    {
        string name = formData["name"].ToString();
    }
</code>```

However, my formData is always null. Does anyone know why?

Thanks

答:
If you are making GET request, you are actually making this request. And you need to access the parameter by Request['id'] & Request['name'].

Request URI: /testController/Test?id={data_id}&name={data_name}

Request Body: <empty>

However, if you are making POST request, you are making this request:

Request URI: /testController/Test

Request Body: {"id":"data_id","name":"data_name"}

The request body is parsed and you can access the data through FormCollection. That's why FormCollection is always null when you make GET request.

Body:
I'm trying to using FormCollection instead of a model.
I created my AJAX request:

myData = {
        id: '1',
        name: $("#name").val()
    };
    $.ajax({
        type: "GET",
        url: '/testController/Test',
        data: JSON.stringify(myData),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            // do something
        },
        error: function (erro) {
            console.debug(erro);
        }
    });

My controller with FormCollection

[HttpGet, ValidateInput(false)]
    public JsonResult Test(FormCollection formData)
    {
        string name = formData["name"].ToString();
    }

However, my formData is always null. Does anyone know why?

Thanks


问:
check if timestamp column is in date range from another dataframe
I have a dataframe, df_A with two columns 'amin' and 'amax', which is a set of time range.

My objective is to find whether a column in df_B lies between any of the rows of range in df_A 'amin' and 'amax' columns.

```<code>df_A[['amin','amax'] ]

                  amin                   amax
          0 2016-07-16 19:37:03   2016-07-17 11:16:32
          1 2016-07-04 21:15:54   2016-07-05 10:57:46
          2 2016-07-24 23:30:41   2016-07-25 15:38:02
          3 2016-07-12 03:02:38   2016-07-12 22:11:01

df_B['created_date']

      created_date
   2016-07-17 01:16:32
   2016-07-05 10:15:54
   2016-07-12 12:11:01

df_A['amin'] = pd.to_datetime(df_A['amin'], errors='coerce')
df_A['amax'] = pd.to_datetime(df_A['amax'], errors='coerce')
df_B['created_date'] = pd.to_datetime(df_B['created_date'],errors='coerce')

def dt2epoch(value):
   epoch = (value - pd.to_datetime(datetime(2015,12,31).strftime('%Y-%m-%d %H:%M:%S.%f'))).total_seconds()
   return epoch

df_A['amax_epoch']=df_A['amax'].apply(dt2epoch)
df_A['amin_epoch']=df_A['amin'].apply(dt2epoch)
df_B['created_date_epoch']=df_B['created_date'].apply(dt2epoch)

def make_tuple(row):
     n= len(row)
     row = [(x,row[n - 1]) for x in row]
     return row

minMaxTuple = minMax.apply(make_tuple, axis =1)
</code>```

Above is part of my code, I've tried below(not sure if it's necessary):

convert them to epoch values

convert df_A into a tuple.

However, df_A and df_B has a different number of rows. Also, I dont have any id column to merge them together.

```<code>label = []

for l in df_B['created_date_epoch']:

    if (m[0] for m in minMaxTuple) <= l <= (m[1] for m in minMaxTuple):
        label.append('1')
    else:
        label.append('0')
</code>```

However, when I run this, the result I get for 'label' is an empty list.

Also, the label should be a column that has the same number of rows as df_A.

Ultimately, I would like to add a new 'label' column in df_A:

```<code>                              minMaxTuple                      label
            (2016-07-16 19:37:03, 2016-07-17 11:16:32)            1
            (2016-07-04 21:15:54, 2016-07-05 10:57:46)            1
            (2016-07-24 23:30:41, 2016-07-25 15:38:02)            0
            (2016-07-12 03:02:38, 2016-07-12 22:11:01)            1
</code>```

答:
One solution would be to see if a created_date in df_b falls between an amin and amax would be to use boolean logic. In a row-wise calculation for each row in df_a you could use the following logic:

```<code>if sum((row['amin'] > df_b['created_date']) | (row['amax'] < df_b['created_date'])) == len(df_b)
</code>```

In this stament I am using the logical operator | to check if amin is less than created_date OR if amax is less than created_date. If the statement is True you could conclude that a created date does not fall between the time period created by amin and amax. If none of the created_dates fall between the period created by amin and amax, you could then assign a value of 0 to df_a['label']: Something like:

```<code>import pandas as pd
from StringIO import StringIO

def myfunc(row, df_b):
    if sum((row['amin'] > df_b['created_date']) | (row['amax'] < df_b['created_date'])) == len(df_b):
        return 0
    else:
        return 1

a_str= """
amin,amax
2016-07-16 19:37:03,2016-07-17 11:16:32
2016-07-04 21:15:54,2016-07-05 10:57:46
2016-07-24 23:30:41,2016-07-25 15:38:02
2016-07-12 03:02:38,2016-07-12 22:11:01"""

b_str = """
created_date
2016-07-17 01:16:32
2016-07-05 10:15:54
2016-07-12 12:11:01"""
df_a = pd.read_csv(StringIO(a_str), sep=',')
df_b = pd.read_csv(StringIO(b_str), sep=',')

#Convert to datetime
df_a['amin'] = pd.to_datetime(df_a['amin'])
df_a['amax'] = pd.to_datetime(df_a['amax'])
df_b['created_date'] = pd.to_datetime(df_b['created_date'])

df_a['label'] = df_a.apply(lambda x: myfunc(x,df_b), axis=1)
</code>```

Which returns a column label in df_a with the expected output of:

```<code>                 amin                amax  label
0 2016-07-16 19:37:03 2016-07-17 11:16:32      1
1 2016-07-04 21:15:54 2016-07-05 10:57:46      1
2 2016-07-24 23:30:41 2016-07-25 15:38:02      0
3 2016-07-12 03:02:38 2016-07-12 22:11:01      1
</code>```

Body:
I have a dataframe, df_A with two columns 'amin' and 'amax', which is a set of time range.

My objective is to find whether a column in df_B lies between any of the rows of range in df_A 'amin' and 'amax' columns.

df_A[['amin','amax'] ]

                  amin                   amax
          0 2016-07-16 19:37:03   2016-07-17 11:16:32
          1 2016-07-04 21:15:54   2016-07-05 10:57:46
          2 2016-07-24 23:30:41   2016-07-25 15:38:02
          3 2016-07-12 03:02:38   2016-07-12 22:11:01

df_B['created_date']

      created_date
   2016-07-17 01:16:32
   2016-07-05 10:15:54
   2016-07-12 12:11:01

df_A['amin'] = pd.to_datetime(df_A['amin'], errors='coerce')
df_A['amax'] = pd.to_datetime(df_A['amax'], errors='coerce')
df_B['created_date'] = pd.to_datetime(df_B['created_date'],errors='coerce')

def dt2epoch(value):
   epoch = (value - pd.to_datetime(datetime(2015,12,31).strftime('%Y-%m-%d %H:%M:%S.%f'))).total_seconds()
   return epoch

df_A['amax_epoch']=df_A['amax'].apply(dt2epoch)
df_A['amin_epoch']=df_A['amin'].apply(dt2epoch)
df_B['created_date_epoch']=df_B['created_date'].apply(dt2epoch)

def make_tuple(row):
     n= len(row)
     row = [(x,row[n - 1]) for x in row]
     return row

minMaxTuple = minMax.apply(make_tuple, axis =1)

Above is part of my code, I've tried below(not sure if it's necessary):

convert them to epoch values

convert df_A into a tuple.

However, df_A and df_B has a different number of rows. Also, I dont have any id column to merge them together.

label = []

for l in df_B['created_date_epoch']:

    if (m[0] for m in minMaxTuple) <= l <= (m[1] for m in minMaxTuple):
        label.append('1')
    else:
        label.append('0')

However, when I run this, the result I get for 'label' is an empty list.

Also, the label should be a column that has the same number of rows as df_A.

Ultimately, I would like to add a new 'label' column in df_A:

                              minMaxTuple                      label
            (2016-07-16 19:37:03, 2016-07-17 11:16:32)            1
            (2016-07-04 21:15:54, 2016-07-05 10:57:46)            1
            (2016-07-24 23:30:41, 2016-07-25 15:38:02)            0
            (2016-07-12 03:02:38, 2016-07-12 22:11:01)            1

Body:
One solution would be to see if a created_date in df_b falls between an amin and amax would be to use boolean logic. In a row-wise calculation for each row in df_a you could use the following logic:

if sum((row['amin'] > df_b['created_date']) | (row['amax'] < df_b['created_date'])) == len(df_b)

In this stament I am using the logical operator | to check if amin is less than created_date OR if amax is less than created_date. If the statement is True you could conclude that a created date does not fall between the time period created by amin and amax. If none of the created_dates fall between the period created by amin and amax, you could then assign a value of 0 to df_a['label']: Something like:

import pandas as pd
from StringIO import StringIO

def myfunc(row, df_b):
    if sum((row['amin'] > df_b['created_date']) | (row['amax'] < df_b['created_date'])) == len(df_b):
        return 0
    else:
        return 1

a_str= """
amin,amax
2016-07-16 19:37:03,2016-07-17 11:16:32
2016-07-04 21:15:54,2016-07-05 10:57:46
2016-07-24 23:30:41,2016-07-25 15:38:02
2016-07-12 03:02:38,2016-07-12 22:11:01"""

b_str = """
created_date
2016-07-17 01:16:32
2016-07-05 10:15:54
2016-07-12 12:11:01"""
df_a = pd.read_csv(StringIO(a_str), sep=',')
df_b = pd.read_csv(StringIO(b_str), sep=',')

#Convert to datetime
df_a['amin'] = pd.to_datetime(df_a['amin'])
df_a['amax'] = pd.to_datetime(df_a['amax'])
df_b['created_date'] = pd.to_datetime(df_b['created_date'])

df_a['label'] = df_a.apply(lambda x: myfunc(x,df_b), axis=1)

Which returns a column label in df_a with the expected output of:

                 amin                amax  label
0 2016-07-16 19:37:03 2016-07-17 11:16:32      1
1 2016-07-04 21:15:54 2016-07-05 10:57:46      1
2 2016-07-24 23:30:41 2016-07-25 15:38:02      0
3 2016-07-12 03:02:38 2016-07-12 22:11:01      1


问:
Deshuffle text with C
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

```<code>1  X
4  T
3  Z
2  L
</code>```

And I wanted to deshuffle it and output another file as so:

```<code>1  X
2  L
3  Z
4  T
</code>```

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

答:
You can build a vector< pair<int,float[4]> > and just sort it using STL.

Just noticed a c tag.... But C idea is about the same:

Build an array with the data:

```<code>struct pair
{
    int idx;
    float val[4];
}

pair *data;
</code>```

And then just sort it.

Title: Deshuffle text with C

Body:
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

1  X
4  T
3  Z
2  L

And I wanted to deshuffle it and output another file as so:

1  X
2  L
3  Z
4  T

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

Body:
You can build a vector< pair<int,float[4]> > and just sort it using STL.

Just noticed a c tag.... But C idea is about the same:

Build an array with the data:

struct pair
{
    int idx;
    float val[4];
}

pair *data;

And then just sort it.


问:
Preventing to Bash script from running in parallel or overlap using cron
If i have the following entries in my cron table:

```<code>00 03 * * * /java_prog1.sh
00 5 * * * /java_prog2.sh
</code>```

The first job usually takes around 30 minutes to complete. The second job takes about 10 minutes. There are some exceptional situations where the first job takes more than two hours.

Is there a way i can configure the two jobs so that the second job does not start if the first one is still running?

I have seen several examples using tools like flock but i think flock does not apply here as i am not trying to prevent the same job running at the same time. I am trying to prevent another job to start if the previous one is still running.

答:
The creation of directories is atomic, so you could add this in both scripts:</p>

```<code>lock_dir=/tmp/name_of_lock_directory
if ! mkdir "$lock_dir"; then
    echo "Cannot run $0: lock directory $lock_dir exists" >&2
    exit 1
fi
cleanup () { rm -r "$lock_dir"; }
trap cleanup EXIT
# if you want, you can add the running pid to a file in the lock directory
echo $$ > "$lock_dir/pid"
</code>```

Body:
If i have the following entries in my cron table:

00 03 * * * /java_prog1.sh
00 5 * * * /java_prog2.sh

The first job usually takes around 30 minutes to complete. The second job takes about 10 minutes. There are some exceptional situations where the first job takes more than two hours.

Is there a way i can configure the two jobs so that the second job does not start if the first one is still running?

I have seen several examples using tools like flock but i think flock does not apply here as i am not trying to prevent the same job running at the same time. I am trying to prevent another job to start if the previous one is still running.

Body:
The creation of directories is atomic, so you could add this in both scripts:

lock_dir=/tmp/name_of_lock_directory
if ! mkdir "$lock_dir"; then
    echo "Cannot run $0: lock directory $lock_dir exists" >&2
    exit 1
fi
cleanup () { rm -r "$lock_dir"; }
trap cleanup EXIT
# if you want, you can add the running pid to a file in the lock directory
echo $$ > "$lock_dir/pid"


问:
How to delete specific elements in a vector using struct data type
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

```<code>struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};
</code>```

then

```<code>vector<QuestionInfo> vec;
</code>```

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

```<code>void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}
</code>```

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.

答:
You're getting tripped up by not accounting for the indexing shift that occurs when you erase an element. I personally would rely on remove_if and erase with a lambda to accomplish this:

```<code>vec.erase(remove_if(begin(vec), end(vec), [&](const auto& i) { return category_choice != i.category; }, end(vec));
vec.erase(remove_if(begin(vec), end(vec), [&](const auto& i) { return level_choice != i.level; }, end(vec));
</code>```

Alternatively you might consider combining them for a bit of speed improvement:

```<code>vec.erase(remove_if(begin(vec), end(vec), [&](const auto& i) { return category_choice != i.category || level_choice != i.level; }, end(vec));
</code>```

Body:
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};

then

vector<QuestionInfo> vec;

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.

Body:
You're getting tripped up by not accounting for the indexing shift that occurs when you erase an element. I personally would rely on remove_if and erase with a lambda to accomplish this:

vec.erase(remove_if(begin(vec), end(vec), [&](const auto& i) { return category_choice != i.category; }, end(vec));
vec.erase(remove_if(begin(vec), end(vec), [&](const auto& i) { return level_choice != i.level; }, end(vec));

Alternatively you might consider combining them for a bit of speed improvement:

vec.erase(remove_if(begin(vec), end(vec), [&](const auto& i) { return category_choice != i.category || level_choice != i.level; }, end(vec));


问:
BeautifulSoup4 import error
I'm trying to build a python code to check if a string contains HTML code. I've tried many times on re-intalling BeautifulSoup4 library by using pip3 install beautifulsoup4 and pip3 install lxml and it already shows me this:

```<code>Requirement already satisfied: beautifulsoup4
</code>```

But whenever I tried to import beautifulsoup it came out with this error code:

```<code>bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested
</code>```

What should I do to import the beautifulsoup library correctly?

Here is the chunk of code:

```<code>from bs4 import BeautifulSoup
body = "..."
bool(BeautifulSoup(body, "body.parser").find())
</code>```

Any help is appreciated. :)

答:
I consider the first sentence in your query first, 'I'm trying to build a python code to check if a string contains HTML code.'

BeautifulSoup is most probably not the tool one would use for this because it has been engineered to take almost any string as input, and produce a parsed HTML structure for that string.

For instance, here I input a string with no tags and all and BS gives back a complete page, even producing a body element for that page.

```<code>>>> import bs4
>>> s = 'this represents just about any string'
>>> soup = bs4.BeautifulSoup(s, 'lxml')
>>> soup
<html><body><p>this represents just about any string</p></body></html>
>>> soup.find_all('body')
[<body><p>this represents just about any string</p></body>]
</code>```

Here's an alternative, somewhat crude approach using HTMLParser. HTMLParser is in the standard Python library.

```<code>>>> from html.parser import HTMLParser
>>> class IsItHTML(HTMLParser):
...     def __init__(self):
...         HTMLParser.__init__(self)
...         self.found = False
...     def handle_starttag(self, tag, attrs):
...         self.found = True
...     def __call__(self):
...         return self.found
...
>>> isitHTML = IsItHTML()
>>> s = 'this represents just about any string'
>>> isitHTML.feed(s)
>>> isitHTML()
False
>>> s = '<body>something</body>'
>>> isitHTML.feed(s)
>>> isitHTML()
True
</code>```

The main criticism I have for this approach is that it involves traversing every tag in an HTML input.

Regarding your second principal question: how do I import BS correctly? I think you're doing that. The problem would appear to be with BeautifulSoup(body, "body.parser").find(). I have no idea what that might mean.

Title: BeautifulSoup4 import error

Body:
I'm trying to build a python code to check if a string contains HTML code. I've tried many times on re-intalling BeautifulSoup4 library by using pip3 install beautifulsoup4 and pip3 install lxml and it already shows me this:

Requirement already satisfied: beautifulsoup4

But whenever I tried to import beautifulsoup it came out with this error code:

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested

What should I do to import the beautifulsoup library correctly?

Here is the chunk of code:

from bs4 import BeautifulSoup
body = "..."
bool(BeautifulSoup(body, "body.parser").find())

Any help is appreciated. :)

Body:
I consider the first sentence in your query first, 'I'm trying to build a python code to check if a string contains HTML code.'

BeautifulSoup is most probably not the tool one would use for this because it has been engineered to take almost any string as input, and produce a parsed HTML structure for that string.

For instance, here I input a string with no tags and all and BS gives back a complete page, even producing a body element for that page.

>>> import bs4
>>> s = 'this represents just about any string'
>>> soup = bs4.BeautifulSoup(s, 'lxml')
>>> soup
<html><body><p>this represents just about any string</p></body></html>
>>> soup.find_all('body')
[<body><p>this represents just about any string</p></body>]

Here's an alternative, somewhat crude approach using HTMLParser. HTMLParser is in the standard Python library.

>>> from html.parser import HTMLParser
>>> class IsItHTML(HTMLParser):
...     def __init__(self):
...         HTMLParser.__init__(self)
...         self.found = False
...     def handle_starttag(self, tag, attrs):
...         self.found = True
...     def __call__(self):
...         return self.found
...
>>> isitHTML = IsItHTML()
>>> s = 'this represents just about any string'
>>> isitHTML.feed(s)
>>> isitHTML()
False
>>> s = '<body>something</body>'
>>> isitHTML.feed(s)
>>> isitHTML()
True

The main criticism I have for this approach is that it involves traversing every tag in an HTML input.

Regarding your second principal question: how do I import BS correctly? I think you're doing that. The problem would appear to be with BeautifulSoup(body, "body.parser").find(). I have no idea what that might mean.


问:
Age group counts using birthdate
I want to be able to get counts on each age group below using the customer's birthday. The customer also has to meet certain conditions. I need to use 2 tables.

```<code>18 to 25
26 to 35
36 to 45
46 to 55
56 to 65
65 and over
</code>```

using the following table and columns:

```<code>BRTH_DT - birthday
MSTR_CUST - customer table where BRTH_DT is
MSTR_ACT - account table where BR_CD is
BR_CD - code , I want to include all customer with code like '%00%'
CUST_ODT - customer open date from customer table, I want to include dates between '2017-11-01' and '2017-11-30'
</code>```

I have tried a few syntax but it doesn't work. I am using Hadoop.

Query:

```<code>SELECT  (
  CASE
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 18 AND 25
      THEN '18-25'
    ELSE
      CASE
        WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 26 AND 35
          THEN '26-35'
        ELSE
          CASE
            WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 36 AND 45
              THEN '36-45'
            ELSE
              CASE
                WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 46 AND 55
                  THEN '46-55'
                ELSE
                  CASE
                    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 56 AND 65
                      THEN '56-65'
                    ELSE
                      CASE
                        WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) > 65
                          THEN '65andOver'
  END) from MSTR_ACCT_A JOIN MSTR_CUST B
  where B.CUST_ODT between '2017-11-01' and '2017-11-30' and A.BR_CD like '%00%';
</code>```

答:
The query provided below should do the same thing that yours is aiming to do. I simplified your case when statements. I'm not sure if nesting case statements is a syntax error, but it overly complicates things. I also added a name to the column that will be created.</p>

```<code>SELECT
  CASE
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 18 AND 25
      THEN '18-25'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 26 AND 35
      THEN '26-35'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 36 AND 45
      THEN '36-45'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 46 AND 55
      THEN '46-55'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 56 AND 65
      THEN '56-65'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) > 65
      THEN '65andOver'
    END AS Age_Range
FROM MSTR_ACCT_A JOIN MSTR_CUST B
WHERE B.CUST_ODT BETWEEN '2017-11-01' AND '2017-11-30' AND A.BR_CD LIKE '%00%';
</code>```

Title: Age group counts using birthdate

Body:
I want to be able to get counts on each age group below using the customer's birthday. The customer also has to meet certain conditions. I need to use 2 tables.

18 to 25
26 to 35
36 to 45
46 to 55
56 to 65
65 and over

using the following table and columns:

BRTH_DT - birthday
MSTR_CUST - customer table where BRTH_DT is
MSTR_ACT - account table where BR_CD is
BR_CD - code , I want to include all customer with code like '%00%'
CUST_ODT - customer open date from customer table, I want to include dates between '2017-11-01' and '2017-11-30'

I have tried a few syntax but it doesn't work. I am using Hadoop.

Query:

SELECT  (
  CASE
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 18 AND 25
      THEN '18-25'
    ELSE
      CASE
        WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 26 AND 35
          THEN '26-35'
        ELSE
          CASE
            WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 36 AND 45
              THEN '36-45'
            ELSE
              CASE
                WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 46 AND 55
                  THEN '46-55'
                ELSE
                  CASE
                    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 56 AND 65
                      THEN '56-65'
                    ELSE
                      CASE
                        WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) > 65
                          THEN '65andOver'
  END) from MSTR_ACCT_A JOIN MSTR_CUST B
  where B.CUST_ODT between '2017-11-01' and '2017-11-30' and A.BR_CD like '%00%';

Body:
The query provided below should do the same thing that yours is aiming to do. I simplified your case when statements. I'm not sure if nesting case statements is a syntax error, but it overly complicates things. I also added a name to the column that will be created.

SELECT
  CASE
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 18 AND 25
      THEN '18-25'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 26 AND 35
      THEN '26-35'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 36 AND 45
      THEN '36-45'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 46 AND 55
      THEN '46-55'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) BETWEEN 56 AND 65
      THEN '56-65'
    WHEN EXTRACT (YEAR FROM (select sysdate from dual)) - EXTRACT (YEAR FROM BRTH_DT) > 65
      THEN '65andOver'
    END AS Age_Range
FROM MSTR_ACCT_A JOIN MSTR_CUST B
WHERE B.CUST_ODT BETWEEN '2017-11-01' AND '2017-11-30' AND A.BR_CD LIKE '%00%';


问:
Applicability of Reflection
There are some great articles out there such as this one on Reflection.

What I want to know is real world examples where it is used and real world reasons or when it's useful and why outside the raw "you can get type info"...I get all that in this article and others.

Ok, so what, it doesn't really help me in context to actual programming situations.  I'm trying to figure out how people are using it in apps, good examples of times that they have been used just to get my head wrapped around when you'd want to use it.

答:
Reflection is also useful when you are dealing with serialization. </p>

<p>Just recently I had to write some very custom serialization code for talking to a third party service, this meant using reflection to find properties, and determine whether the property was eligible to be serialized depending on the attribute. </p>

Title: Applicability of Reflection

Body:
Reflection is also useful when you are dealing with serialization.

Just recently I had to write some very custom serialization code for talking to a third party service, this meant using reflection to find properties, and determine whether the property was eligible to be serialized depending on the attribute.


问:
php - Laravel Search Controller
I am trying to make Laravel Search and stuck at point of handling POST data as an array in Eloquent way

HTML Form is as

```<code><form>
    <select name="hidArray[]">
       <option name="test">Test</option>
       <option name="test2">Test2</option>
    </select>
</form>
</code>```

Now, this input has been initialized as Bootstrap Multiselect

When i get input as POST request then it has been represented as an array like as below and which is expetced

```<code>array:2 [▼
0 => "test"
1 => "test2"
]
</code>```

Now, i want to form Eloquent query to get results from database.

I tried like as below:

```<code>if($request->has('hidArray')){
      $profile->whereIn('hidArray', $request->input('hidArray'));
}
</code>```

But i think, this way it is not working. Is there any other way i can perform this operation?

答:
I don't have exact idea what are you upto but according to what I understood.

You are trying to do something like:

```<code>$profile = ModelName::where('user_id',$id);

if($request->has('hidArray')){
      $profile = $profile->whereIn('hidArray', $request->input('hidArray'));
}

$profile = $profile->get();
</code>```

Title: php - Laravel Search Controller

Body:
I am trying to make Laravel Search and stuck at point of handling POST data as an array in Eloquent way

HTML Form is as

<form>
    <select name="hidArray[]">
       <option name="test">Test</option>
       <option name="test2">Test2</option>
    </select>
</form>

Now, this input has been initialized as Bootstrap Multiselect

When i get input as POST request then it has been represented as an array like as below and which is expetced

array:2 [▼
0 => "test"
1 => "test2"
]

Now, i want to form Eloquent query to get results from database.

I tried like as below:

if($request->has('hidArray')){
      $profile->whereIn('hidArray', $request->input('hidArray'));
}

But i think, this way it is not working. Is there any other way i can perform this operation?

Body:
I don't have exact idea what are you upto but according to what I understood.

You are trying to do something like:

$profile = ModelName::where('user_id',$id);

if($request->has('hidArray')){
      $profile = $profile->whereIn('hidArray', $request->input('hidArray'));
}

$profile = $profile->get();


问:
How to make jQuery countdown a constant one
I created a little countdown (I know it is not the correct term but don't know what is). It counts from one number to another for a specific time.

```<code><div class="headline">
  <p> How much remains to meet the goal? </p>
  </div>
<div class="loader">
  <span class="count">350000</span>
</div>

$('.count').each(function () {
    $(this).prop('Counter',336123).animate({
        Counter: $(this).text()
    }, {
        duration: 1728000000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
</code>```

You can see the code here:

The problem is that whenever the countdown is opened, these 20 days will start from this moment and from the originally assigned number.

How do I make the time start running from one moment run continuously, and when someone opens the page to see only the numbers that remain at the time of opening.

Excuse me for this bad explanation!

答:
You are going to need to store a value somewhere, somehow.

Since you are only needing to store one number you do not need to make a new table if you do not have a database associated with the project [seems unlikely].

Anyway, assuming that you write to a table, the page somewhere, or a different file - you do the following:

// check storage place and see if there is a value (if not, this is the first run of the counter)

// If it is the first run, same current time to storage place; if not, get starting time from the storage place.

// Use this starting time and subtract it from the current time to get elapsed time and then subtract and return [display] the remaining time.

not difficult to implement in any number of ways, I would need more details though to give a better answer.

Body:
I created a little countdown (I know it is not the correct term but don't know what is). It counts from one number to another for a specific time.

 How much remains to meet the goal?

  350000

$('.count').each(function () {
    $(this).prop('Counter',336123).animate({
        Counter: $(this).text()
    }, {
        duration: 1728000000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

You can see the code here:

The problem is that whenever the countdown is opened, these 20 days will start from this moment and from the originally assigned number.

How do I make the time start running from one moment run continuously, and when someone opens the page to see only the numbers that remain at the time of opening.

Excuse me for this bad explanation!


问:
C# How to determine a status of a Form
I have a tray app that starts ( Form 1 ) and shows on right click a "Login" menu strip item.
On click, I setup a Form 2, asking for user and pass.

On a successful authentication, I'd like to close Form 2 and continue with Form 1 ( ie. I would like to start a timer ).

I was thinking of just setting up a timer which would check the Form 2 status ( basically a getter function inside Form 2 ).

Still, I think there has to be an easier way than having something tick.

答:
You should show the login form using the ShowDialog method.

This method shows a modal dialog which will prevent the user from interacting with the rest of your application until the dialog is closed.

You should then perform authentication in the login form's button click handler, and close the form when it's successful.

Title: C# How to determine a status of a Form


问:
(PHP) Using oauth and service accounts to access private Google Photos (Picasa Web) API info
I would like to access info from a private Google Photos album owned by an account which I have access to. Could I log in as the owner of the album to obtain a token and access data? Or would a service account be able to access the data? I know the Picasa API is outdated, however this is the easiest way for me to mass-store photos and videos I want to publish on the web.</p>

答: Ok, so what I found, if you did make an old web album, like when Picasa was still around, it would have public read access. This is the only way to do this, but now I am working on using Imgur to do the same thing.</p>


问:
Symfony CollectionType: this value is not valid (TransformationFailedException)
I'm facing a weird error when customizing the form theme
"This value is not valid" when submitting a form containing a collection.

When the form is not customized, it's working as excepted.
When it's working, the name of an entry is
example[expOnlines][0][name]
when it's not it looks like example[expOnlines][0]

```<code>{% block _cv_expOnlines_widget %}
    <div class="col-md-12 mb-3">
        {{ block('collection_add_button') }}
    </div>

    <div class="c-form__field col-md-12">
        {{ block('collection_widget') }}
    </div>
{% endblock %}

{% block _cv_expOnlines_entry_row %}
    <div class="py-3 row" {{ block('row_container_attributes') }}>
        <div class="col-md-9">
            {{ block('form_widget_simple') }}
        </div>
        <div class="col-auto">
            {{ block('collection_delete_button') }}
        </div>
    </div>
{% endblock %}
</code>```

PHP side (but the bug is not there, because it only happens when overriding the form_theme)

This errors appears on all my CollectionType on the form

答:
Well, I was missing an important point,

It's not a form_widget_simple block. Instead I should do :
{{ block('form_widget') }}

That fixed the problem.

Body:
I'm facing a weird error when customizing the form theme
"This value is not valid" when submitting a form containing a collection.

When the form is not customized, it's working as excepted.
When it's working, the name of an entry is
example[expOnlines][0][name]
when it's not it looks like example[expOnlines][0]

{% block _cv_expOnlines_widget %}

        {{ block('collection_add_button') }}

        {{ block('collection_widget') }}

{% endblock %}

{% block _cv_expOnlines_entry_row %}

            {{ block('form_widget_simple') }}

            {{ block('collection_delete_button') }}

{% endblock %}

PHP side (but the bug is not there, because it only happens when overriding the form_theme)

This errors appears on all my CollectionType on the form


问:
How to put JSON data into a HTML div?
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="output"></div></code>```

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

答:
Your data variable it's a JS object you need to convert it to string or the format you want to show it before calling $('#output').html(data).
You can do something like:</p>

```<code>function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        console.log(data);
        data = JSON.stringify(data)
        $('#output').html(data); //what i try to do but don't work
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }
</code>```

Title: How to put JSON data into a HTML div?

Body:
Here is my problem: I want to put JSON data that I catch with an Ajax call in an HTML div.

function showEspece(espece, categorie, object) {
  $.ajax({
    type: 'POST',
    url: 'getespece.php',
    data: {
      espece: espece,
      categorie: categorie
    },
    dataType: 'json',
    success: function(data) {
      console.log(data);
      $('#output').html(data); //what i try to do but don't work
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
}

And here is what the variable data contains:

How can I show the variable's content in an HTML div - in a table particularly?

Body:
Your data variable it's a JS object you need to convert it to string or the format you want to show it before calling $('#output').html(data).
You can do something like:

function showEspece(espece, categorie, object)
  {
    $.ajax({
      type : 'POST',
      url: 'getespece.php',
      data: {espece: espece, categorie: categorie },
      dataType: 'json',
      success: function(data)
      {
        console.log(data);
        data = JSON.stringify(data)
        $('#output').html(data); //what i try to do but don't work
      },
      error: function(xhr, status, error) {
        console.log(error);
      }
    });
  }


问:
MKPointAnnotation flickers on mapView when on UITableViewCell. How to stop it?
I have a mapView on a UITableViewCell, when I display the mapView, the annotation flickers on and off. Im not sure how to make it stop.

I set up the mapView via

```<code>if let event = event {
            mapView.showsUserLocation = true
            mapView.isUserInteractionEnabled = true

            let center = CLLocationCoordinate2D(latitude: event.latitude, longitude: event.longitude)
            //Create annotation
            let annotation = MKPointAnnotation()
            annotation.coordinate = center
            mapView.addAnnotation(annotation)

            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))

            mapView.setRegion(region, animated: true)
        }
</code>```

I have made sure the annotation is only added to the map once.
Here is a video of it happening https://youtu.be/lkpn9Rqd0AE
Also, this only happens while there is no user interaction, if I scroll it stops doing it, also if I interact with the map it quits flickering.

I created a test project and it does not have this problem, even though I copied and pasted the above code. Im clueless to whats different.

答:
After contacting apple developer support, they told me that this was a bug not caused by my code.

Apple has said to remove and add decencies to find which breaks it, OR use the newest version of Xcode in which they fixed the bug. Downloading the newest version of Xcode solved my problem.

Body:
I have a mapView on a UITableViewCell, when I display the mapView, the annotation flickers on and off. Im not sure how to make it stop.

I set up the mapView via

if let event = event {
            mapView.showsUserLocation = true
            mapView.isUserInteractionEnabled = true

            let center = CLLocationCoordinate2D(latitude: event.latitude, longitude: event.longitude)
            //Create annotation
            let annotation = MKPointAnnotation()
            annotation.coordinate = center
            mapView.addAnnotation(annotation)

            let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005))

            mapView.setRegion(region, animated: true)
        }

I have made sure the annotation is only added to the map once.
Here is a video of it happening https://youtu.be/lkpn9Rqd0AE
Also, this only happens while there is no user interaction, if I scroll it stops doing it, also if I interact with the map it quits flickering.

I created a test project and it does not have this problem, even though I copied and pasted the above code. Im clueless to whats different.


问:
Where to extract manually downloaded android_m2repository_r36.zip?
I was having problem downloading this zip file(android_m2repository_r36.zip) using android studio as my internet connection is not that awesome. I downloaded the file using Internet Download Manager separately. Please provide steps to solve this problem. I'm on windows operating system.</p>

答:
The question is to old, but maybe others need to download last android_m2repository .

After download, unzip, copy/past the content on a path similar to

```<code> ..\android-sdks\extras\android\m2repository..
</code>```

.Hope its Helps.

Body:
The question is to old, but maybe others need to download last android_m2repository .

After download, unzip, copy/past the content on a path similar to

 ..\android-sdks\extras\android\m2repository..

.Hope its Helps.


问:
Cooccurrence in Mongodb
I am familiar with relational database such as MySQL. Recently I'm working on project that use MongoDb to stock 100,000 Documents. The structure of these Docs is as such:

```<code>    {
      "_id" : "1",
      "abstract" : "In this book, we present ....",
      "doi" : "xxxx/xxxxxx",
      "authors" : [
                   "Davis, a",
                   "louis, X",
                   "CUI, Li",
                   "FANG, Y"
                    ]
      }
</code>```

I would like to extract the cooccurrence matrix or cooccurrence value of all possible combination of authors (only pairs). the expected output is:

```<code>{ [auth1 , auth2 : 5 ] [auth1, auth3 : 1] [auth2, auth8 : 9]....}
</code>```

which means that auth1 and auth2 collaborate 5 times (in 5 books) auth2 and auth8 collaborate 9 times...

In relation database, possible solution could be:
in a table auth-book for example:

```<code>    INSERT INTO auth-book (id_book, id_auth) VALUES
              (1, 'auth1'),
              (1, 'auth2'),
              (1, 'auth3'),
              (2, 'auth1'),
              (2, 'auth5'),
              (2, 'auth87'),
              (2, 'auth2')...
</code>```

the query that calculate cooccurrence or collaboration of authors is:

```<code>     SELECT   a.id_auth a, b.id_auth b, COUNT(*) cnt
     FROM     auth-book a JOIN auth-booke b ON b.id_book= a.id_book AND   .id_auth > a.id_auth
     GROUP BY a.id_auth, b.id_auth
</code>```

output: [auth1 auth2 => 2][auth1 auth3 => 1][auth2 auth3 => 1]... etc.

I have no idea how to implement such a query in mongodb

答:
Probably not what you're looking for but this "works."   The challenge is creating the pairs list which is what the self join in SQL is doing.   Moving the pairing out of the query also means it is easier later to change from pairs to triples to whatever because the find() uses the $all function to ensure a match for any number of items.

```<code>c=db.foo.aggregate([
// Create single deduped list of authors:
{$unwind: "$authors"}
,{$group: {_id:null, uu: {$addToSet: "$authors"} }}
            ]);

doc = c.next(); // Get single doc output from above
ulist = doc['uu'];
c.close();

// Create unique pairs:
pairs = [];
for(var index = 0; index < ulist.length; index++) {
    var first = ulist[index];
    for(var p2 = index+1; p2 < ulist.length; p2++) {
        pairs.push([first, ulist[p2]]);
    }
}

// And now go get 'em:
pairs.forEach(function(qq) {
    n=db.foo.find({"authors": {$all: qq }}).count();
    print(qq[0] + "-" + qq[1] + ": " + n);
    });
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cooccurrence in Mongodb

Body:
I am familiar with relational database such as MySQL. Recently I'm working on project that use MongoDb to stock 100,000 Documents. The structure of these Docs is as such:

    {
      "_id" : "1",
      "abstract" : "In this book, we present ....",
      "doi" : "xxxx/xxxxxx",
      "authors" : [
                   "Davis, a",
                   "louis, X",
                   "CUI, Li",
                   "FANG, Y"
                    ]
      }

I would like to extract the cooccurrence matrix or cooccurrence value of all possible combination of authors (only pairs). the expected output is:

{ [auth1 , auth2 : 5 ] [auth1, auth3 : 1] [auth2, auth8 : 9]....}

which means that auth1 and auth2 collaborate 5 times (in 5 books) auth2 and auth8 collaborate 9 times...

In relation database, possible solution could be:
in a table auth-book for example:

    INSERT INTO auth-book (id_book, id_auth) VALUES
              (1, 'auth1'),
              (1, 'auth2'),
              (1, 'auth3'),
              (2, 'auth1'),
              (2, 'auth5'),
              (2, 'auth87'),
              (2, 'auth2')...

the query that calculate cooccurrence or collaboration of authors is:

     SELECT   a.id_auth a, b.id_auth b, COUNT(*) cnt
     FROM     auth-book a JOIN auth-booke b ON b.id_book= a.id_book AND   .id_auth > a.id_auth
     GROUP BY a.id_auth, b.id_auth

output: [auth1 auth2 => 2][auth1 auth3 => 1][auth2 auth3 => 1]... etc.

I have no idea how to implement such a query in mongodb

Body:
Probably not what you're looking for but this "works."   The challenge is creating the pairs list which is what the self join in SQL is doing.   Moving the pairing out of the query also means it is easier later to change from pairs to triples to whatever because the find() uses the $all function to ensure a match for any number of items.

c=db.foo.aggregate([
// Create single deduped list of authors:
{$unwind: "$authors"}
,{$group: {_id:null, uu: {$addToSet: "$authors"} }}
            ]);

doc = c.next(); // Get single doc output from above
ulist = doc['uu'];
c.close();

// Create unique pairs:
pairs = [];
for(var index = 0; index < ulist.length; index++) {
    var first = ulist[index];
    for(var p2 = index+1; p2 < ulist.length; p2++) {
        pairs.push([first, ulist[p2]]);
    }
}

// And now go get 'em:
pairs.forEach(function(qq) {
    n=db.foo.find({"authors": {$all: qq }}).count();
    print(qq[0] + "-" + qq[1] + ": " + n);
    });


问:
Dealing with a password with special characters in Ansible
I'm trying to run an ansible playbook with the ansible_ssh_pass option to connect to the destination server.

```<code>ansible-playbook test-playbook.yml -i hosts -u daniel --extra-vars "{"ansible_ssh_pass":"u5!vuL!<35Lf?<>n'x"}"
</code>```

The problem is that the password has special characters.
I tried saving it using.

```<code>"password\'s"
"password"
"\"password\""
</code>```

Any idea how can I save the password?

答:
If you remove the singe quote special char, you can do single quotes around the rest and it should work:</p>

```<code>ansible-playbook test-playbook.yml -i hosts -u daniel -e ansible_ssh_pass='u5!vuL!<35Lf?<>nx'
</code>```

Body:
I'm trying to run an ansible playbook with the ansible_ssh_pass option to connect to the destination server.

ansible-playbook test-playbook.yml -i hosts -u daniel --extra-vars "{"ansible_ssh_pass":"u5!vuL!<35Lf?<>n'x"}"

The problem is that the password has special characters.
I tried saving it using.

"password\'s"
"password"
"\"password\""

Any idea how can I save the password?

Body:
If you remove the singe quote special char, you can do single quotes around the rest and it should work:

ansible-playbook test-playbook.yml -i hosts -u daniel -e ansible_ssh_pass='u5!vuL!<35Lf?<>nx'


答: A good real-life example of reflection is Spring's Inversion of Control (IoC) framework in Java where you can wire your beans using XML configurations.</p>

Title: Applicability of Reflection

Body:
There are some great articles out there such as this one on Reflection.

What I want to know is real world examples where it is used and real world reasons or when it's useful and why outside the raw "you can get type info"...I get all that in this article and others.

Ok, so what, it doesn't really help me in context to actual programming situations.  I'm trying to figure out how people are using it in apps, good examples of times that they have been used just to get my head wrapped around when you'd want to use it.


问:
how to query with uncertainty a design view with complex nested keys
I'm having access on a CouchDB view which emits documents having keys of two arrays of four integers like [[int, int, int, int], [int, int, int, int]]. In a concrete example those correspond to start-date and end-date of the document:

```<code>[[2017, 5, 5, 10], [2017, 7, 2, 11]]
 Y      m  d  H     Y     m  d  H
</code>```

I'm able to get documents matching a period

```<code>request="localhorst/dbname/_design/a/_view/period"
request+="?key=\[\[2017,5,5,10\],\[2017,7,2,11\]\]"
curl -sX GET $request
</code>```

Question: How to ignore the "hour" field H?

What if the boundaries are partially unknown? How to get all documents within a given period, like 2017-05-05 until 2017-07-02? In other words, how can I ignore the last columns of each boundary?

I tried to use startKey and endKey

```<code>request="localhorst/dbname/_design/a/_view/period"
request+="?startKey=\[\[2017,5,5\],\[2017,7,2\]\]"
request+="&endKey=\[\[2017,5,5,\{\}\],\[2017,7,2,\{\}\]\]"
curl -sX GET $request
</code>```

This does not work since it gets documents with the correct lower bound but the upper bound is wrong, e.g.:

```<code>[[2017,4,5,10],[2017,7,2,12]] <- excluded,  OK
[[2017,5,5,10],[2017,7,2,12]] <- contained, OK
[[2017,5,5,11],[2017,7,2,12]] <- contained, OK
[[2017,5,5,10],[2017,8,2,12]] <- contained, ERROR
</code>```

答:
It's not possible. If you use complex keys, you can perform partial matches with startkey and endkey by dropping items to the right of the key array only, not by dropping items internally in the key array.

Without knowing how your documents are structured, it's difficult to offer more than generic advice. I'd look to emit a single time stamp vector and use startkey and endkey to find the range, rather than trying to use the range as the key. However, this approach might not fit your model.

Otherwise, as suggested above, using Mango may be your best bet.

Body:
I'm having access on a CouchDB view which emits documents having keys of two arrays of four integers like [[int, int, int, int], [int, int, int, int]]. In a concrete example those correspond to start-date and end-date of the document:

[[2017, 5, 5, 10], [2017, 7, 2, 11]]
 Y      m  d  H     Y     m  d  H

I'm able to get documents matching a period

request="localhorst/dbname/_design/a/_view/period"
request+="?key=\[\[2017,5,5,10\],\[2017,7,2,11\]\]"
curl -sX GET $request

Question: How to ignore the "hour" field H?

What if the boundaries are partially unknown? How to get all documents within a given period, like 2017-05-05 until 2017-07-02? In other words, how can I ignore the last columns of each boundary?

I tried to use startKey and endKey

request="localhorst/dbname/_design/a/_view/period"
request+="?startKey=\[\[2017,5,5\],\[2017,7,2\]\]"
request+="&endKey=\[\[2017,5,5,\{\}\],\[2017,7,2,\{\}\]\]"
curl -sX GET $request

This does not work since it gets documents with the correct lower bound but the upper bound is wrong, e.g.:

[[2017,4,5,10],[2017,7,2,12]] <- excluded,  OK
[[2017,5,5,10],[2017,7,2,12]] <- contained, OK
[[2017,5,5,11],[2017,7,2,12]] <- contained, OK
[[2017,5,5,10],[2017,8,2,12]] <- contained, ERROR


问:
What does scikit-learn DecisionTreeClassifier.tree_.value do?
I am working on a DecisionTreeClassifier model and I want to understand the path chosen by the model. So I need to know what values give the

DecisionTreeClassifier.tree_.value
```

答:
Well, you are correct in that the documentation is actually obscure about this (but to be honest, I am not sure about its usefulness, too).

Let's replicate the example from the documentation with the iris data:

from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
```
<p>Asking for <code>clf.tree_.value</code>, we get:</p>
<pre class="lang-python prettyprint-override"><code>array([[[ 50.,  50.,  50.]],
       [[ 50.,   0.,   0.]],
       [[  0.,  50.,  50.]],
       [[  0.,  49.,   5.]],
       [[  0.,  47.,   1.]],
       [[  0.,  47.,   0.]],
       [[  0.,   0.,   1.]],
       [[  0.,   2.,   4.]],
       [[  0.,   0.,   3.]],
       [[  0.,   2.,   1.]],
       [[  0.,   2.,   0.]],
       [[  0.,   0.,   1.]],
       [[  0.,   1.,  45.]],
       [[  0.,   1.,   2.]],
       [[  0.,   1.,   0.]],
       [[  0.,   0.,   2.]],
       [[  0.,   0.,  43.]]])
</code>```

and

len(clf.tree_.value)
# 17
```

To realize what exactly this array represents it is useful to look at the tree visualization (also available in the docs, reproduced here for convenience):

As we can see, the tree has 17 nodes; looking closer, we see that the value of each node is actually an element of our clf.tree_.value array.

So, to make a long story short:

clf.tree_.value is an array of arrays, of length equal to the number of nodes in the tree

Each of its element arrays (which corresponds to a tree node) is of length equal to the number of classes (here 3)

Each of these 3-element arrays corresponds to the amount of training samples that end up in the respective node for each class.

To clarify on the last point with an example, consider the second element of the array, [[ 50.,   0.,   0.]] (which corresponds to the orange-colored node): it says that, in this node, end up 50 samples from the class #0, and zero samples from the other two classes (#1 and #2).

Body:
Well, you are correct in that the documentation is actually obscure about this (but to be honest, I am not sure about its usefulness, too).

Let's replicate the example from the documentation with the iris data:

from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)

Asking for clf.tree_.value, we get:

array([[[ 50.,  50.,  50.]],
       [[ 50.,   0.,   0.]],
       [[  0.,  50.,  50.]],
       [[  0.,  49.,   5.]],
       [[  0.,  47.,   1.]],
       [[  0.,  47.,   0.]],
       [[  0.,   0.,   1.]],
       [[  0.,   2.,   4.]],
       [[  0.,   0.,   3.]],
       [[  0.,   2.,   1.]],
       [[  0.,   2.,   0.]],
       [[  0.,   0.,   1.]],
       [[  0.,   1.,  45.]],
       [[  0.,   1.,   2.]],
       [[  0.,   1.,   0.]],
       [[  0.,   0.,   2.]],
       [[  0.,   0.,  43.]]])

and

len(clf.tree_.value)
# 17

To realize what exactly this array represents it is useful to look at the tree visualization (also available in the docs, reproduced here for convenience):

As we can see, the tree has 17 nodes; looking closer, we see that the value of each node is actually an element of our clf.tree_.value array.

So, to make a long story short:

clf.tree_.value is an array of arrays, of length equal to the number of nodes in the tree

Each of its element arrays (which corresponds to a tree node) is of length equal to the number of classes (here 3)

Each of these 3-element arrays corresponds to the amount of training samples that end up in the respective node for each class.

To clarify on the last point with an example, consider the second element of the array, [[ 50.,   0.,   0.]] (which corresponds to the orange-colored node): it says that, in this node, end up 50 samples from the class #0, and zero samples from the other two classes (#1 and #2).


答:
Let me explain you the problem with my example. Suppose you have a vector of 10 elements, valid indexes are 0 till 9 elements. You have to erase 5th element i == 4. You erase it, then 6th element with index 5 moves to place of 5th elements with index 4. After that you increase i in for, it becomes 5. Thus you skip previous 6th element, that is now 5th with index 4.

You may fix your code like below, moving i ++ to the condition.

```<code>for (unsigned int i = 0; i < vec.size(); ) {
    if (category_choice != vec[i].category)
        vec.erase(vec.begin() + i );
    else
        i ++;
}
</code>```

The preferable solution in C++ way is demonstrated by @Jonathan.

Title: How to delete specific elements in a vector using struct data type

Body:
i'm new to C++. My program is a quiz game which user can choose category and level for the questions. At first, i use the struct data type

struct QuestionInfo
{
   string category;
   string level;
   string question;
   string answer;
};

then

vector<QuestionInfo> vec;

The idea of this part is to store the info of the question include (category, level, question and answer) to each element.
Then after building menu and the output questions UI, i go to the filters

void category_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (category_choice != vec[i].category)
         vec.erase(vec.begin() + i );
   }
}
Void level_filter()
{
   for (unsigned int i = 0; i < vec.size(); i ++)
   {
      if (level_choice != vec[i].level)
         vec.erase(vec.begin() + i );
   }
}

So the idea of the filters is to delete the elements which not contain the matched category and level. But the output questions did not match with the category and the level i had choose before.  I'm not sure what I'm doing wrong.

Body:
Let me explain you the problem with my example. Suppose you have a vector of 10 elements, valid indexes are 0 till 9 elements. You have to erase 5th element i == 4. You erase it, then 6th element with index 5 moves to place of 5th elements with index 4. After that you increase i in for, it becomes 5. Thus you skip previous 6th element, that is now 5th with index 4.

You may fix your code like below, moving i ++ to the condition.

for (unsigned int i = 0; i < vec.size(); ) {
    if (category_choice != vec[i].category)
        vec.erase(vec.begin() + i );
    else
        i ++;
}

The preferable solution in C++ way is demonstrated by @Jonathan.


问:
Member of a class which is a pointer to another class
I have two classes, HouseSecurity and HomeOwner. One of the data members of HomeOwner is a pointer to House Security. In my HomeOwner method I'm trying to call a function from HouseSecurity via the pointer, but I can't find a way that I can call it. The line currentSensorState = house.getSensorState() is the one causing me problems. Any ideas?
Thanks! </p>

```<code>class HouseSecurity : virtual public SecurityStatus{
        SensorInfo mySensorStatus;
public:
        SensorInfo getSensorStatus();
        void setSensorStatus(SensorInfo);
};

class HomeOwner : virtual public IObserver{
    SensorInfo currentSensorState;  // Current state of sensors
    string myName;                  // Personal information pf HomeOwner
    string myPhoneNumber;
    string myEmail;
    HouseSecurity *house;           // HouseSecurity pointer

public:
    HomeOwner (string, string, string, HouseSecurity *); // Constructor
    void Update();      // Called from Notify function in HouseSecurity class
};

// HomeOwner Method
// HomeOwner constructor
HomeOwner::HomeOwner(string name, string number, string email, HouseSecurity *home){
    myName = name;
    myPhoneNumber = number;
    myEmail = email;
    house = home;   // pointer to House Security in the system
}

// Checks the status of the sensors and updates each of the
void HomeOwner::Update(){
    cout << "test update" << house << endl;
    currentSensorState = house.getSensorStatus();
    cout << "HomeOwner " << myName << " says that the status of windows 1, 2 and door are " << currentSensorState.getWin1State() << " " << currentSensorState.getWin2State() << " "
        << currentSensorState.getDoorState();
}
</code>```

答:
When trying to access members of pointer, the pointer needs to be dereferenced. The shortcut is to use the -> operator as in:

house->getSensorStatus();

Body:
I have two classes, HouseSecurity and HomeOwner. One of the data members of HomeOwner is a pointer to House Security. In my HomeOwner method I'm trying to call a function from HouseSecurity via the pointer, but I can't find a way that I can call it. The line currentSensorState = house.getSensorState() is the one causing me problems. Any ideas?
Thanks!

class HouseSecurity : virtual public SecurityStatus{
        SensorInfo mySensorStatus;
public:
        SensorInfo getSensorStatus();
        void setSensorStatus(SensorInfo);
};

class HomeOwner : virtual public IObserver{
    SensorInfo currentSensorState;  // Current state of sensors
    string myName;                  // Personal information pf HomeOwner
    string myPhoneNumber;
    string myEmail;
    HouseSecurity *house;           // HouseSecurity pointer

public:
    HomeOwner (string, string, string, HouseSecurity *); // Constructor
    void Update();      // Called from Notify function in HouseSecurity class
};

// HomeOwner Method
// HomeOwner constructor
HomeOwner::HomeOwner(string name, string number, string email, HouseSecurity *home){
    myName = name;
    myPhoneNumber = number;
    myEmail = email;
    house = home;   // pointer to House Security in the system
}

// Checks the status of the sensors and updates each of the
void HomeOwner::Update(){
    cout << "test update" << house << endl;
    currentSensorState = house.getSensorStatus();
    cout << "HomeOwner " << myName << " says that the status of windows 1, 2 and door are " << currentSensorState.getWin1State() << " " << currentSensorState.getWin2State() << " "
        << currentSensorState.getDoorState();
}


问:
Compressing a JPG image to a given size in KB?
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

```<code>public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}
</code>```

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

答:
For better picture quality first, save the file to storage and then compress it. It helps the user to have the best quality image for there own use.
In some of my projects, I am using this library
https://android-arsenal.com/details/1/3758
this is a very good library and it compresses well.
If you need a File then use this

```<code>compressedImage = new Compressor(this)
        .setMaxWidth(640)
        .setMaxHeight(480)
        .setQuality(75)
        .setCompressFormat(Bitmap.CompressFormat.WEBP)
        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
          Environment.DIRECTORY_PICTURES).getAbsolutePath())
        .compressToFile(actualImage);
</code>```

or if you need a bitmap than this

```<code>compressedImageBitmap = new Compressor(this).compressToBitmap(actualImageFile);
</code>```

Happy Coding :)

Body:
I have a byte array returned by the camera in input.

I need to scale down my image to make its size equal to 500KB. I am trying to achieve this using a Bitmap, but I cannot find how to get the proper compression value.

public static byte[] compressCapture(byte[] capture) {

    // How to get the right compression value ?
    int compression = 50;

    Bitmap bitmap  = BitmapFactory.decodeByteArray(capture, 0, capture.length);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, compression, outputStream);
    return outputStream.toByteArray();
}

The problem is that the compression is not proportional to the image size, meaning that compression equals to 50 will not divide the image size by 2.

Is there a way to get a fixed image size in output that does not depend on the focus, or the smartphone model ?

EDIT :

I do not want to use a File (I work with confidential data).

Body:
For better picture quality first, save the file to storage and then compress it. It helps the user to have the best quality image for there own use.
In some of my projects, I am using this library
https://android-arsenal.com/details/1/3758
this is a very good library and it compresses well.
If you need a File then use this

compressedImage = new Compressor(this)
        .setMaxWidth(640)
        .setMaxHeight(480)
        .setQuality(75)
        .setCompressFormat(Bitmap.CompressFormat.WEBP)
        .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
          Environment.DIRECTORY_PICTURES).getAbsolutePath())
        .compressToFile(actualImage);

or if you need a bitmap than this

compressedImageBitmap = new Compressor(this).compressToBitmap(actualImageFile);

Happy Coding :)


问:
How to retrieve an itemName from firebase and use it for a searchView?
I tried to retrieve itemName from Firebase and tried to use it for searchView. And I don't know what's wrong with my logic in the following code.

So here is my database

And here's my datasnapshot:-

```<code> protected void onStart() {
    super.onStart();

    databaseItems.child("items").orderByChild("itemName").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            itemFinalList.clear();
            for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
                ItemInventory itemInventoryTest = itemSnapShot.getValue(ItemInventory.class);

                itemFinalList.add(itemInventoryTest);

            }

            ItemList adapter = new ItemList(SearchActivity.this, itemFinalList);
            listFinal.setAdapter(adapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
</code>```

And searchview function

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_search, menu);
    MenuItem item = menu.findItem(R.id.menuSearch);
    SearchView searchView = (SearchView) item.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            return false;
        }
    });
    return super.onCreateOptionsMenu(menu);
}
</code>```

And here's my "itemList" class as this is being used in my datasnapshot:-

```<code>public class ItemList extends ArrayAdapter<ItemInventory> {

    private Activity context;
    private List<ItemInventory> items;

    public ItemList(Activity context, List<ItemInventory> items) {
        super(context, R.layout.list_layout, items);
        this.context = context;
        this.items = items;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();

        View listViewItem = inflater.inflate(R.layout.list_layout, null, true);

        TextView textViewCategory = (TextView) listViewItem.findViewById(R.id.textViewCategory);
        TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
        TextView textViewCost = (TextView) listViewItem.findViewById(R.id.textViewCost);
        final TextView textViewCount = (TextView) listViewItem.findViewById(R.id.textViewCount);

        ItemInventory itemInventoryTest = items.get(position);

        textViewCategory.setText(itemInventoryTest.getItemCategory());
        textViewName.setText(itemInventoryTest.getItemName());
        textViewCost.setText(itemInventoryTest.getItemCost());
        textViewCount.setText(itemInventoryTest.getItemCount());

        return listViewItem;

    }
}
</code>```

I can also create a new class for searchList where I change my data types.

答:
```<code> //under class declaration do this:
   private ArrayList<String> itemlists;

itemLists=new ArrayList<String>();
 databaseItems.child("items").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
            String itemname=itemSnapShot.child("itemName").getValue().toString();

            itemlists.add(itemname);
ArrayAdapter adapter = new ArrayAdapter(SearchActivity.this,android.R.layout.simple_list_item_1 itemlists);
        listFinal.setAdapter(adapter);

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
}
</code>```

Try the above, put the clear() before onDataChange thats why it is not working,everytime you are trying to retrieve, you are also clearing the list. Put the clear() before to avoid duplicate values when starting the activity.

Body:
I tried to retrieve itemName from Firebase and tried to use it for searchView. And I don't know what's wrong with my logic in the following code.

So here is my database

And here's my datasnapshot:-

 protected void onStart() {
    super.onStart();

    databaseItems.child("items").orderByChild("itemName").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            itemFinalList.clear();
            for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
                ItemInventory itemInventoryTest = itemSnapShot.getValue(ItemInventory.class);

                itemFinalList.add(itemInventoryTest);

            }

            ItemList adapter = new ItemList(SearchActivity.this, itemFinalList);
            listFinal.setAdapter(adapter);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

And searchview function

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_search, menu);
    MenuItem item = menu.findItem(R.id.menuSearch);
    SearchView searchView = (SearchView) item.getActionView();

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            adapter.getFilter().filter(newText);
            return false;
        }
    });
    return super.onCreateOptionsMenu(menu);
}

And here's my "itemList" class as this is being used in my datasnapshot:-

public class ItemList extends ArrayAdapter<ItemInventory> {

    private Activity context;
    private List<ItemInventory> items;

    public ItemList(Activity context, List<ItemInventory> items) {
        super(context, R.layout.list_layout, items);
        this.context = context;
        this.items = items;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();

        View listViewItem = inflater.inflate(R.layout.list_layout, null, true);

        TextView textViewCategory = (TextView) listViewItem.findViewById(R.id.textViewCategory);
        TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
        TextView textViewCost = (TextView) listViewItem.findViewById(R.id.textViewCost);
        final TextView textViewCount = (TextView) listViewItem.findViewById(R.id.textViewCount);

        ItemInventory itemInventoryTest = items.get(position);

        textViewCategory.setText(itemInventoryTest.getItemCategory());
        textViewName.setText(itemInventoryTest.getItemName());
        textViewCost.setText(itemInventoryTest.getItemCost());
        textViewCount.setText(itemInventoryTest.getItemCount());

        return listViewItem;

    }
}

I can also create a new class for searchList where I change my data types.

Body:
 //under class declaration do this:
   private ArrayList<String> itemlists;

itemLists=new ArrayList<String>();
 databaseItems.child("items").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
            String itemname=itemSnapShot.child("itemName").getValue().toString();

            itemlists.add(itemname);
ArrayAdapter adapter = new ArrayAdapter(SearchActivity.this,android.R.layout.simple_list_item_1 itemlists);
        listFinal.setAdapter(adapter);

        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
}

Try the above, put the clear() before onDataChange thats why it is not working,everytime you are trying to retrieve, you are also clearing the list. Put the clear() before to avoid duplicate values when starting the activity.