问:
Python threads garbage collection
Is a running thread eligable for garbage collection if the thread object is reasigned? For example:

```<code>class A(threading.Thread)
    def run():
        while True:
            #Do stuff

a = A()
a.start()
time.sleep(60)
a = A()
</code>```

at this point, even though thread A is still doing stuff, can the interpreter destroy the original A() thread? If it does, is there a way to prevent this from happening?

答: Threads wont get deleted like that, but I guess the problem you have is that threads disappear for no reason? A unhandled Exception will kill a thread without affecting the main thread! It only prints the traceback to stderr, but you might not see that ...

Title: Python threads garbage collection

Body:
Is a running thread eligable for garbage collection if the thread object is reasigned? For example:

class A(threading.Thread)
    def run():
        while True:
            #Do stuff

a = A()
a.start()
time.sleep(60)
a = A()

at this point, even though thread A is still doing stuff, can the interpreter destroy the original A() thread? If it does, is there a way to prevent this from happening?


来源: stackexchange

问:
Handling multiple MongoDB databases with Eve
I have many MongoDB databases, all containing the same collection. I want to expose these data with Eve.

I would like to invoke a GET to /aaa/bbb/mycoll and get data from collection mycoll in e.g. DB mydb_aaa_bbb.

My question is: is this possible and in case how can I do that?

My guess is that I should set the DB name programmatically using event hooks, or maybe by exploiting the mongo_prefix mechanism.

答: You should be able to do that with Eve 0.6 or higher. Check out mongo_prefix option in configuration and the example how to use it. Of course, for your use case, you should figure out which database to use from URL in some of the event hooks, just like you mentioned.

ContentLicense: CC BY-SA 3.0


答:
You want to use the groupby method of dataframes.

```<code>df.groupby(['user_id','product_id'])['days_since_prior_order'].mean()
</code>```

Will return the average time since prior order per unique user id for each product id that customer has ordered.

Title: Python pandas count specific statistic

Body:
I have DataFrame in pandas which looks like this:

| index | order_id | product_id | user_id | days_since_prior_order | order_number |
|-------|----------|------------|---------|------------------------|--------------|
| 0     | 177      | 21903      | 48308   | 8.0                    | 27           |
| 1     | 177      | 40723      | 48308   | 8.0                    | 27           |
| 2     | 177      | 27531      | 48308   | 8.0                    | 27           |
| 3     | 177      | 1158       | 48308   | 8.0                    | 27           |
| 4     | 177      | 37766      | 48308   | 8.0                    | 27           |
| 5     | 177      | 48299      | 48308   | 8.0                    | 27           |
| 6     | 177      | 46802      | 48308   | 8.0                    | 27           |
| 7     | 177      | 38159      | 48308   | 8.0                    | 27           |
| 8     | 177      | 35055      | 48308   | 8.0                    | 27           |
| 9     | 177      | 40311      | 48308   | 8.0                    | 27           |
| 10    | 177      | 5022       | 48308   | 8.0                    | 27           |
| 11    | 177      | 19906      | 48308   | 8.0                    | 27           |
| 12    | 177      | 29987      | 48308   | 8.0                    | 27           |
| 13    | 177      | 9076       | 48308   | 8.0                    | 27           |
| 14    | 177      | 43352      | 48308   | 8.0                    | 27           |
| 15    | 177      | 33731      | 48308   | 8.0                    | 27           |
| 16    | 177      | 24852      | 48308   | 8.0                    | 27           |
| 17    | 220      | 3919       | 63952   | 6.0                    | 26           |
| 18    | 220      | 11432      | 63952   | 6.0                    | 26           |
| 19    | 220      | 14992      | 63952   | 6.0                    | 26           |
| 20    | 378      | 13249      | 128710  | 2.0                    | 66           |
| 21    | 378      | 43693      | 128710  | 2.0                    | 66           |
| 22    | 946      | 1529       | 157339  | 3.0                    | 10           |
| 23    | 946      | 20734      | 157339  | 3.0                    | 10           |
| 24    | 946      | 22935      | 157339  | 3.0                    | 10           |
| 25    | 946      | 26728      | 157339  | 3.0                    | 10           |

This is not the full dataset, just small part of the table.
What I want to do is count mean days between product reorder for each user. So for each user we take all orders which contain the specific product_id and then calculate time between these orders (including other orders without this product) ((we use order_number to determine orders' order)) and then take mean of that. I want to do it with pandas because the dataset is very big and I don't have so many RAM and resources to calculate that using classic python code. How can I do that?

Edit:
I seem not to be clear enough. What i want is when user orders a product multiple times count days between this product orders and for every product Id calculate mean. So i want to know how ofter is the product ordered.

Edit 2:
I made a csv for one user so you could take a look at how this df looks like :df_for_one_user.csv

Edit 3: "days_since_prior_order" is just days between this and previous order for user. The problem is that between could be an order without specific product.

Body:
You want to use the groupby method of dataframes.

df.groupby(['user_id','product_id'])['days_since_prior_order'].mean()

Will return the average time since prior order per unique user id for each product id that customer has ordered.


问:
how to fix error in std::vector<int> WidthNumbers = 320, 640, 1280;?
So I try to do something like   std::vector<int> WidthNumbers = 320, 640, 1280; but compiler gives me error C2440: 'int' to 'std::vector<_Ty>'

答:
This is slightly more work, but I find it works very well with VS 2010. Instead of using an Initializer List, you can manually add items to the vector using the _vector.push_back() method like so:

```<code>//forward declarations
#include <vector>
#include <iostream>
using namespace std;
// main() function
int _tmain(int argc, _TCHAR *argv)
{
     // declare vector
     vector<int> _vector;
     // fill vector with items
     _vector.push_back(1088);
     _vector.push_back(654);
     _vector.push_back(101101);
     _vector.push_back(123456789);
     // iterate through the vector and print items to the console
     vector<int>::iterator iter = _vector.begin();
     while(iter != _vector.end())
     {
          cout << *iter << endl;
          iter++;
     }
     // pause so you can read the output
     system("PAUSE");
     // end program
     return 0;
 }
</code>```

This is the way I personally declare and initialize vectors, it always works for me

ContentLicense: CC BY-SA 2.5

Body:
This is slightly more work, but I find it works very well with VS 2010. Instead of using an Initializer List, you can manually add items to the vector using the _vector.push_back() method like so:

//forward declarations
#include <vector>
#include <iostream>
using namespace std;
// main() function
int _tmain(int argc, _TCHAR *argv)
{
     // declare vector
     vector<int> _vector;
     // fill vector with items
     _vector.push_back(1088);
     _vector.push_back(654);
     _vector.push_back(101101);
     _vector.push_back(123456789);
     // iterate through the vector and print items to the console
     vector<int>::iterator iter = _vector.begin();
     while(iter != _vector.end())
     {
          cout << *iter << endl;
          iter++;
     }
     // pause so you can read the output
     system("PAUSE");
     // end program
     return 0;
 }

This is the way I personally declare and initialize vectors, it always works for me


答:
Not sure what exactly you want, but something similar to</p>

```<code>df.groupby(['user_id','product_id'])['days_since_prior_order'].mean()
</code>```

Title: Python pandas count specific statistic

Body:
Not sure what exactly you want, but something similar to

df.groupby(['user_id','product_id'])['days_since_prior_order'].mean()


问:
d3.each() index doesn't begin at 0
My question is very similar to this. The solution there was that there was a
 messing things up. There are no <divs> in mine.

I have this CoffeeScript code:

```<code>data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )
</code>```

With the desired console output being:

```<code>0 0
1 1
2 2
3 3
4 4
</code>```

The actual console output is:

```<code>1 1
2 2
3 3
4 4
</code>```

I can get the desired output with this code:

```<code>data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .each((d, i) =>
    console.log(i, d)
  ).enter()
   .each((d, i) =>
    console.log(i, d)
  )
</code>```

But it just feels wrong to have two .each() calls.

答:
Take a look at this
and basically this:
https://stackoverflow.com/a/19726610/3433323

Quoting:
You need to select the non-existent elements as well for the selections to work properly. ... At the moment, the selection you're matching data against contains only the one element
Which means you are selecting against the body only.

In short:

```<code>data = [0, 1, 2, 3, 4]
d3.selectAll("body")
  .selectAll('div') // add this
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )
</code>```

jsfiddle

About selectAll

Title: d3.each() index doesn't begin at 0

Body:
My question is very similar to this. The solution there was that there was a
 messing things up. There are no <divs> in mine.

I have this CoffeeScript code:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )

With the desired console output being:

0 0
1 1
2 2
3 3
4 4

The actual console output is:

1 1
2 2
3 3
4 4

I can get the desired output with this code:

data = [0, 1, 2, 3, 4]
d3.select("body")
  .data(data)
  .each((d, i) =>
    console.log(i, d)
  ).enter()
   .each((d, i) =>
    console.log(i, d)
  )

But it just feels wrong to have two .each() calls.

Body:
Take a look at this
and basically this:
https://stackoverflow.com/a/19726610/3433323

Quoting:
You need to select the non-existent elements as well for the selections to work properly. ... At the moment, the selection you're matching data against contains only the one element
Which means you are selecting against the body only.

In short:

data = [0, 1, 2, 3, 4]
d3.selectAll("body")
  .selectAll('div') // add this
  .data(data)
  .enter()
  .each((d, i) =>
    console.log(i, d)
  )

jsfiddle

About selectAll


问:
Django 1.11 upgrade - object has no attribute 'password'
I've been running fine on Django 1.7.  I'm trying to upgrade to 1.11.

I'm getting the following error on 1.11 and I can't seem to find the problem.

Here's the code in question:

```<code>class Profile(models.Model):
    profile_id = models.CharField(max_length=50, null=True, unique=True, db_index=True)
    pet_shop_customer_id = models.CharField(max_length=40)
    django_user = models.OneToOneField(User, to_field='username', parent_link=True, null=True,
                                       db_column="django_username", default=None, db_index=True, db_constraint=False)
</code>```

The problem is when I call:

```<code>profile = Profile.objects.get(profile_id='x')  # pulls a valid profile
print profile.django_user
</code>```

I get this error:

Exception Value:

```<code>'Profile' object has no attribute 'password'

Exception Location:     /Users/../lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py in <dictcomp>, line 291
</code>```

答: As @adrien mentioned in the comment, that was the issue.  I had to remove the parent_link=True in the one to one field to User.</p>

Body:
I've been running fine on Django 1.7.  I'm trying to upgrade to 1.11.

I'm getting the following error on 1.11 and I can't seem to find the problem.

Here's the code in question:

class Profile(models.Model):
    profile_id = models.CharField(max_length=50, null=True, unique=True, db_index=True)
    pet_shop_customer_id = models.CharField(max_length=40)
    django_user = models.OneToOneField(User, to_field='username', parent_link=True, null=True,
                                       db_column="django_username", default=None, db_index=True, db_constraint=False)

The problem is when I call:

profile = Profile.objects.get(profile_id='x')  # pulls a valid profile
print profile.django_user

I get this error:

Exception Value:

'Profile' object has no attribute 'password'

Exception Location:     /Users/../lib/python2.7/site-packages/django/db/models/fields/related_descriptors.py in <dictcomp>, line 291


问:
Check first element of the array needs to be unique
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

```<code>public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}
</code>```

答:
To check if the first element is unique, you can use the following:

```<code>Collections.frequency(Arrays.asList(stringArray), stringArray[0]) == 1
</code>```

This returns a boolean that is true if the first element of stringArray is unique, otherwise false.

Body:
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}

Body:
To check if the first element is unique, you can use the following:

Collections.frequency(Arrays.asList(stringArray), stringArray[0]) == 1

This returns a boolean that is true if the first element of stringArray is unique, otherwise false.


问:
TestCase "test_Dialog_focusDestroy" does not work properly in Dojo release 1.5
I'm currently using dojo 1.5 and trying to create a simple dojo dialog where once focus is on dialog the main content cannot be edited. I found this functionality under following testcase.

http://download.dojotoolkit.org/release-1.5.0/dojo-release-1.5.0/dijit/tests/test_Dialog_focusDestroy.html

Unfortunately, This test case only work for first click of the "show dialog" button (once click, can not edit main content). Subsequent clicks of "show dialog" button does not disable the main content as intended:( (without refreshing the page). Since overlay functionality does not work properly, user is able to create multiple instances of same dialog by clicking "show dialog" button.

However, I found this test case properly work in one of Dojo previous release 1.2.3.

http://download.dojotoolkit.org/release-1.2.3/dojo-release-1.2.3/dijit/tests/test_Dialog_focusDestroy.html

Please provide me a clarification regarding above dialog functionality. Is there any way to get around this problem in Dojo 1.5?

[EDIT]
I resolve this problem by calling .hide() before calling .destroy() of dialog. Refer to description of

   http://trac.dojotoolkit.org/ticket/5351. It looks like this bug should be re-open.

答: looks like a bug, but perhaps not the same as but #5351.  The area behind the dialog is not disabled, but the keys and focus seem to be working correctly.  Perhaps you should open a new ticket.</p>


问:
Pick list items in VSTS gets auto sorted
I'm trying to add some items (strings) to a pick list in VSTS. The items get auto sorted alphabetically (ascending order).

Below is the scenario:

I entered 'test' then 'abc' and then 'xyz', but it auto sorts and displays 'abc' then 'test' and then 'xyz'.

Is there any way to avoid this sorting and the items should be inserted in the order they were entered?

And I want to achieve this without writing an extension.

答: if you are using VSTS, you cannot avoid the sorting or have your own sorting for a list field. </p>


问:
How to maintain a constant ImageView width and and height
I have a recyclerView displaying a list of imageView(thumbnail size) and textView. Whenever i populate my textViews with lot of text, the imageView is shrinked and the height increases. The textView is also wrapped to the left  leaving lot of white space on the right. Below is an image of what i am talking about. How can i make the thumbnail width and height fixed even though my textView has a lot of texts, so as to maintain the image quality.

*axml**

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="#E2E2E2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    card_view:cardCornerRadius="7dp"
    android:layout_marginRight="4dp"
    android:layout_marginLeft="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="100">
            <ImageView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="25"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:id="@+id/imageView" />
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="18sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/txt_title"
                    android:textStyle="bold"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="14sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/textView"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="13sp"
                    android:textColor="#808080"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/pub_date"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</android.support.v7.widget.CardView>
</code>```

答:
Step 1: Remove this line:

```<code>android:weightSum="100"
</code>```

Step 2: Change 63 to 1 in this line:

```<code>android:layout_weight="63"
</code>```

Step 3: Change the following lines:

```<code>android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="25"
</code>```

to this ones:

```<code>android:layout_width="wrap_content"
android:layout_height="match_parent"
</code>```

or if you want fixed width:

```<code>android:layout_width="150dp"
android:layout_height="match_parent"
</code>```

Body:
I have a recyclerView displaying a list of imageView(thumbnail size) and textView. Whenever i populate my textViews with lot of text, the imageView is shrinked and the height increases. The textView is also wrapped to the left  leaving lot of white space on the right. Below is an image of what i am talking about. How can i make the thumbnail width and height fixed even though my textView has a lot of texts, so as to maintain the image quality.

*axml**

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:tools="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:background="#E2E2E2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="4dp"
    card_view:cardCornerRadius="7dp"
    android:layout_marginRight="4dp"
    android:layout_marginLeft="4dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="12dp">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:weightSum="100">
            <ImageView
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="25"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:id="@+id/imageView" />
            <LinearLayout
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="63"
                android:orientation="vertical"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"
                android:paddingTop="7dp"
                android:paddingBottom="7dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="18sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/txt_title"
                    android:textStyle="bold"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="14sp"
                    android:textColor="#333333"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/textView"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textSize="13sp"
                    android:textColor="#808080"
                    android:text="Caption"
                    android:layout_weight="1"
                    android:ellipsize="none"
                    android:maxLines="100"
                    android:scrollHorizontally="false"
                    android:id="@+id/pub_date"
                    android:fontFamily="Times New Roman"
                    android:layout_marginLeft="4dp"
                    android:layout_marginTop="10dp"
                    android:layout_gravity="center_vertical|left" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</android.support.v7.widget.CardView>

Body:
Step 1: Remove this line:

android:weightSum="100"

Step 2: Change 63 to 1 in this line:

android:layout_weight="63"

Step 3: Change the following lines:

android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="25"

to this ones:

android:layout_width="wrap_content"
android:layout_height="match_parent"

or if you want fixed width:

android:layout_width="150dp"
android:layout_height="match_parent"


答:
Refer to this javadoc for setMaxWidth method of ImageView:

An optional argument to supply a maximum width for this view. Only
  valid if setAdjustViewBounds(boolean) has been set to true. To set an
  image to be a maximum of 100 x 100 while preserving the original
  aspect ratio, do the following:

1) set adjustViewBounds to true

2) set
  maxWidth and maxHeight to 100

3) set the height and width layout
  params to WRAP_CONTENT.

Note that this view could be still smaller than 100 x 100 using this
  approach if the original image is small. To set an image to a fixed
  size, specify that size in the layout params and then use
  setScaleType(android.widget.ImageView.ScaleType) to determine how to
  fit the image within the bounds.

Title: How to maintain a constant ImageView width and and height


问:
Lodash does not work in testing environment
I've got a problem with importing lodash into my testing environment. I'm testing service which uses lodash. In test suite I imported lodash this way:

```<code>import * as _ from "lodash";
</code>```

Then in test I'm able to execute successfully:

```<code>console.log('lodash version:', _.VERSION);
</code>```

But when I run service method, which uses lodash - I'm getting an error:

```<code>TypeError: Cannot read property 'find' of undefined
</code>```

How is it possible?

karma.config.js:

```<code>files: [
  { pattern: './src/test.ts', watched: false },
  'node_modules/lodash/lodash.js'
],
</code>```

答: Is the service method that you are testing using a "_" defined globally or perhaps imports it's own , overwriting your '_' with undefined (for whatever reason) ?</p>

Body:
I've got a problem with importing lodash into my testing environment. I'm testing service which uses lodash. In test suite I imported lodash this way:

import * as _ from "lodash";

Then in test I'm able to execute successfully:

console.log('lodash version:', _.VERSION);

But when I run service method, which uses lodash - I'm getting an error:

TypeError: Cannot read property 'find' of undefined

How is it possible?

karma.config.js:

files: [
  { pattern: './src/test.ts', watched: false },
  'node_modules/lodash/lodash.js'
],


问:
How to get the percentage of apt get output through regex?
Can someone please help me with a regular expression to get the percentage from the below bash output through regex?

```<code>Get:11 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libvlc$

Get:12 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-freefont-ttf$

40% [12 fonts-freefont-ttf 855 kB/4,140 kB 21%]
</code>```

I just need to get the 40% from the above example..

Thanks.

答:
Use this one:

```<code>^\d{1,3}%
</code>```

^ - beginning of the line

\d{1,3} - one, two or three digits

% - percenatage sign

Demo: regex101.com/r/tuyAbD/1

And if you want to have just number (without %) use this one:

```<code>^\d{1,3}(?=%)
</code>```

Demo: regex101.com/r/tuyAbD/2

Body:
Can someone please help me with a regular expression to get the percentage from the below bash output through regex?

Get:11 http://us.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libvlc$

Get:12 http://us.archive.ubuntu.com/ubuntu xenial/main amd64 fonts-freefont-ttf$

40% [12 fonts-freefont-ttf 855 kB/4,140 kB 21%]

I just need to get the 40% from the above example..

Thanks.

Body:
Use this one:

^\d{1,3}%

^ - beginning of the line

\d{1,3} - one, two or three digits

% - percenatage sign

Demo: regex101.com/r/tuyAbD/1

And if you want to have just number (without %) use this one:

^\d{1,3}(?=%)

Demo: regex101.com/r/tuyAbD/2


问:
Node.js Mongoose, how to catch error in post save
I have a collection with a unique field on it. Let's say I create the value of this unique field in the pre save method like this:

```<code>schema.pre('save', function (next) {
    var _self = this;
    try {
        if (config.devMode) {
            log.debug('[' + si.name + ':write] - Executing presave on: ' + _self._id);
        }
        if(!_self.transaction_id){
            _self.transaction_id = powm(30).toLowerCase();
        }
        next();
    } catch (e) {
        log.error('[' + si.name + ':write] - threw an error (SAVE): ', e.stack, _self);
        next(e);
    }
});
</code>```

Powm creates an aleatory string like 'dfjkfj3434jkl23k4j2k3j4asdf', which needs to be unique. Although the string is long enough to not be duplicated, I want to be sure that if it is I can retry the saving with a new one till there is a really unique value on it.

I know MongoDB throws an error that bubbles up when saving the document like this:

```<code>documentname.save(function(err, doc){
   // If mongodb unique error then reset with a new id and resave
});
</code>```

But this forces me to look for all places in the code where this happens. So I was wondering if I can catch this error in the post mongoose middleware. The problem is that no error object seems to be passed to post save method. So, any idea on this? Thanks!

答:
I'm answering with what I found out right now by stumbling on a similar issue.

I'll be focusing in the "catch error in post save" part as I'm not sure, by now if modifying and re-saving the document in this way might or might not cause some trouble. So I'm not sure this will work fine for your specific needs, but you can give it a try.

My scenario is similar to yours, but slightly different:

I want to associate an unique, random, short code to each document of my collection.

I do not generate it randomly at each insertion, but I pre-generated a collection of 1M random codes stored in documents like this:

```<code>{
  value: "khsda",
  status: "FREE"
}
</code>```

Each time I want to insert a new document with an associated code I do the fallowing:

In .pre('validate',...) I select a "FREE" code and set its status to "PENDING".

I assign the new document code to the value of the picked code.

Now, if the saving process goes fine I want to change the status to "TAKEN" otherwise, I want to freed the code, setting its status back to "FREE".

To know If everything went fine, I hook a .post('save',...) middleware that changes the code status to "TAKEN"

To know If something went wrong, I hook a .post('validation',...) middleware. But here's the quirk: the signature of the function I pass to the middleware must be function(error, doc, next). This middleware will be called only if an error occurs in the validation process and lets me put back the status of the code to "FREE".

So, basically, you could hook a middleware like this:

```<code>schema.post('save', function(err, doc, next) {
    // Handle the error...
});
</code>```

I'm not sure if attempting to change and re-save the document at this point will cause any issue, but by logic, the save operation should already have been aborted and here you can control the bubbling of the error through the next(). If you attempt a new save and then call next() without any error as argument, It might work as you need.

Let me know if this works.

Body:
I have a collection with a unique field on it. Let's say I create the value of this unique field in the pre save method like this:

schema.pre('save', function (next) {
    var _self = this;
    try {
        if (config.devMode) {
            log.debug('[' + si.name + ':write] - Executing presave on: ' + _self._id);
        }
        if(!_self.transaction_id){
            _self.transaction_id = powm(30).toLowerCase();
        }
        next();
    } catch (e) {
        log.error('[' + si.name + ':write] - threw an error (SAVE): ', e.stack, _self);
        next(e);
    }
});

Powm creates an aleatory string like 'dfjkfj3434jkl23k4j2k3j4asdf', which needs to be unique. Although the string is long enough to not be duplicated, I want to be sure that if it is I can retry the saving with a new one till there is a really unique value on it.

I know MongoDB throws an error that bubbles up when saving the document like this:

documentname.save(function(err, doc){
   // If mongodb unique error then reset with a new id and resave
});

But this forces me to look for all places in the code where this happens. So I was wondering if I can catch this error in the post mongoose middleware. The problem is that no error object seems to be passed to post save method. So, any idea on this? Thanks!

Body:
I'm answering with what I found out right now by stumbling on a similar issue.

I'll be focusing in the "catch error in post save" part as I'm not sure, by now if modifying and re-saving the document in this way might or might not cause some trouble. So I'm not sure this will work fine for your specific needs, but you can give it a try.

My scenario is similar to yours, but slightly different:

I want to associate an unique, random, short code to each document of my collection.

I do not generate it randomly at each insertion, but I pre-generated a collection of 1M random codes stored in documents like this:

{
  value: "khsda",
  status: "FREE"
}

Each time I want to insert a new document with an associated code I do the fallowing:

In .pre('validate',...) I select a "FREE" code and set its status to "PENDING".

I assign the new document code to the value of the picked code.

Now, if the saving process goes fine I want to change the status to "TAKEN" otherwise, I want to freed the code, setting its status back to "FREE".

To know If everything went fine, I hook a .post('save',...) middleware that changes the code status to "TAKEN"

To know If something went wrong, I hook a .post('validation',...) middleware. But here's the quirk: the signature of the function I pass to the middleware must be function(error, doc, next). This middleware will be called only if an error occurs in the validation process and lets me put back the status of the code to "FREE".

So, basically, you could hook a middleware like this:

schema.post('save', function(err, doc, next) {
    // Handle the error...
});

I'm not sure if attempting to change and re-save the document at this point will cause any issue, but by logic, the save operation should already have been aborted and here you can control the bubbling of the error through the next(). If you attempt a new save and then call next() without any error as argument, It might work as you need.

Let me know if this works.


问:
How to add a stack layout for loop in Kivy?
I'm a completely amateur programmer. So I just started learning Kivy and refreshing my Python memory because I needed to make a mobile app. I kind of understand the basic idea of OOP, but not much else. I haven't taken any courses or anything, I'm just winging it as I go along.

So I have the basic menu set up with one other screen that gets taken to by all the buttons. I'd like to add a stack layout with a bunch of images (named 1.jpg, 2.jpg) with captions underneath them in that other screen. I understand, how to make that happen in Python, I just have no idea how to do it in Kivy. I could just add them all 1 by 1 in the .kv file but that would take ages. I tried a lot of different combinations, but I'm starting to understand that I'm nowhere near enough educated in classes and objects to be doing this. I could never get the add_widget right, because I could never 1) position the code correctly so it would even run and 2) point it at the right attributes so even if it ran, the result wouldn't appear.

The for loop I usually used for testing:

```<code>g = Stack()

for i in range(9)
    btn = Button(text=("Test" + str(i), size_hint=(0.2, 0.1))
    g.add_widget(btn)
</code>```

I looked online and all I got was that I'm missing a "self" or "root" somewhere. I have no idea how to combine a .kv file with add_widget's. For the basic menu I followed a simple tutorial.

```<code>from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import *
from kivy.uix.screenmanager import *
from kivy.lang import Builder
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.image import Image
from kivy.properties import *
from kivy.config import Config
from kivy.uix.button import Button
Config.set('graphics', 'width', '411')
Config.set('graphics', 'height', '731')

class Background(Image):
    pass

class Relative(RelativeLayout):
    pass

class Stack(StackLayout):
    pass

class MainMenu(Screen):
    pass

class Other(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

start = Builder.load_file("KVFile.kv")

class MainApp(App):
    def build(self):
        return start

MainApp().run()
</code>```

The .kv file:

```<code>#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    MainMenu:
    Other:

<MainMenu>:

    # ///// BACKGROUND IMAGE /////

    name: 'main'
    Background:
        source: 'BG.jpg'
        background_color: .34, .2, .48, .7
        size_hint: None, None
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        size: 800, 800

    # ///// MAIN MENU BUTTON LAYOUT /////

    Relative:

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "LOREM"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.3, 'center_y': 0.4}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "IPSUM"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.7, 'center_y': 0.4}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "DOLOR"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.3, 'center_y': 0.3}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "SIT"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.7, 'center_y': 0.3}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "AMET"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.3, 'center_y': 0.2}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "OTHER"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.7, 'center_y': 0.2}

<Other>:
    name: 'other'
    Stack:
</code>```

I know this is a not-very-specific question and I should be studying the Docs, but the amount of information there is overwhelming.

答:
I have no idea what defining the __init__ function did, but it did the trick.

```<code>class Other(Screen):
    pass

class Stack(StackLayout):
    def __init__(self, **kwargs):
        super(Stack, self).__init__(**kwargs)
        for i in range(9):
            btn = Button(size_hint=(0.2, 0.1), text=("Test" + str(i)))
            self.add_widget(btn)
</code>```

And

```<code><Other>:
    name: 'other'
    Stack:
</code>```

Body:
I'm a completely amateur programmer. So I just started learning Kivy and refreshing my Python memory because I needed to make a mobile app. I kind of understand the basic idea of OOP, but not much else. I haven't taken any courses or anything, I'm just winging it as I go along.

So I have the basic menu set up with one other screen that gets taken to by all the buttons. I'd like to add a stack layout with a bunch of images (named 1.jpg, 2.jpg) with captions underneath them in that other screen. I understand, how to make that happen in Python, I just have no idea how to do it in Kivy. I could just add them all 1 by 1 in the .kv file but that would take ages. I tried a lot of different combinations, but I'm starting to understand that I'm nowhere near enough educated in classes and objects to be doing this. I could never get the add_widget right, because I could never 1) position the code correctly so it would even run and 2) point it at the right attributes so even if it ran, the result wouldn't appear.

The for loop I usually used for testing:

g = Stack()

for i in range(9)
    btn = Button(text=("Test" + str(i), size_hint=(0.2, 0.1))
    g.add_widget(btn)

I looked online and all I got was that I'm missing a "self" or "root" somewhere. I have no idea how to combine a .kv file with add_widget's. For the basic menu I followed a simple tutorial.

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.widget import *
from kivy.uix.screenmanager import *
from kivy.lang import Builder
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.image import Image
from kivy.properties import *
from kivy.config import Config
from kivy.uix.button import Button
Config.set('graphics', 'width', '411')
Config.set('graphics', 'height', '731')

class Background(Image):
    pass

class Relative(RelativeLayout):
    pass

class Stack(StackLayout):
    pass

class MainMenu(Screen):
    pass

class Other(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

start = Builder.load_file("KVFile.kv")

class MainApp(App):
    def build(self):
        return start

MainApp().run()

The .kv file:

#: import FadeTransition kivy.uix.screenmanager.FadeTransition

ScreenManagement:
    transition: FadeTransition()
    MainMenu:
    Other:

<MainMenu>:

    # ///// BACKGROUND IMAGE /////

    name: 'main'
    Background:
        source: 'BG.jpg'
        background_color: .34, .2, .48, .7
        size_hint: None, None
        pos_hint: {'center_x': 0.5, 'center_y': 0.5}
        size: 800, 800

    # ///// MAIN MENU BUTTON LAYOUT /////

    Relative:

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "LOREM"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.3, 'center_y': 0.4}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "IPSUM"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.7, 'center_y': 0.4}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "DOLOR"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.3, 'center_y': 0.3}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "SIT"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.7, 'center_y': 0.3}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "AMET"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.3, 'center_y': 0.2}

        Button:
            font_name: 'Effra_Std_Bd'
            font_size: 35
            text: "OTHER"
            on_release: app.root.current = "other"
            background_color: .34, .2, .48, .7
            size_hint: 0.39, 0.09
            pos_hint: {'center_x': 0.7, 'center_y': 0.2}

<Other>:
    name: 'other'
    Stack:

I know this is a not-very-specific question and I should be studying the Docs, but the amount of information there is overwhelming.

Body:
I have no idea what defining the __init__ function did, but it did the trick.

class Other(Screen):
    pass

class Stack(StackLayout):
    def __init__(self, **kwargs):
        super(Stack, self).__init__(**kwargs)
        for i in range(9):
            btn = Button(size_hint=(0.2, 0.1), text=("Test" + str(i)))
            self.add_widget(btn)

And

<Other>:
    name: 'other'
    Stack:


问:
Issue with connecting to URL
This is how request is supposed to look(at the top) :

And this is my code in Java :

```<code>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

public static void main(String[] args) throws Exception{
    URL url = new URL("http://ishin-global.aktsk.com");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);

    conn.setRequestMethod("GET");
    conn.setRequestProperty("/ping ", " HTTP/1.1");
    conn.setRequestProperty("Host"," ishin-global.aktsk.com");
    conn.setRequestProperty("Accept"," */*");
    conn.setRequestProperty("X-Platform"," android");
    conn.setRequestProperty("X-ClientVersion"," 3.1.2");
    conn.setRequestProperty("X-Language"," en");
    conn.connect();

    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    reader.close();
}
</code>```

The issue is that i don't get response from the server,but i get these errors:

```<code>Exception in thread "main" java.io.FileNotFoundException: http://ishin-global.aktsk.com
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1836)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at Main.main(Main.java:24)
</code>```

I haven't been able to figure it out,so i asked here.Thanks in advance

答:
conn.setRequestProperty("/ping ", " HTTP/1.1"); is incorrect.  /ping is not an HTTP request header, it’s the path of the URL.  A URL’s path is part of the URL itself, not a header:

```<code>URL url = new URL("http://ishin-global.aktsk.com/ping");
</code>```

Remove the conn.setRequestProperty("/ping ", " HTTP/1.1"); line.  Java (and every HTTP client) will automatically send the correct initial line when they connect.

Title: Issue with connecting to URL

Body:
This is how request is supposed to look(at the top) :

And this is my code in Java :

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

public static void main(String[] args) throws Exception{
    URL url = new URL("http://ishin-global.aktsk.com");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);

    conn.setRequestMethod("GET");
    conn.setRequestProperty("/ping ", " HTTP/1.1");
    conn.setRequestProperty("Host"," ishin-global.aktsk.com");
    conn.setRequestProperty("Accept"," */*");
    conn.setRequestProperty("X-Platform"," android");
    conn.setRequestProperty("X-ClientVersion"," 3.1.2");
    conn.setRequestProperty("X-Language"," en");
    conn.connect();

    String line;
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
    reader.close();
}

The issue is that i don't get response from the server,but i get these errors:

Exception in thread "main" java.io.FileNotFoundException: http://ishin-global.aktsk.com
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1836)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at Main.main(Main.java:24)

I haven't been able to figure it out,so i asked here.Thanks in advance

Body:
conn.setRequestProperty("/ping ", " HTTP/1.1"); is incorrect.  /ping is not an HTTP request header, it’s the path of the URL.  A URL’s path is part of the URL itself, not a header:

URL url = new URL("http://ishin-global.aktsk.com/ping");

Remove the conn.setRequestProperty("/ping ", " HTTP/1.1"); line.  Java (and every HTTP client) will automatically send the correct initial line when they connect.


问:
react-select-plus + Every backspace Removes call load option method
How to call every backspace remove call load option. I am using select.Async control in every input change method call fetch method and fetch data but when I press backspace then first time called that load option method but in next time that can't call load option method.

getUsers = (input) => {
console.log(input);
if (!input) {
return Promise.resolve({ options: [] });
}
if (input.length > 2) {
const newstate = this.state;
newstate.loadingtext = 'Searching...';
this.setState({ newstate });
const searchLocation = Object.assign({}, cookie.load('cLocation'));
searchLocation.searchText = input;
searchLocation.isBusiness = false;
console.log(input.toString().length);
return fetch(sourceName.searchNavbar, apiUrl.locationAndBusiness,
searchLocation)
.then(json => ({ options: json.data }));
}
return null;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><Select.Async
onChange={this.onChange}
valueKey="placeID"
filterOptions={this.filterOptions}
labelKey="cityState"
loadOptions={this.getUsers}
onInputChange={inp => this.onInputChange(inp)}
onBlur={this.onBlur}
onInputKeyDown={inp => this.onInputKeyDown(inp)}
onFocus={this.onFocousSearch}
value={this.state.value}
searchPromptText="Please enter 3 or more characters"
loadingPlaceholder={this.state.loadingtext}
noResultsText="No results found"
options={this.state.options}
placeholder={this.state.placeholdervalue}
autoBlur

/> </code>```

In above code in load option that get user method call. My get User method is :

When I click first time back space then get user method call but in second time I pressed back space then not called that get user method. How to call every backspace remove call this method.

答: solved my self using cache property in react-select-plus plugin. give that false like this cache={false}. so every time call getuser() method.</p>

Body:
How to call every backspace remove call load option. I am using select.Async control in every input change method call fetch method and fetch data but when I press backspace then first time called that load option method but in next time that can't call load option method.

getUsers = (input) => {
console.log(input);
if (!input) {
return Promise.resolve({ options: [] });
}
if (input.length > 2) {
const newstate = this.state;
newstate.loadingtext = 'Searching...';
this.setState({ newstate });
const searchLocation = Object.assign({}, cookie.load('cLocation'));
searchLocation.searchText = input;
searchLocation.isBusiness = false;
console.log(input.toString().length);
return fetch(sourceName.searchNavbar, apiUrl.locationAndBusiness,
searchLocation)
.then(json => ({ options: json.data }));
}
return null;
}

<Select.Async
onChange={this.onChange}
valueKey="placeID"
filterOptions={this.filterOptions}
labelKey="cityState"
loadOptions={this.getUsers}
onInputChange={inp => this.onInputChange(inp)}
onBlur={this.onBlur}
onInputKeyDown={inp => this.onInputKeyDown(inp)}
onFocus={this.onFocousSearch}
value={this.state.value}
searchPromptText="Please enter 3 or more characters"
loadingPlaceholder={this.state.loadingtext}
noResultsText="No results found"
options={this.state.options}
placeholder={this.state.placeholdervalue}
autoBlur

/>

In above code in load option that get user method call. My get User method is :

When I click first time back space then get user method call but in second time I pressed back space then not called that get user method. How to call every backspace remove call this method.


问:
Why do my unittest work on Chrome driver, but not PhantomJS?
I was writing my first unittest under the Selenium Pychon Bindings document.

I write the test using Chrome driver as below :

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(r"C:\chromedriver_win32\chromedriver")

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get(r"http://www.python.org")
        self.assertIn("Python", driver.title)
        el = driver.find_element_by_name("q")
        el.send_keys("pycon")
        el = driver.find_element_by_id("submit")
        el.click()
        assert "No results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()
</code>```

Run it on terminal and it works.  Terminal returns:

```<code>.
----------------------------------------------------------------------
Ran 1 test in 7.873s

OK
</code>```

But if i replace

```<code>self.driver = webdriver.Chrome(r"C:\chromedriver_win32\chromedriver")
</code>```

with

```<code>self.driver = webdriver.PhantomJS(r"C:\phantomjs-2.1.1\bin\phantomjs")
</code>```

code as below

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.PhantomJS(r"C:\phantomjs-2.1.1\bin\phantomjs")

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get(r"http://www.python.org")
        self.assertIn("Python", driver.title)
        el = driver.find_element_by_name("q")
        el.send_keys("pycon")
        el = driver.find_element_by_id("submit")
        el.click()
        assert "No results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()
</code>```

My terminal gives me an ERROR:

```<code>E
======================================================================
ERROR: test_search_in_python_org (__main__.PythonOrgSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_python_org_search.py", line 24, in test_search_in_python_org
    el.click()
  File "C:\Program Files (x86)
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Program Files (x86)
    return self._parent.execute(command, params)
  File "C:\Program Files (x86)
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: {"errorMessage":"Element is not
"Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:50294",
67e-433b649e227d\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click",
elative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"",
","queryKey":{},"chunks":["click"]},
46/click"}}
Screenshot: available via screen

----------------------------------------------------------------------
Ran 1 test in 6.214s

FAILED (errors=1)
</code>```

Could somebody please tell me why I cannot use click in PhantomJS?

答:
When working with PhantomJS, screenshots are one of your most helpful debugging tools. I modified your script to record a screenshot at the point of failure:

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.PhantomJS()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get(r"http://www.python.org")
        self.assertIn("Python", driver.title)
        el = driver.find_element_by_name("q")
        el.send_keys("pycon")
        el = driver.find_element_by_id("submit")
        try:
            el.click()
        except:
            screenshot = driver.get_screenshot_as_png()
            with open('screenshot.png', 'wb') as w:
                w.write(screenshot)
        assert "No results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()
</code>```

When I run it, I get this screenshot.

You'll note that the page has rendered as if it was on a mobile browser. You should set the browser window size when working with phantomjs:

```<code>def setUp(self):
    self.driver = webdriver.PhantomJS()
    self.driver.set_window_size(800, 1000)
</code>```

Once you do that, and compare the chrome and phantom renderings, you'll see that phantom isn't loading in the submit button correctly:

One work around would be to send the ENTER key, rather than click the button:

```<code>def test_search_in_python_org(self):
    driver = self.driver
    driver.set_window_size(800, 1000)
    driver.get(r"http://www.python.org")
    self.assertIn("Python", driver.title)
    el = driver.find_element_by_name("q")
    el.send_keys("pycon")
    el.send_keys(Keys.ENTER)
    screenshot = driver.get_screenshot_as_png()
    with open('screenshot2.png', 'wb') as w:
        w.write(screenshot)
</code>```

With the above code, I now see results:

It's worth noting that this is why many people, myself included, do not use PhantomJS for testing purposes. I find I am much better off using Chrome and/or Firefox, by either running them in their own headless modes, or by using a virtual frame buffer (like Xvfb).

I personally do my testing on cloud based linux instances, and I use pyvirtualdisplay with Xvfb to manage my virtual displays. With both installed, pyvirtualdisplay will entirely manager your virtual display session. To use it with your above script, I would do the following:

```<code>from pyvirtualdisplay import Display

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.display = Display(visible=False, size=(1200, 1500))
        self.display.start()
        self.driver = webdriver.Chrome()

    def test_search_in_python_org(self):
        # Do test

    def tearDown(self):
        self.driver.close()
        self.display.stop()
</code>```

All that said, I have no experience with Windows, but I believe a similar configuration exists for that OS

Body:
I was writing my first unittest under the Selenium Pychon Bindings document.

I write the test using Chrome driver as below :

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Chrome(r"C:\chromedriver_win32\chromedriver")

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get(r"http://www.python.org")
        self.assertIn("Python", driver.title)
        el = driver.find_element_by_name("q")
        el.send_keys("pycon")
        el = driver.find_element_by_id("submit")
        el.click()
        assert "No results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

Run it on terminal and it works.  Terminal returns:

.
----------------------------------------------------------------------
Ran 1 test in 7.873s

OK

But if i replace

self.driver = webdriver.Chrome(r"C:\chromedriver_win32\chromedriver")

with

self.driver = webdriver.PhantomJS(r"C:\phantomjs-2.1.1\bin\phantomjs")

code as below

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.PhantomJS(r"C:\phantomjs-2.1.1\bin\phantomjs")

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get(r"http://www.python.org")
        self.assertIn("Python", driver.title)
        el = driver.find_element_by_name("q")
        el.send_keys("pycon")
        el = driver.find_element_by_id("submit")
        el.click()
        assert "No results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

My terminal gives me an ERROR:

E
======================================================================
ERROR: test_search_in_python_org (__main__.PythonOrgSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_python_org_search.py", line 24, in test_search_in_python_org
    el.click()
  File "C:\Program Files (x86)
    self._execute(Command.CLICK_ELEMENT)
  File "C:\Program Files (x86)
    return self._parent.execute(command, params)
  File "C:\Program Files (x86)
    self.error_handler.check_response(response)
  File "C:\Program Files (x86)
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.ElementNotVisibleException: Message: {"errorMessage":"Element is not
"Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:50294",
67e-433b649e227d\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click",
elative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"",
","queryKey":{},"chunks":["click"]},
46/click"}}
Screenshot: available via screen

----------------------------------------------------------------------
Ran 1 test in 6.214s

FAILED (errors=1)

Could somebody please tell me why I cannot use click in PhantomJS?

Body:
When working with PhantomJS, screenshots are one of your most helpful debugging tools. I modified your script to record a screenshot at the point of failure:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import unittest

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.PhantomJS()

    def test_search_in_python_org(self):
        driver = self.driver
        driver.get(r"http://www.python.org")
        self.assertIn("Python", driver.title)
        el = driver.find_element_by_name("q")
        el.send_keys("pycon")
        el = driver.find_element_by_id("submit")
        try:
            el.click()
        except:
            screenshot = driver.get_screenshot_as_png()
            with open('screenshot.png', 'wb') as w:
                w.write(screenshot)
        assert "No results found." not in driver.page_source

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

When I run it, I get this screenshot.

You'll note that the page has rendered as if it was on a mobile browser. You should set the browser window size when working with phantomjs:

def setUp(self):
    self.driver = webdriver.PhantomJS()
    self.driver.set_window_size(800, 1000)

Once you do that, and compare the chrome and phantom renderings, you'll see that phantom isn't loading in the submit button correctly:

One work around would be to send the ENTER key, rather than click the button:

def test_search_in_python_org(self):
    driver = self.driver
    driver.set_window_size(800, 1000)
    driver.get(r"http://www.python.org")
    self.assertIn("Python", driver.title)
    el = driver.find_element_by_name("q")
    el.send_keys("pycon")
    el.send_keys(Keys.ENTER)
    screenshot = driver.get_screenshot_as_png()
    with open('screenshot2.png', 'wb') as w:
        w.write(screenshot)

With the above code, I now see results:

It's worth noting that this is why many people, myself included, do not use PhantomJS for testing purposes. I find I am much better off using Chrome and/or Firefox, by either running them in their own headless modes, or by using a virtual frame buffer (like Xvfb).

I personally do my testing on cloud based linux instances, and I use pyvirtualdisplay with Xvfb to manage my virtual displays. With both installed, pyvirtualdisplay will entirely manager your virtual display session. To use it with your above script, I would do the following:

from pyvirtualdisplay import Display

class PythonOrgSearch(unittest.TestCase):

    def setUp(self):
        self.display = Display(visible=False, size=(1200, 1500))
        self.display.start()
        self.driver = webdriver.Chrome()

    def test_search_in_python_org(self):
        # Do test

    def tearDown(self):
        self.driver.close()
        self.display.stop()

All that said, I have no experience with Windows, but I believe a similar configuration exists for that OS


问:
ASP.NET button does not exist in current context
I have a button that is on a pretty simple page. It accepts a file, and when you press the submit button it will load a file. None of that is coded yet as it says the button does not exist in the current context when trying to code the event handler for the button.

Code Behind:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class mass_upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSubmitMass.ServerClick += new EventHandler(btnSubmitMass_Click);
    }

    protected void btnSubmitMass_Click(object sender, EventArgs e)
    {

    }
}
</code>```

Web page:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="mass-upload.aspx.cs" Inherits="mass_upload" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Submissions</title>
    <link href="/favicon.png" rel="icon">
    <link href="css/uikit.min.css" rel="stylesheet">
    <link href="css/uikit.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet">
    <script src="https://use.fontawesome.com/50bcaa1a6b.js"></script>
    <script src="js/uikit.min.js"></script>
    <script src="js/uikit.js"></script>
    <script src="js/uikit-icons.min.js"></script>
</head>
<body runat="server">
    <div class="uk-section uk-section-xsmall" style="background-color: #820024; margin:0px;">
        <div class="uk-container uk-container-large">
            <div uk-grid="">
                <div class="uk-width-1-2">
                    <a href="index.aspx"><img src="images/image.png"></a>
                </div>
                <div class="uk-width-1-2">
                    <div class="uk-float-right">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <nav class="uk-navbar-container" style="background-color: rgba(138,121,103,1); color: #ffffff;" uk-navbar="mode: click">
        <div class="uk-navbar-center">
            <ul class="uk-navbar-nav uk-text-primary" style="color: #ffffff;">
                <li class="uk-active">
                    <a href="index.aspx">Home</a>
                </li>
                <li>
                    <a href="manual-upload.aspx">Manual Submit</a>
                </li>
                <li>
                    <a href="mass-upload.aspx">Mass Submit</a>
                </li>
            </ul>
        </div>
    </nav>
    <div class="uk-section uk-margin-remove-bottom uk-padding-remove-bottom">
        <div class="uk-container">
            <div class="uk-grid">
                <div class="uk-text-center uk-width-1-1">
                    Click in the field below, browse to the file to be uploaded and click "Open". Once the file name is visible in the form field, click the Submit button.
                </div>
            </div>
        </div>
    </div>
    <div class="uk-section" runat="server">
        <div class="uk-container uk-container-large uk-margin uk-margin-left uk-margin-right uk-padding" style="border:1px solid #cccccc;" runat="server">
            <form id="form1" runat="server">
                <fieldset class="uk-fieldset" runat="server">
                    <!-- ****************************************************** -->
                    <div class="uk-grid-small uk-child-width-expand@s uk-text-center" uk-grid>
                        <div>
                            <div class="uk-margin" uk-margin>
                                <div uk-form-custom="target: true">
                                    <input type="file">
                                    <input class="uk-input uk-form-width-medium" disabled placeholder="Select file" type="text">
                                </div>
                                <input type="button" id="btnSubmitMass" runat="server" value="Submit" class="uk-button uk-button-default" />
                            </div>
                        </div>
                    </div>
                    <!-- ****************************************************** -->
                </fieldset>
            </form>
        </div>
    </div>
    <div class="uk-grid" style="margin-bottom:15px;">
        <div class="uk-text-center uk-width-1-1">
            Copyright &copy
        </div>
    </div>
</body>
</html>
</code>```

答:
You can try to declare it manually:

```<code>protected HtmlInputButton btnSubmitMass;

protected void Page_Load(object sender, EventArgs e)
{
    btnSubmitMass.ServerClick += new EventHandler(btnSubmitMass_Click);
}

protected void btnSubmitMass_Click(object sender, EventArgs e)
{

}
</code>```

Normally that control should be declared automatically if you add runat="servser" and then save the aspx page. So you could also simply try to rename it, save, then rename back to your desired id and save again.

Body:
I have a button that is on a pretty simple page. It accepts a file, and when you press the submit button it will load a file. None of that is coded yet as it says the button does not exist in the current context when trying to code the event handler for the button.

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

public partial class mass_upload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnSubmitMass.ServerClick += new EventHandler(btnSubmitMass_Click);
    }

    protected void btnSubmitMass_Click(object sender, EventArgs e)
    {

    }
}

Web page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="mass-upload.aspx.cs" Inherits="mass_upload" %>
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Submissions</title>
    <link href="/favicon.png" rel="icon">
    <link href="css/uikit.min.css" rel="stylesheet">
    <link href="css/uikit.css" rel="stylesheet">
    <link href="css/styles.css" rel="stylesheet" />

    <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet">

                    Home

                    Manual Submit

                    Mass Submit

                    Click in the field below, browse to the file to be uploaded and click "Open". Once the file name is visible in the form field, click the Submit button.

            <form id="form1" runat="server">
                <fieldset class="uk-fieldset" runat="server">

                                    <input type="file">
                                    <input class="uk-input uk-form-width-medium" disabled placeholder="Select file" type="text">

                                <input type="button" id="btnSubmitMass" runat="server" value="Submit" class="uk-button uk-button-default" />

                </fieldset>
            </form>

            Copyright &copy

Body:
You can try to declare it manually:

protected HtmlInputButton btnSubmitMass;

protected void Page_Load(object sender, EventArgs e)
{
    btnSubmitMass.ServerClick += new EventHandler(btnSubmitMass_Click);
}

protected void btnSubmitMass_Click(object sender, EventArgs e)
{

}

Normally that control should be declared automatically if you add runat="servser" and then save the aspx page. So you could also simply try to rename it, save, then rename back to your desired id and save again.


问:
WPF SelectedValue of combobox not updating from viewmodel property
I have the following combobox in my MainWindow:

```<code><ComboBox SelectedValue="{Binding LanguageId}" SelectedValuePath="Id" DisplayMemberPath="Name" ItemsSource="{Binding Languages}"/>
</code>```

in my ViewModel i have the following two properties set:

```<code>public List<Language> Languages
{
  get
  {
    return new List<Language>()
    {
     new Language { Id = 0, Name = ml.ml_string(100, "Language1") },
     new Language { Id = 1, Name = ml.ml_string(101, "Language2") },
     new Language { Id = 2, Name = ml.ml_string(102, "Language3") },
     new Language { Id = 3, Name = ml.ml_string(103, "Language4") }
    };
  }
}

public int LanguageId
{
  get
  {
    return _languageId;
  }
  set
  {
    _languageId = value;
    NotifyPropertyChanged("Languages");
    NotifyPropertyChanged();
  }
}
</code>```

So what i want is to notify my Languages property after i select a language in the combobox but currently when i do this, it shows no value at all(see picture):
combobox error
How can i solve this problem?

答:
The selected item has to be considered equal to an item in the collection. However, you always return a collection of new objects from Languages, so when the selection changes, you set ComboBox.ItemsSource to a new collection which does not contain the object that was just selected. So the ComboBox discards the selected item value as invalid. Using SelectedValuePath doesn't work around this issue, as you found.

You could fix this by overriding Equals(Language) on Language, or (much better) by keeping your Languages around permanently and reusing them.

If you need to translate the Name property, you could do that with a value converter.

The reason I advise against overriding Equals() is that in C#, you get in the habit of assuming that comparing two instances of a reference type means Object.ReferenceEquals(), and breaking that assumption can cause bugs. I speak from experience.

Since we're no longer using the Name property, we can just change Languages into a List<int> of Language Ids -- in which case we can make it readonly and never bother to recreate the list. I've done that here.

```<code>public class LanguageNameConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[0] is int)
        {
            var itemLanguageId = (int)values[0];
            var displayLanguageId = (int)values[1];

            //  Do stuff here to get the translated name of the item language
            var itemLanguageNameTranslated = $"Name of language {itemLanguageId} in language {displayLanguageId}";

            return itemLanguageNameTranslated;
        }
        else return values[0]?.GetType();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

XAML:

```<code><ComboBox
    SelectedValue="{Binding LanguageId}"
    ItemsSource="{Binding Languages}"
    >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Label>
                <Label.Content>
                    <MultiBinding
                        Converter="{StaticResource LanguageNameConverter}"
                        >
                        <Binding Path="." />
                        <Binding
                            Path="DataContext.LanguageId"
                            RelativeSource="{RelativeSource AncestorType=ComboBox}"
                            />
                    </MultiBinding>
                </Label.Content>
            </Label>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
</code>```

If you'd prefer to keep the Language class in Languages, just restore SelectedValuePath="Id" on the ComboBox, and set the Path of the first Binding in the MultiBinding to Id instead of ..

```<code><ComboBox
    SelectedValue="{Binding LanguageId}"
    SelectedValuePath="Id"
    ...
</code>```

...

```<code><MultiBinding
    Converter="{StaticResource LanguageNameConverter}"
    >
    <Binding Path="Id" />
    <Binding
        Path="DataContext.LanguageId"
        RelativeSource="{RelativeSource AncestorType=ComboBox}"
        />
</MultiBinding>
</code>```

Equals-override solution

Here's the Equals() solution; we tried it but it had a problem with keeping the old SelectedItem, with its old name in a previously selected language, after the selection changed. That's because of the Equals() override thing. So we went with the multi-value converter, which doesn't need any workarounds or funny business.

Just do things the way WPF wants, and nobody gets hurt. That's the rule.

```<code>public class Language
{
    public int Id { get; set; }
    public String Name { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Language)
        {
            return ((Language)obj).Id == Id;
        }
        return base.Equals(obj);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}
</code>```

If you choose this solution, you will also need to add a recursion guard to your LanuageId property:

```<code>private int _languageId;
public int LanguageId
{
    get
    {
        return _languageId;
    }
    set
    {
        if (_languageId != value)
        {
            _languageId = value;
            OnPropertyChanged("Languages");
            OnPropertyChanged();
        }
    }
}
</code>```

Replacing ComboBox.ItemsSource will now cause the actual SelectedItem to change to a new object instance, which update SelectedValue, which will cause LanguageId to be set again -- to the same value it already has. If you omit the recursion guard, LanguageId's set block will raise PropertyChanged for Languages once again, which will update SelectedItem, etc. -- and we're off to the races until the stack overflows.

Body:
I have the following combobox in my MainWindow:

<ComboBox SelectedValue="{Binding LanguageId}" SelectedValuePath="Id" DisplayMemberPath="Name" ItemsSource="{Binding Languages}"/>

in my ViewModel i have the following two properties set:

public List<Language> Languages
{
  get
  {
    return new List<Language>()
    {
     new Language { Id = 0, Name = ml.ml_string(100, "Language1") },
     new Language { Id = 1, Name = ml.ml_string(101, "Language2") },
     new Language { Id = 2, Name = ml.ml_string(102, "Language3") },
     new Language { Id = 3, Name = ml.ml_string(103, "Language4") }
    };
  }
}

public int LanguageId
{
  get
  {
    return _languageId;
  }
  set
  {
    _languageId = value;
    NotifyPropertyChanged("Languages");
    NotifyPropertyChanged();
  }
}

So what i want is to notify my Languages property after i select a language in the combobox but currently when i do this, it shows no value at all(see picture):
combobox error
How can i solve this problem?

Body:
The selected item has to be considered equal to an item in the collection. However, you always return a collection of new objects from Languages, so when the selection changes, you set ComboBox.ItemsSource to a new collection which does not contain the object that was just selected. So the ComboBox discards the selected item value as invalid. Using SelectedValuePath doesn't work around this issue, as you found.

You could fix this by overriding Equals(Language) on Language, or (much better) by keeping your Languages around permanently and reusing them.

If you need to translate the Name property, you could do that with a value converter.

The reason I advise against overriding Equals() is that in C#, you get in the habit of assuming that comparing two instances of a reference type means Object.ReferenceEquals(), and breaking that assumption can cause bugs. I speak from experience.

Since we're no longer using the Name property, we can just change Languages into a List<int> of Language Ids -- in which case we can make it readonly and never bother to recreate the list. I've done that here.

public class LanguageNameConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (values[0] is int)
        {
            var itemLanguageId = (int)values[0];
            var displayLanguageId = (int)values[1];

            //  Do stuff here to get the translated name of the item language
            var itemLanguageNameTranslated = $"Name of language {itemLanguageId} in language {displayLanguageId}";

            return itemLanguageNameTranslated;
        }
        else return values[0]?.GetType();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

<ComboBox
    SelectedValue="{Binding LanguageId}"
    ItemsSource="{Binding Languages}"
    >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Label>
                <Label.Content>
                    <MultiBinding
                        Converter="{StaticResource LanguageNameConverter}"
                        >
                        <Binding Path="." />
                        <Binding
                            Path="DataContext.LanguageId"
                            RelativeSource="{RelativeSource AncestorType=ComboBox}"
                            />
                    </MultiBinding>
                </Label.Content>
            </Label>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

If you'd prefer to keep the Language class in Languages, just restore SelectedValuePath="Id" on the ComboBox, and set the Path of the first Binding in the MultiBinding to Id instead of ..

<ComboBox
    SelectedValue="{Binding LanguageId}"
    SelectedValuePath="Id"
    ...

...

<MultiBinding
    Converter="{StaticResource LanguageNameConverter}"
    >
    <Binding Path="Id" />
    <Binding
        Path="DataContext.LanguageId"
        RelativeSource="{RelativeSource AncestorType=ComboBox}"
        />
</MultiBinding>

Equals-override solution

Here's the Equals() solution; we tried it but it had a problem with keeping the old SelectedItem, with its old name in a previously selected language, after the selection changed. That's because of the Equals() override thing. So we went with the multi-value converter, which doesn't need any workarounds or funny business.

Just do things the way WPF wants, and nobody gets hurt. That's the rule.

public class Language
{
    public int Id { get; set; }
    public String Name { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Language)
        {
            return ((Language)obj).Id == Id;
        }
        return base.Equals(obj);
    }

    public override int GetHashCode()
    {
        return Id.GetHashCode();
    }
}

If you choose this solution, you will also need to add a recursion guard to your LanuageId property:

private int _languageId;
public int LanguageId
{
    get
    {
        return _languageId;
    }
    set
    {
        if (_languageId != value)
        {
            _languageId = value;
            OnPropertyChanged("Languages");
            OnPropertyChanged();
        }
    }
}

Replacing ComboBox.ItemsSource will now cause the actual SelectedItem to change to a new object instance, which update SelectedValue, which will cause LanguageId to be set again -- to the same value it already has. If you omit the recursion guard, LanguageId's set block will raise PropertyChanged for Languages once again, which will update SelectedItem, etc. -- and we're off to the races until the stack overflows.


问:
Unable to load JSON
I have the code

```<code>data = open('wg.json', 'r').read()
data_parsed = json.loads(data)
</code>```

And have received the error: ValueError: No JSON object could be decoded

With my JSON file being a python dictionary put into a json file:

```<code>{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}
</code>```

答:
You're missing a " after 73 F (23 C) make that this way:

```<code>{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}
</code>```

Title: Unable to load JSON

Body:
I have the code

data = open('wg.json', 'r').read()
data_parsed = json.loads(data)

And have received the error: ValueError: No JSON object could be decoded

With my JSON file being a python dictionary put into a json file:

{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}

Body:
You're missing a " after 73 F (23 C) make that this way:

{"wind_degrees":103, "dew_p": "73 F (23 C)", "wind_kph": 5.8}


答:
I recommend you to split the string with delimiter ; and add separated Strings to a List, where you can easily validate with the Collections.frequency() static method returning the number as int of the occurence.

```<code>String[] values = strLine.split(";");
List<String> list = Arrays.asList(values);

if (Collections.frequency(list, list.get(0) > 1) {
    System.out.println("The first value is not unique in the list");
}
</code>```

Since Java 8 feel free to use Stream:

```<code>if (list.stream().filter(a -> a.equals(list.get(0))).count() > 1) {
    System.out.println("The first value is not unique in the list");
}
</code>```

Title: Check first element of the array needs to be unique

Body:
I have a semicolon separated text file. The idea is to read the text file line by line. Every line will be splitted to an array element.

Now I want to do some checks like is the ID (first element called "Referenz") unique, are all mandatory "fields" filled, etc...

I guess I have to take the ID and put it to an list. And for the next line I have to compare the ID with the IDs from the list?

So question is that the right way and what / how to realise that.

Here is my code so far:

public class Test_Line2Array {
public static void main(String[] args) {
String strLine = "Referenz;field2;field3;field4;field5;field6;field7;Titel;Name1;Name2;Name3;field8;field9;field10;field11;field12;field13;field14;Street;field15;ZIP;field16;city;field17;dob;field18;field19;field20;field21;field22;field23;field24;field25;field26;field27;field28;field29;field30;field31;field32;field33;field34;field35;field36;field37;field38;field39;phone;mobile;CustomField1;CustomField2;CustomField3;CustomField4;CustomField5;CustomField6;CustomField7;CustomField8;CustomField9;CustomField10";

//declaration
String[] stringArray;
String delimiter = ";";

// allocates memory for 59 strings
stringArray = new String[59];

// split the String after separator ";"
stringArray = strLine.split(";", -1);

// print array
for(int j = 0; j < stringArray.length; j++) {
        System.out.println(j + " " + stringArray[j]);
    }
}

Body:
I recommend you to split the string with delimiter ; and add separated Strings to a List, where you can easily validate with the Collections.frequency() static method returning the number as int of the occurence.

String[] values = strLine.split(";");
List<String> list = Arrays.asList(values);

if (Collections.frequency(list, list.get(0) > 1) {
    System.out.println("The first value is not unique in the list");
}

Since Java 8 feel free to use Stream:

if (list.stream().filter(a -> a.equals(list.get(0))).count() > 1) {
    System.out.println("The first value is not unique in the list");
}


问:
android: Set ToggleButton background back to default
I changed the background for a ToggleButton and wish to reset it back to its default state.

Changed the background:

```<code>btn.setBackgroundColor(Color.parseColor("#FF2929"));
</code>```

Tried changing it back:

```<code>btn.setBackgroundResource(0);                                  //Just text, no button
btn.setBackgroundColor(android.R.drawable.btn_default);        //Normal button not toggle
</code>```

答:
Create an xml file under drawable folder and put this code , currently the xml file name I put is check.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:drawable="@color/Your color"
    android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@color/Your color"
    android:state_checked="false"/>
</selector>
</code>```

Put this code in your toggle button layout xml

```<code>android:background="@drawable/check"
</code>```

This may help you.

Body:
I changed the background for a ToggleButton and wish to reset it back to its default state.

Changed the background:

btn.setBackgroundColor(Color.parseColor("#FF2929"));

Tried changing it back:

btn.setBackgroundResource(0);                                  //Just text, no button
btn.setBackgroundColor(android.R.drawable.btn_default);        //Normal button not toggle

Body:
Create an xml file under drawable folder and put this code , currently the xml file name I put is check.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:drawable="@color/Your color"
    android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@color/Your color"
    android:state_checked="false"/>
</selector>

Put this code in your toggle button layout xml

android:background="@drawable/check"

This may help you.


问:
Detect the location of AppData\LocalLow
I'm trying to locate the path for the AppData\LocalLow folder.

I have found an example which uses:

```<code>string folder = "c:\users\" + Environment.UserName + @"\appdata\LocalLow";
</code>```

which for one is tied to c: and to users which seems a bit fragile.

I tried to use

```<code>Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
</code>```

but this gives me AppData\Local, and I need LocalLow due to the security constraints the application is running under. It returned blank for my service user as well (at least when attaching to the process).

Any other suggestions?

答:
The Environment.SpecialFolder enumeration maps to CSIDL, but there is no CSIDL for the LocalLow folder. So you have to use the KNOWNFOLDERID instead, with the SHGetKnownFolderPath API:

```<code>void Main()
{
    Guid localLowId = new Guid("A520A1A4-1780-4FF6-BD18-167343C5AF16");
    GetKnownFolderPath(localLowId).Dump();
}

string GetKnownFolderPath(Guid knownFolderId)
{
    IntPtr pszPath = IntPtr.Zero;
    try
    {
        int hr = SHGetKnownFolderPath(knownFolderId, 0, IntPtr.Zero, out pszPath);
        if (hr >= 0)
            return Marshal.PtrToStringAuto(pszPath);
        throw Marshal.GetExceptionForHR(hr);
    }
    finally
    {
        if (pszPath != IntPtr.Zero)
            Marshal.FreeCoTaskMem(pszPath);
    }
}

[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);
</code>```

Title: Detect the location of AppData\LocalLow

Body:
I'm trying to locate the path for the AppData\LocalLow folder.

I have found an example which uses:

string folder = "c:\users\" + Environment.UserName + @"\appdata\LocalLow";

which for one is tied to c: and to users which seems a bit fragile.

I tried to use

Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

but this gives me AppData\Local, and I need LocalLow due to the security constraints the application is running under. It returned blank for my service user as well (at least when attaching to the process).

Any other suggestions?

Body:
The Environment.SpecialFolder enumeration maps to CSIDL, but there is no CSIDL for the LocalLow folder. So you have to use the KNOWNFOLDERID instead, with the SHGetKnownFolderPath API:

void Main()
{
    Guid localLowId = new Guid("A520A1A4-1780-4FF6-BD18-167343C5AF16");
    GetKnownFolderPath(localLowId).Dump();
}

string GetKnownFolderPath(Guid knownFolderId)
{
    IntPtr pszPath = IntPtr.Zero;
    try
    {
        int hr = SHGetKnownFolderPath(knownFolderId, 0, IntPtr.Zero, out pszPath);
        if (hr >= 0)
            return Marshal.PtrToStringAuto(pszPath);
        throw Marshal.GetExceptionForHR(hr);
    }
    finally
    {
        if (pszPath != IntPtr.Zero)
            Marshal.FreeCoTaskMem(pszPath);
    }
}

[DllImport("shell32.dll")]
static extern int SHGetKnownFolderPath( [MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out IntPtr pszPath);