问:
Closest function not working in JQuery
I am making a select list.

Now I want to show the options in select list with class "new" according to change in option in list with class old".

Like, when the option 1 is selected, 3,4,5 are visible and when the option 2 is selected, 6,7,8 are visible.

Also, I want to control the options in corresponding row.

$(document).ready(function() {
  $(".new").children('option:gt(0)').hide();
  $('.new option[value="select"]').show();
  $('.new option[value="1"]').show();
  $('.new option[value="2"]').show();
  $('.new option[value="3"]').show();
  $(function() {
    $(".old").change(function() {
      var a = $(this).val();
      if (a == 2) {
        $(".new").children('option:gt(0)').hide();
        $('$(this).closest('tr').find('.new') option[value="select"]').show();
        $('$(this).closest('tr').find('.new') option[value="4"]').show();
        $('$(this).closest('tr').find('.new') option[value="5"]').show();
        $('$(this).closest('tr').find('.new') option[value="6"]').show();
      };
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
</table></code>```

答:
You need to remove the invalid quotes around your jQuery calls.

Also, $(function(){}) is shorthand for $(document).ready(function(){}), so you do not need a ready function twice.

$(function() {
  // Hide all children for all 'new' combos.
  $('.new').children('option:gt(0)').hide();

  // Show only first three 'new' items (if available).
  $('.new option[value="select"]').show();
  $('.new option[value="1"]').show();
  $('.new option[value="2"]').show();
  $('.new option[value="3"]').show();

  $('.old').change(function() {
    var a = $(this).val();
    if (a == 2) {
      // Hide all children for all 'new' combos.
      $('.new').children('option:gt(0)').hide();

      // Show only the 'new' items for the current row.
      let $rowNew = $(this).closest('tr').find('.new');
      $rowNew.find('option[value="select"]').show();
      $rowNew.find('option[value="4"]').show();
      $rowNew.find('option[value="5"]').show();
      $rowNew.find('option[value="6"]').show();
    };
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
</table></code>```

Title: Closest function not working in JQuery

Body:
I am making a select list.

Now I want to show the options in select list with class "new" according to change in option in list with class old".

Like, when the option 1 is selected, 3,4,5 are visible and when the option 2 is selected, 6,7,8 are visible.

Also, I want to control the options in corresponding row.

$(document).ready(function() {
  $(".new").children('option:gt(0)').hide();
  $('.new option[value="select"]').show();
  $('.new option[value="1"]').show();
  $('.new option[value="2"]').show();
  $('.new option[value="3"]').show();
  $(function() {
    $(".old").change(function() {
      var a = $(this).val();
      if (a == 2) {
        $(".new").children('option:gt(0)').hide();
        $('$(this).closest('tr').find('.new') option[value="select"]').show();
        $('$(this).closest('tr').find('.new') option[value="4"]').show();
        $('$(this).closest('tr').find('.new') option[value="5"]').show();
        $('$(this).closest('tr').find('.new') option[value="6"]').show();
      };
    });
  });
});

      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>

      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>

      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>

      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>

Body:
You need to remove the invalid quotes around your jQuery calls.

Also, $(function(){}) is shorthand for $(document).ready(function(){}), so you do not need a ready function twice.

$(function() {
  // Hide all children for all 'new' combos.
  $('.new').children('option:gt(0)').hide();

  // Show only first three 'new' items (if available).
  $('.new option[value="select"]').show();
  $('.new option[value="1"]').show();
  $('.new option[value="2"]').show();
  $('.new option[value="3"]').show();

  $('.old').change(function() {
    var a = $(this).val();
    if (a == 2) {
      // Hide all children for all 'new' combos.
      $('.new').children('option:gt(0)').hide();

      // Show only the 'new' items for the current row.
      let $rowNew = $(this).closest('tr').find('.new');
      $rowNew.find('option[value="select"]').show();
      $rowNew.find('option[value="4"]').show();
      $rowNew.find('option[value="5"]').show();
      $rowNew.find('option[value="6"]').show();
    };
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
  <tr>
    <td>
      <select class="old">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </td>
    <td>
      <select class="new">
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
      </select>
    </td>
  </tr>
</table>


来源: stackexchange

问:
SQL JOIN and different types of JOINs
What is a SQL JOIN and what are different types?

答:
I'm going to push my pet peeve: the USING keyword.

If both tables on both sides of the JOIN have their foreign keys properly named (ie, same name, not just "id) then this can be used:

```<code>SELECT ...
FROM customers JOIN orders USING (customer_id)
</code>```

I find this very practical, readable, and not used often enough.

ContentLicense: CC BY-SA 3.0

Title: SQL JOIN and different types of JOINs

Body:
I'm going to push my pet peeve: the USING keyword.

If both tables on both sides of the JOIN have their foreign keys properly named (ie, same name, not just "id) then this can be used:

SELECT ...
FROM customers JOIN orders USING (customer_id)

I find this very practical, readable, and not used often enough.


问:
Creating objects dynamically using a list of Strings?
I am trying to create objects by using a list of Strings that will populate their fields. For example I have the list of strings, Note that the values repeat after every 3. i.e. id, name , address.

```<code>List<String> myList = "Id1", "name1", "address1", "Id2", "name2", "address2";
</code>```

I would like to dynamically create a number of Person Objects (shown below) using this list

```<code>Person object:

public class Person {

    private String id;
    private String name;
    private String address;

     public Person() {
    }

    public Person(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    //standard getters and setters

}
</code>```

What I want to do is have a method that will take the list of strings as an input and then create the objects dynamically. How could I best do this?

I know that I could do the following if I knew that I was definitely populating 2 objects, but the problem is that there may be more or less.

```<code>public List<Person> createObjectsFromStringList(List<String> list){

    List<person> personList = new Arraylist<>();

    Person person1 = new Person(list.get(0), list.get(1), list.get(2));
    Person person2 = new Person(list.get(3), list.get(4), list.get(5));

    personList.add(person1);
    personList.add(person2);

    return personList;

}
</code>```

答:
You can use recursion

```<code>public List<Person> createObjectsFromStringList(List<String> list){

List<person> personList = new Arraylist<>();
for(int i=0; i<list.size(); i++){
     personList.add(new Person(list(i),list(i+1),list(i+2)));
     i+=2;
}
 return personList;
}
</code>```

Notice that restructuring your list would me much better. make it like this:

```<code>List<String> myList = "Id1_name1_address1", "Id2_name2_address2";
</code>```

Or even use different lists (it is much better). If you change your list structure as above then change the code to this :

```<code>public List<Person> createObjectsFromStringList(List<String> list){

List<person> personList = new Arraylist<>();
for(int i=0; i<list.size(); i++){
     String[] info= list(i).split("_"); // this will give u a 3element array of yout info IdX nameX addressX
     personList.add(new Person(info(0),info(1),info(2)));
     }

return personList;
</code>```

Body:
I am trying to create objects by using a list of Strings that will populate their fields. For example I have the list of strings, Note that the values repeat after every 3. i.e. id, name , address.

List<String> myList = "Id1", "name1", "address1", "Id2", "name2", "address2";

I would like to dynamically create a number of Person Objects (shown below) using this list

Person object:

public class Person {

    private String id;
    private String name;
    private String address;

     public Person() {
    }

    public Person(String id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
    }

    //standard getters and setters

}

What I want to do is have a method that will take the list of strings as an input and then create the objects dynamically. How could I best do this?

I know that I could do the following if I knew that I was definitely populating 2 objects, but the problem is that there may be more or less.

public List<Person> createObjectsFromStringList(List<String> list){

    List<person> personList = new Arraylist<>();

    Person person1 = new Person(list.get(0), list.get(1), list.get(2));
    Person person2 = new Person(list.get(3), list.get(4), list.get(5));

    personList.add(person1);
    personList.add(person2);

    return personList;

}

Body:
You can use recursion

public List<Person> createObjectsFromStringList(List<String> list){

List<person> personList = new Arraylist<>();
for(int i=0; i<list.size(); i++){
     personList.add(new Person(list(i),list(i+1),list(i+2)));
     i+=2;
}
 return personList;
}

Notice that restructuring your list would me much better. make it like this:

List<String> myList = "Id1_name1_address1", "Id2_name2_address2";

Or even use different lists (it is much better). If you change your list structure as above then change the code to this :

public List<Person> createObjectsFromStringList(List<String> list){

List<person> personList = new Arraylist<>();
for(int i=0; i<list.size(); i++){
     String[] info= list(i).split("_"); // this will give u a 3element array of yout info IdX nameX addressX
     personList.add(new Person(info(0),info(1),info(2)));
     }

return personList;


问:
how to pass array used in function to the dynamically allocated array of main?
```<code>#include<iostream>

#include<string>
using namespace std;

char *fun(const char* a)
{
        int size=strlen(a);

        char* str=new char[12];

        for(int i=0;i<size-1;i++)
        {
                str[i]=a[size-i-1];
        }

        str[size-1]='\0';

        return str;
}

main()
{
        int i=0;

        char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};

        char *p=new char[11];

        p=fun(a);

        for(int i=0;i<11;i++)
        {
                cout<<p[i]<<" ";
        }

        delete(ptr);
}
</code>```

<p>//having some troubles using array p in the main here please help.</p>

答:
There are many issues:

Here the a array is not NUL terminated, therefore strlen cannot be used on it in fun:

```<code>char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};
</code>```

Here you are allocating a fixed size of 12, but you need a dynamic size depending on the length of the string:

```<code>char* str=new char[12];
</code>```

Then:

```<code>str[size-1]='\0';
</code>```

should be:

```<code>str[size] = '\0';
</code>```

otherwise your resulting string will miss the last character.

In main:

```<code>char *p=new char[11];
</code>```

is pointless because you assign p right after with p=fun(a);.

You call delete(ptr);, but there is no ptr.

And finally you should also #include <string.h> be sure that strlen is defined, but one some platforms it compiles also without #include <string.h>.

You probably want this:

```<code>#include <iostream>
#include <string>
#include <string.h>

using namespace std;

char *fun(const char* a)
{
  int size = strlen(a);
  char* str = new char[size + 1];

  for (int i = 0; i < size; i++)
  {
    str[i] = a[size - i - 1];
  }

  str[size] = '\0';
  return str;
}

int main()
{
  char a[] = "ABCDE";
  char *p = fun(a);
  int size = strlen(p);

  for (int i = 0; i < size; i++)
  {
    cout << p[i] << " ";
  }

  delete[] p;
}
</code>```

Body:
#include<iostream>

#include<string>
using namespace std;

char *fun(const char* a)
{
        int size=strlen(a);

        char* str=new char[12];

        for(int i=0;i<size-1;i++)
        {
                str[i]=a[size-i-1];
        }

        str[size-1]='\0';

        return str;
}

main()
{
        int i=0;

        char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};

        char *p=new char[11];

        p=fun(a);

        for(int i=0;i<11;i++)
        {
                cout<<p[i]<<" ";
        }

        delete(ptr);
}

//having some troubles using array p in the main here please help.

Body:
There are many issues:

Here the a array is not NUL terminated, therefore strlen cannot be used on it in fun:

char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};

Here you are allocating a fixed size of 12, but you need a dynamic size depending on the length of the string:

char* str=new char[12];

Then:

str[size-1]='\0';

should be:

str[size] = '\0';

otherwise your resulting string will miss the last character.

In main:

char *p=new char[11];

is pointless because you assign p right after with p=fun(a);.

You call delete(ptr);, but there is no ptr.

And finally you should also #include <string.h> be sure that strlen is defined, but one some platforms it compiles also without #include <string.h>.

You probably want this:

#include <iostream>
#include <string>
#include <string.h>

using namespace std;

char *fun(const char* a)
{
  int size = strlen(a);
  char* str = new char[size + 1];

  for (int i = 0; i < size; i++)
  {
    str[i] = a[size - i - 1];
  }

  str[size] = '\0';
  return str;
}

int main()
{
  char a[] = "ABCDE";
  char *p = fun(a);
  int size = strlen(p);

  for (int i = 0; i < size; i++)
  {
    cout << p[i] << " ";
  }

  delete[] p;
}


问:
*ngIf window.location.href.indexOf is not working
I need to show one element only if location is right, if not, it shoudn't be shown.

This is not working:

```<code><div *ngIf="!accessTrue() && window.location.href.indexOf('something')" > -1)>
    CODE
</div>
</code>```

答:
In HTML :  </p>

```<code> <div *ngIf="hasAccess"> CODE </div>
</code>```

<p>In angular Component : </p>

```<code>constructor(){
        this.hasAccess = window.location.href.indexOf('something') > -1 && !this.accessTrue();
}
</code>```

Body:
I need to show one element only if location is right, if not, it shoudn't be shown.

This is not working:

 -1)>
    CODE

Body:
In HTML :

 <div *ngIf="hasAccess"> CODE </div>

In angular Component :

constructor(){
        this.hasAccess = window.location.href.indexOf('something') > -1 && !this.accessTrue();
}


问:
list view cannot display
I just tried to custom ListView (with checkbox) in android about "destination" information, it is very strange for me, because there is no error in Logcat but Listview doesnt display the items

I have searched the possible mistakes for a whole day, but I could figure out the real reason. Please help me! Thx!

here is my source :

code of ListView Adapter :

```<code>public class DestinationAdapter extends BaseAdapter {

private List<Destination> destinationList;

private static HashMap<Integer,Boolean> isSelected;

Context context;

LayoutInflater mInflater = null;

public DestinationAdapter(List<Destination> destinationList, Context context) {

    super();
    destinationList = new ArrayList<Destination>();

    this.context = context;
    this.destinationList = destinationList;

    mInflater = LayoutInflater.from(context);
    isSelected = new HashMap<Integer, Boolean>();

    init();
}

private void init(){
    for(int i=0; i< destinationList.size(); i++) {
        getIsSelected().put(i,false);
    }
}

@Override
public int getCount() {

    return destinationList.size();
}

@Override
public Destination getItem(int position) {

    return destinationList.get(position);
}

@Override
public long getItemId(int position) {

    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.destination_item, null);

        viewHolder = new ViewHolder();

        viewHolder.destinationImage = (ImageView) convertView.findViewById
                (R.id.destination_image);
        viewHolder.destinationName = (TextView) convertView.findViewById
                (R.id.destination_name);
        viewHolder.placeSelected = (CheckBox) convertView.findViewById
                (R.id.place_select);

        convertView.setTag(viewHolder);
        }
    else {
        viewHolder = (ViewHolder) convertView.getTag();
        }

    viewHolder.destinationName.setText(destinationList.get(position).getName());
    viewHolder.destinationImage.setImageResource(destinationList.get(position).getImageId());
    viewHolder.placeSelected.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (isSelected.get(position)) {
                isSelected.put(position, false);
                setIsSelected(isSelected);
            } else {
                isSelected.put(position, true);
                setIsSelected(isSelected);
            }
            notifyDataSetChanged();
        }
    });

    viewHolder.placeSelected.setChecked(getIsSelected().get(position));

    return convertView;
}

public static HashMap<Integer,Boolean> getIsSelected() {
    return isSelected;
}

public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {
    DestinationAdapter.isSelected = isSelected;
}

class ViewHolder {
    ImageView destinationImage;
    TextView destinationName;
    CheckBox placeSelected;
}
</code>```

}

and my activity(I have deleted the irrelevant parts for other display):

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

private ListView listView;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

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

    listView = (ListView) findViewById(R.id.list_destination);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);

    listView.setAdapter(adapter);

   }

//初始化数据
private void initDestinations() {
    Destination destination1 = new Destination("beijing", R.drawable.car);
    destinationList.add(destination1);
    Destination destination2 = new Destination("shanghai", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("hangzhou", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("guangzhou", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("shenzhen", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("zhuhai", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("xiamen", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("qingdao", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("jinan", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("zhengzhou", R.drawable.car);
    destinationList.add(destination10);
}
</code>```

}

and the Destination object:

```<code>public class Destination implements Serializable {

private int id;
private String name;
private int imageId;
private int priority;
private int rank;

// 经度
private double longitude;
// 纬度
private double latitute;

public Destination(double longitude, double latitute){
    this.longitude = longitude;
    this.latitute = latitute;
}

public Destination(String name, int imageId){
    this.name = name;
    this.imageId = imageId;
}

public Destination(int id, String name, int priority){
    this.id = id;
    this.name = name;
    this.priority = priority;
}

public double getLongitude()
{
    return longitude;
}

public void setLongitude(double longitude) {
    this.longitude = longitude;
}

public double getLatitute(){
    return latitute;
}

public void setLatitute(double latitute) {
    this.latitute = latitute;
}

public int getId() { return  id; }
public String getName() {
    return name;
}
public int getImageId() { return imageId; }
public int getPriority(){ return priority; }
public int getRank() {return rank;}

public void setName(String name){
    this.name = name;
}
public void setImageId(int imageId){
    this.imageId = imageId;
}
public void setId(int id){ this.id = id; }
</code>```

}

two layouts xml:

item_destination.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/destination_image"
    android:layout_width="100dp"
    android:layout_height="100dp" />
<TextView
    android:id="@+id/destination_name"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:layout_gravity="center"
    android:layout_marginLeft="10dip" />

<CheckBox
    android:id="@+id/place_select"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentRight="true"
    android:layout_marginRight="10dp"
    android:layout_centerVertical="true"
    android:focusable="false"
    android:clickable="false"
    android:focusableInTouchMode="false"   />
</code>```

destination_layout.xml, the listview is only a part from it

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="@drawable/border"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/vertical_padding"
    android:paddingLeft="@dimen/horizontal_padding"
    android:paddingTop="@dimen/vertical_padding" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:src="@drawable/departure" />

    <TextView
        android:id="@+id/from_place"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="From"
        android:textSize="20dp" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_gravity="top"
    android:background="@drawable/border"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/vertical_padding"
    android:paddingLeft="@dimen/horizontal_padding"
    android:paddingTop="@dimen/vertical_padding" >

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:src="@drawable/departure" />

<ListView
    android:id="@+id/list_destination"
    android:layout_marginLeft="10dp"
    android:layout_width="match_parent"
    android:layout_height="500dp" >
</ListView>
  </LinearLayout>
</code>```

Please help me! It makes me confused for a few days. thx!

答:
Remove below line from adapter's constructor.

```<code>destinationList = new ArrayList<Destination>();
</code>```

You are making new reference of list from inside of adapter.

```<code>  public DestinationAdapter(List<Destination> destinationList, Context context) {
      super();
      // Doing this you are creating new reference of passed argument. Delete it
      destinationList = new ArrayList<Destination>();
      // Here you are getting empty list due to above statement
      this.destinationList = destinationList;
  }
</code>```

Title: list view cannot display

Body:
I just tried to custom ListView (with checkbox) in android about "destination" information, it is very strange for me, because there is no error in Logcat but Listview doesnt display the items

I have searched the possible mistakes for a whole day, but I could figure out the real reason. Please help me! Thx!

here is my source :

code of ListView Adapter :

public class DestinationAdapter extends BaseAdapter {

private List<Destination> destinationList;

private static HashMap<Integer,Boolean> isSelected;

Context context;

LayoutInflater mInflater = null;

public DestinationAdapter(List<Destination> destinationList, Context context) {

    super();
    destinationList = new ArrayList<Destination>();

    this.context = context;
    this.destinationList = destinationList;

    mInflater = LayoutInflater.from(context);
    isSelected = new HashMap<Integer, Boolean>();

    init();
}

private void init(){
    for(int i=0; i< destinationList.size(); i++) {
        getIsSelected().put(i,false);
    }
}

@Override
public int getCount() {

    return destinationList.size();
}

@Override
public Destination getItem(int position) {

    return destinationList.get(position);
}

@Override
public long getItemId(int position) {

    return position;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    ViewHolder viewHolder;

    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.destination_item, null);

        viewHolder = new ViewHolder();

        viewHolder.destinationImage = (ImageView) convertView.findViewById
                (R.id.destination_image);
        viewHolder.destinationName = (TextView) convertView.findViewById
                (R.id.destination_name);
        viewHolder.placeSelected = (CheckBox) convertView.findViewById
                (R.id.place_select);

        convertView.setTag(viewHolder);
        }
    else {
        viewHolder = (ViewHolder) convertView.getTag();
        }

    viewHolder.destinationName.setText(destinationList.get(position).getName());
    viewHolder.destinationImage.setImageResource(destinationList.get(position).getImageId());
    viewHolder.placeSelected.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            if (isSelected.get(position)) {
                isSelected.put(position, false);
                setIsSelected(isSelected);
            } else {
                isSelected.put(position, true);
                setIsSelected(isSelected);
            }
            notifyDataSetChanged();
        }
    });

    viewHolder.placeSelected.setChecked(getIsSelected().get(position));

    return convertView;
}

public static HashMap<Integer,Boolean> getIsSelected() {
    return isSelected;
}

public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {
    DestinationAdapter.isSelected = isSelected;
}

class ViewHolder {
    ImageView destinationImage;
    TextView destinationName;
    CheckBox placeSelected;
}

}

and my activity(I have deleted the irrelevant parts for other display):

public class DestinationActivity extends Activity {

private ListView listView;

private List<Destination> destinationList = new ArrayList<Destination>();

private DestinationAdapter adapter;

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

    listView = (ListView) findViewById(R.id.list_destination);

    initDestinations();

    adapter = new DestinationAdapter(destinationList, DestinationActivity.this);

    listView.setAdapter(adapter);

   }

//初始化数据
private void initDestinations() {
    Destination destination1 = new Destination("beijing", R.drawable.car);
    destinationList.add(destination1);
    Destination destination2 = new Destination("shanghai", R.drawable.car);
    destinationList.add(destination2);
    Destination destination3 = new Destination("hangzhou", R.drawable.car);
    destinationList.add(destination3);
    Destination destination4 = new Destination("guangzhou", R.drawable.car);
    destinationList.add(destination4);
    Destination destination5 = new Destination("shenzhen", R.drawable.car);
    destinationList.add(destination5);
    Destination destination6 = new Destination("zhuhai", R.drawable.car);
    destinationList.add(destination6);
    Destination destination7 = new Destination("xiamen", R.drawable.car);
    destinationList.add(destination7);
    Destination destination8 = new Destination("qingdao", R.drawable.car);
    destinationList.add(destination8);
    Destination destination9 = new Destination("jinan", R.drawable.car);
    destinationList.add(destination9);
    Destination destination10 = new Destination("zhengzhou", R.drawable.car);
    destinationList.add(destination10);
}

}

and the Destination object:

public class Destination implements Serializable {

private int id;
private String name;
private int imageId;
private int priority;
private int rank;

// 经度
private double longitude;
// 纬度
private double latitute;

public Destination(double longitude, double latitute){
    this.longitude = longitude;
    this.latitute = latitute;
}

public Destination(String name, int imageId){
    this.name = name;
    this.imageId = imageId;
}

public Destination(int id, String name, int priority){
    this.id = id;
    this.name = name;
    this.priority = priority;
}

public double getLongitude()
{
    return longitude;
}

public void setLongitude(double longitude) {
    this.longitude = longitude;
}

public double getLatitute(){
    return latitute;
}

public void setLatitute(double latitute) {
    this.latitute = latitute;
}

public int getId() { return  id; }
public String getName() {
    return name;
}
public int getImageId() { return imageId; }
public int getPriority(){ return priority; }
public int getRank() {return rank;}

public void setName(String name){
    this.name = name;
}
public void setImageId(int imageId){
    this.imageId = imageId;
}
public void setId(int id){ this.id = id; }

}

two layouts xml:

item_destination.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/destination_image"
    android:layout_width="100dp"
    android:layout_height="100dp" />
<TextView
    android:id="@+id/destination_name"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:layout_gravity="center"
    android:layout_marginLeft="10dip" />

<CheckBox
    android:id="@+id/place_select"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentRight="true"
    android:layout_marginRight="10dp"
    android:layout_centerVertical="true"
    android:focusable="false"
    android:clickable="false"
    android:focusableInTouchMode="false"   />

destination_layout.xml, the listview is only a part from it

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="top"
    android:background="@drawable/border"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/vertical_padding"
    android:paddingLeft="@dimen/horizontal_padding"
    android:paddingTop="@dimen/vertical_padding" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:src="@drawable/departure" />

    <TextView
        android:id="@+id/from_place"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:gravity="center"
        android:text="From"
        android:textSize="20dp" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="250dp"
    android:layout_gravity="top"
    android:background="@drawable/border"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/vertical_padding"
    android:paddingLeft="@dimen/horizontal_padding"
    android:paddingTop="@dimen/vertical_padding" >

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="45dp"
        android:layout_height="45dp"
        android:src="@drawable/departure" />

<ListView
    android:id="@+id/list_destination"
    android:layout_marginLeft="10dp"
    android:layout_width="match_parent"
    android:layout_height="500dp" >
</ListView>
  </LinearLayout>

Please help me! It makes me confused for a few days. thx!

Body:
Remove below line from adapter's constructor.

destinationList = new ArrayList<Destination>();

You are making new reference of list from inside of adapter.

  public DestinationAdapter(List<Destination> destinationList, Context context) {
      super();
      // Doing this you are creating new reference of passed argument. Delete it
      destinationList = new ArrayList<Destination>();
      // Here you are getting empty list due to above statement
      this.destinationList = destinationList;
  }


问:
Selected row background color
I'm using jqgrid with jquery-ui 'smoothness' theme, unfortunately with this theme the selected row background color is too light, I'm trying to change the background color to make it more visible.  I've tried changing ui-state-highlight in css (with !important override) but this does not work.  Is there a CSS way to do this or perhaps a jqgrid custom formatter is the way to go?</p>

答:
The class ui-state-highlight uses the background CSS attribute. So a small trick is to use background instead of background-color to remove the background image. For example

.ui-state-highlight { background: yellow !important; }
```

<p>see live here.</p>

<p><strong>UPDATED</strong>: It's not necessary to use <code>!important</code>. It's enough to specify a <em>more specific</em> rule like</p>

<pre class="lang-css prettyprint-override"><code>.ui-jqgrid-btable .ui-state-highlight { background: yellow; }
</code>```

or

.ui-jqgrid .ui-state-highlight { background: yellow; }
```

ContentLicense: CC BY-SA 2.5

Title: Selected row background color

Body:
The class ui-state-highlight uses the background CSS attribute. So a small trick is to use background instead of background-color to remove the background image. For example

.ui-state-highlight { background: yellow !important; }

see live here.

UPDATED: It's not necessary to use !important. It's enough to specify a more specific rule like

.ui-jqgrid-btable .ui-state-highlight { background: yellow; }

or

.ui-jqgrid .ui-state-highlight { background: yellow; }


问:
Asking to remove the time in datetime without changing the datatype
I want to ask about this one

How to remove the time in "Tanggal" column, without changing its datatype?

How to remove the 2 last digit 0 in "Harga" column?

Thank you

答:
If you have some negative values in the "Harga" column you should use a combination of FLOOR() and CEILING() functions instead of FLOOR(Harga).</p>

```<code>declare @q TABLE
(
    Tanggal DATETIME,
    Harga   MONEY
)

INSERT @q
VALUES
('2014-02-02', 1200000),
('2013-02-02', 1200000),
('2013-02-02', 1200000),
('2014-12-29 16:25:53.000', 1200000)

SELECT CAST(Tanggal AS DATE) AS Tanggal,
  CAST(FLOOR(Harga) AS INT) AS Harga
FROM @q
</code>```

Body:
If you have some negative values in the "Harga" column you should use a combination of FLOOR() and CEILING() functions instead of FLOOR(Harga).

declare @q TABLE
(
    Tanggal DATETIME,
    Harga   MONEY
)

INSERT @q
VALUES
('2014-02-02', 1200000),
('2013-02-02', 1200000),
('2013-02-02', 1200000),
('2014-12-29 16:25:53.000', 1200000)

SELECT CAST(Tanggal AS DATE) AS Tanggal,
  CAST(FLOOR(Harga) AS INT) AS Harga
FROM @q


问:
How to open a Bootstrap Modal on change of select Box
I am trying to open a modal on the change event of select Box?

This is My Modal

```<code><!-- Modal when adding comment for upload -->
  <div class="modal fade" id="fileUploadModal" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Add Comment</h4>
        </div>
        <div class="modal-body">
          <p><textarea id = "commentsUpload"class="form-control custom-control" rows="3" style="resize:none"></textarea></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" onclick="submitXYX()" data-dismiss="modal">Submit</button>
        </div>
      </div>
    </div>
  </div>
</code>```

And select Box is:

```<code><select class="selectpicker" id = "selectNEWBox">
    <option value = "1">New</option>
    <option value = "2">Old</option>
    <option value = "3">Scrap</option>
</select>
</code>```

What I need to do is to open the Modal on change event of select Box.

What I have tried

In $(document).ready(function () {});

Approach 1

```<code>$("#selectNEWBox").change(function(){
    $('#fileUploadModal').modal({
    show: true
  });
});
</code>```

Approach 2

```<code>$("#selectNEWBox").change(function (){
    $('#fileUploadModal').modal('show');
});
</code>```

but these are not working.

Am I missing something?

答:
just tried your code and it seem working

```<code>$( "#selectNEWBox" ).change(function() {
  $('#fileUploadModal').modal('show')
});
</code>```

try it here

Body:
I am trying to open a modal on the change event of select Box?

This is My Modal

          <button type="button" class="close" data-dismiss="modal">×</button>

Add Comment

<textarea id = "commentsUpload"class="form-control custom-control" rows="3" style="resize:none"></textarea>

          <button type="button" class="btn btn-default" onclick="submitXYX()" data-dismiss="modal">Submit</button>

And select Box is:

<select class="selectpicker" id = "selectNEWBox">
    <option value = "1">New</option>
    <option value = "2">Old</option>
    <option value = "3">Scrap</option>
</select>

What I need to do is to open the Modal on change event of select Box.

What I have tried

In $(document).ready(function () {});

Approach 1

$("#selectNEWBox").change(function(){
    $('#fileUploadModal').modal({
    show: true
  });
});

Approach 2

$("#selectNEWBox").change(function (){
    $('#fileUploadModal').modal('show');
});

but these are not working.

Am I missing something?

Body:
just tried your code and it seem working

$( "#selectNEWBox" ).change(function() {
  $('#fileUploadModal').modal('show')
});

try it here


答:
A simple for loop can do the work:

```<code>public List<Person> createObjectsFromStringList(List<String> list) {

    List<person> personList = new Arraylist<>();
    //We use < size-2 here because we access 2 indeces ahead of x in this loop
    for(int x=0; x<list.size()-2; x+=3) {
        personList.add(new Person(list.get(x), list.get(x+1), list.get(x+2));
    }
    return personList;
}
</code>```

At first glance, I feel like having the different field values across one List is a sign of a poor code structure, but maybe you're already stuck with this List as-is.

Edit:

Now let's suppose you want a partial Person based on the number of remaining elements. Supposing they are still in the same order, you could modify this method to check the validity of the current index for each field:

```<code>public List<Person> createObjectsFromStringList(List<String> list) {

    List<person> personList = new Arraylist<>();
    int size = list.size();
    //Now we remove the "-2" from size check because we will handle this ourselves
    for(int x=0; x<size; x+=3) {
        String id = list.get(x); //Obviously valid
        String name = x+1 < size? list.get(x+1) : null;
        String address = x+2 < size? list.get(x+2) : null;
        personList.add(new Person(id, name, address);
    }
    return personList;
}
</code>```

We're using the ternary operation ? ... : null here, so if we run out of elements we set the associated Person field to null instead of using an out-of-bounds index.

Title: Creating objects dynamically using a list of Strings?

Body:
A simple for loop can do the work:

public List<Person> createObjectsFromStringList(List<String> list) {

    List<person> personList = new Arraylist<>();
    //We use < size-2 here because we access 2 indeces ahead of x in this loop
    for(int x=0; x<list.size()-2; x+=3) {
        personList.add(new Person(list.get(x), list.get(x+1), list.get(x+2));
    }
    return personList;
}

At first glance, I feel like having the different field values across one List is a sign of a poor code structure, but maybe you're already stuck with this List as-is.

Edit:

Now let's suppose you want a partial Person based on the number of remaining elements. Supposing they are still in the same order, you could modify this method to check the validity of the current index for each field:

public List<Person> createObjectsFromStringList(List<String> list) {

    List<person> personList = new Arraylist<>();
    int size = list.size();
    //Now we remove the "-2" from size check because we will handle this ourselves
    for(int x=0; x<size; x+=3) {
        String id = list.get(x); //Obviously valid
        String name = x+1 < size? list.get(x+1) : null;
        String address = x+2 < size? list.get(x+2) : null;
        personList.add(new Person(id, name, address);
    }
    return personList;
}

We're using the ternary operation ? ... : null here, so if we run out of elements we set the associated Person field to null instead of using an out-of-bounds index.


问:
Child nodes doesn't remove on mobile browsers
I make a virtual guide using A-frame in combination with Angular and use next code to remove all hot spots and navigation arrows from the a-entity tag.

```<code>while (this.hotSpotEntity.hasChildNodes()) {
    this.hotSpotEntity.removeChild(this.hotSpotEntity.childNodes[0]);
}

while (this.navigationEntity.hasChildNodes()) {
    this.navigationEntity.removeChild(this.navigationEntity.childNodes[0]);
}
</code>```

This code will remove all elements from the a-entity tags I've defined as global variables. But there is an issue with this code.

P.S.: Can't use databinding because A-frame doesn't support it .

See this first scene below. The arrows and magnifiers are added by the code I've written and are children of the hotspotEntity and navigationEntity.

I've I click on a arrow, the code navigates you to a new scene. But you could see that the arrows and hotspots aren't removed. This are the red striped images. The green circled image is added after navigating.

When you click on the green circled arrow, you're navigating to the next scene. Here you could see that the images from the first sky aren't removed but the images of the second scene are removed.

The bug happens only on mobile browsers (Google Chrome for Android, Samsung Internet) and not on desktop browsers (Firefox, Edge).

Could anyone why this bug occurs only on mobile browsers and how I could solve it?

You could test the tour on this link: http://student.howest.be/hein.pauwelyn-vand1/poppr/aframe/ and full code on this GitHub Gist.

答:
Maybe try something a little different:

```<code>while (this.hotSpotEntity.firstChild) {
   this.hotSpotEntity.removeChild(this.hotSpotEntity.firstChild);
}

while (this.navigationEntity.firstChild) {
    this.navigationEntity.removeChild(this.navigationEntity.firstChild);
}
</code>```

firstChild is a readonly property that will return null if there isn't one. You can use it in the condition because it's truthy when there is a child and falsy when there isn't.

If this works on mobile and fixes the bug, then I don't know why unfortunately. Let me know if this doesn't solve your problem. I'll delete the answer.

Body:
I make a virtual guide using A-frame in combination with Angular and use next code to remove all hot spots and navigation arrows from the a-entity tag.

while (this.hotSpotEntity.hasChildNodes()) {
    this.hotSpotEntity.removeChild(this.hotSpotEntity.childNodes[0]);
}

while (this.navigationEntity.hasChildNodes()) {
    this.navigationEntity.removeChild(this.navigationEntity.childNodes[0]);
}

This code will remove all elements from the a-entity tags I've defined as global variables. But there is an issue with this code.

P.S.: Can't use databinding because A-frame doesn't support it .

See this first scene below. The arrows and magnifiers are added by the code I've written and are children of the hotspotEntity and navigationEntity.

I've I click on a arrow, the code navigates you to a new scene. But you could see that the arrows and hotspots aren't removed. This are the red striped images. The green circled image is added after navigating.

When you click on the green circled arrow, you're navigating to the next scene. Here you could see that the images from the first sky aren't removed but the images of the second scene are removed.

The bug happens only on mobile browsers (Google Chrome for Android, Samsung Internet) and not on desktop browsers (Firefox, Edge).

Could anyone why this bug occurs only on mobile browsers and how I could solve it?

You could test the tour on this link: http://student.howest.be/hein.pauwelyn-vand1/poppr/aframe/ and full code on this GitHub Gist.

Body:
Maybe try something a little different:

while (this.hotSpotEntity.firstChild) {
   this.hotSpotEntity.removeChild(this.hotSpotEntity.firstChild);
}

while (this.navigationEntity.firstChild) {
    this.navigationEntity.removeChild(this.navigationEntity.firstChild);
}

firstChild is a readonly property that will return null if there isn't one. You can use it in the condition because it's truthy when there is a child and falsy when there isn't.

If this works on mobile and fixes the bug, then I don't know why unfortunately. Let me know if this doesn't solve your problem. I'll delete the answer.


问:
Change the default CSS font for uikit
Hoe do you change the default font for uikit? UIKit

The default font is

```<code>"Helvetica Neue",Helvetica,Arial,sans-serif
</code>```

and its set on the html element tag. If i change this font on my custom style in the html tag to something else it doesn't overwrite the changes. I can use important which does change things:

```<code>html {
     font: 'Raleway', sans-serif !important;
}
</code>```

This changes the global font as expected but font-awesome obviously no longer works because the !important is over writing it. Any ideas?

答:
All you need to do is include a custom css file after uikit's css, whether you call uikit from a CDN or locally -

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.18/css/uikit.min.css" />
<link rel="stylesheet" href="/site/templates/css/app.css" />
</code>```

In your app.css do this

```<code>html{
  font-family: 'Raleway', sans-serif;
}
</code>```

and you should be good to go. Font-Awesome should not be affected at all.

Title: Change the default CSS font for uikit

Body:
Hoe do you change the default font for uikit? UIKit

The default font is

"Helvetica Neue",Helvetica,Arial,sans-serif

and its set on the html element tag. If i change this font on my custom style in the html tag to something else it doesn't overwrite the changes. I can use important which does change things:

html {
     font: 'Raleway', sans-serif !important;
}

This changes the global font as expected but font-awesome obviously no longer works because the !important is over writing it. Any ideas?

Body:
All you need to do is include a custom css file after uikit's css, whether you call uikit from a CDN or locally -

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.18/css/uikit.min.css" />
<link rel="stylesheet" href="/site/templates/css/app.css" />

In your app.css do this

html{
  font-family: 'Raleway', sans-serif;
}

and you should be good to go. Font-Awesome should not be affected at all.


问:
Unable to render index.html file from my view folder in angular2
I'm creating a MEAN Stack application where angular has setup in /client folder. I want that when I run npm start command in /client folder it should render index.html file from /views folder, what I'm doing wrong getting this error

Cannot GET /

Folder structure is as follows.

meanApp

----- client (angluar2 setup here but doesn't have an index.html file)

---------- app

----- views

----------index.html

----- routes

----- server.js

Codes in server.js

```<code>var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");

var index =  require('./routes/index');
var tasks = require("./routes/tasks");

var app = express();

//View engines

app.set("views", path.join(__dirname,'views'));

app.set("view engine", 'ejs');

app.engine("html", require("ejs").renderFile);

//Set static folder

app.use(express.static(path.join(__dirname,'client')));

// Body parser

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended:false}));

app.use('/', index);

app.use('/index', index);

app.use('/api', tasks);

//listen

app.listen(3000, function(){

    console.log("Server listing @ 3000");

});
</code>```

答:
```<code>const http = require('http');
fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();

app.set('appPath', 'views');
app.use(express.static(__dirname + '/views'));

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());

app.use('/*', function(req, res, next) {
    res.sendfile(app.get('appPath') + '/index.html');
});

http.createServer(app).listen(3001, function() {
    console.log(`Express server listening on port 3001`);
});

exports = module.exports = app;
</code>```

Body:
I'm creating a MEAN Stack application where angular has setup in /client folder. I want that when I run npm start command in /client folder it should render index.html file from /views folder, what I'm doing wrong getting this error

Cannot GET /

Folder structure is as follows.

meanApp

----- client (angluar2 setup here but doesn't have an index.html file)

---------- app

----- views

----------index.html

----- routes

----- server.js

Codes in server.js

var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");

var index =  require('./routes/index');
var tasks = require("./routes/tasks");

var app = express();

//View engines

app.set("views", path.join(__dirname,'views'));

app.set("view engine", 'ejs');

app.engine("html", require("ejs").renderFile);

//Set static folder

app.use(express.static(path.join(__dirname,'client')));

// Body parser

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({extended:false}));

app.use('/', index);

app.use('/index', index);

app.use('/api', tasks);

//listen

app.listen(3000, function(){

    console.log("Server listing @ 3000");

});


问:
Multiple file uploading is not working in yii2
View:

```<code> <?php echo FileInput::widget([
'model' => $visaDocument,
'attribute' => 'temp_image[]',
'options' => ['multiple' => true]
</code>```

]);
            ?>

Model:

Defined a variable:

```<code>public $temp_image;
</code>```

In rules:

```<code>[['temp_image'], 'file','extensions' => ' pdf, docx, odt, jpg, png','maxFiles' => 4],
</code>```

Created a function:

```<code>public function upload($model, $id) {

    $imageCount = SbhrmVisaDocument::find()->where(['visa_document_id' => $id])->count();

        foreach ($model->temp_image as $file) {
            if($imageCount < 4){

                $image = new SbhrmVisaDocument();
                $image->save();
                $file->saveAs(\Yii::$app->BasePath . '/uploads/' . $file->name);
                $image->visa_document_name = $file->name;
                $image->emp_id = $id;
                $image->save();
            }
            ++$imageCount;
        }

        return true;

}
</code>```

Controller:

```<code>  $visaDocument->temp_image = UploadedFile::getInstances($visaDocument, 'temp_image');
        if(!empty($visaDocument->temp_image)){
        if (!$model->upload($visaDocument,$model->emp_id)) {
            return;

       }

      if($model->validate()){
            $model->save();
           //$this->afterSaveSetting($model);
            Yii::$app->session->setFlash('success','Request Submitted');
            return $this->redirect(\yii\helpers\Url::to(['visa-initiation/my-list']));
        }
    }
</code>```

But when I try to upload multiple files only the last selected one was saved.I just follow the demo http://demos.krajee.com/widget-details/fileinput.

答:
I think you should add

```<code><?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
</code>```

probably that would help.Have you already included that?

Body:
View:

 <?php echo FileInput::widget([
'model' => $visaDocument,
'attribute' => 'temp_image[]',
'options' => ['multiple' => true]

]);
            ?>

Model:

Defined a variable:

public $temp_image;

In rules:

[['temp_image'], 'file','extensions' => ' pdf, docx, odt, jpg, png','maxFiles' => 4],

Created a function:

public function upload($model, $id) {

    $imageCount = SbhrmVisaDocument::find()->where(['visa_document_id' => $id])->count();

        foreach ($model->temp_image as $file) {
            if($imageCount < 4){

                $image = new SbhrmVisaDocument();
                $image->save();
                $file->saveAs(\Yii::$app->BasePath . '/uploads/' . $file->name);
                $image->visa_document_name = $file->name;
                $image->emp_id = $id;
                $image->save();
            }
            ++$imageCount;
        }

        return true;

}

Controller:

  $visaDocument->temp_image = UploadedFile::getInstances($visaDocument, 'temp_image');
        if(!empty($visaDocument->temp_image)){
        if (!$model->upload($visaDocument,$model->emp_id)) {
            return;

       }

      if($model->validate()){
            $model->save();
           //$this->afterSaveSetting($model);
            Yii::$app->session->setFlash('success','Request Submitted');
            return $this->redirect(\yii\helpers\Url::to(['visa-initiation/my-list']));
        }
    }

But when I try to upload multiple files only the last selected one was saved.I just follow the demo http://demos.krajee.com/widget-details/fileinput.

Body:
I think you should add

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

probably that would help.Have you already included that?


问:
Can't generate signed APK in Android Studio, 'java.io.IOException'
I have a problem with generating signed APK in Android Studio. It was working fine few days ago, I dont know what went wrong. I'm getting this error for any project I try to fgenerate signed APK of:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/proguard/release/jars/3/1f/main.jar] (Can't read [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/RealmTransformer/release/folders/1/1/realm(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))

Here is my buildTypes Task:

```<code>buildTypes {
    debug {
        shrinkResources false // This must be first
        minifyEnabled false   // This must be after shrinkResources
        multiDexEnabled true
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules-debug.pro"
    }
    release {
        shrinkResources true
        minifyEnabled true
        useProguard true
        multiDexEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
    }
}
</code>```

Here is the code I've written in proguard file:

```<code>-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-keepattributes Signature
-keepattributes Exceptions
-repackageclasses ''

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.
-keep public class com.android.vending.licensing.ILicensingService

-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry
-keep class com.google.common.cache.LocalCache$ReferenceEntry

-dontnote com.android.vending.licensing.ILicensingService

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class **.R$* {
  public static <fields>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.* { *; }
-keepattributes *Annotation,Signature
-dontwarn in.mylo.pregnancy.baby.app.**
-keep class in.mylo.pregnancy.baby.app.shapeimageview.**{ *; }

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keep class butterknife.*
-keepclasseswithmembernames class * {
 @butterknife.* <methods>; }
-keepclasseswithmembernames class * {
 @butterknife.* <fields>; }

-dontwarn javax.annotation.**
-dontwarn javax.inject.**
-dontwarn sun.misc.Unsafe

-dontwarn java.lang.ClassValue
-dontwarn com.google.j2objc.annotations.Weak
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-dontwarn com.clevertap.android.sdk.**

-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
    public static <fields>;
}

-dontwarn android.support.**

-dontwarn com.google.android.gms.**

-dontwarn com.fasterxml.**
-dontwarn okio.**
-dontwarn com.caverock.**
-dontwarn com.github.siyamed.shapeimageview.**

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-dontwarn sun.misc.Unsafe
-dontwarn com.octo.android.robospice.retrofit.RetrofitJackson**
-dontwarn retrofit.appengine.UrlFetchClient
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keep class com.google.gson.** { *; }
-keep class com.google.inject.** { *; }
-keep class org.apache.http.** { *; }
-keep class org.apache.james.mime4j.** { *; }
-keep class javax.inject.** { *; }
-keep class retrofit.** { *; }
-keep class retrofit2.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn retrofit.**
-dontwarn retrofit2.**

-dontwarn sun.misc.**

-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}

-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   long producerNode;
   long consumerNode;
}

-keep class in.mylo.pregnancy.baby.app.retrofit.** { *; }

-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }

-keepnames public class * extends io.realm.RealmObject
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.** { *; }
-dontwarn javax.**
-dontwarn io.realm.**

-keepnames public class * extends io.realm.RealmObject

-dontwarn com.google.android.gms.location.**
-dontwarn com.google.android.gms.gcm.**
-dontwarn com.google.android.gms.iid.**

-keep class com.google.android.gms.gcm.** { *; }
-keep class com.google.android.gms.iid.** { *; }
-keep class com.google.android.gms.location.** { *; }

-keep class com.moe.pushlibrary.activities.** { *; }
-keep class com.moengage.locationlibrary.GeofenceIntentService
-keep class com.moe.pushlibrary.InstallReceiver
-keep class com.moengage.push.MoEPushWorker
-keep class com.moe.pushlibrary.providers.MoEProvider
-keep class com.moengage.receiver.MoEInstanceIDListener
-keep class com.moengage.worker.MoEGCMListenerService
-keep class com.moe.pushlibrary.models.** { *;}
-keep class com.moengage.core.GeoTask
-keep class com.moengage.location.GeoManager
-keep class com.moengage.inapp.InAppManager
-keep class com.moengage.push.PushManager
-keep class com.moengage.inapp.InAppController

-dontwarn com.moengage.location.GeoManager
-dontwarn com.moengage.core.GeoTask
-dontwarn com.moengage.receiver.*
-dontwarn com.moengage.worker.*
-dontwarn com.moengage.inapp.ViewEngine

-keep class com.delight.**  { *; }

-dontwarn com.google.android.gms.location.**
-keep class com.moe.** { *; }
-keep class com.moengage.** { *; }
-keep class com.delight.** { *; }

-keep class com.google.android.gms.ads.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn android.databinding.**
-keep class android.databinding.** { *; }
</code>```

Any help appreciated, thanks in advance.

答:
Did you tried to disbale proguard for release build?

```<code>release {
    shrinkResources false
    minifyEnabled false
    useProguard false
    multiDexEnabled true
    proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
}
</code>```

if this works, you should fix our proguard config

Body:
I have a problem with generating signed APK in Android Studio. It was working fine few days ago, I dont know what went wrong. I'm getting this error for any project I try to fgenerate signed APK of:

Warning:Exception while processing task java.io.IOException: Can't write [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/proguard/release/jars/3/1f/main.jar] (Can't read [/Users/bhaveshmisri/Downloads/littleone-dagger-mvp/app/build/intermediates/transforms/RealmTransformer/release/folders/1/1/realm(;;;;;;**.class)] (Can't read [com] (Can't read [crashlytics] (Can't read [android] (Can't read [answers] (Can't read [shim] (Can't read [R.class] (Duplicate zip entry [com/crashlytics/android/answers/shim/R.class]))))))))

Here is my buildTypes Task:

buildTypes {
    debug {
        shrinkResources false // This must be first
        minifyEnabled false   // This must be after shrinkResources
        multiDexEnabled true
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules-debug.pro"
    }
    release {
        shrinkResources true
        minifyEnabled true
        useProguard true
        multiDexEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
    }
}

Here is the code I've written in proguard file:

-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
-dontpreverify
-verbose
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-keepattributes Signature
-keepattributes Exceptions
-repackageclasses ''

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.
-keep public class com.android.vending.licensing.ILicensingService

-keep class com.google.common.collect.MapMakerInternalMap$ReferenceEntry
-keep class com.google.common.cache.LocalCache$ReferenceEntry

-dontnote com.android.vending.licensing.ILicensingService

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class **.R$* {
  public static <fields>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.* { *; }
-keepattributes *Annotation,Signature
-dontwarn in.mylo.pregnancy.baby.app.**
-keep class in.mylo.pregnancy.baby.app.shapeimageview.**{ *; }

-keep class android.support.v4.app.** { *; }
-keep interface android.support.v4.app.** { *; }
-keep interface com.actionbarsherlock.** { *; }

-keep class butterknife.*
-keepclasseswithmembernames class * {
 @butterknife.* <methods>; }
-keepclasseswithmembernames class * {
 @butterknife.* <fields>; }

-dontwarn javax.annotation.**
-dontwarn javax.inject.**
-dontwarn sun.misc.Unsafe

-dontwarn java.lang.ClassValue
-dontwarn com.google.j2objc.annotations.Weak
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keep public class * implements com.bumptech.glide.module.GlideModule
-keep public enum com.bumptech.glide.load.resource.bitmap.ImageHeaderParser$** {
  **[] $VALUES;
  public *;
}

-dontwarn com.firebase.**
-dontnote com.firebase.client.core.GaePlatform

-keep class com.firebase.** { *; }

-keepnames class com.fasterxml.jackson.** { *; }
-keepnames class javax.servlet.** { *; }
-keepnames class org.ietf.jgss.** { *; }

-dontwarn com.clevertap.android.sdk.**

-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontnote okhttp3.**

-keep class sun.misc.Unsafe { *; }
-dontwarn java.nio.file.*
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement

-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keepclassmembers class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator CREATOR;
}
-keepclassmembers class **.R$* {
    public static <fields>;
}

-dontwarn android.support.**

-dontwarn com.google.android.gms.**

-dontwarn com.fasterxml.**
-dontwarn okio.**
-dontwarn com.caverock.**
-dontwarn com.github.siyamed.shapeimageview.**

-dontwarn retrofit.**
-keep class retrofit.** { *; }
-dontwarn sun.misc.Unsafe
-dontwarn com.octo.android.robospice.retrofit.RetrofitJackson**
-dontwarn retrofit.appengine.UrlFetchClient
-keepattributes Signature
-keepattributes Exceptions
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keep class com.google.gson.** { *; }
-keep class com.google.inject.** { *; }
-keep class org.apache.http.** { *; }
-keep class org.apache.james.mime4j.** { *; }
-keep class javax.inject.** { *; }
-keep class retrofit.** { *; }
-keep class retrofit2.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.http.AndroidHttpClient
-dontwarn retrofit.**
-dontwarn retrofit2.**

-dontwarn sun.misc.**

-keepclassmembers class rx.internal.util.unsafe.*ArrayQueue*Field* {
   long producerIndex;
   long consumerIndex;
}

-keepclassmembers class rx.internal.util.unsafe.BaseLinkedQueueProducerNodeRef {
   long producerNode;
   long consumerNode;
}

-keep class in.mylo.pregnancy.baby.app.retrofit.** { *; }

-keep interface org.parceler.Parcel
-keep @org.parceler.Parcel class * { *; }
-keep class **$$Parcelable { *; }

-keepnames public class * extends io.realm.RealmObject
-keep @io.realm.annotations.RealmModule class *
-keep class io.realm.** { *; }
-dontwarn javax.**
-dontwarn io.realm.**

-keepnames public class * extends io.realm.RealmObject

-dontwarn com.google.android.gms.location.**
-dontwarn com.google.android.gms.gcm.**
-dontwarn com.google.android.gms.iid.**

-keep class com.google.android.gms.gcm.** { *; }
-keep class com.google.android.gms.iid.** { *; }
-keep class com.google.android.gms.location.** { *; }

-keep class com.moe.pushlibrary.activities.** { *; }
-keep class com.moengage.locationlibrary.GeofenceIntentService
-keep class com.moe.pushlibrary.InstallReceiver
-keep class com.moengage.push.MoEPushWorker
-keep class com.moe.pushlibrary.providers.MoEProvider
-keep class com.moengage.receiver.MoEInstanceIDListener
-keep class com.moengage.worker.MoEGCMListenerService
-keep class com.moe.pushlibrary.models.** { *;}
-keep class com.moengage.core.GeoTask
-keep class com.moengage.location.GeoManager
-keep class com.moengage.inapp.InAppManager
-keep class com.moengage.push.PushManager
-keep class com.moengage.inapp.InAppController

-dontwarn com.moengage.location.GeoManager
-dontwarn com.moengage.core.GeoTask
-dontwarn com.moengage.receiver.*
-dontwarn com.moengage.worker.*
-dontwarn com.moengage.inapp.ViewEngine

-keep class com.delight.**  { *; }

-dontwarn com.google.android.gms.location.**
-keep class com.moe.** { *; }
-keep class com.moengage.** { *; }
-keep class com.delight.** { *; }

-keep class com.google.android.gms.ads.** { *; }

-keep class com.facebook.** {
   *;
}

-dontwarn android.databinding.**
-keep class android.databinding.** { *; }

Any help appreciated, thanks in advance.

Body:
Did you tried to disbale proguard for release build?

release {
    shrinkResources false
    minifyEnabled false
    useProguard false
    multiDexEnabled true
    proguardFiles getDefaultProguardFile('proguard-android.txt'), "proguard-rules.pro"
}

if this works, you should fix our proguard config


问:
Connecting Spark to Multiple Mongo Collections
I have the following MongoDB Collections : employee and details.

Now I have a requirement where I have to get documents from both collections into spark to analyze data.

I tried below code but it seems not working

```<code>SparkConf conf = new SparkConf().setAppName("DBConnection").setMaster("local[*]")
                .set("spark.app.id","MongoSparkExample")
                .set("spark.mongodb.input.uri","mongodb://localhost/Emp.employee")
                .set("spark.executor.memory", "6g");

SparkSession session = SparkSession.builder().appName("Member Log")
                .config(conf).getOrCreate();

SparkConf dailyconf = new SparkConf().setAppName("DBConnection").setMaster("local[*]")
                .set("spark.app.id","Mongo Two Example")
                .set("spark.mongodb.input.uri","mongodb://localhost/Emp.details");

SparkSession mongosession = SparkSession.builder().appName("Daily Log")
                .config(dailyconf).getOrCreate();
</code>```

Any pointers would be highly appreciated.

答:
I fixed this issue by adding below code </p>

```<code>JavaSparkContext newcontext = new JavaSparkContext(session.sparkContext());
Map<String, String> readOverrides = new HashMap<String, String>();
readOverrides.put("collection", "details");
readOverrides.put("readPreference.name", "secondaryPreferred");
ReadConfig readConfig = ReadConfig.create(newcontext).withOptions(readOverrides);
MongoSpark.load(newcontext,readConfig);
</code>```

Body:
I have the following MongoDB Collections : employee and details.

Now I have a requirement where I have to get documents from both collections into spark to analyze data.

I tried below code but it seems not working

SparkConf conf = new SparkConf().setAppName("DBConnection").setMaster("local[*]")
                .set("spark.app.id","MongoSparkExample")
                .set("spark.mongodb.input.uri","mongodb://localhost/Emp.employee")
                .set("spark.executor.memory", "6g");

SparkSession session = SparkSession.builder().appName("Member Log")
                .config(conf).getOrCreate();

SparkConf dailyconf = new SparkConf().setAppName("DBConnection").setMaster("local[*]")
                .set("spark.app.id","Mongo Two Example")
                .set("spark.mongodb.input.uri","mongodb://localhost/Emp.details");

SparkSession mongosession = SparkSession.builder().appName("Daily Log")
                .config(dailyconf).getOrCreate();

Any pointers would be highly appreciated.

Body:
I fixed this issue by adding below code

JavaSparkContext newcontext = new JavaSparkContext(session.sparkContext());
Map<String, String> readOverrides = new HashMap<String, String>();
readOverrides.put("collection", "details");
readOverrides.put("readPreference.name", "secondaryPreferred");
ReadConfig readConfig = ReadConfig.create(newcontext).withOptions(readOverrides);
MongoSpark.load(newcontext,readConfig);


问:
How to change RichTextBox text depending on a string in C#
So, I am trying to build a RichTextBox which allows me to write code into it and changes the color of the keywords based on C# programming language.

First of all, I've declared this:

```<code>string[] palavraschave = { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default",
     "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto",
     "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",
     "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc",
     "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort",
     "using", "virtual", "void", "volatile", "while", "add", "alias", "ascending", "descending", "dynamic", "from", "get", "global", "group",
     "into", "join", "let", "orderby", "partial", "remove", "select", "set", "value", "var", "where", "yield" };
</code>```

Then I have a method to check the RichTextBox:

```<code>private void CheckRichTextBox(string word, Color color, int startIndex)
{
    if (this.rchBoxText.Text.Contains(word))
    {
        int index = -1;
        int selectStart = this.rchBoxText.SelectionStart;

        while ((index = this.rchBoxText.Text.IndexOf(word, (index + 1))) != -1)
        {
            this.rchBoxText.Select((index + startIndex), word.Length);
            this.rchBoxText.SelectionColor = cor;
            this.rchBoxText.Select(selectStart, 0);
            this.rchBoxText.SelectionColor = Color.Black;
        }
    }
}
</code>```

To call it, I will use this piece of code into the RichTextBox TextChanged event:

```<code>this.CheckRichTextBox(palavraschave.ToString(), Color.Blue, 0);
</code>```

But it does not work. What am I doing wrong?

答:
You would need to do a for each on the array of words and call your procedure for each word rather calling toString. Or pass the array to your function and loop in there.

But as other people have said there are plenty of solutions for this type of thing already out there.

Body:
So, I am trying to build a RichTextBox which allows me to write code into it and changes the color of the keywords based on C# programming language.

First of all, I've declared this:

string[] palavraschave = { "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default",
     "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto",
     "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out",
     "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc",
     "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort",
     "using", "virtual", "void", "volatile", "while", "add", "alias", "ascending", "descending", "dynamic", "from", "get", "global", "group",
     "into", "join", "let", "orderby", "partial", "remove", "select", "set", "value", "var", "where", "yield" };

Then I have a method to check the RichTextBox:

private void CheckRichTextBox(string word, Color color, int startIndex)
{
    if (this.rchBoxText.Text.Contains(word))
    {
        int index = -1;
        int selectStart = this.rchBoxText.SelectionStart;

        while ((index = this.rchBoxText.Text.IndexOf(word, (index + 1))) != -1)
        {
            this.rchBoxText.Select((index + startIndex), word.Length);
            this.rchBoxText.SelectionColor = cor;
            this.rchBoxText.Select(selectStart, 0);
            this.rchBoxText.SelectionColor = Color.Black;
        }
    }
}

To call it, I will use this piece of code into the RichTextBox TextChanged event:

this.CheckRichTextBox(palavraschave.ToString(), Color.Blue, 0);

But it does not work. What am I doing wrong?


问:
jQuery - ensure IDs are unique in inserted markup
I have the following markup:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
</code>```

I am attempting to insert the html contents of this markup after itself, using the jQuery html() and after() methods:

```<code>var newSection = $('#section').html();
$('#section').after(newSection);
</code>```

So I'm ending up with something like this:

```<code><div id="section">
    <input type="text" id="myInput">
</div>
<input type="text" id="myInput">
</code>```

Is there a way I can ensure the IDs of my inputs are unique? I would prefer something like "myInput2" for the input that has been inserted. Thank you.

答:
You can use $(selector).length to check if an element exist. Then you could use a while loop to increment the number on the end if it does.

```<code>var i = 0;
selector = "#section";
while($(selector + i).length) {
    i++;
}
// selector is now a unique value. append it to the page
</code>```

Body:
I have the following markup:

    <input type="text" id="myInput">

I am attempting to insert the html contents of this markup after itself, using the jQuery html() and after() methods:

var newSection = $('#section').html();
$('#section').after(newSection);

So I'm ending up with something like this:

    <input type="text" id="myInput">

<input type="text" id="myInput">

Is there a way I can ensure the IDs of my inputs are unique? I would prefer something like "myInput2" for the input that has been inserted. Thank you.

Body:
You can use $(selector).length to check if an element exist. Then you could use a while loop to increment the number on the end if it does.

var i = 0;
selector = "#section";
while($(selector + i).length) {
    i++;
}
// selector is now a unique value. append it to the page


问:
How do I extract named groups with unknown order with a regular expression in Java?
Let's say I want to extract foo\d{2} and bar\d{2} as named groups (say, foo and bar) from strings that might contain one or two of them in any order, e.g.:

```<code>hello foo33 world bar12
bar66 something foo14
this one only has bar45
this one has neither
</code>```

Is there a way to do it in with a single regular expression in Java?

It would be best if the solution could be generalised to 3+ named groups.

答:
you can use (foo|bar)\\d{2} with find method to get all required values

(foo|bar)\\d{2} either match foo

|bar : or bar

\\d{2} : match exactly 2 digits

Code

```<code>    String s="hello foo33 world bar12\n"+
            "bar66 something foo14\n"+
            "this one only has bar45\n"+
            "this one has neither";
    Pattern pattern = Pattern.compile("(foo|bar)\\d{2}");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
</code>```

output :

```<code>foo33
bar12
bar66
foo14
bar45
</code>```

Body:
Let's say I want to extract foo\d{2} and bar\d{2} as named groups (say, foo and bar) from strings that might contain one or two of them in any order, e.g.:

hello foo33 world bar12
bar66 something foo14
this one only has bar45
this one has neither

Is there a way to do it in with a single regular expression in Java?

It would be best if the solution could be generalised to 3+ named groups.

Body:
you can use (foo|bar)\\d{2} with find method to get all required values

(foo|bar)\\d{2} either match foo

|bar : or bar

\\d{2} : match exactly 2 digits

Code

    String s="hello foo33 world bar12\n"+
            "bar66 something foo14\n"+
            "this one only has bar45\n"+
            "this one has neither";
    Pattern pattern = Pattern.compile("(foo|bar)\\d{2}");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

output :

foo33
bar12
bar66
foo14
bar45


答:
Consider using something like ColorCode; this work has already been done well, and likely more efficiently.
To do this, add the NuGet package, then replace your RichTextBox with a WebBrowser control, and pass your source text into the colorizer:

```<code>using ColorCode;
[...]
webBrowser1.DocumentText = new CodeColorizer().Colorize(mySourceText, Languages.CSharp);
</code>```

For info on adding NuGet packages, see here.

Alternatively, if you are looking for a syntax-highlighting text editor, you could use Scintilla.

First add the NuGet package called jacobslusser.ScintillaNET, and this time there's an extra step to make the control appear in the toolbox; right-click the Windows Forms toolbox, select 'Choose Items', then 'Browse', and browse to the Scintilla DLL.
In my project this is here;

packages\jacobslusser.ScintillaNET.3.6.3\lib\net40\ScintillaNET.dll

That will add the 'Scintilla' control to the toolbox, and you can drag this to your form.  Finally, in the form's Load event, add the following 'recipe' to make it look similar to Visual Studio's syntax highlighting:

```<code>private void Form1_Load(object sender, EventArgs e)
{
    // Configuring the default style with properties
    // we have common to every lexer style saves time.
    scintilla1.StyleResetDefault();
    scintilla1.Styles[Style.Default].Font = "Consolas";
    scintilla1.Styles[Style.Default].Size = 10;
    scintilla1.StyleClearAll();

    // Configure the CPP (C#) lexer styles
    scintilla1.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
    scintilla1.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
    scintilla1.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
    scintilla1.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
    scintilla1.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
    scintilla1.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
    scintilla1.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
    scintilla1.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
    scintilla1.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
    scintilla1.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
    scintilla1.Lexer = Lexer.Cpp;

    // Set the keywords
    scintilla1.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
    scintilla1.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

}
</code>```

More about Scintilla here.  Recipe from here.

Title: How to change RichTextBox text depending on a string in C#

Body:
Consider using something like ColorCode; this work has already been done well, and likely more efficiently.
To do this, add the NuGet package, then replace your RichTextBox with a WebBrowser control, and pass your source text into the colorizer:

using ColorCode;
[...]
webBrowser1.DocumentText = new CodeColorizer().Colorize(mySourceText, Languages.CSharp);

For info on adding NuGet packages, see here.

Alternatively, if you are looking for a syntax-highlighting text editor, you could use Scintilla.

First add the NuGet package called jacobslusser.ScintillaNET, and this time there's an extra step to make the control appear in the toolbox; right-click the Windows Forms toolbox, select 'Choose Items', then 'Browse', and browse to the Scintilla DLL.
In my project this is here;

packages\jacobslusser.ScintillaNET.3.6.3\lib\net40\ScintillaNET.dll

That will add the 'Scintilla' control to the toolbox, and you can drag this to your form.  Finally, in the form's Load event, add the following 'recipe' to make it look similar to Visual Studio's syntax highlighting:

private void Form1_Load(object sender, EventArgs e)
{
    // Configuring the default style with properties
    // we have common to every lexer style saves time.
    scintilla1.StyleResetDefault();
    scintilla1.Styles[Style.Default].Font = "Consolas";
    scintilla1.Styles[Style.Default].Size = 10;
    scintilla1.StyleClearAll();

    // Configure the CPP (C#) lexer styles
    scintilla1.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
    scintilla1.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
    scintilla1.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
    scintilla1.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
    scintilla1.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
    scintilla1.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
    scintilla1.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
    scintilla1.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
    scintilla1.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
    scintilla1.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
    scintilla1.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
    scintilla1.Lexer = Lexer.Cpp;

    // Set the keywords
    scintilla1.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
    scintilla1.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

}

More about Scintilla here.  Recipe from here.


问:
replace specific link to *******
using php or javascript or ajax
how to replace specific link to *

http://www.google.com/.
to
http://www.****

答:
I'm assuming you mean something like (in Javascript):

```<code>
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
 if (links[i].href == "http://www.google.com/") links[i].href = "http://www.blather.blorg/"
}
</code>```

Tested and works on Firefox 3.

Title: replace specific link to *******

Body:
I'm assuming you mean something like (in Javascript):

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
 if (links[i].href == "http://www.google.com/") links[i].href = "http://www.blather.blorg/"
}

Tested and works on Firefox 3.