问:
How to handle different button onclick within a cardview and passing intents?
I have a cardview which is presenting the upcoming events with title, date, etc. and there are two imageviews that should function as buttons: if clicked on one it should go to the participation confirming activity, if on the other on the detail activity. Both of these should also pass informations using intents(name, date, user id, token). I have followed this tutorial, because this was the closest solution to my problem but it still does not work. Whatever I change these are the errors I get:  Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference (this is given when  I call the setButtons function), or if the onclick somehow works the intents don't get passed and i get a nullpointerexception. I made sure I have used the right ids and names.
Additional information: i am using Laravel, and retrofit.
EventsActivity:

```<code>public class EventsActivity extends AppCompatActivity {
private static final String TAG = "EventsActivity";
private static final int ACTIVITY_NUM = 1;
private static final String PREFS_NAME = "LoginPrefs";
public static final String EVENT_DETAIL = "EVENT_DETAIL";
private Context mContext = EventsActivity.this;
private Event mEvent = new Event();
private String token, name;
private int id;
private EventAdapter adapter;
private RecyclerView recyclerView;
private List<Event> eventList = new ArrayList<>();
private List<Response> result;
private TextView noEvents;
private Button add, more;

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

    //Get token and id from shared preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    token = settings.getString("token", "");
    id = settings.getInt("id", 0);
    Log.d(TAG, "onResponse: id " + id + "token " + token);

    noEvents = findViewById(R.id.noEvents);
    recyclerView = findViewById(R.id.event_recyclerview);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
    recyclerView.setLayoutManager(layoutManager);
    adapter = new EventAdapter(mContext, eventList);
    recyclerView.setAdapter(adapter);

    adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
        @Override
        public void onAddClicked(int position) {
           addClick(position);
        }

        @Override
        public void onMoreClicked(int position) {
            moreClick(position);
        }
    });

    loadData();
    setButtons();
}

public void addClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventInvitationActivity.class);
    i.putExtra("name", event.getName());
    i.putExtra("name", event.getDescription());
    i.putExtra("name", event.getDate());
    i.putExtra("name", event.getLocation());
    Log.i("hello", event.getName());
    startActivity(i);
}

public void moreClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventDetailActivity.class);
    i.putExtra("name", event.getName());
    Log.i("hello", event.getName());
    startActivity(i);
}

void setButtons() {
     add = findViewById(R.id.add_icon);
     more = findViewById(R.id.more_icon);
    Log.d(TAG, "setButtons: called");
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: add onclicklistener");
            int position = Integer.parseInt(v.getTag().toString());
            addClick(position);
        }
    });
    more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = Integer.parseInt(v.getTag().toString());
            moreClick(position);
        }
    });
}

//Listing events
private void loadData(){
    ApiEvents service = RetrofitBuilder.getRetrofitInstance().create(ApiEvents.class);
    Call<List<Event>> call = service.listEvents("Bearer" + token, id);
    call.enqueue(new Callback<List<Event>>() {
        @Override
        public void onResponse(@NonNull Call<List<Event>> call, @NonNull Response<List<Event>> response) {
            if (response.isSuccessful() && response.body()!=null) {
                Log.d(TAG, "onResponse: loadData called");
                eventList = response.body();
                adapter = new EventAdapter(mContext, eventList);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
                    @Override
                    public void onAddClicked(int position) {
                        addClick(position);
                    }

                    @Override
                    public void onMoreClicked(int position) {
                        moreClick(position);
                    }
                });
            }
            else if(response.body() == null){
                noEvents.setVisibility(View.VISIBLE);
            }
            else{
                Log.d(TAG, "onResponse: " + response.body());
            }
        }

        @Override
        public void onFailure(@NonNull Call<List<Event>> call, @NonNull Throwable t) {
            Log.d("Response", "onFailure: " + t.toString());
        }
    });
}
</code>```

}

EventAdapter

```<code>public class EventAdapter extends RecyclerView.Adapter<EventAdapter.MyViewHolder> {
private Context mContext;
private List<Event> eventList;
private static final String TAG = "EventDetailActivity";
private OnItemClickListener clickListener;

public EventAdapter(Context mContext, List<Event> eventList){
    this.mContext = mContext;
    this.eventList = eventList;
}

public interface OnItemClickListener {
    void onAddClicked(int position);
    void onMoreClicked(int position);
}

public void setOnItemClickListener(OnItemClickListener clickListener) {
    this.clickListener = clickListener;
}

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

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
    Event event = eventList.get(position);
    holder.itemView.setTag(event);
    holder.title.setText(eventList.get(position).getName());
    holder.description.setText(eventList.get(position).getDescription());
    holder.date.setText(eventList.get(position).getDate());
    holder.location.setText(eventList.get(position).getLocation());
    holder.add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onAddClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventInvitationActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onMoreClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventDetailActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView title, description, date, location;
    Button add, more;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.event_name);
        description = itemView.findViewById(R.id.event_description);
        date = itemView.findViewById(R.id.event_date);
        location = itemView.findViewById(R.id.event_location);
        add = itemView.findViewById(R.id.add_icon);

    }

}
</code>```

And this is the way I am trying to get the passed intents in the two activities:

```<code>//Getting resources
    mName = findViewById(R.id.eventName);
    mDescription = findViewById(R.id.description);
    mLocation = findViewById(R.id.location);
    mDate = findViewById(R.id.date);

    mEvent = Objects.requireNonNull(getIntent().getExtras()).getParcelable(EVENT_DETAIL);
   if(mEvent != null){
    mName.setText(mEvent.getName());
    mDescription.setText(mEvent.getDescription());
    mLocation.setText(mEvent.getLocation());
    mDate.setText(mEvent.getDate());
   }
</code>```

And here is a button example within the cardview:

```<code><Button
            android:id="@+id/add_icon"
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:layout_below="@+id/image"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@id/event_description"
            android:drawableStart="@drawable/ic_add_black_24dp"
            android:scaleType="centerCrop"
            android:transitionName="img"
            android:visibility="visible"
            android:textColor="@color/colorAccent"
           />
</code>```

So the question is, how can I make this work?

EDIT
I have figured out what the problem is: the add and more imageviews are on the event_layout as part of the CardView and not on activity_events, where the programme is looking for them. But then, I don't really know how to make the two buttons work, when they are placed on the CardView.

答: In your MyViewHolder constructor you aren't initialising more so that will be null therefore throwing your null reference exception

Body:
I have a cardview which is presenting the upcoming events with title, date, etc. and there are two imageviews that should function as buttons: if clicked on one it should go to the participation confirming activity, if on the other on the detail activity. Both of these should also pass informations using intents(name, date, user id, token). I have followed this tutorial, because this was the closest solution to my problem but it still does not work. Whatever I change these are the errors I get:  Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference (this is given when  I call the setButtons function), or if the onclick somehow works the intents don't get passed and i get a nullpointerexception. I made sure I have used the right ids and names.
Additional information: i am using Laravel, and retrofit.
EventsActivity:

public class EventsActivity extends AppCompatActivity {
private static final String TAG = "EventsActivity";
private static final int ACTIVITY_NUM = 1;
private static final String PREFS_NAME = "LoginPrefs";
public static final String EVENT_DETAIL = "EVENT_DETAIL";
private Context mContext = EventsActivity.this;
private Event mEvent = new Event();
private String token, name;
private int id;
private EventAdapter adapter;
private RecyclerView recyclerView;
private List<Event> eventList = new ArrayList<>();
private List<Response> result;
private TextView noEvents;
private Button add, more;

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

    //Get token and id from shared preferences
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    token = settings.getString("token", "");
    id = settings.getInt("id", 0);
    Log.d(TAG, "onResponse: id " + id + "token " + token);

    noEvents = findViewById(R.id.noEvents);
    recyclerView = findViewById(R.id.event_recyclerview);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);
    recyclerView.setLayoutManager(layoutManager);
    adapter = new EventAdapter(mContext, eventList);
    recyclerView.setAdapter(adapter);

    adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
        @Override
        public void onAddClicked(int position) {
           addClick(position);
        }

        @Override
        public void onMoreClicked(int position) {
            moreClick(position);
        }
    });

    loadData();
    setButtons();
}

public void addClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventInvitationActivity.class);
    i.putExtra("name", event.getName());
    i.putExtra("name", event.getDescription());
    i.putExtra("name", event.getDate());
    i.putExtra("name", event.getLocation());
    Log.i("hello", event.getName());
    startActivity(i);
}

public void moreClick(int position){
    final Event event = eventList.get(position);
    Intent i = new Intent(EventsActivity.this, EventDetailActivity.class);
    i.putExtra("name", event.getName());
    Log.i("hello", event.getName());
    startActivity(i);
}

void setButtons() {
     add = findViewById(R.id.add_icon);
     more = findViewById(R.id.more_icon);
    Log.d(TAG, "setButtons: called");
    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(TAG, "onClick: add onclicklistener");
            int position = Integer.parseInt(v.getTag().toString());
            addClick(position);
        }
    });
    more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = Integer.parseInt(v.getTag().toString());
            moreClick(position);
        }
    });
}

//Listing events
private void loadData(){
    ApiEvents service = RetrofitBuilder.getRetrofitInstance().create(ApiEvents.class);
    Call<List<Event>> call = service.listEvents("Bearer" + token, id);
    call.enqueue(new Callback<List<Event>>() {
        @Override
        public void onResponse(@NonNull Call<List<Event>> call, @NonNull Response<List<Event>> response) {
            if (response.isSuccessful() && response.body()!=null) {
                Log.d(TAG, "onResponse: loadData called");
                eventList = response.body();
                adapter = new EventAdapter(mContext, eventList);
                recyclerView.setAdapter(adapter);
                adapter.setOnItemClickListener(new EventAdapter.OnItemClickListener() {
                    @Override
                    public void onAddClicked(int position) {
                        addClick(position);
                    }

                    @Override
                    public void onMoreClicked(int position) {
                        moreClick(position);
                    }
                });
            }
            else if(response.body() == null){
                noEvents.setVisibility(View.VISIBLE);
            }
            else{
                Log.d(TAG, "onResponse: " + response.body());
            }
        }

        @Override
        public void onFailure(@NonNull Call<List<Event>> call, @NonNull Throwable t) {
            Log.d("Response", "onFailure: " + t.toString());
        }
    });
}

}

EventAdapter

public class EventAdapter extends RecyclerView.Adapter<EventAdapter.MyViewHolder> {
private Context mContext;
private List<Event> eventList;
private static final String TAG = "EventDetailActivity";
private OnItemClickListener clickListener;

public EventAdapter(Context mContext, List<Event> eventList){
    this.mContext = mContext;
    this.eventList = eventList;
}

public interface OnItemClickListener {
    void onAddClicked(int position);
    void onMoreClicked(int position);
}

public void setOnItemClickListener(OnItemClickListener clickListener) {
    this.clickListener = clickListener;
}

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

@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int position) {
    Event event = eventList.get(position);
    holder.itemView.setTag(event);
    holder.title.setText(eventList.get(position).getName());
    holder.description.setText(eventList.get(position).getDescription());
    holder.date.setText(eventList.get(position).getDate());
    holder.location.setText(eventList.get(position).getLocation());
    holder.add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onAddClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventInvitationActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(clickListener != null){
                int position = (int)v.getTag();
                clickListener.onMoreClicked(position);
                final Event event = (Event)v.getTag();
                if(event!= null){
                    Intent i = new Intent(mContext, EventDetailActivity.class);
                    i.putExtra("EVENT_DETAIL", event);
                    v.getContext().startActivity(i);
                }
            }
        }
    });

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

public class MyViewHolder extends RecyclerView.ViewHolder {
    TextView title, description, date, location;
    Button add, more;

    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.event_name);
        description = itemView.findViewById(R.id.event_description);
        date = itemView.findViewById(R.id.event_date);
        location = itemView.findViewById(R.id.event_location);
        add = itemView.findViewById(R.id.add_icon);

    }

}

And this is the way I am trying to get the passed intents in the two activities:

//Getting resources
    mName = findViewById(R.id.eventName);
    mDescription = findViewById(R.id.description);
    mLocation = findViewById(R.id.location);
    mDate = findViewById(R.id.date);

    mEvent = Objects.requireNonNull(getIntent().getExtras()).getParcelable(EVENT_DETAIL);
   if(mEvent != null){
    mName.setText(mEvent.getName());
    mDescription.setText(mEvent.getDescription());
    mLocation.setText(mEvent.getLocation());
    mDate.setText(mEvent.getDate());
   }

And here is a button example within the cardview:

<Button
            android:id="@+id/add_icon"
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:layout_below="@+id/image"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="5dp"
            android:layout_toEndOf="@id/event_description"
            android:drawableStart="@drawable/ic_add_black_24dp"
            android:scaleType="centerCrop"
            android:transitionName="img"
            android:visibility="visible"
            android:textColor="@color/colorAccent"
           />

So the question is, how can I make this work?

EDIT
I have figured out what the problem is: the add and more imageviews are on the event_layout as part of the CardView and not on activity_events, where the programme is looking for them. But then, I don't really know how to make the two buttons work, when they are placed on the CardView.


来源: stackexchange

问:
Pandas rolling sum that includes previous and coming days
A beginner, basically, trying to find a rolling sum that includes today, last 4 days, and coming days, in this case 1 next day (tomorrow).

```<code>            Test
1995-07-01    1
1995-07-02    0
1995-07-03    0
1995-07-04    1
1995-07-05    0
1995-07-06    0
1995-07-07    0
1995-07-08    0
1995-07-09    0
1995-07-10    0
1995-07-11    1
</code>```

Got rolling sum of 'today' and past 4 days to work
df['test'].rolling(5).sum()

```<code>1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    2.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    1.0
1995-07-09    0.0
1995-07-10    0.0
1995-07-11    1.0
</code>```

But including the next day's value into this sum is difficult for me, what I want is the output 1995-07-10 to show 1 since it needs to include 'tomorrow' (since 1995-07-11 is a 1 in the Test data)

答:
I believe what you need is the shift() method. It will allow you to shift your data by a number of days and then you can align it to the dates however you'd like.

See this link for documentation.

```<code>df['test'].shift(-1,fill_value=0).rolling(5).sum()
</code>```

provides:

```<code>date
1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    1.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    0.0
1995-07-09    0.0
1995-07-10    1.0
1995-07-11    1.0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
A beginner, basically, trying to find a rolling sum that includes today, last 4 days, and coming days, in this case 1 next day (tomorrow).

            Test
1995-07-01    1
1995-07-02    0
1995-07-03    0
1995-07-04    1
1995-07-05    0
1995-07-06    0
1995-07-07    0
1995-07-08    0
1995-07-09    0
1995-07-10    0
1995-07-11    1

Got rolling sum of 'today' and past 4 days to work
df['test'].rolling(5).sum()

1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    2.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    1.0
1995-07-09    0.0
1995-07-10    0.0
1995-07-11    1.0

But including the next day's value into this sum is difficult for me, what I want is the output 1995-07-10 to show 1 since it needs to include 'tomorrow' (since 1995-07-11 is a 1 in the Test data)

Body:
I believe what you need is the shift() method. It will allow you to shift your data by a number of days and then you can align it to the dates however you'd like.

See this link for documentation.

df['test'].shift(-1,fill_value=0).rolling(5).sum()

provides:

date
1995-07-01    NaN
1995-07-02    NaN
1995-07-03    NaN
1995-07-04    NaN
1995-07-05    1.0
1995-07-06    1.0
1995-07-07    1.0
1995-07-08    0.0
1995-07-09    0.0
1995-07-10    1.0
1995-07-11    1.0


问:
optimizing insert query
I am trying to insert comma separated values in a global table. When data is large it's taking long time to process the data. I need to optimize my insert query, is there any other ways to achieve below insert statement for better optimization? Please check code below for more info. Appreciated for any help.</p>

```<code>//my proc
emp_id in CLOB;

//insert statement
insert into Global_Emp_Tbl
with inputs(str) as(
select to_clob(emp_id)
from dual
),
temp_table(s, n, empid, st_pos, end_pos) as (
select ',' || str || ',', -1, null, null, 1
from inputs

union all
selct s, n+1, substr(s, st_pos, end_pos - st_pos),
end_pos + 1, instr(s, ',', 1, n+3)
from temp_table
where end_pos != 0
)
select empid from temp_table where empid is not null;
commit;

//using insert table in where clause
exists( select 1 from Global_Emp_Tbl gt  where e.id =gt.emp_id ) //joining with main table
</code>```

答:
Well I can't reporduce your problem in Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

This procedure provides the sample data, a CLOB csv list of the first N interger

```<code>create or replace function get_list(N NUMBER) return CLOB
as
 v_lst CLOB;
 i PLS_INTEGER;
BEGIN
  v_lst :='1';
  for  i  in 2 .. n loop
     v_lst :=v_lst||','||to_char(i);
  end loop;
  return(v_lst);
END;
/
</code>```

Note that the 5K parameter give approximately 20K long list.

```<code>select length(get_list(5000)) from dual;
23892
</code>```

The parsing of this list in a global temporary table is done in seconds not in minutes. Here an example using your SELECT

```<code>SQL> set timi on;
SQL> create global temporary table csv_tbl
  2  ON COMMIT PRESERVE ROWS
  3  as
  4  with inputs(str) as(
  5  select get_list(5000)
  6  from dual
  7  ),
  8  temp_table(s, n, empid, st_pos, end_pos) as (
  9  select ',' || str || ',', -1, null, null, 1
 10  from inputs
 11  union all
 12  select s, n+1, substr(s, st_pos, end_pos - st_pos),
 13  end_pos + 1, instr(s, ',', 1, n+3)
 14  from temp_table
 15  where end_pos != 0
 16  )
 17  select  empid  from temp_table where empid is not null
 18  ;

Table created.

Elapsed: 00:00:01.35
</code>```

So the most probably explanation is, that the most elapsed time is spend in the query with the EXISTS clause

```<code>exists( select 1 from Global_Emp_Tbl gt  where e.id =gt.emp_id )
</code>```

Two problems come to my mind

1) The datatypes of the EMP_ID in the temporary table and in the EMP table differs, e.g. in temporary table it is VARCHAR2, in the EMP table NUMBER - this will prohibit the use of the index on the EMP table.

2) The missing object statistics on the global temporary table leads the CBO to an wrong execution plan and you use the index (in a large nested loops) where you should use a full table scan.

Title: optimizing insert query

Body:
I am trying to insert comma separated values in a global table. When data is large it's taking long time to process the data. I need to optimize my insert query, is there any other ways to achieve below insert statement for better optimization? Please check code below for more info. Appreciated for any help.

//my proc
emp_id in CLOB;

//insert statement
insert into Global_Emp_Tbl
with inputs(str) as(
select to_clob(emp_id)
from dual
),
temp_table(s, n, empid, st_pos, end_pos) as (
select ',' || str || ',', -1, null, null, 1
from inputs

union all
selct s, n+1, substr(s, st_pos, end_pos - st_pos),
end_pos + 1, instr(s, ',', 1, n+3)
from temp_table
where end_pos != 0
)
select empid from temp_table where empid is not null;
commit;

//using insert table in where clause
exists( select 1 from Global_Emp_Tbl gt  where e.id =gt.emp_id ) //joining with main table

Body:
Well I can't reporduce your problem in Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production

This procedure provides the sample data, a CLOB csv list of the first N interger

create or replace function get_list(N NUMBER) return CLOB
as
 v_lst CLOB;
 i PLS_INTEGER;
BEGIN
  v_lst :='1';
  for  i  in 2 .. n loop
     v_lst :=v_lst||','||to_char(i);
  end loop;
  return(v_lst);
END;
/

Note that the 5K parameter give approximately 20K long list.

select length(get_list(5000)) from dual;
23892

The parsing of this list in a global temporary table is done in seconds not in minutes. Here an example using your SELECT

SQL> set timi on;
SQL> create global temporary table csv_tbl
  2  ON COMMIT PRESERVE ROWS
  3  as
  4  with inputs(str) as(
  5  select get_list(5000)
  6  from dual
  7  ),
  8  temp_table(s, n, empid, st_pos, end_pos) as (
  9  select ',' || str || ',', -1, null, null, 1
 10  from inputs
 11  union all
 12  select s, n+1, substr(s, st_pos, end_pos - st_pos),
 13  end_pos + 1, instr(s, ',', 1, n+3)
 14  from temp_table
 15  where end_pos != 0
 16  )
 17  select  empid  from temp_table where empid is not null
 18  ;

Table created.

Elapsed: 00:00:01.35

So the most probably explanation is, that the most elapsed time is spend in the query with the EXISTS clause

exists( select 1 from Global_Emp_Tbl gt  where e.id =gt.emp_id )

Two problems come to my mind

1) The datatypes of the EMP_ID in the temporary table and in the EMP table differs, e.g. in temporary table it is VARCHAR2, in the EMP table NUMBER - this will prohibit the use of the index on the EMP table.

2) The missing object statistics on the global temporary table leads the CBO to an wrong execution plan and you use the index (in a large nested loops) where you should use a full table scan.


问:
Proper way (move semantics) to return a std::vector from function calling in C++11
I want to fill std::vector (or some other STL container):

```<code>class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}
</code>```

1.Good looking ctor, expensive performance

```<code>std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}
</code>```

2. Better performance, worse looking ctor

```<code>void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }
</code>```

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?

答:
In the particular case that you are considering, the first implementation is just as efficient as the second. The compiler will optimize the copy of ret in the get_vector function to the return value, and it will use move semantics to transfer ownership of the vector to the container class. Move construction in a vector requires (implementation dependent, but a good approximation is) 3 pointer copies, independently of the number and sizes of the elements in the container. Passing the vector as a reference to be modified requires a single pointer copy (approximate cost again), but any operation you perform on the vector will dominate the cost of either option.

There are some very specific circumstances when passing a vector into a function for modification might be faster, but those are rare and more related to the domain than to the vector itself. Just ignore that, code first for maintainability, and if the program is slow, profile, determine where the cost of the program is, and only then think on optimizing. The interesting part is that once you have profiled, you probably know what the bottleneck is and that means you will have hints into what to change.

ContentLicense: CC BY-SA 3.0

Body:
I want to fill std::vector (or some other STL container):

class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}

1.Good looking ctor, expensive performance

std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}

2. Better performance, worse looking ctor

void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?


问:
How to adjust TextField width?
I'm re-writing a simple app which calculates averages. However, I have a hard time with a TextField. I would like it to be exactly as on a first screenshot.

The TextField's width is stretched, I don't want that. I want it to be exactly as it is on the screenshot.

Desired look:

What I have:

Code:

import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';

class ArithmeticAverageScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('arithmetic_average_title').tr(),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    ListTile(
                      leading: Icon(Icons.help),
                      title: Text('arithmetic_average_help').tr(),
                      subtitle: Text('arithmetic_average_help_content').tr(),
                    )
                  ],
                ),
              )
            ),
            SizedBox(height: 16.0),
            Card(
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 20.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Text('arithmetic_average_your_grades', style: Theme.of(context).textTheme.headline5).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grades_one_at_a_time', style: Theme.of(context).textTheme.headline6,).tr(),
                    SizedBox(height: 16.0),
                    Text('arithmetic_average_grade', style: Theme.of(context).textTheme.subtitle2).tr(),
                    TextField()
                  ],
                ),
              ),
            )
          ],
        ),
      )
    );
  }
}
```

答:
This will help you make generic width on all devices, so here width * 0.3 means it will take 30% of the screen width

```<code> Container(
          width: MediaQuery.of(context).size.width * 0.3,
          child: TextField(),
        )
</code>```

Title: How to adjust TextField width?

Body:
This will help you make generic width on all devices, so here width * 0.3 means it will take 30% of the screen width

 Container(
          width: MediaQuery.of(context).size.width * 0.3,
          child: TextField(),
        )


问:
How to replace white space in column? Pandas
What I tried?

```<code>//1    myDataFrame['Gender'] = myDataFrame['Gender'].replace('^\s*$', np.nan)
//2    myDataFrame['Gender'] = myDataFrame['Gender'].replace('', np.nan)
       myDataFrame.to_csv('new_Paymets_Loan.csv')
</code>```

The white space is still the csv file.
Link to test csv: https://docs.google.com/spreadsheets/d/1eeHGsx3s7nZaSVPCFvtl0Wwp4KJGK8hAlH97n_4DPbI/edit?usp=sharing

[![enter image description here][1]][1]

```<code>Gender
Male
Female
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female

Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Female
Male
Female
Female
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female

Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male

Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male

Female
Male
Male
Male
Male
Female
Male
Male
Female
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male

Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Female
Male
Male
Male
Female
Male
Female
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Female
Male
Male
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Female
Male
</code>```

答:
You can use the below command to remove white spaces</p>

```<code>myDataFrame['Gender'].replace('\s','',inplace=True,regex=True)
</code>```

Body:
What I tried?

//1    myDataFrame['Gender'] = myDataFrame['Gender'].replace('^\s*$', np.nan)
//2    myDataFrame['Gender'] = myDataFrame['Gender'].replace('', np.nan)
       myDataFrame.to_csv('new_Paymets_Loan.csv')

The white space is still the csv file.
Link to test csv: https://docs.google.com/spreadsheets/d/1eeHGsx3s7nZaSVPCFvtl0Wwp4KJGK8hAlH97n_4DPbI/edit?usp=sharing

[![enter image description here][1]][1]

Gender
Male
Female
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female

Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Female
Male
Female
Female
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female

Male
Male
Male
Male
Female
Male
Male
Female
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male

Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male

Female
Male
Male
Male
Male
Female
Male
Male
Female
Female
Male
Male
Female
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Female
Male

Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Female
Male
Male
Male
Female
Male
Female
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Female
Male
Male
Male
Female
Male
Female
Male
Male
Male
Female
Male
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male
Female
Male
Male
Male
Male
Female
Male
Male
Male
Male
Male

Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Female
Female
Female
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male
Male

Male
Male
Male
Female
Male

Body:
You can use the below command to remove white spaces

myDataFrame['Gender'].replace('\s','',inplace=True,regex=True)


问:
Sylius order update concurrency issue
when under high load (doing load testing to test the checkout process) it seems our Custom Order Controller is throwing an exception when payment is being made. This happens on around 1 in 9 orders:

```<code>RaceConditionException: "Operated entity was previously modified."
</code>```

We have overridden the sylius_shop_checkout_complete route as follows

```<code>sylius_shop_checkout_complete:
path: /complete
methods: [GET, PUT]
defaults:
    _controller: sylius.controller.order:completeSectionAction
    _sylius:
        event: complete
        flash: false
        template: "@SyliusShop/Checkout/complete.html.twig"
        repository:
            method: findCartForSummary
            arguments:
                - "expr:service('sylius.context.cart').getCart().getId()"
        state_machine:
            graph: sylius_order_checkout
            transition: complete
        redirect:
            route: sylius_shop_order_pay
            parameters:
                tokenValue: resource.tokenValue
        form:
            type: Sylius\Bundle\CoreBundle\Form\Type\Checkout\CompleteType
            options:
                validation_groups: 'sylius_checkout_complete'
</code>```

and also our own check payment status route which the PaymentGateway redirects to after payment, as follows:

```<code>sylius_shop_checkout_status:
path: /check-status
methods: [GET, PUT]
defaults:
    _controller: sylius.controller.order:checkStatusAction
    _sylius:
        event: complete
        flash: false
        template: "@SyliusShop/Checkout/complete.html.twig"
        repository:
            method: findCartForSummary
            arguments:
                - "expr:service('sylius.context.cart').getCart().getId()"
        state_machine:
            graph: sylius_order_checkout
            transition: complete
        redirect:
            route: sylius_shop_order_pay
            parameters:
                tokenValue: resource.tokenValue
        form:
            type: Sylius\Bundle\CoreBundle\Form\Type\Checkout\CompleteType
            options:
                validation_groups: 'sylius_checkout_complete'
</code>```

At the checkStatusAction function we get the following exception

```<code>request.CRITICAL: Uncaught PHP Exception Sylius\Component\Resource\Exception\RaceConditionException: "Operated entity was previously modified." at /srv/sylius/vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/Doctrine/ORM/Handler/ResourceUpdateHandler.php line 46 {"exception":"[object] (Sylius\\Component\\Resource\\Exception\\RaceConditionException(code: 0): Operated entity was previously modified. at /srv/sylius/vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/Doctrine/ORM/Handler/ResourceUpdateHandler.php:46, Doctrine\\ORM\\OptimisticLockException(code: 0): The optimistic lock on an entity failed. at /srv/sylius/vendor/doctrine/orm/lib/Doctrine/ORM/OptimisticLockException.php:64)"} []
</code>```

Here is our checkStatus function:

```<code>public function checkStatusAction(Request $request, LoggerInterface $logger): Response
{
    $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);

    $this->isGrantedOr403($configuration, ResourceActions::UPDATE);
    $resource = $this->findOr404($configuration);

    $form = $this->resourceFormFactory->create($configuration, $resource);

    $payment = $resource->getLastPayment();
    $paymentMethod = $payment->getMethod();
    $paymentConfig = $paymentMethod->getGatewayConfig()->getConfig();
    $paymentFactoryName = $paymentMethod->getGatewayConfig()->getFactoryName();

    $response = $this->checkPaymentStatus($request->get('resourcePath'), $resource, $paymentConfig);
    $decodedResponse = json_decode($response, true);

    if(substr($decodedResponse['result']['code'], 0, 4 ) === '000.') {

        // If need to run scheduler
        $tcResponse = null;
        if ($paymentFactoryName === 'tp_payment_subscription' || $paymentFactoryName === 'tp_bank_transfer') {

            $amount = $paymentFactoryName === 'tp_bank_transfer' ?  0.00 : number_format($resource->getTotal() / 100, 2, '.', '');
            $tcResponse = $this->createSubscription($resource, $response, $amount, $paymentConfig);
        }

        // Store payment details
        $paymentDetails = [
            'PayOn' => $response,
            'TotalControl' => $tcResponse
        ];
        $payment->setDetails($paymentDetails);
        $payment->setState(Payment::STATE_COMPLETED);

        try {
            $this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
        } catch (UpdateHandlingException $exception) {

            if (!$configuration->isHtmlRequest()) {
                return $this->viewHandler->handle(
                    $configuration,
                    View::create($form, $exception->getApiResponseCode())
                );
            }

            $this->flashHelper->addErrorFlash($configuration, $exception->getFlash());

            return $this->redirectHandler->redirectToReferer($configuration);
        }

        // if ($configuration->isHtmlRequest()) {
        //     $this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
        // }

        $postEvent = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);

        return $this->redirectHandler->redirectToResource($configuration, $resource);
    }

    $this->flashHelper->addErrorFlash($configuration, 'something_went_wrong_error');

    $flashes = $request->getSession()->getBag('flashes');
    $flashes->add('error', [
        'message' => 'sylius.totalp.payment_failure',
        'parameters' => ['hello' => 'hi']
    ]);

    return $this->redirectHandler->redirectToReferer($configuration, $resource);
}
</code>```

The error is specifically happening at the following line:

```<code>$this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
</code>```

This issue only happens when the website has many orders happening at the same time, does anyone know how to fix this issue?

答:
I've managed to fix this, if anyone has this issue, the Sylius order number generator does not seem to be built for heavy concurrent load.

Specifically the SequentialOrderNumberGenerator.php.

We changed the following (i've left in the commented code for clarity)

```<code>/**
 * {@inheritdoc}
 */
public function generate(OrderInterface $order): string
{
    //$sequence = $this->getSequence();

    //$this->sequenceManager->lock($sequence, LockMode::OPTIMISTIC, $sequence->getVersion());

    $number = $this->generateNumber($order);
    //$sequence->incrementIndex();

    return $number;
}

private function generateNumber($order): string
{
    //$number = $this->startNumber + $index;

    return str_pad((string) $order->getId(), $this->numberLength, '0', \STR_PAD_LEFT);
}
</code>```

Title: Sylius order update concurrency issue

Body:
when under high load (doing load testing to test the checkout process) it seems our Custom Order Controller is throwing an exception when payment is being made. This happens on around 1 in 9 orders:

RaceConditionException: "Operated entity was previously modified."

We have overridden the sylius_shop_checkout_complete route as follows

sylius_shop_checkout_complete:
path: /complete
methods: [GET, PUT]
defaults:
    _controller: sylius.controller.order:completeSectionAction
    _sylius:
        event: complete
        flash: false
        template: "@SyliusShop/Checkout/complete.html.twig"
        repository:
            method: findCartForSummary
            arguments:
                - "expr:service('sylius.context.cart').getCart().getId()"
        state_machine:
            graph: sylius_order_checkout
            transition: complete
        redirect:
            route: sylius_shop_order_pay
            parameters:
                tokenValue: resource.tokenValue
        form:
            type: Sylius\Bundle\CoreBundle\Form\Type\Checkout\CompleteType
            options:
                validation_groups: 'sylius_checkout_complete'

and also our own check payment status route which the PaymentGateway redirects to after payment, as follows:

sylius_shop_checkout_status:
path: /check-status
methods: [GET, PUT]
defaults:
    _controller: sylius.controller.order:checkStatusAction
    _sylius:
        event: complete
        flash: false
        template: "@SyliusShop/Checkout/complete.html.twig"
        repository:
            method: findCartForSummary
            arguments:
                - "expr:service('sylius.context.cart').getCart().getId()"
        state_machine:
            graph: sylius_order_checkout
            transition: complete
        redirect:
            route: sylius_shop_order_pay
            parameters:
                tokenValue: resource.tokenValue
        form:
            type: Sylius\Bundle\CoreBundle\Form\Type\Checkout\CompleteType
            options:
                validation_groups: 'sylius_checkout_complete'

At the checkStatusAction function we get the following exception

request.CRITICAL: Uncaught PHP Exception Sylius\Component\Resource\Exception\RaceConditionException: "Operated entity was previously modified." at /srv/sylius/vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/Doctrine/ORM/Handler/ResourceUpdateHandler.php line 46 {"exception":"[object] (Sylius\\Component\\Resource\\Exception\\RaceConditionException(code: 0): Operated entity was previously modified. at /srv/sylius/vendor/sylius/sylius/src/Sylius/Bundle/CoreBundle/Doctrine/ORM/Handler/ResourceUpdateHandler.php:46, Doctrine\\ORM\\OptimisticLockException(code: 0): The optimistic lock on an entity failed. at /srv/sylius/vendor/doctrine/orm/lib/Doctrine/ORM/OptimisticLockException.php:64)"} []

Here is our checkStatus function:

public function checkStatusAction(Request $request, LoggerInterface $logger): Response
{
    $configuration = $this->requestConfigurationFactory->create($this->metadata, $request);

    $this->isGrantedOr403($configuration, ResourceActions::UPDATE);
    $resource = $this->findOr404($configuration);

    $form = $this->resourceFormFactory->create($configuration, $resource);

    $payment = $resource->getLastPayment();
    $paymentMethod = $payment->getMethod();
    $paymentConfig = $paymentMethod->getGatewayConfig()->getConfig();
    $paymentFactoryName = $paymentMethod->getGatewayConfig()->getFactoryName();

    $response = $this->checkPaymentStatus($request->get('resourcePath'), $resource, $paymentConfig);
    $decodedResponse = json_decode($response, true);

    if(substr($decodedResponse['result']['code'], 0, 4 ) === '000.') {

        // If need to run scheduler
        $tcResponse = null;
        if ($paymentFactoryName === 'tp_payment_subscription' || $paymentFactoryName === 'tp_bank_transfer') {

            $amount = $paymentFactoryName === 'tp_bank_transfer' ?  0.00 : number_format($resource->getTotal() / 100, 2, '.', '');
            $tcResponse = $this->createSubscription($resource, $response, $amount, $paymentConfig);
        }

        // Store payment details
        $paymentDetails = [
            'PayOn' => $response,
            'TotalControl' => $tcResponse
        ];
        $payment->setDetails($paymentDetails);
        $payment->setState(Payment::STATE_COMPLETED);

        try {
            $this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);
        } catch (UpdateHandlingException $exception) {

            if (!$configuration->isHtmlRequest()) {
                return $this->viewHandler->handle(
                    $configuration,
                    View::create($form, $exception->getApiResponseCode())
                );
            }

            $this->flashHelper->addErrorFlash($configuration, $exception->getFlash());

            return $this->redirectHandler->redirectToReferer($configuration);
        }

        // if ($configuration->isHtmlRequest()) {
        //     $this->flashHelper->addSuccessFlash($configuration, ResourceActions::UPDATE, $resource);
        // }

        $postEvent = $this->eventDispatcher->dispatchPostEvent(ResourceActions::UPDATE, $configuration, $resource);

        return $this->redirectHandler->redirectToResource($configuration, $resource);
    }

    $this->flashHelper->addErrorFlash($configuration, 'something_went_wrong_error');

    $flashes = $request->getSession()->getBag('flashes');
    $flashes->add('error', [
        'message' => 'sylius.totalp.payment_failure',
        'parameters' => ['hello' => 'hi']
    ]);

    return $this->redirectHandler->redirectToReferer($configuration, $resource);
}

The error is specifically happening at the following line:

$this->resourceUpdateHandler->handle($resource, $configuration, $this->manager);

This issue only happens when the website has many orders happening at the same time, does anyone know how to fix this issue?

Body:
I've managed to fix this, if anyone has this issue, the Sylius order number generator does not seem to be built for heavy concurrent load.

Specifically the SequentialOrderNumberGenerator.php.

We changed the following (i've left in the commented code for clarity)

/**
 * {@inheritdoc}
 */
public function generate(OrderInterface $order): string
{
    //$sequence = $this->getSequence();

    //$this->sequenceManager->lock($sequence, LockMode::OPTIMISTIC, $sequence->getVersion());

    $number = $this->generateNumber($order);
    //$sequence->incrementIndex();

    return $number;
}

private function generateNumber($order): string
{
    //$number = $this->startNumber + $index;

    return str_pad((string) $order->getId(), $this->numberLength, '0', \STR_PAD_LEFT);
}


问:
Detect Image Problems
I really don't know what it is called (distortion or something else)
But I would like to detect lens camera problems for some different types of images by using emgucv (or opencv)

Any ideas about which algorithms to use would be appreciated

Second image seems to have high noise, but is there any way to understand high noise via opencv?

答: An alternative method is to consider evaluating your images in the frequency domain following a Fourier transform. Principally, the noise examples you have provided are images containing unwanted, high frequency content. Conduct FFT and evaluate for images violating a threshold for high frequencies. Here you will from an example of FFT with Emgu: FFT with Emgu </p>

Title: Detect Image Problems


问:
Pass id parameter in fetch query (ReactJS)
I am new in javscript development, and I have some trouble with passing id parameter in query URL.
I am passing ID value in body now, which is not right, I guess in REST approach.

How can I pass Id: event.target.DepartmentId.value, into URL like https://localhost:5001/api/departments/{id} ?

handleSubmit(event){
    event.preventDefault();
    fetch("https://localhost:5001/api/departments/", {
        method: "PUT",
        headers:{
            "Accept":"application/json",
            "Content-Type":"application/json",
            "Origin": "*"
        },
        body: JSON.stringify({
            Id: event.target.DepartmentId.value,
            Name: event.target.DepartmentName.value
        })
    })
    .then(res=>res.json())
    .then((result)=>
    {
        this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})

    },
    (error) =>{
        this.setState({snackbaropen: true, snackbarmsg: "failed"})
    }
    )
}```

Thanks for any help!

答:
you can use js template literal like this:

handleSubmit(event){
    event.preventDefault();
    fetch(`https://localhost:5001/api/departments/${event.target.DepartmentId.value}`, {
        method: "PUT",
        headers:{
            "Accept":"application/json",
            "Content-Type":"application/json",
            "Origin": "*"
        },
        body: JSON.stringify({
            Id: event.target.DepartmentId.value,
            Name: event.target.DepartmentName.value
        })
    })
    .then(res=>res.json())
    .then((result)=>
    {
        this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})

    },
    (error) =>{
        this.setState({snackbaropen: true, snackbarmsg: "failed"})
    }
    )
}```

Body:
I am new in javscript development, and I have some trouble with passing id parameter in query URL.
I am passing ID value in body now, which is not right, I guess in REST approach.

How can I pass Id: event.target.DepartmentId.value, into URL like https://localhost:5001/api/departments/{id} ?

handleSubmit(event){
    event.preventDefault();
    fetch("https://localhost:5001/api/departments/", {
        method: "PUT",
        headers:{
            "Accept":"application/json",
            "Content-Type":"application/json",
            "Origin": "*"
        },
        body: JSON.stringify({
            Id: event.target.DepartmentId.value,
            Name: event.target.DepartmentName.value
        })
    })
    .then(res=>res.json())
    .then((result)=>
    {
        this.setState({snackbaropen: true, snackbarmsg: "Edited successfully!"})

    },
    (error) =>{
        this.setState({snackbaropen: true, snackbarmsg: "failed"})
    }
    )
}

Thanks for any help!


问:
find the corresponding control in repeater control
I have a Repeater control which contains a CheckBox and a lable control in each row. When a CheckBox is selected. I want to retrieve the text of the Label for the corresponding CheckBox. How to get it?

答: rowcommand event or rowdatabound event, find the 2 controls values from row in that event and get and use values . for more info http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx</p>


问:
Autoprefixer in npm script show TypeError: Patterns must be a string or an array of strings
When I run npm run prefix:css it show the

TypeError: Patterns must be a string or an array of strings

```<code>{
  "name": "natours",
  "version": "1.0.0",
  "description": "A natours project",
  "main": "index.js",
  "scripts": {
    "watch:sass": "node-sass sass/main.scss css/style.css -w",
    "compile:sass": "node-sass sass/main.scss css/style.comp.css",
    "concat:css": "concat -o css/style.concat.css css/icon-font.css
                   css/style.comp.css",
    "prefix:css": "postcss --use autoprefixer -b 'last 10 versions'
                   css/style.concat.css -o css/style.prefix.css"
   },
   "author": "Rahmat",
   "license": "ISC",
   "devDependencies": {
      "autoprefixer": "^9.6.1",
      "concat": "^1.0.3",
      "node-sass": "^4.12.0",
      "postcss-cli": "^6.1.3"
    }
   }
</code>```

This is my packge.json file

And the Error pic is -

How can i solve it?

答:
Try this:

```<code>"prefix:css": "postcss --use autoprefixer -b 'last versions'
               css/style.concat.css -o css/style.prefix.css"
</code>```

Just remove the 10, it work fine.

Body:
When I run npm run prefix:css it show the

TypeError: Patterns must be a string or an array of strings

{
  "name": "natours",
  "version": "1.0.0",
  "description": "A natours project",
  "main": "index.js",
  "scripts": {
    "watch:sass": "node-sass sass/main.scss css/style.css -w",
    "compile:sass": "node-sass sass/main.scss css/style.comp.css",
    "concat:css": "concat -o css/style.concat.css css/icon-font.css
                   css/style.comp.css",
    "prefix:css": "postcss --use autoprefixer -b 'last 10 versions'
                   css/style.concat.css -o css/style.prefix.css"
   },
   "author": "Rahmat",
   "license": "ISC",
   "devDependencies": {
      "autoprefixer": "^9.6.1",
      "concat": "^1.0.3",
      "node-sass": "^4.12.0",
      "postcss-cli": "^6.1.3"
    }
   }

This is my packge.json file

And the Error pic is -

How can i solve it?

Body:
Try this:

"prefix:css": "postcss --use autoprefixer -b 'last versions'
               css/style.concat.css -o css/style.prefix.css"

Just remove the 10, it work fine.


问:
Resizing image in Xamarin Forms
I have created an app where the user can select or take a picture.  This picture is then submitted to a web service, and can be a maximum size of 4MB.  Some pictures are larger than this so I need to resize them before submitting to get under the 4MB limit, but doing this as little as possible to keep as much detail as possible.  I couldn't find a built in way of image resizing down to a certain filesize, so to do this I have so far created a DependencyService with a specific image resizing implementation in Android and iOS.

The code that I have come up with for Android (and iOS is similar) is as follows, where I repeatedly scale the bitmap by 0.9 until it gets under the limit.  Is there a better way of doing this?:

```<code>   public byte[] ResizeImage(byte[] imageData)
        {
            var originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
            var resizedImage = originalImage;
            double newWidth = originalImage.Width;
            double newHeight = originalImage.Height;

            while (resizedImage.ByteCount > 4194304)
            {
                newWidth *= 0.9;
                newHeight *= 0.9;
                resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int) newWidth,
                    (int) newHeight, false);
            }

            using (var ms = new MemoryStream())
            {
                resizedImage.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
                return ms.ToArray();
            }
        }
</code>```

答:
I see that you use JPG without compression (in your code sample the quality is set to '100'). We also know that RGB bit depth is 24 bit/pixel. Given this we have:

```<code>ImageWidthPx * ImageHeightPx * 24/8 = TotalImageSizeInBytes
</code>```

What you are looking for is:

```<code>ScaleFactor = TotalImageSizeInBytes / (ImageWidthPx * ImageHeightPx * 24/8)
</code>```

And in your case:

```<code>var scaleFactor = 4194304 / (originalImage.Width * originalImage.Height * 3)
</code>```

Title: Resizing image in Xamarin Forms

Body:
I have created an app where the user can select or take a picture.  This picture is then submitted to a web service, and can be a maximum size of 4MB.  Some pictures are larger than this so I need to resize them before submitting to get under the 4MB limit, but doing this as little as possible to keep as much detail as possible.  I couldn't find a built in way of image resizing down to a certain filesize, so to do this I have so far created a DependencyService with a specific image resizing implementation in Android and iOS.

The code that I have come up with for Android (and iOS is similar) is as follows, where I repeatedly scale the bitmap by 0.9 until it gets under the limit.  Is there a better way of doing this?:

   public byte[] ResizeImage(byte[] imageData)
        {
            var originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length);
            var resizedImage = originalImage;
            double newWidth = originalImage.Width;
            double newHeight = originalImage.Height;

            while (resizedImage.ByteCount > 4194304)
            {
                newWidth *= 0.9;
                newHeight *= 0.9;
                resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int) newWidth,
                    (int) newHeight, false);
            }

            using (var ms = new MemoryStream())
            {
                resizedImage.Compress(Bitmap.CompressFormat.Jpeg, 100, ms);
                return ms.ToArray();
            }
        }

Body:
I see that you use JPG without compression (in your code sample the quality is set to '100'). We also know that RGB bit depth is 24 bit/pixel. Given this we have:

ImageWidthPx * ImageHeightPx * 24/8 = TotalImageSizeInBytes

What you are looking for is:

ScaleFactor = TotalImageSizeInBytes / (ImageWidthPx * ImageHeightPx * 24/8)

And in your case:

var scaleFactor = 4194304 / (originalImage.Width * originalImage.Height * 3)


答:
you should use params

and query params at the server side

```<code>   `https://localhost:5001/api/departments/?id=${id}`
</code>```

Title: Pass id parameter in fetch query (ReactJS)

Body:
you should use params

and query params at the server side

   `https://localhost:5001/api/departments/?id=${id}`


问:
Was Form.create() from antd replaced?
i am trying to create a login page in react using antd. I found a tutorial for doing this,but i belive that it is outdated, because it gives an error. I read on a forum that form.create() is not available anymore, but i don't know how to replace it.Here is my code:

```<code>import { Form, Icon, Input, Button, Spin } from 'antd';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import * as actions from '../store/actions/auth';

const FormItem = Form.Item;
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onAuth(values.userName, values.password);
        this.props.history.push('/');
      }
    });
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (
            <p>{this.props.error.message}</p>
        );
    }

    const { getFieldDecorator } = this.props.form;
    return (
        <div>
            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onSubmit={this.handleSubmit} className="login-form">

                    <FormItem>
                    {getFieldDecorator('userName', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    )}
                    </FormItem>

                    <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    )}
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }
      </div>
    );
  }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(WrappedNormalLoginForm);
</code>```

When i try to run it, i get an error that says:

```<code>TypeError: _antd.Form.create(...) is not a function
</code>```

How can i rewrite the code in order to make it run?

答:
AntD has removed Form.create in v4 and you can replace the above code with the modified API structure like

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onAuth(values.userName, values.password);
        this.props.history.push('/');
      }
    });
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (

{this.props.error.message}

        );
    }

    const { getFieldDecorator } = this.props.form;
    return (

            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onSubmit={this.handleSubmit} className="login-form">
                    <FormItem name='userName' rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    </FormItem>

                    <FormItem name="password" rules={[{ required: true, message: 'Please input your Password!' }]}>
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }

    );
  }
}

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(NormalLoginForm);
```

Please see the migration guidelines for more details

Title: Was Form.create() from antd replaced?

Body:
i am trying to create a login page in react using antd. I found a tutorial for doing this,but i belive that it is outdated, because it gives an error. I read on a forum that form.create() is not available anymore, but i don't know how to replace it.Here is my code:

import { Form, Icon, Input, Button, Spin } from 'antd';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import * as actions from '../store/actions/auth';

const FormItem = Form.Item;
const antIcon = <Icon type="loading" style={{ fontSize: 24 }} spin />;

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onAuth(values.userName, values.password);
        this.props.history.push('/');
      }
    });
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (

{this.props.error.message}

        );
    }

    const { getFieldDecorator } = this.props.form;
    return (

            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onSubmit={this.handleSubmit} className="login-form">

                    <FormItem>
                    {getFieldDecorator('userName', {
                        rules: [{ required: true, message: 'Please input your username!' }],
                    })(
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    )}
                    </FormItem>

                    <FormItem>
                    {getFieldDecorator('password', {
                        rules: [{ required: true, message: 'Please input your Password!' }],
                    })(
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    )}
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }

    );
  }
}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(WrappedNormalLoginForm);

When i try to run it, i get an error that says:

TypeError: _antd.Form.create(...) is not a function

How can i rewrite the code in order to make it run?

Body:
AntD has removed Form.create in v4 and you can replace the above code with the modified API structure like

class NormalLoginForm extends React.Component {
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onAuth(values.userName, values.password);
        this.props.history.push('/');
      }
    });
  }

  render() {
    let errorMessage = null;
    if (this.props.error) {
        errorMessage = (
            <p>{this.props.error.message}</p>
        );
    }

    const { getFieldDecorator } = this.props.form;
    return (
        <div>
            {errorMessage}
            {
                this.props.loading ?

                <Spin indicator={antIcon} />

                :

                <Form onSubmit={this.handleSubmit} className="login-form">
                    <FormItem name='userName' rules={[{ required: true, message: 'Please input your username!' }]}>
                        <Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
                    </FormItem>

                    <FormItem name="password" rules={[{ required: true, message: 'Please input your Password!' }]}>
                        <Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
                    </FormItem>

                    <FormItem>
                    <Button type="primary" htmlType="submit" style={{marginRight: '10px'}}>
                        Login
                    </Button>
                    Or
                    <NavLink
                        style={{marginRight: '10px'}}
                        to='/signup/'> signup
                    </NavLink>
                    </FormItem>
                </Form>
            }
      </div>
    );
  }
}

const mapStateToProps = (state) => {
    return {
        loading: state.loading,
        error: state.error
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onAuth: (username, password) => dispatch(actions.authLogin(username, password))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(NormalLoginForm);

Please see the migration guidelines for more details


问:
How to double split string in PHP?
I have problem that I can't solve even hours searching for answer in Google.

I have string for example:

```<code>$string = "___username1,password1___username2,password2";
</code>```

I need to split string from "___" then save result into variable and then split it again from every "," so result should be:

From first split result:

```<code>$s[0] = username1,password1
$s[1] = username2,passwrod2
</code>```

And from second split I need to get result like:

```<code>username1
password1
username2
password2
</code>```

I tried:

```<code>$s0 = explode("___",$string);
$s1 = explode(",",$s0);
</code>```

Error:

Warning: explode() expects parameter 2 to be string, array given

Could you help me please?

答:
You are almost there with the explode() using ___ as the delimiter.  You can then use 2 things, array_map() to process the result with the callback as str_getcsv as each part is a comma separated list.

As the string starts with the delimiter, this uses array_shift() to remove the blank entry off the start...

```<code>$final = array_map("str_getcsv", explode("___", $string));
array_shift($final);
print_r($final);
</code>```

gives...

```<code>Array
(
    [0] => Array
        (
            [0] => username1
            [1] => password1
        )

    [1] => Array
        (
            [0] => username2
            [1] => password2
        )

)
</code>```

Title: How to double split string in PHP?

Body:
I have problem that I can't solve even hours searching for answer in Google.

I have string for example:

$string = "___username1,password1___username2,password2";

I need to split string from "___" then save result into variable and then split it again from every "," so result should be:

From first split result:

$s[0] = username1,password1
$s[1] = username2,passwrod2

And from second split I need to get result like:

username1
password1
username2
password2

I tried:

$s0 = explode("___",$string);
$s1 = explode(",",$s0);

Error:

Warning: explode() expects parameter 2 to be string, array given

Could you help me please?

Body:
You are almost there with the explode() using ___ as the delimiter.  You can then use 2 things, array_map() to process the result with the callback as str_getcsv as each part is a comma separated list.

As the string starts with the delimiter, this uses array_shift() to remove the blank entry off the start...

$final = array_map("str_getcsv", explode("___", $string));
array_shift($final);
print_r($final);

gives...

Array
(
    [0] => Array
        (
            [0] => username1
            [1] => password1
        )

    [1] => Array
        (
            [0] => username2
            [1] => password2
        )

)


问:
How to make Swift Coordinator reflect parent's bindings changes?
Let's say I have:

structure Document, which represents text document.

EditorView  — an NSTextView, wrapped with Combine, which binds to Document.content<String>.

Document is a part of complex store:ObservableObject, so it can be bouneded to EditorView instance.

When I first create binding, it works as expected — editing NSTextView changes value in Document.content.

let document1 = Document(...)
let document2 = Document(...)
var editor = EditorView(doc: document1)
```

<p>But if change binding to another Document...</p>

<pre class="lang-swift prettyprint-override"><code>editor.doc = document2
</code>```

...then updateNSView can see new document2. But inside Coordiantor's textDidChange  has still refrence to document1.

func textDidChange(_ notification: Notification) {
    guard let textView = notification.object as? NSTextView else {
        return
    }

    self.parent.doc.content = textView.string
    self.selectedRanges = textView.selectedRanges
}
```

<p>So, initially, when i set new bindint, NSTextView changes it content to <code>document2</code>, but as I type, coordinator sends changes to <code>document1</code>.</p>

<p>Is it true, that Coordiantor keeps it's own copy of <code>parent</code>, and even if parent changes (<code>@Binding doc</code> is updated), it still references to old one?</p>

<p>How to make Coordinator reflect parent's bindings changes?</p>

<p>Thank you!</p>

<pre class="lang-swift prettyprint-override"><code>struct Document: Identifiable, Equatable {
    let id: UUID = UUID()
    var name: String
    var content: String
}

struct EditorView: NSViewRepresentable {
    @Binding var doc: Document

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeNSView(context: Context) -> CustomTextView {
        let textView = CustomTextView(
            text: doc.content,
            isEditable: isEditable,
            font: font
        )
        textView.delegate = context.coordinator

        return textView
    }

    func updateNSView(_ view: CustomTextView, context: Context) {
        view.text = doc.content
        view.selectedRanges = context.coordinator.selectedRanges

    }
}

// MARK: - Coordinator

extension EditorView {

    class Coordinator: NSObject, NSTextViewDelegate {
        var parent: EditorView
        var selectedRanges: [NSValue] = []

        init(_ parent: EditorView) {
            self.parent = parent
        }

        func textDidBeginEditing(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }

            self.parent.doc.content = textView.string
            self.parent.onEditingChanged()
        }

        func textDidChange(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }

            self.parent.doc.content = textView.string
            self.selectedRanges = textView.selectedRanges
        }

        func textDidEndEditing(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }

            self.parent.doc.content = textView.string
            self.parent.onCommit()
        }
    }
}

// MARK: - CustomTextView

final class CustomTextView: NSView {
    private var isEditable: Bool
    private var font: NSFont?

    weak var delegate: NSTextViewDelegate?

    var text: String {
        didSet {
            textView.string = text
        }
    }
    // ...
</code>```

答:
Is it true, that Coordiantor keeps it's own copy of parent, and even
  if parent changes (@Binding doc is updated), it still references to
  old one?

A parent, ie EditorView here, is struct, so answer is yes, in general it can be copied.

How to make Coordinator reflect parent's bindings changes?

Instead of (or additional to) parent, inject binding to Coordinator (via constructor) explicitly and work with it directly.

Body:
Let's say I have:

structure Document, which represents text document.

EditorView  — an NSTextView, wrapped with Combine, which binds to Document.content<String>.

Document is a part of complex store:ObservableObject, so it can be bouneded to EditorView instance.

When I first create binding, it works as expected — editing NSTextView changes value in Document.content.

let document1 = Document(...)
let document2 = Document(...)
var editor = EditorView(doc: document1)

But if change binding to another Document...

editor.doc = document2

...then updateNSView can see new document2. But inside Coordiantor's textDidChange  has still refrence to document1.

func textDidChange(_ notification: Notification) {
    guard let textView = notification.object as? NSTextView else {
        return
    }

    self.parent.doc.content = textView.string
    self.selectedRanges = textView.selectedRanges
}

So, initially, when i set new bindint, NSTextView changes it content to document2, but as I type, coordinator sends changes to document1.

Is it true, that Coordiantor keeps it's own copy of parent, and even if parent changes (@Binding doc is updated), it still references to old one?

How to make Coordinator reflect parent's bindings changes?

Thank you!

struct Document: Identifiable, Equatable {
    let id: UUID = UUID()
    var name: String
    var content: String
}

struct EditorView: NSViewRepresentable {
    @Binding var doc: Document

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeNSView(context: Context) -> CustomTextView {
        let textView = CustomTextView(
            text: doc.content,
            isEditable: isEditable,
            font: font
        )
        textView.delegate = context.coordinator

        return textView
    }

    func updateNSView(_ view: CustomTextView, context: Context) {
        view.text = doc.content
        view.selectedRanges = context.coordinator.selectedRanges

    }
}

// MARK: - Coordinator

extension EditorView {

    class Coordinator: NSObject, NSTextViewDelegate {
        var parent: EditorView
        var selectedRanges: [NSValue] = []

        init(_ parent: EditorView) {
            self.parent = parent
        }

        func textDidBeginEditing(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }

            self.parent.doc.content = textView.string
            self.parent.onEditingChanged()
        }

        func textDidChange(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }

            self.parent.doc.content = textView.string
            self.selectedRanges = textView.selectedRanges
        }

        func textDidEndEditing(_ notification: Notification) {
            guard let textView = notification.object as? NSTextView else {
                return
            }

            self.parent.doc.content = textView.string
            self.parent.onCommit()
        }
    }
}

// MARK: - CustomTextView

final class CustomTextView: NSView {
    private var isEditable: Bool
    private var font: NSFont?

    weak var delegate: NSTextViewDelegate?

    var text: String {
        didSet {
            textView.string = text
        }
    }
    // ...


问:
WebRTC: onicecandidate function not been called, hence remote video is not showing
I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.

Git: https://github.com/developerajendra/react-native-webrtc-demo

```<code>import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});
</code>```

答:
In WebRTC you have to configure SSL or you can just use it in a local environment. Otherwise MediaStream object can not be captured.
Also, you are not connecting to same-origin in the socket client. Make sure that the socket connection has not faced a CORS problem and your signaling procedure is working properly.

Body:
I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.

Git: https://github.com/developerajendra/react-native-webrtc-demo

import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});