问:
How to find scala java.util.Date difference in minutes?
```<code>scala> val dates = filtering1.map(x => (format.parse(x._1),format.parse(x._2)))
dates: org.apache.spark.rdd.RDD[(java.util.Date, java.util.Date)] = MapPartitionsRDD[7] at map at <console>:34
</code>```

stores below values

```<code>scala> dates.collect
res0: Array[(java.util.Date, java.util.Date)] = Array((Sat Jun 30 23:42:00 IST 2018,Thu Jul 04 15:10:00 IST 2019), (Sat Jun 30 23:37:00 IST 2018,Sun Jul 01 14:44:00 IST 2018), (Sat Jun 30 23:13:00 IST 2018,Sun Feb 28 23:34:00 IST 219), (Sat Jun 30 22:58:00 IST 2018,Mon Jul 01 18:22:00 IST 2019), (Sat Jun 30 22:36:00 IST 2018,Mon Jul 01 16:01:00 IST 2019), (Sat Jun 30 21:53:00 IST 2018,Tue Jul 02 10:36:00 IST 2019), (Sat Jun 30 21:42:00 IST 2018,Sun Jun 30 23:25:00 IST 2019), (Sat Jun 30 21:36:00 IST 2018,Mon Jul 01 16:47:00 IST 2019), (Sat Jun 30 21:16:00 IST 2018,Mon Jul 01 18:18:00 IST 2019), (Sat Jun 30 21:10:00 IST 2018,Thu Jul 04 12:25:00 IST 2019), (Sat Jun 30 21:02:00 IST 2018,Sat Dec 01 17:29:00 IST 2018), (Sat Jun 30 20:54:00 IST 2018,Mon Jul 01 15:51:00 IST 2019), (Sat Jun 30 ...
</code>```

But how to perform operation so the difference in dates, is grouped together, gives value in minutes.

I have command , it does not give me desired output, what changes should be made?

val time_diff = dates.map(x => (x._2.getTime()-x._1.getTime())/(60*1000)%60)

what is (60*1000)%60) values represent?

答:
getTime gives milliseconds, so dividing by 1000.0 gives seconds and dividing by 1000.0*60 gives minutes. Be aware that dividing a Long by an Int gives you another Long, so you are truncating the resulting minutes to the next lowest integer. Adding modulus 60, % 60, simply wraps the minutes to 0-59, so if you had a 90 minutes difference, that would be 1 hour 30 minutes, and the result of your calculation would just be 30.

```<code>val t = System.currentTimeMillis
val x = new java.util.Date(t)
val y = new java.util.Date(t + 10000) // ten seconds later
(y.getTime - x.getTime) / (1000.0 * 60) // 0.167
(y.getTime - x.getTime) / (1000   * 60) // 0 !
</code>```

Body:
scala> val dates = filtering1.map(x => (format.parse(x._1),format.parse(x._2)))
dates: org.apache.spark.rdd.RDD[(java.util.Date, java.util.Date)] = MapPartitionsRDD[7] at map at <console>:34

stores below values

scala> dates.collect
res0: Array[(java.util.Date, java.util.Date)] = Array((Sat Jun 30 23:42:00 IST 2018,Thu Jul 04 15:10:00 IST 2019), (Sat Jun 30 23:37:00 IST 2018,Sun Jul 01 14:44:00 IST 2018), (Sat Jun 30 23:13:00 IST 2018,Sun Feb 28 23:34:00 IST 219), (Sat Jun 30 22:58:00 IST 2018,Mon Jul 01 18:22:00 IST 2019), (Sat Jun 30 22:36:00 IST 2018,Mon Jul 01 16:01:00 IST 2019), (Sat Jun 30 21:53:00 IST 2018,Tue Jul 02 10:36:00 IST 2019), (Sat Jun 30 21:42:00 IST 2018,Sun Jun 30 23:25:00 IST 2019), (Sat Jun 30 21:36:00 IST 2018,Mon Jul 01 16:47:00 IST 2019), (Sat Jun 30 21:16:00 IST 2018,Mon Jul 01 18:18:00 IST 2019), (Sat Jun 30 21:10:00 IST 2018,Thu Jul 04 12:25:00 IST 2019), (Sat Jun 30 21:02:00 IST 2018,Sat Dec 01 17:29:00 IST 2018), (Sat Jun 30 20:54:00 IST 2018,Mon Jul 01 15:51:00 IST 2019), (Sat Jun 30 ...

But how to perform operation so the difference in dates, is grouped together, gives value in minutes.

I have command , it does not give me desired output, what changes should be made?

val time_diff = dates.map(x => (x._2.getTime()-x._1.getTime())/(60*1000)%60)

what is (60*1000)%60) values represent?

Body:
getTime gives milliseconds, so dividing by 1000.0 gives seconds and dividing by 1000.0*60 gives minutes. Be aware that dividing a Long by an Int gives you another Long, so you are truncating the resulting minutes to the next lowest integer. Adding modulus 60, % 60, simply wraps the minutes to 0-59, so if you had a 90 minutes difference, that would be 1 hour 30 minutes, and the result of your calculation would just be 30.

val t = System.currentTimeMillis
val x = new java.util.Date(t)
val y = new java.util.Date(t + 10000) // ten seconds later
(y.getTime - x.getTime) / (1000.0 * 60) // 0.167
(y.getTime - x.getTime) / (1000   * 60) // 0 !


来源: stackexchange

问:
JSX adding attribute with no value with conditional statement
So in JSX I know how I can use an conditional on class names etc or where the attribute has a value.

So if I'm doing class="something" or style="something" etc. The issue I'm having is i'm unsure how I'd do a conditional when adding the hidden attribute.

Example;

```<code>  className={classNames({
    'hidden': true,
    'visible': props.showAll,
  })}
</code>```

This will add a class depending on the value of showAll.

But the hidden attribute is literally just
this text is hidden
.

How would I go about adding a conditional into my JSX react component that renders an attribute but no value?

答:
Simply try with:

```<code><p hidden={!showAll}>
</code>```

Attribute hidden with no value is concidered as true, so you can easily pass a boolean value.

ContentLicense: CC BY-SA 3.0

Body:
So in JSX I know how I can use an conditional on class names etc or where the attribute has a value.

So if I'm doing class="something" or style="something" etc. The issue I'm having is i'm unsure how I'd do a conditional when adding the hidden attribute.

Example;

  className={classNames({
    'hidden': true,
    'visible': props.showAll,
  })}

This will add a class depending on the value of showAll.

But the hidden attribute is literally just
this text is hidden
.

How would I go about adding a conditional into my JSX react component that renders an attribute but no value?

Body:
Simply try with:

<p hidden={!showAll}>

Attribute hidden with no value is concidered as true, so you can easily pass a boolean value.


问:
SQL db2 query on ambiguity
Is there away I use the column name as it is while I select and solve the ambiguity issue starting from and where or join

e.g

```<code>Select account,currency from acc acc
Join card card on acc.account=card.prmaccount
</code>```

In this query 'currency' column is available in both the tables, so 'currency' is ambiguous in the select-list.

Problem:

Account and currency is hard coded in program so I cannot
Use Alais name. But I can write my join or any other
Starting at the 'from' clause via the front end tool.

Is there any way to do this

Select account,currency —- hardcoded in program
From acc acc onwards -- i can write my own using front end

答:
```<code>Select account, currency from acc
where account in (select prmaccount from card)
</code>```

For a query that simple the execution plan should be identical to the one with the explicit join.

Title: SQL db2 query on ambiguity

Body:
Is there away I use the column name as it is while I select and solve the ambiguity issue starting from and where or join

e.g

Select account,currency from acc acc
Join card card on acc.account=card.prmaccount

In this query 'currency' column is available in both the tables, so 'currency' is ambiguous in the select-list.

Problem:

Account and currency is hard coded in program so I cannot
Use Alais name. But I can write my join or any other
Starting at the 'from' clause via the front end tool.

Is there any way to do this

Select account,currency —- hardcoded in program
From acc acc onwards -- i can write my own using front end

Body:
Select account, currency from acc
where account in (select prmaccount from card)

For a query that simple the execution plan should be identical to the one with the explicit join.


问:
How can I make sharedpreferences in Custom Adapter get the latest values of my ArrayList?
I use Volley in the onCreate of my Activity which gets a string on my server, then I convert this string to an arraylist,checkedContactsAsArrayList, and I pass it over to my custom adapter using sharedpreferences, which does stuff with the arraylist in the listview.

But the custom adapter keeps getting the previous arraylist in sharedpreferences, not the one I've just got from the server. The Volley call is too late or something - I can see in logcat the latest values are put after they are got, if you know what I mean.

For example:

```<code>VolleyCall 1 putString: 1,2,3
VolleyCall 2 putString: 4,5,6
VolleyCall 3 putString: 7,8,9

Custom Adapter 1 getString: gets values of the last time app was used
Custom Adapter 2 getString: 1,2,3
Custom Adapter 3 getString: 4,5,6
</code>```

Any idea how to fix this? I could try doing the Volley call in the getView of my custom adapter but I've read on Stackoverflow that's bad practice.

Here are the relvant parts of my code - I've slimmed it down a bit, as there's a lot of stuff in there irrelevant to this issue.

Here's the code of my activity, ViewContact:

```<code>public class ViewContact extends AppCompatActivity implements android.widget.CompoundButton.OnCheckedChangeListener  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_view_contact);

        //selectPhoneContacts is an empty array list that will hold our SelectPhoneContact info
        selectPhoneContacts = new ArrayList<SelectPhoneContact>();

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

        StringRequest stringRequest = new StringRequest(Request.Method.POST, ViewContact_URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {

                        //toast the response of ViewContact.php, which has been converted to a
                        //JSON object by the Php file with JSON encode
                        Toast.makeText(ViewContact.this, "OnResponse is" + response, Toast.LENGTH_LONG).show();
                        System.out.println("ViewContact: And the response is " + response);

                        try {

                            //checkedContacts is a String
                            String checkedContacts = responseObject.getString("checkedcontacts");

                            //convert the checkedContacts string to an arraylist

                            checkedContactsAsArrayList = new ArrayList<String>(Arrays.asList(checkedcontacts.split(",")));
                            System.out.println("ViewContact: checkedContactsAsArrayList is " + checkedContactsAsArrayList);

                            //we want to bring the checkedContactsAsArrayList array list to our SelectPhoneContactAdapter.
                            // It looks like Shared Preferences
                            //only works easily with strings so best way to bring the array list in Shared Preferences is with
                            //Gson.
                            //Here, we PUT the arraylist into the sharedPreferences

                    SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
                    SharedPreferences.Editor editorcheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.edit();
                    Gson gsoncheckedContactsAsArrayList = new Gson();
                    String jsoncheckedContactsAsArrayList = gsoncheckedContactsAsArrayList.toJson(checkedContactsAsArrayList);
                    editorcheckedContactsAsArrayList.putString("checkedContactsAsArrayList", jsoncheckedContactsAsArrayList);
                    editorcheckedContactsAsArrayList.commit();
                    System.out.println("ViewContact: jsoncheckedContactsAsArrayList is " + jsoncheckedContactsAsArrayList);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }

                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(ViewContact.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                //we are posting review_id into our ViewContact.php file, which
                //we get when a row is clicked in populistolistview
                //to get matching details
                params.put("review_id", review_id);
                return params;

            }

        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        //checkBoxforContact.setChecked(true);

    }

    //******for the phone contacts in the listview

    // Load data in background
    class LoadContact extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            //we want to delete the old selectContacts from the listview when the Activity loads
            //because it may need to be updated and we want the user to see the updated listview,
            //like if the user adds new names and numbers to their phone contacts.
            selectPhoneContacts.clear();

                SelectPhoneContact selectContact = new SelectPhoneContact();

                selectContact.setName(phoneNameofContact);

            }

            return null;

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            adapter = new SelectPhoneContactAdapter(selectPhoneContacts, ViewContact.this,0);

            listView.setAdapter(adapter);

            adapter.notifyDataSetChanged();

        }
    }

    @Override
    protected void onResume() {

        super.onResume();

        // getPrefs();

        ViewContact.LoadContact loadContact = new ViewContact.LoadContact();

        loadContact.execute();

        Toast.makeText(ViewContact.this, "resuming!", Toast.LENGTH_SHORT).show();

    }

}
</code>```

And my custom adapter, SelectPhoneContactAdapter :

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

//define a list made out of SelectPhoneContacts and call it theContactsList
public List<SelectPhoneContact> theContactsList;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectPhoneContact> arraylist;
Context _c;
ArrayList<String> MatchingContactsAsArrayList;
ArrayList<String> checkedContactsAsArrayList;
ArrayList <String> allNamesofContacts;
String contactToCheck;
//we will run through different logic in this custom adapter based on the activity that is passed to it
private int whichactivity;

String phoneNumberofContact;
String[] phoneNumberofContactStringArray;
String ContactsString;

Intent intent;

public SelectPhoneContactAdapter(final List<SelectPhoneContact> selectPhoneContacts, Context context, int activity) {
    theContactsList = selectPhoneContacts;
    _c = context;
    this.arraylist = new ArrayList<SelectPhoneContact>();
    this.arraylist.addAll(theContactsList);
    whichactivity = activity;

    //we are fetching the array list checkedContactsAsArrayList, created in ViewContact.
    //with this we will put a tick in the checkboxes of contacts the review is being shared with

    SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(_c);
    Gson gsoncheckedContactsAsArrayList = new Gson();
    String jsoncheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.getString("checkedContactsAsArrayList", "");
    Type type2 = new TypeToken<ArrayList<String>>() {
    }.getType();
    checkedContactsAsArrayList = gsoncheckedContactsAsArrayList.fromJson(jsoncheckedContactsAsArrayList, type2);
    System.out.println("SelectPhoneContactAdapter checkedContactsAsArrayList :" + checkedContactsAsArrayList);

                                 }
}

@Override
public int getCount() {
    return arraylist.size();
}

@Override
public Object getItem(int i) {
    return arraylist.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}

static class ViewHolder {
    //In each cell in the listview show the items you want to have
    //Having a ViewHolder caches our ids, instead of having to call and load each one again and again
    TextView title, phone;
    CheckBox check;
    Button invite;
}

@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {

    //this is the SelectPhoneContact object; consists of textboxes, buttons, checkbox
    final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);

    ViewHolder holder = null;

    if (convertView == null) {

        //if there is nothing there (if it's null) inflate the view with the layout
        LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = li.inflate(R.layout.phone_inflate_listview, null);

        holder = new ViewHolder();
        //So, for example, title is cast to the name id, in phone_inflate_listview,
        //phone is cast to the id called no etc
        holder.title = (TextView) convertView.findViewById(R.id.name);
        holder.phone = (TextView) convertView.findViewById(R.id.no);
        holder.invite = (Button)  convertView.findViewById(R.id.btnInvite);
        holder.check = (CheckBox) convertView.findViewById(R.id.checkBoxContact);

        convertView.setTag(holder);

    } else {

        holder = (ViewHolder) convertView.getTag();

    }

    //in the listview for contacts, set the name
    holder.title.setText(data.getName());

    //in the listview for contacts, set the number
    holder.phone.setText(data.getPhone());

    holder.check.setTag(data);

    return convertView;

    }

}
</code>```

答:
Call this: loadContact.execute();
After you call .commit();

```<code>ViewContact.LoadContact loadContact = new ViewContact.LoadContact();
loadContact.execute();
</code>```

Body:
I use Volley in the onCreate of my Activity which gets a string on my server, then I convert this string to an arraylist,checkedContactsAsArrayList, and I pass it over to my custom adapter using sharedpreferences, which does stuff with the arraylist in the listview.

But the custom adapter keeps getting the previous arraylist in sharedpreferences, not the one I've just got from the server. The Volley call is too late or something - I can see in logcat the latest values are put after they are got, if you know what I mean.

For example:

VolleyCall 1 putString: 1,2,3
VolleyCall 2 putString: 4,5,6
VolleyCall 3 putString: 7,8,9

Custom Adapter 1 getString: gets values of the last time app was used
Custom Adapter 2 getString: 1,2,3
Custom Adapter 3 getString: 4,5,6

Any idea how to fix this? I could try doing the Volley call in the getView of my custom adapter but I've read on Stackoverflow that's bad practice.

Here are the relvant parts of my code - I've slimmed it down a bit, as there's a lot of stuff in there irrelevant to this issue.

Here's the code of my activity, ViewContact:

public class ViewContact extends AppCompatActivity implements android.widget.CompoundButton.OnCheckedChangeListener  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(activity_view_contact);

        //selectPhoneContacts is an empty array list that will hold our SelectPhoneContact info
        selectPhoneContacts = new ArrayList<SelectPhoneContact>();

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

        StringRequest stringRequest = new StringRequest(Request.Method.POST, ViewContact_URL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {

                        //toast the response of ViewContact.php, which has been converted to a
                        //JSON object by the Php file with JSON encode
                        Toast.makeText(ViewContact.this, "OnResponse is" + response, Toast.LENGTH_LONG).show();
                        System.out.println("ViewContact: And the response is " + response);

                        try {

                            //checkedContacts is a String
                            String checkedContacts = responseObject.getString("checkedcontacts");

                            //convert the checkedContacts string to an arraylist

                            checkedContactsAsArrayList = new ArrayList<String>(Arrays.asList(checkedcontacts.split(",")));
                            System.out.println("ViewContact: checkedContactsAsArrayList is " + checkedContactsAsArrayList);

                            //we want to bring the checkedContactsAsArrayList array list to our SelectPhoneContactAdapter.
                            // It looks like Shared Preferences
                            //only works easily with strings so best way to bring the array list in Shared Preferences is with
                            //Gson.
                            //Here, we PUT the arraylist into the sharedPreferences

                    SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
                    SharedPreferences.Editor editorcheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.edit();
                    Gson gsoncheckedContactsAsArrayList = new Gson();
                    String jsoncheckedContactsAsArrayList = gsoncheckedContactsAsArrayList.toJson(checkedContactsAsArrayList);
                    editorcheckedContactsAsArrayList.putString("checkedContactsAsArrayList", jsoncheckedContactsAsArrayList);
                    editorcheckedContactsAsArrayList.commit();
                    System.out.println("ViewContact: jsoncheckedContactsAsArrayList is " + jsoncheckedContactsAsArrayList);

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }

                    }

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(ViewContact.this, error.toString(), Toast.LENGTH_LONG).show();

                    }

                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                //we are posting review_id into our ViewContact.php file, which
                //we get when a row is clicked in populistolistview
                //to get matching details
                params.put("review_id", review_id);
                return params;

            }

        };
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        //checkBoxforContact.setChecked(true);

    }

    //******for the phone contacts in the listview

    // Load data in background
    class LoadContact extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            //we want to delete the old selectContacts from the listview when the Activity loads
            //because it may need to be updated and we want the user to see the updated listview,
            //like if the user adds new names and numbers to their phone contacts.
            selectPhoneContacts.clear();

                SelectPhoneContact selectContact = new SelectPhoneContact();

                selectContact.setName(phoneNameofContact);

            }

            return null;

        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            adapter = new SelectPhoneContactAdapter(selectPhoneContacts, ViewContact.this,0);

            listView.setAdapter(adapter);

            adapter.notifyDataSetChanged();

        }
    }

    @Override
    protected void onResume() {

        super.onResume();

        // getPrefs();

        ViewContact.LoadContact loadContact = new ViewContact.LoadContact();

        loadContact.execute();

        Toast.makeText(ViewContact.this, "resuming!", Toast.LENGTH_SHORT).show();

    }

}

And my custom adapter, SelectPhoneContactAdapter :

public class SelectPhoneContactAdapter extends BaseAdapter {

//define a list made out of SelectPhoneContacts and call it theContactsList
public List<SelectPhoneContact> theContactsList;
//define an array list made out of SelectContacts and call it arraylist
private ArrayList<SelectPhoneContact> arraylist;
Context _c;
ArrayList<String> MatchingContactsAsArrayList;
ArrayList<String> checkedContactsAsArrayList;
ArrayList <String> allNamesofContacts;
String contactToCheck;
//we will run through different logic in this custom adapter based on the activity that is passed to it
private int whichactivity;

String phoneNumberofContact;
String[] phoneNumberofContactStringArray;
String ContactsString;

Intent intent;

public SelectPhoneContactAdapter(final List<SelectPhoneContact> selectPhoneContacts, Context context, int activity) {
    theContactsList = selectPhoneContacts;
    _c = context;
    this.arraylist = new ArrayList<SelectPhoneContact>();
    this.arraylist.addAll(theContactsList);
    whichactivity = activity;

    //we are fetching the array list checkedContactsAsArrayList, created in ViewContact.
    //with this we will put a tick in the checkboxes of contacts the review is being shared with

    SharedPreferences sharedPreferencescheckedContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(_c);
    Gson gsoncheckedContactsAsArrayList = new Gson();
    String jsoncheckedContactsAsArrayList = sharedPreferencescheckedContactsAsArrayList.getString("checkedContactsAsArrayList", "");
    Type type2 = new TypeToken<ArrayList<String>>() {
    }.getType();
    checkedContactsAsArrayList = gsoncheckedContactsAsArrayList.fromJson(jsoncheckedContactsAsArrayList, type2);
    System.out.println("SelectPhoneContactAdapter checkedContactsAsArrayList :" + checkedContactsAsArrayList);

                                 }
}

@Override
public int getCount() {
    return arraylist.size();
}

@Override
public Object getItem(int i) {
    return arraylist.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}

static class ViewHolder {
    //In each cell in the listview show the items you want to have
    //Having a ViewHolder caches our ids, instead of having to call and load each one again and again
    TextView title, phone;
    CheckBox check;
    Button invite;
}

@Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {

    //this is the SelectPhoneContact object; consists of textboxes, buttons, checkbox
    final SelectPhoneContact data = (SelectPhoneContact) arraylist.get(i);

    ViewHolder holder = null;

    if (convertView == null) {

        //if there is nothing there (if it's null) inflate the view with the layout
        LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = li.inflate(R.layout.phone_inflate_listview, null);

        holder = new ViewHolder();
        //So, for example, title is cast to the name id, in phone_inflate_listview,
        //phone is cast to the id called no etc
        holder.title = (TextView) convertView.findViewById(R.id.name);
        holder.phone = (TextView) convertView.findViewById(R.id.no);
        holder.invite = (Button)  convertView.findViewById(R.id.btnInvite);
        holder.check = (CheckBox) convertView.findViewById(R.id.checkBoxContact);

        convertView.setTag(holder);

    } else {

        holder = (ViewHolder) convertView.getTag();

    }

    //in the listview for contacts, set the name
    holder.title.setText(data.getName());

    //in the listview for contacts, set the number
    holder.phone.setText(data.getPhone());

    holder.check.setTag(data);

    return convertView;

    }

}

Body:
Call this: loadContact.execute();
After you call .commit();

ViewContact.LoadContact loadContact = new ViewContact.LoadContact();
loadContact.execute();


问:
nginx routes redirect to index.html in SPA but second sub dimension
I've an vue.js (Quasar framework with webpack) app and I use vue-router. I use nginx (with laravel forge) on the server side. In the local (quasar dev or npm run dev), everything is alright. I hadn't been able to refresh pages for the address which is like /settings and I solve it with add

```<code>location / {
    try_files $uri $uri/ /index.html?$query_string;
}
</code>```

lines to nginx configuration file. After that I could refresh the /settings page on the server. But now, I can't refresh a page if it has one more dimension.

```<code>/survey/1
</code>```

I tried to add these lines to nginx configuration file

```<code>location /survey/ {
    alias /;
    try_files $uri $uri/ /index.html?$query_string;
}
</code>```

but it doesn't work.

When I look at the errors, I see js addresses are wrong.

```<code>http://example.com/survey/js/manifest.js'
</code>```

It should be

```<code>http://example.com/js/manifest.js'
</code>```

I researched a bit but couldn't find a solution.

答:
I found the problem. It's in webpack build configuration, quasar framework. I just need to modify the Project/config/index.js file's build part. Under the build section, publicPath should be updated from

```<code>publicPath: ""
</code>```

to

```<code>publicPath: "/"
</code>```

And it's the same for the dev section too. When update dev section's publicPath the problem has been fixed.

I just needed to put "/" to publicPath.

Body:
I've an vue.js (Quasar framework with webpack) app and I use vue-router. I use nginx (with laravel forge) on the server side. In the local (quasar dev or npm run dev), everything is alright. I hadn't been able to refresh pages for the address which is like /settings and I solve it with add

location / {
    try_files $uri $uri/ /index.html?$query_string;
}

lines to nginx configuration file. After that I could refresh the /settings page on the server. But now, I can't refresh a page if it has one more dimension.

/survey/1

I tried to add these lines to nginx configuration file

location /survey/ {
    alias /;
    try_files $uri $uri/ /index.html?$query_string;
}

but it doesn't work.

When I look at the errors, I see js addresses are wrong.

http://example.com/survey/js/manifest.js'

It should be

http://example.com/js/manifest.js'

I researched a bit but couldn't find a solution.

Body:
I found the problem. It's in webpack build configuration, quasar framework. I just need to modify the Project/config/index.js file's build part. Under the build section, publicPath should be updated from

publicPath: ""

to

publicPath: "/"

And it's the same for the dev section too. When update dev section's publicPath the problem has been fixed.

I just needed to put "/" to publicPath.

ContentLicense: CC BY-SA 4.0


问:
How do I store image sequence changes to a mysql database with php
I am trying to build a photo organization table and am looking for advice and/or examples of how to save the display sequence of photos to a database.
I'm using php and mysql

Example:
If I have 10 photos in an album and decide to change the sequence of images, so I move a photo from seq 2 to seq 7, then the sequence changes to the following.

1, 2, 3, 4, 5, 6, 7, 8, 9, 10 Original Sequence

1, 7, 2, 3, 4, 5, 6, 8, 9, 10 New Sequence

How do I tell the database that the sequence column for all the affected rows has changed? ...in one operation.

Do I change multiple rows in the db at once?  Can I limit to just the affected rows

the photos table currently has   "rowID, sequence, URL...."

答: You could also just write your table to have next_image_id and previous_image_id, that way all you have to do to to insert an image is change the previous images next_image_id and the next images previous_id, along with that same image.</p>

ContentLicense: CC BY-SA 2.5


问:
Maintain checkbox state while the app is running in WPF
I'm working in MVVM, WPF and I have a popup; inside this popup is a listbox and inside the listbox I have a checkbox. The problem is: if I uncheck an item from the list box and click outside, popup disappears; if a I click again the checkbox is reseted at its initial value (all the items become checked).

So, how can I maintain the state of the popup set and stop its resetting while the app is running ? Can I do this through XAML ?

here is the code:

```<code>public class CheckedListItem<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isChecked = false;
    private T item;

    public CheckedListItem()
    { }

    public CheckedListItem(T item, bool isChecked)
    {
        this.item = item;
        this.isChecked = isChecked;
    }

    public T Item
    {
        get { return item; }
        set
        {
            item = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item"));
        }
    }

    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
}
</code>```

the viewModel:

```<code> private void OnApplyFiltersCommandRaised(object obj)
    {
         if (FilterElement.Contains("ClassView"))
        {
            switch (FilterElement)
            {
                case "buttonClassViewClassFilter":
                    FilteredClassViewItems.Clear();
                    FilteredFieldViewItems.Clear();
                    foreach (var filterItem in FilterItems)
                    {
                        if (filterItem.IsChecked == true)
                        {
                            FilteredClassViewItems.Add(classViewItems.First(c => c.ClassName == filterItem.Item));
                            FilteredFieldViewItems.Add(fieldViewItems.First(c => c.ClassName == filterItem.Item));

                        }
                    }

                    break;
...

public ObservableCollection<CheckedListItem<string>> FilterItems
    {
        get
        {
            return filterItems;
        }

        set
        {
            filterItems = value;
            SetPropertyChanged("FilterItems");

        }
    }
</code>```

the XAML part:

```<code>              <ListBox x:Name="listBoxPopupContent"
                             Height="250"
                             ItemsSource="{Binding FilterItems}"
                             BorderThickness="0"
                             ScrollViewer.VerticalScrollBarVisibility="Auto">
                        <ListBox.Resources>
                            <Style TargetType="{x:Type ListBoxItem}">
                                <Setter Property="FontSize" Value="8" />
                                <Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay}" />
                            </Style>

                        </ListBox.Resources>
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <CheckBox IsChecked="{Binding IsChecked}"
                                          Content="{Binding Item}"
                                          Command="{Binding DataContext.ApplyFiltersCommand,
                                                RelativeSource={RelativeSource FindAncestor,
                                                AncestorType={x:Type ListBox}}}"
                                          CommandParameter="{Binding IsChecked,
                                                RelativeSource={RelativeSource Self},
                                                Mode=OneWay}"/>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
</code>```

Thanks in advance !

答:
If you want to keep the state, you can just create a new view that will contain your listbox. Then your popup will be

```<code><Popup>
   <views:MyListBoxview>
</Popup>
</code>```

where views is the path where wpf can find MyListBoxview.

This is an example of how you can do MyListBoxView. First of all, add a new usercontrol to your project. Then you create:

```<code><ListBox ItemSource = {Binding MyCollectionOfItem}>
    <ListBox.ItemTemplate>
        <DataTemplate>
           <CheckBox IsChecked = {Binding IsItemChecked} Content = {Binding Name}/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

You will need to assign to this view a viewmodel that will of course implement INotifyPropertyChanged and that will have these this class defined inside it (also this class will implement INotifyPropertyChanged)

```<code>public class MyItem : INotifyPropertyChanged
{
    public void SetPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isItemChecked = false;
    public bool IsItemChecked
    {
        get { return isItemChecked; }
        set
        {
            isItemChecked = value;
            SetPropertyChanged("IsItemChecked");
        }
    }

    private string name ;
    public string Name
    {
        get { return Name; }
        set
        {
            name = value;
            SetPropertyChanged("Name");
        }
    }
}
</code>```

finally, the viewmodel that will represent the state of the popup will have inside this property

```<code>private ObservableCollection<MyItem> myCollectionOfItem = new ObservableCollection<MyItem>();
public ObservableCollection<MyItem> MyCollectionOfItem
{
    get { return myCollectionOfItem; }
    set
    {
        myCollectionOfItem = value;
        SetPropertyChanged("MyCollectionOfItem");
    }
}
</code>```

I usually handle this kind of problem modelling properly the object that i need to bind to my controls in WPF

Body:
I'm working in MVVM, WPF and I have a popup; inside this popup is a listbox and inside the listbox I have a checkbox. The problem is: if I uncheck an item from the list box and click outside, popup disappears; if a I click again the checkbox is reseted at its initial value (all the items become checked).

So, how can I maintain the state of the popup set and stop its resetting while the app is running ? Can I do this through XAML ?

here is the code:

public class CheckedListItem<T> : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isChecked = false;
    private T item;

    public CheckedListItem()
    { }

    public CheckedListItem(T item, bool isChecked)
    {
        this.item = item;
        this.isChecked = isChecked;
    }

    public T Item
    {
        get { return item; }
        set
        {
            item = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item"));
        }
    }

    public bool IsChecked
    {
        get { return isChecked; }
        set
        {
            isChecked = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
        }
    }
}

the viewModel:

 private void OnApplyFiltersCommandRaised(object obj)
    {
         if (FilterElement.Contains("ClassView"))
        {
            switch (FilterElement)
            {
                case "buttonClassViewClassFilter":
                    FilteredClassViewItems.Clear();
                    FilteredFieldViewItems.Clear();
                    foreach (var filterItem in FilterItems)
                    {
                        if (filterItem.IsChecked == true)
                        {
                            FilteredClassViewItems.Add(classViewItems.First(c => c.ClassName == filterItem.Item));
                            FilteredFieldViewItems.Add(fieldViewItems.First(c => c.ClassName == filterItem.Item));

                        }
                    }

                    break;
...

public ObservableCollection<CheckedListItem<string>> FilterItems
    {
        get
        {
            return filterItems;
        }

        set
        {
            filterItems = value;
            SetPropertyChanged("FilterItems");

        }
    }

the XAML part:

              <ListBox x:Name="listBoxPopupContent"
                             Height="250"
                             ItemsSource="{Binding FilterItems}"
                             BorderThickness="0"
                             ScrollViewer.VerticalScrollBarVisibility="Auto">
                        <ListBox.Resources>

                        </ListBox.Resources>
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <CheckBox IsChecked="{Binding IsChecked}"
                                          Content="{Binding Item}"
                                          Command="{Binding DataContext.ApplyFiltersCommand,
                                                RelativeSource={RelativeSource FindAncestor,
                                                AncestorType={x:Type ListBox}}}"
                                          CommandParameter="{Binding IsChecked,
                                                RelativeSource={RelativeSource Self},
                                                Mode=OneWay}"/>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>

Thanks in advance !

Body:
If you want to keep the state, you can just create a new view that will contain your listbox. Then your popup will be

<Popup>
   <views:MyListBoxview>
</Popup>

where views is the path where wpf can find MyListBoxview.

This is an example of how you can do MyListBoxView. First of all, add a new usercontrol to your project. Then you create:

<ListBox ItemSource = {Binding MyCollectionOfItem}>
    <ListBox.ItemTemplate>
        <DataTemplate>
           <CheckBox IsChecked = {Binding IsItemChecked} Content = {Binding Name}/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

You will need to assign to this view a viewmodel that will of course implement INotifyPropertyChanged and that will have these this class defined inside it (also this class will implement INotifyPropertyChanged)

public class MyItem : INotifyPropertyChanged
{
    public void SetPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;

    private bool isItemChecked = false;
    public bool IsItemChecked
    {
        get { return isItemChecked; }
        set
        {
            isItemChecked = value;
            SetPropertyChanged("IsItemChecked");
        }
    }

    private string name ;
    public string Name
    {
        get { return Name; }
        set
        {
            name = value;
            SetPropertyChanged("Name");
        }
    }
}

finally, the viewmodel that will represent the state of the popup will have inside this property

private ObservableCollection<MyItem> myCollectionOfItem = new ObservableCollection<MyItem>();
public ObservableCollection<MyItem> MyCollectionOfItem
{
    get { return myCollectionOfItem; }
    set
    {
        myCollectionOfItem = value;
        SetPropertyChanged("MyCollectionOfItem");
    }
}

I usually handle this kind of problem modelling properly the object that i need to bind to my controls in WPF


问:
Batch check Adobe Acrobat .pdf's for files containing rotated text
Does anybody know if there is a way to check whether a list of Adobe Acrobat .pdf files contain rotated text (any text not at 0 degrees)?

I thought this would be simple, but I'm struggling to find an answer.

I am using ABBYY Recognition Server to OCR thousands of files and the results are quite poor where the text is rotated.  I need to get a list of files that have rotated text to allow me to perform some pre-processing on them.

I usually use iTextSharp for .pdf automation and modification but don't seem to be able to find anything for checking text rotation.

Thanks

答:
You could achieve your goal by extracting all words from these PDFs and checking if any of the words is rotated.

I would recommend you to use a PDF library higher level abilities for the task. Docotic.Pdf library is a good choice (of course, I am one of the developers of the library).

Here is an articles that shows how to extract words from PDFs with extra info about their position etc.

Each extracted word comes in PdfTextData object. The PdfTextData contains IsTransformed property to check if word is rotated, scaled, and / or flipped. You can also analyze PdfTextData.TransformationMatrix for more information about the transformation.


问:
A fatal error was encountered. The library 'libhostpolicy.so' required
I am running dotnet core 2.0 console project.
Ran into the following error when trying to run it from Docker.

A fatal error was encountered. The library 'libhostpolicy.so' required
  to execute the application was not found in '/app'.

答:
After some googleing I found this:

https://github.com/aspnet/aspnet-docker/issues/301

I'm not certain what caused it but it seems to have gone away. It's
  probably because I had a case mismatch of appSettings.json instead of
  appsettings.json which meant that the file was not being loaded.
  Terrible error though.

In my case it was that I had forgot to put appsettings.json to copy on builds.

Hope this helps someone else and get's higher on google searches.


问:
dowloading photos uploaded as google form answer with a name
I have created a google form where I collect info about workers (name famil photo etc...).
I want to download all photos uploaded through the form to my PC but I want each photo downloaded to have a name suitable to the name and family answers that the worker submitted , i.e. _.
This will be used to produce magnetic cards automatically without the need to go over each one and choose his image manually.</p>

答:
For uploading file, you can use the method specified in the documentation.

The Drive API allows you to upload file data when creating or
  updating a File resource.

You can send upload requests in any of the following ways:

Simple upload: uploadType=media. For quick transfer of a small file    (5 MB or less). To perform a simple upload, refer to
  Performing a    Simple Upload.

Multipart upload: uploadType=multipart. For quick transfer of a small    file (5 MB or less) and metadata describing the file, all in
  a single    request. To perform a multipart upload, refer to
  Performing a    Multipart Upload.

Resumable upload: uploadType=resumable. For more reliable transfer,    especially important with large files. Resumable uploads are a good

  choice for most applications, since they also work for small files at
  the cost of one additional HTTP request per upload. To perform a

  resumable upload, refer to Performing a Resumable Upload.

Most Google API client libraries implement at least one of the
  methods. Refer to the client library documentation for additional
  details on how to use each of the methods.

Then you can manipulate your metadata,

Much of the information you'll need to get started inserting and
  retrieving files is detailed in the Files reference. Here are a
  few more important considerations for naming files and working with
  metadata like thumbnails and indexable text.

Next, here is how to Specify file names and extensions

Apps should specify a file extension in the title property when
  inserting files with the API. For example, an operation to insert a
  JPEG file should specify something like "name": "cat.jpg" in the
  metadata.

Subsequent GET requests include the read-only fileExtension
  property populated with the extension originally specified in the name
  property. When a Google Drive user requests to download a file, or
  when the file is downloaded through the sync client, Drive builds a
  full filename (with extension) based on the title. In cases where the
  extension is missing, Google Drive attempts to determine the extension
  based on the file's MIME type.


问:
Would this std::vector push_back in OpenMP parallel region result in false-sharing?
The sample code below is a simplified version of my working code. In this code, writing to shared variable is done only at the last line where std::vector::push_back is called.

```<code>std::vector<struct FortyByteStruct> results;

#pragma omp parallel for num_threads(8)
for (int i = 0; i < 250; i++)
{
    struct FortyByteStruct result = some_heavy_work(i);

    #pragma omp critical
    {
        results.push_back(result);
    }
}
</code>```

I was wondering if this push_back operation would result in false-sharing, giving me some chance to optimize further by getting rid of it. I've decided to do some bench tests first, before digging into this issue.

With chrono, I've measured the wall clock execution time of some_heavy_work() and the critical section separately. The latter took about 10^(-4) times of execution time of the former, so I've concluded that there would be almost no benefit from optimizing this part whether false-sharing is involved or not.

Anyway, I'm still curious whether false-sharing is an issue here. Do I have to look at the internal implementation of std::vector? Any enlightment would be greatly appreciated. (I'm on VS2015)

答:
Given that your FortyByteStruct is probably smaller than a cache line (usually 64 byte), there may some false sharing when writing the results data. However, it is hardly consequential, because it will be overshadowed by the cost of the critical section - and also the "true" sharing of modifying the vector itself (not it's data). You don't need to know the details of the std::vector's implementation - only that it's data is contiguous in memory and that it's state (pointer(s) to data/size/capacity) is in the memory of the vector variable itself. False sharing is usually an issue when separate data on the same cache line is accessed by multiple threads in an unprotected fashion. Keep in mind that false sharing does not affect correctness, only performance.

A slightly different example of false sharing would be when you have a std::vector<std::vector<struct FortyByteStruct>> and each thread performs an unprotected push_back. I explained that in detail here.

In your example, with a known total size of the vector, the best approach would be to resize the vector before the loop and then just assign results[i] = result. This avoids the critical section and OpenMP typically distributes the loop iterations in such a way that there is little false sharing. Also you get a deterministic order of results.

That said, when you have have confirmed by measurement that the time is dominated by some_heavy_work, then you are fine.

Body:
The sample code below is a simplified version of my working code. In this code, writing to shared variable is done only at the last line where std::vector::push_back is called.

std::vector<struct FortyByteStruct> results;

#pragma omp parallel for num_threads(8)
for (int i = 0; i < 250; i++)
{
    struct FortyByteStruct result = some_heavy_work(i);

    #pragma omp critical
    {
        results.push_back(result);
    }
}

I was wondering if this push_back operation would result in false-sharing, giving me some chance to optimize further by getting rid of it. I've decided to do some bench tests first, before digging into this issue.

With chrono, I've measured the wall clock execution time of some_heavy_work() and the critical section separately. The latter took about 10^(-4) times of execution time of the former, so I've concluded that there would be almost no benefit from optimizing this part whether false-sharing is involved or not.

Anyway, I'm still curious whether false-sharing is an issue here. Do I have to look at the internal implementation of std::vector? Any enlightment would be greatly appreciated. (I'm on VS2015)


问:
How to parse children recursively using jQuery
I am having my jQuery code as following (which is working fine):

```<code>$('[RptrRowEnableAutoHeight=""True""]').each(function () {
        var ch = 10;
        $(this).children().each(function(){ch += $(this).height();});
        $(this).height(ch);
});
</code>```

The above works only for the immediate children of the root element.  How can I achieve the same for all nested child elements.

This is a special case for us as the layout was developed using absolute positioning (almost everywhere).  At this moment, we are unable to modify entire layout with flow-layout.

In simple, I would like to have all (container) controls to expand (their height/width) automatically to enclose their child elements in a proper fashion (without any scrollbars/hiding).

thanks

答: You can use $(this).find('*').each(...

Body:
I am having my jQuery code as following (which is working fine):

$('[RptrRowEnableAutoHeight=""True""]').each(function () {
        var ch = 10;
        $(this).children().each(function(){ch += $(this).height();});
        $(this).height(ch);
});

The above works only for the immediate children of the root element.  How can I achieve the same for all nested child elements.

This is a special case for us as the layout was developed using absolute positioning (almost everywhere).  At this moment, we are unable to modify entire layout with flow-layout.

In simple, I would like to have all (container) controls to expand (their height/width) automatically to enclose their child elements in a proper fashion (without any scrollbars/hiding).

thanks

Body: You can use $(this).find('*').each(...


问:
Using TextWatcher to calculate average between EditTexts
I have a problem with a project on android studio and i need your help. I have created a line with 3 EditText and one Textview. I want to write numbers on the EditText and calculate the average on the Textview. I also use a button to create a new line when i click it. I achieved the calculation on the first line but every time i try to calculate a line where the button created, i get no result. Here is my code:

```<code>public class MainActivity extends AppCompatActivity {
private LinearLayout parentLinearLayout;
private BreakIterator resultsText;
EditText editText1;
EditText editText2;
EditText editText3;
TextView textViewResult;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    parentLinearLayout = (LinearLayout) findViewById(R.id.parent_linear_layout);
    editText1 = (EditText) findViewById(R.id.number_edit_text1);
    editText2 = (EditText) findViewById(R.id.number_edit_text2);
    editText3 = (EditText) findViewById(R.id.number_edit_text3);

    textViewResult = (TextView) findViewById(R.id.number_text_view);

    editText1.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    editText2.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    editText3.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
}

private String avg() {
    int number1;
    int number2;
    int number3;
    if(editText1.getText().toString() != "" && editText1.getText().length() > 0) {
        number1 = Integer.parseInt(editText1.getText().toString());
    } else {
        number1 = 0;
    }
    if(editText2.getText().toString() != "" && editText2.getText().length() > 0) {
        number2 = Integer.parseInt(editText2.getText().toString());
    } else {
        number2 = 0;
    }
    if(editText3.getText().toString() != "" && editText3.getText().length() > 0) {
        number3 = Integer.parseInt(editText3.getText().toString());
    } else {
        number3 = 0;
    }

    return Integer.toString((number1 + number2 + number3)/3 );
}

public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    // Add the new row before the add field button.
    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);

}

public void onDelete(View v) {
    parentLinearLayout.removeView((View) v.getParent());
}

}
</code>```

And two .xml files:
activity_main.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="495dp"
    android:layout_margin="0dp"
    android:orientation="vertical"
    android:weightSum="1">

    <TableLayout
        android:id="@+id/tlTable01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#CCC"
        android:orientation="vertical"
        android:paddingTop="0dp"
        android:theme="@style/AppTheme">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#7CFC00"
            android:gravity="center_horizontal"
            android:paddingBottom="1dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#7CFC00"
                android:gravity="left"
                android:padding="5dp"
                android:text="Scoring List"
                android:textSize="18dp"
                android:textStyle="bold"
                android:typeface="serif" />

            <EditText
                android:layout_width="190dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="1dp"
                android:background="#FFF"
                android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
                android:gravity="center_horizontal"
                android:inputType="text"
                android:padding="5dp"
                android:text="Examiner's Name"
                android:textSize="18dp"
                android:textStyle="bold"
                android:typeface="serif" />
        </TableRow>
    </TableLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_weight="0.01"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="Student's Name"
        android:textStyle="bold"
        android:typeface="serif" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="User Interface"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="Functions"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="User Manual"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="AVG"
        android:textStyle="bold"
        android:typeface="serif"/>

    <TextView
        android:layout_height="match_parent"
        android:layout_weight="2.35"
        android:gravity="left"
        android:layout_marginLeft="5dp"
        android:layout_width="wrap_content" />
    </LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_weight="0.01"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/word_edit_text"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
        android:gravity="center_horizontal"
        android:inputType="text" />

    <EditText
        android:id="@+id/number_edit_text1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <EditText
        android:id="@+id/number_edit_text2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <EditText
        android:id="@+id/number_edit_text3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <TextView
        android:id="@+id/number_text_view"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:textSize="18dp"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginTop="9dp"/>

    <Button
        android:id="@+id/delete_button"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="2.15"
        android:background="@android:drawable/ic_delete"
        android:onClick="onDelete" />
</LinearLayout>

<Button
        android:id="@+id/add_field_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="#555"
        android:onClick="onAddField"
        android:paddingLeft="5dp"
        android:text="Add Field"
        android:textColor="#FFF" />
</LinearLayout>
</code>```

and field.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_weight="0.01">

<EditText
    android:id="@+id/number_edit_text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text2"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text3"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<TextView
    android:id="@+id/number_text_view"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:gravity="center_horizontal"
    android:textSize="18dp"
    android:textStyle="bold"
    android:typeface="serif"
    android:layout_marginTop="9dp"/>

<Button
    android:id="@+id/delete_button"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_weight="2.15"
    android:background="@android:drawable/ic_delete"
    android:onClick="onDelete" />

</LinearLayout>
</code>```

Thank you in advance!

答:
You need to add TextWatcher in new line edittexts also.Without add textwatcher you unable to find average for them

check the below code and I hope it's will help for you:

```<code>private String avg(EditText editText1,
                   EditText editText2,
                   EditText editText3) {
    int number1;
    int number2;
    int number3;
    if (editText1.getText().toString() != "" && editText1.getText().length() > 0) {
        number1 = Integer.parseInt(editText1.getText().toString());
    } else {
        number1 = 0;
    }
    if (editText2.getText().toString() != "" && editText2.getText().length() > 0) {
        number2 = Integer.parseInt(editText2.getText().toString());
    } else {
        number2 = 0;
    }
    if (editText3.getText().toString() != "" && editText3.getText().length() > 0) {
        number3 = Integer.parseInt(editText3.getText().toString());
    } else {
        number3 = 0;
    }

    return Integer.toString((number1 + number2 + number3) / 3);
}

private void addTextListeners(EditText editText1,
                              EditText editText2,
                              EditText editText3,
                              TextView textViewResult) {

    editText1.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg(editText1, editText2, editText3));
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    editText2.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg(editText1, editText2, editText3));

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    editText3.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg(editText1, editText2, editText3));

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

}

public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    // Add the new row before the add field button.

    EditText editText1 = (EditText) rowView.findViewById(R.id.number_edit_text1);
    EditText editText2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
    EditText editText3 = (EditText) rowView.findViewById(R.id.number_edit_text3);

    TextView textViewResult = (TextView) findViewById(R.id.number_text_view);
    addTextListeners(editText1, editText2, editText3, textViewResult);

    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}
</code>```

1) remove your text change listeners from on create and just call

```<code> addTextListeners(editText1, editText2, editText3, textViewResult);
</code>```

2)Updated your onAddField(v) and avg() with above methods

Body:
I have a problem with a project on android studio and i need your help. I have created a line with 3 EditText and one Textview. I want to write numbers on the EditText and calculate the average on the Textview. I also use a button to create a new line when i click it. I achieved the calculation on the first line but every time i try to calculate a line where the button created, i get no result. Here is my code:

public class MainActivity extends AppCompatActivity {
private LinearLayout parentLinearLayout;
private BreakIterator resultsText;
EditText editText1;
EditText editText2;
EditText editText3;
TextView textViewResult;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    parentLinearLayout = (LinearLayout) findViewById(R.id.parent_linear_layout);
    editText1 = (EditText) findViewById(R.id.number_edit_text1);
    editText2 = (EditText) findViewById(R.id.number_edit_text2);
    editText3 = (EditText) findViewById(R.id.number_edit_text3);

    textViewResult = (TextView) findViewById(R.id.number_text_view);

    editText1.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    editText2.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    editText3.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
}

private String avg() {
    int number1;
    int number2;
    int number3;
    if(editText1.getText().toString() != "" && editText1.getText().length() > 0) {
        number1 = Integer.parseInt(editText1.getText().toString());
    } else {
        number1 = 0;
    }
    if(editText2.getText().toString() != "" && editText2.getText().length() > 0) {
        number2 = Integer.parseInt(editText2.getText().toString());
    } else {
        number2 = 0;
    }
    if(editText3.getText().toString() != "" && editText3.getText().length() > 0) {
        number3 = Integer.parseInt(editText3.getText().toString());
    } else {
        number3 = 0;
    }

    return Integer.toString((number1 + number2 + number3)/3 );
}

public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    // Add the new row before the add field button.
    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);

}

public void onDelete(View v) {
    parentLinearLayout.removeView((View) v.getParent());
}

}

And two .xml files:
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="495dp"
    android:layout_margin="0dp"
    android:orientation="vertical"
    android:weightSum="1">

    <TableLayout
        android:id="@+id/tlTable01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#CCC"
        android:orientation="vertical"
        android:paddingTop="0dp"
        android:theme="@style/AppTheme">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#7CFC00"
            android:gravity="center_horizontal"
            android:paddingBottom="1dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#7CFC00"
                android:gravity="left"
                android:padding="5dp"
                android:text="Scoring List"
                android:textSize="18dp"
                android:textStyle="bold"
                android:typeface="serif" />

            <EditText
                android:layout_width="190dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="1dp"
                android:background="#FFF"
                android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
                android:gravity="center_horizontal"
                android:inputType="text"
                android:padding="5dp"
                android:text="Examiner's Name"
                android:textSize="18dp"
                android:textStyle="bold"
                android:typeface="serif" />
        </TableRow>
    </TableLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_weight="0.01"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="Student's Name"
        android:textStyle="bold"
        android:typeface="serif" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="User Interface"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="Functions"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="User Manual"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="AVG"
        android:textStyle="bold"
        android:typeface="serif"/>

    <TextView
        android:layout_height="match_parent"
        android:layout_weight="2.35"
        android:gravity="left"
        android:layout_marginLeft="5dp"
        android:layout_width="wrap_content" />
    </LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_weight="0.01"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/word_edit_text"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
        android:gravity="center_horizontal"
        android:inputType="text" />

    <EditText
        android:id="@+id/number_edit_text1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <EditText
        android:id="@+id/number_edit_text2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <EditText
        android:id="@+id/number_edit_text3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <TextView
        android:id="@+id/number_text_view"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:textSize="18dp"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginTop="9dp"/>

    <Button
        android:id="@+id/delete_button"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="2.15"
        android:background="@android:drawable/ic_delete"
        android:onClick="onDelete" />
</LinearLayout>

<Button
        android:id="@+id/add_field_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="#555"
        android:onClick="onAddField"
        android:paddingLeft="5dp"
        android:text="Add Field"
        android:textColor="#FFF" />
</LinearLayout>

and field.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_weight="0.01">

<EditText
    android:id="@+id/number_edit_text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text2"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text3"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<TextView
    android:id="@+id/number_text_view"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:gravity="center_horizontal"
    android:textSize="18dp"
    android:textStyle="bold"
    android:typeface="serif"
    android:layout_marginTop="9dp"/>

<Button
    android:id="@+id/delete_button"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_weight="2.15"
    android:background="@android:drawable/ic_delete"
    android:onClick="onDelete" />

</LinearLayout>

Thank you in advance!

Body:
You need to add TextWatcher in new line edittexts also.Without add textwatcher you unable to find average for them

check the below code and I hope it's will help for you:

private String avg(EditText editText1,
                   EditText editText2,
                   EditText editText3) {
    int number1;
    int number2;
    int number3;
    if (editText1.getText().toString() != "" && editText1.getText().length() > 0) {
        number1 = Integer.parseInt(editText1.getText().toString());
    } else {
        number1 = 0;
    }
    if (editText2.getText().toString() != "" && editText2.getText().length() > 0) {
        number2 = Integer.parseInt(editText2.getText().toString());
    } else {
        number2 = 0;
    }
    if (editText3.getText().toString() != "" && editText3.getText().length() > 0) {
        number3 = Integer.parseInt(editText3.getText().toString());
    } else {
        number3 = 0;
    }

    return Integer.toString((number1 + number2 + number3) / 3);
}

private void addTextListeners(EditText editText1,
                              EditText editText2,
                              EditText editText3,
                              TextView textViewResult) {

    editText1.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg(editText1, editText2, editText3));
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    editText2.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg(editText1, editText2, editText3));

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    editText3.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg(editText1, editText2, editText3));

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

}

public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    // Add the new row before the add field button.

    EditText editText1 = (EditText) rowView.findViewById(R.id.number_edit_text1);
    EditText editText2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
    EditText editText3 = (EditText) rowView.findViewById(R.id.number_edit_text3);

    TextView textViewResult = (TextView) findViewById(R.id.number_text_view);
    addTextListeners(editText1, editText2, editText3, textViewResult);

    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);
}

1) remove your text change listeners from on create and just call

 addTextListeners(editText1, editText2, editText3, textViewResult);

2)Updated your onAddField(v) and avg() with above methods


问:
How to get back result as returned object type when executing script as PowerShell.exe -File
If I have a script (script.ps1) like below:

```<code>$dir = Get-Item "C:\Windows"
$dir
</code>```

and if I call it like:

```<code>$myDir = "script.ps1"
</code>```

I get back the $dir object in $myDir and if I use:

```<code>$myDir.Name
</code>```

I get:

```<code>Windows
</code>```

I have a scenario where I need to call scripts using

```<code>$myDir = Powershell.exe -File "script.ps1"
</code>```

With this, I end up getting the output in the form of a string array object and not in the form of the script-returned object as the command is apparently executed in a different session. Due to this, I can't call any property. E.g: $myDir.Name returns nothing

My question is, how do I get the returned object type back as the result in the above case. i.e, even when I execute

```<code>$myDir = Powershell.exe -File "script.ps1"
</code>```

$myDir.Name should return Windows. Is it even possible?

Thanks for any help.

答:
You can use the -OutputFormat parameter of powershell.exe.

```<code>#Write the command to file
"get-item c:\windows\" | out-file C:\temp\test.ps1
$justastring = powershell.exe -file c:\temp\test.ps1
#this is a string array
$justastring | get-member
$notastring = powershell.exe -outputformat xml -file c:\temp\test.ps1
#this is a Deserialized.System.IO.DirectoryInfo
$notastring | get-member
</code>```

This output is also able to be saved as a file and brought back in later. See Import-CliXml and Export-CliXml. Note that because they are serialized objects they are no longer "live". Some of the methods you are used to seeing will not be there, property values will no longer update either. Its essentially a snapshot of the command output at the instant that the command ran.

Body:
If I have a script (script.ps1) like below:

$dir = Get-Item "C:\Windows"
$dir

and if I call it like:

$myDir = "script.ps1"

I get back the $dir object in $myDir and if I use:

$myDir.Name

I get:

Windows

I have a scenario where I need to call scripts using

$myDir = Powershell.exe -File "script.ps1"

With this, I end up getting the output in the form of a string array object and not in the form of the script-returned object as the command is apparently executed in a different session. Due to this, I can't call any property. E.g: $myDir.Name returns nothing

My question is, how do I get the returned object type back as the result in the above case. i.e, even when I execute

$myDir = Powershell.exe -File "script.ps1"

$myDir.Name should return Windows. Is it even possible?

Thanks for any help.

Body:
You can use the -OutputFormat parameter of powershell.exe.

#Write the command to file
"get-item c:\windows\" | out-file C:\temp\test.ps1
$justastring = powershell.exe -file c:\temp\test.ps1
#this is a string array
$justastring | get-member
$notastring = powershell.exe -outputformat xml -file c:\temp\test.ps1
#this is a Deserialized.System.IO.DirectoryInfo
$notastring | get-member

This output is also able to be saved as a file and brought back in later. See Import-CliXml and Export-CliXml. Note that because they are serialized objects they are no longer "live". Some of the methods you are used to seeing will not be there, property values will no longer update either. Its essentially a snapshot of the command output at the instant that the command ran.


问:
getElementById("id").text return object but should be return value from this paragraph
I have a project in HTML/JS.
The problem is that when I want get a value of the paragraph using getElementById("id").text I got object.

var data = document.getElementById("pid").text;
console.log(data);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="pid" >Hello</p></code>```

Chrome:
data returns:

Hello

But I want only Hello value.

Thanks for the answers

答:
You can use innerText property like this:-

```<code>var data = document.getElementById("pid").innerText;
</code>```

Body:
I have a project in HTML/JS.
The problem is that when I want get a value of the paragraph using getElementById("id").text I got object.

var data = document.getElementById("pid").text;
console.log(data);

Hello

Chrome:
data returns:

Hello

But I want only Hello value.

Thanks for the answers

Body:
You can use innerText property like this:-

var data = document.getElementById("pid").innerText;


问:
Case insensitive match in SPARQL triple
Is there a way to make the following query case insensitive?

```<code>ASK {
    VALUES (?r) { (dbr:Game_of_Thrones) }
        { ?r ?p ?o }
        UNION
        { ?s ?r ?o }
        UNION
        { ?s ?p ?r }
    }
</code>```

It shall return true no matter if I use dbr:Game_of_Thrones or dbr:game_of_thrones.

I tried using LCASE() but it's not allowed inside the triples. Is there another way?
I'm using the DBpedia SPARQL endpoint (https://dbpedia.org/sparql).

答:
IRIs are case-sensitive for good reasons. If you really want to workaround this then you have to use FILTER(lcase(str(?tmp)) = lcase(str(?r))) in each UNION clause:

```<code>ASK {
    VALUES (?r) { (dbr:Game_of_Thrones) }
        { ?tmp ?p ?o. FILTER(LCASE(STR(tmp)) = LCASE(STR(?r))) }
        UNION
        { ?s ?r ?o. FILTER(LCASE(STR(tmp)) = LCASE(STR(?r))) }
        UNION
        { ?s ?p ?r. FILTER(LCASE(STR(tmp)) = LCASE(STR(?r))) }
    }
</code>```

Note, this can result in poor performance at it has to scan over all triples and do String comparison.

For fuzzy search, you should really think about a full-text index.

I'd also suggest omitting the second UNION clause as long as you're looking for resources that are probably not schema entities, thus, never occur in predicate position of an RDF triple.

Title: Case insensitive match in SPARQL triple

Body:
Is there a way to make the following query case insensitive?

ASK {
    VALUES (?r) { (dbr:Game_of_Thrones) }
        { ?r ?p ?o }
        UNION
        { ?s ?r ?o }
        UNION
        { ?s ?p ?r }
    }

It shall return true no matter if I use dbr:Game_of_Thrones or dbr:game_of_thrones.

I tried using LCASE() but it's not allowed inside the triples. Is there another way?
I'm using the DBpedia SPARQL endpoint (https://dbpedia.org/sparql).

Body:
IRIs are case-sensitive for good reasons. If you really want to workaround this then you have to use FILTER(lcase(str(?tmp)) = lcase(str(?r))) in each UNION clause:

ASK {
    VALUES (?r) { (dbr:Game_of_Thrones) }
        { ?tmp ?p ?o. FILTER(LCASE(STR(tmp)) = LCASE(STR(?r))) }
        UNION
        { ?s ?r ?o. FILTER(LCASE(STR(tmp)) = LCASE(STR(?r))) }
        UNION
        { ?s ?p ?r. FILTER(LCASE(STR(tmp)) = LCASE(STR(?r))) }
    }

Note, this can result in poor performance at it has to scan over all triples and do String comparison.

For fuzzy search, you should really think about a full-text index.

I'd also suggest omitting the second UNION clause as long as you're looking for resources that are probably not schema entities, thus, never occur in predicate position of an RDF triple.