问:
how to push the user after login or register to the home page in react js?
all my handlesubmit work correctly except the push function  ,she worked in other places </p>

```<code>handleSubmit = (e) => {
      e.preventDefault();
      const form = this.props.form;
      const { user } = this.state;
      this.setState({ submitted: true });
      let data = new FormData(); // creates a new FormData object

      data.append('password', form.getFieldValue('user.password'));
      data.append('nom', form.getFieldValue('user.nom'));
      data.append('prenom',form.getFieldValue('user.prenom'));
      data.append('email', form.getFieldValue('user.email'));
      data.append('residence',form.getFieldValue('user.residence'));
      data.append('phone',form.getFieldValue('user.phone'));
      data.append('username',form.getFieldValue('user.username') );

      axios.post('http://127.0.0.1:8000/user/register/', data)
      .then(res => {
        console.log(res)
        return res // data comes from the return of res
     })
    .then(data => { if(data.status === 201){
      history.push('/home');
  console.log(data.username)}})
      .catch(err=>console.log(err))

 };
</code>```

<p>no errors was shown </p>

答:
did you setup correctly react-router with the HOC ?

Example :

```<code>import { withRouter } from 'react-router-dom'

const Button = ({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Button)
</code>```

In your case use this.props.history

Body:
all my handlesubmit work correctly except the push function  ,she worked in other places

handleSubmit = (e) => {
      e.preventDefault();
      const form = this.props.form;
      const { user } = this.state;
      this.setState({ submitted: true });
      let data = new FormData(); // creates a new FormData object

      data.append('password', form.getFieldValue('user.password'));
      data.append('nom', form.getFieldValue('user.nom'));
      data.append('prenom',form.getFieldValue('user.prenom'));
      data.append('email', form.getFieldValue('user.email'));
      data.append('residence',form.getFieldValue('user.residence'));
      data.append('phone',form.getFieldValue('user.phone'));
      data.append('username',form.getFieldValue('user.username') );

      axios.post('http://127.0.0.1:8000/user/register/', data)
      .then(res => {
        console.log(res)
        return res // data comes from the return of res
     })
    .then(data => { if(data.status === 201){
      history.push('/home');
  console.log(data.username)}})
      .catch(err=>console.log(err))

 };

no errors was shown

Body:
did you setup correctly react-router with the HOC ?

Example :

import { withRouter } from 'react-router-dom'

const Button = ({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
)

export default withRouter(Button)

In your case use this.props.history


来源: stackexchange

问:
Is there any way i can achieve this step bar?
I am trying to make this type of step bar as in the picture but i am unable to do it.Please Suggest some way to achieve it.

I have tried various libraries like https://github.com/shuhart/StepView but i cannot get the desired results.

答:
Here's some code to get you going:

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

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/imageView4"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        android:progress="33"
        android:progressTint="@color/green"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView2"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView3"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView4"
        app:layout_constraintHorizontal_bias="0.166"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@+id/imageView3"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView3"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@id/imageView3"
        app:layout_constraintTop_toBottomOf="@+id/imageView3" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView4"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@id/imageView4"
        app:layout_constraintTop_toBottomOf="@+id/imageView4" />
</android.support.constraint.ConstraintLayout>
</code>```

Just stylise the views accordingly and set click listeners to the imageViews. Then programmatically set the progress of the bar to the desired percentage.

```<code>imageview2.setOnCLickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setProgress(33);
            }
        });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's some code to get you going:

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

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/imageView4"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        android:progress="33"
        android:progressTint="@color/green"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView2"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView3"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView4"
        app:layout_constraintHorizontal_bias="0.166"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="20dp"
        android:layout_height="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@+id/imageView3"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/accent" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView3"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@id/imageView3"
        app:layout_constraintTop_toBottomOf="@+id/imageView3" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="@+id/imageView4"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="@id/imageView4"
        app:layout_constraintTop_toBottomOf="@+id/imageView4" />
</android.support.constraint.ConstraintLayout>

Just stylise the views accordingly and set click listeners to the imageViews. Then programmatically set the progress of the bar to the desired percentage.

imageview2.setOnCLickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressBar.setProgress(33);
            }
        });


问:
Can't get dual values for my non-convex QP
How can I get CPLEX to solve for the dual values in a quadratic program? It is currently giving me error that my program is mixed integer when in fact it is not. I came up with a simple example as follows:
max z = x^2 + 2x + y
s.t 0 <= x <= 10; 0 <= y <= 10

Below is my codes in cplex c++:

```<code>IloEnv env;

IloNumVar x(env, 0, IloInfinity);
IloNumVar y(env, 0, IloInfinity);

IloExpr obj(env);
obj = x*x + 2*x + y;

IloModel model(env);
model.add(IloMaximize(env,obj));

IloRange r1(env, 0, x, 10);
IloRange r2(env, 0, y, 10);

model.add(r1);
model.add(r2);

IloCplex cplex(model);
cplex.setOut(env.getNullStream());
cplex.setWarning(env.getNullStream());
cplex.setParam(IloCplex::Param::SolutionTarget,IloCplex::SolutionOptimalGlobal);

try{
    cplex.solve();
    env.out() << "x: " << cplex.getValue(x) << endl;
    env.out() << "y: " << cplex.getValue(y) << endl;
    env.out() << "Dual r1: " << cplex.getDual(r1) << endl;
    env.out() << "Dual r2: " << cplex.getDual(r2) << endl;

    } catch (IloException& e) {
    std::cerr << "IloException: " << e << endl;
} catch (std::exception& e) {
    std::cerr << "Standard exception: " << e.what() << endl;
} catch (...) {
    std::cerr << "Some other exception!" << endl;
}
</code>```

While cplex is able to solve for the optimal solution, it is unable to generate the dual values. Error message is "Cplex Error 1017: Not available for mixed integer programs.

答:
You didn't specify which version of CPLEX you were using. Let me try with the latest one, 12.9. Here's your problem:

```<code>$ cat foo.lp
Maximize
 obj1: 2 x + y + [ 2 x ^2 ] / 2
Subject To
 c1: x <= 10
 c2: y <= 10
End
</code>```

And here's the CPLEX log when setting the OptimalityTarget parameter to 3, as you did, to get a globally optimal solution:

```<code>$ cplex -c "read foo.lp" "set optimalitytarget 3" "optimize"

Welcome to IBM(R) ILOG(R) CPLEX(R) Interactive Optimizer 12.9.0.0
  with Simplex, Mixed Integer & Barrier Optimizers
5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
Copyright IBM Corp. 1988, 2019.  All Rights Reserved.

Type 'help' for a list of available commands.
Type 'help' followed by a command name for more
information on commands.

CPLEX> Problem 'foo.lp' read.
Read time = 0.00 sec. (0.00 ticks)
CPLEX> New value for type of solution CPLEX will attempt to compute: 3
CPLEX> CPXPARAM_OptimalityTarget                        3
Warning: global optimality target changes problem type to MIQP.
Found incumbent of value 0.000000 after 0.00 sec. (0.00 ticks)
Tried aggregator 1 time.
MIQP Presolve eliminated 2 rows and 2 columns.
All rows and columns eliminated.
Presolve time = 0.00 sec. (0.00 ticks)

Root node processing (before b&c):
  Real time             =    0.00 sec. (0.00 ticks)
Parallel b&c, 4 threads:
  Real time             =    0.00 sec. (0.00 ticks)
  Sync time (average)   =    0.00 sec.
  Wait time (average)   =    0.00 sec.
                          ------------
Total (root+branch&cut) =    0.00 sec. (0.00 ticks)

Solution pool: 2 solutions saved.

MIP - Integer optimal solution:  Objective =  1.3000000000e+02
Solution time =    0.00 sec.  Iterations = 0  Nodes = 0
Deterministic time = 0.00 ticks  (2.00 ticks/sec)

CPLEX>
</code>```

You can notice the following warning (you could not see it, because you disabled the warning stream):

```<code>Warning: global optimality target changes problem type to MIQP.
</code>```

In order to solve a non-convex QP to global optimality, CPLEX has to consider the problem as a Mixed-Integer QP.  And dual values are not available for Mixed-Integer problems.

To get dual values for your solution, you can turn the problem to a fixed MIQP: the problem is relaxed to a QP with the variable bounds fixed to the incumbent solution. Then ask for local optimality (otherwise the problem will again be turned into an MIQP), and re-solve.  Here's how it looks like in the Interactive:

```<code>$ cplex129 -c "read foo.lp" "set optimalitytarget 3" "optimize" \
              "change problem fixed_miqp" "set optimalitytarget 2" \
              "optimize" "display solution dual *"

[...]

CPLEX> MIQP problem relaxed to QP with fixed integer variables using
incumbent solution.
CPLEX> New value for type of solution CPLEX will attempt to compute: 2
CPLEX> CPXPARAM_OptimalityTarget                        2
Note: Q in objective is not positive semi-definite.
Tried aggregator 1 time.
QP Presolve eliminated 2 rows and 2 columns.
All rows and columns eliminated.
Presolve time = 0.00 sec. (0.00 ticks)
Barrier time = 0.00 sec. (0.00 ticks)

Total time on 4 threads = 0.00 sec. (0.00 ticks)

Barrier - Optimal:  Objective =  1.3000000000e+02
Solution time =    0.00 sec.  Iterations = 0
Deterministic time = 0.00 ticks  (0.68 ticks/sec)

CPLEX> Constraint Name             Dual Price
c1                           22.000000
c2                            1.000000
CPLEX>
</code>```

Body:
How can I get CPLEX to solve for the dual values in a quadratic program? It is currently giving me error that my program is mixed integer when in fact it is not. I came up with a simple example as follows:
max z = x^2 + 2x + y
s.t 0 <= x <= 10; 0 <= y <= 10

Below is my codes in cplex c++:

IloEnv env;

IloNumVar x(env, 0, IloInfinity);
IloNumVar y(env, 0, IloInfinity);

IloExpr obj(env);
obj = x*x + 2*x + y;

IloModel model(env);
model.add(IloMaximize(env,obj));

IloRange r1(env, 0, x, 10);
IloRange r2(env, 0, y, 10);

model.add(r1);
model.add(r2);

IloCplex cplex(model);
cplex.setOut(env.getNullStream());
cplex.setWarning(env.getNullStream());
cplex.setParam(IloCplex::Param::SolutionTarget,IloCplex::SolutionOptimalGlobal);

try{
    cplex.solve();
    env.out() << "x: " << cplex.getValue(x) << endl;
    env.out() << "y: " << cplex.getValue(y) << endl;
    env.out() << "Dual r1: " << cplex.getDual(r1) << endl;
    env.out() << "Dual r2: " << cplex.getDual(r2) << endl;

    } catch (IloException& e) {
    std::cerr << "IloException: " << e << endl;
} catch (std::exception& e) {
    std::cerr << "Standard exception: " << e.what() << endl;
} catch (...) {
    std::cerr << "Some other exception!" << endl;
}

While cplex is able to solve for the optimal solution, it is unable to generate the dual values. Error message is "Cplex Error 1017: Not available for mixed integer programs.

Body:
You didn't specify which version of CPLEX you were using. Let me try with the latest one, 12.9. Here's your problem:

$ cat foo.lp
Maximize
 obj1: 2 x + y + [ 2 x ^2 ] / 2
Subject To
 c1: x <= 10
 c2: y <= 10
End

And here's the CPLEX log when setting the OptimalityTarget parameter to 3, as you did, to get a globally optimal solution:

$ cplex -c "read foo.lp" "set optimalitytarget 3" "optimize"

Welcome to IBM(R) ILOG(R) CPLEX(R) Interactive Optimizer 12.9.0.0
  with Simplex, Mixed Integer & Barrier Optimizers
5725-A06 5725-A29 5724-Y48 5724-Y49 5724-Y54 5724-Y55 5655-Y21
Copyright IBM Corp. 1988, 2019.  All Rights Reserved.

Type 'help' for a list of available commands.
Type 'help' followed by a command name for more
information on commands.

CPLEX> Problem 'foo.lp' read.
Read time = 0.00 sec. (0.00 ticks)
CPLEX> New value for type of solution CPLEX will attempt to compute: 3
CPLEX> CPXPARAM_OptimalityTarget                        3
Warning: global optimality target changes problem type to MIQP.
Found incumbent of value 0.000000 after 0.00 sec. (0.00 ticks)
Tried aggregator 1 time.
MIQP Presolve eliminated 2 rows and 2 columns.
All rows and columns eliminated.
Presolve time = 0.00 sec. (0.00 ticks)

Root node processing (before b&c):
  Real time             =    0.00 sec. (0.00 ticks)
Parallel b&c, 4 threads:
  Real time             =    0.00 sec. (0.00 ticks)
  Sync time (average)   =    0.00 sec.
  Wait time (average)   =    0.00 sec.
                          ------------
Total (root+branch&cut) =    0.00 sec. (0.00 ticks)

Solution pool: 2 solutions saved.

MIP - Integer optimal solution:  Objective =  1.3000000000e+02
Solution time =    0.00 sec.  Iterations = 0  Nodes = 0
Deterministic time = 0.00 ticks  (2.00 ticks/sec)

CPLEX>

You can notice the following warning (you could not see it, because you disabled the warning stream):

Warning: global optimality target changes problem type to MIQP.

In order to solve a non-convex QP to global optimality, CPLEX has to consider the problem as a Mixed-Integer QP.  And dual values are not available for Mixed-Integer problems.

To get dual values for your solution, you can turn the problem to a fixed MIQP: the problem is relaxed to a QP with the variable bounds fixed to the incumbent solution. Then ask for local optimality (otherwise the problem will again be turned into an MIQP), and re-solve.  Here's how it looks like in the Interactive:

$ cplex129 -c "read foo.lp" "set optimalitytarget 3" "optimize" \
              "change problem fixed_miqp" "set optimalitytarget 2" \
              "optimize" "display solution dual *"

[...]

CPLEX> MIQP problem relaxed to QP with fixed integer variables using
incumbent solution.
CPLEX> New value for type of solution CPLEX will attempt to compute: 2
CPLEX> CPXPARAM_OptimalityTarget                        2
Note: Q in objective is not positive semi-definite.
Tried aggregator 1 time.
QP Presolve eliminated 2 rows and 2 columns.
All rows and columns eliminated.
Presolve time = 0.00 sec. (0.00 ticks)
Barrier time = 0.00 sec. (0.00 ticks)

Total time on 4 threads = 0.00 sec. (0.00 ticks)

Barrier - Optimal:  Objective =  1.3000000000e+02
Solution time =    0.00 sec.  Iterations = 0
Deterministic time = 0.00 ticks  (0.68 ticks/sec)

CPLEX> Constraint Name             Dual Price
c1                           22.000000
c2                            1.000000
CPLEX>


问:
Position in recylerview changes while scrolling
Seems like position in recylerview changes while scrolling.

What I want to do is like this.

Adapter.java

```<code>@Override
public void onBindViewHolder(aViewHolder holder, int position) {

    if (position == 0) {
        holder.zeroIcon.setVisibility(View.VISIBLE);
    } else if (position == 1) {
        holder.oneIcon.setVisiblity(View.VISIBLE);
    } else {
        holder.otherIcon.setVisiblity(View.VISIBLE);
    }

    // Set text on each item
    ...
}

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

public class aViewHolder extends RecyclerView.ViewHolder {

    private ImageView zeroIcon;
    private ImageView oneIcon;
    private ImageView otherIcon;

    public aViewHolder(View itemView) {
        super(itemView);
        zeroIcon = itemview.findViewById(...);
        ...
    }
}
</code>```

I set these icon's visibility GONE as default in xml file.

When I see the recylerview at first, the icons show up as I expected depending on its position.

However, when I scroll down and scroll up, incorrect icons also show up on incorrect position.
Like otherIcon shows up on the first and second item while scrolling down and up. While scrolling down, zeroIcon and oneIcon show up on some other items.

How can I fix this?

list_item.xml is like this.

```<code><RelativeLayout ...>

     <ImageView
         android:id="@+id/zero"
         android:visiblity="gone"
         android:background="@drawable/zero" />

     <ImageView
         android:id="@id/one"
         android:visiblity="gone"
         android:background="@drawable/one" />

     <ImageView
         android:id="@id/other"
         android:visiblity="gone"
         android:background="@drawable/other" />
</code>```

答:
Modify it in this way,

```<code>if (position == 0) {
    holder.zeroIcon.setVisibility(View.VISIBLE);
    holder.otherIcon.setVisiblity(View.GONE);
    holder.oneIcon.setVisiblity(View.GONE);
} else if (position == 1) {
    holder.oneIcon.setVisiblity(View.VISIBLE);
    holder.zeroIcon.setVisibility(View.GONE);
    holder.otherIcon.setVisiblity(View.GONE);
} else {
    holder.otherIcon.setVisiblity(View.VISIBLE);
    holder.oneIcon.setVisiblity(View.GONE);
    holder.zeroIcon.setVisibility(View.GONE);
}
</code>```

In RecyclerView you should manage other views also while changing an item.

Body:
Seems like position in recylerview changes while scrolling.

What I want to do is like this.

Adapter.java

@Override
public void onBindViewHolder(aViewHolder holder, int position) {

    if (position == 0) {
        holder.zeroIcon.setVisibility(View.VISIBLE);
    } else if (position == 1) {
        holder.oneIcon.setVisiblity(View.VISIBLE);
    } else {
        holder.otherIcon.setVisiblity(View.VISIBLE);
    }

    // Set text on each item
    ...
}

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

public class aViewHolder extends RecyclerView.ViewHolder {

    private ImageView zeroIcon;
    private ImageView oneIcon;
    private ImageView otherIcon;

    public aViewHolder(View itemView) {
        super(itemView);
        zeroIcon = itemview.findViewById(...);
        ...
    }
}

I set these icon's visibility GONE as default in xml file.

When I see the recylerview at first, the icons show up as I expected depending on its position.

However, when I scroll down and scroll up, incorrect icons also show up on incorrect position.
Like otherIcon shows up on the first and second item while scrolling down and up. While scrolling down, zeroIcon and oneIcon show up on some other items.

How can I fix this?

list_item.xml is like this.

<RelativeLayout ...>

     <ImageView
         android:id="@+id/zero"
         android:visiblity="gone"
         android:background="@drawable/zero" />

     <ImageView
         android:id="@id/one"
         android:visiblity="gone"
         android:background="@drawable/one" />

     <ImageView
         android:id="@id/other"
         android:visiblity="gone"
         android:background="@drawable/other" />

Body:
Modify it in this way,

if (position == 0) {
    holder.zeroIcon.setVisibility(View.VISIBLE);
    holder.otherIcon.setVisiblity(View.GONE);
    holder.oneIcon.setVisiblity(View.GONE);
} else if (position == 1) {
    holder.oneIcon.setVisiblity(View.VISIBLE);
    holder.zeroIcon.setVisibility(View.GONE);
    holder.otherIcon.setVisiblity(View.GONE);
} else {
    holder.otherIcon.setVisiblity(View.VISIBLE);
    holder.oneIcon.setVisiblity(View.GONE);
    holder.zeroIcon.setVisibility(View.GONE);
}

In RecyclerView you should manage other views also while changing an item.


问:
MongoDB findOneAndUpdate returns null
I have this and I cannot get it to work. Console.log logs null.
If I log before de update code it actually logs the item that im trying to edit. If I do it after the findOneAndUpdate() it returns null.

Edit 2:

I changed the mongoose method to findById and it worked. Still have one problem though. New code:

```<code>let promo = await Promo.findById(req.body._id)
      console.log('Promo findById(promoId) => ' + promo)
      console.log('Promo Fields => ' + JSON.stringify(promoFields))
      if (promo) {
        // Update
        const promo = await Promo.findOneAndUpdate(
          { promo: req.body_id },
          { $set: promoFields },
          { new: true },
          (err, doc) =>
            console.log(err + ' <--- err ///// ' + doc + ' <--- doc ')
        )
        return res.json(promo)
</code>```

Output:

```<code>[0] Promo findById(promoId) => { _id: 5cee8b0134349e1eec482053,
[0]   title: 'Dos',
[0]   subtitle: 'dos',
[0]   desc: 'dos',
[0]   __v: 0 }
[0] Promo Fields => {"title":"Dos","subtitle":"dos","desc":"dos"}
[0] null <--- err ///// { _id: 5cee6bcbcfd3f11d580aa715,
[0]   new: false,
[0]   desc: 'dos',
[0]   subtitle: 'dos',
[0]   title: 'Dos' } <--- doc
</code>```

The problem now is no matter what item from the list I edit it always updates de first one. Can it be an id mismatch? If I debug the id from req, I have the correct id from the item selected.. don't know why it behaves this way.
Last but not least here's the reducer:

```<code>const initialState = {
  promos: null
}

export default function(state = initialState, action) {
  const { type, payload } = action

  switch (type) {
    case POST_PROMOS:
      return {
        ...state,
        ...payload,
        loading: false
      }
    default:
      return state
  }
}
</code>```

I was wondering if I could in the reduce make something like

```<code>state.promos.filter(promo => promo._id !== payload)
</code>```

and then generate a new array with the payload item. I'm mixing concepts?

Thank you in advance

答: You should use $addToSet in place of $set and it will maybe work.

Title: MongoDB findOneAndUpdate returns null

Body:
I have this and I cannot get it to work. Console.log logs null.
If I log before de update code it actually logs the item that im trying to edit. If I do it after the findOneAndUpdate() it returns null.

Edit 2:

I changed the mongoose method to findById and it worked. Still have one problem though. New code:

let promo = await Promo.findById(req.body._id)
      console.log('Promo findById(promoId) => ' + promo)
      console.log('Promo Fields => ' + JSON.stringify(promoFields))
      if (promo) {
        // Update
        const promo = await Promo.findOneAndUpdate(
          { promo: req.body_id },
          { $set: promoFields },
          { new: true },
          (err, doc) =>
            console.log(err + ' <--- err ///// ' + doc + ' <--- doc ')
        )
        return res.json(promo)

Output:

[0] Promo findById(promoId) => { _id: 5cee8b0134349e1eec482053,
[0]   title: 'Dos',
[0]   subtitle: 'dos',
[0]   desc: 'dos',
[0]   __v: 0 }
[0] Promo Fields => {"title":"Dos","subtitle":"dos","desc":"dos"}
[0] null <--- err ///// { _id: 5cee6bcbcfd3f11d580aa715,
[0]   new: false,
[0]   desc: 'dos',
[0]   subtitle: 'dos',
[0]   title: 'Dos' } <--- doc

The problem now is no matter what item from the list I edit it always updates de first one. Can it be an id mismatch? If I debug the id from req, I have the correct id from the item selected.. don't know why it behaves this way.
Last but not least here's the reducer:

const initialState = {
  promos: null
}

export default function(state = initialState, action) {
  const { type, payload } = action

  switch (type) {
    case POST_PROMOS:
      return {
        ...state,
        ...payload,
        loading: false
      }
    default:
      return state
  }
}

I was wondering if I could in the reduce make something like

state.promos.filter(promo => promo._id !== payload)

and then generate a new array with the payload item. I'm mixing concepts?

Thank you in advance


问:
Cannot read property 'doc' of undefined when mocking service class through spy/karma
I am trying to test my angular application through Karma. My application is connected to a firebase firestore database. I am trying to mock a collection and use this to test my component functions.

The code snippets that I am using are the following:

sprint.service.ts:

```<code>export class SprintService {

  getSprints() {
    return this.firestore.collection('sprints').snapshotChanges();
  }
  constructor(private firestore: AngularFirestore) { }
}
</code>```

sprints.component.ts

```<code>sprints : Sprint[];

constructor(private sprintService: SprintService) { }

ngOnInit() {
    this.sprintService.getSprints().subscribe(data => {
      this.sprints = data.map(e => {
        return {
          id: e.payload.doc.id, //HERE IT ERRORS
          ...e.payload.doc.data()
        } as Sprint;
      })
    });
  }
</code>```

sprints.component.spec.ts

```<code>//Mock class
class MockSprintServce
{
  getSprints(){
    return of([
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ])
    }
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, AngularFireModule.initializeApp(environment.firebase) ],
      declarations: [ ArchivedUserstoriesComponent,SprintDetailComponent, SprintsComponent, UserDetailComponent, UsersComponent, UserstoriesComponent, UserstoryDetailComponent ],
      providers: [AngularFirestore, {provide: SprintService, useClass: MockSprintServce}]
    })
    .compileComponents();
  }));

beforeEach(() => {
    app.sprints = [
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ]
  });

it(`should return all Sprints`, async(() => {

    //arrange
    let getSpy = spyOn(mockSprintServiceObject, 'getSprints').and.returnValue({ subscribe: () => {} });

    //act
    app.ngOnInit({});

    //assert
    expect(getSpy).toHaveBeenCalled();
    expect(getSpy).toContain(app.sprints[1]);
  }));
</code>```

I want the code to be working without any errors. I probably think i have to rewrite the getSprints method in my MockSprintService. Does anybody know what i should return or generate in the getSprints() method to make my ngOnInit work again? Help would be appreciated.

答:
In your mocked getSprints() method you should return array of objects with following structure:

```<code>{ payload: { doc: { id: some_id }} }
</code>```

because right now you e.payload is undefined in your mocked array.

Body:
I am trying to test my angular application through Karma. My application is connected to a firebase firestore database. I am trying to mock a collection and use this to test my component functions.

The code snippets that I am using are the following:

sprint.service.ts:

export class SprintService {

  getSprints() {
    return this.firestore.collection('sprints').snapshotChanges();
  }
  constructor(private firestore: AngularFirestore) { }
}

sprints.component.ts

sprints : Sprint[];

constructor(private sprintService: SprintService) { }

ngOnInit() {
    this.sprintService.getSprints().subscribe(data => {
      this.sprints = data.map(e => {
        return {
          id: e.payload.doc.id, //HERE IT ERRORS
          ...e.payload.doc.data()
        } as Sprint;
      })
    });
  }

sprints.component.spec.ts

//Mock class
class MockSprintServce
{
  getSprints(){
    return of([
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ])
    }
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, AngularFireModule.initializeApp(environment.firebase) ],
      declarations: [ ArchivedUserstoriesComponent,SprintDetailComponent, SprintsComponent, UserDetailComponent, UsersComponent, UserstoriesComponent, UserstoryDetailComponent ],
      providers: [AngularFirestore, {provide: SprintService, useClass: MockSprintServce}]
    })
    .compileComponents();
  }));

beforeEach(() => {
    app.sprints = [
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ]
  });

it(`should return all Sprints`, async(() => {

    //arrange
    let getSpy = spyOn(mockSprintServiceObject, 'getSprints').and.returnValue({ subscribe: () => {} });

    //act
    app.ngOnInit({});

    //assert
    expect(getSpy).toHaveBeenCalled();
    expect(getSpy).toContain(app.sprints[1]);
  }));

I want the code to be working without any errors. I probably think i have to rewrite the getSprints method in my MockSprintService. Does anybody know what i should return or generate in the getSprints() method to make my ngOnInit work again? Help would be appreciated.

Body:
In your mocked getSprints() method you should return array of objects with following structure:

{ payload: { doc: { id: some_id }} }

because right now you e.payload is undefined in your mocked array.


问:
what's the difference between /proc/self and /proc/$$?
I used to think that  /proc/self and /proc/$$ are the same in bash terminal, but now I find they are different.

I know $$ means the current process' pid, and /proc/self is the currently running process, it should be bash terminal. why they are different?

root@VM-73-203-debian:~# echo $$
24415
root@VM-73-203-debian:~# ls -l /proc/self
lrwxrwxrwx 1 root root 0 Nov 22  2018 /proc/self -> 24465
root@VM-73-203-debian:~# ls -l /proc/$$
total 0
dr-xr-xr-x 2 root root 0 May 29 16:23 attr
...
```

答:
$$ is a special bash variable that gets expanded to the pid of the shell.

/proc/self is a real symbolic link to the /proc/ subdirectory of the process that is making the call.

When you do ls /proc/$$ the shell expands it to ls /proc/pid-of-bash and that is what you see, the contents of the shell process.

But when you do ls /proc/self you see the contents of the short lived ls process.

The $$ is not limited to this usage, you can write echo $$ to see the bash pid; you can use it to kill yourself, etc.


问:
TS2538 Type 'undefined' cannot be used as an index type. when check assigned to variable
I get TS error:

TypeScript error: Type 'undefined' cannot be used as an index type.  TS2538

For this simple function (getting object from array based on provided index):

const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]

function getData(index?: number) {
    const isIndex : boolean = typeof index !== 'undefined';

    return isIndex ? myArr[index] : {};
}
```

<p>What's more mysterious for me is that when I change it to:</p>

```function getData(index?: number) {
    return typeof index !== 'undefined' ? myArr[index] : {};
}
```

Everything works like a charm - why?

答:
Typescript will not perform code analysis as expected due to an indirection in the code flow. This is when User Defined Type Guards come in to save the day.

```<code>function isUndefined(index: any): index is boolean {
    return typeof index === "undefined";
}

function getData(index?: number) {
    return isUndefined(index) ? {} : myArr[index];
}
</code>```

Because index is optional in the getData method, it is possible that it will be undefined, your second technique works.

Body:
I get TS error:

TypeScript error: Type 'undefined' cannot be used as an index type.  TS2538

For this simple function (getting object from array based on provided index):

const myArr: Array<object> = [{name: 'John'}, {name: 'Tom'}]

function getData(index?: number) {
    const isIndex : boolean = typeof index !== 'undefined';

    return isIndex ? myArr[index] : {};
}

What's more mysterious for me is that when I change it to:

function getData(index?: number) {
    return typeof index !== 'undefined' ? myArr[index] : {};
}

Everything works like a charm - why?

Body:
Typescript will not perform code analysis as expected due to an indirection in the code flow. This is when User Defined Type Guards come in to save the day.

function isUndefined(index: any): index is boolean {
    return typeof index === "undefined";
}

function getData(index?: number) {
    return isUndefined(index) ? {} : myArr[index];
}

Because index is optional in the getData method, it is possible that it will be undefined, your second technique works.


问:
How to add new field in array of arrays in angular5
I am getting response from my database is like this

```<code>content:Array
0:Object
title:"title1"
content:"content1"
illustrations:Array
0:Object
title:"someTitle"
imagePath:"1.jpg"
</code>```

Here I want to add one randomId in illustrations array. like this

```<code>illustrations:Array
    0:Object
    title:"someTitle"
    imagePath:"1.jpg"
    randomId:54321
</code>```

I tried like this

```<code>var randid=Math.random()*900000
            var rand=Math.round(randid)
this.illustrations[i]=Object.assign({},this.illustrations[i],{randid:rand})
and also
this.illustrations[i]=Object.assign(this.illustrations[i],{randid:rand})
</code>```

But not working.
Can any one please help.

答:
@Siva Goud..  give a try to this,

```<code>this.illustrations[i]['randomId'] = rand;
</code>```

I hope this will work...   :)

Body:
I am getting response from my database is like this

content:Array
0:Object
title:"title1"
content:"content1"
illustrations:Array
0:Object
title:"someTitle"
imagePath:"1.jpg"

Here I want to add one randomId in illustrations array. like this

illustrations:Array
    0:Object
    title:"someTitle"
    imagePath:"1.jpg"
    randomId:54321

I tried like this

var randid=Math.random()*900000
            var rand=Math.round(randid)
this.illustrations[i]=Object.assign({},this.illustrations[i],{randid:rand})
and also
this.illustrations[i]=Object.assign(this.illustrations[i],{randid:rand})

But not working.
Can any one please help.

Body:
@Siva Goud..  give a try to this,

this.illustrations[i]['randomId'] = rand;

I hope this will work...   :)


问:
Setting summary to describe the current value
When I'm trying to set summary when the users select a preference item, it normally saved. But when my app is restarted, the summary is gone.

Here is my code to set the summary for ListPreference and EditTextPreference:

```<code>public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){

    Preference pref = findPreference(key);

    // I feel the problem is happened here
    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference) pref;
        pref.setSummary(listPref.getEntry());
    }
    // Same problem here
    if (pref instanceof EditTextPreference) {
        EditTextPreference editText = (EditTextPreference) pref;
        pref.setSummary(editText.getEntry().toString());
    }
}
</code>```

Is there something wrong?

答:
I struggled so much to make summaries dynamic. Not exactly sure if this answers the question but wanted to post somewhere so if someone searches they don't have to struggle like i did.

This is the simple solution useSimpleSummaryProvider="true"

ContentLicense: CC BY-SA 3.0

Body:
When I'm trying to set summary when the users select a preference item, it normally saved. But when my app is restarted, the summary is gone.

Here is my code to set the summary for ListPreference and EditTextPreference:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){

    Preference pref = findPreference(key);

    // I feel the problem is happened here
    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference) pref;
        pref.setSummary(listPref.getEntry());
    }
    // Same problem here
    if (pref instanceof EditTextPreference) {
        EditTextPreference editText = (EditTextPreference) pref;
        pref.setSummary(editText.getEntry().toString());
    }
}

Is there something wrong?


问:
Time complexity of an algorithm that finds prime numbers given a vector
I am trying to find the time complexity of the following algorithm that finds the prime numbers given the vector. Specifically I am not sure about the last for loop with another loop nested in it. I think it's O(sqrt(n)/2), and then the loop inside it is O(n)? </p>

```<code>void PrimeFind (std::vector<bool> &vec)
{
  int vsize = vec.size();
  size_t sqvsize = ceil(sqrt(vsize));

  std::fill(vec.begin(), vec.end(), true);
  vec[0] = false;
  vec[1] = false;

  for (int i = 4; i < vsize; i += 2)
  {
    vec[i] = false;
  }

  for (int i = 3; i < sqrtvsize; i += 2)
  {
    if (vec[i])
    {
      for (int j = i * i; j < vsize; j += i)
      {
        vec[j] = false;
      }
    }
  }
}
</code>```

答:
Work performed by basic sieve of Erastophene is almost entirely culling composite numbers and it takes

In your case you start from i * i which effectively reduces number of culling operation by i - 1 for every prime. So, we need  to count number of all primes till n (vsize). This is

So, asymptotically we have

Where the last addend is the number of primes less than n.

Body:
I am trying to find the time complexity of the following algorithm that finds the prime numbers given the vector. Specifically I am not sure about the last for loop with another loop nested in it. I think it's O(sqrt(n)/2), and then the loop inside it is O(n)?

void PrimeFind (std::vector<bool> &vec)
{
  int vsize = vec.size();
  size_t sqvsize = ceil(sqrt(vsize));

  std::fill(vec.begin(), vec.end(), true);
  vec[0] = false;
  vec[1] = false;

  for (int i = 4; i < vsize; i += 2)
  {
    vec[i] = false;
  }

  for (int i = 3; i < sqrtvsize; i += 2)
  {
    if (vec[i])
    {
      for (int j = i * i; j < vsize; j += i)
      {
        vec[j] = false;
      }
    }
  }
}


问:
illegal_argument_exception in elasticsearch
I am trying to implement fuzzy,synonym,autocomplete,ngram search on "name" and " name_auto" field. but i am getting an illegal exception error.

If i remove the synonym search only then my search works fine.but below i cant even create index.what might be the issue here please help.

```<code>   {
            "settings": {
                "index": {
                    "analysis": {
                        "filter": {
                            "synonym": {
                                "type": "synonym",
                                "format": "wordnet",
                                "synonyms_path": "analysis/wn_s.pl"
                            },
                            "english_stop": {
                                "type": "stop",
                                "stopwords": "_english_"
                            },
                            "english_stemmer": {
                                "type": "stemmer",
                                "language": "english"
                            }
                        },
                        "analyzer": {
                            "synonym": {
                                "tokenizer": "standard",
                                "filter": ["english_stop", "english_stemmer", "synonym"]
                            },

                            "keyword_analyzer": {
                                "filter": [
                                    "lowercase",
                                    "asciifolding",
                                    "trim"
                                ],
                                "char_filter": [],
                                "type": "custom",
                                "tokenizer": "keyword"
                            },
                            "edge_ngram_analyzer": {
                                "filter": [
                                    "lowercase"
                                ],
                                "tokenizer": "edge_ngram_tokenizer"
                            },
                            "edge_ngram_search_analyzer": {
                                "tokenizer": "lowercase"
                            }
                        },

                        "tokenizer": {
                            "edge_ngram_tokenizer": {
                                "type": "edge_ngram",
                                "min_gram": 1,
                                "max_gram": 25,
                                "token_chars": [
                                    "letter"
                                ]
                            }

                        },
                        "mappings": {
                            "properties": {
                                "firebaseId": {
                                    "type": "text"
                                },
                                "name": {
                                    "fielddata": true,
                                    "type": "text",
                                    "analyzer": "standard"
                                },
                                "name_auto": {
                                    "type": "text",

                                    "fields": {
                                        "keywordstring": {
                                            "type": "text",
                                            "analyzer": "keyword_analyzer"
                                        },
                                        "edgengram": {
                                            "type": "text",
                                            "analyzer": "edge_ngram_analyzer",
                                            "search_analyzer": "edge_ngram_search_analyzer"
                                        },
                                        "completion": {
                                            "type": "completion"
                                        },
                                        "synonym_analyzer": {
                                            "type": "string",
                                            "analyzer": "synonym"
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
</code>```

Below is the response i am getting

```<code>{
    "error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "failed to build synonyms"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "failed to build synonyms",
        "caused_by": {
            "type": "parse_exception",
            "reason": "Invalid synonym rule at line 109",
            "caused_by": {
                "type": "illegal_argument_exception",
                "reason": "term: course of action analyzed to a token (action) with position increment != 1 (got: 2)"
            }
        }
    },
    "statu
</code>```

s": 400
}

答:
The solution was pretty simple i had to remove the "english_stop", "english_stemmer" filter.it seems like it wasnt supporting .</p>

```<code>  {
            "settings": {
                "index": {
                    "analysis": {
                        "filter": {
                            "synonym": {
                                "type": "synonym",
                                "format": "wordnet",
                                "synonyms_path": "analysis/wn_s.pl"
                            }

                        },
                        "analyzer": {
                            "synonym": {
                                "tokenizer": "standard",
                                "filter": ["synonym"]
                            },

                            "keyword_analyzer": {
                                "filter": [
                                    "lowercase",
                                    "asciifolding",
                                    "trim"
                                ],
                                "char_filter": [],
                                "type": "custom",
                                "tokenizer": "keyword"
                            },
                            "edge_ngram_analyzer": {
                                "filter": [
                                    "lowercase"
                                ],
                                "tokenizer": "edge_ngram_tokenizer"
                            },
                            "edge_ngram_search_analyzer": {
                                "tokenizer": "lowercase"
                            }
                        },

                        "tokenizer": {
                            "edge_ngram_tokenizer": {
                                "type": "edge_ngram",
                                "min_gram": 1,
                                "max_gram": 25,
                                "token_chars": [
                                    "letter"
                                ]
                            }

                        },
                        "mappings": {
                            "properties": {
                                "firebaseId": {
                                    "type": "text"
                                },
                                "name": {
                                    "fielddata": true,
                                    "type": "text",
                                    "analyzer": "standard"
                                },
                                "name_auto": {
                                    "type": "text",

                                    "fields": {
                                        "keywordstring": {
                                            "type": "text",
                                            "analyzer": "keyword_analyzer"
                                        },
                                        "edgengram": {
                                            "type": "text",
                                            "analyzer": "edge_ngram_analyzer",
                                            "search_analyzer": "edge_ngram_search_analyzer"
                                        },
                                        "completion": {
                                            "type": "completion"
                                        },
                                        "synonym_analyzer": {
                                            "type": "string",
                                            "analyzer": "synonym"
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
</code>```

Body:
I am trying to implement fuzzy,synonym,autocomplete,ngram search on "name" and " name_auto" field. but i am getting an illegal exception error.

If i remove the synonym search only then my search works fine.but below i cant even create index.what might be the issue here please help.

   {
            "settings": {
                "index": {
                    "analysis": {
                        "filter": {
                            "synonym": {
                                "type": "synonym",
                                "format": "wordnet",
                                "synonyms_path": "analysis/wn_s.pl"
                            },
                            "english_stop": {
                                "type": "stop",
                                "stopwords": "_english_"
                            },
                            "english_stemmer": {
                                "type": "stemmer",
                                "language": "english"
                            }
                        },
                        "analyzer": {
                            "synonym": {
                                "tokenizer": "standard",
                                "filter": ["english_stop", "english_stemmer", "synonym"]
                            },

                            "keyword_analyzer": {
                                "filter": [
                                    "lowercase",
                                    "asciifolding",
                                    "trim"
                                ],
                                "char_filter": [],
                                "type": "custom",
                                "tokenizer": "keyword"
                            },
                            "edge_ngram_analyzer": {
                                "filter": [
                                    "lowercase"
                                ],
                                "tokenizer": "edge_ngram_tokenizer"
                            },
                            "edge_ngram_search_analyzer": {
                                "tokenizer": "lowercase"
                            }
                        },

                        "tokenizer": {
                            "edge_ngram_tokenizer": {
                                "type": "edge_ngram",
                                "min_gram": 1,
                                "max_gram": 25,
                                "token_chars": [
                                    "letter"
                                ]
                            }

                        },
                        "mappings": {
                            "properties": {
                                "firebaseId": {
                                    "type": "text"
                                },
                                "name": {
                                    "fielddata": true,
                                    "type": "text",
                                    "analyzer": "standard"
                                },
                                "name_auto": {
                                    "type": "text",

                                    "fields": {
                                        "keywordstring": {
                                            "type": "text",
                                            "analyzer": "keyword_analyzer"
                                        },
                                        "edgengram": {
                                            "type": "text",
                                            "analyzer": "edge_ngram_analyzer",
                                            "search_analyzer": "edge_ngram_search_analyzer"
                                        },
                                        "completion": {
                                            "type": "completion"
                                        },
                                        "synonym_analyzer": {
                                            "type": "string",
                                            "analyzer": "synonym"
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }

Below is the response i am getting

{
    "error": {
        "root_cause": [
            {
                "type": "illegal_argument_exception",
                "reason": "failed to build synonyms"
            }
        ],
        "type": "illegal_argument_exception",
        "reason": "failed to build synonyms",
        "caused_by": {
            "type": "parse_exception",
            "reason": "Invalid synonym rule at line 109",
            "caused_by": {
                "type": "illegal_argument_exception",
                "reason": "term: course of action analyzed to a token (action) with position increment != 1 (got: 2)"
            }
        }
    },
    "statu

s": 400
}

Body:
The solution was pretty simple i had to remove the "english_stop", "english_stemmer" filter.it seems like it wasnt supporting .

  {
            "settings": {
                "index": {
                    "analysis": {
                        "filter": {
                            "synonym": {
                                "type": "synonym",
                                "format": "wordnet",
                                "synonyms_path": "analysis/wn_s.pl"
                            }

                        },
                        "analyzer": {
                            "synonym": {
                                "tokenizer": "standard",
                                "filter": ["synonym"]
                            },

                            "keyword_analyzer": {
                                "filter": [
                                    "lowercase",
                                    "asciifolding",
                                    "trim"
                                ],
                                "char_filter": [],
                                "type": "custom",
                                "tokenizer": "keyword"
                            },
                            "edge_ngram_analyzer": {
                                "filter": [
                                    "lowercase"
                                ],
                                "tokenizer": "edge_ngram_tokenizer"
                            },
                            "edge_ngram_search_analyzer": {
                                "tokenizer": "lowercase"
                            }
                        },

                        "tokenizer": {
                            "edge_ngram_tokenizer": {
                                "type": "edge_ngram",
                                "min_gram": 1,
                                "max_gram": 25,
                                "token_chars": [
                                    "letter"
                                ]
                            }

                        },
                        "mappings": {
                            "properties": {
                                "firebaseId": {
                                    "type": "text"
                                },
                                "name": {
                                    "fielddata": true,
                                    "type": "text",
                                    "analyzer": "standard"
                                },
                                "name_auto": {
                                    "type": "text",

                                    "fields": {
                                        "keywordstring": {
                                            "type": "text",
                                            "analyzer": "keyword_analyzer"
                                        },
                                        "edgengram": {
                                            "type": "text",
                                            "analyzer": "edge_ngram_analyzer",
                                            "search_analyzer": "edge_ngram_search_analyzer"
                                        },
                                        "completion": {
                                            "type": "completion"
                                        },
                                        "synonym_analyzer": {
                                            "type": "string",
                                            "analyzer": "synonym"
                                        }
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }


问:
How to migrate Kafka topic used in a standalone Kafka server to Kafka cluster with replication-factor 2?
I'm running a standalone Kafka server with multiple producers and consumers. Now I want to implement Kafka cluster by adding another broker. How can I do this by using same topic with replication-factor.</p>

答:
Now you are moving to a cluster having two kafka brokers then you should increase the number of partitions to two using the following commands.

```<code>kafka-topics --topic my-topic --alter --partitions 2 --zookeeper zoo1
</code>```

# Observe partitions with Number of partition 2 and RF: 1

```<code>kafka-topics --topic my-topic --describe  --zookeeper zoo1

Topic:my-topic PartitionCount:2 ReplicationFactor:1 Configs:

 Topic: my-topic Partition: 0 Leader: 0 Replicas: 1 Isr: 0
 Topic: my-topic Partition: 1 Leader: 2 Replicas: 1 Isr: 1
</code>```

Increasing the replication factor of an existing topic is easy.Need to specify the extra replicas in the custom reassignment json file and use it with --execute option.

Create increase-replication-factor.json

```<code>   {"version":1,
  "partitions":[
     {"topic":"my-topic","partition":0,"replicas":[0,1]},
     {"topic":"my-topic","partition":1,"replicas":[0,1]}
]}
</code>```

Execute the following command

```<code>kafka-reassign-partitions --zookeeper localhost:2181 --reassignment-json-file increase-replication-factor.json --execute
</code>```

You can verify the replicas using the following command.

```<code>kafka-topics --zookeeper localhost:2181 --topic my-topic --describe

Topic: my-topic Partition: 0    Leader: 0   Replicas: 0,1 Isr: 0,1
Topic: my-topic Partition: 1    Leader: 1   Replicas: 0,1 Isr: 0,1
</code>```

I would suggest you to go through the following link to redistribute the data on two partitions equally.

https://labs.tabmo.io/rebalancing-kafkas-partitions-803918d8d244
https://kafka.apache.org/documentation/#basic_ops_increase_replication_factor

Hope it will be helpful to you.

Body:
Now you are moving to a cluster having two kafka brokers then you should increase the number of partitions to two using the following commands.

kafka-topics --topic my-topic --alter --partitions 2 --zookeeper zoo1

# Observe partitions with Number of partition 2 and RF: 1

kafka-topics --topic my-topic --describe  --zookeeper zoo1

Topic:my-topic PartitionCount:2 ReplicationFactor:1 Configs:

 Topic: my-topic Partition: 0 Leader: 0 Replicas: 1 Isr: 0
 Topic: my-topic Partition: 1 Leader: 2 Replicas: 1 Isr: 1

Increasing the replication factor of an existing topic is easy.Need to specify the extra replicas in the custom reassignment json file and use it with --execute option.

Create increase-replication-factor.json

   {"version":1,
  "partitions":[
     {"topic":"my-topic","partition":0,"replicas":[0,1]},
     {"topic":"my-topic","partition":1,"replicas":[0,1]}
]}

Execute the following command

kafka-reassign-partitions --zookeeper localhost:2181 --reassignment-json-file increase-replication-factor.json --execute

You can verify the replicas using the following command.

kafka-topics --zookeeper localhost:2181 --topic my-topic --describe

Topic: my-topic Partition: 0    Leader: 0   Replicas: 0,1 Isr: 0,1
Topic: my-topic Partition: 1    Leader: 1   Replicas: 0,1 Isr: 0,1

I would suggest you to go through the following link to redistribute the data on two partitions equally.

https://labs.tabmo.io/rebalancing-kafkas-partitions-803918d8d244
https://kafka.apache.org/documentation/#basic_ops_increase_replication_factor

Hope it will be helpful to you.


答:
You can't do the "limit 1" at the outer level, you loose what you are looking for... ALL devices last entry.  Use a pre-query for the last ID of each device, then join back...

```<code>select
        Devices.*,
        DataLog.Time_Stamp,
        DataLog.FuelLevel,
        DataLog.Voltage
    from
        ( select DeviceID,
                 max( ID ) LastActionID
              from
                 DataLog
              group by
                 1 ) LastInstance
        join DataLog
            on LastInstance.LastActionID = DataLog.ID
        join Devices
            on LastInstance.DeviceID = Devices.DeviceID
   order by
       Devices.DeviceName
</code>```

Per your last comment, I would actually change to something like...

Update your device table with a "LastLogID".  Then, via a trigger an insert into your DataLog table, update the Device table immediately with that new ID... This way, you never need to pre-query the data log directly.. You'll already HAVE the last ID and run from that directly to the data log joined by that ID.

Title: Joining one table to the latest row in another table using MySQL

Body:
I want to join two tables in a special way, first table is devices which has a list of devices.

The second table is datalog which is where abit of data is stored for everytime a device in devices gets polled.

Devices Table:

+----------+------------+----------------------------+---------------------+
| deviceId | deviceName | deviceDescription          | timeCreated         |
+----------+------------+----------------------------+---------------------+
|        1 | System 1   | Main System in Server Room | 2010-01-01 00:00:00 |
|        2 | System 2   | Outdoor System             | 2010-01-01 00:00:00 |
+----------+------------+----------------------------+---------------------+

DataLog Table:

+----+---------------------+----------+-----------+---------+
| id | time_stamp          | DeviceId | FuelLevel | Voltage |
+----+---------------------+----------+-----------+---------+
|  1 | 2010-01-01 00:00:00 |        1 |        60 |     220 |
|  2 | 2010-01-01 00:00:00 |        2 |        20 |     221 |
|  3 | 2010-01-02 00:00:00 |        1 |       100 |     219 |
|  4 | 2010-01-02 00:00:00 |        2 |       100 |     222 |
|  5 | 2010-01-03 00:00:00 |        1 |        80 |     219 |
|  6 | 2010-01-03 00:00:00 |        2 |        99 |     220 |
+----+---------------------+----------+-----------+---------+

Currently I am getting the latest data for each device using a query on the DataLog table with:

 Where DeviceId = 1 ORDER BY timestamp DESC LIMIT 1

What I would like is one query to return a list of all devices, with the columns joined with the latest data for each device like this:

+----------+------------+----------------------------+---------------------+-----------+---------+
| deviceId | deviceName | deviceDescription          | time_stamp          |FuelLevel  | Voltage |
+----------+------------+----------------------------+---------------------+-----------+---------+
|        1 | System 1   | Main System in Server Room | 2010-01-03 00:00:00 |        80 |     219 |
|        2 | System 2   | Outdoor System             | 2010-01-03 00:00:00 |       99  |     220 |
+----------+------------+----------------------------+---------------------+-----------+---------+

Body:
You can't do the "limit 1" at the outer level, you loose what you are looking for... ALL devices last entry.  Use a pre-query for the last ID of each device, then join back...

select
        Devices.*,
        DataLog.Time_Stamp,
        DataLog.FuelLevel,
        DataLog.Voltage
    from
        ( select DeviceID,
                 max( ID ) LastActionID
              from
                 DataLog
              group by
                 1 ) LastInstance
        join DataLog
            on LastInstance.LastActionID = DataLog.ID
        join Devices
            on LastInstance.DeviceID = Devices.DeviceID
   order by
       Devices.DeviceName

Per your last comment, I would actually change to something like...

Update your device table with a "LastLogID".  Then, via a trigger an insert into your DataLog table, update the Device table immediately with that new ID... This way, you never need to pre-query the data log directly.. You'll already HAVE the last ID and run from that directly to the data log joined by that ID.


问:
Shortest distance between two degree marks on a circle?
I'm looking for a formula to find the shortest distance in degrees between two degree marks on a circle:  for instance, 30 degrees and 170 degrees (140 degrees).

The two degree marks can be virtually any real number, and isn't necessarily between 0 and 360 (can be negative, or much greater than 360, for instance -528.2 and 740 (which is 171.8 degrees)).  However, the distance should always be <= 180 degrees and >= 0 degrees.

It sounds simple enough.  But, I've been trying to find a good solution for this and I've tried a lot of different code but nothing I've found so far works in all the cases I've tried.  I'm working in c++.  Does anyone have any ideas?

答:
For beginners like me, the other answers - though very likely to give you a good result -  were a bit difficult to understand what is going on. Therefore, here is my method that checks which direction (clockwise or counter-clockwise) is shortest between a cp(current point) and a tp(target point). It also assigns that shortest distance value to a shortestDistance variable. Based on what I specifically needed this method for, it was important for me to return a boolean value as to whether the shortest distance was in the clockwise or counter-clockwise direction. Here is the method:

```<code>public boolean checkIfClockwiseIsShortest(int cp, int tp) {
    boolean clockwiseIsShortest = false;
    if (cp != tp) { // if current point and target point are not the same...
        if (tp > cp) { // if current point is less than target point AND..
            if ((tp - cp) <= ((360 - tp) + cp)) {
                clockwiseIsShortest = true;
                shortestDistance = (tp-cp);
                System.out.println("Case A: " + shortestDistance +" degrees clockwise");//[CAN REMOVE]

            } else if ((tp - cp) > ((360 - tp) + cp)) {
                clockwiseIsShortest = false;
                shortestDistance = ((360 - tp) + cp);
                System.out.println("Case B: " + shortestDistance+" degrees counter-clockwise");//[CAN REMOVE]
            }
        } else { // BUT if target point < current point
            if ((cp - tp) <= ((360 - cp) + tp)) {
                clockwiseIsShortest = false;
                shortestDistance = (cp-tp);
                System.out.println("Case C: " + shortestDistance+" degrees counter-clockwise");//[CAN REMOVE]
            } else if ((cp - tp) > ((360 - cp) + tp)) {
                clockwiseIsShortest = true;
                shortestDistance = ((360 - cp) + tp);
                System.out.println("Case D: " + shortestDistance+" degrees clockwise");//[CAN REMOVE]
            }
        }
    }
    return clockwiseIsShortest;
}
</code>```

Note that cp is the starting point in integer degrees and tp is the target point in integer degrees; the type can be changed to double for more precision .

It does account for going (counter)clockwise past 0 degree mark.

The 3 if's it checks:

is the starting/current point (cp) equal to target point(tp)? if so, no distance is given.

if not equal, is the target point > current point in degrees OR is target point < current point in degrees?

Based on this, the last if in the nest checks if going clockwise is less degrees that going counter-clockwise (or vise versa).

Again, the other posts with shorter code may work just fine.

Edit: BTW, the shortestDistance variable is a class variable, initialized within the same class as this method; if you are ripping this code, make sure that your class in which you are placing it also has a shortestDistance variable based on the primitive type as the cp and tp variables (or cast it).

Body:
For beginners like me, the other answers - though very likely to give you a good result -  were a bit difficult to understand what is going on. Therefore, here is my method that checks which direction (clockwise or counter-clockwise) is shortest between a cp(current point) and a tp(target point). It also assigns that shortest distance value to a shortestDistance variable. Based on what I specifically needed this method for, it was important for me to return a boolean value as to whether the shortest distance was in the clockwise or counter-clockwise direction. Here is the method:

public boolean checkIfClockwiseIsShortest(int cp, int tp) {
    boolean clockwiseIsShortest = false;
    if (cp != tp) { // if current point and target point are not the same...
        if (tp > cp) { // if current point is less than target point AND..
            if ((tp - cp) <= ((360 - tp) + cp)) {
                clockwiseIsShortest = true;
                shortestDistance = (tp-cp);
                System.out.println("Case A: " + shortestDistance +" degrees clockwise");//[CAN REMOVE]

            } else if ((tp - cp) > ((360 - tp) + cp)) {
                clockwiseIsShortest = false;
                shortestDistance = ((360 - tp) + cp);
                System.out.println("Case B: " + shortestDistance+" degrees counter-clockwise");//[CAN REMOVE]
            }
        } else { // BUT if target point < current point
            if ((cp - tp) <= ((360 - cp) + tp)) {
                clockwiseIsShortest = false;
                shortestDistance = (cp-tp);
                System.out.println("Case C: " + shortestDistance+" degrees counter-clockwise");//[CAN REMOVE]
            } else if ((cp - tp) > ((360 - cp) + tp)) {
                clockwiseIsShortest = true;
                shortestDistance = ((360 - cp) + tp);
                System.out.println("Case D: " + shortestDistance+" degrees clockwise");//[CAN REMOVE]
            }
        }
    }
    return clockwiseIsShortest;
}

Note that cp is the starting point in integer degrees and tp is the target point in integer degrees; the type can be changed to double for more precision .

It does account for going (counter)clockwise past 0 degree mark.

The 3 if's it checks:

is the starting/current point (cp) equal to target point(tp)? if so, no distance is given.

if not equal, is the target point > current point in degrees OR is target point < current point in degrees?

Based on this, the last if in the nest checks if going clockwise is less degrees that going counter-clockwise (or vise versa).

Again, the other posts with shorter code may work just fine.

Edit: BTW, the shortestDistance variable is a class variable, initialized within the same class as this method; if you are ripping this code, make sure that your class in which you are placing it also has a shortestDistance variable based on the primitive type as the cp and tp variables (or cast it).


问:
How can i have more than one buttons on action with search view?
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

```<code>@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

</code>```

this is xml of search view menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>
</code>```

this is xml of dropdown menu

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>
</code>```

答:
Here is example for capturing images from webcam.This is newer, OO, consolidated OpenCV 2 Python API.</p>

```<code>import cv2

# Camera 0 is your port number
camera_port = 0

#Number of frames to throw away while the camera adjusts to light levels
ramp_frames = 30

# Initialize cam with port
camera = cv2.VideoCapture(camera_port)

# Captures a single image & returns  in PIL format
def get_image():

# read full image out of a VideoCapture object.
retval, im = camera.read()
return im

# Ramp the camera - these frames will be discarded and are only used to allow v4l2
for i in xrange(ramp_frames):
temp = get_image()
print("Taking image...")

# Take the actual image we want to keep
camera_capture = get_image()
file = "/home/codeplasma/test_image.png"

# correct format based on the file extension you provide. Convenient!
cv2.imwrite(file, camera_capture)

# capture object until your script exits
del(camera)
</code>```

Body:
Actually i want to make an action bar in which in should have dropdown menu , serach option,menu option and one other icon when i add drop down menu , the search bar is not on full action bar.when i click search icon the search view should be on full action bar but it only on half remaining is covered by dropdown menu

this is java code

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.mainpage, menu);
        getMenuInflater().inflate(R.menu.android_action_bar_spinner_menu, menu);

        MenuItem item = menu.findItem(R.id.spinner);
        Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.dropdown, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_search, menu);

        MenuItem search_item = menu.findItem(R.id.mi_search);

        SearchView searchView = (SearchView) search_item.getActionView();
        searchView.setFocusable(false);
        searchView.setQueryHint("Search");
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String s) {

                //clear the previous data in search arraylist if exist
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                     return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                Toast.makeText(MainpageActivity.this, s, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_alldocs) {
            // Handle the camera action
        } else if (id == R.id.nav_shared) {

        } else if (id == R.id.nav_tags) {

        } else if (id == R.id.notifications) {

        } else if (id == R.id.nav_settings) {

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

this is xml of search view menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="codes4.com.simplelistview.MainActivity">

    <item

        android:id="@+id/mi_search"
        android:title="search something"
        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView"
        />

</menu>

this is xml of dropdown menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/spinner"
        android:title="ActionBar Spinner"
        app:actionViewClass="android.widget.Spinner"
        android:background="#ff00"
        app:showAsAction="always"
        />
</menu>

Body:
Here is example for capturing images from webcam.This is newer, OO, consolidated OpenCV 2 Python API.

import cv2

# Camera 0 is your port number
camera_port = 0

#Number of frames to throw away while the camera adjusts to light levels
ramp_frames = 30

# Initialize cam with port
camera = cv2.VideoCapture(camera_port)

# Captures a single image & returns  in PIL format
def get_image():

# read full image out of a VideoCapture object.
retval, im = camera.read()
return im

# Ramp the camera - these frames will be discarded and are only used to allow v4l2
for i in xrange(ramp_frames):
temp = get_image()
print("Taking image...")

# Take the actual image we want to keep
camera_capture = get_image()
file = "/home/codeplasma/test_image.png"

# correct format based on the file extension you provide. Convenient!
cv2.imwrite(file, camera_capture)

# capture object until your script exits
del(camera)


问:
c# Task.WhenAll to block while awaiting completion
I have a simple Winforms application. I would like to background TCP connections/print requests and check the output of all tasks at a set point in my code.

I would expect ReportOnTasks to block until WaitAll is complete. Please could someone explain why this is not the case? I'm also worried I haven't structured this correctly.

Edit, to clarify my intentions:
I would like to send the print jobs as soon as I receive the data. Then continue with some other DB operations. Once all the print operations are complete, I would like to update the UI to state the result.

I've attempted to simplify the code as much as I can. Maybe too much. HomeController just inits some stuff. There are buttons on the form and file watchers that trigger the main functionality.

```<code>public class HomeController
{

    public HomeController(){

        MessageBox.Show("1");

        oPrintController.PrintAsync("192.168.2.213", Encoding.ASCII.GetBytes("string to print"));

        MessageBox.Show("2");

        // Block here untill tasks are complete
        ReportOnTasks();

        MessageBox.Show("Report on tasks complete");
    }

    public async void ReportOnTasks()
    {
        await Task.WhenAll(oPrintController.Tasks);

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
}
</code>```

and the PrintController

```<code>public class PrintController
{

    public List<Task<PrintResult>> Tasks = new List<Task<PrintResult>>();

    public async void PrintAsync(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {
        var s = await Task.Run(() => PrintAsync1(sIP, lsToPrint));
    }

    public async System.Threading.Tasks.Task<PrintResult> PrintAsync1(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {

        using (TcpClient tc = new TcpClient())
        {
            await tc.ConnectAsync(sIP, iPort);
            using (var ns = tc.GetStream())
            {
                foreach (byte[] btLabel in lsToPrint)
                {
                    await ns.WriteAsync(btLabel, 0, btLabel.Length);
                }
            }
        }

        Thread.Sleep(10000);

        return new PrintResult();
    }
}

public class PrintResult
{
    bool bSuccess = false;
}
</code>```

答:
You are not awaiting the call to ReportOnTasks()

Moreover, you can't await within a ctor, because they can't be async.

Depending on how your HomeController is used, you could use a static async method which returns an instance of HomeController, created by a private ctor instead:

Something like this:

```<code>public class HomeController
{

    //notice private - you can't new up a HomeController - you have to use `CreateInstance`
    private HomeController(){

        MessageBox.Show("1");

        //not clear from your code where oPrintController comes from??
        oPrintController.PrintAsync("192.168.2.213", Encoding.ASCII.GetBytes("string to print"));

        MessageBox.Show("2");

        MessageBox.Show("Report on tasks complete");
    }

    public static async Task<HomeController> CreateInstance() {
        var homeController = new HomeController();

        await homeController.ReportOnTasks();

        return homeController;
    }

    //don't use async void! Change to Task
    public async Task ReportOnTasks()
    {
        //not clear from your code where oPrintController comes from??
        await Task.WhenAll(oPrintController.Tasks);

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
}
</code>```

Usage:

```<code>var homeControllerInstance = await HomeController.CreateInstance();
</code>```

Body:
I have a simple Winforms application. I would like to background TCP connections/print requests and check the output of all tasks at a set point in my code.

I would expect ReportOnTasks to block until WaitAll is complete. Please could someone explain why this is not the case? I'm also worried I haven't structured this correctly.

Edit, to clarify my intentions:
I would like to send the print jobs as soon as I receive the data. Then continue with some other DB operations. Once all the print operations are complete, I would like to update the UI to state the result.

I've attempted to simplify the code as much as I can. Maybe too much. HomeController just inits some stuff. There are buttons on the form and file watchers that trigger the main functionality.

public class HomeController
{

    public HomeController(){

        MessageBox.Show("1");

        oPrintController.PrintAsync("192.168.2.213", Encoding.ASCII.GetBytes("string to print"));

        MessageBox.Show("2");

        // Block here untill tasks are complete
        ReportOnTasks();

        MessageBox.Show("Report on tasks complete");
    }

    public async void ReportOnTasks()
    {
        await Task.WhenAll(oPrintController.Tasks);

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
}

and the PrintController

public class PrintController
{

    public List<Task<PrintResult>> Tasks = new List<Task<PrintResult>>();

    public async void PrintAsync(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {
        var s = await Task.Run(() => PrintAsync1(sIP, lsToPrint));
    }

    public async System.Threading.Tasks.Task<PrintResult> PrintAsync1(string sIP, List<byte[]> lsToPrint, int iPort = 9100)
    {

        using (TcpClient tc = new TcpClient())
        {
            await tc.ConnectAsync(sIP, iPort);
            using (var ns = tc.GetStream())
            {
                foreach (byte[] btLabel in lsToPrint)
                {
                    await ns.WriteAsync(btLabel, 0, btLabel.Length);
                }
            }
        }

        Thread.Sleep(10000);

        return new PrintResult();
    }
}

public class PrintResult
{
    bool bSuccess = false;
}

Body:
You are not awaiting the call to ReportOnTasks()

Moreover, you can't await within a ctor, because they can't be async.

Depending on how your HomeController is used, you could use a static async method which returns an instance of HomeController, created by a private ctor instead:

Something like this:

public class HomeController
{

    //notice private - you can't new up a HomeController - you have to use `CreateInstance`
    private HomeController(){

        MessageBox.Show("1");

        //not clear from your code where oPrintController comes from??
        oPrintController.PrintAsync("192.168.2.213", Encoding.ASCII.GetBytes("string to print"));

        MessageBox.Show("2");

        MessageBox.Show("Report on tasks complete");
    }

    public static async Task<HomeController> CreateInstance() {
        var homeController = new HomeController();

        await homeController.ReportOnTasks();

        return homeController;
    }

    //don't use async void! Change to Task
    public async Task ReportOnTasks()
    {
        //not clear from your code where oPrintController comes from??
        await Task.WhenAll(oPrintController.Tasks);

        foreach(Task<PrintController.PrintResult> PR in oPrintController.Tasks)
        {
            // do something with the result of task
        }
    }
}

Usage:

var homeControllerInstance = await HomeController.CreateInstance();


问:
Reading an HTML File from Folder in Python
I want to read an HTML file in Python 3.4.3.

I have tried:

```<code>import urllib.request
fname = r"C:\Python34\html.htm"
HtmlFile = open(fname,'w')
print (HtmlFile)
</code>```

This prints:

```<code><_io.TextIOWrapper name='C:\\Python34\\html.htm' mode='w' encoding='cp1252'>
</code>```

I want to get the HTML source so that I can parse it with beautiful soup.

答:
I was trying to read the saved HTML file in the folder. I tried code mentioned by Vikasa but was getting an error. So I changed the code and tried to read it again it worked for me. The code is as follows:

```<code>    fname = 'page_source.html' #this html file is stored on the same folder of the code file
    html_file = open(fname, 'r')
    source_code = html_file.read()
</code>```

print the html page using

```<code>source_code
</code>```

It will print the content read from the page_source.html file.

Body:
I want to read an HTML file in Python 3.4.3.

I have tried:

import urllib.request
fname = r"C:\Python34\html.htm"
HtmlFile = open(fname,'w')
print (HtmlFile)

This prints:

<_io.TextIOWrapper name='C:\\Python34\\html.htm' mode='w' encoding='cp1252'>

I want to get the HTML source so that I can parse it with beautiful soup.

Body:
I was trying to read the saved HTML file in the folder. I tried code mentioned by Vikasa but was getting an error. So I changed the code and tried to read it again it worked for me. The code is as follows:

    fname = 'page_source.html' #this html file is stored on the same folder of the code file
    html_file = open(fname, 'r')
    source_code = html_file.read()

print the html page using

source_code

It will print the content read from the page_source.html file.