问:
I need user input to tell the program which list to use?
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

```<code>import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)
</code>```

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

```<code>import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)
</code>```

now the variable secretword stores the word that is randomly chosen from the list.

答:
Use the while block to validate the response.

```<code>valid_options = ['Animal', 'Clothing' , 'Weather', 'Colors' ]

while True:
    opt = input('Enter: ')
    if opt in valid_options:
        break
    else:
        print('Not a valid option. Valid options are: %s', % ",".join(valid_options))
</code>```

after this code, you can use Christian code to map the values of categories.

Body:
So i'm pretty new to python and i'm making a hangman program.  Here is the code I have so far.

import random
print('Welcome to hangman')
print('Type one of the following categories')
Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Storms']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']
print('Animal, Clothing, Weather, Colors')

category=input()
randomwordindex=random.randint(1,7)

Where it says category=input() I want the user input to be one of the lists I have above.  Then I can use category with an random integer to pick a random word to start the game.  How do I get the input() to be the list and not a string value?

Edit: Okay I got it thanks guys.

Here is the code that I have currently.  I'll probably add a for loop eventually and clean up my while loop so it's one line.

import random

print('Welcome to hangman')
print('Type one of the following categories')

Animal=['Cat','Dog','Bird','Cow','Fish','Lizard']
Clothing=['Shirt','Jeans','Sweatshirt','Shoes','Hat','Scarf']
Weather=['Rain','Snow','Sunny','Sleet','Windy','Stormy']
Colors=['Red','Blue','Green','Purple','Yellow','Grey']

print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')

category=int(input())

while category > 4:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

while category == 0:
    print('Your input isn\'t one of the categories. Make sure your choice is a number from 1 to 4.')
    print('Try entering again')
    print('Type 1 for Animal, 2 for Clothing, 3 for Weather, 4 for Colors')
    category=int(input())

if category == 1: secretword=random.choice(Animal)
if category == 2: secretword=random.choice(Clothing)
if category == 3: secretword=random.choice(Weather)
if category == 4: secretword=random.choice(Colors)

now the variable secretword stores the word that is randomly chosen from the list.

Body:
Use the while block to validate the response.

valid_options = ['Animal', 'Clothing' , 'Weather', 'Colors' ]

while True:
    opt = input('Enter: ')
    if opt in valid_options:
        break
    else:
        print('Not a valid option. Valid options are: %s', % ",".join(valid_options))

after this code, you can use Christian code to map the values of categories.


来源: stackexchange

问:
Why field doesnìt create?
Just need to make a table and put info in it. Make some code but it gives me error

```<code>E/SQLiteLog: (1) table tableOne has no column named email
E/SQLiteDatabase: Error inserting email=Email1 name=Name1
                  android.database.sqlite.SQLiteException: table tableOne has no column named email (code 1): , while compiling: INSERT INTO tableOne(email,name) VALUES (?,?)
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
</code>```

And my code is

```<code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{

final String LOG_TAG = "myLogs";

Button btnAdd;
Button btnRead;
EditText editNameField;
EditText editEmailField;

DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnAdd = (Button) findViewById(R.id.btn_add);
    btnRead = (Button) findViewById(R.id.btn_read);
    editNameField = (EditText) findViewById(R.id.edit_name);
    editEmailField = (EditText) findViewById(R.id.edit_email);

    dbHelper = new DBHelper(this);

    btnAdd.setOnClickListener(this);
    btnRead.setOnClickListener(this);

}

@Override
public void onClick(View view) {

    ContentValues cv = new ContentValues();

    String name = editNameField.getText().toString();
    String email = editEmailField.getText().toString();

    SQLiteDatabase db = dbHelper.getWritableDatabase();

    switch (view.getId()){
        case R.id.btn_add:
            Log.d(LOG_TAG, "--- Insert in mytable: ---");

            cv.put("name", name);
            cv.put("email", email);

            long rowID = db.insert("tableOne", null, cv);
            Log.d(LOG_TAG, "row inserted, ID = " + rowID);
            break;
        case R.id.btn_read:
            Log.d(LOG_TAG, "--- Rows in mytable: ---");

            Cursor c = db.query("tableOne",
                    null,
                    null,
                    null,
                    null,
                    null,
                    null
                    );

            if (c.moveToFirst()){

                int idColIndex = c.getColumnIndex("id");
                int nameColIndex = c.getColumnIndex("name");
                int emailColIndex = c.getColumnIndex("email");

                do {
                    Log.d(LOG_TAG,
                            "ID = " + c.getInt(idColIndex) +
                                    ", name = " + c.getString(nameColIndex) +
                                    ", email = " + c.getString(emailColIndex));
                } while (c.moveToNext());
            } else {
                Log.d(LOG_TAG, "0 rows");
                c.close();
                break;
            }

    }
}

class DBHelper extends SQLiteOpenHelper{

    public DBHelper(Context context) {
        super(context, "tableOne", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(LOG_TAG, "--- onCreate database ---");

        db.execSQL("create table tableOne ("
                + "id integer primary key autoincrement,"
                + "name text,"
                + "email text" + ");");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
}
</code>```

答:
Try to uninstall the application and re install into the emulator and check the problem exist . If exsist then open the adb shell to the emulator and do the following steps.

Open command prompt and type adb shell.

once the shell of the emulator opens -- > then type runas <\package name\>

cd /database

In this location check you have the database created. if created then open it using the sqlite3 <\database_name\>.db .

Type in the queries and check weather the columns are created properly.

If the columns are not found then check out your table creation statement properly. Might have some small issue. Try giving the column name as emailId instead of email and check.

ContentLicense: CC BY-SA 3.0

Title: Why field doesnìt create?

Body:
Just need to make a table and put info in it. Make some code but it gives me error

E/SQLiteLog: (1) table tableOne has no column named email
E/SQLiteDatabase: Error inserting email=Email1 name=Name1
                  android.database.sqlite.SQLiteException: table tableOne has no column named email (code 1): , while compiling: INSERT INTO tableOne(email,name) VALUES (?,?)
                      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)

And my code is

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

final String LOG_TAG = "myLogs";

Button btnAdd;
Button btnRead;
EditText editNameField;
EditText editEmailField;

DBHelper dbHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnAdd = (Button) findViewById(R.id.btn_add);
    btnRead = (Button) findViewById(R.id.btn_read);
    editNameField = (EditText) findViewById(R.id.edit_name);
    editEmailField = (EditText) findViewById(R.id.edit_email);

    dbHelper = new DBHelper(this);

    btnAdd.setOnClickListener(this);
    btnRead.setOnClickListener(this);

}

@Override
public void onClick(View view) {

    ContentValues cv = new ContentValues();

    String name = editNameField.getText().toString();
    String email = editEmailField.getText().toString();

    SQLiteDatabase db = dbHelper.getWritableDatabase();

    switch (view.getId()){
        case R.id.btn_add:
            Log.d(LOG_TAG, "--- Insert in mytable: ---");

            cv.put("name", name);
            cv.put("email", email);

            long rowID = db.insert("tableOne", null, cv);
            Log.d(LOG_TAG, "row inserted, ID = " + rowID);
            break;
        case R.id.btn_read:
            Log.d(LOG_TAG, "--- Rows in mytable: ---");

            Cursor c = db.query("tableOne",
                    null,
                    null,
                    null,
                    null,
                    null,
                    null
                    );

            if (c.moveToFirst()){

                int idColIndex = c.getColumnIndex("id");
                int nameColIndex = c.getColumnIndex("name");
                int emailColIndex = c.getColumnIndex("email");

                do {
                    Log.d(LOG_TAG,
                            "ID = " + c.getInt(idColIndex) +
                                    ", name = " + c.getString(nameColIndex) +
                                    ", email = " + c.getString(emailColIndex));
                } while (c.moveToNext());
            } else {
                Log.d(LOG_TAG, "0 rows");
                c.close();
                break;
            }

    }
}

class DBHelper extends SQLiteOpenHelper{

    public DBHelper(Context context) {
        super(context, "tableOne", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(LOG_TAG, "--- onCreate database ---");

        db.execSQL("create table tableOne ("
                + "id integer primary key autoincrement,"
                + "name text,"
                + "email text" + ");");

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}
}


问:
Filtering with jQuery "find" and "filter" with multiple dropdowns
I have been trying to make some filter options for a page on a clients website with multiple dropdown menus. I can make it work, but it will always reset the filtering when I select an option. I need them to work "together". It's for filtering rooms in a hotel (not a lot of rooms there).

So the first dropdown is the number of persons that can fit in a room, then the type of room to rent, and finally the number of bedrooms in that room/house.

A user can user all 3 dropdowns to filter his results, or he can use only 1. Whatever he likes. He must be able to select "3" in the first dropdown, then it filters everything to show only rooms with up to "3" in the results box. After, if he selects "Studios" in the second dropdown, it needs to keep in mind he has selected "3" for the number of persons that fits in the room, but also the keep in mind that he just selected "Studios" now, so it should display Studios that can have up to 3 persons. etc.

I think you get the idea.
Here's my HTML code:

```<code><select class="bedroom-min">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="type">
  <option value="all">Select...</option>
  <option value="casitas">Casitas</option>
  <option value="studios">Studios</option>
  <option value="dorm">Dorm</option>
</select>

<select class="bedrooms">
  <option value="all">Select...</option>
  <option value="1">1 bedroom</option>
  <option value="2">2 bedrooms</option>
</select>

<div class="property-load-section">
  <div class="property-item" data-bedrooms="5" data-type="casitas" data-bed="1">Room #529</div>
  <div class="property-item" data-bedrooms="4" data-type="studios" data-bed="2">Room #737</div>
  <div class="property-item" data-bedrooms="3" data-type="dorm" data-bed="2">Room #123</div>
  <div class="property-item" data-bedrooms="2" data-type="studios" data-bed="2">Room #126</div>
  <div class="property-item" data-bedrooms="1" data-type="casitas" data-bed="1">Room #523</div>
</div>
</code>```

And here's the jQuery code :

```<code>//Filtering for number of person that can sleep in that room
$("select").change(function() {
  var minValue = $('select.bedroom-min').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') < minValue;
  }).fadeOut('fast');
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') >= minValue;
  }).fadeIn('fast');
});

//Filtering for type of rooms
$("select.type").change(function() {
    var roomType = $('select.type').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-type') != roomType;
  }).fadeOut('fast');
});

//Filtering for the number of bedrooms
$("select.bedrooms").change(function() {
    var roomBed = $('select.bedrooms').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bed') != roomBed;
  }).fadeOut('fast');
});
</code>```

Here's a CodePen link: https://codepen.io/anon/pen/bRxXVK?editors=1010

Can anyone help me out with this? I'm pretty new to javascript/jQuery. Thanks a lot

答:
I would recommend doing the same logic for each select's change event and in that logic you should check for all of the three filtering options at once. In the cases of type and bedrooms the value "all" should also be taken into consideration as it is a special value which will not be equal to the data- attributes you set.

With that said here is the modified  JavaScript code:

```<code>//call the same function for each select's change event
$("select.bedroom-min, select.type, select.bedrooms").change(updateRooms);

function updateRooms() {
  //get all the values
  var minValue = $('select.bedroom-min').val();
  var roomType = $('select.type').val();
  var roomBed = $('select.bedrooms').val();

  $('.property-load-section')
    .find('.property-item')
    .hide()
    .filter(function () {
      var okMinBedrooms = $(this).attr('data-bedrooms') >= minValue;

      var okRoomType = true;
      if(roomType !== "all"){
        okRoomType = $(this).attr('data-type') === roomType;
      }

      var okRoomBed = true;
      if(roomBed !== "all"){
        okRoomBed = $(this).attr('data-bed') === roomBed;
      }

      //only fade a room if it satisfies all three conditions
      return okMinBedrooms && okRoomType && okRoomBed;
  }).fadeIn('fast');
}
</code>```

And a CodePen link.

Body:
I have been trying to make some filter options for a page on a clients website with multiple dropdown menus. I can make it work, but it will always reset the filtering when I select an option. I need them to work "together". It's for filtering rooms in a hotel (not a lot of rooms there).

So the first dropdown is the number of persons that can fit in a room, then the type of room to rent, and finally the number of bedrooms in that room/house.

A user can user all 3 dropdowns to filter his results, or he can use only 1. Whatever he likes. He must be able to select "3" in the first dropdown, then it filters everything to show only rooms with up to "3" in the results box. After, if he selects "Studios" in the second dropdown, it needs to keep in mind he has selected "3" for the number of persons that fits in the room, but also the keep in mind that he just selected "Studios" now, so it should display Studios that can have up to 3 persons. etc.

I think you get the idea.
Here's my HTML code:

<select class="bedroom-min">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select class="type">
  <option value="all">Select...</option>
  <option value="casitas">Casitas</option>
  <option value="studios">Studios</option>
  <option value="dorm">Dorm</option>
</select>

<select class="bedrooms">
  <option value="all">Select...</option>
  <option value="1">1 bedroom</option>
  <option value="2">2 bedrooms</option>
</select>

Room #529

Room #737

Room #123

Room #126

Room #523

And here's the jQuery code :

//Filtering for number of person that can sleep in that room
$("select").change(function() {
  var minValue = $('select.bedroom-min').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') < minValue;
  }).fadeOut('fast');
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') >= minValue;
  }).fadeIn('fast');
});

//Filtering for type of rooms
$("select.type").change(function() {
    var roomType = $('select.type').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-type') != roomType;
  }).fadeOut('fast');
});

//Filtering for the number of bedrooms
$("select.bedrooms").change(function() {
    var roomBed = $('select.bedrooms').val();
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bed') != roomBed;
  }).fadeOut('fast');
});

Here's a CodePen link: https://codepen.io/anon/pen/bRxXVK?editors=1010

Can anyone help me out with this? I'm pretty new to javascript/jQuery. Thanks a lot

Body:
I would recommend doing the same logic for each select's change event and in that logic you should check for all of the three filtering options at once. In the cases of type and bedrooms the value "all" should also be taken into consideration as it is a special value which will not be equal to the data- attributes you set.

With that said here is the modified  JavaScript code:

//call the same function for each select's change event
$("select.bedroom-min, select.type, select.bedrooms").change(updateRooms);

function updateRooms() {
  //get all the values
  var minValue = $('select.bedroom-min').val();
  var roomType = $('select.type').val();
  var roomBed = $('select.bedrooms').val();

  $('.property-load-section')
    .find('.property-item')
    .hide()
    .filter(function () {
      var okMinBedrooms = $(this).attr('data-bedrooms') >= minValue;

      var okRoomType = true;
      if(roomType !== "all"){
        okRoomType = $(this).attr('data-type') === roomType;
      }

      var okRoomBed = true;
      if(roomBed !== "all"){
        okRoomBed = $(this).attr('data-bed') === roomBed;
      }

      //only fade a room if it satisfies all three conditions
      return okMinBedrooms && okRoomType && okRoomBed;
  }).fadeIn('fast');
}

And a CodePen link.


答:
Check out this fiddle - https://jsfiddle.net/pjz958n6/.

```<code>$("select").change(function() {
  var minValue = $('select.bedroom-min').val();
  var roomType = $('select.type').val();
  var roomBed = $('select.bedrooms').val();

  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') < minValue
            || ($(this).attr('data-type') != roomType || roomType == "all")
            || ($(this).attr('data-bed') != roomBed || roomBed == "all");
  }).fadeOut('fast');
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') >= minValue
            && ($(this).attr('data-type') == roomType || roomType == "all")
            && ($(this).attr('data-bed') == roomBed || roomBed == "all");
  }).fadeIn('fast');
});
</code>```

All you need to do is just evaluate all the select options on change of any. The similar for fade-out, just that you need to do an || contrary to && in fade-in.

Title: Filtering with jQuery "find" and "filter" with multiple dropdowns

Body:
Check out this fiddle - https://jsfiddle.net/pjz958n6/.

$("select").change(function() {
  var minValue = $('select.bedroom-min').val();
  var roomType = $('select.type').val();
  var roomBed = $('select.bedrooms').val();

  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') < minValue
            || ($(this).attr('data-type') != roomType || roomType == "all")
            || ($(this).attr('data-bed') != roomBed || roomBed == "all");
  }).fadeOut('fast');
  $('.property-load-section').find('.property-item').filter(function () {
    return $(this).attr('data-bedrooms') >= minValue
            && ($(this).attr('data-type') == roomType || roomType == "all")
            && ($(this).attr('data-bed') == roomBed || roomBed == "all");
  }).fadeIn('fast');
});

All you need to do is just evaluate all the select options on change of any. The similar for fade-out, just that you need to do an || contrary to && in fade-in.


问:
How could I use PyQuery traversal correctly?
There is a file called "name.txt"

Content is below

```<code><td>
    <input class="name" value="Michael">
    <input class="age" value="22">
    <input class="location" value="hebei">

</td>

<td>
    <input class="name" value="Jack">
    <input class="age" value="23">
    <input class="location" value="NewYo">
</td>
</code>```

Now I want to use pyquery to get all input tags, then traversal input tags

Use '.filter' to get all name class and age class

At last, get the value of name and age and write all results into a file called'name_file.txt'

My code is below

```<code># -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
doc = pq(filename='name.txt')

input = doc('input')

for result in input.items():
    name_result = result.filter('.name')
    age_result = result.filter('.age')
    name = name_result.attr('value')
    age = age_result.attr('value')
    print "%s:%s" %(name,age)
    c = "%s:%s" %(name,age)
    f = file('name_file.txt','w')
    f.write(c)
    f.close()
</code>```

But now, I met 2 issues

1. The results I got are not "Michael:22", they are "Michael:None" and "None:22"

2. The content of 'name_file' I wrote into is just 'None:None', not all results I got.

答:
The first problem stems from the fact that you're looping through all your <input ... > elements (collected by doc('input')) so you only either get the name, or the age, but not the both. What you can do is loop through individual  ... 	 blocks and extract the matching children - a bit wasteful but to keep in line with your idea:

```<code>from pyquery import PyQuery as pq

doc = pq(filename='name.txt')  # open our document from `name.txt` file

for result in doc('td').items():  # loop through all <td> ... </td> items
    name_result = result.find('.name')  # grab a tag with class="name"
    age_result = result.find('.age')  # grab a tag with class="age"
    name = name_result.attr('value')  # get the name's `value` attribute value
    age = age_result.attr('value')  # get the age's `value` attribute value
    print("{}:{}".format(name, age))  # print it to the STDOUT as name:age
</code>```

As for the second part - you're opening your name_file.txt file in write mode, writing a line and then closing it on each loop - when you open a file in write mode it will truncate everything in it so you keep writing the first line for each loop. Try doing this instead:

```<code>from pyquery import PyQuery as pq

doc = pq(filename='name.txt')  # open our document from `name.txt` file

with open("name_file.txt", "w") as f:  # open name_file.txt for writing
    for result in doc('td').items():  # loop through all <td> ... </td> items
        name_result = result.find('.name')  # grab a tag with class="name"
        age_result = result.find('.age')  # grab a tag with class="age"
        name = name_result.attr('value')  # get the name's `value` attribute value
        age = age_result.attr('value')  # get the age's `value` attribute value
        print("{}:{}".format(name, age))  # print values to the STDOUT as name:age
        f.write("{}:{}\n".format(name, age))  # write to the file as name:age + a new line
</code>```

Body:
There is a file called "name.txt"

Content is below

    <input class="name" value="Michael">
    <input class="age" value="22">
    <input class="location" value="hebei">

    <input class="name" value="Jack">
    <input class="age" value="23">
    <input class="location" value="NewYo">

Now I want to use pyquery to get all input tags, then traversal input tags

Use '.filter' to get all name class and age class

At last, get the value of name and age and write all results into a file called'name_file.txt'

My code is below

# -*- coding: utf-8 -*-
from pyquery import PyQuery as pq
doc = pq(filename='name.txt')

input = doc('input')

for result in input.items():
    name_result = result.filter('.name')
    age_result = result.filter('.age')
    name = name_result.attr('value')
    age = age_result.attr('value')
    print "%s:%s" %(name,age)
    c = "%s:%s" %(name,age)
    f = file('name_file.txt','w')
    f.write(c)
    f.close()

But now, I met 2 issues

1. The results I got are not "Michael:22", they are "Michael:None" and "None:22"

2. The content of 'name_file' I wrote into is just 'None:None', not all results I got.

Body:
The first problem stems from the fact that you're looping through all your <input ... > elements (collected by doc('input')) so you only either get the name, or the age, but not the both. What you can do is loop through individual <td> ... </td> blocks and extract the matching children - a bit wasteful but to keep in line with your idea:

from pyquery import PyQuery as pq

doc = pq(filename='name.txt')  # open our document from `name.txt` file

for result in doc('td').items():  # loop through all <td> ... </td> items
    name_result = result.find('.name')  # grab a tag with class="name"
    age_result = result.find('.age')  # grab a tag with class="age"
    name = name_result.attr('value')  # get the name's `value` attribute value
    age = age_result.attr('value')  # get the age's `value` attribute value
    print("{}:{}".format(name, age))  # print it to the STDOUT as name:age

As for the second part - you're opening your name_file.txt file in write mode, writing a line and then closing it on each loop - when you open a file in write mode it will truncate everything in it so you keep writing the first line for each loop. Try doing this instead:

from pyquery import PyQuery as pq

doc = pq(filename='name.txt')  # open our document from `name.txt` file

with open("name_file.txt", "w") as f:  # open name_file.txt for writing
    for result in doc('td').items():  # loop through all <td> ... </td> items
        name_result = result.find('.name')  # grab a tag with class="name"
        age_result = result.find('.age')  # grab a tag with class="age"
        name = name_result.attr('value')  # get the name's `value` attribute value
        age = age_result.attr('value')  # get the age's `value` attribute value
        print("{}:{}".format(name, age))  # print values to the STDOUT as name:age
        f.write("{}:{}\n".format(name, age))  # write to the file as name:age + a new line


问:
Export JAR with Netbeans
How to export java project to JAR with Netbeans ? I cannot find options like in Eclipse.</p>

答: It does this by default, you just need to look into the project's /dist folder.

ContentLicense: CC BY-SA 2.5

Title: Export JAR with Netbeans


问:
location for product.tpl file in xcart
I want to know the location of product details page. There are so many product tpl files there. so I do not even know is it product.tpl or product_detail.tpl. So please help.</p>

答:
if you want product details page then it is in

skin/commin_files/customer/main/product.tpl.(this is default if you have your new template then it can be different than common_files)

and if you want PHP file of product details. then it will be in the root directory with name,

product.php

Title: location for product.tpl file in xcart


问:
Execution error: Can't open jupyter notebook on command line (MacOS)
I am a novice just starting to learn Python and other computer languages. I installed Jupiter notebook on my Mac and also anaconda and just encountered a problem when I tried to open jupyter notebook on my command.

The message popped out as :

```<code>execution error: "~~~(I just abbreviated the location)" doesn’t understand the “open location” message. (-1708)
</code>```

I have no sense what's happening here.

How can I solve this?

答:
My workaround was to use the automator tool app for Mac to open both Chrome and jupyter notebook at the same time. Here's the applescript:

```<code>on run {input, parameters}
    tell application "Terminal"
        activate
        do script with command "jupyter notebook"
    end tell
    tell application "Google Chrome"
        activate
        open location "http://localhost:8888/"
    end tell

end run
</code>```

Hopefully this helps!
Here is a good URL on how to use Automator if you have not used it in the past: http://radarearth.com/content/automate-terminal-automator

Body:
I am a novice just starting to learn Python and other computer languages. I installed Jupiter notebook on my Mac and also anaconda and just encountered a problem when I tried to open jupyter notebook on my command.

The message popped out as :

execution error: "~~~(I just abbreviated the location)" doesn’t understand the “open location” message. (-1708)

I have no sense what's happening here.

How can I solve this?

Body:
My workaround was to use the automator tool app for Mac to open both Chrome and jupyter notebook at the same time. Here's the applescript:

on run {input, parameters}
    tell application "Terminal"
        activate
        do script with command "jupyter notebook"
    end tell
    tell application "Google Chrome"
        activate
        open location "http://localhost:8888/"
    end tell

end run

Hopefully this helps!
Here is a good URL on how to use Automator if you have not used it in the past: http://radarearth.com/content/automate-terminal-automator


问:
PHP string comparison for strpos strcmp
I'm using PHP 7.0 and I want to do only string comparison. PHP has strpos strcmp function to do that but I don't know which function will be fast and safe to do string comparison. I have to compare a lot of string and I want to know which function would bring faster result.

In my test, strpos doesn't return NULL for array string comparison but strcmp does. In PHP 7 I tested, but I may use other PHP version for hosting and this problem will be sensitive. Is okay to use if (strpos($x, $y)) to use string comparison?

答:
strpos — Find the position of the first occurrence of a substring in a string

strcmp — Binary safe string comparison

If the string is a string of text like you would get from user input or anything that is not binary then strcmp seems overkill.
I would use Difster's suggestion; It read cleaner then if (strcmp($a,$b))

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

This is the method signature for strpos will the return a truthy value if $b is in $a. So i would not use it to compare if two string are equal only if you want to see if a string is inside another or want to know where the string is at inside the other.

Title: PHP string comparison for strpos strcmp


问:
How to use DataTables font awesome icons?
I am using DataTables and instead of using images for the pagination buttons I decided to use icons. I used the Bootstrap Font awesome CDN which works perfectly fine but in a proxy server, for some reason, the file throws 404 but the DataTables CDN loads properly. From the DataTables documentation I found that DataTables has its own font-awesome meaning embedded one which is as follows:

Here is the fiddle [JSFiddle][1]

```<code>cdn.datatables.net/plug-ins/1.10.15/integration/font-awesome/dataTables.fontAwesome.css
</code>```

Bootstrap CDN has the fa-forward etc classes for the fonts but in the DataTables CDN I couldn't find any so how can I add the icons for the pagination.

JQuery

```<code>var table = $('#example').DataTable({
 pagingType: 'input',
 pageLength: 5,
 language: {
 oPaginate: {
   sNext: '<i class="fa fa-forward"></i>',
   sPrevious: '<i class="fa fa-backward"></i>',
   sFirst: '<i class="fa fa-step-backward"></i>',
   sLast: '<i class="fa fa-step-forward"></i>'
   }
   }
  })
</code>```

Using DataTables font awesome how can I add the classes in my Jquery?

答:
Try with this code

Hope this will helps You.

Edit

Here you can use full_numbers instead of input else it will throw error like

Cannot read property 'fnInit' of undefined.

And in your given font-awesome library there is a no such fonts which you want to use. So use other instead.

$('#example').DataTable({

     language: {
      oPaginate: {
          sNext: '',
          sPrevious: '',
          sFirst: '',
          sLast: ''
      }

   } ,
   pagingType: 'full_numbers',
   pageLength: 5
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<table id="example">
<thead>
        <tr>
            <th>Subscriber ID</th>
            <th>Install Location</th>
            <th>Subscriber Name</th>
            <th>some data</th>
        </tr>
    </thead>
</table></code>```

In Your given CDN

```<code>table.dataTable thead th.sorting:after,
table.dataTable thead th.sorting_asc:after,
table.dataTable thead th.sorting_desc:after {
    position: absolute;
    top: 12px;
    right: 8px;
    display: block;
    font-family: FontAwesome;
}
</code>```

Here you see that your cdn inherits the fontawesome font family

So if you can't use direct fontawesome CDN than download it locally and upload on your server it will helps you.

ContentLicense: CC BY-SA 4.0

Body:
I am using DataTables and instead of using images for the pagination buttons I decided to use icons. I used the Bootstrap Font awesome CDN which works perfectly fine but in a proxy server, for some reason, the file throws 404 but the DataTables CDN loads properly. From the DataTables documentation I found that DataTables has its own font-awesome meaning embedded one which is as follows:

Here is the fiddle [JSFiddle][1]

cdn.datatables.net/plug-ins/1.10.15/integration/font-awesome/dataTables.fontAwesome.css

Bootstrap CDN has the fa-forward etc classes for the fonts but in the DataTables CDN I couldn't find any so how can I add the icons for the pagination.

JQuery

var table = $('#example').DataTable({
 pagingType: 'input',
 pageLength: 5,
 language: {
 oPaginate: {
   sNext: '',
   sPrevious: '',
   sFirst: '',
   sLast: ''
   }
   }
  })

Using DataTables font awesome how can I add the classes in my Jquery?

Body:
Try with this code

Hope this will helps You.

Edit

Here you can use full_numbers instead of input else it will throw error like

Cannot read property 'fnInit' of undefined.

And in your given font-awesome library there is a no such fonts which you want to use. So use other instead.

$('#example').DataTable({

     language: {
      oPaginate: {
          sNext: '<i class="fa fa-forward"></i>',
          sPrevious: '<i class="fa fa-backward"></i>',
          sFirst: '<i class="fa fa-step-backward"></i>',
          sLast: '<i class="fa fa-step-forward"></i>'
      }

   } ,
   pagingType: 'full_numbers',
   pageLength: 5
});

<link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<table id="example">
<thead>
        <tr>
            <th>Subscriber ID</th>
            <th>Install Location</th>
            <th>Subscriber Name</th>
            <th>some data</th>
        </tr>
    </thead>
</table>

In Your given CDN

table.dataTable thead th.sorting:after,
table.dataTable thead th.sorting_asc:after,
table.dataTable thead th.sorting_desc:after {
    position: absolute;
    top: 12px;
    right: 8px;
    display: block;
    font-family: FontAwesome;
}

Here you see that your cdn inherits the fontawesome font family

So if you can't use direct fontawesome CDN than download it locally and upload on your server it will helps you.


问:
How to get on video Shell folder with command line for any windows system?
I'm making a new batch file to convert any *.mp4 files to *.mp3 files with VLC in command line, but i want to improve it to choose the Input folder on Videos for any windows system !

My question is : How to get on videos folder with command line for any windows system?

Here is my code : MP4-MP3_Converter.bat

@echo off
Title Convert (*.mp4) to (*.mp3) with VLC by (c) Hackoo 2017
mode con:cols=85 lines=5 & COLOR 0E
Taskkill /IM "vlc.exe" /F >nul 2>&1
echo.
set "VLC_URL=http://www.videolan.org/vlc/download-windows.html"

IF /I "%PROCESSOR_ARCHITECTURE%"=="x86" (
        Set "vlc=%ProgramFiles%\VideoLAN\VLC\vlc.exe"
    ) else (
        Set "vlc=%ProgramFiles(x86)%\VideoLAN\VLC\vlc.exe"
)

If Not Exist "%vlc%" (
    Cls & COLOR 0C
    echo.
    Echo       "The VLC program is not installed on your system"
    TimeOut /T 5 /NoBreak>nul
    Start "" %VLC_URL%
    Exit
)

Set "MP4Folder=C:\MP4Folder"
Set "MP3Folder=C:\MP3Folder"
If not exist "%MP3Folder%" MD "%MP3Folder%"
CD /D "%MP4Folder%"
for %%a in (*.mp4) do (
    Cls
    echo(
    echo           Please wait a while ... The Conversion is in progress ...
    echo   Conversion of "%%~na.mp4" to "%%~na.mp3"
    "%vlc%" -I dummy "%%a" --sout=#transcode{acodec=mp3,ab=128,vcodec=dummy}:std{access="file",mux="raw",dst="%MP3Folder%\%%~na.mp3"} vlc://quit
)
Explorer "%MP3Folder%" & Exit
```

答:
Not sure how consistent this is across different Windows versions, but I suspect you can use "%userprofile%\videos".

But what is so special about that location? You are making a big assumption that all videos of interest are in that location. For example, I never use that folder, yet I have loads of videos on my hard drive.


问:
ConnectionService implementation for OutgoingCall
I am trying to implement ConnectionService, PhoneAccount and PhoneAccountHandle inorder to get the disconnectCause for the disconnection of my outgoing call(E.g. User rejected the call, unreachable, etc.)
So far I have been able to initiate a call using customPhoneAccount but that phonecall never goes through and hence I am unable to get the response.

Here is the code which I have written uptill now:

register() is the method which is being called from my activity to register the phoneAccount:

```<code>public void register() {
    TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
    PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
            new ComponentName(getPackageName(),
                    MyConnectionService.class.getName()), "myConnectionServiceId");
    PhoneAccount.Builder builder = PhoneAccount.builder(phoneAccountHandle, "CustomAccount");
    builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER | PhoneAccount.CAPABILITY_CONNECTION_MANAGER);
    PhoneAccount phoneAccount = builder.build();
    manager.registerPhoneAccount(phoneAccount);
}
</code>```

call()method which initiates the call:

```<code> public void call() {
    TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
    PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
            new ComponentName(getPackageName(),
                    MyConnectionService.class.getName()), "myConnectionServiceId");
    Bundle test = new Bundle();
    test.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
    manager.placeCall(Uri.parse("tel:" + "1212312312"), test);
}
</code>```

Here is MyConnectionService:

```<code>public class MyConnectionService extends ConnectionService {

public static final String TAG = MyConnectionService.class.getName();
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
    Log.d(TAG, "On Start");
    return super.onStartCommand(intent, flags, startId);
}

@Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
    Connection connection = super.onCreateOutgoingConnection(connectionManagerPhoneAccount, request);
    Log.d(TAG, connection.getDisconnectCause().getReason());
    return connection;
}

@Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
    if (request != null) {
        Log.d(TAG, request.toString());
    }
    super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}
</code>```

I have tried with different capabilities along with all options mentioned on other threads related to ConnectionService but couldn't get the desired result, can anybody help me in this ?

答:
A few things:

You should not use the PhoneAccount.CAPABILITY_CONNECTION_MANAGER, that has a special purpose which is not applicable to your use case and which requires special permissions.

Your onCreateOutgoingConnection method should not call the super version; that method is an blank method in the base ConnectionService class. Telecom calls your override of onCreateOutgoingConnection so that you can provide a new instance of Connection.

Take a look at the Android Open Source TestConnectionService class; it implements a simple ConnectionService:
https://android.googlesource.com/platform/packages/services/Telecomm/+/master/testapps/src/com/android/server/telecom/testapps/TestConnectionService.java

Body:
I am trying to implement ConnectionService, PhoneAccount and PhoneAccountHandle inorder to get the disconnectCause for the disconnection of my outgoing call(E.g. User rejected the call, unreachable, etc.)
So far I have been able to initiate a call using customPhoneAccount but that phonecall never goes through and hence I am unable to get the response.

Here is the code which I have written uptill now:

register() is the method which is being called from my activity to register the phoneAccount:

public void register() {
    TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
    PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
            new ComponentName(getPackageName(),
                    MyConnectionService.class.getName()), "myConnectionServiceId");
    PhoneAccount.Builder builder = PhoneAccount.builder(phoneAccountHandle, "CustomAccount");
    builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER | PhoneAccount.CAPABILITY_CONNECTION_MANAGER);
    PhoneAccount phoneAccount = builder.build();
    manager.registerPhoneAccount(phoneAccount);
}

call()method which initiates the call:

 public void call() {
    TelecomManager manager = (TelecomManager) getSystemService(TELECOM_SERVICE);
    PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
            new ComponentName(getPackageName(),
                    MyConnectionService.class.getName()), "myConnectionServiceId");
    Bundle test = new Bundle();
    test.putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccountHandle);
    manager.placeCall(Uri.parse("tel:" + "1212312312"), test);
}

Here is MyConnectionService:

public class MyConnectionService extends ConnectionService {

public static final String TAG = MyConnectionService.class.getName();
@Override
public int onStartCommand(Intent intent,int flags, int startId) {
    Log.d(TAG, "On Start");
    return super.onStartCommand(intent, flags, startId);
}

@Override
public Connection onCreateOutgoingConnection(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
    Connection connection = super.onCreateOutgoingConnection(connectionManagerPhoneAccount, request);
    Log.d(TAG, connection.getDisconnectCause().getReason());
    return connection;
}

@Override
public void onCreateOutgoingConnectionFailed(PhoneAccountHandle connectionManagerPhoneAccount, ConnectionRequest request) {
    if (request != null) {
        Log.d(TAG, request.toString());
    }
    super.onCreateOutgoingConnectionFailed(connectionManagerPhoneAccount, request);
}

I have tried with different capabilities along with all options mentioned on other threads related to ConnectionService but couldn't get the desired result, can anybody help me in this ?


问:
How to change position of md-grid-list child position ( md-grid-tile ) from left to right?
I have  md-grid-list  in my code and it has three md-grid-tile as children,   md-grid-list has relative position and  md-grid-tiles have absolute position with left attribute that calculated automatically. How can I change this position to right and puts md-grid-tiles from right to left instead of left to right ?

答:
Whats about document.body.dir == 'rtl';?
I don't know any angular-material but I think that's what you need.

Maybe this Plunker would help you - click me

or have a look into this github angular.js "ng-grid" rtl


问:
gdb get different structure size when command run twice
I have a program run in such a way:

process A  ---write-->global structure---read by--->process B

whereas process B can't get what A once written

Using GDB, I found something weird like that:

Can any one explain why this happen?

答:
There's not a lot of details to go on in your question, but making some assumptions, let me ask: Are these two programs compiled against the same headers?

If the header files used to compile each program differ, sizeof(struct) in each might differ.


问:
I cant install netbeans
I get this error:</p>

```<code>A fatal error has been detected by the Java Runtime Environment:

 EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x60ed21f4, pid=5164, tid=0x00000f24

 JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
 Java VM: Java HotSpot(TM) Client VM (25.131-b11 mixed mode, sharing windows-x86 )
 Problematic frame:
 C  [msvcr100.dll+0x121f4]

Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
</code>```

答:
So it can a various things :
The download can be uncomplete or curropted, try re-downloading: https://netbeans.org/downloads/

if it continous it can be a problem with Java so you can try reinstallation and be sure you use the proper version of Java (64bit/32bit):  https://java.com/en/download/manual.jsp

if after all this it still persist it can be a malware or a virus.
Or the Java Runtime Environment files where erased by a different program in error or with malicious intends.

Title: I cant install netbeans

Body:
I get this error:

A fatal error has been detected by the Java Runtime Environment:

 EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x60ed21f4, pid=5164, tid=0x00000f24

 JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
 Java VM: Java HotSpot(TM) Client VM (25.131-b11 mixed mode, sharing windows-x86 )
 Problematic frame:
 C  [msvcr100.dll+0x121f4]

Failed to write core dump. Minidumps are not enabled by default on client versions of Windows


问:
Fix migrate android code error on eclipse?

I got an error while i build my app on eclipse

anyone can tell me how can i fix it ?

答: remove switch case ,and use else if  or other whatever you want error resolved.</p>


问:
why use xsd with wsdl in java Web services
In one of my project it is told write wsdl and xsd file to create web services in java
It is necessary to always write xsd for wsdl? </p>

答: xsd is important for the data structure of the messages that will be sent between the client and the service hosting the web service. They ensure that the client cannot just out any arbitrary data fields from no where. So you will be sure when using xsds that the structure of the data will always be in the way that it is specified on the xsd. It's the same concept as the compiler of your code, that ensures that the syntax of your code follows a specified structure before allowing you to do anything else.</p>


问:
How can I make Bootstrap 4 columns have a height of 100%?
how can I make a column take up 100% height of the browser w bootstrap 4?

See the following: https://codepen.io/johnpickly/pen/dRqxjV

Note the yellow div, I need this div/column to take up a height of 100%... Is there way to make this happen without having to make all parent div's have a height of 100%?

Thank you

html:

```<code><div class="container-fluid">
  <div class="row justify-content-center">

    <div class="col-4 hidden-md-down" id="yellow">
      XXXX
    </div>

    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8">
      Form Goes Here
    </div>
  </div>
</div>
</code>```

答:
Set display: table for parent div and display: table-cell for children divs

HTML :

      XXXX

      XXXX

      XXXX

      XXXX

      XXXX

      XXXX
vv
      XXXX

      Form Goes Here

```

<p>CSS: </p>

<pre class="lang-css prettyprint-override"><code>#yellow {
  height: 100%;
  background: yellow;
  width: 50%;
}
#red {background: red}

.container-fluid {bacgkround: #ccc}

/* this is the part make equal height */
.display-as-table {display: table; width: 100%;}
.display-as-table > div {display: table-cell; float: none;}
</code>```

Body:
how can I make a column take up 100% height of the browser w bootstrap 4?

See the following: https://codepen.io/johnpickly/pen/dRqxjV

Note the yellow div, I need this div/column to take up a height of 100%... Is there way to make this happen without having to make all parent div's have a height of 100%?

Thank you

html:

      XXXX

      Form Goes Here

Body:
Set display: table for parent div and display: table-cell for children divs

HTML :

<div class="container-fluid">
  <div class="row justify-content-center display-as-table">

    <div class="col-4 hidden-md-down" id="yellow">
      XXXX<br />
      XXXX<br />
      XXXX<br />
      XXXX<br />
      XXXX<br />
      XXXX<br />vv
      XXXX<br />
    </div>

    <div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8" id="red">
      Form Goes Here
    </div>
  </div>
</div>

CSS:

#yellow {
  height: 100%;
  background: yellow;
  width: 50%;
}
#red {background: red}

.container-fluid {bacgkround: #ccc}

/* this is the part make equal height */
.display-as-table {display: table; width: 100%;}
.display-as-table > div {display: table-cell; float: none;}


问:
How do I apply a diff or patch file?
when using the rugged git library how can I apply that diff to my dest branch as a commit?.

```<code>  # @param src [Rugged::Object] - the rugged object or string to compare from
  # @param dst [Rugged::Object] - the rugged object or string to compare to, defaults to parent
  # @return [Rugged::Diff] a rugged diff object between src and dst
  def create_diff(src, dst = nil)
    src = repo.lookup(find_ref(src))
    dst ||= repo.lookup(src.parents.first)
    dst = find_ref(dst)
    src.diff(dst)
  end

  # @param sha_or_ref [String] - the name or sha of the ref
  # @return [String] the oid of the sha or ref
  def find_ref(sha_or_ref)
    case sha_or_ref
      when Rugged::Object
        sha_or_ref.oid
      else
        repo.rev_parse_oid(sha_or_ref)
    end
  end
</code>```

Is there not an easy way to apply a patch or diff?  Seems silly that I would need to loop through each change in the diff and either add/rm the file.

答:
Considering the:

libgit2/rugged is the ruby bindings to libgit2

libgit2's apply patch feature was requested from a long time (2013) and only recently merged (a year ago) for libgit2 0.24.4,

You would have to wait for that feature to be ported in rugged.

The last official release v0.24.0 does not include 0.24.4.

Title: How do I apply a diff or patch file?

Body:
when using the rugged git library how can I apply that diff to my dest branch as a commit?.

  # @param src [Rugged::Object] - the rugged object or string to compare from
  # @param dst [Rugged::Object] - the rugged object or string to compare to, defaults to parent
  # @return [Rugged::Diff] a rugged diff object between src and dst
  def create_diff(src, dst = nil)
    src = repo.lookup(find_ref(src))
    dst ||= repo.lookup(src.parents.first)
    dst = find_ref(dst)
    src.diff(dst)
  end

  # @param sha_or_ref [String] - the name or sha of the ref
  # @return [String] the oid of the sha or ref
  def find_ref(sha_or_ref)
    case sha_or_ref
      when Rugged::Object
        sha_or_ref.oid
      else
        repo.rev_parse_oid(sha_or_ref)
    end
  end

Is there not an easy way to apply a patch or diff?  Seems silly that I would need to loop through each change in the diff and either add/rm the file.


问:
how to use map function in a list using Javascript or Jquery
this is my HTMl,

   <select id="Select1" style="display:none" multiple="multiple" data-limit="7" wtx-context="5C3D486B-FBBF-4191-BDA3-C2F28323036B">
      <option></option>
      <option data-img-src="" value="728" data-img-label="10"></option>
      <option data-img-src="" data-img-label="11"></option>
      <option data-img-src="" value="730" data-img-label="12"></option>
   </select>

```
</div>
</div>
</p>

<p>has a <code>select</code> control that has a list associated to it. I want to map and get all image sources that has <code>thumbnail selected</code> class</p>

<p>I tried this but i get an empty array,</p>

```var list = $('.thumbnail').map(function () { return $(this).closest("img").attr("src"); }).get();

console.log(list.join(','))
```

答:
You need to do children() instead of closest() (Because images are children of thumbnail divs):-

var list = $('.thumbnail').map(function () { return $(this).children("img").attr("src"); }).get();

console.log(list);

//console.log(list.join(','));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="myGal" tabindex="5001" style="overflow: hidden; outline: none;">
  <select id="Select1" style="display:none" multiple="multiple" data-limit="7" wtx-context="5C3D486B-FBBF-4191-BDA3-C2F28323036B">
    <option></option>
    <option data-img-src="" value="728" data-img-label="10"></option>
    <option data-img-src="" data-img-label="11"></option><option data-img-src="" value="730" data-img-label="12"></option>
  </select>
  <ul class="thumbnails image_picker_selector">
    <li>
      <div class="thumbnail selected">
        <img class="image_picker_image loaded" src="http://localhost:1344//ARTSQLDATA/PTDIR/170629062/Pictures/Personal_Picture/170629062_4353_4a97162c-7350-43eb-82df-6e92f49b30bb.jpg?w=90&h=90&mode=max">
      </div>
    </li>
    <li>
      <div class="thumbnail">
        <img class="image_picker_image loaded" src="http://localhost:1344//ARTSQLDATA/PTDIR/170629062/Pictures/Personal_Picture/170629062_4353_bb197250-91ab-449e-9cd0-3f69ef3a7353.jpg?w=90&h=90&mode=max">
      </div>
    </li>
    <li>
      <div class="thumbnail selected">
        <img class="image_picker_image" src="http://localhost:1344//ARTSQLDATA/PTDIR/170629062/Pictures/Personal_Picture/170629062_4353_8eb91587-f229-46f4-af1e-7327cb81a25e.jpg?w=90&h=90&mode=max">
      </div>
    </li>
  </ul>
</div></code>```

Note:- closest() use to check elements on same-level, but here images are children of the corresponding div, that's why you are getting empty array.

Body:
this is my HTMl,

   <select id="Select1" style="display:none" multiple="multiple" data-limit="7" wtx-context="5C3D486B-FBBF-4191-BDA3-C2F28323036B">
      <option></option>
      <option data-img-src="" value="728" data-img-label="10"></option>
      <option data-img-src="" data-img-label="11"></option>
      <option data-img-src="" value="730" data-img-label="12"></option>
   </select>

has a select control that has a list associated to it. I want to map and get all image sources that has thumbnail selected class

I tried this but i get an empty array,

var list = $('.thumbnail').map(function () { return $(this).closest("img").attr("src"); }).get();

console.log(list.join(','))

Body:
You need to do children() instead of closest() (Because images are children of thumbnail divs):-

var list = $('.thumbnail').map(function () { return $(this).children("img").attr("src"); }).get();

console.log(list);

//console.log(list.join(','));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="myGal" tabindex="5001" style="overflow: hidden; outline: none;">
  <select id="Select1" style="display:none" multiple="multiple" data-limit="7" wtx-context="5C3D486B-FBBF-4191-BDA3-C2F28323036B">
    <option></option>
    <option data-img-src="" value="728" data-img-label="10"></option>
    <option data-img-src="" data-img-label="11"></option><option data-img-src="" value="730" data-img-label="12"></option>
  </select>
  <ul class="thumbnails image_picker_selector">
    <li>
      <div class="thumbnail selected">
        <img class="image_picker_image loaded" src="http://localhost:1344//ARTSQLDATA/PTDIR/170629062/Pictures/Personal_Picture/170629062_4353_4a97162c-7350-43eb-82df-6e92f49b30bb.jpg?w=90&amp;h=90&amp;mode=max">
      </div>
    </li>
    <li>
      <div class="thumbnail">
        <img class="image_picker_image loaded" src="http://localhost:1344//ARTSQLDATA/PTDIR/170629062/Pictures/Personal_Picture/170629062_4353_bb197250-91ab-449e-9cd0-3f69ef3a7353.jpg?w=90&amp;h=90&amp;mode=max">
      </div>
    </li>
    <li>
      <div class="thumbnail selected">
        <img class="image_picker_image" src="http://localhost:1344//ARTSQLDATA/PTDIR/170629062/Pictures/Personal_Picture/170629062_4353_8eb91587-f229-46f4-af1e-7327cb81a25e.jpg?w=90&amp;h=90&amp;mode=max">
      </div>
    </li>
  </ul>
</div>

Note:- closest() use to check elements on same-level, but here images are children of the corresponding div, that's why you are getting empty array.


问:
How to add list elements into dictionary
Let's say I have dict = {'a': 1, 'b': 2'} and I also have a list = ['a', 'b, 'c', 'd', 'e']. Goal is to add the list elements into the dictionary and print out the new dict values along with the sum of those values. Should look like:

```<code>2 a
3 b
1 c
1 d
1 e
Total number of items: 8
</code>```

Instead I get:

```<code>1 a
2 b
1 c
1 d
1 e
Total number of items: 6
</code>```

What I have so far:

```<code>def addToInventory(inventory, addedItems)
    for items in list():
        dict.setdefault(item, [])

def displayInventory(inventory):
    print('Inventory:')
    item_count = 0
    for k, v in inventory.items():
       print(str(v) + ' ' + k)
       item_count += int(v)
    print('Total number of items: ' + str(item_count))

newInventory=addToInventory(dict, list)
displayInventory(dict)
</code>```

Any help will be appreciated!

答:
For the first section of this question this is the code that I came up with.

```<code>invt = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
print ("Inventory:")
total = sum(invt.values())
for x, v in invt.items():
  print (str(v) + ' ' + x)
print ("Total number of items: {}".format(total))
</code>```

I see that most people are interating through the loop to add to the total variable. However using the sum method, I skipped a step ..

Always open to feedback....

Body:
Let's say I have dict = {'a': 1, 'b': 2'} and I also have a list = ['a', 'b, 'c', 'd', 'e']. Goal is to add the list elements into the dictionary and print out the new dict values along with the sum of those values. Should look like:

2 a
3 b
1 c
1 d
1 e
Total number of items: 8

Instead I get:

1 a
2 b
1 c
1 d
1 e
Total number of items: 6

What I have so far:

def addToInventory(inventory, addedItems)
    for items in list():
        dict.setdefault(item, [])

def displayInventory(inventory):
    print('Inventory:')
    item_count = 0
    for k, v in inventory.items():
       print(str(v) + ' ' + k)
       item_count += int(v)
    print('Total number of items: ' + str(item_count))

newInventory=addToInventory(dict, list)
displayInventory(dict)

Any help will be appreciated!

Body:
For the first section of this question this is the code that I came up with.

invt = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
print ("Inventory:")
total = sum(invt.values())
for x, v in invt.items():
  print (str(v) + ' ' + x)
print ("Total number of items: {}".format(total))

I see that most people are interating through the loop to add to the total variable. However using the sum method, I skipped a step ..

Always open to feedback....


问:
Merging objects within an array and keeping the highest value for identical properties
I have this array and I would like to merge the objects within it.

```<code>[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]
</code>```

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }```

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.

答:
You can do it with _.mergeWith from Lodash library.</p>

```<code>var input = [null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}];
var output = _.mergeWith({}, ...input, (obj, src) => obj > src ? obj : src);
</code>```

Body:
I have this array and I would like to merge the objects within it.

[null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}]

I thought about using something like this:

var o1 = { a: 1, b: 1, c: 1 };
var o2 = { b: 2, c: 2 };
var o3 = { c: 3 };

var obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }

However, the properties are overwritten by other objects that have the same properties later in the parameters order

What I want is to keep the highest value available for the same property.

In my example, I have {"2":1} and {"2":2}, I would like to keep the {"2":2} because 2 is the highest value available for the "2" property.

I want to end up with this object: {"1":1,"2":2,"3":1,"5":1}.

Body:
You can do it with _.mergeWith from Lodash library.

var input = [null, null, {"1":1},{"2":1},{"3":1},{"2":2},{"5":1}];
var output = _.mergeWith({}, ...input, (obj, src) => obj > src ? obj : src);


问:
Entity Framework record is adding a new record instead of using existing record
I have an issue where I'm inserting a new record of order and inside of order i have order details.  There can be multiple details each with a product which already exists in the database. My problem is when i try to update the order detail product with the product from the database it wants to put a new record into the database with an empty guid instead of using the one that is already there.

```<code>var order = context.Orders.FirstOrDefault(o => o.OrderId == request.Order.OrderId);
if (order == null)
{
    ...

    // This is where a new order is mapped in from a class model
    // The class model contains order information and order details.

    ...

    // Order Detail
    foreach (var detail in order.OrderDetails)
    {
        var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
        detail.Product = product;
        detail.ProductId = product.Id;
    }

    context.SaveChanges();
}
</code>```

I have tried to set the detail.Product state to unchanged but that does not work either.

Here is what the records look like after one order has been inserted.  You can see the same ProductId but different Guid's.  The one that has a Guid is the original that it found but after doing SaveChanges then the empty Guid record was inserted.

```<code>Id                                      ProductId   CostPrice   DateCreated
00000000-0000-0000-0000-000000000000    11671170639 14.75       2017-07-08 04:16:21.927
931F65C2-919B-4876-8D6A-77387FF22001    11671170639 14.75       2017-07-07 11:11:29.327
</code>```

答:
i think you don't need the line which i say it below:

```<code> // Order Detail
    foreach (var detail in order.OrderDetails)
    {
        var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
        detail.Product = product;
        detail.ProductId = product.Id;   // why you did this??? it has to bind at upper line
    }
</code>```

and next...i dont understand your database... you are selecting orders product at this line:

```<code> var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
</code>```

and then you bind detail.Product again? why you wan to do this ? if your product has a product by the same id so it has...you don't need to bind it again.
i think its better to have a review on your code logic!.

Body:
I have an issue where I'm inserting a new record of order and inside of order i have order details.  There can be multiple details each with a product which already exists in the database. My problem is when i try to update the order detail product with the product from the database it wants to put a new record into the database with an empty guid instead of using the one that is already there.

var order = context.Orders.FirstOrDefault(o => o.OrderId == request.Order.OrderId);
if (order == null)
{
    ...

    // This is where a new order is mapped in from a class model
    // The class model contains order information and order details.

    ...

    // Order Detail
    foreach (var detail in order.OrderDetails)
    {
        var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
        detail.Product = product;
        detail.ProductId = product.Id;
    }

    context.SaveChanges();
}

I have tried to set the detail.Product state to unchanged but that does not work either.

Here is what the records look like after one order has been inserted.  You can see the same ProductId but different Guid's.  The one that has a Guid is the original that it found but after doing SaveChanges then the empty Guid record was inserted.

Id                                      ProductId   CostPrice   DateCreated
00000000-0000-0000-0000-000000000000    11671170639 14.75       2017-07-08 04:16:21.927
931F65C2-919B-4876-8D6A-77387FF22001    11671170639 14.75       2017-07-07 11:11:29.327

Body:
i think you don't need the line which i say it below:

 // Order Detail
    foreach (var detail in order.OrderDetails)
    {
        var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);
        detail.Product = product;
        detail.ProductId = product.Id;   // why you did this??? it has to bind at upper line
    }

and next...i dont understand your database... you are selecting orders product at this line:

 var product = context.Products.FirstOrDefault(p => p.ProductId == detail.Product.ProductId);

and then you bind detail.Product again? why you wan to do this ? if your product has a product by the same id so it has...you don't need to bind it again.
i think its better to have a review on your code logic!.


问:
How do I have hostnames with full stop in Openstack Heat templates?
I am trying to set the hostname to be the full DNS name of a server, but if I include a full stop it seems to be cut from the end.

This is how I am setting the hostname:

```<code>properties:
      name: sample-name.domain.com
</code>```

However, this gives a hostname of sample-name. The full name shows up correctly in the Instances list.

答:
I looked into the /var/log/cloud-init.log and I see that the hostname is set to "sample-name" irrespective of whether you set the name to "sample-name.domain.com" or "sample-name" in the properties.

So, we can set the hostname using "user_data" in heat template as below:

```<code>user_data:
            #!/bin/bash
            sudo bash -c "echo 'sample-name.domain.com' > /etc/hostname"
            sudo bash -c "hostname sample-name.domain.com"
</code>```

Body:
I am trying to set the hostname to be the full DNS name of a server, but if I include a full stop it seems to be cut from the end.

This is how I am setting the hostname:

properties:
      name: sample-name.domain.com

However, this gives a hostname of sample-name. The full name shows up correctly in the Instances list.

Body:
I looked into the /var/log/cloud-init.log and I see that the hostname is set to "sample-name" irrespective of whether you set the name to "sample-name.domain.com" or "sample-name" in the properties.

So, we can set the hostname using "user_data" in heat template as below:

user_data:
            #!/bin/bash
            sudo bash -c "echo 'sample-name.domain.com' > /etc/hostname"
            sudo bash -c "hostname sample-name.domain.com"


问:
WordPress sitemap with the Google XML Sitemaps plugin
I installed the plugin and as expected the sitemap should be visible on domainname.com/sitemap.xml. It is visible, but like shown in the photo. I don't have posts, only pages. The list of the pages links is only visible when I click on one of the sub-sitemaps links. How to remove them? Thank you.

答:
A sitemap index file is like a master sitemap file.

Basics (Which I am sure you are already aware of)
A sitemap is a set of links which a crawler will file and index.
A master sitemap file is a link to other sitemap files.

Google fully understands the process of a sitemap index file and will work with it very well. So if you are concerned about your pages getting indexed, sitemap index file will do just fine. It even has more advantages over normal sitemap file.

Don't want to have sub sitemap files?

If you are still looking for a normal sitemap file with, you can downgrade the version of your current plugin to 3.x version as version 4 supports only the new format. If you don't want to downgrade, you can use other plugins like yoast. Both will do just fine.

P.S. If your site has proper navigation and no island pages, submitting a sitemap is not necessary at all. Google will do its job.


问:
Pyparsing: How can I parse data and then edit a specific value in a .txt file?
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

```<code>from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value
</code>```

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

答:
Even though you have already selected another answer, let me answer your original question, which was how to do this using pyparsing.

If you are trying to make selective changes in some body of text, then transformString is a better choice than scanString (although scanString or searchString are fine for validating your grammar expression by looking for matching text).  transformString will apply token suppression or parse action modifications to your input string as it scans through the text looking for matches.

```<code># alphas + alphanums is unnecessary, since alphanums includes all alphas
ident = Word(alphanums + "_")
# I find this shorthand form of setResultsName is a little more readable
macroDef = ident("name") + "=" + ident("value")

# define values to be updated, and their new values
valuesToUpdate = {
    "variablename" : "new_value"
    }

# define a parse action to apply value updates, and attach to macroDef
def updateSelectedDefinitions(tokens):
    if tokens.name in valuesToUpdate:
        newval = valuesToUpdate[tokens.name]
        return "%s = %s" % (tokens.name, newval)
    else:
        raise ParseException("no update defined for this definition")
macroDef.setParseAction(updateSelectedDefinitions)

# now let transformString do all the work!
print macroDef.transformString(src)
</code>```

Gives:

```<code>variablename = new_value
something = thisvalue
youget = the_idea
</code>```

Body:
my data is located in a .txt file (no, I can't change it to a different format) and it looks like this:

varaiablename = value

something = thisvalue

youget = the_idea

Here is my code so far (taken from the examples in Pyparsing):

from pyparsing import Word, alphas, alphanums, Literal, restOfLine, OneOrMore, \
empty, Suppress, replaceWith

input = open("text.txt", "r")
src = input.read()

# simple grammar to match #define's
ident = Word(alphas + alphanums + "_")
macroDef = ident.setResultsName("name") + "= " + ident.setResultsName("value") + Literal("#") + restOfLine.setResultsName("desc")
for t,s,e in macroDef.scanString(src):
print t.name,"=", t.value

So how can I tell my script to edit a specific value for a specific variable?

Example:

I want to change the value of variablename, from value to new_value.
So essentially variable = (the data we want to edit).

I probably should make it clear that I don't want to go directly into the file and change the value by changing value to new_value but I want to parse the data, find the variable and then give it a new value.

Body:
Even though you have already selected another answer, let me answer your original question, which was how to do this using pyparsing.

If you are trying to make selective changes in some body of text, then transformString is a better choice than scanString (although scanString or searchString are fine for validating your grammar expression by looking for matching text).  transformString will apply token suppression or parse action modifications to your input string as it scans through the text looking for matches.

# alphas + alphanums is unnecessary, since alphanums includes all alphas
ident = Word(alphanums + "_")
# I find this shorthand form of setResultsName is a little more readable
macroDef = ident("name") + "=" + ident("value")

# define values to be updated, and their new values
valuesToUpdate = {
    "variablename" : "new_value"
    }

# define a parse action to apply value updates, and attach to macroDef
def updateSelectedDefinitions(tokens):
    if tokens.name in valuesToUpdate:
        newval = valuesToUpdate[tokens.name]
        return "%s = %s" % (tokens.name, newval)
    else:
        raise ParseException("no update defined for this definition")
macroDef.setParseAction(updateSelectedDefinitions)

# now let transformString do all the work!
print macroDef.transformString(src)

Gives:

variablename = new_value
something = thisvalue
youget = the_idea


问:
Issue loading data from array into a select list in react
I have the following class:

```<code>class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => {
            <option value={c.value} >{c.text}</option>
          })
        }
      </select>
    );
  }
}
</code>```

If I render the select list with regular html syntax then it works perfectly, where as if I try to create it dynamically then it doesn't load anything. How would you go about creating a list dynamically in react so that it maintains its binding?

Any advice would be appreciated!

Thanks.

答:
When you are using the curly braces in the following piece of code:

```<code>this.bookOptions.map((c) => {
  <option value={c.value} >{c.text}</option>
})
</code>```

You are not returning anything, hence you are rendering an array of undefined elements. Remove that and your code should work as expected. See the working code below.

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => <option key={c.text} value={c.value} >{c.text}</option>)
        }
      </select>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Body:
I have the following class:

class App extends Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => {
            <option value={c.value} >{c.text}</option>
          })
        }
      </select>
    );
  }
}

If I render the select list with regular html syntax then it works perfectly, where as if I try to create it dynamically then it doesn't load anything. How would you go about creating a list dynamically in react so that it maintains its binding?

Any advice would be appreciated!

Thanks.

Body:
When you are using the curly braces in the following piece of code:

this.bookOptions.map((c) => {
  <option value={c.value} >{c.text}</option>
})

You are not returning anything, hence you are rendering an array of undefined elements. Remove that and your code should work as expected. See the working code below.

class App extends React.Component {

  constructor(props){
    super(props);
    this.state = {value: 'currentlyReading'};

    this.handleChange = this.handleChange.bind(this);
  }

  bookOptions = [{
        value: 'currentlyReading',
        text: 'Currently Reading'
    },
    {
        value: 'wantToRead',
        text: 'Want to Read'
    },
    {
        value: 'read',
        text: 'Read'
    },
    {
        value: 'none',
        text: 'None'
    }]

    onHandleChange = (e) => {
        this.setState({
            state: e.target.value
        })
    };

  handleChange(e){
    this.setState({value: e.target.value});
  }
  render() {
    return (
      <select value={this.state.value} onChange={this.handleChange}>
        {
          this.bookOptions.map((c) => <option key={c.text} value={c.value} >{c.text}</option>)
        }
      </select>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
how to clear “distinct” RxJS operator in Angular 2?
Is there a way to clear the distinct() cache?

as you can see, sometimes i set this.messages=[], at that point, i'd like to clear the cache. Instead i've done a hack, where i increase distinctCount.

```<code>ngOnInit() {
    let saved = {}
    let distinctCount = 1000000000000
    let messageStream = this.route.params
            .map(params=>params['id'])
            .switchMap((id)=> {
                this.messages = []
                saved[this.id] = this.newMessage
                this.id = id
                distinctCount+=1000000000000
                this.newMessage = saved[id] || ''
                return Observable.interval(3500).startWith(0).switchMap(()=> {
                    let count = 5
                    if (this.messages.length == 0) {
                        count = 10
                    }
                    return this.conversationsApi.apiConversationsByConversationIdGetMessagesGet(this.id, this.authService.getAuth(), undefined, count, undefined, undefined, undefined)
                })
            })
            .concatMap((messages:Array<MessageModel>)=>{
                return Observable.from(messages.slice().reverse())
            })
            .distinct(message=>message.id+distinctCount)
}
</code>```

答:
ended up having a nice solution to this, simply pass this.route.params observable as the second argument to distinct().

the second argument is a flush observable, distinct flushes its cache whenever that observable emits

so whenever a user navigates between conversations, the cache flushes.

```<code>    ngOnInit() {
            let saved = {}
            let messageStream = this.route.params
                    .map(params=>params['id'])
                    .switchMap((id)=> {
                        this.messages = []
                        saved[this.id] = this.newMessage
                        this.id = id
                        this.newMessage = saved[id] || ''
                        return Observable.interval(3500).startWith(0).switchMap(()=> {
                            let count = 5
                            if (this.messages.length == 0) {
                                count = 10
                            }
                            return this.conversationsApi.apiConversationsByConversationIdGetMessagesGet(this.id, this.authService.getAuth(), undefined, count, undefined, undefined, undefined)
                        })
                    })
                    .concatMap((messages:Array<MessageModel>)=>{
                        return Observable.from(messages.slice().reverse())
                    })
                    .distinct(message=>message.id, this.route.params)
}
</code>```

Body:
Is there a way to clear the distinct() cache?

as you can see, sometimes i set this.messages=[], at that point, i'd like to clear the cache. Instead i've done a hack, where i increase distinctCount.

ngOnInit() {
    let saved = {}
    let distinctCount = 1000000000000
    let messageStream = this.route.params
            .map(params=>params['id'])
            .switchMap((id)=> {
                this.messages = []
                saved[this.id] = this.newMessage
                this.id = id
                distinctCount+=1000000000000
                this.newMessage = saved[id] || ''
                return Observable.interval(3500).startWith(0).switchMap(()=> {
                    let count = 5
                    if (this.messages.length == 0) {
                        count = 10
                    }
                    return this.conversationsApi.apiConversationsByConversationIdGetMessagesGet(this.id, this.authService.getAuth(), undefined, count, undefined, undefined, undefined)
                })
            })
            .concatMap((messages:Array<MessageModel>)=>{
                return Observable.from(messages.slice().reverse())
            })
            .distinct(message=>message.id+distinctCount)
}

Body:
ended up having a nice solution to this, simply pass this.route.params observable as the second argument to distinct().

the second argument is a flush observable, distinct flushes its cache whenever that observable emits

so whenever a user navigates between conversations, the cache flushes.

    ngOnInit() {
            let saved = {}
            let messageStream = this.route.params
                    .map(params=>params['id'])
                    .switchMap((id)=> {
                        this.messages = []
                        saved[this.id] = this.newMessage
                        this.id = id
                        this.newMessage = saved[id] || ''
                        return Observable.interval(3500).startWith(0).switchMap(()=> {
                            let count = 5
                            if (this.messages.length == 0) {
                                count = 10
                            }
                            return this.conversationsApi.apiConversationsByConversationIdGetMessagesGet(this.id, this.authService.getAuth(), undefined, count, undefined, undefined, undefined)
                        })
                    })
                    .concatMap((messages:Array<MessageModel>)=>{
                        return Observable.from(messages.slice().reverse())
                    })
                    .distinct(message=>message.id, this.route.params)
}


问:
What keyboard shortcut is there to organize C# usings in Visual Studio?
Is there a way to organize C# usings (remove and sort, in separate or together) via a shortcut in Visual Studio for one or more files of a project?

I know that this can be done via the menu for one file by selecting

Edit > IntelliSense > Organize Usings > Remove and Sort

but I want to do this much faster.
I am using Visual Studio 2013 Express for C# development (wondering how this can be done in older & other versions too though). Thank you in advance.

答: Since VS2017, it's a builtin shortcut. Simply press Ctrl + R, Ctrl + G. Credit goes to Emanuel Ve, who mentioned this first in the comments; I'm putting the advice into an answer for greater visibility.