问:
Replace accented letters in mysql column not working
Why won't the following query work on the accented characters in my column?

```<code>UPDATE people SET firstname = REPLACE(firstname,'à','a');
</code>```

It works fine when I do:

```<code>UPDATE people SET firstname = REPLACE(firstname,'e','a');
</code>```

The database character set is utf8mb4.  I've tried changing the column's collation, but that didn't work.

Edit: I added this before my query and it worked:

```<code>mysqli_set_charset($conn,"utf8mb4");
</code>```

答:
Follow this -> Accented characters in mySQL table

I think that's what you are needing to do for your DB to accept accented characters.

Body:
Why won't the following query work on the accented characters in my column?

UPDATE people SET firstname = REPLACE(firstname,'à','a');

It works fine when I do:

UPDATE people SET firstname = REPLACE(firstname,'e','a');

The database character set is utf8mb4.  I've tried changing the column's collation, but that didn't work.

Edit: I added this before my query and it worked:

mysqli_set_charset($conn,"utf8mb4");


来源: stackexchange

问:
How to call Activity class method from another Activity class
My MainActivity class is:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UserInterface_Main  UIMain = new UserInterface_Main();
    setContentView(R.layout.activity_main);
    UIMain.ExpendableListView();
}
</code>```

The another Activity class is:

```<code>public class UserInterface_Main extends Activity{

ExpandableListView exv;

public void ExpendableListView()
{

    Context context = getApplicationContext();
    exv=(ExpandableListView)findViewById(R.id.elv1);
    exv.setAdapter(new MAdapter(context));
}
</code>```

Now tell me how to call ExpendableListView() method from MainActivity class.

答:
To call an activity from another activity (not the main activity), you have to sepcify the context :</p>

```<code>                Intent i = new Intent(getApplicationContext(), secondActivity.class);
                getApplicationContext().startActivity(i);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My MainActivity class is:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    UserInterface_Main  UIMain = new UserInterface_Main();
    setContentView(R.layout.activity_main);
    UIMain.ExpendableListView();
}

The another Activity class is:

public class UserInterface_Main extends Activity{

ExpandableListView exv;

public void ExpendableListView()
{

    Context context = getApplicationContext();
    exv=(ExpandableListView)findViewById(R.id.elv1);
    exv.setAdapter(new MAdapter(context));
}

Now tell me how to call ExpendableListView() method from MainActivity class.

Body:
To call an activity from another activity (not the main activity), you have to sepcify the context :

                Intent i = new Intent(getApplicationContext(), secondActivity.class);
                getApplicationContext().startActivity(i);


问:
View lombok generated code in IntelliJ IDEA
I have the lombok plugin setup in IntelliJ and my code builds fine. I can see the lombok generated methods in the structure view. What I want is some way to actually see the source lombok generates for each of the methods. I realize I can delombok the file but I'm wondering if there is some way I can flip a switch to show or hide the lombok generated code.</p>

答: Just in case somebody ends up looking for an answer here. With lombok plugin starting with v0.8.6 it is possible.


问:
Manage Other User Accounts via Firebase auth()
According to the Manage Users section in the Firebase docs, user profiles can be modified using the methods below

```<code>var user = firebase.auth().currentUser;
user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
  // Update successful.
}, function(error) {
  // An error happened.
});
</code>```

All of the  examples in this guide seem tailored to only the currentUser that is signed in, but how can we modify other users programatically? Is there a getUser(uid) method  that I'm not seeing?

It seems this can be done with the Firebase Admin Node.js SDK, but how can we do this from the Web?

答:
The Web implementation of the Authentication API is intended to be used client-side only. To edit another user, you would have to authenticate/login as that user. Which would mean currentUser would be the user you require.

You should do this server-side using the Admin API. Which is a separate API.

Setup: https://firebase.google.com/docs/admin/setup/

Manage Users: https://firebase.google.com/docs/auth/admin/manage-users

Body:
According to the Manage Users section in the Firebase docs, user profiles can be modified using the methods below

var user = firebase.auth().currentUser;
user.updateProfile({
  displayName: "Jane Q. User",
  photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
  // Update successful.
}, function(error) {
  // An error happened.
});

All of the  examples in this guide seem tailored to only the currentUser that is signed in, but how can we modify other users programatically? Is there a getUser(uid) method  that I'm not seeing?

It seems this can be done with the Firebase Admin Node.js SDK, but how can we do this from the Web?


问:
Pass individual elements of an array to a case statement in Ruby - LCD display numbers
I am trying to pass an array of numbers to a case statement.
For example: I ask the user to input a value, for example 12. Then I split it into an array [1,2]. I then pass it to my method case statement. My case statement is to output the digital format of 1 and 2.

My Issue:
I cannot get it to print more than an input of 1 element.
How can I output both the 1 and 2 as a digital number with 1 array? Or with a users input? Is my code far off?

My Code:

```<code>puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
x = x.split('')

def digital_number(n)

digits = n

#Start case for digit input
  case digits
  when ["1"]
  puts " | "
  puts "   "
  puts " | "
  puts "   "
  puts n

  when ["2"]
  puts " - "
  puts "  |"
  puts " - "
  puts "|  "
  puts " - "

  else
  puts "That is not an available number."

  end
end

digital_number(x)
</code>```

答:
x is your array of digits. You should pass each digit to case sequentially:

```<code>number = gets.chomp
digits = number.split('')

digits.each { |digit| digital_number(digit) }
</code>```

And case the digits:

```<code>case digit
when '1'
  # ...
when '2'
  # ...
end
</code>```

Body:
I am trying to pass an array of numbers to a case statement.
For example: I ask the user to input a value, for example 12. Then I split it into an array [1,2]. I then pass it to my method case statement. My case statement is to output the digital format of 1 and 2.

My Issue:
I cannot get it to print more than an input of 1 element.
How can I output both the 1 and 2 as a digital number with 1 array? Or with a users input? Is my code far off?

My Code:

puts "Enter numbers between 0-9 up to 2 digits: "

x = gets.chomp
x = x.split('')

def digital_number(n)

digits = n

#Start case for digit input
  case digits
  when ["1"]
  puts " | "
  puts "   "
  puts " | "
  puts "   "
  puts n

  when ["2"]
  puts " - "
  puts "  |"
  puts " - "
  puts "|  "
  puts " - "

  else
  puts "That is not an available number."

  end
end

digital_number(x)

Body:
x is your array of digits. You should pass each digit to case sequentially:

number = gets.chomp
digits = number.split('')

digits.each { |digit| digital_number(digit) }

And case the digits:

case digit
when '1'
  # ...
when '2'
  # ...
end


问:
How do I get jquery to ignore ids when filtering
I am searching all ids in a content div and prepending a href. I can't predict what the child ids will be so it prepends it anyway. </p>

<p>How do I get the jquery to search the dom but ignore cetain div's id and its children? </p>

```<code>           $('*[id]').each(function() {
            var selectVariable = this;
            $(selectVariable).prepend('<a href="#" class="" id="' + $(selectVariable).attr('id') + '">*</a>');
        });

        <div id='content'>
             <!-- How do I stop the jquery from prepending  `id='I can predict'` and all its children-->
            <div id='I can predict'>
                 <div id='I can't predict'>
                 </div>

                  <div id='I can't predict'>
                  </div>
            </div>

            <div id='another piece of content'>
                  <div id='I can't predict (but needs an a link)'>
                  </div>
            </div>
        </div>
</code>```

答:
Check if div has id "I_can_predict" or if any of its parents have this id:

```<code>if (!$(selectVariable).parents('#I_can_predict').length &&
    selectVariable.id != 'I_can_predict') {
       $(selectVariable).prepend('<a href="#" class="" id="' + $(selectVariable).attr('id') + '">*</a>');
    }
</code>```

Here's a fiddle:
https://jsfiddle.net/7kmc09av/

Body:
I am searching all ids in a content div and prepending a href. I can't predict what the child ids will be so it prepends it anyway.

How do I get the jquery to search the dom but ignore cetain div's id and its children?

           $('*[id]').each(function() {
            var selectVariable = this;
            $(selectVariable).prepend('*');
        });

Body:
Check if div has id "I_can_predict" or if any of its parents have this id:

if (!$(selectVariable).parents('#I_can_predict').length &&
    selectVariable.id != 'I_can_predict') {
       $(selectVariable).prepend('<a href="#" class="" id="' + $(selectVariable).attr('id') + '">*</a>');
    }

Here's a fiddle:
https://jsfiddle.net/7kmc09av/


问:
Address Book Program
I'm doing an address book as part of a school assignment and I have it mostly figured out, but I'm stuck on one part. Here's my code first. I have an AddressBook class that contains variables and appropriate getter and setter methods to change/return the information for each person in the book. Then I have a TestAddressBook class with a method main that demonstrates how the address book works. The only thing I'm stuck on is the final requirement, where I'm asked to compare two names and see if they're equal and print the results. I have the program designed the way I want it but for some reason when I do the comparison, it doesn't print the comparison results. It just prints nothing at all. I've got to be missing something obvious. Here's the code for the classes.

AddressBook...

```<code>public class AddressBook {

private String firstName;
private String middleName;
private String lastName;
private String homeAddress;
private String homePhone;
private String cellPhone;
private String businessPhone;
private String skypeId;
private String facebookId;
private String personalWebSite;

public AddressBook(String firstName, String middleName, String lastName,
                   String homeAddress, String homePhone, String cellPhone,
                   String businessPhone, String skypeID, String facebookID,
                   String personalWebSite) {

                        this.firstName = firstName;
                        this.middleName = middleName;
                        this.lastName  = lastName;
                        this.homeAddress = homeAddress;
                        this.homePhone = homePhone;
                        this.cellPhone = cellPhone;
                        this.businessPhone = businessPhone;
                        this.skypeId = skypeID;
                        this.facebookId = facebookID;
                        this.personalWebSite = personalWebSite;
                        }

public AddressBook(String firstName) {
    this.firstName = firstName;
}

public AddressBook(String firstName, String middleName) {
    this.firstName = firstName;
    this.middleName = middleName;
}

public AddressBook(String firstName, String middleName, String lastName) {
    this.firstName = firstName;
    this.middleName = middleName;
    this.lastName = lastName;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getMiddleName() {
    return middleName;
}

public void setMiddleName(String middleName) {
    this.middleName = middleName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getHomeAddress() {
    return homeAddress;
}

public void setHomeAddress(String homeAddress) {
    this.homeAddress = homeAddress;
}

public String getHomePhone() {
    return homePhone;
}

public void setHomePhone(String homePhone) {
    this.homePhone = homePhone;
}

public String getCellPhone() {
    return cellPhone;
}

public void setCellPhone(String cellPhone) {
    this.cellPhone = cellPhone;
}

public String getBusinessPhone() {
    return businessPhone;
}

public void setBusinessPhone(String businessPhone) {
    this.businessPhone = businessPhone;
}

public String getSkypeId() {
    return skypeId;
}

public void setSkypeId(String skypeId) {
    this.skypeId = skypeId;
}

public String getFacebookId() {
    return facebookId;
}

public void setFacebookId(String facebookId) {
    this.facebookId = facebookId;
}

public String getPersonalWebSite() {
    return personalWebSite;
}

public void setPersonalWebSite(String personalWebSite) {
    this.personalWebSite = personalWebSite;
}

public static String compareNames(String name1, String name2) {
    String nameEquals;
    if ( name1.equals(name2) ) {
        nameEquals = (name1 + " and " + name2 + " are equal names.");
        return nameEquals;
    }
    else {
        nameEquals = (name1 + " and " + name2 + " are not equal names.");
        return nameEquals;
    }
}
</code>```

}

Test Class...

```<code>public class TestAddressBook {

public static void main(String[] args) {

    System.out.println("ENTRY 1");

    AddressBook entry1 = new AddressBook("Robert", "James", "Smith", "3 Fake St",
                                         "222-321-8371", "222-423-2382",
                                         "222-438-2918", "bob483", "bobfb493",
                                         "http://www.freewebhost.com/bob848");

    System.out.println( "First Name:        " + entry1.getFirstName() );
    System.out.println( "Middle Name:       " + entry1.getMiddleName() );
    System.out.println( "Last  Name:        " + entry1.getLastName() );
    System.out.println( "Address:           " + entry1.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry1.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry1.getCellPhone() );
    System.out.println( "Business Phone:    " + entry1.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry1.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry1.getFacebookId() );
    System.out.println( "Personal Website:  " + entry1.getPersonalWebSite() );

    System.out.println("\nENTRY 2");

    AddressBook entry2 = new AddressBook("Bruce", "Allan", "Carter", "56 Outtamy Way",
                                         "564-342-8372", "564-283-9832",
                                         "564-293-3489", "brucie392", "brucieface28",
                                         "http://www.freewebhost.com/carteristheman");

    System.out.println( "First Name:        " + entry2.getFirstName() );
    System.out.println( "Middle Name:       " + entry2.getMiddleName() );
    System.out.println( "Last  Name:        " + entry2.getLastName() );
    System.out.println( "Address:           " + entry2.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry2.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry2.getCellPhone() );
    System.out.println( "Business Phone:    " + entry2.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry2.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry2.getFacebookId() );
    System.out.println( "Personal Website:  " + entry2.getPersonalWebSite() );

    System.out.println("\nENTRY 3");

    AddressBook entry3 = new AddressBook("Susan", "Anne", "Peters", "6 Madeup Blvd",
                                         "736-453-1238", "736-392-2385",
                                         "736-926-2439", "anniep", "susananne",
                                         "http://www.freewebhost.com/Susanspage");

    System.out.println( "First Name:        " + entry3.getFirstName() );
    System.out.println( "Middle Name:       " + entry3.getMiddleName() );
    System.out.println( "Last  Name:        " + entry3.getLastName() );
    System.out.println( "Address:           " + entry3.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry3.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry3.getCellPhone() );
    System.out.println( "Business Phone:    " + entry3.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry3.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry3.getFacebookId() );
    System.out.println( "Personal Website:  " + entry3.getPersonalWebSite() );

    AddressBook.compareNames(entry1.getFirstName() + " " +
                             entry1.getMiddleName().charAt(0) + " " +
                             entry1.getLastName(),
                             entry2.getFirstName() + " " +
                             entry2.getMiddleName().charAt(0) + " " +
                             entry2.getLastName() );

}
</code>```

}

答:
well you have it good look at this

```<code>package teteo;

public class TestAddressBook {

    public static void main(String[] args) {

        System.out.println("ENTRY 1");

        AddressBook entry1 = new AddressBook("Robert", "James", "Smith", "3 Fake St",
                                             "222-321-8371", "222-423-2382",
                                             "222-438-2918", "bob483", "bobfb493",
                                             "http://www.freewebhost.com/bob848");

        System.out.println( "First Name:        " + entry1.getFirstName() );
        System.out.println( "Middle Name:       " + entry1.getMiddleName() );
        System.out.println( "Last  Name:        " + entry1.getLastName() );
        System.out.println( "Address:           " + entry1.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry1.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry1.getCellPhone() );
        System.out.println( "Business Phone:    " + entry1.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry1.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry1.getFacebookId() );
        System.out.println( "Personal Website:  " + entry1.getPersonalWebSite() );

        System.out.println("\nENTRY 2");

        AddressBook entry2 = new AddressBook("Robert", "James", "Smith", "56 Outtamy Way",
                                             "564-342-8372", "564-283-9832",
                                             "564-293-3489", "brucie392", "brucieface28",
                                             "http://www.freewebhost.com/carteristheman");

        System.out.println( "First Name:        " + entry2.getFirstName() );
        System.out.println( "Middle Name:       " + entry2.getMiddleName() );
        System.out.println( "Last  Name:        " + entry2.getLastName() );
        System.out.println( "Address:           " + entry2.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry2.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry2.getCellPhone() );
        System.out.println( "Business Phone:    " + entry2.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry2.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry2.getFacebookId() );
        System.out.println( "Personal Website:  " + entry2.getPersonalWebSite() );

        System.out.println("\nENTRY 3");

        AddressBook entry3 = new AddressBook("Susan", "Anne", "Peters", "6 Madeup Blvd",
                                             "736-453-1238", "736-392-2385",
                                             "736-926-2439", "anniep", "susananne",
                                             "http://www.freewebhost.com/Susanspage");

        System.out.println( "First Name:        " + entry3.getFirstName() );
        System.out.println( "Middle Name:       " + entry3.getMiddleName() );
        System.out.println( "Last  Name:        " + entry3.getLastName() );
        System.out.println( "Address:           " + entry3.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry3.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry3.getCellPhone() );
        System.out.println( "Business Phone:    " + entry3.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry3.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry3.getFacebookId() );
        System.out.println( "Personal Website:  " + entry3.getPersonalWebSite() );

      String equal =   AddressBook.compareNames(entry1.getFirstName() + " " +
                                 entry1.getMiddleName().charAt(0) + " " +
                                 entry1.getLastName(),
                                 entry2.getFirstName() + " " +
                                 entry2.getMiddleName().charAt(0) + " " +
                                 entry2.getLastName() );

System.out.println(equal);

}
}
</code>```

now it is equals, but you must know that in order to do this you should use

compareTo() or comparable look at this

https://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html

What would happen if you use a map? where it depends of a key, you will get duplicate values, i mean if you won't use that it is ok your code, but if you will use it then look an eye in there :)

Title: Address Book Program

Body:
I'm doing an address book as part of a school assignment and I have it mostly figured out, but I'm stuck on one part. Here's my code first. I have an AddressBook class that contains variables and appropriate getter and setter methods to change/return the information for each person in the book. Then I have a TestAddressBook class with a method main that demonstrates how the address book works. The only thing I'm stuck on is the final requirement, where I'm asked to compare two names and see if they're equal and print the results. I have the program designed the way I want it but for some reason when I do the comparison, it doesn't print the comparison results. It just prints nothing at all. I've got to be missing something obvious. Here's the code for the classes.

AddressBook...

public class AddressBook {

private String firstName;
private String middleName;
private String lastName;
private String homeAddress;
private String homePhone;
private String cellPhone;
private String businessPhone;
private String skypeId;
private String facebookId;
private String personalWebSite;

public AddressBook(String firstName, String middleName, String lastName,
                   String homeAddress, String homePhone, String cellPhone,
                   String businessPhone, String skypeID, String facebookID,
                   String personalWebSite) {

                        this.firstName = firstName;
                        this.middleName = middleName;
                        this.lastName  = lastName;
                        this.homeAddress = homeAddress;
                        this.homePhone = homePhone;
                        this.cellPhone = cellPhone;
                        this.businessPhone = businessPhone;
                        this.skypeId = skypeID;
                        this.facebookId = facebookID;
                        this.personalWebSite = personalWebSite;
                        }

public AddressBook(String firstName) {
    this.firstName = firstName;
}

public AddressBook(String firstName, String middleName) {
    this.firstName = firstName;
    this.middleName = middleName;
}

public AddressBook(String firstName, String middleName, String lastName) {
    this.firstName = firstName;
    this.middleName = middleName;
    this.lastName = lastName;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getMiddleName() {
    return middleName;
}

public void setMiddleName(String middleName) {
    this.middleName = middleName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getHomeAddress() {
    return homeAddress;
}

public void setHomeAddress(String homeAddress) {
    this.homeAddress = homeAddress;
}

public String getHomePhone() {
    return homePhone;
}

public void setHomePhone(String homePhone) {
    this.homePhone = homePhone;
}

public String getCellPhone() {
    return cellPhone;
}

public void setCellPhone(String cellPhone) {
    this.cellPhone = cellPhone;
}

public String getBusinessPhone() {
    return businessPhone;
}

public void setBusinessPhone(String businessPhone) {
    this.businessPhone = businessPhone;
}

public String getSkypeId() {
    return skypeId;
}

public void setSkypeId(String skypeId) {
    this.skypeId = skypeId;
}

public String getFacebookId() {
    return facebookId;
}

public void setFacebookId(String facebookId) {
    this.facebookId = facebookId;
}

public String getPersonalWebSite() {
    return personalWebSite;
}

public void setPersonalWebSite(String personalWebSite) {
    this.personalWebSite = personalWebSite;
}

public static String compareNames(String name1, String name2) {
    String nameEquals;
    if ( name1.equals(name2) ) {
        nameEquals = (name1 + " and " + name2 + " are equal names.");
        return nameEquals;
    }
    else {
        nameEquals = (name1 + " and " + name2 + " are not equal names.");
        return nameEquals;
    }
}

}

Test Class...

public class TestAddressBook {

public static void main(String[] args) {

    System.out.println("ENTRY 1");

    AddressBook entry1 = new AddressBook("Robert", "James", "Smith", "3 Fake St",
                                         "222-321-8371", "222-423-2382",
                                         "222-438-2918", "bob483", "bobfb493",
                                         "http://www.freewebhost.com/bob848");

    System.out.println( "First Name:        " + entry1.getFirstName() );
    System.out.println( "Middle Name:       " + entry1.getMiddleName() );
    System.out.println( "Last  Name:        " + entry1.getLastName() );
    System.out.println( "Address:           " + entry1.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry1.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry1.getCellPhone() );
    System.out.println( "Business Phone:    " + entry1.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry1.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry1.getFacebookId() );
    System.out.println( "Personal Website:  " + entry1.getPersonalWebSite() );

    System.out.println("\nENTRY 2");

    AddressBook entry2 = new AddressBook("Bruce", "Allan", "Carter", "56 Outtamy Way",
                                         "564-342-8372", "564-283-9832",
                                         "564-293-3489", "brucie392", "brucieface28",
                                         "http://www.freewebhost.com/carteristheman");

    System.out.println( "First Name:        " + entry2.getFirstName() );
    System.out.println( "Middle Name:       " + entry2.getMiddleName() );
    System.out.println( "Last  Name:        " + entry2.getLastName() );
    System.out.println( "Address:           " + entry2.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry2.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry2.getCellPhone() );
    System.out.println( "Business Phone:    " + entry2.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry2.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry2.getFacebookId() );
    System.out.println( "Personal Website:  " + entry2.getPersonalWebSite() );

    System.out.println("\nENTRY 3");

    AddressBook entry3 = new AddressBook("Susan", "Anne", "Peters", "6 Madeup Blvd",
                                         "736-453-1238", "736-392-2385",
                                         "736-926-2439", "anniep", "susananne",
                                         "http://www.freewebhost.com/Susanspage");

    System.out.println( "First Name:        " + entry3.getFirstName() );
    System.out.println( "Middle Name:       " + entry3.getMiddleName() );
    System.out.println( "Last  Name:        " + entry3.getLastName() );
    System.out.println( "Address:           " + entry3.getHomeAddress() );
    System.out.println( "Home Phone:        " + entry3.getHomePhone() );
    System.out.println( "Cell Phone:        " + entry3.getCellPhone() );
    System.out.println( "Business Phone:    " + entry3.getBusinessPhone() );
    System.out.println( "Skype ID:          " + entry3.getSkypeId() );
    System.out.println( "Facebook ID:       " + entry3.getFacebookId() );
    System.out.println( "Personal Website:  " + entry3.getPersonalWebSite() );

    AddressBook.compareNames(entry1.getFirstName() + " " +
                             entry1.getMiddleName().charAt(0) + " " +
                             entry1.getLastName(),
                             entry2.getFirstName() + " " +
                             entry2.getMiddleName().charAt(0) + " " +
                             entry2.getLastName() );

}

}

Body:
well you have it good look at this

package teteo;

public class TestAddressBook {

    public static void main(String[] args) {

        System.out.println("ENTRY 1");

        AddressBook entry1 = new AddressBook("Robert", "James", "Smith", "3 Fake St",
                                             "222-321-8371", "222-423-2382",
                                             "222-438-2918", "bob483", "bobfb493",
                                             "http://www.freewebhost.com/bob848");

        System.out.println( "First Name:        " + entry1.getFirstName() );
        System.out.println( "Middle Name:       " + entry1.getMiddleName() );
        System.out.println( "Last  Name:        " + entry1.getLastName() );
        System.out.println( "Address:           " + entry1.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry1.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry1.getCellPhone() );
        System.out.println( "Business Phone:    " + entry1.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry1.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry1.getFacebookId() );
        System.out.println( "Personal Website:  " + entry1.getPersonalWebSite() );

        System.out.println("\nENTRY 2");

        AddressBook entry2 = new AddressBook("Robert", "James", "Smith", "56 Outtamy Way",
                                             "564-342-8372", "564-283-9832",
                                             "564-293-3489", "brucie392", "brucieface28",
                                             "http://www.freewebhost.com/carteristheman");

        System.out.println( "First Name:        " + entry2.getFirstName() );
        System.out.println( "Middle Name:       " + entry2.getMiddleName() );
        System.out.println( "Last  Name:        " + entry2.getLastName() );
        System.out.println( "Address:           " + entry2.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry2.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry2.getCellPhone() );
        System.out.println( "Business Phone:    " + entry2.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry2.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry2.getFacebookId() );
        System.out.println( "Personal Website:  " + entry2.getPersonalWebSite() );

        System.out.println("\nENTRY 3");

        AddressBook entry3 = new AddressBook("Susan", "Anne", "Peters", "6 Madeup Blvd",
                                             "736-453-1238", "736-392-2385",
                                             "736-926-2439", "anniep", "susananne",
                                             "http://www.freewebhost.com/Susanspage");

        System.out.println( "First Name:        " + entry3.getFirstName() );
        System.out.println( "Middle Name:       " + entry3.getMiddleName() );
        System.out.println( "Last  Name:        " + entry3.getLastName() );
        System.out.println( "Address:           " + entry3.getHomeAddress() );
        System.out.println( "Home Phone:        " + entry3.getHomePhone() );
        System.out.println( "Cell Phone:        " + entry3.getCellPhone() );
        System.out.println( "Business Phone:    " + entry3.getBusinessPhone() );
        System.out.println( "Skype ID:          " + entry3.getSkypeId() );
        System.out.println( "Facebook ID:       " + entry3.getFacebookId() );
        System.out.println( "Personal Website:  " + entry3.getPersonalWebSite() );

      String equal =   AddressBook.compareNames(entry1.getFirstName() + " " +
                                 entry1.getMiddleName().charAt(0) + " " +
                                 entry1.getLastName(),
                                 entry2.getFirstName() + " " +
                                 entry2.getMiddleName().charAt(0) + " " +
                                 entry2.getLastName() );

System.out.println(equal);

}
}

now it is equals, but you must know that in order to do this you should use

compareTo() or comparable look at this

https://www.javacodegeeks.com/2013/03/difference-between-comparator-and-comparable-in-java.html

What would happen if you use a map? where it depends of a key, you will get duplicate values, i mean if you won't use that it is ok your code, but if you will use it then look an eye in there :)


问:
Multiple user controls and clientid asp.net JS
I am following the post:

http://mosesofegypt.net/post/GridView-with-Select-All-CheckBox-using-JQuery.aspx

to create a checkbox column in asp.net gridview with select/deselect all functionality.
In my case, the gridview and the javascript (JQuery) code lies inside a dynamically load usercontrol, and there are more than one instances of that user control. The select/deselect functionality works only in the last usercontrol created on page.
In other words, the gvProducts.ClientId in the js script knows only about the last gridview.
Any ideas how can I get reference to the ClientIds of gridview inside other usercontrol (i.e. other than the last) ?
Any help would be most appreciated.

EDIT :  This question is essentially the same as asked in this post : Multiple user control instances and ClientID in JS
but there are no helping answers for it.

Thanks,
Ali

答:
You could add a CssClass to the GridView and base your jQuery selector off of that.

Script:

```<code><script type="text/javascript">
    $(function () {
        $(".t th input:checkbox").click(function () {
            var $checkbox = $(this).closest('table').find(':checkbox:not(:first)');
            $checkbox.attr('checked', $(this).attr('checked'));
        });
    });
</script>
</code>```

2 tables with the same class name:

```<code> <table class="t">
    <tr>
        <th align="left" scope="col">Category</th>
        <th align="left" scope="col">Product</th>
        <th align="right" scope="col">Unit Price</th>
        <th align="left" scope="col">Supplier</th>
        <th scope="col">
            <input type="checkbox" name="select-all" />
        </th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>
<br /><br /><br />
<table class="t">
    <tr>
        <th align="left" scope="col">Category</th>
        <th align="left" scope="col">Product</th>
        <th align="right" scope="col">Unit Price</th>
        <th align="left" scope="col">Supplier</th>
        <th scope="col">
            <input type="checkbox" name="select-all" />
        </th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could add a CssClass to the GridView and base your jQuery selector off of that.

Script:

<script type="text/javascript">
    $(function () {
        $(".t th input:checkbox").click(function () {
            var $checkbox = $(this).closest('table').find(':checkbox:not(:first)');
            $checkbox.attr('checked', $(this).attr('checked'));
        });
    });
</script>

2 tables with the same class name:

 <table class="t">
    <tr>
        <th align="left" scope="col">Category</th>
        <th align="left" scope="col">Product</th>
        <th align="right" scope="col">Unit Price</th>
        <th align="left" scope="col">Supplier</th>
        <th scope="col">
            <input type="checkbox" name="select-all" />
        </th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>
<br /><br /><br />
<table class="t">
    <tr>
        <th align="left" scope="col">Category</th>
        <th align="left" scope="col">Product</th>
        <th align="right" scope="col">Unit Price</th>
        <th align="left" scope="col">Supplier</th>
        <th scope="col">
            <input type="checkbox" name="select-all" />
        </th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>


问:
Brainscript example with Dynamic Axes
I am building an LSTM that handles several parallel sequences, and I'm struggling to find any brainscript example that handles dynamic axes.

In my specific case, an example consists of a binary label and N sequences, where each sequence i has a fixed length (but may differ for j<>i).
For example, sequence 1 is always length 1024, sequence 2 is length 4096, sequence 3 is length 1024.
I am expressing these sequences by packing them in parallel in the CNTK text format:

```<code>0 |Label 1 |S1 0 |S2 1 |S3 0
0 |S1 1 |S2 1 |S3 1
... another 1021 rows
0 |S2 0
0 |S2 1
... another 3070 rows with only S2 defined
1 |Label 0 |S1 0 |S2 1 |S3 0
1 |S1 1 |S2 1 |S3 0
... another 1021 rows
1 |S2 1
1 |S2 0
... another 3070 rows with only S2 defined
2 |Label ...
</code>```

and so on.  I feel as though I've constructed examples like this in the past but I've been unable to track down any sample configs, or even any BS examples that specify dynamic axes.  Is this approach doable?

答:
The G2P example (...\Examples\SequenceToSequence\CMUDict\BrainScript\G2P.cntk) uses multiple dynamic axes. This is a snippet from this file:

```<code># inputs and axes must be defined on top-scope level in order to get a clean node name from BrainScript.
inputAxis = DynamicAxis()
rawInput  = Input (inputVocabDim, dynamicAxis=inputAxis, tag='feature')
rawLabels = Input (labelVocabDim, tag='label')
</code>```

However, since in your case the axes all have the same length for each input, you may also want to consider to just put them into fixed-sized tensors. E.g instead of 1024 values, you would just have a single value of dimension 1024.

The choice depends on what you want to do with the sequences. Are you planning to run a recurrence over them? If so, you want to keep them as dynamic sequences. If they are just vectors that you plan to process with, say, big matrix products, you would rather want to keep them as static axes.

Title: Brainscript example with Dynamic Axes

Body:
I am building an LSTM that handles several parallel sequences, and I'm struggling to find any brainscript example that handles dynamic axes.

In my specific case, an example consists of a binary label and N sequences, where each sequence i has a fixed length (but may differ for j<>i).
For example, sequence 1 is always length 1024, sequence 2 is length 4096, sequence 3 is length 1024.
I am expressing these sequences by packing them in parallel in the CNTK text format:

0 |Label 1 |S1 0 |S2 1 |S3 0
0 |S1 1 |S2 1 |S3 1
... another 1021 rows
0 |S2 0
0 |S2 1
... another 3070 rows with only S2 defined
1 |Label 0 |S1 0 |S2 1 |S3 0
1 |S1 1 |S2 1 |S3 0
... another 1021 rows
1 |S2 1
1 |S2 0
... another 3070 rows with only S2 defined
2 |Label ...

and so on.  I feel as though I've constructed examples like this in the past but I've been unable to track down any sample configs, or even any BS examples that specify dynamic axes.  Is this approach doable?

Body:
The G2P example (...\Examples\SequenceToSequence\CMUDict\BrainScript\G2P.cntk) uses multiple dynamic axes. This is a snippet from this file:

# inputs and axes must be defined on top-scope level in order to get a clean node name from BrainScript.
inputAxis = DynamicAxis()
rawInput  = Input (inputVocabDim, dynamicAxis=inputAxis, tag='feature')
rawLabels = Input (labelVocabDim, tag='label')

However, since in your case the axes all have the same length for each input, you may also want to consider to just put them into fixed-sized tensors. E.g instead of 1024 values, you would just have a single value of dimension 1024.

The choice depends on what you want to do with the sequences. Are you planning to run a recurrence over them? If so, you want to keep them as dynamic sequences. If they are just vectors that you plan to process with, say, big matrix products, you would rather want to keep them as static axes.


问:
Server Push not working on Repeat View
We're using the Link header to preload our font files and it's working great when the browser cache is empty. However on "Repeat View" the font files are loaded twice and Chrome shows a warning message. How can we fix that?

The Link header and the CSS files both point to the full relative URL:

```<code>/app/themes/foobar/assets/fonts/Montserrat-Light.woff
</code>```

First View:

Repeat View:

答:
The problem was a missing crossorigin, so instead of:

Link: </path/to/font.woff2>; rel=preload; as=font

Use:

Link: </path/to/font.woff2>; rel=preload; as=font; crossorigin

Title: Server Push not working on Repeat View

Body:
We're using the Link header to preload our font files and it's working great when the browser cache is empty. However on "Repeat View" the font files are loaded twice and Chrome shows a warning message. How can we fix that?

The Link header and the CSS files both point to the full relative URL:

/app/themes/foobar/assets/fonts/Montserrat-Light.woff

First View:

Repeat View:


问:
Python asyncio, possible to await / yield entire myFunction()
I've written a library of objects, many which make HTTP / IO calls. I've been looking at moving over to asyncio due to the mounting overheads, but I don't want to rewrite the underlying code.

I've been hoping to wrap asyncio around my code in order to perform functions asynchronously without replacing all of my deep / low level code with await / yield.

I began by attempting the following:

```<code>async def my_function1(some_object, some_params):
      #Lots of existing code which uses existing objects
      #No await statements
      return output_data

async def my_function2():
      #Does more stuff

while True:
    loop = asyncio.get_event_loop()
    tasks = my_function(some_object, some_params), my_function2()
    output_data = loop.run_until_complete(asyncio.gather(*tasks))
    print(output_data)
</code>```

I quickly realised that while this code runs, nothing actually happens asynchronously, the functions complete synchronously. I'm very new to asynchronous programming, but I think this is because neither of my functions are using the keyword await or yield and thus these functions are not cooroutines, and do not yield, thus do not provide an opportunity to move to a different cooroutine. Please correct me if I am wrong.

My question is, is it possible to wrap complex functions (where deep within they make HTTP / IO calls ) in an asyncio await keyword, e.g.

```<code>async def my_function():
    print("Welcome to my function")
    data = await bigSlowFunction()
</code>```

UPDATE - Following Karlson's Answer

Following and thanks to Karlsons accepted answer, I used the following code which works nicely:

```<code>from concurrent.futures import ThreadPoolExecutor
import time

#Some vars
a_var_1 = 0
a_var_2 = 10

pool = ThreadPoolExecutor(3)

future = pool.submit(my_big_function, object, a_var_1, a_var_2)
while not future.done() :
    print("Waiting for future...")
    time.sleep(0.01)
print("Future done")
print(future.result())
</code>```

This works really nicely, and the future.done() / sleep loop gives you an idea of how many CPU cycles you get to use by going async.

答:
The short answer is, you can't have the benefits of asyncio without explicitly marking the points in your code where control may be passed back to the event loop. This is done by turning your IO heavy functions into coroutines, just like you assumed.

Without changing existing code you might achieve your goal with greenlets (have a look at eventlet or gevent).

Another possibility would be to make use of Python's Future implementation wrapping and passing calls to your already written functions to some ThreadPoolExecutor and yield the resulting Future. Be aware, that this comes with all the caveats of multi-threaded programming, though.

Something along the lines of

```<code>from concurrent.futures import ThreadPoolExecutor

from thinair import big_slow_function

executor = ThreadPoolExecutor(max_workers=5)

async def big_slow_coroutine():
    await executor.submit(big_slow_function)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've written a library of objects, many which make HTTP / IO calls. I've been looking at moving over to asyncio due to the mounting overheads, but I don't want to rewrite the underlying code.

I've been hoping to wrap asyncio around my code in order to perform functions asynchronously without replacing all of my deep / low level code with await / yield.

I began by attempting the following:

async def my_function1(some_object, some_params):
      #Lots of existing code which uses existing objects
      #No await statements
      return output_data

async def my_function2():
      #Does more stuff

while True:
    loop = asyncio.get_event_loop()
    tasks = my_function(some_object, some_params), my_function2()
    output_data = loop.run_until_complete(asyncio.gather(*tasks))
    print(output_data)

I quickly realised that while this code runs, nothing actually happens asynchronously, the functions complete synchronously. I'm very new to asynchronous programming, but I think this is because neither of my functions are using the keyword await or yield and thus these functions are not cooroutines, and do not yield, thus do not provide an opportunity to move to a different cooroutine. Please correct me if I am wrong.

My question is, is it possible to wrap complex functions (where deep within they make HTTP / IO calls ) in an asyncio await keyword, e.g.

async def my_function():
    print("Welcome to my function")
    data = await bigSlowFunction()

UPDATE - Following Karlson's Answer

Following and thanks to Karlsons accepted answer, I used the following code which works nicely:

from concurrent.futures import ThreadPoolExecutor
import time

#Some vars
a_var_1 = 0
a_var_2 = 10

pool = ThreadPoolExecutor(3)

future = pool.submit(my_big_function, object, a_var_1, a_var_2)
while not future.done() :
    print("Waiting for future...")
    time.sleep(0.01)
print("Future done")
print(future.result())

This works really nicely, and the future.done() / sleep loop gives you an idea of how many CPU cycles you get to use by going async.

Body:
The short answer is, you can't have the benefits of asyncio without explicitly marking the points in your code where control may be passed back to the event loop. This is done by turning your IO heavy functions into coroutines, just like you assumed.

Without changing existing code you might achieve your goal with greenlets (have a look at eventlet or gevent).

Another possibility would be to make use of Python's Future implementation wrapping and passing calls to your already written functions to some ThreadPoolExecutor and yield the resulting Future. Be aware, that this comes with all the caveats of multi-threaded programming, though.

Something along the lines of

from concurrent.futures import ThreadPoolExecutor

from thinair import big_slow_function

executor = ThreadPoolExecutor(max_workers=5)

async def big_slow_coroutine():
    await executor.submit(big_slow_function)


问:
Query MySql database in Docker
I have a docker container with mariadb, and have created a database my_db in it (through an external script in a different container). How can I run SQL queries on my_db now from the command line? I just want to do

select * from my_table

from the terminal that is running the container.

答:
If you have the commandline tool installed in the app container,

```<code>mysql -h 192.168.1.7 -u admin -pxyz -P 10202
</code>```

This allows for the docker instance to be on another machine (192...) and with a special port (-P ...), etc.  (I have multiple docker containers; that one is for MariaDB 10.2.2.)

Title: Query MySql database in Docker

Body:
If you have the commandline tool installed in the app container,

mysql -h 192.168.1.7 -u admin -pxyz -P 10202

This allows for the docker instance to be on another machine (192...) and with a special port (-P ...), etc.  (I have multiple docker containers; that one is for MariaDB 10.2.2.)


问:
How do you test code without uploading to the web server?
(This is a high level software development question)

I'm running a web app.  In the past, to test new features, I have uploaded under a subdirectory such as test/.  This generally broke all the URLs, so I'd have to redo the URLs in the test code. Then I'd have to rename all the URLs when I pushed it to the main site.  I'm sure there's a better way but don't know what people usually do.

Do you install a web server on your laptop?  I could always buy a cheap computer and run it as a test web server, I suppose.

Eventually I'd like to have a version control system with a friend also coding, so maybe we'd both need to install Apache and MySQL on our laptops?  That way we don't interfere with each other when testing new code.

答:
I test locally, running a local We Server and/or App Server seems pretty normal to me.

You may well also have "staging" servers where things are opened up to larger communities.

With some care you can also make your links relative, so that you can parallel-run old and new versions on the same server, deploying with different Context Roots. For large-scale systems this tends to be very useful: you can cut over different communities of users to the new system, giving a gradual roll-out.

I do agree that Unit testing without a server is also important, but sometime before you let the users onto a new version you do really need to run on a Server.

OwnerDisplayName: anon


问:
Htaccess and url for multilingual site
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

```<code>- Same filename
site.com/fr/login
site.com/en/login
</code>```

OR

```<code>- Different filename
site.com/fr/connexion
site.com/en/login
</code>```

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)

答:
i usally show in mostly website they give url like site.com/en and site.com/fr as you mention but it upon you how you want to show website to user. i prefer make default site.com/en and give user option to select his language.

if you still confuse then refer below link it will usefull.

See Refferal Link Here

Title: Htaccess and url for multilingual site

Body:
I'm ready to use the subdirectory format for my multilingual website.
My first question is:
For SEO, have I to translate the page name in the url or it is useless?
Example:

- Same filename
site.com/fr/login
site.com/en/login

OR

- Different filename
site.com/fr/connexion
site.com/en/login

Then, when user is on site.com: Should I redirect him to site.com/en and site.com/fr depending user's IP? Or have I to set a default local, and have my url like site.com/page and site.com/fr/page

Finally, what is the best way to get the local from user's current URL?
Parsing url to get /fr or /en, or add a GET parameter in url with lang=fr (hidden with htaccess)

Thanks :)


问:
My nested for loop number pattern doesn't out put the correct pattern
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

```<code>Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

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

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

```<code>import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }
</code>```

This is the Output I'm Getting

```<code>run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6
</code>```

答:
Here's the modified code for your patterns.

```<code>public class Patterns {
    public static void main(String[] args) {

        for (int i = 0; i < 6; i++) {

            for (int j = 0; j < (5 - i) * 2; j++) {
                System.out.print(" ");
            }

            for (int j = i + 1; j >= 1; j--) {
                System.out.print(j + " ");
            }

            System.out.println();
        }

        System.out.println();

        for (int i = 0; i < 6; i++) {

            for (int j = 0; j < i * 2; j++) {
                System.out.print(" ");
            }

            for (int j = 1; j <= 6 - i; j++) {
                System.out.print(j + " ");
            }

            System.out.println();
        }

    }
}
</code>```

Output

```<code>          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

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

Update: fixed bug for spaces

Working=> Consider the first half of the pattern

```<code>          1 line 0: 10 spaces  = (5 - 0) * 2 spaces
        2 1 line 1: 8  spaces  = (5 - 1) * 2 spaces
      3 2 1 line 2: 6  spaces  = (5 - 2) * 2 spaces
    4 3 2 1 line 3: 4  spaces  = (5 - 3) * 2 spaces
  5 4 3 2 1 line 4: 2  spaces  = (5 - 4) * 2 spaces
6 5 4 3 2 1 line 5: 0  spaces  = (5 - 5) * 2 spaces
</code>```

Consider the second half of the pattern

```<code>1 2 3 4 5 6 line 0: 0 spaces  = 0 * 2 spaces
  1 2 3 4 5 line 1: 2 spaces  = 1 * 2 spaces
    1 2 3 4 line 2: 4 spaces  = 2 * 2 spaces
      1 2 3 line 3: 6 spaces  = 3 * 2 spaces
        1 2 line 4: 8 spaces  = 4 * 2 spaces
          1 line 5: 10 spaces = 5 * 2 spaces
</code>```

Body:
I'm trying to print out this pattern but I'm having trouble arranging the numbers and spacing them out to achieve the expected out put.

Expected Output:
          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

Here is my Code. I don't know how to space the numbers and put the correct numbers in the order that the out put has specified.

import java.util.Scanner;

public class patterns{
 public static void main(String[] args)
{
    Scanner sc = new Scanner(System.in);

   for (int i = 6; i >= 1; i--)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

                System.out.println();

   for (int i = 1; i <= 6; i++)
    {

        for (int j = 1; j < i; j++)
        {
            System.out.print(" ");
        }

        for (int j = i; j <= 6; j++)
        {
            System.out.print(j);
        }

        System.out.println();
    }

   }
 }

This is the Output I'm Getting

run:
     6
    56
   456
  3456
 23456
123456

123456
 23456
  3456
   456
    56
     6

Body:
Here's the modified code for your patterns.

public class Patterns {
    public static void main(String[] args) {

        for (int i = 0; i < 6; i++) {

            for (int j = 0; j < (5 - i) * 2; j++) {
                System.out.print(" ");
            }

            for (int j = i + 1; j >= 1; j--) {
                System.out.print(j + " ");
            }

            System.out.println();
        }

        System.out.println();

        for (int i = 0; i < 6; i++) {

            for (int j = 0; j < i * 2; j++) {
                System.out.print(" ");
            }

            for (int j = 1; j <= 6 - i; j++) {
                System.out.print(j + " ");
            }

            System.out.println();
        }

    }
}

Output

          1
        2 1
      3 2 1
    4 3 2 1
  5 4 3 2 1
6 5 4 3 2 1

1 2 3 4 5 6
  1 2 3 4 5
    1 2 3 4
      1 2 3
        1 2
          1

Update: fixed bug for spaces

Working=> Consider the first half of the pattern

          1 line 0: 10 spaces  = (5 - 0) * 2 spaces
        2 1 line 1: 8  spaces  = (5 - 1) * 2 spaces
      3 2 1 line 2: 6  spaces  = (5 - 2) * 2 spaces
    4 3 2 1 line 3: 4  spaces  = (5 - 3) * 2 spaces
  5 4 3 2 1 line 4: 2  spaces  = (5 - 4) * 2 spaces
6 5 4 3 2 1 line 5: 0  spaces  = (5 - 5) * 2 spaces

Consider the second half of the pattern

1 2 3 4 5 6 line 0: 0 spaces  = 0 * 2 spaces
  1 2 3 4 5 line 1: 2 spaces  = 1 * 2 spaces
    1 2 3 4 line 2: 4 spaces  = 2 * 2 spaces
      1 2 3 line 3: 6 spaces  = 3 * 2 spaces
        1 2 line 4: 8 spaces  = 4 * 2 spaces
          1 line 5: 10 spaces = 5 * 2 spaces


问:
How to remove lines contained in file 1 from file 2 if in file 2 they are prefixed?
I have the following situation:

source.txt

```<code>ID1:email1@domain1.com
ID2:email2@domain2.com
ID3:email3@domain3.com
...
</code>```

IDs are numeric strings, e.g. 1234, 23412, 897... (one or more digits).

exclude.txt

```<code>emailX@domainX.com
emailY@domainY.com
emailZ@domainZ.com
...
</code>```

i.e. only emails, no IDs.

I want to remove all lines from source.txt which contain emails listed in exclude.txt, preserving the ID:email pairs for the lines which are not removed.

How can I do that with linux command line tools (or simple bash script if needed)?

答:
You can do it easily with awk:

```<code>awk -F":" 'NR==FNR{a[$1];next}(!($2 in a))' exclude.txt source.txt
</code>```

Alternative with grep:

```<code>grep -v -F -f exclude.txt source.txt
</code>```

Use grep with care, since grep does a regex matching. You might need to add also -w option to grep (word matching)

Body:
I have the following situation:

source.txt

ID1:email1@domain1.com
ID2:email2@domain2.com
ID3:email3@domain3.com
...

IDs are numeric strings, e.g. 1234, 23412, 897... (one or more digits).

exclude.txt

emailX@domainX.com
emailY@domainY.com
emailZ@domainZ.com
...

i.e. only emails, no IDs.

I want to remove all lines from source.txt which contain emails listed in exclude.txt, preserving the ID:email pairs for the lines which are not removed.

How can I do that with linux command line tools (or simple bash script if needed)?

Body:
You can do it easily with awk:

awk -F":" 'NR==FNR{a[$1];next}(!($2 in a))' exclude.txt source.txt

Alternative with grep:

grep -v -F -f exclude.txt source.txt

Use grep with care, since grep does a regex matching. You might need to add also -w option to grep (word matching)


问:
How to change content on hover
I've been playing around with this, and I thought it would be pretty simple. What I'm trying to do is hover over the 'NEW' label. Once in its hover state, change the content from 'NEW' to 'ADD' using only CSS.

body{
    font-family: Arial, Helvetica, sans-serif;
}
.item{
    width: 30px;
}
a{
    text-decoration:none;
}
.label {
    padding: 1px 3px 2px;
    font-size: 9.75px;
    font-weight: bold;
    color: #ffffff;
    text-transform: uppercase;
    white-space: nowrap;
    background-color: #bfbfbf;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    text-decoration: none;
}
.label.success {
    background-color: #46a546;
}

.item a p.new-label span{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span{
  display: none;
}
.item:hover a p.new-label{
  content: 'ADD';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="item">

         <p class="label success new-label"><span class="align">New</span></p>

</div></code>```

Here's a JSFiddle to show you what I'm working with.

答:
.label:after{
    content:'ADD';
}
.label:hover:after{
    content:'NEW';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="label"></span></code>```

Title: How to change content on hover

Body:
I've been playing around with this, and I thought it would be pretty simple. What I'm trying to do is hover over the 'NEW' label. Once in its hover state, change the content from 'NEW' to 'ADD' using only CSS.

body{
    font-family: Arial, Helvetica, sans-serif;
}
.item{
    width: 30px;
}
a{
    text-decoration:none;
}
.label {
    padding: 1px 3px 2px;
    font-size: 9.75px;
    font-weight: bold;
    color: #ffffff;
    text-transform: uppercase;
    white-space: nowrap;
    background-color: #bfbfbf;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    text-decoration: none;
}
.label.success {
    background-color: #46a546;
}

.item a p.new-label span{
  position: relative;
  content: 'NEW'
}
.item:hover a p.new-label span{
  display: none;
}
.item:hover a p.new-label{
  content: 'ADD';
}

New

Here's a JSFiddle to show you what I'm working with.

Body:
.label:after{
    content:'ADD';
}
.label:hover:after{
    content:'NEW';
}

<span class="label"></span>


问:
Transitioning opacity on an element with css drop-shadow filter
I have an svg element with a drop-shadow css filter blur applied to it like so:

```<code>.my-svg {
  opacity: 0;
  filter: drop-shadow( 0px 0px 10px rgba(255, 0, 0, 1) );
}

.active & {
  transision: opacity 1s;
  opacity: 1;
}
</code>```

When the containing div has the active class applied to it, the element fades in as expected, but when the transition time is over, the blur cuts back to be less... blurry. It's like the spread is increased during the transition. If I remove the transition it switches to what the element would look like in its final state after the transition animation completed.

What is it about transitioning opacity on an element with blur that causes the blur to be so much more pronounced until the animation is finished? It's not so bad on chrome but it's more pronounced on safari. It's really jarring. I've also tried keyframe animation for the opacity but the same thing still happens. It also doesn't affect text-shadow, only filter: drop-shadow.

答:
Ok so I figured out how to get it to do what I want but I don't know why it works. Seems to work on chrome, ff and safari.

Using a keyframe animation AND a transition works. It doesn't work if you only use keyframes, and it doesn't work if you only use transitions. Here's the code that works:

```<code>.my-svg {
  opacity: 0;
  filter: drop-shadow( 0px 0px 10px rgba(255, 0, 0, 1) );
}

.active & {
  animation: fadein 1s;
  animation-fill-mode: forwards;
  transition: opacity 1s;
  opacity: 1;
}

@keyframes fadein {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}
</code>```

I'm not going accept this answer because I think it still needs an explanation.

Body:
I have an svg element with a drop-shadow css filter blur applied to it like so:

.my-svg {
  opacity: 0;
  filter: drop-shadow( 0px 0px 10px rgba(255, 0, 0, 1) );
}

.active & {
  transision: opacity 1s;
  opacity: 1;
}

When the containing div has the active class applied to it, the element fades in as expected, but when the transition time is over, the blur cuts back to be less... blurry. It's like the spread is increased during the transition. If I remove the transition it switches to what the element would look like in its final state after the transition animation completed.

What is it about transitioning opacity on an element with blur that causes the blur to be so much more pronounced until the animation is finished? It's not so bad on chrome but it's more pronounced on safari. It's really jarring. I've also tried keyframe animation for the opacity but the same thing still happens. It also doesn't affect text-shadow, only filter: drop-shadow.

Body:
Ok so I figured out how to get it to do what I want but I don't know why it works. Seems to work on chrome, ff and safari.

Using a keyframe animation AND a transition works. It doesn't work if you only use keyframes, and it doesn't work if you only use transitions. Here's the code that works:

.my-svg {
  opacity: 0;
  filter: drop-shadow( 0px 0px 10px rgba(255, 0, 0, 1) );
}

.active & {
  animation: fadein 1s;
  animation-fill-mode: forwards;
  transition: opacity 1s;
  opacity: 1;
}

@keyframes fadein {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

I'm not going accept this answer because I think it still needs an explanation.


答:
You can use .not($('#I_can_predict, #I_can_predict *')) to exclude the part you want out:

$('*[id]').not($('#I_can_predict, #I_can_predict *')).each(function() {
    var selectVariable = this;
    $(selectVariable).prepend('*');
});```
<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='content'>
    content
     <!-- How do I stop the jquery from prepending  `id='I can predict'` and all its children-->
    <div id='I_can_predict'>I can predict
         <div id="I_can't_predict">I can't predict1
         </div>

          <div id="I_can't_predict2">I can't predict2
          </div>
    </div>

    <div id='another_piece_of_content'>another piece of content
          <div id="I_can't_predict_(but_needs_an_a_link)">I_can't_predict_(but_needs_an_a_link)
          </div>
    </div>
</div></code>```

Title: How do I get jquery to ignore ids when filtering

Body:
I am searching all ids in a content div and prepending a href. I can't predict what the child ids will be so it prepends it anyway.

How do I get the jquery to search the dom but ignore cetain div's id and its children?

           $('*[id]').each(function() {
            var selectVariable = this;
            $(selectVariable).prepend('*');
        });

Body:
You can use .not($('#I_can_predict, #I_can_predict *')) to exclude the part you want out:

$('*[id]').not($('#I_can_predict, #I_can_predict *')).each(function() {
    var selectVariable = this;
    $(selectVariable).prepend('<a href="#" class="" id="'
                              + $(selectVariable).attr('id') + '">*</a>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='content'>
    content
     <!-- How do I stop the jquery from prepending  `id='I can predict'` and all its children-->
    <div id='I_can_predict'>I can predict
         <div id="I_can't_predict">I can't predict1
         </div>

          <div id="I_can't_predict2">I can't predict2
          </div>
    </div>

    <div id='another_piece_of_content'>another piece of content
          <div id="I_can't_predict_(but_needs_an_a_link)">I_can't_predict_(but_needs_an_a_link)
          </div>
    </div>
</div>


问:
Why does Windows Forms databinding want to set my nested boolean databound property when I raise a notification event on the parent object?
OK, so here is some context for my problem, written as pseudo-C# code (feel free to point out any mistake): (You can jump directly to the stacktrace and read the context later.)

```<code>public class SomeForm {
    private _model = new ViewModelClass
    public void new() {
        // Normal Winforms init omitted
        ViewModelClassBindingSource.DataSource = _model;
        SomeControl1.SetModel(_model);
    }
}
public class SomeControl {
    private _model = new ViewModelClass

    internal void SetModel(ViewModelClass model) {
        _model = model;
        ViewModelClassBindingSource.DataSource = model;
        ViewModelClassBindingSource.ResetBindings(true);
    }
}

public class ComplexObject : IPropertyChanging, IPropertyChanged {
    public property bool BoolProp {get; set;}
}

public class ViewModelClass : IPropertyChanged {
    property IList<ComplexObject> ComplexObjects {get;}

    property ComplexObject SelectedComplexObject {get; set;}

    property Object SomethingNotNecessarilyRelated {get; set;}

    private void NotifyPropertyChanged(string propName) {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}
</code>```

All of the mentioned properties in these classes are databound in the Visual Studio 2008 Windows Forms designer, in the SomeForm or in the SomeControl classes. (ComplexObject.BoolProp is databound in both). Don't hesitate to ask more questions about the context.

The problem: When I make some (bunch of) notifications in the ViewModelClass class, there is some kind of knee-jerk reaction that sets ComplexObject.BoolProp to false, using that kind of stack trace:

```<code>System.dll!System.ComponentModel.ReflectPropertyDescriptor.SetValue(object component = "Object Exposed in 'SelectedComplexObject'", object value = false) + 0x124 bytes
System.Windows.Forms.dll!System.Windows.Forms.BindToObject.SetValue(object value) + 0x5d bytes
System.Windows.Forms.dll!System.Windows.Forms.Binding.PullData(bool reformat, bool force) + 0x15a bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingManagerBase.PullData(out bool success = true) + 0x6e bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.ParentCurrencyManager_CurrentItemChanged(object sender = {System.Windows.Forms.CurrencyManager}, System.EventArgs e) + 0x54 bytes
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnCurrentItemChanged(System.EventArgs e) + 0x17 bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x3bc bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x7e bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.InnerList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x2e bytes
System.dll!System.ComponentModel.BindingList<System.__Canon>.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x17 bytes
System.dll!System.ComponentModel.BindingList<MyCompany.ViewModelClass>.Child_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + 0x176 bytes
[Native to Managed Transition]
[Managed to Native Transition]
MyCompany.Gui.exe!MyCompany.ViewModelClass.NotifyPropertyChanged(String propertyName = "SomethingNotNecessarilyRelated") Line 437 + 0x3c bytes  Basic
</code>```

Why does the program want to set SomeBool to false? And how I can prevent that?

答:
I have refactored the single ViewModelClass into SomeFormViewModel and SomeControlViewModel, and binding them to their respective classes.

Simply doing that has made the issue disappear.

I would still like a better understanding of the stacktrace that I put, though - I conjecture that the gist of the problem is that each BindingSource maintains its own information of the changes made to the object - and as both of them made changes to the same object, they did not know what was happening anymore.

Body:
OK, so here is some context for my problem, written as pseudo-C# code (feel free to point out any mistake): (You can jump directly to the stacktrace and read the context later.)

public class SomeForm {
    private _model = new ViewModelClass
    public void new() {
        // Normal Winforms init omitted
        ViewModelClassBindingSource.DataSource = _model;
        SomeControl1.SetModel(_model);
    }
}
public class SomeControl {
    private _model = new ViewModelClass

    internal void SetModel(ViewModelClass model) {
        _model = model;
        ViewModelClassBindingSource.DataSource = model;
        ViewModelClassBindingSource.ResetBindings(true);
    }
}

public class ComplexObject : IPropertyChanging, IPropertyChanged {
    public property bool BoolProp {get; set;}
}

public class ViewModelClass : IPropertyChanged {
    property IList<ComplexObject> ComplexObjects {get;}

    property ComplexObject SelectedComplexObject {get; set;}

    property Object SomethingNotNecessarilyRelated {get; set;}

    private void NotifyPropertyChanged(string propName) {
        PropertyChanged(this, new PropertyChangedEventArgs(propName));
    }
}

All of the mentioned properties in these classes are databound in the Visual Studio 2008 Windows Forms designer, in the SomeForm or in the SomeControl classes. (ComplexObject.BoolProp is databound in both). Don't hesitate to ask more questions about the context.

The problem: When I make some (bunch of) notifications in the ViewModelClass class, there is some kind of knee-jerk reaction that sets ComplexObject.BoolProp to false, using that kind of stack trace:

System.dll!System.ComponentModel.ReflectPropertyDescriptor.SetValue(object component = "Object Exposed in 'SelectedComplexObject'", object value = false) + 0x124 bytes
System.Windows.Forms.dll!System.Windows.Forms.BindToObject.SetValue(object value) + 0x5d bytes
System.Windows.Forms.dll!System.Windows.Forms.Binding.PullData(bool reformat, bool force) + 0x15a bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingManagerBase.PullData(out bool success = true) + 0x6e bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.ParentCurrencyManager_CurrentItemChanged(object sender = {System.Windows.Forms.CurrencyManager}, System.EventArgs e) + 0x54 bytes
[Native to Managed Transition]
[Managed to Native Transition]
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnCurrentItemChanged(System.EventArgs e) + 0x17 bytes
System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x3bc bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x7e bytes
System.Windows.Forms.dll!System.Windows.Forms.BindingSource.InnerList_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e) + 0x2e bytes
System.dll!System.ComponentModel.BindingList<System.__Canon>.OnListChanged(System.ComponentModel.ListChangedEventArgs e) + 0x17 bytes
System.dll!System.ComponentModel.BindingList<MyCompany.ViewModelClass>.Child_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) + 0x176 bytes
[Native to Managed Transition]
[Managed to Native Transition]
MyCompany.Gui.exe!MyCompany.ViewModelClass.NotifyPropertyChanged(String propertyName = "SomethingNotNecessarilyRelated") Line 437 + 0x3c bytes  Basic

Why does the program want to set SomeBool to false? And how I can prevent that?


问:
How can I set the initial value of Select2 when using AJAX?
I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is not shown in the select box, it is still showing the placeholder.

Whereas I should be seeing something like this:

In my form fields:

<input name="creditor_id" type="hidden" value="3" />

        Creditor:

            <select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
                <option></option>
            </select>

```
<p>My javascript:</p>
<pre class="lang-js prettyprint-override"><code>var initial_creditor_id="3";
$(".creditor_select2").select2({
    ajax: {
        url: "/admin/api/transactions/creditorlist",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term,
                c_id: initial_creditor_id,
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    },
    placeholder: "Search for a Creditor",
    width: "element",
    theme: "bootstrap",
    allowClear: true
}).on("select2:select", function (e) {
    var selected=e.params.data;
    if (typeof selected!=="undefined") {
        $("[name='creditor_id']").val(selected.creditor_id);
        $("#allocationsDiv").hide();
        $("[name='amount_cash']").val("");
        $("[name='amount_cheque']").val("");
        $("[name='amount_direct']").val("");
        $("[name='amount_creditcard']").val("");
    }
}).on("select2:unselecting", function (e) {
    $("form").each(function () {
        this.reset()
    });
    ("#allocationsDiv").hide();
    $("[name='creditor_id']").val("");
}).val(initial_creditor_id);
</code>```

How can I make the select box show the selected item rather than the placeholder? Should I be sending this as part of the AJAX JSON response perhaps?

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This worked fine for me in v3.5.

答:
after spending a few hours searching for a solution, I decided to create my own. He it is:

```<code> function CustomInitSelect2(element, options) {
            if (options.url) {
                $.ajax({
                    type: 'GET',
                    url: options.url,
                    dataType: 'json'
                }).then(function (data) {
                    element.select2({
                        data: data
                    });
                    if (options.initialValue) {
                        element.val(options.initialValue).trigger('change');
                    }
                });
            }
        }
</code>```

And you can initialize the selects using this function:

```<code>$('.select2').each(function (index, element) {
            var item = $(element);
            if (item.data('url')) {
                CustomInitSelect2(item, {
                    url: item.data('url'),
                    initialValue: item.data('value')
                });
            }
            else {
                item.select2();
            }
        });
</code>```

And of course, here is the html:

```<code><select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>
</code>```

Body:
I have a select2 v4.0.0 being populated from an Ajax array. If I set the val of the select2 I can see via javascript debugging that it has selected the correct item (#3 in my case), however this is not shown in the select box, it is still showing the placeholder.

Whereas I should be seeing something like this:

In my form fields:

<input name="creditor_id" type="hidden" value="3" />

        Creditor:

            <select class="creditor_select2 input-xlarge form-control minimal select2 col-xs-8">
                <option></option>
            </select>

My javascript:

var initial_creditor_id="3";
$(".creditor_select2").select2({
    ajax: {
        url: "/admin/api/transactions/creditorlist",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term,
                c_id: initial_creditor_id,
                page: params.page
            };
        },
        processResults: function (data, page) {
            return {
                results: data
            };
        },
        cache: true
    },
    placeholder: "Search for a Creditor",
    width: "element",
    theme: "bootstrap",
    allowClear: true
}).on("select2:select", function (e) {
    var selected=e.params.data;
    if (typeof selected!=="undefined") {
        $("[name='creditor_id']").val(selected.creditor_id);
        $("#allocationsDiv").hide();
        $("[name='amount_cash']").val("");
        $("[name='amount_cheque']").val("");
        $("[name='amount_direct']").val("");
        $("[name='amount_creditcard']").val("");
    }
}).on("select2:unselecting", function (e) {
    $("form").each(function () {
        this.reset()
    });
    ("#allocationsDiv").hide();
    $("[name='creditor_id']").val("");
}).val(initial_creditor_id);

How can I make the select box show the selected item rather than the placeholder? Should I be sending this as part of the AJAX JSON response perhaps?

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This worked fine for me in v3.5.

Body:
after spending a few hours searching for a solution, I decided to create my own. He it is:

 function CustomInitSelect2(element, options) {
            if (options.url) {
                $.ajax({
                    type: 'GET',
                    url: options.url,
                    dataType: 'json'
                }).then(function (data) {
                    element.select2({
                        data: data
                    });
                    if (options.initialValue) {
                        element.val(options.initialValue).trigger('change');
                    }
                });
            }
        }

And you can initialize the selects using this function:

$('.select2').each(function (index, element) {
            var item = $(element);
            if (item.data('url')) {
                CustomInitSelect2(item, {
                    url: item.data('url'),
                    initialValue: item.data('value')
                });
            }
            else {
                item.select2();
            }
        });

And of course, here is the html:

<select class="form-control select2" id="test1" data-url="mysite/load" data-value="123"></select>


问:
while(multiple array lengths > 0)
I've found similar questions about my problem though the answers contain suggestions which do half of what I need - none of them do it all.

I need to develop a function which will cope with both:

an unknown number of arrays, AND...

of differing lengths AND...

alternately merge the arrays (added as edit)

I'm trying to write a function based on two I've found and believe I just need to figure the while() out, but I'm totally stumped. I can't seem to track down any examples of while loops that use an array in their conditions... if you follow.

```<code>function alternately_merge_arrays() {
  $arrays = func_get_args();
  $new_array = array();
  //

  while( count($array) in $arrays is > 0  ) {

  //
    foreach($arrays as $array) {
      if ( count($array) > 0 )
         $new_array[] = array_shift($array);
     }
  }
 return $new_array;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9));
</code>```

Of course I may be completely wrong and it needs to be something other than a while() loop. I'm cool using for() and foreach(), though if the first array is the shortest these would stop looping where while() should continue...

Edit: The output I need would be:

```<code>array(1,2,3,4,5,6,7,8,9)
</code>```

答:
I would rewrite it like this:

```<code>function alternately_merge_arrays() {
    $arrays = func_get_args();
    $new_array = [];
    while ($arrays) {
        foreach ($arrays as $key => &$array) {
            $item = array_shift($array);
            if ($item) {
                $new_array[] = $item;
            } else {
                unset($arrays[$key]);
            }
        }
    }
    return $new_array;
}
</code>```

The key changes are:

you don't need to use count just to see if an array is empty, because an empty array will evaluate to false.

If you use a reference (&$array), then array_shift will directly affect the array in question, so you can remove each array from $arrays if it has been emptied after removing an element with array_shift.

If you're using PHP 5.6+, then you can take advantage of variable length argument lists (variadic functions) and use:

```<code>function alternately_merge_arrays(...$arrays) {
</code>```

so you can forgo the func_get_args and still use it with a variable number of arrays.

Title: while(multiple array lengths > 0)

Body:
I've found similar questions about my problem though the answers contain suggestions which do half of what I need - none of them do it all.

I need to develop a function which will cope with both:

an unknown number of arrays, AND...

of differing lengths AND...

alternately merge the arrays (added as edit)

I'm trying to write a function based on two I've found and believe I just need to figure the while() out, but I'm totally stumped. I can't seem to track down any examples of while loops that use an array in their conditions... if you follow.

function alternately_merge_arrays() {
  $arrays = func_get_args();
  $new_array = array();
  //

  while( count($array) in $arrays is > 0  ) {

  //
    foreach($arrays as $array) {
      if ( count($array) > 0 )
         $new_array[] = array_shift($array);
     }
  }
 return $new_array;
}

var_dump(alternately_merge_arrays(array(1,4), array(2,5,7), array(3,6,8,9));

Of course I may be completely wrong and it needs to be something other than a while() loop. I'm cool using for() and foreach(), though if the first array is the shortest these would stop looping where while() should continue...

Edit: The output I need would be:

array(1,2,3,4,5,6,7,8,9)

Body:
I would rewrite it like this:

function alternately_merge_arrays() {
    $arrays = func_get_args();
    $new_array = [];
    while ($arrays) {
        foreach ($arrays as $key => &$array) {
            $item = array_shift($array);
            if ($item) {
                $new_array[] = $item;
            } else {
                unset($arrays[$key]);
            }
        }
    }
    return $new_array;
}

The key changes are:

you don't need to use count just to see if an array is empty, because an empty array will evaluate to false.

If you use a reference (&$array), then array_shift will directly affect the array in question, so you can remove each array from $arrays if it has been emptied after removing an element with array_shift.

If you're using PHP 5.6+, then you can take advantage of variable length argument lists (variadic functions) and use:

function alternately_merge_arrays(...$arrays) {

so you can forgo the func_get_args and still use it with a variable number of arrays.


问:
How to link a button to a special place on Image?
I've placed buttons and imageView on RelativeLayout, and these buttons are placed perfectly on Nexus 5: How it looks on Nexus 5

But on Nexus One it changes a lot: How it looks on Nexus One

Here's my xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            app:srcCompat="@drawable/main_menu_top" />

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            app:srcCompat="@drawable/main_menu_center"
            android:layout_below="@+id/imageView6" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/imageView6">

        </RelativeLayout>

        <Button
            android:id="@+id/top_left_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/imageView6"
            android:layout_marginLeft="77dp"
            android:layout_marginStart="77dp"
            android:layout_marginTop="38dp"
            android:background="@drawable/button_main_menu_port"
            android:text="Example" />

        <Button
            android:id="@+id/top_right_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:background="@drawable/button_main_menu_port"
            android:text="Example"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="80dp"
            android:layout_marginEnd="80dp"
            android:layout_alignBottom="@+id/top_left_button" />

        <Button
            android:id="@+id/bot_left_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:layout_alignLeft="@+id/top_left_button"
            android:layout_alignParentBottom="true"
            android:layout_alignStart="@+id/top_left_button"
            android:layout_marginBottom="39dp"
            android:background="@drawable/button_main_menu_port"
            android:text="Example" />

        <Button
            android:id="@+id/bot_right_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:layout_alignBottom="@+id/bot_left_button"
            android:layout_alignLeft="@+id/top_right_button"
            android:layout_alignStart="@+id/top_right_button"
            android:background="@drawable/button_main_menu_port"
            android:lines="2"
            android:maxLines="2"
            android:minLines="2"
            android:text="Example" />

    </RelativeLayout>

</LinearLayout>
</code>```

However, these buttons need to be on positions of the rhombuses in this image.

答:
You have used fixed layout width and height for buttons and also used fixed layout margins. Fixed values causes the problem because the resolution of Nexus Five and Nexus One are different.

Solution:

You can use LinearLayout with attribute android:weightSum and use android:layout_weight to buttons instead of fixed width and height.

Body:
I've placed buttons and imageView on RelativeLayout, and these buttons are placed perfectly on Nexus 5: How it looks on Nexus 5

But on Nexus One it changes a lot: How it looks on Nexus One

Here's my xml code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imageView6"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            app:srcCompat="@drawable/main_menu_top" />

        <ImageView
            android:id="@+id/imageView7"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            app:srcCompat="@drawable/main_menu_center"
            android:layout_below="@+id/imageView6" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/imageView6">

        </RelativeLayout>

        <Button
            android:id="@+id/top_left_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/imageView6"
            android:layout_marginLeft="77dp"
            android:layout_marginStart="77dp"
            android:layout_marginTop="38dp"
            android:background="@drawable/button_main_menu_port"
            android:text="Example" />

        <Button
            android:id="@+id/top_right_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:background="@drawable/button_main_menu_port"
            android:text="Example"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="80dp"
            android:layout_marginEnd="80dp"
            android:layout_alignBottom="@+id/top_left_button" />

        <Button
            android:id="@+id/bot_left_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:layout_alignLeft="@+id/top_left_button"
            android:layout_alignParentBottom="true"
            android:layout_alignStart="@+id/top_left_button"
            android:layout_marginBottom="39dp"
            android:background="@drawable/button_main_menu_port"
            android:text="Example" />

        <Button
            android:id="@+id/bot_right_button"
            android:layout_width="105dp"
            android:layout_height="105dp"
            android:layout_alignBottom="@+id/bot_left_button"
            android:layout_alignLeft="@+id/top_right_button"
            android:layout_alignStart="@+id/top_right_button"
            android:background="@drawable/button_main_menu_port"
            android:lines="2"
            android:maxLines="2"
            android:minLines="2"
            android:text="Example" />

    </RelativeLayout>

</LinearLayout>

However, these buttons need to be on positions of the rhombuses in this image.