问:
Using multiple viewholders for several laytous
I'm an average programmer, and I'm trying to finalize a project, but I crashed again on an issue that is making me sleepy.
The point is that i am trying to use several layouts in a recycleview, taking the data from firebase, in this case i will use several viewholders, but i did several tests with content that i searched, but some errors occur and i couldn't solve it. Can someone help me?
I'll put all the code here, point out the errors, and if there is a simpler way to do this, you can talk.
In the future I will reuse the code for another part of the application with more than 10 views.

Firebase.

Main.class

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral;
import com.example.visualizarautomoveis.Models.ModelBicicleta;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.Models.ModelMoto;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {

    private final String ested = "GE";
    private final String city = "Geoneion";

    DatabaseReference automoveis_banco;

    FirebaseDatabase database;

    ArrayList<ModelCompleto> list;

    private Context context;

    private RecyclerView recyclerView;

    RecyclerView.LayoutManager manager;
    AdaptadorGeral adaptadorGeral;

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

        recyclerView = findViewById(R.id.recyclerview);

        list = new ArrayList<ModelCompleto>();

        manager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager);

        automoveis_banco = FirebaseDatabase.getInstance().getReference().child(estet).child(cidy).child("Automoveis");

        automoveis_banco.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot eventSnapshot: dataSnapshot.getChildren())
                {
                    ModelCompleto mod =eventSnapshot.getValue(ModelCompleto.class);
                    list.add(mod);

                    Collections.reverse(list);
                }
                adaptadorGeral = new AdaptadorGeral(MainActivity.this,list);
                recyclerView.setAdapter(adaptadorGeral);
                adaptadorGeral.notifyDataSetChanged();

            }

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

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

AdaptadorGeral.class

```<code>package com.example.visualizarautomoveis.Adapatadores;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.R;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;

import java.util.ArrayList;

public class AdaptadorGeral extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private final ArrayList<ModelCompleto> completos;

    private final String BICICLETA = "0";
    private final String MOTO = "1";

    public AdaptadorGeral(Context context, ArrayList<ModelCompleto> completos)
    {
        this.context = context;
        this.completos = completos;

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        switch (completos.get(viewType).getTipo()){
            case "0":
                return new ViewHolderBicicletas(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_bicicletas,parent,false));

            case "1":
                return new ViewHolderMotos(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_motocicletas, parent, false));

            default:
                break;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        switch (completos.get(position).getTipo()){

            case "0":
                RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderBicicletas viewHolderBicicletas = (ViewHolderBicicletas) holder;

                ((ViewHolderBicicletas) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderBicicletas) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderBicicletas) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderBicicletas) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderBicicletas) holder).textViewValor.setText("R$ "+completos.get(position).getValor());
                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);
            case "1":
                RequestOptions requestOptions2 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderMotos viewHolderMotos = (ViewHolderMotos)holder;

                ((ViewHolderMotos) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderMotos) holder).textViewModelo.setText(completos.get(position).getModelo());
                ((ViewHolderMotos) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderMotos) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderMotos) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderMotos) holder).textViewValor.setText("R$ "+completos.get(position).getValor());

                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions2).into(((ViewHolderMotos) holder).imageViewFoto);

        }
    }

    @Override
    public int getItemCount() {

        if (completos != null){
            return this.completos.size();
        }else {
            return 0;
        }
    }

    @Override
    public int getItemViewType(int position) {

        if (completos.get(position).getTipo().equals("0"))
            return 0;
        if (completos.get(position).getTipo().equals("1")) {
            return 1;
        }
        return position;
    }
}
</code>```

ViewHolderBicicletas.class

```<code>package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderBicicletas extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

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

        textViewAno = itemView.findViewById(R.id.popup_ano_bicicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_bicicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_bicicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_pubicacao_bicicleta);
        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_bicicletas);
        textViewValor = itemView.findViewById(R.id.popup_valor_bicicleta);
    }
}
</code>```

ViewHolderMotos.class

```<code>package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderMotos extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewModelo;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

    public ViewHolderMotos(@NonNull View itemView) {
        super(itemView);
        textViewAno = itemView.findViewById(R.id.popup_ano_motocicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_motocicleta);
        textViewModelo = itemView.findViewById(R.id.popup_modelo_motocicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_motocicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_public_moto);
        textViewValor = itemView.findViewById(R.id.popup_valor_motocicleta);

        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_motocicletas);

    }
}
</code>```

ModelCompleto.class

```<code>package com.example.visualizarautomoveis.Models;

public class ModelCompleto {
    private String valor,descricao,datapubicacao,foto1,marca,ano,modelo,tipo;

    public ModelCompleto() {
    }

    public ModelCompleto(String valor, String descricao, String datapubicacao, String foto1, String marca, String ano, String modelo, String tipo) {
        this.valor = valor;
        this.descricao = descricao;
        this.datapubicacao = datapubicacao;
        this.foto1 = foto1;
        this.marca = marca;
        this.ano = ano;
        this.modelo = modelo;
        this.tipo = tipo;
    }

    public String getValor() {
        return valor;
    }

    public void setValor(String valor) {
        this.valor = valor;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getDatapubicacao() {
        return datapubicacao;
    }

    public void setDatapubicacao(String datapubicacao) {
        this.datapubicacao = datapubicacao;
    }

    public String getFoto1() {
        return foto1;
    }

    public void setFoto1(String foto1) {
        this.foto1 = foto1;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getAno() {
        return ano;
    }

    public void setAno(String ano) {
        this.ano = ano;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public String getTipo() {
        return tipo;
    }

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

Error that appears when running the program:

```<code>D/TextView: setTypeface with style : 0
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.visualizarautomoveis, PID: 27653
    java.lang.ClassCastException: com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas cannot be cast to com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos
        at com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral.onBindViewHolder(AdaptadorGeral.java:84)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1080)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:3175)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2776)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2477)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1544)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7602)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7331)
Process 27653 terminated.
</code>```

答:
Here logcat is clearly saying that - classCastException.
So, Use the break statement for switch.
Because you didn't added break statement - every time it is creating the
ViewHolderMotos instance.</p>

```<code>  @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

            switch (completos.get(position).getTipo()){

                case "0":
                    RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                    ViewHolderBicicletas viewHolderBicicletas = (ViewHolderBicicletas) holder;

                    ((ViewHolderBicicletas) holder).textViewMarca.setText(completos.get(position).getMarca());
                    ((ViewHolderBicicletas) holder).textViewAno.setText(completos.get(position).getAno());
                    ((ViewHolderBicicletas) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                    ((ViewHolderBicicletas) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                    ((ViewHolderBicicletas) holder).textViewValor.setText("R$ "+completos.get(position).getValor());
                    Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);

                break;
                case "1":
                    RequestOptions requestOptions2 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                    ViewHolderMotos viewHolderMotos = (ViewHolderMotos)holder;

                    ((ViewHolderMotos) holder).textViewMarca.setText(completos.get(position).getMarca());
                    ((ViewHolderMotos) holder).textViewModelo.setText(completos.get(position).getModelo());
                    ((ViewHolderMotos) holder).textViewAno.setText(completos.get(position).getAno());
                    ((ViewHolderMotos) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                    ((ViewHolderMotos) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                    ((ViewHolderMotos) holder).textViewValor.setText("R$ "+completos.get(position).getValor());

                    Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions2).into(((ViewHolderMotos) holder).imageViewFoto);

                break;

            }
        }
</code>```

Body:
I'm an average programmer, and I'm trying to finalize a project, but I crashed again on an issue that is making me sleepy.
The point is that i am trying to use several layouts in a recycleview, taking the data from firebase, in this case i will use several viewholders, but i did several tests with content that i searched, but some errors occur and i couldn't solve it. Can someone help me?
I'll put all the code here, point out the errors, and if there is a simpler way to do this, you can talk.
In the future I will reuse the code for another part of the application with more than 10 views.

Firebase.

Main.class

package com.example.visualizarautomoveis;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral;
import com.example.visualizarautomoveis.Models.ModelBicicleta;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.Models.ModelMoto;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {

    private final String ested = "GE";
    private final String city = "Geoneion";

    DatabaseReference automoveis_banco;

    FirebaseDatabase database;

    ArrayList<ModelCompleto> list;

    private Context context;

    private RecyclerView recyclerView;

    RecyclerView.LayoutManager manager;
    AdaptadorGeral adaptadorGeral;

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

        recyclerView = findViewById(R.id.recyclerview);

        list = new ArrayList<ModelCompleto>();

        manager = new LinearLayoutManager(context);
        recyclerView.setLayoutManager(manager);

        automoveis_banco = FirebaseDatabase.getInstance().getReference().child(estet).child(cidy).child("Automoveis");

        automoveis_banco.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot eventSnapshot: dataSnapshot.getChildren())
                {
                    ModelCompleto mod =eventSnapshot.getValue(ModelCompleto.class);
                    list.add(mod);

                    Collections.reverse(list);
                }
                adaptadorGeral = new AdaptadorGeral(MainActivity.this,list);
                recyclerView.setAdapter(adaptadorGeral);
                adaptadorGeral.notifyDataSetChanged();

            }

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

            }
        });
    }
}

AdaptadorGeral.class

package com.example.visualizarautomoveis.Adapatadores;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.visualizarautomoveis.Models.ModelCompleto;
import com.example.visualizarautomoveis.R;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas;
import com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos;

import java.util.ArrayList;

public class AdaptadorGeral extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private final ArrayList<ModelCompleto> completos;

    private final String BICICLETA = "0";
    private final String MOTO = "1";

    public AdaptadorGeral(Context context, ArrayList<ModelCompleto> completos)
    {
        this.context = context;
        this.completos = completos;

    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        switch (completos.get(viewType).getTipo()){
            case "0":
                return new ViewHolderBicicletas(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_bicicletas,parent,false));

            case "1":
                return new ViewHolderMotos(LayoutInflater.from(context).inflate(R.layout.popup_automoveis_motocicletas, parent, false));

            default:
                break;
        }
        return null;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        switch (completos.get(position).getTipo()){

            case "0":
                RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderBicicletas viewHolderBicicletas = (ViewHolderBicicletas) holder;

                ((ViewHolderBicicletas) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderBicicletas) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderBicicletas) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderBicicletas) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderBicicletas) holder).textViewValor.setText("R$ "+completos.get(position).getValor());
                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);
            case "1":
                RequestOptions requestOptions2 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                ViewHolderMotos viewHolderMotos = (ViewHolderMotos)holder;

                ((ViewHolderMotos) holder).textViewMarca.setText(completos.get(position).getMarca());
                ((ViewHolderMotos) holder).textViewModelo.setText(completos.get(position).getModelo());
                ((ViewHolderMotos) holder).textViewAno.setText(completos.get(position).getAno());
                ((ViewHolderMotos) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                ((ViewHolderMotos) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                ((ViewHolderMotos) holder).textViewValor.setText("R$ "+completos.get(position).getValor());

                Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions2).into(((ViewHolderMotos) holder).imageViewFoto);

        }
    }

    @Override
    public int getItemCount() {

        if (completos != null){
            return this.completos.size();
        }else {
            return 0;
        }
    }

    @Override
    public int getItemViewType(int position) {

        if (completos.get(position).getTipo().equals("0"))
            return 0;
        if (completos.get(position).getTipo().equals("1")) {
            return 1;
        }
        return position;
    }
}

ViewHolderBicicletas.class

package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderBicicletas extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

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

        textViewAno = itemView.findViewById(R.id.popup_ano_bicicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_bicicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_bicicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_pubicacao_bicicleta);
        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_bicicletas);
        textViewValor = itemView.findViewById(R.id.popup_valor_bicicleta);
    }
}

ViewHolderMotos.class

package com.example.visualizarautomoveis.ViewHolderes;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.visualizarautomoveis.R;

public class ViewHolderMotos extends RecyclerView.ViewHolder{

    public  TextView textViewMarca;
    public  TextView textViewModelo;
    public  TextView textViewAno;
    public  TextView textViewDescrip;
    public  TextView textViewDataPublicacao;
    public  TextView textViewValor;
    public  ImageView imageViewFoto;

    public ViewHolderMotos(@NonNull View itemView) {
        super(itemView);
        textViewAno = itemView.findViewById(R.id.popup_ano_motocicleta);
        textViewMarca = itemView.findViewById(R.id.popup_marca_motocicleta);
        textViewModelo = itemView.findViewById(R.id.popup_modelo_motocicleta);
        textViewDescrip = itemView.findViewById(R.id.popup_descricao_motocicleta);
        textViewDataPublicacao = itemView.findViewById(R.id.popup_data_public_moto);
        textViewValor = itemView.findViewById(R.id.popup_valor_motocicleta);

        imageViewFoto = itemView.findViewById(R.id.popup_imagem_central_motocicletas);

    }
}

ModelCompleto.class

package com.example.visualizarautomoveis.Models;

public class ModelCompleto {
    private String valor,descricao,datapubicacao,foto1,marca,ano,modelo,tipo;

    public ModelCompleto() {
    }

    public ModelCompleto(String valor, String descricao, String datapubicacao, String foto1, String marca, String ano, String modelo, String tipo) {
        this.valor = valor;
        this.descricao = descricao;
        this.datapubicacao = datapubicacao;
        this.foto1 = foto1;
        this.marca = marca;
        this.ano = ano;
        this.modelo = modelo;
        this.tipo = tipo;
    }

    public String getValor() {
        return valor;
    }

    public void setValor(String valor) {
        this.valor = valor;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public String getDatapubicacao() {
        return datapubicacao;
    }

    public void setDatapubicacao(String datapubicacao) {
        this.datapubicacao = datapubicacao;
    }

    public String getFoto1() {
        return foto1;
    }

    public void setFoto1(String foto1) {
        this.foto1 = foto1;
    }

    public String getMarca() {
        return marca;
    }

    public void setMarca(String marca) {
        this.marca = marca;
    }

    public String getAno() {
        return ano;
    }

    public void setAno(String ano) {
        this.ano = ano;
    }

    public String getModelo() {
        return modelo;
    }

    public void setModelo(String modelo) {
        this.modelo = modelo;
    }

    public String getTipo() {
        return tipo;
    }

    public void setTipo(String tipo) {
        this.tipo = tipo;
    }
}

Error that appears when running the program:

D/TextView: setTypeface with style : 0
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.visualizarautomoveis, PID: 27653
    java.lang.ClassCastException: com.example.visualizarautomoveis.ViewHolderes.ViewHolderBicicletas cannot be cast to com.example.visualizarautomoveis.ViewHolderes.ViewHolderMotos
        at com.example.visualizarautomoveis.Adapatadores.AdaptadorGeral.onBindViewHolder(AdaptadorGeral.java:84)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3851)
        at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4404)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1080)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1742)
        at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1585)
        at android.widget.LinearLayout.onLayout(LinearLayout.java:1494)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.widget.FrameLayout.layoutChildren(FrameLayout.java:344)
        at android.widget.FrameLayout.onLayout(FrameLayout.java:281)
        at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:3175)
        at android.view.View.layout(View.java:18010)
        at android.view.ViewGroup.layout(ViewGroup.java:5911)
        at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2776)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2477)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1544)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7602)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911)
        at android.view.Choreographer.doCallbacks(Choreographer.java:686)
        at android.view.Choreographer.doFrame(Choreographer.java:622)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7331)
Process 27653 terminated.

Body:
Here logcat is clearly saying that - classCastException.
So, Use the break statement for switch.
Because you didn't added break statement - every time it is creating the
ViewHolderMotos instance.

  @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

            switch (completos.get(position).getTipo()){

                case "0":
                    RequestOptions requestOptions1 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                    ViewHolderBicicletas viewHolderBicicletas = (ViewHolderBicicletas) holder;

                    ((ViewHolderBicicletas) holder).textViewMarca.setText(completos.get(position).getMarca());
                    ((ViewHolderBicicletas) holder).textViewAno.setText(completos.get(position).getAno());
                    ((ViewHolderBicicletas) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                    ((ViewHolderBicicletas) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                    ((ViewHolderBicicletas) holder).textViewValor.setText("R$ "+completos.get(position).getValor());
                    Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);

                break;
                case "1":
                    RequestOptions requestOptions2 = new RequestOptions().placeholder(R.drawable.ic_launcher_background);
                    ViewHolderMotos viewHolderMotos = (ViewHolderMotos)holder;

                    ((ViewHolderMotos) holder).textViewMarca.setText(completos.get(position).getMarca());
                    ((ViewHolderMotos) holder).textViewModelo.setText(completos.get(position).getModelo());
                    ((ViewHolderMotos) holder).textViewAno.setText(completos.get(position).getAno());
                    ((ViewHolderMotos) holder).textViewDescrip.setText(completos.get(position).getDescricao());
                    ((ViewHolderMotos) holder).textViewDataPublicacao.setText(completos.get(position).getDatapubicacao());
                    ((ViewHolderMotos) holder).textViewValor.setText("R$ "+completos.get(position).getValor());

                    Glide.with(context).load(completos.get(position).getFoto1()).apply(requestOptions2).into(((ViewHolderMotos) holder).imageViewFoto);

                break;

            }
        }


来源: stackexchange

问:
Is there such thing as a parallel linked list?
Ok so basically, i'm not asking for source code or anything, but essentially I'm writing a scholarship program where the user can store all the scholarships that they're interested in. Thus, they input the info (name, deadline, award amount, etc), and they do this everytime they wanna add something new to the list.

As for my problem, I want to be able to have a sort method that sorts it how they choose, so alphabetical order, most money awarded, etc. I'm trying to do it with a linked list, where one list is for names and another for the deadline, and the other things listed above, but when I sort it based on one criteria, how can I make the other list sort the same way?

Is this possible another way with a linked list or am I going about this the completely wrong way?

btw I know you can do it with arrays, but i'm hoping to score extra points on my assignment with a linked list.

答:
Q : hoping to score extra points on my assignment with a linked list.

If hunting extra points, you may cite, that this problem has been solved as early as half a century ago, by no smaller genius than Charles H. MOORE, the only man who never had to learn FORTH ( as he has created it ).

A lovely picture about multi-context linked-lists implemented in FORTH vocabularies, having for each context another, context-specific linked-list-pointers-{PREV|NEXT} was presented 40 years ago in Leo BRODIE's (a must-read book+) - "An Introduction to the FORTH Language and Operating System for Beginners and Professionals"

This system-level implementation in FORTH is smart and utmost efficient for any reasonable multi-processing accesses, be it either a just-[CONCURRENT] or a true-[PARALLEL] consumer-processing ( whereas the maintenance needs some form of transaction-level protection, during the network-of-pointers re-writes, doesn't it? )

+) Starting FORTH [Pg.242]; Leo BRODIE

ContentLicense: CC BY-SA 4.0


问:
Files and folders added to a cloned repository are not seen in remote repository after pushing
I have a problem with pushing to my remote repository.
What I did is:

1) I cloned an existing repository to my computer

2) I was working for a while at my computer with the project  (adding some folders with new data, doing some changes to the existing files)

3)

a) I created my own remote repository on GitHub

b) used git remote set-url origin new.git.url/here

c) used: git add . then git commit -m "Comment" then git push.

The outcome is that in my remote repository I have now only the files that were in the original cloned repository (if I made any changes to them, the changes are there), but no files or folders added by me are there.
When I commit files I added after pushing the repository for the first time, they are seen and commited.
Could you help me to push also all the changes I made to the project before pushing for the first time?
Edit: I think the problem lies in .gitgnore file, but I am not sure which lines I can delete and which not:

```<code>*.o
*.a
*.dSYM
*.csv
*.out
*.png
*.so
*.exe
*.dll
*.lib
*.dylib
mnist/
data/
caffe/
grasp/
images/
opencv/
convnet/
decaf/
submission/
cfg/
build/darknet/*
build_*/
!build/darknet/YoloWrapper.cs
.fuse*
*.weights
build/*.cmake
build/*.ninja
build/*.txt
build/*.json
build/CMakeFiles/
build/detect_cuda_compute_capabilities.cu
build/.ninja_deps
build/.ninja_log
build/Makefile

# OS Generated #
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
*.swp

# IDE generated #
.vs/
.vscode/

# Managed by CMake
src/version.h

# Build artifacts
lib/
share/
include/darknet/
uselib
uselib_track
darknet
</code>```

This is link to the original repository: https://github.com/AlexeyAB/darknet

答:
The right way in your case is to use forks.

So, the first step is to fork remote repository, than you can add changes to it, commit and push to your own fork.
You can't add changes and push it to the original repository if you are not the author of such repo, but you can do it with forks.

Body:
I have a problem with pushing to my remote repository.
What I did is:

1) I cloned an existing repository to my computer

2) I was working for a while at my computer with the project  (adding some folders with new data, doing some changes to the existing files)

3)

a) I created my own remote repository on GitHub

b) used git remote set-url origin new.git.url/here

c) used: git add . then git commit -m "Comment" then git push.

The outcome is that in my remote repository I have now only the files that were in the original cloned repository (if I made any changes to them, the changes are there), but no files or folders added by me are there.
When I commit files I added after pushing the repository for the first time, they are seen and commited.
Could you help me to push also all the changes I made to the project before pushing for the first time?
Edit: I think the problem lies in .gitgnore file, but I am not sure which lines I can delete and which not:

*.o
*.a
*.dSYM
*.csv
*.out
*.png
*.so
*.exe
*.dll
*.lib
*.dylib
mnist/
data/
caffe/
grasp/
images/
opencv/
convnet/
decaf/
submission/
cfg/
build/darknet/*
build_*/
!build/darknet/YoloWrapper.cs
.fuse*
*.weights
build/*.cmake
build/*.ninja
build/*.txt
build/*.json
build/CMakeFiles/
build/detect_cuda_compute_capabilities.cu
build/.ninja_deps
build/.ninja_log
build/Makefile

# OS Generated #
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
*.swp

# IDE generated #
.vs/
.vscode/

# Managed by CMake
src/version.h

# Build artifacts
lib/
share/
include/darknet/
uselib
uselib_track
darknet

This is link to the original repository: https://github.com/AlexeyAB/darknet


问:
Angular keeps automatically reloading
Angular keeps automatically reloading when using:

ng serve
  This behaviour only happens on my computer.

iMac Late 2013
OS: OSX High Sierra

答: Just to clear it out, i had the same issue tough it is temporary because when iCloud will finish the sync the endless refresh will be over</p>

Title: Angular keeps automatically reloading


问:
create index on creation of table in Oracle
In MySql, one can create an index on a (non-unique) column along with a table, e.g.

```<code>create table orders(
   orderid varchar(20) not null unique,
   customerid varchar(20),
   index(customerid)
   );
</code>```

Having not found a corresponding option in Oracle, i.e. creating the index on table creation rather than as a separate command afterwards, I suspect it is not possible. Is this correct? If so, what is the reason behind this - efficiency, as for example discussed here
Insertion of data after creating index on empty table or creating unique index after inserting data on oracle? ?
Thanks in advance!

答: The root reason for the difference is that MySQL and Oracle are two distinctly different products, developed at different times by different software engineering teams.  The fact thay MySQL is owned by Oracle means nothing in this case.  MySQL was a separate and separetly developed product which was subsequently purchased by Oracle. As for why the two separate and distinct design teams made the decisions they did ... you'd have to ask them. But I'm pretty certain it has nothing to do with operational efficiency as you suggest.  Once a table and index are created, there is no difference between having created an index as part of the CREATE TABLE vs. creating the index separately.  And so there would be no difference in efficiency of any DML on said table.

Body:
In MySql, one can create an index on a (non-unique) column along with a table, e.g.

create table orders(
   orderid varchar(20) not null unique,
   customerid varchar(20),
   index(customerid)
   );

Having not found a corresponding option in Oracle, i.e. creating the index on table creation rather than as a separate command afterwards, I suspect it is not possible. Is this correct? If so, what is the reason behind this - efficiency, as for example discussed here
Insertion of data after creating index on empty table or creating unique index after inserting data on oracle? ?
Thanks in advance!


问:
Delayed scroll to Div ID when select option is chosen
I'd like to be able to scroll to a particular ID when a select option has been chosen from a drop down list. It seems like it should be extremely simple, however I can't find an example on here that performs how I want it to.

Basically, I have a div near the top of the page

CONTENT

Then lower down the page, a select box:

```<code><select id="variant">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</code>```

What I would like to do, is - once a selection has been made - for the page to scroll back up to the id "mainimage".

If possible, ideally this would happen after a delay of around half a second, and scroll smoothly.

It seems like it should be fairly straightforward, as the page just needs to scroll to the same ID regardless of the selection.

Is this possible with javascript?

Thanks in advance.

答:
You can try this.

I added CSS scroll smooth, also you can change JS it's only to see the dynamics.

document.getElementById("select").onchange = function(){
  if(this.selectedIndex == 0){
     window.location.hash = '#section1';
  } else {
    window.location.hash = '#section2';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  scroll-behavior: smooth;
}
* {
margin-bottom: 300px;
}
#section1 {
height: 500px;
background-color: red;
color: white;
}

#section2 {
height: 500px;
background-color: blue;
color: white;
}</code>```

<select id="select" name="sections">
  <option>Section 1</option>
  <option>Section 2</option>
</select>

Section 1

Section 2

```

Body:
I'd like to be able to scroll to a particular ID when a select option has been chosen from a drop down list. It seems like it should be extremely simple, however I can't find an example on here that performs how I want it to.

Basically, I have a div near the top of the page

CONTENT

Then lower down the page, a select box:

<select id="variant">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

What I would like to do, is - once a selection has been made - for the page to scroll back up to the id "mainimage".

If possible, ideally this would happen after a delay of around half a second, and scroll smoothly.

It seems like it should be fairly straightforward, as the page just needs to scroll to the same ID regardless of the selection.

Is this possible with javascript?

Thanks in advance.

Body:
You can try this.

I added CSS scroll smooth, also you can change JS it's only to see the dynamics.

document.getElementById("select").onchange = function(){
  if(this.selectedIndex == 0){
     window.location.hash = '#section1';
  } else {
    window.location.hash = '#section2';
  }
}

html {
  scroll-behavior: smooth;
}
* {
margin-bottom: 300px;
}
#section1 {
height: 500px;
background-color: red;
color: white;
}

#section2 {
height: 500px;
background-color: blue;
color: white;
}

<select id="select" name="sections">
  <option>Section 1</option>
  <option>Section 2</option>
</select>

<div id="section1">
Section 1
</div>

<div id="section2">
Section 2
</div>


问:
Optimal solution for looping and inserting/updating
I am interested to know if there is a better / more optimal solution than what I have so far as it uses a cursor, which I know is not too good performance wise.

Basically my requirement is too check if a number of settings exists for an ID and then update or insert them accordingly.

To do this I have:

```<code>DECLARE @UserId UNIQUEIDENTIFIER = '{PUT-GUID-HERE}'
</code>```

I then declare a table variable which I add the setting names and values to, there are approx 15 of these in total.

```<code>DECLARE @SettingsToCheck TABLE (SettingName varchar(100), SettingValue varchar(100)
INSERT INTO @SettingsToCheck ('Setting1', 'Setting1 Value') --Repeat...

DECLARE @CurrentSettingName varchar(100)
DECLARE @CurrentSettingValue varchar(100)
DECLARE Settings_Cursor CURSOR FOR SELECT SettingName, SettingValue FROM @SettingsToCheck
OPEN Settings_Cursor

FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
WHILE @@FETCH_STATUS = 0
BEGIN
    IF EXISTS (SELECT * FROM MyActualTable WHERE UserID = @UserId AND SettingName = @CurrentSettingName)
    BEGIN
        UPDATE MyActualTable SET SettingValue = @CurrentSettingValue WHERE UserID = @UserId AND SettingName = @CurrentSettingName
    END
    ELSE
    BEGIN
        INSERT INTO MyActualTableVALUES (NEWID(), @UserId, GETDATE(), @CurrentSettingName, @CurrentSettingValue)
    END

    FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
END

CLOSE Settings_Cursor
DEALLOCATE Settings_Cursor
</code>```

I know this question is subject to opinion, but I am unaware of any alternatives.

EDIT:

There could be a scenario where some/none or all of the settings already exist. But here's an example.

BEFORE:

```<code>SettingName  |  SettingValue
____________________________
Setting1     |  Setting1Value
</code>```

AFTER:

```<code>SettingName  |  SettingValue
____________________________
Setting1     |  Setting1ValueUPDATED

Setting2     |  NewSetting
</code>```

答:
I know people like to use MERGE, but I prefer just separating them out to their individual task.  Aaron Bertrand documented some of the issues with MERGE here: https://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/,
but I am not sure how many of those still persist.

Anyways, this is an alternative:

```<code>CREATE TABLE #SettingsToCheck
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

CREATE TABLE #ActualTable
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

INSERT INTO #SettingsToCheck
VALUES
('Setting1', 'Setting1 Value') --Repeat...
,('Setting2', 'Setting2 Value')
,('Setting3', 'Setting3 Value')
,('Setting4', 'Setting45 Value')
,('Setting5', 'Setting5 Value')
,('Setting6', 'Setting6 Value')
,('Setting7', 'Setting7 Value')

INSERT INTO #ActualTable
VALUES
 ('Setting4', 'Setting4 Value')

 UPDATE #ActualTable
    SET SettingValue = t2.SettingValue
    FROM #ActualTable t1
    INNER JOIN #SettingsToCheck t2 on t1.SettingName = t2.SettingName

INSERT INTO #ActualTable(SettingName,SettingValue)
SELECT t1.SettingName,t1.SettingValue
    FROM #SettingsToCheck t1
    LEFT JOIN #ActualTable t2 on t1.SettingName = t2.SettingName
    WHERE t2.SettingName IS NULL

select * from #ActualTable
</code>```

Body:
I am interested to know if there is a better / more optimal solution than what I have so far as it uses a cursor, which I know is not too good performance wise.

Basically my requirement is too check if a number of settings exists for an ID and then update or insert them accordingly.

To do this I have:

DECLARE @UserId UNIQUEIDENTIFIER = '{PUT-GUID-HERE}'

I then declare a table variable which I add the setting names and values to, there are approx 15 of these in total.

DECLARE @SettingsToCheck TABLE (SettingName varchar(100), SettingValue varchar(100)
INSERT INTO @SettingsToCheck ('Setting1', 'Setting1 Value') --Repeat...

DECLARE @CurrentSettingName varchar(100)
DECLARE @CurrentSettingValue varchar(100)
DECLARE Settings_Cursor CURSOR FOR SELECT SettingName, SettingValue FROM @SettingsToCheck
OPEN Settings_Cursor

FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
WHILE @@FETCH_STATUS = 0
BEGIN
    IF EXISTS (SELECT * FROM MyActualTable WHERE UserID = @UserId AND SettingName = @CurrentSettingName)
    BEGIN
        UPDATE MyActualTable SET SettingValue = @CurrentSettingValue WHERE UserID = @UserId AND SettingName = @CurrentSettingName
    END
    ELSE
    BEGIN
        INSERT INTO MyActualTableVALUES (NEWID(), @UserId, GETDATE(), @CurrentSettingName, @CurrentSettingValue)
    END

    FETCH NEXT FROM Settings_Cursor INTO @CurrentSettingName, @CurrentSettingValue
END

CLOSE Settings_Cursor
DEALLOCATE Settings_Cursor

I know this question is subject to opinion, but I am unaware of any alternatives.

EDIT:

There could be a scenario where some/none or all of the settings already exist. But here's an example.

BEFORE:

SettingName  |  SettingValue
____________________________
Setting1     |  Setting1Value

AFTER:

SettingName  |  SettingValue
____________________________
Setting1     |  Setting1ValueUPDATED

Setting2     |  NewSetting

Body:
I know people like to use MERGE, but I prefer just separating them out to their individual task.  Aaron Bertrand documented some of the issues with MERGE here: https://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/,
but I am not sure how many of those still persist.

Anyways, this is an alternative:

CREATE TABLE #SettingsToCheck
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

CREATE TABLE #ActualTable
(
    SettingName varchar(100)
    ,SettingValue varchar(100)
)

INSERT INTO #SettingsToCheck
VALUES
('Setting1', 'Setting1 Value') --Repeat...
,('Setting2', 'Setting2 Value')
,('Setting3', 'Setting3 Value')
,('Setting4', 'Setting45 Value')
,('Setting5', 'Setting5 Value')
,('Setting6', 'Setting6 Value')
,('Setting7', 'Setting7 Value')

INSERT INTO #ActualTable
VALUES
 ('Setting4', 'Setting4 Value')

 UPDATE #ActualTable
    SET SettingValue = t2.SettingValue
    FROM #ActualTable t1
    INNER JOIN #SettingsToCheck t2 on t1.SettingName = t2.SettingName

INSERT INTO #ActualTable(SettingName,SettingValue)
SELECT t1.SettingName,t1.SettingValue
    FROM #SettingsToCheck t1
    LEFT JOIN #ActualTable t2 on t1.SettingName = t2.SettingName
    WHERE t2.SettingName IS NULL

select * from #ActualTable


问:
Modifying a String (char array)
I am trying to modify a string in C language

```<code>    char signal_cat[8];

        if (k == 1) {
            strcpy_s(signal_cat, "HPHA",6);             //why cant I change char array (string) values???
        }
        else if (k == 2) {
            strcpy_s(signal_cat, "Normal",6);
        }

        printf("Original signal category: %s \n", signal_cat);

</code>```

When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"

I have tried

```<code>signal_cat = "HPHA";
</code>```

too, but an error shows "expression must be a modifiable lvalue"

Does anyone know how I can go about doing this?

答:
You specified an invalid order of arguments. A call of strcpy_s should look like

```<code>strcpy_s(signal_cat, sizeof( signal_cat ), "HPHA" );
</code>```

Otherwise use the standard C function strcpy like

```<code>strcpy( signal_cat, "HPHA" );
</code>```

provided that the array signal_cat has enough space to accommodate the string literal.

Or you can use another standard function strncpy

```<code>strncpy( signal_cat, "HPHA", sizeof( signal_cat ) );
signal_cat[sizeof( signal_cat )-1] = '\0';
</code>```

As for this statement

```<code>signal_cat = "HPHA";
</code>```

then arrays do not have the assignment operator. They are non-modifiable lvalues.

Title: Modifying a String (char array)

Body:
I am trying to modify a string in C language

    char signal_cat[8];

        if (k == 1) {
            strcpy_s(signal_cat, "HPHA",6);             //why cant I change char array (string) values???
        }
        else if (k == 2) {
            strcpy_s(signal_cat, "Normal",6);
        }

        printf("Original signal category: %s \n", signal_cat);

When I run this it shows an exception "Unhandled exception at 0x7BEBF71D (ucrtbased.dll) in Lab3Parti.exe: 0xC0000005: Access violation reading location 0x00000006"

I have tried

signal_cat = "HPHA";

too, but an error shows "expression must be a modifiable lvalue"

Does anyone know how I can go about doing this?

Body:
You specified an invalid order of arguments. A call of strcpy_s should look like

strcpy_s(signal_cat, sizeof( signal_cat ), "HPHA" );

Otherwise use the standard C function strcpy like

strcpy( signal_cat, "HPHA" );

provided that the array signal_cat has enough space to accommodate the string literal.

Or you can use another standard function strncpy

strncpy( signal_cat, "HPHA", sizeof( signal_cat ) );
signal_cat[sizeof( signal_cat )-1] = '\0';

As for this statement

signal_cat = "HPHA";

then arrays do not have the assignment operator. They are non-modifiable lvalues.


问:
Get current size of IPython window
I am trying to make a progress bar. I'm trying to make it fit perfectly with the ipython window. The number of elements in the progress bar would depend on the width of the window. For instance:

```<code>print('loading' + '-----'*window_width//2)
</code>```

How can I get this?

答:
```<code>import os

os.get_terminal_size()
</code>```

```<code>Out[1]: os.terminal_size(columns=33, lines=9)
</code>```

Title: Get current size of IPython window

Body:
I am trying to make a progress bar. I'm trying to make it fit perfectly with the ipython window. The number of elements in the progress bar would depend on the width of the window. For instance:

print('loading' + '-----'*window_width//2)

How can I get this?

Body:
import os

os.get_terminal_size()

Out[1]: os.terminal_size(columns=33, lines=9)


问:
is there a way that i don't have to write a full query in each condition?
is there a way that i don't have to write a full query in each condition?</p>

```<code>if($_GET['l'] == 1){
    $num = $db -> query("SELECT * FROM text WHERE type = '' AND gg = '1'") -> num_rows;
}
elseif($_GET['l'] == 2){
    $num = $db -> query("SELECT * FROM text WHERE type = '' AND gg = '2'") -> num_rows;
}
else {
    $num = $db -> query("SELECT * FROM text WHERE type = ''") -> num_rows;
}
</code>```

答:
It Simple,
Declare a variable and make a query in the variable.

```<code>$query = "SELECT * FROM text WHERE type = ''";
if($_GET['l'] == 1){
    $query .= "  AND gg = '1'";
}
elseif($_GET['l'] == 2){
    $query .= "  AND gg = '2'";
}
else {
    $query .= " ";
}
    $num = $db -> query($query) -> num_rows;

</code>```

Hope this help you.

Body:
is there a way that i don't have to write a full query in each condition?

if($_GET['l'] == 1){
    $num = $db -> query("SELECT * FROM text WHERE type = '' AND gg = '1'") -> num_rows;
}
elseif($_GET['l'] == 2){
    $num = $db -> query("SELECT * FROM text WHERE type = '' AND gg = '2'") -> num_rows;
}
else {
    $num = $db -> query("SELECT * FROM text WHERE type = ''") -> num_rows;
}

Body:
It Simple,
Declare a variable and make a query in the variable.

$query = "SELECT * FROM text WHERE type = ''";
if($_GET['l'] == 1){
    $query .= "  AND gg = '1'";
}
elseif($_GET['l'] == 2){
    $query .= "  AND gg = '2'";
}
else {
    $query .= " ";
}
    $num = $db -> query($query) -> num_rows;

Hope this help you.


问:
Passing data to activity from widget
I am trying to pass data from widget to activity and I always receive null.
Here is onUpdate from widget class:

```<code>@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

    for (int widgetId : allWidgetIds) {

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget);

        Intent configIntent = new Intent(context, WebViewActivity.class);
        configIntent.putExtra("URL", "Content");
        PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.buttonOpen, configPendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);

}
</code>```

Second Activity:

```<code>public class WebViewActivity extends AppCompatActivity  {

WebView webView;

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

    String sessionId = getIntent().getStringExtra("URL");
    Log.d("DTAG","URL: "+sessionId); //Is null

    webView = findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(sessionId);
}
</code>```

}

答:
If you wish to replace extras in a PendingIntent, you need to use FLAG_UPDATE_CURRENT for the final parameter to PendingIntent.getActivity(). Otherwise, the extras in your new Intent will be ignored.

And, if you wish to have different extras for different PendingIntent objects (e.g., per widget ID), you need to pass a unique ID as the second parameter to PendingIntent.getActivity(). If you use 0 all the time, you get exactly one PendingIntent with one set of extras.

Title: Passing data to activity from widget

Body:
I am trying to pass data from widget to activity and I always receive null.
Here is onUpdate from widget class:

@Override
public void onUpdate(final Context context, final AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    ComponentName thisWidget = new ComponentName(context, MyWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

    for (int widgetId : allWidgetIds) {

        RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget);

        Intent configIntent = new Intent(context, WebViewActivity.class);
        configIntent.putExtra("URL", "Content");
        PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.buttonOpen, configPendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);

}

Second Activity:

public class WebViewActivity extends AppCompatActivity  {

WebView webView;

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

    String sessionId = getIntent().getStringExtra("URL");
    Log.d("DTAG","URL: "+sessionId); //Is null

    webView = findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl(sessionId);
}

}


问:
$ bundle update - error - Can't find the PostgreSQL client library (libpq) *** extconf.rb failed ***
I'm trying to run
$bundle update, but it errors after going through several gems with the following:

```<code>Installing pg (0.11.0) with native extensions /Library/Ruby/Site/1.8/rubygems/installer.rb:483:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /opt/local/lib/postgresql83/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pqlib
    --without-pqlib
    --with-libpqlib
    --without-libpqlib
    --with-ms/libpqlib
    --without-ms/libpqlib

Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/pg-0.11.0 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/pg-0.11.0/ext/gem_make.out
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `each'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `build_extensions'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:198:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/source.rb:100:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:55:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:44:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:8:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/cli.rb:252:in `update'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `send'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/bin/bundle:13
    from /usr/bin/bundle:19:in `load'
    from /usr/bin/bundle:19
</code>```

Have you seen this or have any ideas on what's breaking here? thanks

答: When you tried to compile a postgres gem to the ruby, you have to have installed a development version of Posgtresql library, in Ubuntu (Debian etc.) it is named libpq-dev and client library, which is named libpqx (x is the version of this library).</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to run
$bundle update, but it errors after going through several gems with the following:

Installing pg (0.11.0) with native extensions /Library/Ruby/Site/1.8/rubygems/installer.rb:483:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for pg_config... yes
Using config values from /opt/local/lib/postgresql83/bin/pg_config
checking for libpq-fe.h... yes
checking for libpq/libpq-fs.h... yes
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config
    --with-pqlib
    --without-pqlib
    --with-libpqlib
    --without-libpqlib
    --with-ms/libpqlib
    --without-ms/libpqlib

Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/pg-0.11.0 for inspection.
Results logged to /Library/Ruby/Gems/1.8/gems/pg-0.11.0/ext/gem_make.out
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `each'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:446:in `build_extensions'
    from /Library/Ruby/Site/1.8/rubygems/installer.rb:198:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/source.rb:100:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:55:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/spec_set.rb:12:in `each'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:44:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/installer.rb:8:in `install'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/cli.rb:252:in `update'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `send'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /Library/Ruby/Gems/1.8/gems/bundler-1.0.0/bin/bundle:13
    from /usr/bin/bundle:19:in `load'
    from /usr/bin/bundle:19

Have you seen this or have any ideas on what's breaking here? thanks


问:
What is the rationale behind the `std::unique_XXX` naming convention?
It seems like there was a mini-trend to name things std::unique_XXX at some point. It makes sense that std::unique_ptr is a smart pointer that is only meant to be handled by one consumer, and therefore "unique" in this case makes sense.

But at least one other class got the unique moniker and I'm not really sure why. Why is std::unique_lock called that? As opposed to std::lock_guard, which is not any less or more unique, right?

I think I'm missing something.

I can't recall what other classes followed suit but I seem to remember we have more. Maybe it was just std::unique_lock; I forget. But if there are other std::unique_XXX class names, why are they named that?

答:
You mention that std::unique_ptr makes sense.

std::unique_lock is modeled after boost::unique_lock.  Here's the proposal to put it in the standard.

The paper doesn't seem to mention the reasoning behind the name, but I'm going to speculate that the unique_ prefix is intended to denote a type that:

Can be "empty"

Default constructs "empty"

Can be moved.

Can be released prior to destruction

Expressly forbids sharing/copying (There is a std::shared_lock that expressly allows sharing)


问:
SQL Server : group by userId - merge 2 rows into 1 row
When I query a user by UserName I get two rows but I would like to merge them into one row. For example,

Current result:

Desired result:

答:
You can do aggregation :</p>

```<code>select userid, username,
       max(case when phonetype = 'primary' then phonenumber end) as primary_no,
       max(case when phonetype = 'secondary' then phonenumber end) as secondary_no
from t
group by userid, username;
</code>```

Body:
You can do aggregation :

select userid, username,
       max(case when phonetype = 'primary' then phonenumber end) as primary_no,
       max(case when phonetype = 'secondary' then phonenumber end) as secondary_no
from t
group by userid, username;


问:
Initialization in a parameterless constructor should be avoided?
some of my colleagues demand to avoid parameterless constructor and it's initialization completly.
Because they tell me that a default initialization of a string property for example quickly hides the ability to find out the source of the error.

But a standard initialization of objects prevent the raise of a NullReferenceException in advance.
And don't unit tests prevent those 'hard to find' errors?

So what is the best practice of doing this in C#?

What if i had a class with 10 Properties? Should the properties also be initialized via parameters of the constructor if i want to avoid the parameterless constructor? Isn't it to verbose?

For example i have this class, so people told me that i shouldn't do the default initialzation this way:

```<code>public class UserForCreationDto
{
    public UserForCreationDto()
    {
        Username = "";
        Email = "";
    }

    [Required]
    [MaxLength(100)]
    public string Username { get; set; }

    [Required]
    [MaxLength(100)]
    public string Email { get; set; }
}
</code>```

答:
If you want to intialize the properties to something else than their default values, you could do this directly in the definition:

```<code>public class UserForCreationDto
{
    [Required]
    [MaxLength(100)]
    public string Username { get; set; } = "";

    [Required]
    [MaxLength(100)]
    public string Email { get; set; } = "";
}
</code>```

But if you want to prevent NullReferenceExceptions, you should also make the setters private. Given your current implementation, both properties can still be set to null explicitly.

That's why you should always - as a precaution - verify that a reference type variable is initialized before you try to access any of its properties:

```<code>if (!string.IsNullOrEmpty(dto.Username) { ... }
</code>```

Body:
some of my colleagues demand to avoid parameterless constructor and it's initialization completly.
Because they tell me that a default initialization of a string property for example quickly hides the ability to find out the source of the error.

But a standard initialization of objects prevent the raise of a NullReferenceException in advance.
And don't unit tests prevent those 'hard to find' errors?

So what is the best practice of doing this in C#?

What if i had a class with 10 Properties? Should the properties also be initialized via parameters of the constructor if i want to avoid the parameterless constructor? Isn't it to verbose?

For example i have this class, so people told me that i shouldn't do the default initialzation this way:

public class UserForCreationDto
{
    public UserForCreationDto()
    {
        Username = "";
        Email = "";
    }

    [Required]
    [MaxLength(100)]
    public string Username { get; set; }

    [Required]
    [MaxLength(100)]
    public string Email { get; set; }
}

Body:
If you want to intialize the properties to something else than their default values, you could do this directly in the definition:

public class UserForCreationDto
{
    [Required]
    [MaxLength(100)]
    public string Username { get; set; } = "";

    [Required]
    [MaxLength(100)]
    public string Email { get; set; } = "";
}

But if you want to prevent NullReferenceExceptions, you should also make the setters private. Given your current implementation, both properties can still be set to null explicitly.

That's why you should always - as a precaution - verify that a reference type variable is initialized before you try to access any of its properties:

if (!string.IsNullOrEmpty(dto.Username) { ... }


问:
Get file extension native method
I'm using MVS 2010, C++ program without using CRT.

Implementation of finding extension of file:

```<code>LPWSTR findExtension(LPCWSTR fileName)
{
    int pos = findchr(fileName, L".");
    if (pos != -1) {
        int lenght = lstrlenW(fileName);
        wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, lenght - pos + 1);
        for (int i = 0; i < lenght - pos; i++)
        {
            extension[i] = fileName[pos + 1 + i];
        }
        extension[lenght - pos] = 0;
        LPWSTR ret = extension;

        return ret;
    }
}
</code>```

There are problems. Sometimes it can crash application. And memory leak.
How to fix this issues?

答:
HeapAlloc() function will allocate memory on heap. When you're not using the heap memory block you need to free it. You can use:

    BOOL HeapFree( HANDLE hHeap,DWORD dwFlags,_Frees_ptr_opt_ LPVOID lpMem);

Even though you're in a {....} module, heap will not behave just like the stack that it will automatically FREE its memory. The more you reuse the function the more it will allocate memory to the heap and your private memory size(see task manager) will grow bigger and bigger. And by the time the OS can't give you memory it will suddenly crash.

Not freeing heap memory after using is bad if your program is running a long period (worst case if infinite time) and always perform processes.

Title: Get file extension native method

Body:
I'm using MVS 2010, C++ program without using CRT.

Implementation of finding extension of file:

LPWSTR findExtension(LPCWSTR fileName)
{
    int pos = findchr(fileName, L".");
    if (pos != -1) {
        int lenght = lstrlenW(fileName);
        wchar_t* extension = (wchar_t*)HeapAlloc(GetProcessHeap(), NULL, lenght - pos + 1);
        for (int i = 0; i < lenght - pos; i++)
        {
            extension[i] = fileName[pos + 1 + i];
        }
        extension[lenght - pos] = 0;
        LPWSTR ret = extension;

        return ret;
    }
}

There are problems. Sometimes it can crash application. And memory leak.
How to fix this issues?


问:
Apply MinMaxScaler on multiple columns in PySpark
I want to apply MinMaxScalar of PySpark to multiple columns of PySpark data frame df. So far, I only know how to apply it to a single column, e.g. x.

```<code>from pyspark.ml.feature import MinMaxScaler

pdf = pd.DataFrame({'x':range(3), 'y':[1,2,5], 'z':[100,200,1000]})
df = spark.createDataFrame(pdf)

scaler = MinMaxScaler(inputCol="x", outputCol="x")
scalerModel = scaler.fit(df)
scaledData = scalerModel.transform(df)
</code>```

What if I have 100 columns? Is there any way to do min-max scaling for many columns in PySpark?

Update:

Also, how to apply MinMaxScalar on integer or double values? It throws the following error:

```<code>java.lang.IllegalArgumentException: requirement failed: Column length must be of type struct<type:tinyint,size:int,indices:array<int>,values:array<double>> but was actually int.
</code>```

答:
Question 1:

How to change your example to run properly. You need to prepare the data as a vector for the transformers to work.

```<code>from pyspark.ml.feature import MinMaxScaler
from pyspark.ml import Pipeline
from pyspark.ml.linalg import VectorAssembler

pdf = pd.DataFrame({'x':range(3), 'y':[1,2,5], 'z':[100,200,1000]})
df = spark.createDataFrame(pdf)

assembler = VectorAssembler(inputCols=["x"], outputCol="x_vec")
scaler = MinMaxScaler(inputCol="x_vec", outputCol="x_scaled")
pipeline = Pipeline(stages=[assembler, scaler])
scalerModel = pipeline.fit(df)
scaledData = scalerModel.transform(df)
</code>```

Question 2:

To run MinMaxScaler on multiple columns you can use a pipeline that receives a list of transformation prepared with with a list comprehension:

```<code>from pyspark.ml import Pipeline
from pyspark.ml.feature import MinMaxScaler
columns_to_scale = ["x", "y", "z"]
assemblers = [VectorAssembler(inputCols=[col], outputCol=col + "_vec") for col in columns_to_scale]
scalers = [MinMaxScaler(inputCol=col + "_vec", outputCol=col + "_scaled") for col in columns_to_scale]
pipeline = Pipeline(stages=assemblers + scalers)
scalerModel = pipeline.fit(df)
scaledData = scalerModel.transform(df)
</code>```

Check this example pipeline in the official documentation.

Eventually, you will end with the results in this format:

```<code>>>> scaledData.printSchema()
root
 |-- x: long (nullable = true)
 |-- y: long (nullable = true)
 |-- z: long (nullable = true)
 |-- x_vec: vector (nullable = true)
 |-- y_vec: vector (nullable = true)
 |-- z_vec: vector (nullable = true)
 |-- x_scaled: vector (nullable = true)
 |-- y_scaled: vector (nullable = true)
 |-- z_scaled: vector (nullable = true)

>>> scaledData.show()
+---+---+----+-----+-----+--------+--------+--------+--------------------+
|  x|  y|   z|x_vec|y_vec|   z_vec|x_scaled|y_scaled|            z_scaled|
+---+---+----+-----+-----+--------+--------+--------+--------------------+
|  0|  1| 100|[0.0]|[1.0]| [100.0]|   [0.0]|   [0.0]|               [0.0]|
|  1|  2| 200|[1.0]|[2.0]| [200.0]|   [0.5]|  [0.25]|[0.1111111111111111]|
|  2|  5|1000|[2.0]|[5.0]|[1000.0]|   [1.0]|   [1.0]|               [1.0]|
+---+---+----+-----+-----+--------+--------+--------+--------------------+
</code>```

Extra Post-processing:

You can recover the columns in their original names with some post-processing. For example:

```<code>from pyspark.sql import functions as f
names = {x + "_scaled": x for x in columns_to_scale}
scaledData = scaledData.select([f.col(c).alias(names[c]) for c in names.keys()])
</code>```

The output will be:

```<code>scaledData.show()
+------+-----+--------------------+
|     y|    x|                   z|
+------+-----+--------------------+
| [0.0]|[0.0]|               [0.0]|
|[0.25]|[0.5]|[0.1111111111111111]|
| [1.0]|[1.0]|               [1.0]|
+------+-----+--------------------+
</code>```

Body:
I want to apply MinMaxScalar of PySpark to multiple columns of PySpark data frame df. So far, I only know how to apply it to a single column, e.g. x.

from pyspark.ml.feature import MinMaxScaler

pdf = pd.DataFrame({'x':range(3), 'y':[1,2,5], 'z':[100,200,1000]})
df = spark.createDataFrame(pdf)

scaler = MinMaxScaler(inputCol="x", outputCol="x")
scalerModel = scaler.fit(df)
scaledData = scalerModel.transform(df)

What if I have 100 columns? Is there any way to do min-max scaling for many columns in PySpark?

Update:

Also, how to apply MinMaxScalar on integer or double values? It throws the following error:

java.lang.IllegalArgumentException: requirement failed: Column length must be of type struct<type:tinyint,size:int,indices:array<int>,values:array<double>> but was actually int.

Body:
Question 1:

How to change your example to run properly. You need to prepare the data as a vector for the transformers to work.

from pyspark.ml.feature import MinMaxScaler
from pyspark.ml import Pipeline
from pyspark.ml.linalg import VectorAssembler

pdf = pd.DataFrame({'x':range(3), 'y':[1,2,5], 'z':[100,200,1000]})
df = spark.createDataFrame(pdf)

assembler = VectorAssembler(inputCols=["x"], outputCol="x_vec")
scaler = MinMaxScaler(inputCol="x_vec", outputCol="x_scaled")
pipeline = Pipeline(stages=[assembler, scaler])
scalerModel = pipeline.fit(df)
scaledData = scalerModel.transform(df)

Question 2:

To run MinMaxScaler on multiple columns you can use a pipeline that receives a list of transformation prepared with with a list comprehension:

from pyspark.ml import Pipeline
from pyspark.ml.feature import MinMaxScaler
columns_to_scale = ["x", "y", "z"]
assemblers = [VectorAssembler(inputCols=[col], outputCol=col + "_vec") for col in columns_to_scale]
scalers = [MinMaxScaler(inputCol=col + "_vec", outputCol=col + "_scaled") for col in columns_to_scale]
pipeline = Pipeline(stages=assemblers + scalers)
scalerModel = pipeline.fit(df)
scaledData = scalerModel.transform(df)

Check this example pipeline in the official documentation.

Eventually, you will end with the results in this format:

>>> scaledData.printSchema()
root
 |-- x: long (nullable = true)
 |-- y: long (nullable = true)
 |-- z: long (nullable = true)
 |-- x_vec: vector (nullable = true)
 |-- y_vec: vector (nullable = true)
 |-- z_vec: vector (nullable = true)
 |-- x_scaled: vector (nullable = true)
 |-- y_scaled: vector (nullable = true)
 |-- z_scaled: vector (nullable = true)

>>> scaledData.show()
+---+---+----+-----+-----+--------+--------+--------+--------------------+
|  x|  y|   z|x_vec|y_vec|   z_vec|x_scaled|y_scaled|            z_scaled|
+---+---+----+-----+-----+--------+--------+--------+--------------------+
|  0|  1| 100|[0.0]|[1.0]| [100.0]|   [0.0]|   [0.0]|               [0.0]|
|  1|  2| 200|[1.0]|[2.0]| [200.0]|   [0.5]|  [0.25]|[0.1111111111111111]|
|  2|  5|1000|[2.0]|[5.0]|[1000.0]|   [1.0]|   [1.0]|               [1.0]|
+---+---+----+-----+-----+--------+--------+--------+--------------------+

Extra Post-processing:

You can recover the columns in their original names with some post-processing. For example:

from pyspark.sql import functions as f
names = {x + "_scaled": x for x in columns_to_scale}
scaledData = scaledData.select([f.col(c).alias(names[c]) for c in names.keys()])

The output will be:

scaledData.show()
+------+-----+--------------------+
|     y|    x|                   z|
+------+-----+--------------------+
| [0.0]|[0.0]|               [0.0]|
|[0.25]|[0.5]|[0.1111111111111111]|
| [1.0]|[1.0]|               [1.0]|
+------+-----+--------------------+


问:
JavaScript conditonal statement behaving differently
I have an endpoint localhost:3000/users/add and localhost:3000/users/login. When a user logs in the server returns a Jsonwebtoken with two properties in the following format: user: { username: 'user_name', access_level: 4 }. I then have an auth custom middleware that validates the access_level of the user and I use it to protect localhost:3000/users/add. The route then looks as follows:

router.js:

```<code>router.post('/add', auth, async (req, res, next) => {
    // get user input
    const user = req.body;
    try {
        const data = await Helper.validateUserInput(user)

        // encrypt password
        const hash = await Helper.encryptPassword(data.value.password)
        if(hash) {
            const databaseUser = new User({
                'username': data.value.username,
                'password': hash,
                'access_level': data.value.access_level
            });
            // persist to database
            const saved = await databaseUser.save();
            console.log(saved);
            res.status(200).json({success: true, message: `User successfully added`})

        }

    }
    // if there's an error
    catch(error){
        if(error.hasOwnProperty('code')) {
            const error_code = error.code;
            if(error_code === 11000) {
                return res.status(400).json({
                    success: false,
                    error_message: error.errmsg
                })
            }else {
                return res.status(500).json({
                    success: false,
                    error: error
                })
            }
        }
    }
});
</code>```

The auth middleware function is as follows:

auth.js:

```<code>const Helper = require('../helpers/helpers')

module.exports = function async (req, res, next) {
    const token = req.query.token;
    if(!token) {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    }
    Helper.verify_token(token)
    .then((user) => {
        const { access_level } = user.user;
        console.log(access_level)
        if(access_level != 4) {
            res.status(401).json ({
                success: false,
                error_message: `Unauthorized - Invalid credentials!`
            })
        }else {
            next()
        }
    })
    .catch((err) => {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    })
}
</code>```

I then try to access the protected route and Postman just hangs and does not give a response. What is strange though is that if I change the if statement in auth.jseg:

```<code>if(access_level != 1) {
   res.status(401).json ({
      success: false,
         error_message: `Unauthorized - Invalid credentials!`
      })
   }else {
     next()
 }
</code>```

everything works fine. I really don't understand what the issue is here.

答:
Chane the add function

```<code>router.post('/add', auth, async (req, res, next) => {
    // get user input
    const user = req.body;
    try {
        const data = await Helper.validateUserInput(user)

        // encrypt password
        const hash = await Helper.encryptPassword(data.value.password)
        if (hash) {
            const databaseUser = new User({
                'username': data.value.username,
                'password': hash,
                'access_level': data.value.access_level
            });
            // persist to database
            const saved = await databaseUser.save();
            console.log(saved);
            return res.status(200).json({ success: true, message: `User successfully added` })
        } else {
            return res.status(500).json({
                success: false,
                error: "Please try again"
            })
        }

    }
    // if there's an error
    catch (error) {
        if (error.hasOwnProperty('code')) {
            const error_code = error.code;
            if (error_code === 11000) {
                return res.status(400).json({
                    success: false,
                    error_message: error.errmsg
                })
            } else {
                return res.status(500).json({
                    success: false,
                    error: error
                })
            }
        }
        else {
            return res.status(500).json({
                success: false,
                error: error
            })
        }
    }
});
</code>```

And change the auth middleware

```<code>const Helper = require('../helpers/helpers')

module.exports = function async (req, res, next) {
    const token = req.query.token;
    if(!token) {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    }
   else{
    Helper.verify_token(token)
    .then((user) => {
        const { access_level } = user.user;
        console.log(access_level)
        if(access_level != 4) {
            res.status(401).json ({
                success: false,
                error_message: `Unauthorized - Invalid credentials!`
            })
        }else {
            next()
        }
    })
    .catch((err) => {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    })
  }
}
</code>```

Body:
I have an endpoint localhost:3000/users/add and localhost:3000/users/login. When a user logs in the server returns a Jsonwebtoken with two properties in the following format: user: { username: 'user_name', access_level: 4 }. I then have an auth custom middleware that validates the access_level of the user and I use it to protect localhost:3000/users/add. The route then looks as follows:

router.js:

router.post('/add', auth, async (req, res, next) => {
    // get user input
    const user = req.body;
    try {
        const data = await Helper.validateUserInput(user)

        // encrypt password
        const hash = await Helper.encryptPassword(data.value.password)
        if(hash) {
            const databaseUser = new User({
                'username': data.value.username,
                'password': hash,
                'access_level': data.value.access_level
            });
            // persist to database
            const saved = await databaseUser.save();
            console.log(saved);
            res.status(200).json({success: true, message: `User successfully added`})

        }

    }
    // if there's an error
    catch(error){
        if(error.hasOwnProperty('code')) {
            const error_code = error.code;
            if(error_code === 11000) {
                return res.status(400).json({
                    success: false,
                    error_message: error.errmsg
                })
            }else {
                return res.status(500).json({
                    success: false,
                    error: error
                })
            }
        }
    }
});

The auth middleware function is as follows:

auth.js:

const Helper = require('../helpers/helpers')

module.exports = function async (req, res, next) {
    const token = req.query.token;
    if(!token) {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    }
    Helper.verify_token(token)
    .then((user) => {
        const { access_level } = user.user;
        console.log(access_level)
        if(access_level != 4) {
            res.status(401).json ({
                success: false,
                error_message: `Unauthorized - Invalid credentials!`
            })
        }else {
            next()
        }
    })
    .catch((err) => {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    })
}

I then try to access the protected route and Postman just hangs and does not give a response. What is strange though is that if I change the if statement in auth.jseg:

if(access_level != 1) {
   res.status(401).json ({
      success: false,
         error_message: `Unauthorized - Invalid credentials!`
      })
   }else {
     next()
 }

everything works fine. I really don't understand what the issue is here.

Body:
Chane the add function

router.post('/add', auth, async (req, res, next) => {
    // get user input
    const user = req.body;
    try {
        const data = await Helper.validateUserInput(user)

        // encrypt password
        const hash = await Helper.encryptPassword(data.value.password)
        if (hash) {
            const databaseUser = new User({
                'username': data.value.username,
                'password': hash,
                'access_level': data.value.access_level
            });
            // persist to database
            const saved = await databaseUser.save();
            console.log(saved);
            return res.status(200).json({ success: true, message: `User successfully added` })
        } else {
            return res.status(500).json({
                success: false,
                error: "Please try again"
            })
        }

    }
    // if there's an error
    catch (error) {
        if (error.hasOwnProperty('code')) {
            const error_code = error.code;
            if (error_code === 11000) {
                return res.status(400).json({
                    success: false,
                    error_message: error.errmsg
                })
            } else {
                return res.status(500).json({
                    success: false,
                    error: error
                })
            }
        }
        else {
            return res.status(500).json({
                success: false,
                error: error
            })
        }
    }
});

And change the auth middleware

const Helper = require('../helpers/helpers')

module.exports = function async (req, res, next) {
    const token = req.query.token;
    if(!token) {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    }
   else{
    Helper.verify_token(token)
    .then((user) => {
        const { access_level } = user.user;
        console.log(access_level)
        if(access_level != 4) {
            res.status(401).json ({
                success: false,
                error_message: `Unauthorized - Invalid credentials!`
            })
        }else {
            next()
        }
    })
    .catch((err) => {
        res.status(403).json({
            success: false,
            error_message: `Forbiden - Invalid credentials!`
        })
    })
  }
}