问:
Changing an array code to a vector
So I have been trying to look all over, but can't seem to find a whole lot on what exactly needs to be changed in order to convert an array to vector.  Or rather, I suppose I just don't know what exactly to search for.

The array is this:

```<code>public class Member{

 private int id;
 private String name;
 private String[] books = new String[5];
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String[] getBooks(){
     return books;
 }

 public void setBooks(String[] pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books[x] + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String[] args) {
    String[] list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books[i] = list[i];
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books[x] = list[i];
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}
</code>```

Now, I have been trying to convert it, but to be honest, I don't know what I am doing.

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

public class Member{

 private int id;
 private String name;
 private Vector<String> books = new Vector<String>(5);
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String getBooks(){
     return books;
 }

 public void setBooks(String pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books<x> + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String args) {
    String list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books<i> = list<i>;
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books<x> = list<i>;
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}
</code>```

Any help would be greatly appreciated.

答:
Alex,
If your code does not need to be safe in a multi threaded environment, as everyone suggested you should use ArrayList.

In case, you have concurrent operations, you may want to have a look at  Collections.synchronizedList. However, do check some of the limitations of using that as given here

Lastly, there are some situations where vector is necessary. There I would recommended Vector<String> v = new Vector<String>(Arrays.asList(myList)) as suggested by Mike earlier.

Title: Changing an array code to a vector

Body:
So I have been trying to look all over, but can't seem to find a whole lot on what exactly needs to be changed in order to convert an array to vector.  Or rather, I suppose I just don't know what exactly to search for.

The array is this:

public class Member{

 private int id;
 private String name;
 private String[] books = new String[5];
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String[] getBooks(){
     return books;
 }

 public void setBooks(String[] pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books[x] + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String[] args) {
    String[] list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books[i] = list[i];
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books[x] = list[i];
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}

Now, I have been trying to convert it, but to be honest, I don't know what I am doing.

import java.util.Vector;

public class Member{

 private int id;
 private String name;
 private Vector<String> books = new Vector<String>(5);
 //replace the String books array with a Vector variable named books
 //that functions exactly the same way

 public Member() {
     id = 0;
     name = "John Doe";
 }

 public Member(int pId, String pName) {
     id = pId;
     name = pName;
 }

 public int getId(){
     return id;
 }

 public void setId(int pId){
     id=pId;
 }

 public String getName(){
     return name;
 }

 public void setName(String pName){
     name=pName;
 }

 public String getBooks(){
     return books;
 }

 public void setBooks(String pBooks){
     books=pBooks;
 }

 public String toString(){
     StringBuffer buf = new StringBuffer();
     buf.append("ID: " + getId() + "  Member: " + getName() + "\n");
     for(int x=0; x<books.length; x++ ) {
         buf.append("Book: " + books<x> + "\n");
     }
     return buf.toString();
 }

/**
 * @param args
 */
public static void main(String args) {
    String list = {"Java Data Structures", "The Bible", "Grapes of Wrath",
                    "Goldfinger", "Sam I Am", "The Cat in the Hat", "Shawshenk Redemption",
                    "Green Eggs and Ham", "Linus and Lucy", "Abraham Lincoln"};

    Member m1 = new Member();
    m1.setId(431);
    m1.setName("William Wallace");
    for(int i=0; i<5; i++) {
        m1.books = list;
    }

    Member m2 = new Member(7010, "Bonny Clyde");
    for(int i=5; i<list.length; i++) {
        int x = i-5;
        m2.books<x> = list;
    }

    System.out.println(m1.toString());
    System.out.println();
    System.out.println(m2.toString());
}

}

Any help would be greatly appreciated.


来源: stackexchange

问:
In C++, how do i use like strncmp function in C?
In C++, Isn`t there string function like strncmp() in C ???

for example

```<code>string str1 = "abc";
string str2 = "ab";

str2.compare(0,1,str1) == 0
</code>```

is it possible??

答:
std::string has overloaded its '==' operator. Just if (a == b) works.
Interestingly even (a < b) works and applies a lexical ordering.

EDIT: Since the TE seems to ask about the equality of the length of strings after all, not their actual letters:

```<code>if (str1.length() == str2.length())
{

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In C++, Isn`t there string function like strncmp() in C ???

for example

string str1 = "abc";
string str2 = "ab";

str2.compare(0,1,str1) == 0

is it possible??

Body:
std::string has overloaded its '==' operator. Just if (a == b) works.
Interestingly even (a < b) works and applies a lexical ordering.

EDIT: Since the TE seems to ask about the equality of the length of strings after all, not their actual letters:

if (str1.length() == str2.length())
{

}


问:
Recycler View can't display mysql data
please help me on this code.
I want to display data from mysql and display it to android. I inserted data in my mysql and display on my android how many data are in my mysql so that i know if my android app can read all my data from mysql, but when i run my android app, it says that no data. Please help me

Android code...

```<code>data_list = new ArrayList<>();
    load_data_from_server();
    gridLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(gridLayoutManager);

    adapter = new CustomAdapter(this, data_list);
    recyclerView.setAdapter(adapter);

if (adapter.getItemCount() == 0){
        Toast.makeText(this, "Empty", Toast.LENGTH_SHORT).show();
    }

private void load_data_from_server() {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.43.147/webapp/travelplanning.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());

                for(int i = 0; i < array.length(); i++){
                    JSONObject object = array.getJSONObject(i);
                    MyData data = new MyData(object.getInt("ID"), object.getString("AttractionName"), object.getString("Location"));

                    data_list.add(data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter.notifyDataSetChanged();
        }
    };
}
</code>```

Adapter...

```<code>public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;

public CustomAdapter(Context context, List<MyData> my_data) {
    this.context = context;
    this.my_data = my_data;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.travel_planning_card, parent, false);
    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.id.setText(my_data.get(position).getId());
    holder.attractionName.setText(my_data.get(position).getAttractioName());
    holder.location.setText(my_data.get(position).getLocation());
}

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

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView attractionName, location, id;
    public ImageView image;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        attractionName = itemView.findViewById(R.id.tvAttractionName);
        location = itemView.findViewById(R.id.tvLocation);
        id = itemView.findViewById(R.id.tvID);
    }
}
</code>```

}

Constructor...

```<code>package com.example.tourismolocal;

public class MyData {
private int id;
private String attractioName, location, image;

public MyData(int id, String attractioName, String location) {
    this.id = id;
    this.attractioName = attractioName;
    this.location = location;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getAttractioName() {
    return attractioName;
}

public void setAttractioName(String attractioName) {
    this.attractioName = attractioName;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}
</code>```

}

Layout...

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".travelplanning"
android:background="@drawable/img_banner">

<FrameLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="120dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="60dp"
    android:background="@drawable/square"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/recTravel">

        </androidx.recyclerview.widget.RecyclerView>

    </LinearLayout>
</FrameLayout>

<EditText
    android:id="@+id/etSearchAttraction"
    android:layout_width="0dp"
    android:layout_height="38dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="72dp"
    android:autofillHints=""
    android:background="@drawable/searchdestination"
    android:drawableStart="@drawable/icon_search1"
    android:ems="10"
    android:hint="@string/etsearchdestination"
    android:inputType="textPersonName"
    android:paddingStart="10dp"
    app:layout_constraintEnd_toStartOf="@+id/btnAddAttraction"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:focusable="false"/>

<Button
    android:id="@+id/btnAddAttraction"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="5dp"
    android:layout_marginEnd="10dp"
    android:background="@drawable/icon_plus"
    app:layout_constraintBaseline_toBaselineOf="@+id/etSearchAttraction"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/etSearchAttraction" />

<FrameLayout
    android:id="@+id/frameLayout2"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/navbar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@drawable/nav_topborder"></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:orientation="horizontal"
        android:paddingTop="1dp">

        <Button
            android:id="@+id/btnAttraction"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_places"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/attract"
            android:textAllCaps="false"
            android:textColor="#2d3e52"
            android:textSize="9dp" />

        <Button
            android:id="@+id/btnTrips"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_trips"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/trips"
            android:textAllCaps="false"
            android:textColor="#A6A3A3"
            android:textSize="9dp" />

        <Button
            android:id="@+id/btnWishlist"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_wishlist"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/wishlist"
            android:textAllCaps="false"
            android:textColor="#A6A3A3"
            android:textSize="9dp" />
    </LinearLayout>

</FrameLayout>

<ImageView
    android:id="@+id/imgUser"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="15dp"
    android:src="@drawable/icon_mainuser"
    app:layout_constraintStart_toEndOf="@+id/imageView4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginTop="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/img_logowhite" />
</code>```

Card layout...

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

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgAttraction"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher_round"
        android:layout_margin="10dp"/>

    <LinearLayout
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="320dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tvAttractionName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Attraction Name"
                android:textSize="20dp"
                android:textColor="#000000"/>

            <TextView
                android:id="@+id/tvLocation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Location"
                android:textSize="20dp"
                android:textColor="#000000"/>
        </LinearLayout>

        <TextView
            android:id="@+id/tvID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ID"
            android:textSize="26dp"
            android:textColor="#000000"
            android:layout_marginTop="7dp"
            android:textAlignment="textEnd"
            android:visibility="invisible"/>

        <TextView
            android:id="@+id/tvRate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:text="Rating"
            android:textAlignment="textEnd"
            android:textColor="#000000"
            android:textSize="26dp" />

    </LinearLayout>

</androidx.cardview.widget.CardView>
</code>```

PHP File....

```<code><?php
require "init.php";

if(mysqli_connect_error($con))
{
    echo "Failed to connect";
}

$query = "Select id, attractionname, location from attraction";
$result = mysqli_query($con, $query);

if($result){
    while($row=mysqli_fetch_array($result)){
       $flag[]=$row;
    }

    print(json_encode($flag));
}
mysqli_close($con);
?>
</code>```

答:
You can't this. Because, you don't change ui operations in AsyncTask. Try this.</p>

```<code>private void load_data_from_server() {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.43.147/webapp/travelplanning.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());
                List<MyData> list = new ArrayList<>();
                for(int i = 0; i < array.length(); i++){
                    JSONObject object = array.getJSONObject(i);
                    MyData data = new MyData(object.getInt("ID"), object.getString("AttractionName"), object.getString("Location"));

                    list.add(data);
                }
                setListData(list);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
        }
    };
}

private void setListData(List<MyData> list) {
  data_list.addAll(list);
  adapter.notifyDataSetChanged();
}
</code>```

Title: Recycler View can't display mysql data

Body:
please help me on this code.
I want to display data from mysql and display it to android. I inserted data in my mysql and display on my android how many data are in my mysql so that i know if my android app can read all my data from mysql, but when i run my android app, it says that no data. Please help me

Android code...

data_list = new ArrayList<>();
    load_data_from_server();
    gridLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(gridLayoutManager);

    adapter = new CustomAdapter(this, data_list);
    recyclerView.setAdapter(adapter);

if (adapter.getItemCount() == 0){
        Toast.makeText(this, "Empty", Toast.LENGTH_SHORT).show();
    }

private void load_data_from_server() {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.43.147/webapp/travelplanning.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());

                for(int i = 0; i < array.length(); i++){
                    JSONObject object = array.getJSONObject(i);
                    MyData data = new MyData(object.getInt("ID"), object.getString("AttractionName"), object.getString("Location"));

                    data_list.add(data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter.notifyDataSetChanged();
        }
    };
}

Adapter...

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private Context context;
private List<MyData> my_data;

public CustomAdapter(Context context, List<MyData> my_data) {
    this.context = context;
    this.my_data = my_data;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.travel_planning_card, parent, false);
    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.id.setText(my_data.get(position).getId());
    holder.attractionName.setText(my_data.get(position).getAttractioName());
    holder.location.setText(my_data.get(position).getLocation());
}

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

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView attractionName, location, id;
    public ImageView image;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        attractionName = itemView.findViewById(R.id.tvAttractionName);
        location = itemView.findViewById(R.id.tvLocation);
        id = itemView.findViewById(R.id.tvID);
    }
}

}

Constructor...

package com.example.tourismolocal;

public class MyData {
private int id;
private String attractioName, location, image;

public MyData(int id, String attractioName, String location) {
    this.id = id;
    this.attractioName = attractioName;
    this.location = location;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getAttractioName() {
    return attractioName;
}

public void setAttractioName(String attractioName) {
    this.attractioName = attractioName;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

}

Layout...

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".travelplanning"
android:background="@drawable/img_banner">

<FrameLayout
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="120dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="60dp"
    android:background="@drawable/square"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/recTravel">

        </androidx.recyclerview.widget.RecyclerView>

    </LinearLayout>
</FrameLayout>

<EditText
    android:id="@+id/etSearchAttraction"
    android:layout_width="0dp"
    android:layout_height="38dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="72dp"
    android:autofillHints=""
    android:background="@drawable/searchdestination"
    android:drawableStart="@drawable/icon_search1"
    android:ems="10"
    android:hint="@string/etsearchdestination"
    android:inputType="textPersonName"
    android:paddingStart="10dp"
    app:layout_constraintEnd_toStartOf="@+id/btnAddAttraction"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:focusable="false"/>

<Button
    android:id="@+id/btnAddAttraction"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="5dp"
    android:layout_marginEnd="10dp"
    android:background="@drawable/icon_plus"
    app:layout_constraintBaseline_toBaselineOf="@+id/etSearchAttraction"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/etSearchAttraction" />

<FrameLayout
    android:id="@+id/frameLayout2"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="@drawable/navbar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@drawable/nav_topborder"></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="63dp"
        android:orientation="horizontal"
        android:paddingTop="1dp">

        <Button
            android:id="@+id/btnAttraction"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_places"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/attract"
            android:textAllCaps="false"
            android:textColor="#2d3e52"
            android:textSize="9dp" />

        <Button
            android:id="@+id/btnTrips"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_trips"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/trips"
            android:textAllCaps="false"
            android:textColor="#A6A3A3"
            android:textSize="9dp" />

        <Button
            android:id="@+id/btnWishlist"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/navbar"
            android:drawableTop="@drawable/icon_wishlist"
            android:paddingTop="7dp"
            android:paddingBottom="18dp"
            android:text="@string/wishlist"
            android:textAllCaps="false"
            android:textColor="#A6A3A3"
            android:textSize="9dp" />
    </LinearLayout>

</FrameLayout>

<ImageView
    android:id="@+id/imgUser"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="15dp"
    android:src="@drawable/icon_mainuser"
    app:layout_constraintStart_toEndOf="@+id/imageView4"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<ImageView
    android:id="@+id/imageView6"
    android:layout_width="0dp"
    android:layout_height="25dp"
    android:layout_marginTop="20dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/img_logowhite" />

Card layout...

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

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgAttraction"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher_round"
        android:layout_margin="10dp"/>

    <LinearLayout
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="320dp"
        android:layout_width="match_parent"
        android:layout_height="55dp"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tvAttractionName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Attraction Name"
                android:textSize="20dp"
                android:textColor="#000000"/>

            <TextView
                android:id="@+id/tvLocation"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Location"
                android:textSize="20dp"
                android:textColor="#000000"/>
        </LinearLayout>

        <TextView
            android:id="@+id/tvID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ID"
            android:textSize="26dp"
            android:textColor="#000000"
            android:layout_marginTop="7dp"
            android:textAlignment="textEnd"
            android:visibility="invisible"/>

        <TextView
            android:id="@+id/tvRate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:text="Rating"
            android:textAlignment="textEnd"
            android:textColor="#000000"
            android:textSize="26dp" />

    </LinearLayout>

</androidx.cardview.widget.CardView>

PHP File....

<?php
require "init.php";

if(mysqli_connect_error($con))
{
    echo "Failed to connect";
}

$query = "Select id, attractionname, location from attraction";
$result = mysqli_query($con, $query);

if($result){
    while($row=mysqli_fetch_array($result)){
       $flag[]=$row;
    }

    print(json_encode($flag));
}
mysqli_close($con);
?>

Body:
You can't this. Because, you don't change ui operations in AsyncTask. Try this.

private void load_data_from_server() {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://192.168.43.147/webapp/travelplanning.php")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                JSONArray array = new JSONArray(response.body().string());
                List<MyData> list = new ArrayList<>();
                for(int i = 0; i < array.length(); i++){
                    JSONObject object = array.getJSONObject(i);
                    MyData data = new MyData(object.getInt("ID"), object.getString("AttractionName"), object.getString("Location"));

                    list.add(data);
                }
                setListData(list);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
        }
    };
}

private void setListData(List<MyData> list) {
  data_list.addAll(list);
  adapter.notifyDataSetChanged();
}


问:
SELECT, FROM, INNER JOIN, WHERE function
I have two tables "users" and "emp_details". "users" are Branch mangers who have login id for monitoring their own branch's employees. "emp_details" includes employees working for different branches which include branch managers aslo.

when Branch manager ("users") log in it should fetch details from "emp_details" only if this particular "users" branch (code: location) match.

```<code>SELECT emp_details.emp_no, emp_name, designation, emp_details.location
 FROM emp_details
 INNER JOIN users
 WHERE users.location = emp_details.location
</code>```

used above code but showing data for all users created not as per the login-ed users location. Please help

答:
It looks like you want a WHERE clause -- after fixing your WHERE clause to be an ON clause:

```<code>SELECT ed.emp_no, ed.emp_name, ed.designation, ed.location
FROM emp_details ed JOIn
     users u
     ON u.location = ed.location
WHERE u.login_id = ?;
</code>```

? is a parameter placeholder for the manager's login id.  That seems to be how you are identifying the users.

Body:
I have two tables "users" and "emp_details". "users" are Branch mangers who have login id for monitoring their own branch's employees. "emp_details" includes employees working for different branches which include branch managers aslo.

when Branch manager ("users") log in it should fetch details from "emp_details" only if this particular "users" branch (code: location) match.

SELECT emp_details.emp_no, emp_name, designation, emp_details.location
 FROM emp_details
 INNER JOIN users
 WHERE users.location = emp_details.location

used above code but showing data for all users created not as per the login-ed users location. Please help

Body:
It looks like you want a WHERE clause -- after fixing your WHERE clause to be an ON clause:

SELECT ed.emp_no, ed.emp_name, ed.designation, ed.location
FROM emp_details ed JOIn
     users u
     ON u.location = ed.location
WHERE u.login_id = ?;

? is a parameter placeholder for the manager's login id.  That seems to be how you are identifying the users.


问:
xhprof not working for php rabbitmq consumers
I have rabbitmq consumers written in php with symfony2-framework, and I'm trying to see the inner workings and issues of the system with xhprof. Problem is that it's not saving anything into the mongodb. Mongo is totally empty.

I've tried to set the auto_prepend_file(which adds the necessary header-file) in php.ini, the applications .htaccess -file, and the apaches virtual hosts.

I set the profiler to profile every request and it profiles everything else just fine, eeexcept the rabbitmq-consumers running in the background. But why not?

For instance, I called phpinfo.php -file and it profiled it perfectly, but not the consumers, nope.

答:
Xhprof does not forcibly save the profile data when the script exits. But when you instruct him to do so. Lot of setups includes something like from https://github.com/patrickallaert/xhprof#profile-your-page, using register_shutdown_function(), which gets executed at the end of a script.

But it is up to you to put xhprof_enable() / xhprof_disable() around the code that you want to profile. It is also perfectly valid in a loop, example:

```<code><?php

while (true) {
    // Fetch a message from the queue

    // Start profiling
    xhprof_enable();

    // [treatment of your message]

    // End profiling and dump the result
    file_put_contents("/tmp/" . uniqid() . ".your_app.xhprof", serialize(xhprof_disable()));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Xhprof does not forcibly save the profile data when the script exits. But when you instruct him to do so. Lot of setups includes something like from https://github.com/patrickallaert/xhprof#profile-your-page, using register_shutdown_function(), which gets executed at the end of a script.

But it is up to you to put xhprof_enable() / xhprof_disable() around the code that you want to profile. It is also perfectly valid in a loop, example:

<?php

while (true) {
    // Fetch a message from the queue

    // Start profiling
    xhprof_enable();

    // [treatment of your message]

    // End profiling and dump the result
    file_put_contents("/tmp/" . uniqid() . ".your_app.xhprof", serialize(xhprof_disable()));
}


问:
Loop over columns of dataframe in R
How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

```<code>x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}
</code>```

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function

答:
Here is a dplyr example:

```<code>library(tidyverse)

df %>%
    summarise_at(vars(col30, col126, col145), wilcox.test, y = level)
</code>```

Title: Loop over columns of dataframe in R

Body:
How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function

Body:
Here is a dplyr example:

library(tidyverse)

df %>%
    summarise_at(vars(col30, col126, col145), wilcox.test, y = level)


问:
Warning: Failed prop type: The prop `leads` is marked as required in `Leads`, but its value is `undefined`
I am trying this tutorial to display information into my table using React and Redux, but I keep on getting this error:

Warning: Failed prop type: The prop leads is marked as required in
  Leads, but its value is undefined   Uncaught Type Error: Cannot
  read property 'map' of undefined Leads.js:52

My code:

```<code>import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getLeads } from "../../actions/leads";

export class Leads extends Component {

  static propTypes = {
    leads: PropTypes.array.isRequired,
  };

  componentDidMount() {
    this.props.getLeads();
  }

  render() {
    return (
      <Fragment>
        <h2>Leads</h2>
        <table className="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>Name</th>
              <th>Email</th>
              <th>Message</th>
              <th />
            </tr>
          </thead>
          <tbody>
            {this.props.leads.map(lead => (
              <tr key={lead.id}>
                <td>{lead.id}</td>
                <td>{lead.name}</td>
                <td>{lead.email}</td>
                <td>{lead.message}</td>
                <td><button className="btn btn-danger btn-sm">Delete</button></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Fragment>
    );
  }
}

const mapStateToProps = state => ({
  leads: state.leads.leads
});

export default connect(
  mapStateToProps,
  { getLeads }
)(Leads);
</code>```

What am I doing wrong?

答:
the problem is not on this Leads component,
but the parent component who used Leads.

you must add props called leads with array format.

Body:
I am trying this tutorial to display information into my table using React and Redux, but I keep on getting this error:

Warning: Failed prop type: The prop leads is marked as required in
  Leads, but its value is undefined   Uncaught Type Error: Cannot
  read property 'map' of undefined Leads.js:52

My code:

import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getLeads } from "../../actions/leads";

export class Leads extends Component {

  static propTypes = {
    leads: PropTypes.array.isRequired,
  };

  componentDidMount() {
    this.props.getLeads();
  }

  render() {
    return (
      <Fragment>

Leads

              ID
              Name
              Email
              Message

            {this.props.leads.map(lead => (

                {lead.id}
                {lead.name}
                {lead.email}
                {lead.message}
                <button className="btn btn-danger btn-sm">Delete</button>

            ))}

      </Fragment>
    );
  }
}

const mapStateToProps = state => ({
  leads: state.leads.leads
});

export default connect(
  mapStateToProps,
  { getLeads }
)(Leads);

What am I doing wrong?


问:
Linq-to-Entities match ID in list of integers in a compiled query
I'm trying to find a way to implement a Linq-to-Entities compiled query of the form:

```<code>Func<MyEntities, List<int>, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, List<int> IDs) => (
         (from au in entities.Mine where IDs.Any(x => x == au.ID) select au)
    ));
</code>```

Because only scalar parameters can be passed to CompiledQuery.Compile the above fails. I'm trying to find some clever way to pass a comma delimited list of integers as a string and use that in the L2E query along the lines of:

```<code>Func<MyEntities, string, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, string IDs) => (
         (from au in entities.Mine where IDs.Split(',').Any(x => Convert.ToInt32(x) == au.ID) select au)
    ));
</code>```

But that doesn't work due to the unsupported Split function.

Any clever ideas about how this could be implemented?

答: I'm not sure if this could possibly work, but maybe try to use join of List<int> IDs and MyEntities entities?

Body:
I'm trying to find a way to implement a Linq-to-Entities compiled query of the form:

Func<MyEntities, List<int>, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, List<int> IDs) => (
         (from au in entities.Mine where IDs.Any(x => x == au.ID) select au)
    ));

Because only scalar parameters can be passed to CompiledQuery.Compile the above fails. I'm trying to find some clever way to pass a comma delimited list of integers as a string and use that in the L2E query along the lines of:

Func<MyEntities, string, IQueryable<MyClass>> query = System.Data.Objects.CompiledQuery.Compile(
    (MyEntities entities, string IDs) => (
         (from au in entities.Mine where IDs.Split(',').Any(x => Convert.ToInt32(x) == au.ID) select au)
    ));

But that doesn't work due to the unsupported Split function.

Any clever ideas about how this could be implemented?


问:
Google script trigger stopped working with permission errors (Code:11:28)
My calendar booking script stopped working in the past week. Checking the error logs, it seems that the trigger is still being fired but I am getting this error:

Exception: The script doesn't have permission to perform that action. Required permission: (https://www.googleapis.com/auth/calendar || https://www.googleapis.com/auth/calendar.readonly || https://www.google.com/calendar/feeds) at unknown function

I have modified my appsscript.json to include the oauth for these three permissions but the script still doesn't work. Can anyone please advise? Thanks.

Contents of appsscript.json:

```<code>{
  "oauthScopes": [
    "https://www.googleapis.com/auth/calendar",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.google.com/calendar/feeds"
  ],
  "timeZone": "Europe/London",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"

}
</code>```

答: Managed to sort it out be re-enabling permissions in the script file itself (by running the trigger script), and adding in additional oauthscopes as requested by the various errors. I previously did not need to do this, so have no idea why this happened in the last 4 days. </p>

Body:
My calendar booking script stopped working in the past week. Checking the error logs, it seems that the trigger is still being fired but I am getting this error:

Exception: The script doesn't have permission to perform that action. Required permission: (https://www.googleapis.com/auth/calendar || https://www.googleapis.com/auth/calendar.readonly || https://www.google.com/calendar/feeds) at unknown function

I have modified my appsscript.json to include the oauth for these three permissions but the script still doesn't work. Can anyone please advise? Thanks.

Contents of appsscript.json:

{
  "oauthScopes": [
    "https://www.googleapis.com/auth/calendar",
    "https://www.googleapis.com/auth/calendar.readonly",
    "https://www.google.com/calendar/feeds"
  ],
  "timeZone": "Europe/London",
  "dependencies": {
  },
  "webapp": {
    "access": "ANYONE",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"

}


问:
React making axios get, returns error: CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
I am trying to make an axios get request, but i am getting corse policy error. I am kinda new to axios, this is what i tried:

```<code>useEffect(() => {
    let url =
      'http://18.189.49.66:3000/api/calculate/' +
      props.type +
      '/' +
      height +
      '/' +
      width;

    var config = {
      headers: { 'Access-Control-Allow-Origin': '*' }
    };

    axios.get(url, config).then(_result => {
      console.log('Duomenys: ' + JSON.stringify(_result));
    });

}, [length, width, height]);
</code>```

In my app.js on node.js express i have these lines:

```<code>var cors = require('cors');
app.use(cors());
</code>```

And here is the error:

Access to XMLHttpRequest at 'http://18.189.49.66:3000/api/calculate/LF/80/200'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:172 GET http://18.189.49.66:3000/api/calculate/LF/80/200 net::ERR_FAILED dispatchXhrRequest
@ xhr.js:172 xhrAdapter
@ xhr.js:11 dispatchRequest
@ dispatchRequest.js:59 Promise.then (async) request
@ Axios.js:53 Axios.<computed>
@ Axios.js:68 wrap
@ bind.js:9 (anonymous)
@ Calculator.js:113 commitHookEffectList
@ react-dom.development.js:22030 commitPassiveHookEffects
@ react-dom.development.js:22064 callCallback
@ react-dom.development.js:336 invokeGuardedCallbackDev
@ react-dom.development.js:385 invokeGuardedCallback
@ react-dom.development.js:440 flushPassiveEffectsImpl
@ react-dom.development.js:25392 unstable_runWithPriority
@ scheduler.development.js:697 runWithPriority$2
@ react-dom.development.js:12149 flushPassiveEffects
@ react-dom.development.js:25361 flushDiscreteUpdates
@ react-dom.development.js:24359 finishEventHandler
@ react-dom.development.js:1384 batchedEventUpdates
@ react-dom.development.js:1418 dispatchEventForPluginEventSystem
@ react-dom.development.js:5894 attemptToDispatchEvent
@ react-dom.development.js:6010 dispatchEvent
@ react-dom.development.js:5914 ListPicker._handleMouseUp createError.js:16

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)
```

<p>My backend:</p>

<p>...
    var cors = require('cors');
    ...</p>

```app.use(cors());
```

...

How should i edit my request?

答: The problem was that in URL which i was calling letters were upper case, that caused error.</p>

Body:
I am trying to make an axios get request, but i am getting corse policy error. I am kinda new to axios, this is what i tried:

useEffect(() => {
    let url =
      'http://18.189.49.66:3000/api/calculate/' +
      props.type +
      '/' +
      height +
      '/' +
      width;

    var config = {
      headers: { 'Access-Control-Allow-Origin': '*' }
    };

    axios.get(url, config).then(_result => {
      console.log('Duomenys: ' + JSON.stringify(_result));
    });

}, [length, width, height]);

In my app.js on node.js express i have these lines:

var cors = require('cors');
app.use(cors());

And here is the error:

Access to XMLHttpRequest at 'http://18.189.49.66:3000/api/calculate/LF/80/200'
from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

xhr.js:172 GET http://18.189.49.66:3000/api/calculate/LF/80/200 net::ERR_FAILED dispatchXhrRequest
@ xhr.js:172 xhrAdapter
@ xhr.js:11 dispatchRequest
@ dispatchRequest.js:59 Promise.then (async) request
@ Axios.js:53 Axios.<computed>
@ Axios.js:68 wrap
@ bind.js:9 (anonymous)
@ Calculator.js:113 commitHookEffectList
@ react-dom.development.js:22030 commitPassiveHookEffects
@ react-dom.development.js:22064 callCallback
@ react-dom.development.js:336 invokeGuardedCallbackDev
@ react-dom.development.js:385 invokeGuardedCallback
@ react-dom.development.js:440 flushPassiveEffectsImpl
@ react-dom.development.js:25392 unstable_runWithPriority
@ scheduler.development.js:697 runWithPriority$2
@ react-dom.development.js:12149 flushPassiveEffects
@ react-dom.development.js:25361 flushDiscreteUpdates
@ react-dom.development.js:24359 finishEventHandler
@ react-dom.development.js:1384 batchedEventUpdates
@ react-dom.development.js:1418 dispatchEventForPluginEventSystem
@ react-dom.development.js:5894 attemptToDispatchEvent
@ react-dom.development.js:6010 dispatchEvent
@ react-dom.development.js:5914 ListPicker._handleMouseUp createError.js:16

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:81)

My backend:

...
    var cors = require('cors');
    ...

app.use(cors());

...

How should i edit my request?


问:
Unity CanvasRenderer expects meshes with 16 bit indices for drawing a graph chart
When applying IndexFormat.UInt32 to a UI Mesh:

mesh.indexFormat = IndexFormat.UInt32;
```

Unity complains about the CanvasRenderer expects meshes with 16 bit indices, but I have not found how to change it to 32 bit indices.

Does is it possible to apply IndexFormat.UInt32 to a CanvasRenderer?

[EDIT 1]

I'm using Unity 2019.3.0f3, the issue comes with this package: assetstore.unity.com/packages/tools/gui/graph-and-chart

Sometimes a graph chart can have more 5000+ items.

答:
As a fix I have filtered my data by using the Douglas-Peucker Line Approximation Algorithm which consists in compressing a data curve.

The source code of the implementation can be found here: A C# Implementation of Douglas-Peucker Line Approximation Algorithm

And an explanation of the algorithm: Ramer–Douglas–Peucker algorithm

Body:
When applying IndexFormat.UInt32 to a UI Mesh:

mesh.indexFormat = IndexFormat.UInt32;

Unity complains about the CanvasRenderer expects meshes with 16 bit indices, but I have not found how to change it to 32 bit indices.

Does is it possible to apply IndexFormat.UInt32 to a CanvasRenderer?

[EDIT 1]

I'm using Unity 2019.3.0f3, the issue comes with this package: assetstore.unity.com/packages/tools/gui/graph-and-chart

Sometimes a graph chart can have more 5000+ items.


问:
How do we make multiple file_get_contents in PHP run faster?
We're building an API that performs repetitive file_get_contents.
I have an array of userids and the number of file_get_contents() will be repeated by the number of contents in the array. We will do thousands of requests.

```<code>function request($userid) {
    global $access_token;
    $url = 'https://<api-domain>'.$userid.'?access_token='.$access_token;
    $response = file_get_contents($url);
    return json_decode($response);
}

function loopUserIds($arrayUserIds) {
    global $countFollowers;
    $arrayAllUserIds = array();
    foreach ($arrayUserIds as $userid) {
        $followers = request($userid);
        ...
    }
    ...
}
</code>```

My concern is it takes time to get everything. Since the function will also be called in a loop. Please advise how we can make this (many file_get_contents() requests) run faster?

答: When curl_multi_exec isn't available, you can gain performance when you reuse $ch instead of creating a new for every file, which will reuse the connection when downloading from the same host. </p>

Body:
We're building an API that performs repetitive file_get_contents.
I have an array of userids and the number of file_get_contents() will be repeated by the number of contents in the array. We will do thousands of requests.

function request($userid) {
    global $access_token;
    $url = 'https://<api-domain>'.$userid.'?access_token='.$access_token;
    $response = file_get_contents($url);
    return json_decode($response);
}

function loopUserIds($arrayUserIds) {
    global $countFollowers;
    $arrayAllUserIds = array();
    foreach ($arrayUserIds as $userid) {
        $followers = request($userid);
        ...
    }
    ...
}

My concern is it takes time to get everything. Since the function will also be called in a loop. Please advise how we can make this (many file_get_contents() requests) run faster?


问:
GWT - occasional com.google.gwt.user.client.rpc.SerializationException
we are haunted by occasional occurences of exceptions such as:

com.google.gwt.user.client.rpc.SerializationException: Type 'xxx' was not assignable to 'com.google.gwt.user.client.rpc.IsSerializable' and did not have a custom field serializer.For security purposes, this type will not be serialized.: instance = xxx
      at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serialize(ServerSerializationStreamWriter.java:610)
      at com.google.gwt.user.client.rpc.impl.AbstractSerializationStreamWriter.writeObject(AbstractSerializationStreamWriter.java:129)
      at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter$ValueWriter$8.write(ServerSerializationStreamWriter.java:152)
      at com.google.gwt.user.server.rpc.impl.ServerSerializationStreamWriter.serializeValue(ServerSerializationStreamWriter.java:534)
      at com.google.gwt.user.server.rpc.RPC.encodeResponse(RPC.java:609)
      at com.google.gwt.user.server.rpc.RPC.encodeResponseForSuccess(RPC.java:467)
      at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:564)
      at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:188)
      at de.softconex.travicemanager.server.TraviceManagerServiceImpl.processCall(TraviceManagerServiceImpl.java:615)
      at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:224)
      at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
      at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
      at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
      at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
      at org.apache.coyote.ajp.AjpAprProcessor.process(AjpAprProcessor.java:419)
      at org.apache.coyote.ajp.AjpAprProtocol$AjpConnectionHandler.process(AjpAprProtocol.java:378)
      at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
      at java.lang.Thread.run(Thread.java:619)

The application is normally running fine. The indicated class implements Serializable (the whole object graph).

So far the only patterns / observations are:

we seem to have the issue only when the application is used inside an iframe

the problem seems to happen when a new version of the application has been deployed

running firefox in privacy mode (disabling all caches etc.) doesn't fix the problem

Any ideas?

Holger

答: I've had the same error and fix this by clean the browse cache and navigation history.</p>

ContentLicense: CC BY-SA 2.5


问:
multiply the numbers entered by user and when the user types 'x' for example to print the sum of the numbers enter by that moment
```<code>using System;

namespace While_product
{
    class Program
    {
        static void Main(string[] args)
        {

            string firstInput = Console.ReadLine();
            int sum1 = 0;

            if (firstInput == "x")
            {
                Console.WriteLine(1);
            }

            else

                while (firstInput != "x")
                {

                    int number = Convert.ToInt32(firstInput);
                    sum1 *= number;
                    Console.ReadLine();

                }
            Console.WriteLine();

        }
    }
}
</code>```

<hr>

```<code>for exampe:
5
4
3
x
output: 60
</code>```

答:
As per I understood you have to multiply the records which you have entered before x, here we go.

```<code>  using System;
  using System.Collections.Generic;
  using System.Linq;

  namespace Print
 {
   class Program
   {
    static void Main(string[] args)
    {
        int y = 0;

        string firstInput = Console.ReadLine();
        List<string> strArray = new List<string>();
        int multiplication = 1;

        strArray.Add(firstInput);

        if (firstInput == "x")
        {
            Console.WriteLine(multiplication);
        }

        else
        {
            while (y == 0)
            {
                multiplication = 1;
                for (int i = 0; i < strArray.Count; i++)
                {
                    if (strArray[i] != "x")
                    {
                        int number = Convert.ToInt32(strArray[i]);
                        multiplication *= number;
                        firstInput = Console.ReadLine();
                        strArray.Add(firstInput);
                    }
                    else
                    {
                        y = 1;
                    }
                }
            }
        }

        Console.WriteLine(multiplication);
    }
}
 }
</code>```

Body:
using System;

namespace While_product
{
    class Program
    {
        static void Main(string[] args)
        {

            string firstInput = Console.ReadLine();
            int sum1 = 0;

            if (firstInput == "x")
            {
                Console.WriteLine(1);
            }

            else

                while (firstInput != "x")
                {

                    int number = Convert.ToInt32(firstInput);
                    sum1 *= number;
                    Console.ReadLine();

                }
            Console.WriteLine();

        }
    }
}

for exampe:
5
4
3
x
output: 60

Body:
As per I understood you have to multiply the records which you have entered before x, here we go.

  using System;
  using System.Collections.Generic;
  using System.Linq;

  namespace Print
 {
   class Program
   {
    static void Main(string[] args)
    {
        int y = 0;

        string firstInput = Console.ReadLine();
        List<string> strArray = new List<string>();
        int multiplication = 1;

        strArray.Add(firstInput);

        if (firstInput == "x")
        {
            Console.WriteLine(multiplication);
        }

        else
        {
            while (y == 0)
            {
                multiplication = 1;
                for (int i = 0; i < strArray.Count; i++)
                {
                    if (strArray[i] != "x")
                    {
                        int number = Convert.ToInt32(strArray[i]);
                        multiplication *= number;
                        firstInput = Console.ReadLine();
                        strArray.Add(firstInput);
                    }
                    else
                    {
                        y = 1;
                    }
                }
            }
        }

        Console.WriteLine(multiplication);
    }
}
 }


问:
Running Plain SQL dynamically in Quill using infix fails with wrong query syntax during runtime
I want to construct my query in plain SQL and then run it using Quill, I am using infix operator .
My code is like this.

```<code>case class Employee(name: String, age: String, company_name: String)

case class Company(name: String, pin_code: String)

case class CombinedEmployee(employee_age: Int,
                      employee_name: Option[String],
                      company_name: String,
                      pin: Option[String])

val sql =    "SELECT t1.age AS employee_age, t1.name AS employee_name, t2.name AS company_name, t2.pin as pin FROM employee t1 JOIN company t2 ON t1.company_name = t2.name"
</code>```

// it can be anything which is calculated dynamically.

```<code>def rawQuery = quote { (myQuery: String) =>
 infix"""$myQuery"""
 .as[Query[CombinedEmployee]]
 }
</code>```

and I am calling

```<code>    ctx.translate(rawQuery(lift(sql)))
</code>```

this prints

```<code>        SELECT x.employee_age, x.employee_name, x.company_name, x.pin FROM ('SELECT t1.age AS employee_age, t1.name AS employee_name, t2.name AS company_name, t2.pin as pin FROM employee t1 JOIN company t2 ON t1.company_name = t2.name') AS x
</code>```

which is a wrong syntax, when I executed this using run method this fails.
Is the way of writing plain SQL correct ?? If no, is there a different way to run Plain SQL and model into case classes ??

答:
This can be solved by adding a # before $

```<code>def rawQuery = quote { (myQuery: String) =>
 infix"""#$myQuery"""
 .as[Query[CombinedEmployee]]
</code>```

}

Body:
I want to construct my query in plain SQL and then run it using Quill, I am using infix operator .
My code is like this.

case class Employee(name: String, age: String, company_name: String)

case class Company(name: String, pin_code: String)

case class CombinedEmployee(employee_age: Int,
                      employee_name: Option[String],
                      company_name: String,
                      pin: Option[String])

val sql =    "SELECT t1.age AS employee_age, t1.name AS employee_name, t2.name AS company_name, t2.pin as pin FROM employee t1 JOIN company t2 ON t1.company_name = t2.name"

// it can be anything which is calculated dynamically.

def rawQuery = quote { (myQuery: String) =>
 infix"""$myQuery"""
 .as[Query[CombinedEmployee]]
 }

and I am calling

    ctx.translate(rawQuery(lift(sql)))

this prints

        SELECT x.employee_age, x.employee_name, x.company_name, x.pin FROM ('SELECT t1.age AS employee_age, t1.name AS employee_name, t2.name AS company_name, t2.pin as pin FROM employee t1 JOIN company t2 ON t1.company_name = t2.name') AS x

which is a wrong syntax, when I executed this using run method this fails.
Is the way of writing plain SQL correct ?? If no, is there a different way to run Plain SQL and model into case classes ??

Body:
This can be solved by adding a # before $

def rawQuery = quote { (myQuery: String) =>
 infix"""#$myQuery"""
 .as[Query[CombinedEmployee]]

}


问:
Javascript alert box for textarea values using PHP
While submitting below:

It gives me an alert as "hey";

But while submitting below:

It doesn't alert anything.

PHP Code:

```<code>$text = htmlspecialchars($_POST['tval']);
echo "<script>alert('".$text."');</script>";
</code>```

HTML Code:

```<code><textarea cols="40" rows="5" type="text" name="tval" placeholder="Type Here..." required></textarea>
</code>```

答:
You can use template literals to write strings with new lines:

```<code>$text = htmlspecialchars($_POST['tval']);
echo "<script>alert(`".$text."`);</script>";
</code>```

from your comments:

You can use split() and map() to get different alert for different lines:

//var text = `<?php echo $text;?>`
var text = `firstline
secondline
thirdline`; //example text for snippet
text.split("\n").map((line)=>{
  alert(line);
});```

Body:
While submitting below:

It gives me an alert as "hey";

But while submitting below:

It doesn't alert anything.

PHP Code:

$text = htmlspecialchars($_POST['tval']);
echo "";

HTML Code:

<textarea cols="40" rows="5" type="text" name="tval" placeholder="Type Here..." required></textarea>

Body:
You can use template literals to write strings with new lines:

$text = htmlspecialchars($_POST['tval']);
echo "<script>alert(`".$text."`);</script>";

from your comments:

You can use split() and map() to get different alert for different lines:

//var text = `<?php echo $text;?>`
var text = `firstline
secondline
thirdline`; //example text for snippet
text.split("\n").map((line)=>{
  alert(line);
});


问:
Error when trying to create my table in sqlalchemy => sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: dht_new
It cant find my db even tho i have created it wite create_table? I have tried to put the function
create_Table" in diffrent places with no result? However i get the error,

```<code>sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: dht_new
[SQL: INSERT INTO dht_new (name) VALUES (?)]
[parameters: (None,)]
</code>```

app.py

```<code>import os
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy
from db import db

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///newdata.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

@app.before_first_request
def create_tables():
    db.create_all()

class fixdb(db.Model):
    __tablename__ = 'dht_new'

    id = db.Column(db.Integer, primary_key =True)
    name = db.Column(db.String(80))

    def __init__(self, temp):
        self.temp = temp

    def add_to_db(self):
        db.session.add(self)
        db.session.commit()

@app.route('/get', methods=['GET'])
def postrandom():
    temp = {'temperature': '23'}
    test_temp = fixdb(temp)

    test_temp.add_to_db()
    return jsonify(temp)

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)
</code>```

答:
You need to create table first in your SQLite database. You can use the SQLite Browser to do the same else use the python CLI to create the table. Since you didn't mention your .py file name so I can't exactly show you the code but it would be something like this

first type python in your terminal, then

from app import db
db.drop_all()
db.create_all()
```

and this should do it for you.

Body:
It cant find my db even tho i have created it wite create_table? I have tried to put the function
create_Table" in diffrent places with no result? However i get the error,

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: dht_new
[SQL: INSERT INTO dht_new (name) VALUES (?)]
[parameters: (None,)]

app.py

import os
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from flask_sqlalchemy import SQLAlchemy
from db import db

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///newdata.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

@app.before_first_request
def create_tables():
    db.create_all()

class fixdb(db.Model):
    __tablename__ = 'dht_new'

    id = db.Column(db.Integer, primary_key =True)
    name = db.Column(db.String(80))

    def __init__(self, temp):
        self.temp = temp

    def add_to_db(self):
        db.session.add(self)
        db.session.commit()

@app.route('/get', methods=['GET'])
def postrandom():
    temp = {'temperature': '23'}
    test_temp = fixdb(temp)

    test_temp.add_to_db()
    return jsonify(temp)

if __name__ == '__main__':
    from db import db
    db.init_app(app)
    app.run(port=5000, debug=True)

Body:
You need to create table first in your SQLite database. You can use the SQLite Browser to do the same else use the python CLI to create the table. Since you didn't mention your .py file name so I can't exactly show you the code but it would be something like this

first type python in your terminal, then

from app import db
db.drop_all()
db.create_all()

and this should do it for you.


问:
javac adding classpath breaks my local class compilation
When I import a package to my MyLib class (which requires -cp to javac) I can no longer compile my MyMain class.

MyMain.java:

```<code>class MyMain
{
    public static void main (String [] args)
    {
        MyLib.do_stuff ();
    }
}
</code>```

MyLib.java:

```<code>import com.google.gson.JsonElement;

class MyLib
{
    public static void do_stuff ()
    {
        System.out.println ("Hello.");
    }
}
</code>```

When I javac MyLib.java I have do do it like this

```<code>javac -cp GSON_JAR_PATH MyLib.java
</code>```

That works but if I

```<code>javac MyMain.java
</code>```

I get

```<code>./MyLib.java:1: error: package com.google.gson does not exist
import com.google.gson.JsonElement;
</code>```

but if I add -cp to the compilation command

```<code>javac -cp GSON_JAR_PATH MyMain.java
</code>```

I get

```<code>MyMain.java:5: error: cannot find symbol
                MyLib.do_stuff ();
                ^
  symbol:   variable MyLib
  location: class MyMain
</code>```

答:
Use "-cp path1:path2" - colon separated. (semicolon works on windows) (the parameter to cp is quoted....

```<code>javac -cp path1:path2 //or ; for windows.
</code>```

Note 1 - setting -cp overrides any existing CLASSPATH environment or default
 path setting.

Note 2 - if no CLASSPATH setting then default is '.' - until the -cp overrides that.

So in the posted case - the "." was set for path (either CLASSPATH or default) up until the -cp was used which overrode that default - so it needs to be added back in.

Body:
When I import a package to my MyLib class (which requires -cp to javac) I can no longer compile my MyMain class.

MyMain.java:

class MyMain
{
    public static void main (String [] args)
    {
        MyLib.do_stuff ();
    }
}

MyLib.java:

import com.google.gson.JsonElement;

class MyLib
{
    public static void do_stuff ()
    {
        System.out.println ("Hello.");
    }
}

When I javac MyLib.java I have do do it like this

javac -cp GSON_JAR_PATH MyLib.java

That works but if I

javac MyMain.java

I get

./MyLib.java:1: error: package com.google.gson does not exist
import com.google.gson.JsonElement;

but if I add -cp to the compilation command

javac -cp GSON_JAR_PATH MyMain.java

I get

MyMain.java:5: error: cannot find symbol
                MyLib.do_stuff ();
                ^
  symbol:   variable MyLib
  location: class MyMain

Body:
Use "-cp path1:path2" - colon separated. (semicolon works on windows) (the parameter to cp is quoted....

javac -cp path1:path2 //or ; for windows.

Note 1 - setting -cp overrides any existing CLASSPATH environment or default
 path setting.

Note 2 - if no CLASSPATH setting then default is '.' - until the -cp overrides that.

So in the posted case - the "." was set for path (either CLASSPATH or default) up until the -cp was used which overrode that default - so it needs to be added back in.


问:
Pass two variable to method in Laravel
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

```<code>public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}
</code>```

Route

```<code>Route::get('post/{slug}', 'PagesController@post')->name('post.show');
</code>```

答:
Here you go:

Get post_id from the $post itself.

```<code>public function post($slug){
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    ...
}
</code>```

Title: Pass two variable to method in Laravel

Body:
i want to find post by slug also in url ..
but the comments must be found by post_id

Controller

public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}

Route

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

Body:
Here you go:

Get post_id from the $post itself.

public function post($slug){
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    ...
}


问:
UIelement programmatically created. Can I take the name of new created UIelement from variable?
I edited exactly what I want to achieve, this time different example without taken parameter in function.

What I want to achieve is:

```<code>var array = [String]()
func create() {

var arrayCount = array.count         // will be 0
var nameForUI = "view/(arrayCount)" // will be view0

let nameForUI: UIVIew = {
let view = UIVIew()
return view

}()
array.append(nameForUI)
view.addSubview(nameForUI)
//
}
</code>```

next time if I call create() func , the next view will be called "view1" So my question is, how to achieve this result? every time function will called it will create new element with new name.

答:
Edit

To directly answer your question: No, you cannot do that.

Code written in Swift is compiled -- it is not an interpreted / scripted language.

So you cannot write code that creates a button named "littleButton" and then have a line of code littleButton.backgroundColor = .red

You can sort of do this by creating a Dictionary that maintains the "name" of the element as the key, and a reference to the element as the value.

Start with initializing an empty dictionary:

```<code>var buttonsDict: [String : UIButton] = [String : UIButton]()
</code>```

Your "create" func can start like this:

```<code>func createButton(named str: String) -> Void {
    // create a button
    let b = UIButton()
    // give it a default title
    b.setTitle("Button", for: .normal)
    // add it to our Dictionary
    buttonsDict.updateValue(b, forKey: str)
}
</code>```

When you want to create a button:

```<code>createButton(named: "littleButton")
</code>```

When you want to access that button by name:

```<code>// use guard to make sure you get a valid button reference
guard let btn = buttonsDict["littleButton"] else { return }
view.addSubview(btn)
</code>```

Edit 2

Another option, which is perhaps more similar to your edited question:

```<code>// initialize empty array of views
var viewsArray: [UIView] = [UIView]()

override func viewDidLoad() {
    super.viewDidLoad()

    // create 5 views
    for _ in 0..<5 {
        create()
    }

    // ...

    // then, somewhere else in your code
    viewsArray[0].backgroundColor = .red
    viewsArray[1].backgroundColor = .green
    viewsArray[2].backgroundColor = .blue
    viewsArray[3].backgroundColor = .yellow
    viewsArray[4].backgroundColor = .orange

}

func create() -> Void {
    // create a view
    let v = UIView()
    // add it to our array
    viewsArray.append(v)
    // add it as a subview
    view.addSubview(v)
}
</code>```

As you see, instead of trying to reference the created views by name (which you cannot do), you can reference them by array index.

Just remember that arrays are zero-based... so the first element added to the array will be at [0] not [1].

Body:
I edited exactly what I want to achieve, this time different example without taken parameter in function.

What I want to achieve is:

var array = [String]()
func create() {

var arrayCount = array.count         // will be 0
var nameForUI = "view/(arrayCount)" // will be view0

let nameForUI: UIVIew = {
let view = UIVIew()
return view

}()
array.append(nameForUI)
view.addSubview(nameForUI)
//
}

next time if I call create() func , the next view will be called "view1" So my question is, how to achieve this result? every time function will called it will create new element with new name.

Body:
Edit

To directly answer your question: No, you cannot do that.

Code written in Swift is compiled -- it is not an interpreted / scripted language.

So you cannot write code that creates a button named "littleButton" and then have a line of code littleButton.backgroundColor = .red

You can sort of do this by creating a Dictionary that maintains the "name" of the element as the key, and a reference to the element as the value.

Start with initializing an empty dictionary:

var buttonsDict: [String : UIButton] = [String : UIButton]()

Your "create" func can start like this:

func createButton(named str: String) -> Void {
    // create a button
    let b = UIButton()
    // give it a default title
    b.setTitle("Button", for: .normal)
    // add it to our Dictionary
    buttonsDict.updateValue(b, forKey: str)
}

When you want to create a button:

createButton(named: "littleButton")

When you want to access that button by name:

// use guard to make sure you get a valid button reference
guard let btn = buttonsDict["littleButton"] else { return }
view.addSubview(btn)

Edit 2

Another option, which is perhaps more similar to your edited question:

// initialize empty array of views
var viewsArray: [UIView] = [UIView]()

override func viewDidLoad() {
    super.viewDidLoad()

    // create 5 views
    for _ in 0..<5 {
        create()
    }

    // ...

    // then, somewhere else in your code
    viewsArray[0].backgroundColor = .red
    viewsArray[1].backgroundColor = .green
    viewsArray[2].backgroundColor = .blue
    viewsArray[3].backgroundColor = .yellow
    viewsArray[4].backgroundColor = .orange

}

func create() -> Void {
    // create a view
    let v = UIView()
    // add it to our array
    viewsArray.append(v)
    // add it as a subview
    view.addSubview(v)
}

As you see, instead of trying to reference the created views by name (which you cannot do), you can reference them by array index.

Just remember that arrays are zero-based... so the first element added to the array will be at [0] not [1].


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答: Abstract base class has on overhead of virtual calls but it has an advantage that all derived classes are really base classes. Not so when you use templates – Car<Brake> and Car<BrakeWithABS> are unrelated to each other and you'll have to either dynamic_cast and check for null or have templates for all the code that deals with Car.</p>

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?


答:
Issue is with

```<code>static propTypes = {
    leads: PropTypes.array.isRequired,
};
</code>```

You have marked this as compulsory value to be passed when you use Leads component.

So you have to use like this

```<code><Leads lead={[]} />
</code>```

and empty array or some data you have to share to this component.

Title: Warning: Failed prop type: The prop `leads` is marked as required in `Leads`, but its value is `undefined`

Body:
I am trying this tutorial to display information into my table using React and Redux, but I keep on getting this error:

Warning: Failed prop type: The prop leads is marked as required in
  Leads, but its value is undefined   Uncaught Type Error: Cannot
  read property 'map' of undefined Leads.js:52

My code:

import React, { Component, Fragment } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { getLeads } from "../../actions/leads";

export class Leads extends Component {

  static propTypes = {
    leads: PropTypes.array.isRequired,
  };

  componentDidMount() {
    this.props.getLeads();
  }

  render() {
    return (
      <Fragment>

Leads

              ID
              Name
              Email
              Message

            {this.props.leads.map(lead => (

                {lead.id}
                {lead.name}
                {lead.email}
                {lead.message}
                <button className="btn btn-danger btn-sm">Delete</button>

            ))}

      </Fragment>
    );
  }
}

const mapStateToProps = state => ({
  leads: state.leads.leads
});

export default connect(
  mapStateToProps,
  { getLeads }
)(Leads);

What am I doing wrong?

Body:
Issue is with

static propTypes = {
    leads: PropTypes.array.isRequired,
};

You have marked this as compulsory value to be passed when you use Leads component.

So you have to use like this

<Leads lead={[]} />

and empty array or some data you have to share to this component.