问:
Problem with null reference passing data to a RecyclerView
I'm passing data from a firebase database to a RecyclerView in an Activity through a RecyclerView Adapter.

I can't see any error, but everytime i try to access to this activity the app crashes.

This Activity has also some spinners to make filters to select only some objects from the database; but even i removed this part of the code, it isn't still working.

The RecyclerView Activity:

public class Lista extends AppCompatActivity {

    //ListView listatocha;
    DatabaseReference bbdd;
    Button btnreestablecer;

    RecyclerView rcvg;
    Adaptagrande rAdapterg;
    RecyclerView.LayoutManager layoutManagerg;
    List<Juego> juegostocha;

    Spinner spncons;
    Spinner spnform;
    Spinner spnpos;
    Spinner spnavan;
    Spinner spnvec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista);
       // listatocha = (ListView) findViewById(R.id.lstvwlistgrand);
        btnreestablecer = (Button) findViewById(R.id.btntitlsrc);
        rcvg = (RecyclerView) findViewById(R.id.recyclergrande);
        rcvg.setLayoutManager(new LinearLayoutManager(getApplicationContext())); //a ver si
        juegostocha = new ArrayList<>();
        rAdapterg = new Adaptagrande(getApplicationContext(),juegostocha);
        rcvg.setAdapter(rAdapterg);

        bbdd = FirebaseDatabase.getInstance().getReference("juegos");

        spncons = (Spinner) findViewById(R.id.spnplataformal);
        spnform = (Spinner) findViewById(R.id.spnformatol);
        spnpos = (Spinner) findViewById(R.id.spnposesionl);
        spnavan = (Spinner) findViewById(R.id.spnavancel);
        spnvec = (Spinner) findViewById(R.id.spnvecesl);

        /*
        spncons.setSelection(0);
        spnform.setSelection(0);
        spnpos.setSelection(0);
        spnavan.setSelection(0);
        spnvec.setSelection(0);
        */

        String[] plataformas = new String[] {"Plataforma","PC", "PS2", "PS3", "PS4", "N64", "Gamecube", "Wii", "WiiU", "NSwitch", "Xbox", "Xbox360", "XboxOne", "PSone", "GameBoy", "GBA", "DS", "3DS", "PSP", "PSVita"}; //2-8 | 2.2 3.8 4.2 5.1 6.1 7.4 8.1
        String[] avance = new String[] {"Avance","Nulo", "Probado", "Intermedio", "Pasado", "Completado", "Irrelevante"}; //4-11 | 4.1 6.1 7.1 10.2 11.1
        String[] veces = new String[] {"Veces","0","1","2","3-5","+5"}; //0-3
        String[] posesion = new String[] {"Posesión","Si","No"};  //siempre igual
        String[] formato = new String[] {"Físico","Si","No"};     //siempre igual

        ArrayAdapter<String> adaptaforms = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, plataformas);
        ArrayAdapter<String> adaptavanc = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, avance);
        ArrayAdapter<String> adaptveces = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, veces);
        ArrayAdapter<String> adaptapose = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, posesion);
        ArrayAdapter<String> adaptaform = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, formato);

        spncons.setAdapter(adaptaforms);
        spnvec.setAdapter(adaptveces);
        spnavan.setAdapter(adaptavanc);
        spnpos.setAdapter(adaptapose);
        spnform.setAdapter(adaptaform);

        spncons.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spnpos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spnform.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spnavan.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spnvec.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnreestablecer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spncons.setSelection(0);
                spnform.setSelection(0);
                spnpos.setSelection(0);
                spnavan.setSelection(0);
                spnvec.setSelection(0);
            }
        });
    }

    protected void cosa(){
        bbdd.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                juegostocha.clear();
                //ArrayAdapter<String> adaptadorr;
                //ArrayList<String> lista = new ArrayList<String>();
                String busqueda = "Buscando ";

                for (DataSnapshot datasnapshot: dataSnapshot.getChildren()) {
                    dataSnapshot.getValue(Juego.class);
                    Juego juego = datasnapshot.getValue(Juego.class);

                    String titulo = juego.getTitulo();
                    String plataforma = juego.getPlataforma();
                    String poses = juego.getPosesion();
                    String forma = juego.getFisico();
                    String avanc = juego.getAvance();
                    String veces = juego.getVeces();
                    //String juegolst = titulo;

                    //esto antes iba por listview

                    //juegolst = juegolst+" |  "+"  |  "+plataforma+"  |  "+poses+"  |  "+forma+"  |  "+avanc+"  |  "+veces;

                    if (spncons.getSelectedItem().toString().equals("Plataforma")&&spnform.getSelectedItem().toString().equals("Físico")&&spnpos.getSelectedItem().toString().equals("Posesión")&&spnavan.getSelectedItem().toString().equals("Avance")&&spnvec.getSelectedItem().toString().equals("Veces")){
                        //lista.add(juegolst);
                        juegostocha.add(juego);
                        busqueda = "Buscando todos los ";
                    }else{
                        if (plataforma.equals(spncons.getSelectedItem().toString())|| spncons.getSelectedItem().toString().equals("Plataforma")){
                            if (poses.equals(spnpos.getSelectedItem().toString())|| spnpos.getSelectedItem().toString().equals("Posesión")){
                                if (forma.equals(spnform.getSelectedItem().toString())|| spnform.getSelectedItem().toString().equals("Físico")){
                                    if (avanc.equals(spnavan.getSelectedItem().toString())|| spnavan.getSelectedItem().toString().equals("Avance")){
                                        int numveces = Integer.parseInt(veces);

                                        if (spnvec.getSelectedItem().toString().equals("Veces")){
                                            //lista.add(juegolst);
                                            juegostocha.add(juego);
                                        }else{
                                            switch (numveces) {
                                                case 0:
                                                    if (spnvec.getSelectedItem().toString().equals("0")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 1:
                                                    if (spnvec.getSelectedItem().toString().equals("1")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 2:
                                                    if (spnvec.getSelectedItem().toString().equals("2")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 3:
                                                    if (spnvec.getSelectedItem().toString().equals("3-5")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 4:
                                                    if (spnvec.getSelectedItem().toString().equals("3-5")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 5:
                                                    if (spnvec.getSelectedItem().toString().equals("3-5")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                    default:
                                                        if (spnvec.getSelectedItem().toString().equals("+5")){
                                                            //lista.add(juegolst);
                                                            juegostocha.add(juego);
                                                    }
                                                        break;

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }

                rAdapterg.notifyDataSetChanged();

                //adaptadorr = new ArrayAdapter<String>(Lista.this,android.R.layout.simple_list_item_1,lista);
              //  listatocha.setAdapter(adaptadorr);

                if (spncons.getSelectedItem().toString().equals("Plataforma")){
                    busqueda = busqueda + "juegos para cualquier plataforma, ";
                }else{
                    busqueda = busqueda + "juegos para "+spncons.getSelectedItem().toString()+", ";
                }
                if (spnpos.getSelectedItem().toString().equals("Si")){
                    busqueda = busqueda + "en posesión, ";
                }else{
                    if (spnpos.getSelectedItem().toString().equals("No")){
                        busqueda = busqueda + "NO en posesión, ";
                    }
                }

                if (spnform.getSelectedItem().toString().equals("Si")){
                    busqueda = busqueda + "en físico, ";
                }else{
                    if (spnform.getSelectedItem().toString().equals("No")){
                        busqueda = busqueda + "en digital, ";
                    }else{
                        busqueda = busqueda + "en cualquier formato, ";
                    }
                }
                busqueda = busqueda +"con un grado de avance ";
                if (spnavan.getSelectedItem().toString().equals("Avance")){
                    busqueda = busqueda+"cualquiera y pasado ";
                }else{
                    busqueda = busqueda+spnavan.getSelectedItem().toString()+" y pasado ";
                }
                if (spnvec.getSelectedItem().toString().equals("Veces")){
                    busqueda = busqueda+"cuantas veces sea";
                }else{
                    busqueda = busqueda+spnvec.getSelectedItem().toString()+" veces.";
                }

                //Toast toast = Toast.makeText(getApplicationContext(),busqueda,Toast.LENGTH_LONG);
                //toast.show();

                //Ahora es un snackbar lo que se crea con la info. de la búsqueda, y se queda hasta que la cierres

                final Snackbar snackBar = Snackbar.make(findViewById(android.R.id.content), busqueda, Snackbar.LENGTH_INDEFINITE);

                snackBar.setAction("Entendido", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        snackBar.dismiss();
                    }
                });
                snackBar.show();

            } //aqui acaba el on data change

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

```

<p>The Adapter java file:</p>

<pre class="lang-java prettyprint-override"><code>public class Adaptagrande extends RecyclerView.Adapter<Adaptagrande.jHolder>{

    List<Juego> jueguiss;
    private Context micontext;

    public Adaptagrande(Context micontext, List<Juego> jueguiss){
        this.jueguiss = jueguiss;
        this.micontext = micontext;
    }

    @NonNull
    @Override
    public jHolder onCreateViewHolder(ViewGroup grupo, int i){
        View vv = LayoutInflater.from(grupo.getContext()).inflate(R.layout.layout_juegofull, grupo, false);
        jHolder holdeer = new jHolder(vv);

        return holdeer;
    }

    @Override
    public void onBindViewHolder(final jHolder holder, final int pos){
        final Juego j1 = jueguiss.get(pos);
        holder.titxtlist.setText(j1.getTitulo());
        holder.platxtlist.setText(j1.getPlataforma());
        holder.posetxtlist.setText(j1.getPosesion());
        holder.formatxtlist.setText(j1.getFisico());
        holder.avatxtlist.setText(j1.getAvance());
        holder.vectxtlist.setText(j1.getVeces());
    }
    @Override
    public int getItemCount() {
        return jueguiss.size();
    }

    public static class jHolder extends RecyclerView.ViewHolder{

        public TextView titxtlist;
        public TextView platxtlist;
        public TextView posetxtlist;
        public TextView formatxtlist;
        public TextView avatxtlist;
        public TextView vectxtlist;

        public jHolder(View itemViewer){
            super(itemViewer);
            titxtlist=(TextView) itemView.findViewById(R.id.titltxt);
            platxtlist=(TextView) itemView.findViewById(R.id.platxtlist);
            posetxtlist=(TextView) itemView.findViewById(R.id.posetxtlist);
            formatxtlist=(TextView) itemView.findViewById(R.id.formatxtlist);
            avatxtlist=(TextView) itemView.findViewById(R.id.avatxtlist);
            vectxtlist=(TextView) itemView.findViewById(R.id.vectxtlist);

        }
    }
}

</code>```

The XML file for every Recycler object:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#505050"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/titxtlist"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/platxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/posetxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/formatxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/avatxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/vectxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>

</LinearLayout>

```

<p>The XML file for the RecyclerView Activity:</p>

<pre class="lang-xml prettyprint-override"><code>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#919191"
    android:orientation="vertical"
    tools:context=".Lista">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp">

        <Button
            android:id="@+id/btntitlsrc"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Todos" />

        <Spinner
            android:id="@+id/spnplataformal"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnposesionl"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnformatol"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnavancel"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnvecesl"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

    </LinearLayout>

    <!--
    <ListView
        android:id="@+id/lstvwlistgrand"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
          -->
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclergrande"
        />

</LinearLayout>

</code>```

The Logcat says this:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.prueba.Adaptagrande.onBindViewHolder(Adaptagrande.java:37)
        at com.example.prueba.Adaptagrande.onBindViewHolder(Adaptagrande.java:15)
        at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2792)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2319)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
2019-05-31 18:04:00.987 6377-6377/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
</code>```

But i don't see where is the null reference or the error receiving or transforming the data

答:
Probably it is just a typo .. The id for titxtlist is wrong. You are finding textview in your viewholder by using id as

```<code>titxtlist=(TextView) itemView.findViewById(R.id.titltxt);
</code>```

but in your layout file it is

```<code>android:id="@+id/titxtlist"
</code>```

The id is not same in your viewholder

Body:
I'm passing data from a firebase database to a RecyclerView in an Activity through a RecyclerView Adapter.

I can't see any error, but everytime i try to access to this activity the app crashes.

This Activity has also some spinners to make filters to select only some objects from the database; but even i removed this part of the code, it isn't still working.

The RecyclerView Activity:

public class Lista extends AppCompatActivity {

    //ListView listatocha;
    DatabaseReference bbdd;
    Button btnreestablecer;

    RecyclerView rcvg;
    Adaptagrande rAdapterg;
    RecyclerView.LayoutManager layoutManagerg;
    List<Juego> juegostocha;

    Spinner spncons;
    Spinner spnform;
    Spinner spnpos;
    Spinner spnavan;
    Spinner spnvec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lista);
       // listatocha = (ListView) findViewById(R.id.lstvwlistgrand);
        btnreestablecer = (Button) findViewById(R.id.btntitlsrc);
        rcvg = (RecyclerView) findViewById(R.id.recyclergrande);
        rcvg.setLayoutManager(new LinearLayoutManager(getApplicationContext())); //a ver si
        juegostocha = new ArrayList<>();
        rAdapterg = new Adaptagrande(getApplicationContext(),juegostocha);
        rcvg.setAdapter(rAdapterg);

        bbdd = FirebaseDatabase.getInstance().getReference("juegos");

        spncons = (Spinner) findViewById(R.id.spnplataformal);
        spnform = (Spinner) findViewById(R.id.spnformatol);
        spnpos = (Spinner) findViewById(R.id.spnposesionl);
        spnavan = (Spinner) findViewById(R.id.spnavancel);
        spnvec = (Spinner) findViewById(R.id.spnvecesl);

        /*
        spncons.setSelection(0);
        spnform.setSelection(0);
        spnpos.setSelection(0);
        spnavan.setSelection(0);
        spnvec.setSelection(0);
        */

        String[] plataformas = new String[] {"Plataforma","PC", "PS2", "PS3", "PS4", "N64", "Gamecube", "Wii", "WiiU", "NSwitch", "Xbox", "Xbox360", "XboxOne", "PSone", "GameBoy", "GBA", "DS", "3DS", "PSP", "PSVita"}; //2-8 | 2.2 3.8 4.2 5.1 6.1 7.4 8.1
        String[] avance = new String[] {"Avance","Nulo", "Probado", "Intermedio", "Pasado", "Completado", "Irrelevante"}; //4-11 | 4.1 6.1 7.1 10.2 11.1
        String[] veces = new String[] {"Veces","0","1","2","3-5","+5"}; //0-3
        String[] posesion = new String[] {"Posesión","Si","No"};  //siempre igual
        String[] formato = new String[] {"Físico","Si","No"};     //siempre igual

        ArrayAdapter<String> adaptaforms = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, plataformas);
        ArrayAdapter<String> adaptavanc = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, avance);
        ArrayAdapter<String> adaptveces = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, veces);
        ArrayAdapter<String> adaptapose = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, posesion);
        ArrayAdapter<String> adaptaform = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, formato);

        spncons.setAdapter(adaptaforms);
        spnvec.setAdapter(adaptveces);
        spnavan.setAdapter(adaptavanc);
        spnpos.setAdapter(adaptapose);
        spnform.setAdapter(adaptaform);

        spncons.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spnpos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spnform.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spnavan.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spnvec.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cosa();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnreestablecer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spncons.setSelection(0);
                spnform.setSelection(0);
                spnpos.setSelection(0);
                spnavan.setSelection(0);
                spnvec.setSelection(0);
            }
        });
    }

    protected void cosa(){
        bbdd.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                juegostocha.clear();
                //ArrayAdapter<String> adaptadorr;
                //ArrayList<String> lista = new ArrayList<String>();
                String busqueda = "Buscando ";

                for (DataSnapshot datasnapshot: dataSnapshot.getChildren()) {
                    dataSnapshot.getValue(Juego.class);
                    Juego juego = datasnapshot.getValue(Juego.class);

                    String titulo = juego.getTitulo();
                    String plataforma = juego.getPlataforma();
                    String poses = juego.getPosesion();
                    String forma = juego.getFisico();
                    String avanc = juego.getAvance();
                    String veces = juego.getVeces();
                    //String juegolst = titulo;

                    //esto antes iba por listview

                    //juegolst = juegolst+" |  "+"  |  "+plataforma+"  |  "+poses+"  |  "+forma+"  |  "+avanc+"  |  "+veces;

                    if (spncons.getSelectedItem().toString().equals("Plataforma")&&spnform.getSelectedItem().toString().equals("Físico")&&spnpos.getSelectedItem().toString().equals("Posesión")&&spnavan.getSelectedItem().toString().equals("Avance")&&spnvec.getSelectedItem().toString().equals("Veces")){
                        //lista.add(juegolst);
                        juegostocha.add(juego);
                        busqueda = "Buscando todos los ";
                    }else{
                        if (plataforma.equals(spncons.getSelectedItem().toString())|| spncons.getSelectedItem().toString().equals("Plataforma")){
                            if (poses.equals(spnpos.getSelectedItem().toString())|| spnpos.getSelectedItem().toString().equals("Posesión")){
                                if (forma.equals(spnform.getSelectedItem().toString())|| spnform.getSelectedItem().toString().equals("Físico")){
                                    if (avanc.equals(spnavan.getSelectedItem().toString())|| spnavan.getSelectedItem().toString().equals("Avance")){
                                        int numveces = Integer.parseInt(veces);

                                        if (spnvec.getSelectedItem().toString().equals("Veces")){
                                            //lista.add(juegolst);
                                            juegostocha.add(juego);
                                        }else{
                                            switch (numveces) {
                                                case 0:
                                                    if (spnvec.getSelectedItem().toString().equals("0")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 1:
                                                    if (spnvec.getSelectedItem().toString().equals("1")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 2:
                                                    if (spnvec.getSelectedItem().toString().equals("2")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 3:
                                                    if (spnvec.getSelectedItem().toString().equals("3-5")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 4:
                                                    if (spnvec.getSelectedItem().toString().equals("3-5")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                case 5:
                                                    if (spnvec.getSelectedItem().toString().equals("3-5")){
                                                        //lista.add(juegolst);
                                                        juegostocha.add(juego);
                                                    }
                                                    break;
                                                    default:
                                                        if (spnvec.getSelectedItem().toString().equals("+5")){
                                                            //lista.add(juegolst);
                                                            juegostocha.add(juego);
                                                    }
                                                        break;

                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }

                rAdapterg.notifyDataSetChanged();

                //adaptadorr = new ArrayAdapter<String>(Lista.this,android.R.layout.simple_list_item_1,lista);
              //  listatocha.setAdapter(adaptadorr);

                if (spncons.getSelectedItem().toString().equals("Plataforma")){
                    busqueda = busqueda + "juegos para cualquier plataforma, ";
                }else{
                    busqueda = busqueda + "juegos para "+spncons.getSelectedItem().toString()+", ";
                }
                if (spnpos.getSelectedItem().toString().equals("Si")){
                    busqueda = busqueda + "en posesión, ";
                }else{
                    if (spnpos.getSelectedItem().toString().equals("No")){
                        busqueda = busqueda + "NO en posesión, ";
                    }
                }

                if (spnform.getSelectedItem().toString().equals("Si")){
                    busqueda = busqueda + "en físico, ";
                }else{
                    if (spnform.getSelectedItem().toString().equals("No")){
                        busqueda = busqueda + "en digital, ";
                    }else{
                        busqueda = busqueda + "en cualquier formato, ";
                    }
                }
                busqueda = busqueda +"con un grado de avance ";
                if (spnavan.getSelectedItem().toString().equals("Avance")){
                    busqueda = busqueda+"cualquiera y pasado ";
                }else{
                    busqueda = busqueda+spnavan.getSelectedItem().toString()+" y pasado ";
                }
                if (spnvec.getSelectedItem().toString().equals("Veces")){
                    busqueda = busqueda+"cuantas veces sea";
                }else{
                    busqueda = busqueda+spnvec.getSelectedItem().toString()+" veces.";
                }

                //Toast toast = Toast.makeText(getApplicationContext(),busqueda,Toast.LENGTH_LONG);
                //toast.show();

                //Ahora es un snackbar lo que se crea con la info. de la búsqueda, y se queda hasta que la cierres

                final Snackbar snackBar = Snackbar.make(findViewById(android.R.id.content), busqueda, Snackbar.LENGTH_INDEFINITE);

                snackBar.setAction("Entendido", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        snackBar.dismiss();
                    }
                });
                snackBar.show();

            } //aqui acaba el on data change

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

The Adapter java file:

public class Adaptagrande extends RecyclerView.Adapter<Adaptagrande.jHolder>{

    List<Juego> jueguiss;
    private Context micontext;

    public Adaptagrande(Context micontext, List<Juego> jueguiss){
        this.jueguiss = jueguiss;
        this.micontext = micontext;
    }

    @NonNull
    @Override
    public jHolder onCreateViewHolder(ViewGroup grupo, int i){
        View vv = LayoutInflater.from(grupo.getContext()).inflate(R.layout.layout_juegofull, grupo, false);
        jHolder holdeer = new jHolder(vv);

        return holdeer;
    }

    @Override
    public void onBindViewHolder(final jHolder holder, final int pos){
        final Juego j1 = jueguiss.get(pos);
        holder.titxtlist.setText(j1.getTitulo());
        holder.platxtlist.setText(j1.getPlataforma());
        holder.posetxtlist.setText(j1.getPosesion());
        holder.formatxtlist.setText(j1.getFisico());
        holder.avatxtlist.setText(j1.getAvance());
        holder.vectxtlist.setText(j1.getVeces());
    }
    @Override
    public int getItemCount() {
        return jueguiss.size();
    }

    public static class jHolder extends RecyclerView.ViewHolder{

        public TextView titxtlist;
        public TextView platxtlist;
        public TextView posetxtlist;
        public TextView formatxtlist;
        public TextView avatxtlist;
        public TextView vectxtlist;

        public jHolder(View itemViewer){
            super(itemViewer);
            titxtlist=(TextView) itemView.findViewById(R.id.titltxt);
            platxtlist=(TextView) itemView.findViewById(R.id.platxtlist);
            posetxtlist=(TextView) itemView.findViewById(R.id.posetxtlist);
            formatxtlist=(TextView) itemView.findViewById(R.id.formatxtlist);
            avatxtlist=(TextView) itemView.findViewById(R.id.avatxtlist);
            vectxtlist=(TextView) itemView.findViewById(R.id.vectxtlist);

        }
    }
}

The XML file for every Recycler object:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#505050"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/titxtlist"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/platxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/posetxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/formatxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/avatxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />

        <TextView
            android:id="@+id/vectxtlist"
            android:layout_width="50dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>

</LinearLayout>

The XML file for the RecyclerView Activity:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#919191"
    android:orientation="vertical"
    tools:context=".Lista">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:orientation="horizontal"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingBottom="10dp">

        <Button
            android:id="@+id/btntitlsrc"
            android:layout_width="30dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Todos" />

        <Spinner
            android:id="@+id/spnplataformal"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnposesionl"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnformatol"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnavancel"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

        <Spinner
            android:id="@+id/spnvecesl"
            android:layout_width="30dp"
            android:layout_height="40dp"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:background="#B6A9A9" />

    </LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclergrande"
        />

</LinearLayout>

The Logcat says this:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.prueba.Adaptagrande.onBindViewHolder(Adaptagrande.java:37)
        at com.example.prueba.Adaptagrande.onBindViewHolder(Adaptagrande.java:15)
        at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
        at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
        at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
        at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
        at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
        at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
        at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
        at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
        at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:4194)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1565)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:261)
        at com.android.internal.policy.DecorView.onLayout(DecorView.java:753)
        at android.view.View.layout(View.java:20672)
        at android.view.ViewGroup.layout(ViewGroup.java:6194)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2792)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2319)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
2019-05-31 18:04:00.987 6377-6377/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

But i don't see where is the null reference or the error receiving or transforming the data

Body:
Probably it is just a typo .. The id for titxtlist is wrong. You are finding textview in your viewholder by using id as

titxtlist=(TextView) itemView.findViewById(R.id.titltxt);

but in your layout file it is

android:id="@+id/titxtlist"

The id is not same in your viewholder


来源: stackexchange

问:
TensorFlow multivariate linear regression placeholder and matrix multiplication error
I am using the auto-mpg.data. I'm running into this problem:

Traceback (most recent call last):
  File "C:/PythonProjects/test5.py", line 60, in
    _, c = sess.run([optimizer, loss], feed_dict={X: xTrain, Y: yTrain})  # Get loss value
  File "C:\Python3\lib\site-packages\tensorflow\python\client\session.py", line 929, in run
    run_metadata_ptr)
  File "C:\Python3\lib\site-packages\tensorflow\python\client\session.py", line 1128, in _run
    str(subfeed_t.get_shape())))

ValueError: Cannot feed value of shape (352, 1) for Tensor 'Placeholder_1:0', which has shape '(?,)'

I have tried creating separate placeholders for Xtrain,Xtest,Ytrain,Ytest but I believe that is not the right way too.

How do I use the same X and Y placeholder for both test/train data?

```<code>import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

filename = "auto-mpg.data"
column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
df = pd.read_csv(filename, delim_whitespace=True, header=None, na_values = "?", names=column_names)
df = df.drop('name', axis=1)
df = df.dropna()

# Ont-hot encoding for category data
origin = df.pop('origin')
df['USA'] = (origin == 1)*1.0
df['Europe'] = (origin == 2)*1.0
df['Japan'] = (origin == 3)*1.0

df = df.drop(['year'], axis=1)
x_data = df.drop('mpg', axis=1)
y_data = df[['mpg']] # Continuous target variable : mpg

print(df.shape)

# Test/Train split of 90%/10%
xTrain, xTest, yTrain, yTest = train_test_split(x_data, y_data, test_size=0.1, random_state=0)

print(xTrain.shape)  # 352x8
print(xTest.shape)  # 40x8
print(yTrain.shape)  # 352x1
print(yTest.shape)  #40x1

def LinearRegression():
    y_pred = tf.add(tf.matmul(X, W), b)
    loss = tf.reduce_mean(tf.square(y_pred - Y))
    return loss

# Xtrain = tf.placeholder(tf.float32, [352,8])
# Ytrain = tf.placeholder(tf.float32, [352,1])
# Xtest = tf.placeholder(tf.float32, [40,8])
# Ytest = tf.placeholder(tf.float32, [40,1])
numFeatures = xTrain.shape[1]
X = tf.placeholder(tf.float32, [None,numFeatures])
Y = tf.placeholder(tf.float32, [None])

W = tf.get_variable(name='Weight', dtype=tf.float32, shape=([8,1]), initializer=tf.zeros_initializer())
b = tf.get_variable(name='Bias', dtype=tf.float32, shape=([1]), initializer=tf.zeros_initializer())
loss=LinearRegression()
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0000001).minimize(loss)
epochs = 1000
display_step = 100  # Display every 10s output

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    for e in range(epochs):
        _, c = sess.run([optimizer, loss], feed_dict={X: xTrain, Y: yTrain})  # Get loss value
        if (e + 1) % display_step == 0:
            print('Epoch #:', '%d' % (e + 1), 'Loss =', '{:.9f}'.format(c), 'W =', sess.run(W), 'b =', sess.run(b))

    print("Training completed...")

    training_cost = sess.run(loss, feed_dict={X: xTrain, Y: yTrain})
    weight = sess.run(W)
    bias = sess.run(b)
    print("Training cost=", training_cost, '; ' "W =", weight, '; ' "b =", bias)

    print("Testing result...")
    test_loss = LinearRegression()  # Same function as above
    testing_cost = sess.run(test_loss, feed_dict={X: xTest, Y: yTest})
    print("Testing cost:", testing_cost)
    print("Absolute mean square loss difference:", abs(training_cost - testing_cost))

    fitted_prediction = sess.run(W) * xTest + sess.run(b)
    print('fitted_prediction = ',fitted_prediction)
</code>```

答:
It seems like your yTrain is rank 2 ( [352,1] ) but the placeholder you are trying to feed with it is a scalar. Try changing Y to</p>

```<code>Y = tf.placeholder(tf.float32, [None,1])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using the auto-mpg.data. I'm running into this problem:

Traceback (most recent call last):
  File "C:/PythonProjects/test5.py", line 60, in
    _, c = sess.run([optimizer, loss], feed_dict={X: xTrain, Y: yTrain})  # Get loss value
  File "C:\Python3\lib\site-packages\tensorflow\python\client\session.py", line 929, in run
    run_metadata_ptr)
  File "C:\Python3\lib\site-packages\tensorflow\python\client\session.py", line 1128, in _run
    str(subfeed_t.get_shape())))

ValueError: Cannot feed value of shape (352, 1) for Tensor 'Placeholder_1:0', which has shape '(?,)'

I have tried creating separate placeholders for Xtrain,Xtest,Ytrain,Ytest but I believe that is not the right way too.

How do I use the same X and Y placeholder for both test/train data?

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

filename = "auto-mpg.data"
column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
df = pd.read_csv(filename, delim_whitespace=True, header=None, na_values = "?", names=column_names)
df = df.drop('name', axis=1)
df = df.dropna()

# Ont-hot encoding for category data
origin = df.pop('origin')
df['USA'] = (origin == 1)*1.0
df['Europe'] = (origin == 2)*1.0
df['Japan'] = (origin == 3)*1.0

df = df.drop(['year'], axis=1)
x_data = df.drop('mpg', axis=1)
y_data = df[['mpg']] # Continuous target variable : mpg

print(df.shape)

# Test/Train split of 90%/10%
xTrain, xTest, yTrain, yTest = train_test_split(x_data, y_data, test_size=0.1, random_state=0)

print(xTrain.shape)  # 352x8
print(xTest.shape)  # 40x8
print(yTrain.shape)  # 352x1
print(yTest.shape)  #40x1

def LinearRegression():
    y_pred = tf.add(tf.matmul(X, W), b)
    loss = tf.reduce_mean(tf.square(y_pred - Y))
    return loss

# Xtrain = tf.placeholder(tf.float32, [352,8])
# Ytrain = tf.placeholder(tf.float32, [352,1])
# Xtest = tf.placeholder(tf.float32, [40,8])
# Ytest = tf.placeholder(tf.float32, [40,1])
numFeatures = xTrain.shape[1]
X = tf.placeholder(tf.float32, [None,numFeatures])
Y = tf.placeholder(tf.float32, [None])

W = tf.get_variable(name='Weight', dtype=tf.float32, shape=([8,1]), initializer=tf.zeros_initializer())
b = tf.get_variable(name='Bias', dtype=tf.float32, shape=([1]), initializer=tf.zeros_initializer())
loss=LinearRegression()
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0000001).minimize(loss)
epochs = 1000
display_step = 100  # Display every 10s output

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    for e in range(epochs):
        _, c = sess.run([optimizer, loss], feed_dict={X: xTrain, Y: yTrain})  # Get loss value
        if (e + 1) % display_step == 0:
            print('Epoch #:', '%d' % (e + 1), 'Loss =', '{:.9f}'.format(c), 'W =', sess.run(W), 'b =', sess.run(b))

    print("Training completed...")

    training_cost = sess.run(loss, feed_dict={X: xTrain, Y: yTrain})
    weight = sess.run(W)
    bias = sess.run(b)
    print("Training cost=", training_cost, '; ' "W =", weight, '; ' "b =", bias)

    print("Testing result...")
    test_loss = LinearRegression()  # Same function as above
    testing_cost = sess.run(test_loss, feed_dict={X: xTest, Y: yTest})
    print("Testing cost:", testing_cost)
    print("Absolute mean square loss difference:", abs(training_cost - testing_cost))

    fitted_prediction = sess.run(W) * xTest + sess.run(b)
    print('fitted_prediction = ',fitted_prediction)

Body:
It seems like your yTrain is rank 2 ( [352,1] ) but the placeholder you are trying to feed with it is a scalar. Try changing Y to

Y = tf.placeholder(tf.float32, [None,1])


问:
How to initialize array out of the class and set a value to the first element?
Use in Arduino. The problem is there: Player::coords[0] = {0, 0};

Heading file:

#ifndef game_h
#define game_h
#include <Arduino.h>

class Player {
  public:
    int getScore();
    static int coords[3250][2];
    coordinates: x, y

  private:
    static int score;
};

#endif
```

<p>Cpp file:</p>

<pre class="lang-cpp prettyprint-override"><code>#include "game.h"

int Player::score = 1;

int Player::getScore() {
  return this->score;
}

int Player::coords[3250][2];
Player::coords[0] = {0, 0};
</code>```

Compiler writes: 'coords' in 'class Player' does not name a type

答:
You may not do this way at a namespace scope

```<code>int Player::coords[3250][2];
Player::coords[0] = {0, 0};
</code>```

In fact these statements are equivalent to this one

```<code>int Player::coords[3250][2] = { { 0, 0 } };
</code>```

or

```<code>int Player::coords[3250][2] = {};
</code>```

or even just

```<code>int Player::coords[3250][2];
</code>```

because the array has the static storage duration and zero-initialized by the compiler.

Body:
Use in Arduino. The problem is there: Player::coords[0] = {0, 0};

Heading file:

#ifndef game_h
#define game_h
#include <Arduino.h>

class Player {
  public:
    int getScore();
    static int coords[3250][2];
    coordinates: x, y

  private:
    static int score;
};

#endif

Cpp file:

#include "game.h"

int Player::score = 1;

int Player::getScore() {
  return this->score;
}

int Player::coords[3250][2];
Player::coords[0] = {0, 0};

Compiler writes: 'coords' in 'class Player' does not name a type

Body:
You may not do this way at a namespace scope

int Player::coords[3250][2];
Player::coords[0] = {0, 0};

In fact these statements are equivalent to this one

int Player::coords[3250][2] = { { 0, 0 } };

or

int Player::coords[3250][2] = {};

or even just

int Player::coords[3250][2];

because the array has the static storage duration and zero-initialized by the compiler.


问:
Get only string in T-SQL
Given the below strings,

```<code>DECLARE @Text1 = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'
</code>```

I would like to know if there is a way to get the character "#"

答:
This is one option of getting it. It first removes anything all the way through CAR: and then removes all after any digits in the remaining string.

```<code>SELECT SUBSTRING( x.TruncString, 0, PATINDEX( '%[^0-9]%', x.TruncString))
FROM (VALUES('This is the 1st time I found the Car# CAR:8 #NumberIncluded#'),
            ('This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:8 #NumberIncluded##NumberIncluded#')
     )SampleData(String)
CROSS APPLY( SELECT STUFF( String, 1, CHARINDEX( 'CAR:', String)+3, ''))x(TruncString)
</code>```

Title: Get only string in T-SQL

Body:
Given the below strings,

DECLARE @Text1 = 'This is the 1st time I found the Car# CAR:8 #NumberIncluded#'

I would like to know if there is a way to get the character "#"

Body:
This is one option of getting it. It first removes anything all the way through CAR: and then removes all after any digits in the remaining string.

SELECT SUBSTRING( x.TruncString, 0, PATINDEX( '%[^0-9]%', x.TruncString))
FROM (VALUES('This is the 1st time I found the Car# CAR:8 #NumberIncluded#'),
            ('This is the 1st time I found the Car# CAR:8 #NumberIncluded# with no ID tied to it, the prices is 588USD for  CAR:8 #NumberIncluded##NumberIncluded#')
     )SampleData(String)
CROSS APPLY( SELECT STUFF( String, 1, CHARINDEX( 'CAR:', String)+3, ''))x(TruncString)


问:
Java InetAddress to PostgreSQL inet and vice versa
I'd like to use the PSQL inet datatype, but it doesn't accept strings (getRemoteAddr()) or byte[] (InetAddress).

Is there a way to convert it properly using Java?

答:
Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the JavaDoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

~ InetAddress javadoc

If you were asking about getting the string from the IP:

String getHostAddress()
Returns the IP address string in textual presentation.

String getHostName()
Gets the host name for this IP address.

Sorry I couldn't be of more help.


问:
How to recreate a angular 6 reactive form control with using new field object and place it in existing position
I am trying insert a new field and i don't know its the write word to use create a form control for new field and add in the existing form index,
for example if i have 3 input fields rendered at initial response, if i click change button in side of a field it should change to radio button in the same index position of form.

here is the code i have tried, html

```<code><form [formGroup]="registerForm">
<div class="form-group" *ngFor="let item of listData; let i = index">
<div class="inputFeild">
        <label>{{i +' '+ item.label}}</label>
    <input [type]="item.controlType" [formControlName]="item.name">

    </div>
    <div (click)="changeMe(item.name,i)">change me</div>
    <br />
</div>
        <div class="form-group">
                <button type="submit" [disabled]="!registerForm.valid">submit</button>

            </div>
</form>
</code>```

and ts

```<code>  public registerForm: FormGroup;
  listData = [{
     label: "First Name",
     controlType: "text",
     name:"firstName"
    },
    {
      label: "Last Name",
      controlType: "text",
      name:"lastName"
     },
     {
      label: "School Name",
      controlType: "text",
      name:"schoolName"
     },
     {
      label: "College Name",
      controlType: "text",
      name:"collegeName"
     },
    ]

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {

      this.registerForm = this.formBuilder.group({});
      this.listData.forEach(item => {
        // if (field.type === "button") return;
        const control = this.formBuilder.control(
          null,
          Validators.required);
        this.registerForm.addControl(item.name, control);
      });
  }

  changeMe(questionName, groupIndex){
    const changeData = {

      controlType: 'radio',
        name: 'country',
        label: 'Country',
        value: 'in',
        required: true,
        options: [
          { key: 'm', label: 'Male' },
          { key: 'f', label: 'Female' }
        ]

    }

    this.listData[groupIndex].label = "test change";

  }
</code>```

https://stackblitz.com/edit/angular-3xarhi?file=src/app/app.component.ts

答:
You can use the SWITCH structural directive to choose between control types and when you change the data of the array, the view is going to change too.

So, it is not hard to build.

Good luck!

Body:
I am trying insert a new field and i don't know its the write word to use create a form control for new field and add in the existing form index,
for example if i have 3 input fields rendered at initial response, if i click change button in side of a field it should change to radio button in the same index position of form.

here is the code i have tried, html

<form [formGroup]="registerForm">

        {{i +' '+ item.label}}
    <input [type]="item.controlType" [formControlName]="item.name">

change me

                <button type="submit" [disabled]="!registerForm.valid">submit</button>

</form>

and ts

  public registerForm: FormGroup;
  listData = [{
     label: "First Name",
     controlType: "text",
     name:"firstName"
    },
    {
      label: "Last Name",
      controlType: "text",
      name:"lastName"
     },
     {
      label: "School Name",
      controlType: "text",
      name:"schoolName"
     },
     {
      label: "College Name",
      controlType: "text",
      name:"collegeName"
     },
    ]

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {

      this.registerForm = this.formBuilder.group({});
      this.listData.forEach(item => {
        // if (field.type === "button") return;
        const control = this.formBuilder.control(
          null,
          Validators.required);
        this.registerForm.addControl(item.name, control);
      });
  }

  changeMe(questionName, groupIndex){
    const changeData = {

      controlType: 'radio',
        name: 'country',
        label: 'Country',
        value: 'in',
        required: true,
        options: [
          { key: 'm', label: 'Male' },
          { key: 'f', label: 'Female' }
        ]

    }

    this.listData[groupIndex].label = "test change";

  }

https://stackblitz.com/edit/angular-3xarhi?file=src/app/app.component.ts


问:
C# opening file in a solution
I think this question might be trivial for the most of you but somehow I cannot find the answer... so, I have a Visual Studio 2008 Solution foo and a Project bar in this solution. In my bar-Project i've got a Directory called baz, it looks like this:

```<code>foo dir
 |
 +-> bar dir
      |
      +-> baz dir
           |
           +-> asd file
</code>```

now I want to open my "asd file" in bar-project but need the exact path to "asd file", how can I find it? I tried simply "baz\asd" but it doesn't work.

Thanks!

J

答:
It might be better to add a simple Target into the Build file (Project file - csproj for C#). Open csproj file in text mode and add:

  <Target Name="AfterBuild">
    <Copy SourceFiles="<SourceFileLocationRelativeToPrjFile>\<SourceFilename>" DestinationFiles="<SourceFilename>" />

  </Target>

MS Build will take care of copying your file to the right place - that is right folder no matter what your Configuration (Debug/Release) is.

If you are interested in Publishing as well, you will need to go an extra mile, but I guess, you are not asking for that now - so, will keep it simple.

OwnerDisplayName: Jay

ContentLicense: CC BY-SA 2.5

Title: C# opening file in a solution

Body:
I think this question might be trivial for the most of you but somehow I cannot find the answer... so, I have a Visual Studio 2008 Solution foo and a Project bar in this solution. In my bar-Project i've got a Directory called baz, it looks like this:

foo dir
 |
 +-> bar dir
      |
      +-> baz dir
           |
           +-> asd file

now I want to open my "asd file" in bar-project but need the exact path to "asd file", how can I find it? I tried simply "baz\asd" but it doesn't work.

Thanks!

J

ContentLicense: CC BY-SA 3.0


问:
Post to Array of Objects
How do i post my data properly here.

I keep getting an error, i cannot successfully insert the data into user.SavedMachines.Id and user.SavedMachines.Date.

I also tried user.SavedMachines.Id = req.body.SavedMachinesId and user.Savedmachines.Date = Date.now() but i still get errors.

Would anyone know how to successfully insert the data? thank you

```<code>//My Route:
router.route('/')
  .post((req, res) => {
    let user = new User();
    user.FirstName = req.body.FirstName;
    user.LastName = req.body.LastName;
    user.Email = req.body.Email;
    user.UserName = req.body.UserName;
    user.Password = req.body.Password;
    user.AdminRole = req.body.AdminRole;
    user.SavedMachines.Id.push(req.body.SavedMachinesId);
    user.SavedMachines.Date.push(Date.now());
    user.DateCreated = Date.now();
    user.LastUpdated = Date.now();

    user.save((err) => {user
      if (err) {
        res.send(err);
      } else {
        res.json({ message: 'User successfully added!'});
      }
    });
  })

// My Model Schema:
const UserSchema = new mongoose.Schema({
    FirstName: {
        type: String,
        default: ''
    },
    LastName: {
        type: String,
        default: ''
    },
    Email: {
        type: String,
        default: ''
    },
    UserName: {
        type: String,
        required: true,
        unique: true
    },
    Password: {
        type: String,
        required: true,
        bcrypt: true
    },
    AdminRole: {
        type: Boolean,
        default: false
    },
    SavedMachines: [{
        Id: {
            type: String,
            default: ''
        },
        Date: {
            type: Date,
            default: ''
        }
    }],
    DateCreated: {
        type: Date,
        default: ''
    },
    LastUpdated: {
        type: Date,
        default: Date.now
    }
});
</code>```

答:
i figured it out</p>

```<code>user.SavedMachines.push({Id: req.body.SavedMachinesId, Date: Date.now()});
</code>```

Title: Post to Array of Objects

Body:
How do i post my data properly here.

I keep getting an error, i cannot successfully insert the data into user.SavedMachines.Id and user.SavedMachines.Date.

I also tried user.SavedMachines.Id = req.body.SavedMachinesId and user.Savedmachines.Date = Date.now() but i still get errors.

Would anyone know how to successfully insert the data? thank you

//My Route:
router.route('/')
  .post((req, res) => {
    let user = new User();
    user.FirstName = req.body.FirstName;
    user.LastName = req.body.LastName;
    user.Email = req.body.Email;
    user.UserName = req.body.UserName;
    user.Password = req.body.Password;
    user.AdminRole = req.body.AdminRole;
    user.SavedMachines.Id.push(req.body.SavedMachinesId);
    user.SavedMachines.Date.push(Date.now());
    user.DateCreated = Date.now();
    user.LastUpdated = Date.now();

    user.save((err) => {user
      if (err) {
        res.send(err);
      } else {
        res.json({ message: 'User successfully added!'});
      }
    });
  })

// My Model Schema:
const UserSchema = new mongoose.Schema({
    FirstName: {
        type: String,
        default: ''
    },
    LastName: {
        type: String,
        default: ''
    },
    Email: {
        type: String,
        default: ''
    },
    UserName: {
        type: String,
        required: true,
        unique: true
    },
    Password: {
        type: String,
        required: true,
        bcrypt: true
    },
    AdminRole: {
        type: Boolean,
        default: false
    },
    SavedMachines: [{
        Id: {
            type: String,
            default: ''
        },
        Date: {
            type: Date,
            default: ''
        }
    }],
    DateCreated: {
        type: Date,
        default: ''
    },
    LastUpdated: {
        type: Date,
        default: Date.now
    }
});

Body:
i figured it out

user.SavedMachines.push({Id: req.body.SavedMachinesId, Date: Date.now()});


问:
Component will not wait for API response before rendering
I have tried conditional rendering with a flag set after the API call and also using componentDidMount but cannot get this component to wait for an API response before rendering. I know the API response is valid because it is logging ok in the console. I'm new to react, could you tell me what I'm doing wrong? I have looked at the similar questions on Stackoverflow and can't find a fix. Many thanks!

I have cut some methods out of the code snippet to make it more readable.

```<code>import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react';

import {
  SAMPLE_SERVER_BASE_URL,
} from './config';

export default class CallPane extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: null,
      connection: 'Connecting',
      publishVideo: true,
      apiKey: '',
      sessionId: '',
      token: '',
      isLoaded: false,
    };

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        console.log(data)
        this.setState({ apiKey: data.apiKey })
        console.log(data.apiKey)
        this.setState({ sessionId: data.sessionId })
        console.log(data.sessionId)
        this.setState({ token: data.token })
        console.log(data.token)
        this.setState({ isLoaded: true })
      })
      .catch((err) => {
        console.error('Failed to get session credentials', err);
        alert('Failed to get opentok sessionId and token. Make sure you have updated the config.js file.');
      });
  }

  render() {

    const { error, connection, publishVideo } = this.state;
    // const { apiKey, sessionId, token } = this.state;

    return (
      // (isLoaded)
      <div>
        <div id="sessionStatus">Session Status: {connection}</div>
        {error ? (
          <div className="error">
            <strong>Error:</strong> {error}
          </div>
        ) : null}
        <OTSession
          apiKey={this.apiKey}
          sessionId={this.sessionId}
          token={this.token}
          onError={this.onSessionError}
          eventHandlers={this.sessionEventHandlers}
        >
          <button id="videoButton" onClick={this.toggleVideo}>
            {publishVideo ? 'Disable' : 'Enable'} Video
          </button>
          <OTPublisher
            properties={{ publishVideo, width: 250, height: 250, }}
            onPublish={this.onPublish}
            onError={this.onPublishError}
            eventHandlers={this.publisherEventHandlers}
          />
          <OTStreams>
            <OTSubscriber
              properties={{ width: 300, height: 300 }}
              onSubscribe={this.onSubscribe}
              onError={this.onSubscribeError}
              eventHandlers={this.subscriberEventHandlers}
            />
          </OTStreams>
        </OTSession>
      </div>
    );
  }
}
</code>```

答:
you can put if statement inside your render method:</p>

```<code>render() {

    const { error, connection, publishVideo, isLoaded } = this.state;
    // const { apiKey, sessionId, token } = this.state;

    if(!isLoaded) {
      // not loaded
      return (
        <div>Loading...</div>
      )
    }

    return (
      // (isLoaded)
      // your code
    );
  }
</code>```

Body:
I have tried conditional rendering with a flag set after the API call and also using componentDidMount but cannot get this component to wait for an API response before rendering. I know the API response is valid because it is logging ok in the console. I'm new to react, could you tell me what I'm doing wrong? I have looked at the similar questions on Stackoverflow and can't find a fix. Many thanks!

I have cut some methods out of the code snippet to make it more readable.

import { OTSession, OTPublisher, OTStreams, OTSubscriber } from 'opentok-react';

import {
  SAMPLE_SERVER_BASE_URL,
} from './config';

export default class CallPane extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: null,
      connection: 'Connecting',
      publishVideo: true,
      apiKey: '',
      sessionId: '',
      token: '',
      isLoaded: false,
    };

  componentDidMount() {
    fetch(SAMPLE_SERVER_BASE_URL + '/session')
      .then(data => data.json())
      .then(data => {
        console.log(data)
        this.setState({ apiKey: data.apiKey })
        console.log(data.apiKey)
        this.setState({ sessionId: data.sessionId })
        console.log(data.sessionId)
        this.setState({ token: data.token })
        console.log(data.token)
        this.setState({ isLoaded: true })
      })
      .catch((err) => {
        console.error('Failed to get session credentials', err);
        alert('Failed to get opentok sessionId and token. Make sure you have updated the config.js file.');
      });
  }

  render() {

    const { error, connection, publishVideo } = this.state;
    // const { apiKey, sessionId, token } = this.state;

    return (
      // (isLoaded)

Session Status: {connection}

        {error ? (

            Error: {error}

        ) : null}
        <OTSession
          apiKey={this.apiKey}
          sessionId={this.sessionId}
          token={this.token}
          onError={this.onSessionError}
          eventHandlers={this.sessionEventHandlers}
        >
          <button id="videoButton" onClick={this.toggleVideo}>
            {publishVideo ? 'Disable' : 'Enable'} Video
          </button>
          <OTPublisher
            properties={{ publishVideo, width: 250, height: 250, }}
            onPublish={this.onPublish}
            onError={this.onPublishError}
            eventHandlers={this.publisherEventHandlers}
          />
          <OTStreams>
            <OTSubscriber
              properties={{ width: 300, height: 300 }}
              onSubscribe={this.onSubscribe}
              onError={this.onSubscribeError}
              eventHandlers={this.subscriberEventHandlers}
            />
          </OTStreams>
        </OTSession>

    );
  }
}

Body:
you can put if statement inside your render method:

render() {

    const { error, connection, publishVideo, isLoaded } = this.state;
    // const { apiKey, sessionId, token } = this.state;

    if(!isLoaded) {
      // not loaded
      return (
        <div>Loading...</div>
      )
    }

    return (
      // (isLoaded)
      // your code
    );
  }


问:
Need to remove duplicate columns from a dataframe in pyspark
I have a dataframe with 432 columns and has 24 duplicate columns.

df_tickets-->This has 432 columns

duplicatecols--> This has the cols from df_tickets which are duplicate.

I want to remove the cols in df_tickets which are duplicate. So df_tickets should only have 432-24=408 columns.

I have tried this with the below code but its throwing error.

```<code>df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()
</code>```

The error is

```<code>An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........
</code>```

Can someone help me on this?

答:
try this:

```<code>select_list = list(set(df_tickets.columns)-set(duplicatecols))
df_tickets.select(select_list).show()
</code>```

let me know if this works for you or not.

Body:
I have a dataframe with 432 columns and has 24 duplicate columns.

df_tickets-->This has 432 columns

duplicatecols--> This has the cols from df_tickets which are duplicate.

I want to remove the cols in df_tickets which are duplicate. So df_tickets should only have 432-24=408 columns.

I have tried this with the below code but its throwing error.

df_tickets.select([c for c in df_tickets.columns if c not in duplicatecols]).show()

The error is

An error occurred while calling o1657.showString.
: org.apache.spark.sql.catalyst.errors.package$TreeNodeException: execute, tree:
HashAggregate(keys=[ms_bvoip_order_extension_id#953, ms_order_id#954...........

Can someone help me on this?

Body:
try this:

select_list = list(set(df_tickets.columns)-set(duplicatecols))
df_tickets.select(select_list).show()

let me know if this works for you or not.


问:
Reference all commits between master branch-tip and HEAD in git
I currently am branched out of master (call it branchA). I have made a couple of commits to branchA and would now like to squash commits together on my branch prior to merging to master. Usually I do something like this in my branchA repo:

```<code>git rebase -i HEAD~n
</code>```

I would get n by doing a git log and manually counting the commits from (not including) the master branch tip until (and including) the branch's HEAD. For now the count has been easy as the commits are few.

Is there a simple way to reference all commits on current branch after master branch-tip commit?

答:
You could try:

```<code>git rebase -i $( git merge-base master HEAD )
</code>```

You are fiding the point where master and your current branch diverged (or at least, one of the latest common ancestors) and using it as the parameter for rebase. That might work.

If what you want to know is how many revisions there are on your branch:

```<code>git log --pretty=%h $( git merge-base master HEAD ) | wc -l
</code>```

As a side note, you could just as easily squash without doing rebase:

```<code>git reset --soft $( git merge-base master HEAD )
git commit -m "Squashed feature"
</code>```

IMHO warning: I don't see why people would rather go to an editor, edit God knows how many lines when a couple of commands would do the trick. But.... anyway.

Body:
I currently am branched out of master (call it branchA). I have made a couple of commits to branchA and would now like to squash commits together on my branch prior to merging to master. Usually I do something like this in my branchA repo:

git rebase -i HEAD~n

I would get n by doing a git log and manually counting the commits from (not including) the master branch tip until (and including) the branch's HEAD. For now the count has been easy as the commits are few.

Is there a simple way to reference all commits on current branch after master branch-tip commit?

Body:
You could try:

git rebase -i $( git merge-base master HEAD )

You are fiding the point where master and your current branch diverged (or at least, one of the latest common ancestors) and using it as the parameter for rebase. That might work.

If what you want to know is how many revisions there are on your branch:

git log --pretty=%h $( git merge-base master HEAD ) | wc -l

As a side note, you could just as easily squash without doing rebase:

git reset --soft $( git merge-base master HEAD )
git commit -m "Squashed feature"

IMHO warning: I don't see why people would rather go to an editor, edit God knows how many lines when a couple of commands would do the trick. But.... anyway.


问:
R Using ggplot with a list of dataframes
I have a list of dataframes (df_list) which I want to plot with ggplot. I want to display the Date on the x-scale (its always the same of course) and then 2 different geo_lines. The first geoline out of the df1-3 and the 2nd line from abc. Here is an examle code:

```<code>library(lubridate)
v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,7, length = 10)
v4 = seq(-6,3, length = 10)
df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(3,21, length = 10)
v3 = seq(-3,8, length = 10)
v4 = seq(-7,4, length = 10)
df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(4,22, length = 10)
v3 = seq(-4,9, length = 10)
v4 = seq(-8,5, length = 10)
df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,8, length = 10)
v4 = seq(-6,3, length = 10)
abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

df_list = list(df1, df2, df3, abc)
names(df_list) = c("df1", "df2", "df3", "abc")
</code>```

For example I want to plot df_list$df1$df1_Tmax together with df_list$abc$ABC_Tmax.

I tried this:

```<code>ggplot(data = df_list, aes(x = df1$Date)) +
  geom_line(aes(y = df1$df1_Tmax), color = "darkgreen", size = 1) +
  geom_line(aes(y = abc$ABC_Tmax), color = "grey27", size = 1) +
  labs(title="Title",
       subtitle="subtitle",
       x = "day",
       y = "T") +
  scale_x_date(date_labels="%d",date_breaks  ="1 day")
</code>```

But I get this error message:

```<code>Error: `data` must be a data frame, or other object coercible by `fortify()`, not a list
</code>```

Any ideas how to solve this problem?

答:
You can try this.

```<code>library(ggplot2)
ggplot(data = cbind(df_list$df1, df_list$abc), aes(x = Date)) +
  geom_line(aes(y = df1_Tmax), color = "darkgreen", size = 1) +
  geom_line(aes(y = ABC_Tmax), color = "grey27", size = 1) +
  labs(title="Title",
       subtitle="subtitle",
       x = "day",
       y = "T") +
  scale_x_date(date_labels="%d",date_breaks  ="1 day")
</code>```

Just generate a new data frame using cbind, i.e., cbind(df_list$df1, df_list$abc) within ggplot function.

Caution:
cbind(df_list$df1, df_list$abc) leads to the following error.

Error: data must be uniquely named but has duplicate columns

Please try this since you also have the same Date variable in these two data frames.

Body:
I have a list of dataframes (df_list) which I want to plot with ggplot. I want to display the Date on the x-scale (its always the same of course) and then 2 different geo_lines. The first geoline out of the df1-3 and the 2nd line from abc. Here is an examle code:

library(lubridate)
v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,7, length = 10)
v4 = seq(-6,3, length = 10)
df1 = data.frame(Date = v1, df1_Tmax = v2, df1_Tmean = v3, df1_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(3,21, length = 10)
v3 = seq(-3,8, length = 10)
v4 = seq(-7,4, length = 10)
df2 = data.frame(Date = v1, df2_Tmax = v2, df2_Tmean = v3, df2_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(4,22, length = 10)
v3 = seq(-4,9, length = 10)
v4 = seq(-8,5, length = 10)
df3 = data.frame(Date = v1, df3_Tmax = v2, df3_Tmean = v3, df3_Tmin = v4)

v1 = seq(ymd('2000-05-01'),ymd('2000-05-10'),by='day')
v2 = seq(2,20, length = 10)
v3 = seq(-2,8, length = 10)
v4 = seq(-6,3, length = 10)
abc = data.frame(Date = v1, ABC_Tmax = v2, ABC_Tmean = v3, ABC_Tmin = v4)

df_list = list(df1, df2, df3, abc)
names(df_list) = c("df1", "df2", "df3", "abc")

For example I want to plot df_list$df1$df1_Tmax together with df_list$abc$ABC_Tmax.

I tried this:

ggplot(data = df_list, aes(x = df1$Date)) +
  geom_line(aes(y = df1$df1_Tmax), color = "darkgreen", size = 1) +
  geom_line(aes(y = abc$ABC_Tmax), color = "grey27", size = 1) +
  labs(title="Title",
       subtitle="subtitle",
       x = "day",
       y = "T") +
  scale_x_date(date_labels="%d",date_breaks  ="1 day")

But I get this error message:

Error: `data` must be a data frame, or other object coercible by `fortify()`, not a list

Any ideas how to solve this problem?

Body:
You can try this.

library(ggplot2)
ggplot(data = cbind(df_list$df1, df_list$abc), aes(x = Date)) +
  geom_line(aes(y = df1_Tmax), color = "darkgreen", size = 1) +
  geom_line(aes(y = ABC_Tmax), color = "grey27", size = 1) +
  labs(title="Title",
       subtitle="subtitle",
       x = "day",
       y = "T") +
  scale_x_date(date_labels="%d",date_breaks  ="1 day")

Just generate a new data frame using cbind, i.e., cbind(df_list$df1, df_list$abc) within ggplot function.

Caution:
cbind(df_list$df1, df_list$abc) leads to the following error.

Error: data must be uniquely named but has duplicate columns

Please try this since you also have the same Date variable in these two data frames.


问:
Wordpress host IP changed
I've got a Wordpress site on our home intranet that has run into trouble now that the IP address has changed - The index page loads, but not the CSS and I can't log in to the site administration panel.

Unfortunately I am a bit behind on backups. Is there a way to get Wordpress to refer to the new IP address?

答:
To temporarily be able to login, use this code in your wp-config.php:

```<code>define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
</code>```

or you can add this to your theme's functions.php:

```<code>update_option('siteurl','http://example.com/');
update_option('home','http://example.com/');
</code>```

Warning: Updating the SQL database will be required in order for installed plugins to use the new URL/hostname. So if you use plugins modifying the database is required.

OwnerDisplayName: Andrew

Title: Wordpress host IP changed

Body:
To temporarily be able to login, use this code in your wp-config.php:

define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');

or you can add this to your theme's functions.php:

update_option('siteurl','http://example.com/');
update_option('home','http://example.com/');

Warning: Updating the SQL database will be required in order for installed plugins to use the new URL/hostname. So if you use plugins modifying the database is required.


问:
How to connect to Azure AD MSI extension inside from a windows container
I am running a web API inside windows container on a VM, Its need to communicate to Azure Key-Vault through Azure AD MSI Extension ( which already installed on VM where Container has been created )

I tied various ways to access it through

http://HOST_MACHINE IP:50432/oauth2/token

http://DEFAULT GATEWay IP:50432/oauth2/token

http://localhost:50432/oauth2/token
etc..

But I am always getting the error " Unable to connect to the remote server
"

So Is it possible to get MSI extension access from a container and what I need to do if I want to communicate on port 50432 of the host system from a container?

答: The Azure AD MSI Extension is now end of life, information on the deprecation is here: https://azure.microsoft.com/en-us/blog/azure-ad-managed-service-identity-updates/. Tokens should now be retrieved through the Instance Metadata Service (IMDS) endpoint at http://169.254.169.254/metadata/identity/oauth2/token from within the VM.</p>


问:
Trouble adding WMS Source to Mapbox style.json
I am trying to customize a style.json to add a WMS for mapbox using the docs:

https://docs.mapbox.com/mapbox-gl-js/style-spec/

Specifically this part:

By providing a url to a WMS server that supports EPSG:3857 (or EPSG:900913) as a source of tiled data. The server url should contain a "{bbox-epsg-3857}"replacement token to supply the bbox parameter.

```<code>"wms-imagery": {
    "type": "raster",
    "tiles": [
    'http://a.example.com/wms?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&width=256&height=256&layers=example'
    ],
    "tileSize": 256
}
</code>```

I've tried various iterations of code but I can't seem to figure it out. I think I've got the right structure. I am not new to coding (python) but I am new to using this tool, so I am sure it's something simple.

Here is the Sources section of the json that is causing the error:

```<code>    "sources": {
        "composite": {
            "url": "mapbox://mapbox.mapbox-streets-v8,mapbox.mapbox-terrain-v2,<hiddenmapboxid>",
            "type": "vector"
        },
        "fires_viirs_24": {
            "type": "raster",
            "tiles":[
            "https://firms.modaps.eosdis.nasa.gov/wms/?REQUEST=GetMap&layers=fires_viirs_24&WIDTH=512&HEIGHT=512&BBOX={bbox-espg-3857}&SRS=EPSG:3857&MAP_KEY=<hiddenAPIKey>"
            ],
            "tileSize": 512
            }
           }
</code>```

this causes "style must include source url" error. But as far as I can see it's formatted exactly like the docs says it should be.

I've tried surrounding the "tiles" url like '' which throws an "unexpected token" error. Then tried "" and got "style must include source url". Also tried using the "url" instead of the "tiles" and got "invalid url".

Thanks for any help!

答:
There is an example on mapbox.com that adds a WMS as a layer during runtime which might work for your use case.

If not, it might at least help you figure out how to structure your query

Body:
I am trying to customize a style.json to add a WMS for mapbox using the docs:

https://docs.mapbox.com/mapbox-gl-js/style-spec/

Specifically this part:

By providing a url to a WMS server that supports EPSG:3857 (or EPSG:900913) as a source of tiled data. The server url should contain a "{bbox-epsg-3857}"replacement token to supply the bbox parameter.

"wms-imagery": {
    "type": "raster",
    "tiles": [
    'http://a.example.com/wms?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&width=256&height=256&layers=example'
    ],
    "tileSize": 256
}

I've tried various iterations of code but I can't seem to figure it out. I think I've got the right structure. I am not new to coding (python) but I am new to using this tool, so I am sure it's something simple.

Here is the Sources section of the json that is causing the error:

    "sources": {
        "composite": {
            "url": "mapbox://mapbox.mapbox-streets-v8,mapbox.mapbox-terrain-v2,<hiddenmapboxid>",
            "type": "vector"
        },
        "fires_viirs_24": {
            "type": "raster",
            "tiles":[
            "https://firms.modaps.eosdis.nasa.gov/wms/?REQUEST=GetMap&layers=fires_viirs_24&WIDTH=512&HEIGHT=512&BBOX={bbox-espg-3857}&SRS=EPSG:3857&MAP_KEY=<hiddenAPIKey>"
            ],
            "tileSize": 512
            }
           }

this causes "style must include source url" error. But as far as I can see it's formatted exactly like the docs says it should be.

I've tried surrounding the "tiles" url like '' which throws an "unexpected token" error. Then tried "" and got "style must include source url". Also tried using the "url" instead of the "tiles" and got "invalid url".

Thanks for any help!


问:
how to set pointer back to original state after moving it?
i have this code

```<code>for(int i =0;i<file_num;i++) {
    int rc =in_file(file_name[i],argv,1,argc);
    if (rc ==0)
    *eligible_file++ =file_name[i];
}
</code>```

so after each iteration,eligible_file is pushed up by 1.Is there any fast way that can return the pointer(after the for_loop) to its original state(before the for_loop), without having to put the loop inside a function?

答:
```<code><type> * tmp = eligible_file;
for(int i =0;i<file_num;i++){
    int rc =in_file(file_name[i],argv,1,argc);
    if (rc ==0)
    *eligible_file++ =file_name[i];
}
eligible_file = tmp;
</code>```

But I would recommend this instead:

```<code><type> * tmp = eligible_file;
for(int i = 0, i<file_num;i++){
    int rc =in_file(file_name[i],argv,1,argc);
    if (rc ==0)
    *tmp++ =file_name[i];
}
</code>```

Body:
i have this code

for(int i =0;i<file_num;i++) {
    int rc =in_file(file_name[i],argv,1,argc);
    if (rc ==0)
    *eligible_file++ =file_name[i];
}

so after each iteration,eligible_file is pushed up by 1.Is there any fast way that can return the pointer(after the for_loop) to its original state(before the for_loop), without having to put the loop inside a function?

Body:
<type> * tmp = eligible_file;
for(int i =0;i<file_num;i++){
    int rc =in_file(file_name[i],argv,1,argc);
    if (rc ==0)
    *eligible_file++ =file_name[i];
}
eligible_file = tmp;

But I would recommend this instead:

<type> * tmp = eligible_file;
for(int i = 0, i<file_num;i++){
    int rc =in_file(file_name[i],argv,1,argc);
    if (rc ==0)
    *tmp++ =file_name[i];
}


问:
How to use variable range in Google Sheets?
Currently I have such formula:
COUNTIFS(B3:B36,"16",E3:E36,"01")

Would it be possible to turn these ranges B3:B36 and E3:E36 into variables, like B'start_cell_value':B'stop_cell_value'.

The whole thing would look like:

```<code> =COUNTIFS(B'start_cell_value':B'stop_cell_value',"16",E'start_cell_value':E'stop_cell_value',"01")
</code>```

start_cell_value and stop_cell_value are just some numbers stored in a separate cell. This would help, since changing numbers in those cells only would also change everything in the formula and that's exactly what I want.

I have tried to combine a numeric value from other cells with a letter to make a valid cell name but it doesn't seem to work or it just throws a reference error.

Any ideas would be appreciated.

答:
with Named Ranges you can have it even exact:

```<code>=COUNTIFS(INDIRECT("B"&start_cell_value&":B"&stop_cell_value), "16",
          INDIRECT("E"&start_cell_value&":E"&stop_cell_value), "01")
</code>```

```<code>=COUNTIFS(INDIRECT("B"&A1&":B"&A2), "16",
          INDIRECT("E"&A1&":E"&A2), "01")
</code>```

Body:
Currently I have such formula:
COUNTIFS(B3:B36,"16",E3:E36,"01")

Would it be possible to turn these ranges B3:B36 and E3:E36 into variables, like B'start_cell_value':B'stop_cell_value'.

The whole thing would look like:

 =COUNTIFS(B'start_cell_value':B'stop_cell_value',"16",E'start_cell_value':E'stop_cell_value',"01")

start_cell_value and stop_cell_value are just some numbers stored in a separate cell. This would help, since changing numbers in those cells only would also change everything in the formula and that's exactly what I want.

I have tried to combine a numeric value from other cells with a letter to make a valid cell name but it doesn't seem to work or it just throws a reference error.

Any ideas would be appreciated.

Body:
with Named Ranges you can have it even exact:

=COUNTIFS(INDIRECT("B"&start_cell_value&":B"&stop_cell_value), "16",
          INDIRECT("E"&start_cell_value&":E"&stop_cell_value), "01")

=COUNTIFS(INDIRECT("B"&A1&":B"&A2), "16",
          INDIRECT("E"&A1&":E"&A2), "01")