问:
How to access adapter class textview in fragment
This is my adapter class

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {

List<ListData> listData;

public RecyclerViewAdapter(List<ListData> listData) {
    this.listData = listData;
}

@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);

    return new MyHolder(view);
}

public void onBindViewHolder(MyHolder holder, int position) {
    ListData data = listData.get(position);
    holder.name.setText(data.getName());
    holder.message.setText(data.getMessage());
}

@Override
public int getItemCount() {
    return listData.size();
}

class MyHolder extends RecyclerView.ViewHolder {
    TextView message, name, badge;

    public MyHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.tv_email);
        message = itemView.findViewById(R.id.tv_message);
        badge = itemView.findViewById(R.id.badge);

    }
}
</code>```

This is my Fragment class.

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();

            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message))
                       hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                    }
                } else
                    hashMap.put(nameCaps, message)
            }
            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }
        @Override
        public void onCancelled(DatabaseError error) {

        }
    });
    return view;
}
</code>```

private ArrayListconvertHashToObjectList(HashMap hashMap) {

```<code>    ArrayList<ListData> listData = new ArrayList<>();
    for (Map.Entry<String, String> entry : hashMap.entrySet()) {
        listData.add(new ListData(entry.getKey(), entry.getValue()));
    }
 return listData;
}
</code>```

I want to use the textview badge in fragment class. How to access the adapter class textview in fragment class. When i instantiated the textview in Fragment class it shows the error null object reference.

答:
The way to update some items in a RecyclerView is by updating your data set, then notifying the adapter that the data set has changed.

So first you need to update the data for badge in your List<ListData>.
Then you need to notify change for the adapter. Here's an example

The code goes inside your adapter

```<code>public void updateData(List<ListData> newData) {
    listData = newData;
    notifyDataSetChanged();
}
</code>```

And make sure in your onBindViewHolder() to set the value of badge if exists.

Body:
This is my adapter class

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {

List<ListData> listData;

public RecyclerViewAdapter(List<ListData> listData) {
    this.listData = listData;
}

@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);

    return new MyHolder(view);
}

public void onBindViewHolder(MyHolder holder, int position) {
    ListData data = listData.get(position);
    holder.name.setText(data.getName());
    holder.message.setText(data.getMessage());
}

@Override
public int getItemCount() {
    return listData.size();
}

class MyHolder extends RecyclerView.ViewHolder {
    TextView message, name, badge;

    public MyHolder(View itemView) {
        super(itemView);
        name = itemView.findViewById(R.id.tv_email);
        message = itemView.findViewById(R.id.tv_message);
        badge = itemView.findViewById(R.id.badge);

    }
}

This is my Fragment class.

public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle b) {
    View view = inflater.inflate(R.layout.fragment_chats, group, false);
    recyclerview = view.findViewById(R.id.rview);
    badge = view.findViewById(R.id.badge);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("message");
    hashMap = new HashMap<>();
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();

            for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                UserDetails userdetails = dataSnapshot1.getValue(UserDetails.class);
                String name = userdetails.getName();
                String nameCaps = name.substring(0, 1).toUpperCase() + name.substring(1);
                String message = userdetails.getMessage();

                if (hashMap.containsKey(name)) {
                    if (!hashMap.get(name).equalsIgnoreCase(message))
                       hashMap.remove(name);
                        hashMap.put(nameCaps, message);
                    }
                } else
                    hashMap.put(nameCaps, message)
            }
            list = convertHashToObjectList(hashMap);
            RecyclerViewAdapter recycler = new RecyclerViewAdapter(list);
            RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutManager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);
        }
        @Override
        public void onCancelled(DatabaseError error) {

        }
    });
    return view;
}

private ArrayListconvertHashToObjectList(HashMap hashMap) {

    ArrayList<ListData> listData = new ArrayList<>();
    for (Map.Entry<String, String> entry : hashMap.entrySet()) {
        listData.add(new ListData(entry.getKey(), entry.getValue()));
    }
 return listData;
}

I want to use the textview badge in fragment class. How to access the adapter class textview in fragment class. When i instantiated the textview in Fragment class it shows the error null object reference.

Body:
The way to update some items in a RecyclerView is by updating your data set, then notifying the adapter that the data set has changed.

So first you need to update the data for badge in your List<ListData>.
Then you need to notify change for the adapter. Here's an example

The code goes inside your adapter

public void updateData(List<ListData> newData) {
    listData = newData;
    notifyDataSetChanged();
}

And make sure in your onBindViewHolder() to set the value of badge if exists.


来源: stackexchange

问:
C++ Why is this vector access giving a Runtime Error?
I've singled out a runtime error on this line of my code:

```<code>for (synsAuxCopyIndex=1; synsAuxCopyIndex<synsAux.size(); synsAuxCopyIndex++)
</code>```

Which is runnhing inside the pushSynonyms(string synline, vector<WordInfo> &wordInfoVector) function. I don't get why is this particular line generating the error, as I don't think I'm indexing anything out of range.

The debugger is saying:

```<code>Uncontrolled Exception 0x00411cbf in program.exe: 0xC0000005: Infracción de acceso al leer la ubicación 0x00000000.
</code>```

I guess "Infracción de acceso" will translate as Unauthorized access on an English debugger.

The input file is

dictionary.txt

```<code>1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful
synonyms
1 7
7 1
antonyms
1 3
3 1 7
4 5
5 4
7 3
</code>```

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

class WordInfo{
 public:
  WordInfo() {}

  ~WordInfo() {}

  int id() const { return myId; }

  void readWords(istream &in) {
    in >> myId >> word;
  }

  vector<int>& getSynonyms () {
    return mySynonyms;
  }

  vector<int>& getAntonyms() {
     return myAntonyms;
  }

  string getWord() {
    return word;
  }

  void pushSynonyms (string synline, vector<WordInfo>& wordInfoVector) {
    stringstream synstream(synline);
    vector<int> synsAux;
    int num;
    while (synstream >> num)
      synsAux.push_back(num);
    int wordInfoVectorIndex;
    int synsAuxCopyIndex;
    for (wordInfoVectorIndex=0;
         wordInfoVectorIndex < wordInfoVector.size();
         wordInfoVectorIndex++) {
      if (synsAux[0] == wordInfoVector[wordInfoVectorIndex].id()) {
        // this is the line that's generating a Runtime Error, Why?
        for (synsAuxCopyIndex = 1;
             synsAuxCopyIndex < synsAux.size();
             synsAuxCopyIndex++) {
//        wordInfoVector[wordInfoVectorIndex].mySynonyms.push_back(
//            synsAux[synsAuxCopyIndex]);
        }
      }
    }
  }

  void pushAntonyms (string antline, vector<WordInfo> wordInfoVector) {
    stringstream antstream(antline);
    vector<int> antsAux;
    int num;
    while (antstream >> num)
      antsAux.push_back(num);
//    for (int i=0; i<antsAux.size(); i++){
//      cout<<antsAux[i]<<endl;
//    }
  }

  //--dictionary output function
  void printWords (ostream &out) {
    out<<myId<< " "<<word;
  }

  //--equals operator for String
  bool operator == (const string &aString) const {
    return word ==aString;
  }

  //--less than operator
  bool operator < (const WordInfo &otherWordInfo) const {
    return word<otherWordInfo.word;
  }

  //--more than operator
  bool operator > (const WordInfo &otherWordInfo) const {
    return word>otherWordInfo.word;
  }

 public:
  vector<int> mySynonyms;
  vector <int> myAntonyms;

 private:
//vector <int> mySynonyms;
//vector <int> myAntonyms;
  string word;
  int myId;
};

//--Definition of input operator for WordInfo
istream & operator >> (istream &in, WordInfo &word) {
  word.readWords(in);
}

//--Definition of output operator
ostream & operator << (ostream &out, WordInfo &word) {
  word.printWords(out);
}

int main() {
  string wordFile;
  cout << "enter name of dictionary file: ";
  getline (cin, wordFile);
  ifstream inStream(wordFile.data());
  if (!inStream.is_open()) {
    cerr << "cannot open " << wordFile << endl;
    exit(1);
  }

  vector <WordInfo> wordInfoVector;
  WordInfo aword;

  while (inStream >> aword && (!(aword == "synonyms")))
    wordInfoVector.push_back(aword);

  inStream.clear();

  int i=0;
  while (i < wordInfoVector.size()) {
    cout << wordInfoVector[i] << endl;
    i++;
  }

  vector <int> intVector;
  string synLine;

  while (getline(inStream, synLine) && (synLine != ("antonyms")))
    aword.pushSynonyms(synLine, wordInfoVector);

  int theIndex;
  for (theIndex=0;
       theIndex < wordInfoVector[0].mySynonyms.size();
       theIndex++)
    cout << "the synonyms of 1 are " <<
        wordInfoVector[0].mySynonyms[theIndex] << endl;
  cout << "the size of mySynonyms of 1 is " <<
      wordInfoVector[0].mySynonyms.size() << endl;

  for (theIndex=0;
       theIndex < wordInfoVector[0].mySynonyms.size();
       theIndex++)
    cout << "the synonyms of 7 are " <<
        wordInfoVector[6].mySynonyms[theIndex] << endl;
  cout << " the size of mySynonyms of 7 is " <<
      wordInfoVector[6].mySynonyms.size() << endl;

  string antLine;
  while (getline(inStream, antLine))
    aword.pushAntonyms(antLine, wordInfoVector);

  wordInfoVector[0].mySynonyms.push_back(1);
  system("PAUSE");
  return 0;
}
</code>```

答:
If you add some debugging output to your program, you'd notice you never enter or even reach the "culprit" for-loop.

The problem is actually the test against "synsAux[0]" right above it - synxAux.size() is zero, so accessing the zeroth element is an index out-of-bounds error.

ContentLicense: CC BY-SA 2.5

Body:
I've singled out a runtime error on this line of my code:

for (synsAuxCopyIndex=1; synsAuxCopyIndex<synsAux.size(); synsAuxCopyIndex++)

Which is runnhing inside the pushSynonyms(string synline, vector<WordInfo> &wordInfoVector) function. I don't get why is this particular line generating the error, as I don't think I'm indexing anything out of range.

The debugger is saying:

Uncontrolled Exception 0x00411cbf in program.exe: 0xC0000005: Infracción de acceso al leer la ubicación 0x00000000.

I guess "Infracción de acceso" will translate as Unauthorized access on an English debugger.

The input file is

dictionary.txt

1 cute
2 hello
3 ugly
4 easy
5 difficult
6 tired
7 beautiful
synonyms
1 7
7 1
antonyms
1 3
3 1 7
4 5
5 4
7 3

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

class WordInfo{
 public:
  WordInfo() {}

  ~WordInfo() {}

  int id() const { return myId; }

  void readWords(istream &in) {
    in >> myId >> word;
  }

  vector<int>& getSynonyms () {
    return mySynonyms;
  }

  vector<int>& getAntonyms() {
     return myAntonyms;
  }

  string getWord() {
    return word;
  }

  void pushSynonyms (string synline, vector<WordInfo>& wordInfoVector) {
    stringstream synstream(synline);
    vector<int> synsAux;
    int num;
    while (synstream >> num)
      synsAux.push_back(num);
    int wordInfoVectorIndex;
    int synsAuxCopyIndex;
    for (wordInfoVectorIndex=0;
         wordInfoVectorIndex < wordInfoVector.size();
         wordInfoVectorIndex++) {
      if (synsAux[0] == wordInfoVector[wordInfoVectorIndex].id()) {
        // this is the line that's generating a Runtime Error, Why?
        for (synsAuxCopyIndex = 1;
             synsAuxCopyIndex < synsAux.size();
             synsAuxCopyIndex++) {
//        wordInfoVector[wordInfoVectorIndex].mySynonyms.push_back(
//            synsAux[synsAuxCopyIndex]);
        }
      }
    }
  }

  void pushAntonyms (string antline, vector<WordInfo> wordInfoVector) {
    stringstream antstream(antline);
    vector<int> antsAux;
    int num;
    while (antstream >> num)
      antsAux.push_back(num);
//    for (int i=0; i<antsAux.size(); i++){
//      cout<<antsAux[i]<<endl;
//    }
  }

  //--dictionary output function
  void printWords (ostream &out) {
    out<<myId<< " "<<word;
  }

  //--equals operator for String
  bool operator == (const string &aString) const {
    return word ==aString;
  }

  //--less than operator
  bool operator < (const WordInfo &otherWordInfo) const {
    return word<otherWordInfo.word;
  }

  //--more than operator
  bool operator > (const WordInfo &otherWordInfo) const {
    return word>otherWordInfo.word;
  }

 public:
  vector<int> mySynonyms;
  vector <int> myAntonyms;

 private:
//vector <int> mySynonyms;
//vector <int> myAntonyms;
  string word;
  int myId;
};

//--Definition of input operator for WordInfo
istream & operator >> (istream &in, WordInfo &word) {
  word.readWords(in);
}

//--Definition of output operator
ostream & operator << (ostream &out, WordInfo &word) {
  word.printWords(out);
}

int main() {
  string wordFile;
  cout << "enter name of dictionary file: ";
  getline (cin, wordFile);
  ifstream inStream(wordFile.data());
  if (!inStream.is_open()) {
    cerr << "cannot open " << wordFile << endl;
    exit(1);
  }

  vector <WordInfo> wordInfoVector;
  WordInfo aword;

  while (inStream >> aword && (!(aword == "synonyms")))
    wordInfoVector.push_back(aword);

  inStream.clear();

  int i=0;
  while (i < wordInfoVector.size()) {
    cout << wordInfoVector[i] << endl;
    i++;
  }

  vector <int> intVector;
  string synLine;

  while (getline(inStream, synLine) && (synLine != ("antonyms")))
    aword.pushSynonyms(synLine, wordInfoVector);

  int theIndex;
  for (theIndex=0;
       theIndex < wordInfoVector[0].mySynonyms.size();
       theIndex++)
    cout << "the synonyms of 1 are " <<
        wordInfoVector[0].mySynonyms[theIndex] << endl;
  cout << "the size of mySynonyms of 1 is " <<
      wordInfoVector[0].mySynonyms.size() << endl;

  for (theIndex=0;
       theIndex < wordInfoVector[0].mySynonyms.size();
       theIndex++)
    cout << "the synonyms of 7 are " <<
        wordInfoVector[6].mySynonyms[theIndex] << endl;
  cout << " the size of mySynonyms of 7 is " <<
      wordInfoVector[6].mySynonyms.size() << endl;

  string antLine;
  while (getline(inStream, antLine))
    aword.pushAntonyms(antLine, wordInfoVector);

  wordInfoVector[0].mySynonyms.push_back(1);
  system("PAUSE");
  return 0;
}

LastEditorDisplayName: phjr

OwnerDisplayName: HUAGHAGUAH


问:
Mouse events between two ItemsContorl elements
Take a look at below code. BoxControl has MouseLeftButtonDown/MouseLeftButtonUp events and those work fine when the mouse is clicked on
the box control other than when the mouse is clicked on below text block. I want MouseLeftButtonDown/MouseLeftButtonUp events of BoxControl
to work when the mouse is clicked on below textblock. Appreciate your help!</p>

答:
It works as expected. Your BoxControl is the one which has the click events so that is the only control which is listening for these events, and TextBlock isn't.

There are two things you can do:

1) Add the TextBlock in your BoxControl

OR

2) Add the MouseLeftButtonDown and MouseLeftButtonUp events on your current TextBlock and get these textblock_MouseClickHandlers to delegate to the event handlers for the BoxControl


问:
5702 : The SQL Server is terminating this process because the database view
after modifying the view as below, if use the view in the select statements by the application(as below query), then we are getting

DB error 5702: The SQL Server is terminating this process.

Here's the query

```<code>select *
from view1 v1,
view2 v2
where v1.column in(select M_FLOW_ID from VW_NETPAY_UNDO)
</code>```

is the issue because more number of view in sql statements ?

答:
Most provably is that your query is runing for a long long time and sybase decided to stop the process,  root of the problem ist that  you have a cross join between the 2 Views.
You should match the 2 views,(on View1.columnA= View2.columnA)

```<code>    select *
     from view1 v1,
     view2 v2 on V1.id = V2.id  -- id like common value column
      where v1.column in(select colum1 from table1)
</code>```

.If you don´t do that you have a cartesian products between the 2 Views and then the resuld wouldnt arrise.

Best Regards,
Enrique

ContentLicense: CC BY-SA 3.0

Body:
after modifying the view as below, if use the view in the select statements by the application(as below query), then we are getting

DB error 5702: The SQL Server is terminating this process.

Here's the query

select *
from view1 v1,
view2 v2
where v1.column in(select M_FLOW_ID from VW_NETPAY_UNDO)

is the issue because more number of view in sql statements ?

Body:
Most provably is that your query is runing for a long long time and sybase decided to stop the process,  root of the problem ist that  you have a cross join between the 2 Views.
You should match the 2 views,(on View1.columnA= View2.columnA)

    select *
     from view1 v1,
     view2 v2 on V1.id = V2.id  -- id like common value column
      where v1.column in(select colum1 from table1)

.If you don´t do that you have a cartesian products between the 2 Views and then the resuld wouldnt arrise.

Best Regards,
Enrique


问:
Ubuntu. Sending emails with embedded images
I have Ubuntu server(16.04) + Nagios, also I have created a script that makes a screenshot(Nagios status) every night and sends this screenshot to two recipients. But occurs problem, I receive mail with images(embed in a body, not attachment) - is OK, but my friend receives the same mail with broken images(blank files in attachment).
Any suggestion, how to solve this problem?
Script code:</p>

```<code>    #!/bin/bash

cat <<EOT | /usr/sbin/sendmail -t
TO: @email1, @email2
SUBJECT: Report: Nagios Event Log  $(date +%F --date=yesterday)
MIME-Version: 1.0
Content-Type: multipart/related;boundary="XYZ"

--XYZ
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-15">
</head>
<body bgcolor="#ffffff" text="#000000">
Hello Team,<br>Daily Nagios report of $(date +%F --date=yesterday) is generated.
<img src="cid:part1.06090408.01060107" alt="">
<br>Best Regards, Nagios Admin
</body>
</html>

--XYZ
Content-Type: image/png;name="Nagios-EventLog-`date +%F --date="yesterday"`.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline; filename="Nagios-EventLog-`date +%F --date="yesterday"`.png"
$(base64 /some_path/NagiosReport/Nagios-EventLog-`date +%F --date="yesterday"`.png)
--XYZ--
EOT
</code>```

答:
You lack a newline between the MIME headers and the base64 image data.

Running base64 in a command substitution inside a here document will probably produce overlong lines in the output. Try (rough pseudocode)

```<code>( cat <<EOF
  From: blah blah ...
  Subject: blah blah ...
  :
  --XYZ
  Content-description: image/png; name=etc etc

  EOF

  base64 file

  printf "\n--XYZ--\n" ) | sendmail -oi -t
</code>```

(I'm assuming you did PATH=/usr/sbin:$PATH near the top of the script so you don't have to hard-code the path to sendmail.)

If improved knowledge of MIME isn't a personal development goal, probably use a program which knows how to do this properly.  Many people use mutt to send mail on their behalf without having to worry about how exactly to do it right.

As a stylistic aside, running $(date +%F) multiple times seems clunky. Just run it once and capture the output in a variable. (In the pathological case, the script runs around midnight, and you get different dates in different parts of the message!)

Body:
I have Ubuntu server(16.04) + Nagios, also I have created a script that makes a screenshot(Nagios status) every night and sends this screenshot to two recipients. But occurs problem, I receive mail with images(embed in a body, not attachment) - is OK, but my friend receives the same mail with broken images(blank files in attachment).
Any suggestion, how to solve this problem?
Script code:

    #!/bin/bash

cat <<EOT | /usr/sbin/sendmail -t
TO: @email1, @email2
SUBJECT: Report: Nagios Event Log  $(date +%F --date=yesterday)
MIME-Version: 1.0
Content-Type: multipart/related;boundary="XYZ"

--XYZ
Content-Type: text/html; charset=ISO-8859-15
Content-Transfer-Encoding: 7bit

<meta http-equiv="content-type" content="text/html; charset=ISO-8859-15">

Hello Team,
Daily Nagios report of $(date +%F --date=yesterday) is generated.

Best Regards, Nagios Admin

--XYZ
Content-Type: image/png;name="Nagios-EventLog-`date +%F --date="yesterday"`.png"
Content-Transfer-Encoding: base64
Content-ID: <part1.06090408.01060107>
Content-Disposition: inline; filename="Nagios-EventLog-`date +%F --date="yesterday"`.png"
$(base64 /some_path/NagiosReport/Nagios-EventLog-`date +%F --date="yesterday"`.png)
--XYZ--
EOT

Body:
You lack a newline between the MIME headers and the base64 image data.

Running base64 in a command substitution inside a here document will probably produce overlong lines in the output. Try (rough pseudocode)

( cat <<EOF
  From: blah blah ...
  Subject: blah blah ...
  :
  --XYZ
  Content-description: image/png; name=etc etc

  EOF

  base64 file

  printf "\n--XYZ--\n" ) | sendmail -oi -t

(I'm assuming you did PATH=/usr/sbin:$PATH near the top of the script so you don't have to hard-code the path to sendmail.)

If improved knowledge of MIME isn't a personal development goal, probably use a program which knows how to do this properly.  Many people use mutt to send mail on their behalf without having to worry about how exactly to do it right.

As a stylistic aside, running $(date +%F) multiple times seems clunky. Just run it once and capture the output in a variable. (In the pathological case, the script runs around midnight, and you get different dates in different parts of the message!)


问:
Java: RemoveAll(Collection c) returns false
In my java code I have two arrayList one is assignedRiders and other is nearestRiders, and  I want to remove elements from nearestRiders list if it also exist in assignedRiders , for this I used following line but when I run this it returns me false even when they have same elements

Code

```<code>List<User> nearestRiders=new ArrayList<User>();
List<User> assignedRiders=new ArrayList<User>();
nearestRiders=riderLocationRepo.findNearestRiderList(orderRequest.getLatitudeShop(),
                    orderRequest.getLongitudeShop());
assignedRiders=orderAlredayAssigned();
Boolean dataChanhged=nearestRiders.removeAll(assignedRiders);
</code>```

答:
You can do it like that :   </p>

```<code>for(User u : nearestRiders){
assignedRRiders.remove(u)}
</code>```

Body:
In my java code I have two arrayList one is assignedRiders and other is nearestRiders, and  I want to remove elements from nearestRiders list if it also exist in assignedRiders , for this I used following line but when I run this it returns me false even when they have same elements

Code

List<User> nearestRiders=new ArrayList<User>();
List<User> assignedRiders=new ArrayList<User>();
nearestRiders=riderLocationRepo.findNearestRiderList(orderRequest.getLatitudeShop(),
                    orderRequest.getLongitudeShop());
assignedRiders=orderAlredayAssigned();
Boolean dataChanhged=nearestRiders.removeAll(assignedRiders);

Body:
You can do it like that :

for(User u : nearestRiders){
assignedRRiders.remove(u)}


问:
Geolocation coords not passing from javascript to php
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

```<code>var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};
</code>```

it should send the data to template-userslocation.phpwhere I have this code:

```<code><?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>
</code>```

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

答:
first console your lat. and lang. to check if you get any result then use the following code in ajax

```<code>data:  { 'lang' : coordinates , 'lat': coordinate},
</code>```

then use $_POST['lant'] and $_POST['lang'] in destination file

Body:
Been having a lot of dificulties to send geolocation data to php for store after in mysql. Searching and getting support has achieved a lot but still doesn't see the coords of the users in page.

Here the code.

1.code from template-maps.php:

var pos;
var posZae = function(pos){
                    return {
                            coords: {
                                latitude: pos.coords.latitude,
                                longitude: pos.coords.longitude,
                                accuracy: pos.coords.accuracy.toFixed()
                            },
                            timestamp: pos.timestamp
                    }
            };
var netPOS;
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        infoWindow.setPosition(pos);
        infoWindow.setContent('You are here');
        map.setCenter(pos);
        var netPOS = JSON.stringify(posZae(position));
        $.ajax({
            type: 'POST',
            data:  { 'pos' : pos},
            url: '/wp-content/themes/honolulu/template-userslocation.php'
        });
    },
    function() {
        handleLocationError(true, infoWindow, map.getCenter());
    });
} else {
    // Browser doesn't support Geolocation
    handleLocationError(false, infoWindow, map.getCenter());
};

it should send the data to template-userslocation.phpwhere I have this code:

<?php
    /**
    * Template Name: template-userslocation
    */

    $lat = isset($_POST['pos']['lat']) ? $_POST['pos']['lat'] : null;
    $lng = isset($_POST['pos']['lng']) ? $_POST['pos']['lng'] : null;
?>

I get no ERROR, but if I charge the page there is no data. Nothing in the page and in the console.

Solved:

The problem is that it is being made in Wordpress and Wordpress has his own way to handle AJAX.

Here the info

Body:
first console your lat. and lang. to check if you get any result then use the following code in ajax

data:  { 'lang' : coordinates , 'lat': coordinate},

then use $_POST['lant'] and $_POST['lang'] in destination file


问:
Localization do not work when "l18parent" is empty (0)
When a content element is translated using "translate" method and so have a l18parent, the content shows up in frontend.
When using "copy" method or created the content in new language without l18parent the content do not appear in frontend.

Can simply test it when unselecting a l18parent in CE form and selecting a parent again.
See screenshots attached.

With parent, working.
Without parent, not working (not appearing in frontend).

Not working

Working

答:
Since TYPO3 6.2 there is a new setting for the CONTENT object: includeRecordsWithoutDefaultTranslation

see here: https://docs.typo3.org/typo3cms/TyposcriptReference/6.2/Functions/Select/

Before this, the CONTENT object fetched all elements.
After this change, only elements which were correctly translated in the backend with the translation buttons, are displayed, because they have a parent.

Maybe you can check with these settings in your typoscript (at the beginning of your typoscript):

```<code>styles.content.get.select.includeRecordsWithoutDefaultTranslation = 1
styles.content.getLeft.select.includeRecordsWithoutDefaultTranslation = 1
styles.content.getRight.select.includeRecordsWithoutDefaultTranslation = 1
</code>```

Then all elements should show up again; even the ones without parent.

Original resource for this is written in german here:
http://blog.teamgeist-medien.de/2014/08/typo3-content-anzeige-von-uebersetzungen-ohne-parent-bzw-default-translation.html

Body:
Since TYPO3 6.2 there is a new setting for the CONTENT object: includeRecordsWithoutDefaultTranslation

see here: https://docs.typo3.org/typo3cms/TyposcriptReference/6.2/Functions/Select/

Before this, the CONTENT object fetched all elements.
After this change, only elements which were correctly translated in the backend with the translation buttons, are displayed, because they have a parent.

Maybe you can check with these settings in your typoscript (at the beginning of your typoscript):

styles.content.get.select.includeRecordsWithoutDefaultTranslation = 1
styles.content.getLeft.select.includeRecordsWithoutDefaultTranslation = 1
styles.content.getRight.select.includeRecordsWithoutDefaultTranslation = 1

Then all elements should show up again; even the ones without parent.

Original resource for this is written in german here:
http://blog.teamgeist-medien.de/2014/08/typo3-content-anzeige-von-uebersetzungen-ohne-parent-bzw-default-translation.html


问:
Vaadin Designer Set Tab Caption
Problem according to the Vaadin docs to set a Tab caption do the following.

```<code>// Set an attribute using the returned reference
tabsheet.addTab(myTab).setCaption("My Tab");
</code>```

When using the Vaadin designer you already have a Tab created within the design.

How do you set the name of the Tab?

答:
You resolve this by first getting the Tab from the Design and then setting the caption for the Tab.  addTab() will add another Tab.

```<code>// Set an attribute using the returned reference
tabsheet.getTab(myTab).setCaption("My Tab");
</code>```

Title: Vaadin Designer Set Tab Caption

Body:
Problem according to the Vaadin docs to set a Tab caption do the following.

// Set an attribute using the returned reference
tabsheet.addTab(myTab).setCaption("My Tab");

When using the Vaadin designer you already have a Tab created within the design.

How do you set the name of the Tab?

Body:
You resolve this by first getting the Tab from the Design and then setting the caption for the Tab.  addTab() will add another Tab.

// Set an attribute using the returned reference
tabsheet.getTab(myTab).setCaption("My Tab");


问:
Why am I getting a Linker error with template function pointer?
I have a class EventMgr which has a template function to register a listener. But, when I register a listener, linker gives me a "error LNK2019: unresolved external symbol".

Appetizer code:

```<code>class EventMgr {

 template< class T, class EvenT>
 void RegisterListener(T* listener, int EventType, void (T::*MemFunc)(EvenT*) );
}
</code>```

SoundMgr(which is a listener) tries to register for event:

```<code>SoundMgr::SoundMgr(void)
{
  EventManager::GetInstance()->RegisterListener(this, 1, (&SoundMgr::handleBulletFired));
}
</code>```

I'm not sure why it won't link. Why can it not find the reference types ?

答:
If you simply declared the template in a .h file and the implementation is instead in a .cpp file then this is the error you will get, because  a C++ compiler works one compile unit at a time. When the compiler finds your code calling a template function that has been just declared it will assume that the concrete instantiation will be done by some other compilation unit (there is no way the compiler can know where to find the .cpp file for that function... the compiler only sees one .cpp and all the included .h at a time).

If the template parameters are from a well known list you can simply request the all explicit implementations you know that will be needed for the program in the .cpp.

For example if you have a template function

```<code>template<typename T>
T foo(T x)
{
   ...
}
</code>```

and you know are just going to need int foo(int); and string foo(string); then it's fine to use just the declaration in the .h, provided you also add two lines in the .cpp saying:

```<code>template<> int foo(int);
template<> string foo(string);
</code>```

By doing that you are telling the compiler about what specialization to build. If you later end up using other specializations (e.g. vector<int> foo(vector<int>)) then you must also add this explicit instantiation in the .cpp file of the template.

However in your example looking at the code I guess that you don't know in advance which kind of events will be defined and so this explicit instantiation cannot be done.

The other solution is to simply put the whole template implementation in the .h file instead of separating declaration from implementation. This sometimes can be not trivial because requires you to expose more implementation details probably introducing more dependencies.

Body:
I have a class EventMgr which has a template function to register a listener. But, when I register a listener, linker gives me a "error LNK2019: unresolved external symbol".

Appetizer code:

class EventMgr {

 template< class T, class EvenT>
 void RegisterListener(T* listener, int EventType, void (T::*MemFunc)(EvenT*) );
}

SoundMgr(which is a listener) tries to register for event:

SoundMgr::SoundMgr(void)
{
  EventManager::GetInstance()->RegisterListener(this, 1, (&SoundMgr::handleBulletFired));
}

I'm not sure why it won't link. Why can it not find the reference types ?

Body:
If you simply declared the template in a .h file and the implementation is instead in a .cpp file then this is the error you will get, because  a C++ compiler works one compile unit at a time. When the compiler finds your code calling a template function that has been just declared it will assume that the concrete instantiation will be done by some other compilation unit (there is no way the compiler can know where to find the .cpp file for that function... the compiler only sees one .cpp and all the included .h at a time).

If the template parameters are from a well known list you can simply request the all explicit implementations you know that will be needed for the program in the .cpp.

For example if you have a template function

template<typename T>
T foo(T x)
{
   ...
}

and you know are just going to need int foo(int); and string foo(string); then it's fine to use just the declaration in the .h, provided you also add two lines in the .cpp saying:

template<> int foo(int);
template<> string foo(string);

By doing that you are telling the compiler about what specialization to build. If you later end up using other specializations (e.g. vector<int> foo(vector<int>)) then you must also add this explicit instantiation in the .cpp file of the template.

However in your example looking at the code I guess that you don't know in advance which kind of events will be defined and so this explicit instantiation cannot be done.

The other solution is to simply put the whole template implementation in the .h file instead of separating declaration from implementation. This sometimes can be not trivial because requires you to expose more implementation details probably introducing more dependencies.


问:
Move commit to a new branch
I know it's supposed to be easy, only  I am new to Git and a little bit confused of its terminology (like HEAD or Origin for instance...are they the same ?)

At the moment I have the branch v4000 with the below commits :

```<code>---X-Y-Z (v4000 branch head)
</code>```

I realized that branch v4000 Head should be at commit Y, and I need a new branch v4100 and move commit Z to that one :

```<code>---X-Y (v4000 head)
      \
       Z (v4100 head)
</code>```

Can you please help me how to achieve this from within Visual Studio 2017 Team Explorer ?

Thank you in advance.

答:
A branch is nothing but a pointer to a certain commit. As @LethalProgrammer said in the comments, the HEAD of your current branch is the commit it points to. Origin now is something completely different, it's the default name for the remote repository (i.e. the repository on the server, where you pull from and push to).

When you're on branch v4000 with Z as it's HEAD (your current state as far as I understand), you can just create a new branch v4100 and reset the v4000 branch back to Y.

On the command line, this looks like this:

git stash stash any uncommited changes

git branch v4100 create branch v4100 with Z as it's head

git reset --hard Y with Y being the commit' s SHA id: reset branch v4000's HEAD to commit Y

git stash pop restore previously stashed changes, if any

You can also do this via VSTeamExplorer, but I don't know how to stash there, so be sure that you have no uncommited changes before you try this:

Select Branches -> New Branch, enter v4100 as branch name, uncheck Checkout branch and click create. This creates branch 4100 with commit Z as it's HEAD.

Then, still in the Branches tab, select Actions->View History. In the opening window, right-click commit Y and select Reset-> Delete Changes (--hard).

EDIT: As always, be careful when using git reset --hard either way, since it can potentially result in data loss.

Just this description should be enough to convince you that using git via command line is cleaner and it's much easier for people to explain stuff via native git commands. And,as @axiac recommended in the comments, reading the Git Book is definitely worth the time.

Title: Move commit to a new branch

Body:
I know it's supposed to be easy, only  I am new to Git and a little bit confused of its terminology (like HEAD or Origin for instance...are they the same ?)

At the moment I have the branch v4000 with the below commits :

---X-Y-Z (v4000 branch head)

I realized that branch v4000 Head should be at commit Y, and I need a new branch v4100 and move commit Z to that one :

---X-Y (v4000 head)
      \
       Z (v4100 head)

Can you please help me how to achieve this from within Visual Studio 2017 Team Explorer ?

Thank you in advance.


问:
What is meant by intercepting a Python call in the sys.exit documentation?
In the Python documentation, it is said that it is possible to intercept the exit call at the outer level. So what does "intercept at the outside level" actually mean here?
More specifically, what is meant by intercepting a call?</p>

答:
It means that an except SystemExit will catch the raised exception thereby intercepting the attempted call at exiting Python. sys.exit is implemented by raising SystemExit, which you can handle.

Using the appropriate except clause:

```<code>from sys import exit
try:
    exit("Exiting")
except SystemExit as e:
    print("Well, no you're not.")
</code>```

works just fine and continues on with execution. You intercepted it.

As @chepner notes, the call isn't being intercepted; the call to exit is completed. The resulting exception is intercepted by the except handler you provide.

Body:
It means that an except SystemExit will catch the raised exception thereby intercepting the attempted call at exiting Python. sys.exit is implemented by raising SystemExit, which you can handle.

Using the appropriate except clause:

from sys import exit
try:
    exit("Exiting")
except SystemExit as e:
    print("Well, no you're not.")

works just fine and continues on with execution. You intercepted it.

As @chepner notes, the call isn't being intercepted; the call to exit is completed. The resulting exception is intercepted by the except handler you provide.


问:
Remove null properties in Sesam DTL
Using Sesam I'm left with a bunch of null properties.

How would i proceed to skip properties that are null completely in DTL?
Any examples of DTL that does this would be great.

Example

From:

```<code>{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "column2": "null",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}
</code>```

To:

```<code>{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}
</code>```

Title: Remove null properties in Sesam DTL

Body:
Using Sesam I'm left with a bunch of null properties.

How would i proceed to skip properties that are null completely in DTL?
Any examples of DTL that does this would be great.

Example

From:

{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "column2": "null",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}

To:

{
  "address": "37484 Mohr Freeway\nNew Myrnaview, MI 89092",
  "birth_date": "2001-02-18",
  "column1": "01ba3bc2-8e22-4971-9683-b2ae05a39cd1",
  "company": "Fay-Cole",
  "credit_card": "4049553515365",
  "first_name": "Dummy",
  "home_page": "http://www.mante.com/faq/",
  "job": "Airline pilot",
  "last_name": "User",
}

Body:
Here are two different solutions:

Alternative 1:

{
  "_id": "test",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "test",
      "a": 1,
      "b": null,
      "c": 2,
      "d": null
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "*"],
        ["remove",
            ["filter",
              ["is-null",
                ["path", "_.", "_T."]
              ],
              ["keys", "_T."]
            ]
        ]
      ]
    }
  }
}

Alternative 2:

{
  "_id": "test",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "test",
      "a": 1,
      "b": null,
      "c": 2,
      "d": null
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "*"],
        ["remove",
          ["map",
            ["first", "_."],
            ["filter",
              ["is-null",
                ["last", "_."]
              ],
              ["items", "_T."]
            ]
          ]
        ]
      ]
    }
  }
}

Alternative 3:

{
  "_id": "test",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "test",
      "a": 1,
      "b": null,
      "c": 2,
      "d": null
    }]
  },
  "transform": {
    "type": "dtl",
    "rules": {
      "default": [
        ["copy", "*"],
        ["remove",
          ["map",
            ["nth", 0, "_."],
            ["filter",
              ["is-null",
                ["nth", 1, "_."]
              ],
              ["items", "_T."]
            ]
          ]
        ]
      ]
    }
  }
}

Result:

[
  {
    "_id": "test",
    "a": 1,
    "c": 2
  }
]


问:
Excel sheet is not genearting in IIS.but it working fine in local machine in asp.net. I have done all setings in Domconfig files
Excel sheet is not generating in IIS.but its working fine in local system.
I have done all settings in DOMCONFIG file. but still its not working</p>

答: Did you check the mime type settings in IIS? .xlsx or xls extension should be available.</p>


问:
How to do this task with `while` loop?
I don't know how to convert from for-loop to while-loop all my attempts have failed. I have the following code:

```<code>public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

int counter = 1;
</code>```

How can I convert this for-loops to while-loops?

```<code> //fill arr numbers from 1 to 10
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = counter++;
            }
        }

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

    }
}
</code>```

Output:

```<code>arr [ 0 ] = 1 2 3 4
arr [ 1 ] = 5 6
arr [ 2 ] = 7
arr [ 3 ] = 8 9 10
</code>```

答:
```<code>while(int i <arr.length)
{
   while(int j<arr[i].length)
   {
     arr[i][j] = counter++;
    j++;
   }
i++;
}

 while(int i <arr.length)
{
   System.out.print(" arr [ " + i + " ] = ");
   while(int j<arr[i].length)
   {
     System.out.print(arr[i][j] + " ");
    j++;
   }
 System.out.println(" ");
i++;
}
</code>```

This might help you.

Title: How to do this task with `while` loop?

Body:
I don't know how to convert from for-loop to while-loop all my attempts have failed. I have the following code:

public static void main(String[] args) {
    int[][] arr = new int[4][];
    arr[0] = new int[4];
    arr[1] = new int[2];
    arr[2] = new int[1];
    arr[3] = new int[3];

int counter = 1;

How can I convert this for-loops to while-loops?

 //fill arr numbers from 1 to 10
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = counter++;
            }
        }

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

    }
}

Output:

arr [ 0 ] = 1 2 3 4
arr [ 1 ] = 5 6
arr [ 2 ] = 7
arr [ 3 ] = 8 9 10

Body:
while(int i <arr.length)
{
   while(int j<arr[i].length)
   {
     arr[i][j] = counter++;
    j++;
   }
i++;
}

 while(int i <arr.length)
{
   System.out.print(" arr [ " + i + " ] = ");
   while(int j<arr[i].length)
   {
     System.out.print(arr[i][j] + " ");
    j++;
   }
 System.out.println(" ");
i++;
}

This might help you.


问:
How do I get the Materialize select dropdown to work with React?
Adding the following template code provided by Materialize doesn't immediately work in a React component:

```<code><div class="input-field col s12">
  <select>
    <option value="" disabled selected>Choose your option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>
  <label>Materialize Select</label>
</div>
</code>```

How do fix this so that the select dropdown works?

答:
The solution to this is to use browser default as the class name.

```<code><div class="input-field col s12">
  <select className="browser-default">
    <option value="" disabled selected>Choose your option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>
  <label>Materialize Select</label>
</div>
</code>```

Body:
Adding the following template code provided by Materialize doesn't immediately work in a React component:

  <select>
    <option value="" disabled selected>Choose your option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>
  Materialize Select

How do fix this so that the select dropdown works?

Body:
The solution to this is to use browser default as the class name.

<div class="input-field col s12">
  <select className="browser-default">
    <option value="" disabled selected>Choose your option</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>
  <label>Materialize Select</label>
</div>


答:
Objects in those lists are not necessarily equal if they have equal values.

Source code for removeAll

```<code>public boolean removeAll(Collection<?> c) {
    boolean modified = false;
    Iterator<?> e = iterator();
    while (e.hasNext()) {
        if (c.contains(e.next())) {
            e.remove();
            modified = true;
        }
    }
    return modified;
}
</code>```

It calls contains, which calls equalTo. This means you could override equalTo in the class of the objects you're trying to remove to check for a specific value such as GUID.

Title: Java: RemoveAll(Collection c) returns false

Body:
In my java code I have two arrayList one is assignedRiders and other is nearestRiders, and  I want to remove elements from nearestRiders list if it also exist in assignedRiders , for this I used following line but when I run this it returns me false even when they have same elements

Code

List<User> nearestRiders=new ArrayList<User>();
List<User> assignedRiders=new ArrayList<User>();
nearestRiders=riderLocationRepo.findNearestRiderList(orderRequest.getLatitudeShop(),
                    orderRequest.getLongitudeShop());
assignedRiders=orderAlredayAssigned();
Boolean dataChanhged=nearestRiders.removeAll(assignedRiders);

Body:
Objects in those lists are not necessarily equal if they have equal values.

Source code for removeAll

public boolean removeAll(Collection<?> c) {
    boolean modified = false;
    Iterator<?> e = iterator();
    while (e.hasNext()) {
        if (c.contains(e.next())) {
            e.remove();
            modified = true;
        }
    }
    return modified;
}

It calls contains, which calls equalTo. This means you could override equalTo in the class of the objects you're trying to remove to check for a specific value such as GUID.


问:
Filter ranges using Django Backend filter?
I am working on project using django rest framework in which i have to filter different parameters given by user.I am using django Filter backend.
 Here is my code:

```<code>class FilterViewSet(viewsets.ModelViewSet):

serializer_class = SearchSerializer

#Filters on specific fields
filter_backends = (DjangoFilterBackend,)

filter_fields = ('property_zipcode','property_state',
                 'property_county',
                 'property_city','property_area',)#range between 100 to 500 or area less then 500.

#range is pass by user as a property_area=300.

def filter_queryset(self, queryset):
    if self.request.query_params.get('property_state', None):
        queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset())
        return queryset
    else:
        queryset = self.get_queryset()
        return queryset
</code>```

Everything is working fine. But now i have to filter property_area based on range like 100 sqft to 500 sqft. How i can achieve this using djangoFilter backend?

答:
Thanks @Gabriel Muj. From the django-filter documentation i solved my problem. I created my own filter class added fields which is use for filters.

```<code>class Filter(django_filters.FilterSet):

    class Meta:
        model = Property
        fields = {
            'property_state': ['exact'],
            'year_built': ['lt', 'gt'],
            'tax':['lt','gt'],

        }
</code>```

Call it in Viewset:

```<code>    class FilterViewSet(viewsets.ModelViewSet):

          serializer_class = SearchSerializer

         #Filters on specific fields
          filter_class = Filter

        def filter_queryset(self, queryset):
             if self.request.query_params.get('property_state', None):
              queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset())
              return queryset
          else:
              queryset = self.get_queryset()
              return queryset
</code>```

Body:
I am working on project using django rest framework in which i have to filter different parameters given by user.I am using django Filter backend.
 Here is my code:

class FilterViewSet(viewsets.ModelViewSet):

serializer_class = SearchSerializer

#Filters on specific fields
filter_backends = (DjangoFilterBackend,)

filter_fields = ('property_zipcode','property_state',
                 'property_county',
                 'property_city','property_area',)#range between 100 to 500 or area less then 500.

#range is pass by user as a property_area=300.

def filter_queryset(self, queryset):
    if self.request.query_params.get('property_state', None):
        queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset())
        return queryset
    else:
        queryset = self.get_queryset()
        return queryset

Everything is working fine. But now i have to filter property_area based on range like 100 sqft to 500 sqft. How i can achieve this using djangoFilter backend?

Body:
Thanks @Gabriel Muj. From the django-filter documentation i solved my problem. I created my own filter class added fields which is use for filters.

class Filter(django_filters.FilterSet):

    class Meta:
        model = Property
        fields = {
            'property_state': ['exact'],
            'year_built': ['lt', 'gt'],
            'tax':['lt','gt'],

        }

Call it in Viewset:

    class FilterViewSet(viewsets.ModelViewSet):

          serializer_class = SearchSerializer

         #Filters on specific fields
          filter_class = Filter

        def filter_queryset(self, queryset):
             if self.request.query_params.get('property_state', None):
              queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset())
              return queryset
          else:
              queryset = self.get_queryset()
              return queryset


问:
Using bindings to control column order in a DataGrid
Problem

I have a WPF Toolkit DataGrid, and I'd like to be able to switch among several preset column orders. This is an MVVM project, so the column orders are stored in a ViewModel. The problem is, I can't get bindings to work for the DisplayIndex property. No matter what I try, including the sweet method in this Josh Smith tutorial, I get:

The DisplayIndex for the DataGridColumn with Header 'ID' is out of range.  DisplayIndex must be greater than or equal to 0 and less than Columns.Count. Parameter name: displayIndex. Actual value was -1.

Is there any workaround for this?

I'm including my test code below. Please let me know if you see any problems with it.

ViewModel code

```<code>public class MainViewModel
{
    public List<Plan> Plans { get; set; }
    public int IdDisplayIndex { get; set; }
    public int NameDisplayIndex { get; set; }
    public int DescriptionDisplayIndex { get; set; }

    public MainViewModel()
    {
        Initialize();
    }

    private void Initialize()
    {
        IdDisplayIndex = 1;
        NameDisplayIndex = 2;
        DescriptionDisplayIndex = 0;
        Plans = new List<Plan>
        {
            new Plan { Id = 1, Name = "Primary", Description = "Likely to work." },
            new Plan { Id = 2, Name = "Plan B", Description = "Backup plan." },
            new Plan { Id = 3, Name = "Plan C", Description = "Last resort." }
        };
    }
}
</code>```

Plan Class

```<code>public class Plan
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}
</code>```

Window code - this uses Josh Smith's DataContextSpy

```<code><Window
    x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:mwc="http://schemas.microsoft.com/wpf/2008/toolkit"
    Title="Main Window" Height="300" Width="300">
    <Grid>
        <mwc:DataGrid ItemsSource="{Binding Plans}" AutoGenerateColumns="False">
            <mwc:DataGrid.Resources>
                <local:DataContextSpy x:Key="spy" />
            </mwc:DataGrid.Resources>
            <mwc:DataGrid.Columns>
                <mwc:DataGridTextColumn
                    Header="ID"
                    Binding="{Binding Id}"
                    DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.IdDisplayIndex}" />
                <mwc:DataGridTextColumn
                    Header="Name"
                    Binding="{Binding Name}"
                    DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.NameDisplayIndex}" />
                <mwc:DataGridTextColumn
                    Header="Description"
                    Binding="{Binding Description}"
                    DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.DescriptionDisplayIndex}" />
            </mwc:DataGrid.Columns>
        </mwc:DataGrid>
    </Grid>
</Window>
</code>```

Note: If I just use plain numbers for DisplayIndex, everything works fine, so the problem is definitely with the bindings.

Update 5/1/2010

I was just doing a little maintenance on my project, and I noticed that when I ran it, the problem I discuss in this post had returned. I knew that it worked last time I ran it, so I eventually narrowed the problem down to the fact that I had installed a newer version of the WPF Toolkit (Feb '10). When I reverted to the June '09 version, everything worked fine again. So, I'm now doing something I should have done in the first place: I'm including the WPFToolkit.dll that works in my solution folder and checking it into version control. It's unfortunate, though, that the newer toolkit has a breaking change.

答:
Set FallbackValue=<idx> in your DisplayIndex binding, where <idx> is your column's index.  For example:

```<code>DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.IdDisplayIndex, FallbackValue=0}" />
</code>```

Body:
Problem

I have a WPF Toolkit DataGrid, and I'd like to be able to switch among several preset column orders. This is an MVVM project, so the column orders are stored in a ViewModel. The problem is, I can't get bindings to work for the DisplayIndex property. No matter what I try, including the sweet method in this Josh Smith tutorial, I get:

The DisplayIndex for the DataGridColumn with Header 'ID' is out of range.  DisplayIndex must be greater than or equal to 0 and less than Columns.Count. Parameter name: displayIndex. Actual value was -1.

Is there any workaround for this?

I'm including my test code below. Please let me know if you see any problems with it.

ViewModel code

public class MainViewModel
{
    public List<Plan> Plans { get; set; }
    public int IdDisplayIndex { get; set; }
    public int NameDisplayIndex { get; set; }
    public int DescriptionDisplayIndex { get; set; }

    public MainViewModel()
    {
        Initialize();
    }

    private void Initialize()
    {
        IdDisplayIndex = 1;
        NameDisplayIndex = 2;
        DescriptionDisplayIndex = 0;
        Plans = new List<Plan>
        {
            new Plan { Id = 1, Name = "Primary", Description = "Likely to work." },
            new Plan { Id = 2, Name = "Plan B", Description = "Backup plan." },
            new Plan { Id = 3, Name = "Plan C", Description = "Last resort." }
        };
    }
}

Plan Class

public class Plan
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

Window code - this uses Josh Smith's DataContextSpy

<Window
    x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    xmlns:mwc="http://schemas.microsoft.com/wpf/2008/toolkit"
    Title="Main Window" Height="300" Width="300">
    <Grid>
        <mwc:DataGrid ItemsSource="{Binding Plans}" AutoGenerateColumns="False">
            <mwc:DataGrid.Resources>
                <local:DataContextSpy x:Key="spy" />
            </mwc:DataGrid.Resources>
            <mwc:DataGrid.Columns>
                <mwc:DataGridTextColumn
                    Header="ID"
                    Binding="{Binding Id}"
                    DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.IdDisplayIndex}" />
                <mwc:DataGridTextColumn
                    Header="Name"
                    Binding="{Binding Name}"
                    DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.NameDisplayIndex}" />
                <mwc:DataGridTextColumn
                    Header="Description"
                    Binding="{Binding Description}"
                    DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.DescriptionDisplayIndex}" />
            </mwc:DataGrid.Columns>
        </mwc:DataGrid>
    </Grid>
</Window>

Note: If I just use plain numbers for DisplayIndex, everything works fine, so the problem is definitely with the bindings.

Update 5/1/2010

I was just doing a little maintenance on my project, and I noticed that when I ran it, the problem I discuss in this post had returned. I knew that it worked last time I ran it, so I eventually narrowed the problem down to the fact that I had installed a newer version of the WPF Toolkit (Feb '10). When I reverted to the June '09 version, everything worked fine again. So, I'm now doing something I should have done in the first place: I'm including the WPFToolkit.dll that works in my solution folder and checking it into version control. It's unfortunate, though, that the newer toolkit has a breaking change.

Body:
Set FallbackValue=<idx> in your DisplayIndex binding, where <idx> is your column's index.  For example:

DisplayIndex="{Binding Source={StaticResource spy}, Path=DataContext.IdDisplayIndex, FallbackValue=0}" />


问:
Companion objects benefits of posibility to implement interfaces
Why in Kotlin/Scala companion objects can implements some interfaces, what benefits this can have? When is useful to use this feature?</p>

答:
Because companion objects are objects, objects can implement interfaces (or extend classes), and there is no good reason to disallow it for companion objects in particular.

One common use in Scala is for factories: e.g. Seq, List, Vector etc. companion objects all extend TraversableFactory so you can write code working with a TraversableFactory and pass any of them to construct the type you want. E.g.

```<code>def build[CC[X] <: Traversable[X] with GenericTraversableTemplate[X, CC], A](factory: TraversableFactory[CC])(elems: A*) = factory(elems)

// build(List)(1,2,3) == List(1, 2, 3)
// build(Set)(1,2,3) == Set(1, 2, 3)
</code>```

Similarly, all case class companion objects extend function types.

Body:
Because companion objects are objects, objects can implement interfaces (or extend classes), and there is no good reason to disallow it for companion objects in particular.

One common use in Scala is for factories: e.g. Seq, List, Vector etc. companion objects all extend TraversableFactory so you can write code working with a TraversableFactory and pass any of them to construct the type you want. E.g.

def build[CC[X] <: Traversable[X] with GenericTraversableTemplate[X, CC], A](factory: TraversableFactory[CC])(elems: A*) = factory(elems)

// build(List)(1,2,3) == List(1, 2, 3)
// build(Set)(1,2,3) == Set(1, 2, 3)

Similarly, all case class companion objects extend function types.


问:
Dynamic number of series with one query in Grafana
Is there a way to get multiple series in one query using Postgres connection in Grafana? Let’s say I have 5 attributes associated to my data and I’d like to display 5 series using one query so it’s dynamic.

When one attribute is added or removed, so is done with series.

```<code>attribute | bits    | created_at
------------------------------
1         | 44632   | <datetime>
4         | 124854  | <datetime>
2         | 488     | <datetime>
2         | 8       | <datetime>
4         | 384332  | <datetime>
3         | 44632   | <datetime>
1         | 6732    | <datetime>
3         | 162     | <datetime>
</code>```

Example query:

```<code>SELECT
    $__time(created_at),
    sum(bits),
    attribute
FROM
    table
WHERE
    $__timeFilter(created_at)
GROUP BY created_at, attribute
ORDER BY created_at;
</code>```

and attribute has distinct values (1, 2, 3, 4) so I get 4 different series, each showing data for specific attribute’s value using some kind of similar query.

Is there a way to do that?

答:
you would want to group based on attribute, like you are doing in the example.

The exact query you would need is something like this:

```<code>SELECT
    $__time(created_at),
    attribute as metric,
    sum(bits)
FROM
    table
WHERE
    $__timeFilter(created_at)
GROUP BY created_at, attribute
ORDER BY created_at;
</code>```

by giving the 'metric' alias to attribute, it will be picked up as the name of the individual timeseries and the grouping should take care of the rest

Body:
Is there a way to get multiple series in one query using Postgres connection in Grafana? Let’s say I have 5 attributes associated to my data and I’d like to display 5 series using one query so it’s dynamic.

When one attribute is added or removed, so is done with series.

attribute | bits    | created_at
------------------------------
1         | 44632   | <datetime>
4         | 124854  | <datetime>
2         | 488     | <datetime>
2         | 8       | <datetime>
4         | 384332  | <datetime>
3         | 44632   | <datetime>
1         | 6732    | <datetime>
3         | 162     | <datetime>

Example query:

SELECT
    $__time(created_at),
    sum(bits),
    attribute
FROM
    table
WHERE
    $__timeFilter(created_at)
GROUP BY created_at, attribute
ORDER BY created_at;

and attribute has distinct values (1, 2, 3, 4) so I get 4 different series, each showing data for specific attribute’s value using some kind of similar query.

Is there a way to do that?

Body:
you would want to group based on attribute, like you are doing in the example.

The exact query you would need is something like this:

SELECT
    $__time(created_at),
    attribute as metric,
    sum(bits)
FROM
    table
WHERE
    $__timeFilter(created_at)
GROUP BY created_at, attribute
ORDER BY created_at;

by giving the 'metric' alias to attribute, it will be picked up as the name of the individual timeseries and the grouping should take care of the rest


问:
DateTime culture issue in Entity Framework
I use Entity Framework with a code-first approach to send a model to database (which is SQL Server 2014).

The model has 2 DateTime fields and one of them is user input. I store it in a datetime? variable and then EF does the rest to store the model in the database.

My project is multi culture and when I am using another culture like fa-ir, then EF shows the following error :

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.

It works in windows 2014 and newer which have Persian culture but not in previous versions which didn't support Persian culture.

Any solution?

答:
SQL datetime data type only supports dates from 1753-01-01 to 9999-12-31.

But current year in persian calendar is 1396.

So you have to change the SQL column to datetime2 data type which supports 0001-01-01 to 9999-12-31.


问:
Why does SFAuthenticationSession prompt for consent every time?
I'm using SFAuthenticationSession with SSO and OAuth.

When calling the start() method, iOS pops up a consent dialog asking the user to allow the app to use the OAuth provider. The consent popup appears every time the authentication session is started.

Is this by design? It seems like it should appear once, like other consent dialogs.

答: This is by design yes. There is really nothing you can do to avoid the consent dialog as of now when using SFAuthenticationSession, it's working as Apple wanted it to work. Check out Apple's own documentation on SFAuthenticationSession here


答:
```<code>int i = 0;
while ( i < arr.length ) {
int j = 0;
    while ( j < arr[i].length;)
       {
        arr[i][j] = counter++;
       j++;
       }
i++;
}
</code>```

Then print value

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

Title: How to do this task with `while` loop?

Body:
int i = 0;
while ( i < arr.length ) {
int j = 0;
    while ( j < arr[i].length;)
       {
        arr[i][j] = counter++;
       j++;
       }
i++;
}

Then print value

int i = 0;
while ( i < arr.length ) {
    System.out.print(" arr [ " + i + " ] = ");
    int j = 0;
    while ( j < arr[i].length) {
        System.out.print(arr[i][j] + " ");
     j++;
    }
    System.out.println(" ");
i++;
}


答:
for loop is basically a compact way of writing while loop.

```<code>for (int i = 0; i < arr.length; i++) {
  ...
}
</code>```

is same as :

```<code>int i=0;
while(i<arr.length){
  ....
  i++;

}
</code>```

Title: How to do this task with `while` loop?

Body:
for loop is basically a compact way of writing while loop.

for (int i = 0; i < arr.length; i++) {
  ...
}

is same as :

int i=0;
while(i<arr.length){
  ....
  i++;

}


问:
Invalid heap address and fatal signal 11 while decoding json string into java object
I am calling a static method updateHistory(String message) of class DrawingView from another class useActivity multiple times. The statement inside updateHistory method(marked inside code section) creates runtime exception as

```<code>A/libc(8006): @@@ ABORTING: LIBC: ARGUMENT IS INVALID HEAP ADDRESS IN dlfree addr=0x6552d4a8
A/libc(8006): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 8015 (FinalizerDaemon)
</code>```

useActivity.java

```<code>public class UseActivity extends Activity implements Observer {
public void onCreate(Bundle savedInstanceState){...}
...
public void updateHistory{
...
for loop(10 times){
DrawingView.updateHistory(message); //called 10 times & message is a string changes every time
}
...
...
}//class ends
</code>```

DrawingView.java

```<code>public class DrawingView extends View  implements OnTouchListener  {
public static  DrawingView my_View=null;

public DrawingView(Context context, AttributeSet attr) {
super(context);
my_View=this;
...
}

public static void updateHistory(String json){

Gson gson2=new Gson();

ArrayList<Pair<Path, Paint>> my_Paths=gson2.fromJson(json,new TypeToken<ArrayList<Pair<Path,Paint>>>(){}.getType());
//The above statement creates problem
...
}

}//class ends
</code>```

How can i change that statement as gson2.fromJson creates new arraylist object every time the method called.

NOTE

My basic objective is to convert the json string(previously encoded from ArrayList of Path) into ArrayList of Paths and draw them over canvas.

答:
I have noticed this issue using fromJson method.
To avoid this error, change this part of code to someting like that:

```<code>JSONObject json = new JSONObject(str);

Location objLocation = new Location("");
objLocation.setLatitude(json.getDouble("mLatitude"));
objLocation.setLongitude(json.getDouble("mLongitude"));
objLocation.setTime(json.getLong("mTime"));
objLocation.setAccuracy( (float)
json.getDouble("mAccuracy"));
objLocation.setAltitude( json.getDouble("mAltitude"));
objLocation.setBearing( (float) json.getDouble("mBearing"));
objLocation.setElapsedRealtimeNanos( json.getLong("mElapsedRealtimeNanos"));
objLocation.setSpeed( (float) json.getDouble("mSpeed"));
</code>```

Body:
I am calling a static method updateHistory(String message) of class DrawingView from another class useActivity multiple times. The statement inside updateHistory method(marked inside code section) creates runtime exception as

A/libc(8006): @@@ ABORTING: LIBC: ARGUMENT IS INVALID HEAP ADDRESS IN dlfree addr=0x6552d4a8
A/libc(8006): Fatal signal 11 (SIGSEGV) at 0xdeadbaad (code=1), thread 8015 (FinalizerDaemon)

useActivity.java

public class UseActivity extends Activity implements Observer {
public void onCreate(Bundle savedInstanceState){...}
...
public void updateHistory{
...
for loop(10 times){
DrawingView.updateHistory(message); //called 10 times & message is a string changes every time
}
...
...
}//class ends

DrawingView.java

public class DrawingView extends View  implements OnTouchListener  {
public static  DrawingView my_View=null;

public DrawingView(Context context, AttributeSet attr) {
super(context);
my_View=this;
...
}

public static void updateHistory(String json){

Gson gson2=new Gson();

ArrayList<Pair<Path, Paint>> my_Paths=gson2.fromJson(json,new TypeToken<ArrayList<Pair<Path,Paint>>>(){}.getType());
//The above statement creates problem
...
}

}//class ends

How can i change that statement as gson2.fromJson creates new arraylist object every time the method called.

NOTE

My basic objective is to convert the json string(previously encoded from ArrayList of Path) into ArrayList of Paths and draw them over canvas.

Body:
I have noticed this issue using fromJson method.
To avoid this error, change this part of code to someting like that:

JSONObject json = new JSONObject(str);

Location objLocation = new Location("");
objLocation.setLatitude(json.getDouble("mLatitude"));
objLocation.setLongitude(json.getDouble("mLongitude"));
objLocation.setTime(json.getLong("mTime"));
objLocation.setAccuracy( (float)
json.getDouble("mAccuracy"));
objLocation.setAltitude( json.getDouble("mAltitude"));
objLocation.setBearing( (float) json.getDouble("mBearing"));
objLocation.setElapsedRealtimeNanos( json.getLong("mElapsedRealtimeNanos"));
objLocation.setSpeed( (float) json.getDouble("mSpeed"));


问:
Efficient Packet types/transfer protocol
Using boost::asio in C++, I'm trying to determine the best way to encrypt packets in my program. I thought of defining packets all by myself by type number, each with different fixed packet sizes. The system reads the header (type, and quantity of entries for lists of data) and creates the appropriate structure to receive the data, then it reacts according to the data received.

However, when I look at this method, I wonder if there would be a simpler way to accomplish this without sacrificing efficiency.

These packets are to be sent between different applications trough TCP. Ideally, I'm aiming at both applications using as least bandwidth and CPU as possible while also being as simple to modify as possible. Any suggestions?

答: Have you considered google protobufs? While it doesn't actually do the encryption (you'll have to do that yourself), it does provide a way of encoding the structured data allowing you to send it over the wire efficiently. Additionally, there are many language bindings for it (C++, Java, and Python off the top of my head).</p>


问:
Run different class based on variable name?
Let's say we have a few different classes: ClassA, ClassB, ClassC, and ClassD. I have a variable I will set based on different circumstances. I know what it will be ahead of time, but I don't want to have to rewrite many different lines of code in different files each time I need to change it. It is NOT user set.

So now we have
Variable = ClassX

So, Let's say I set Variable to ClassA. How can I make it call ClassA using just that? For example, I know I can do this:

```<code>Variable = ClassA
if Variable == ClassA:
     # Call ClassA and run it
elif Variable == ClassB:
     # Call ClassB and run it
elif Variable == ClassC:
     # Call ClassC and run it
elif Variable == ClassD:
     # Call ClassD and run it
</code>```

However, I want to do something like this:

```<code>Variable = ClassA
V = Variable()
</code>```

Is this possible?

EDIT:
A little more detail...

So I have 3 files that are used in this scenario.

File1.py:

```<code># Class = ClassA
# Class = ClassB
Class = ClassC
# Class = ClassD
...
if Class == "ClassA":
    c = ClassSystem.ClassA
    short_name = c.get_short_name()
elif Class == "ClassB":
    c = ClassSystem.ClassB
    short_name = c.get_short_name()
elif Class == "ClassC":
    c = ClassSystem.ClassC
    short_name = c.get_short_name()
elif Class == "ClassD":
    c = ClassSystem.ClassD
    short_name = c.get_short_name()
...
</code>```

File2.py:

```<code>from Folder.File1 import short_name
from Folder.ClassSystem import *
...
S = short_name()
S.get_information()
</code>```

This doesn't seem to work. File2 is referencing the variable from file1. I then need File2 to use the variable from File1 to run the same class in ClassSystem.

答:
You can use eval,

```<code>c_name = 'ClassA'
obj = eval(c_name)()
</code>```

but i am not sure if eval is the recommended way to do this.

Body:
Let's say we have a few different classes: ClassA, ClassB, ClassC, and ClassD. I have a variable I will set based on different circumstances. I know what it will be ahead of time, but I don't want to have to rewrite many different lines of code in different files each time I need to change it. It is NOT user set.

So now we have
Variable = ClassX

So, Let's say I set Variable to ClassA. How can I make it call ClassA using just that? For example, I know I can do this:

Variable = ClassA
if Variable == ClassA:
     # Call ClassA and run it
elif Variable == ClassB:
     # Call ClassB and run it
elif Variable == ClassC:
     # Call ClassC and run it
elif Variable == ClassD:
     # Call ClassD and run it

However, I want to do something like this:

Variable = ClassA
V = Variable()

Is this possible?

EDIT:
A little more detail...

So I have 3 files that are used in this scenario.

File1.py:

# Class = ClassA
# Class = ClassB
Class = ClassC
# Class = ClassD
...
if Class == "ClassA":
    c = ClassSystem.ClassA
    short_name = c.get_short_name()
elif Class == "ClassB":
    c = ClassSystem.ClassB
    short_name = c.get_short_name()
elif Class == "ClassC":
    c = ClassSystem.ClassC
    short_name = c.get_short_name()
elif Class == "ClassD":
    c = ClassSystem.ClassD
    short_name = c.get_short_name()
...

File2.py:

from Folder.File1 import short_name
from Folder.ClassSystem import *
...
S = short_name()
S.get_information()

This doesn't seem to work. File2 is referencing the variable from file1. I then need File2 to use the variable from File1 to run the same class in ClassSystem.

Body:
You can use eval,

c_name = 'ClassA'
obj = eval(c_name)()

but i am not sure if eval is the recommended way to do this.


问:
simple String example
i have the following piece of code but i could not detect why there is no output
when i debug it , the control flow is never goes inside for loop but i cannot figure out why </p>

<p>could anyone please help me ?
 here is my code </p>

```<code>public class DealWithStrings {
    ArrayList<String> container = new ArrayList<>();

    public void printDuplicate() {
        String string = "aaabed";
        String[] res = string.split("");

        for (int i = 1; i < string.length(); i++) {
            if (res[i] == res[i - 1]) {
                container.add(res[i]);
            }
        }

        for (String s : container) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        DealWithStrings d = new DealWithStrings();
        d.printDuplicate();
    }
}
</code>```

答:
Compare String using .equals, not ==

Instead of

```<code>if(res[i]==res[i-1])
</code>```

Use

```<code>if(res[i].equals(res[i-1]))
</code>```

== will evaluate to true if the objects are the same, and in this case they never are. .equals will check if the contents of the Strings (the actual text) are the same.

Title: simple String example

Body:
i have the following piece of code but i could not detect why there is no output
when i debug it , the control flow is never goes inside for loop but i cannot figure out why

could anyone please help me ?
 here is my code

public class DealWithStrings {
    ArrayList<String> container = new ArrayList<>();

    public void printDuplicate() {
        String string = "aaabed";
        String[] res = string.split("");

        for (int i = 1; i < string.length(); i++) {
            if (res[i] == res[i - 1]) {
                container.add(res[i]);
            }
        }

        for (String s : container) {
            System.out.println(s);
        }
    }

    public static void main(String[] args) {
        DealWithStrings d = new DealWithStrings();
        d.printDuplicate();
    }
}

Body:
Compare String using .equals, not ==

Instead of

if(res[i]==res[i-1])

Use

if(res[i].equals(res[i-1]))

== will evaluate to true if the objects are the same, and in this case they never are. .equals will check if the contents of the Strings (the actual text) are the same.


问:
Uncaught Error: [$injector:modulerr] while using external js file
Uncaught Error: [$injector:modulerr] this is the error I'm getting only when I'm using an external js file for my code otherwise if I just copy the angular code in the html/php file it just works.

index.php

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

    <script src="angular.min.js"></script>
    <script src="app.js"></script>
    <title>Learn</title>
</head>
<body ng-app="myApp">
    <div class="container" ng-controller="myCtrl" >

    </div>
</body>
</html>
</code>```

app.js

```<code>(function(){
    var app = angular.module('myApp', ["ngRoute"]);

    app.controller('myCtrl', function($scope){

    });

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

Error :

```<code>angular.min.js:sourcemap:7 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.6/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.6%2F%24injector%2Fmodulerr%3Fp0%3DngRoute%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.6.6%252F%2524injector%252Fnomod%253Fp0%253DngRoute%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A7%253A76%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A408%250A%2520%2520%2520%2520at%2520b%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A25%253A439)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A182%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A290%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A322%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20hb%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A332)
    at angular.min.js:sourcemap:7
    at angular.min.js:sourcemap:43
    at p (angular.min.js:sourcemap:8)
    at g (angular.min.js:sourcemap:42)
    at hb (angular.min.js:sourcemap:46)
    at c (angular.min.js:sourcemap:22)
    at Uc (angular.min.js:sourcemap:22)
    at we (angular.min.js:sourcemap:21)
    at angular.min.js:sourcemap:334
    at HTMLDocument.b (angular.min.js:sourcemap:38)
</code>```

答:
If you are using Angular Routing("ngRoute") as dependency Injection you have to add routing script below angular in your html file.

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
</code>```

or else remove dependency array.

```<code>var app = angular.module('myApp', []);
</code>```

Body:
Uncaught Error: [$injector:modulerr] this is the error I'm getting only when I'm using an external js file for my code otherwise if I just copy the angular code in the html/php file it just works.

index.php

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css">

    <title>Learn</title>

app.js

(function(){
    var app = angular.module('myApp', ["ngRoute"]);

    app.controller('myCtrl', function($scope){

    });

})();

Error :

angular.min.js:sourcemap:7 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.6/$injector/modulerr?p0=myApp&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.6.6%2F%24injector%2Fmodulerr%3Fp0%3DngRoute%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.6.6%252F%2524injector%252Fnomod%253Fp0%253DngRoute%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A7%253A76%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A408%250A%2520%2520%2520%2520at%2520b%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A25%253A439)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A26%253A182%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A290%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A322%250A%2520%2520%2520%2520at%2520p%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A8%253A7)%250A%2520%2520%2520%2520at%2520g%2520(http%253A%252F%252Flocalhost%252Fang%252Fangular.min.js%253A42%253A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A7%3A76%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A43%3A70%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A322%0A%20%20%20%20at%20p%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A8%3A7)%0A%20%20%20%20at%20g%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A42%3A138)%0A%20%20%20%20at%20hb%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A46%3A250)%0A%20%20%20%20at%20c%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A19)%0A%20%20%20%20at%20Uc%20(http%3A%2F%2Flocalhost%2Fang%2Fangular.min.js%3A22%3A332)
    at angular.min.js:sourcemap:7
    at angular.min.js:sourcemap:43
    at p (angular.min.js:sourcemap:8)
    at g (angular.min.js:sourcemap:42)
    at hb (angular.min.js:sourcemap:46)
    at c (angular.min.js:sourcemap:22)
    at Uc (angular.min.js:sourcemap:22)
    at we (angular.min.js:sourcemap:21)
    at angular.min.js:sourcemap:334
    at HTMLDocument.b (angular.min.js:sourcemap:38)

Body:
If you are using Angular Routing("ngRoute") as dependency Injection you have to add routing script below angular in your html file.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

or else remove dependency array.

var app = angular.module('myApp', []);


问:
React hot loader not working with styled-components
I am using react-hot-loader version 3.1.3, styled-components version 2.2.0 and react 16. This is the error message i get in the console. I've tried downgrading styled-components to version 2.0.0 and downgrading react-hot-loader to version 3.0.0 but it still does not work and so i am using the latest version of those scripts.

React Hot Loader: this component is not accepted by Hot Loader. Please check is it extracted as a top level class, a function or a variable.

Click below to reveal the source location: ƒ StyledComponent() { classCallCheck(this, StyledComponent); return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments)); }

I have one styled component like so:

```<code>const Li = styled.li`
  padding: 10px;
  padding-bottom: 20px;
  margin: 0;
  font-size: 14px;
  color: #333`;
</code>```

And at the top of my script i am importing styled like so:

```<code>import styled from 'styled-components';
</code>```

And here is my index.js file's content:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './assets/css/index.css';
import App from './components/App/App';
import { BrowserRouter } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';
import { AppContainer } from 'react-hot-loader';

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <BrowserRouter>
        <Component/>
      </BrowserRouter>
    </AppContainer>,
    document.getElementById('root')
  );
}

render(App);

if (module.hot){
  module.hot.accept( './components/App/App', () => { render(App) });
}

registerServiceWorker();
</code>```

答:
I think this is happening due to this issue of react-hot-loader.

Try to wrap the following portion of your code into a standalone component

```<code><BrowserRouter>
   <Component/>
</BrowserRouter>
</code>```

Then, import the exported component in index.js and place it between AppContainer tag.

Note: Hot module replacement doed not work with styled-components v2.2.1 due to this issue. As you are using v2.2.0, you should not encounter this problem.

Body:
I am using react-hot-loader version 3.1.3, styled-components version 2.2.0 and react 16. This is the error message i get in the console. I've tried downgrading styled-components to version 2.0.0 and downgrading react-hot-loader to version 3.0.0 but it still does not work and so i am using the latest version of those scripts.

React Hot Loader: this component is not accepted by Hot Loader. Please check is it extracted as a top level class, a function or a variable.

Click below to reveal the source location: ƒ StyledComponent() { classCallCheck(this, StyledComponent); return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments)); }

I have one styled component like so:

const Li = styled.li`
  padding: 10px;
  padding-bottom: 20px;
  margin: 0;
  font-size: 14px;
  color: #333`;

And at the top of my script i am importing styled like so:

import styled from 'styled-components';

And here is my index.js file's content:

import React from 'react';
import ReactDOM from 'react-dom';
import './assets/css/index.css';
import App from './components/App/App';
import { BrowserRouter } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';
import { AppContainer } from 'react-hot-loader';

const render = Component => {
  ReactDOM.render(
    <AppContainer>
      <BrowserRouter>
        <Component/>
      </BrowserRouter>
    </AppContainer>,
    document.getElementById('root')
  );
}

render(App);

if (module.hot){
  module.hot.accept( './components/App/App', () => { render(App) });
}

registerServiceWorker();

Body:
I think this is happening due to this issue of react-hot-loader.

Try to wrap the following portion of your code into a standalone component

<BrowserRouter>
   <Component/>
</BrowserRouter>

Then, import the exported component in index.js and place it between AppContainer tag.

Note: Hot module replacement doed not work with styled-components v2.2.1 due to this issue. As you are using v2.2.0, you should not encounter this problem.


问:
Textview doesn't display anything if the string is over 18175 characters long
I have a textview that has its text set from a local xml file. Anytime the string is over 18175 characters long, the entire textview is blank. Anything at 18175 or under will display perfectly fine.

This only happens on OS 2.1 and under. I've tried looking around for a similar issue but have not had any luck. Does anyone know if this is a bug?

答:
I'd assume that for OS 2.1 and below nobody thought of a device that would be able to display that many characters at the same time.

If you have a larger String or buffer, you might display parts of it via the public final void setText (char[] text, int start, int len) method.

There are various places where Android provides quite sharp resource limits - another example is the default stack size which is so small that it broke recursive methods for me.