问:
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>```

答:
Pass context to Glide like this:</p>

```<code>Glide.with(holder.itemView.getContext()).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);
</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:
Pass context to Glide like this:

Glide.with(holder.itemView.getContext()).load(completos.get(position).getFoto1()).apply(requestOptions1).into(((ViewHolderBicicletas) holder).imageViewFoto);


来源: stackexchange

问:
How to use custom font path in tkinter? Windows ONLY
i want to use a font that is in the same directory with my python program but actually python will search windows fonts folder for it, how should i fix it?

(i want to give my program the font path or import the font to use it in my labels)

for e.g :
here if the font myfont located in fonts folder my program will work but if not , it will be shown by the default font.

from tkinter import *
root = Tk()
my_lab = Label(root,font=("myfont" ,10 )).place(x=1,y=1)

i have use font=(f"path/to/font",10) but it doesnt work

答:
Question: How to use custom font path in tkinter? Windows ONLY

Reference:

SO:Answer - Truly custom font in Tkinter

def loadfont(fontpath, private=True, enumerable=False)

Change the function to Python 3:

```<code>def loadfont(fontpath, private=True, enumerable=False):
    ...

    # For 3.x, you have to convert the isinstance checks to bytes and str

    if isinstance(fontpath, bytes):
        pathbuf = create_string_buffer(fontpath)
        AddFontResourceEx = windll.gdi32.AddFontResourceExA

    elif isinstance(fontpath, str):
        pathbuf = create_unicode_buffer(fontpath)
        AddFontResourceEx = windll.gdi32.AddFontResourceExW
    ...
</code>```

Try variants of the arguments private=False, enumerable=True and make sure you  have entered the font name correctly.

Run the function loadfont(...), like:

```<code>loadfont("path//to//font.ttf", private=False, enumerable=True)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Question: How to use custom font path in tkinter? Windows ONLY

Reference:

SO:Answer - Truly custom font in Tkinter

def loadfont(fontpath, private=True, enumerable=False)

Change the function to Python 3:

def loadfont(fontpath, private=True, enumerable=False):
    ...

    # For 3.x, you have to convert the isinstance checks to bytes and str

    if isinstance(fontpath, bytes):
        pathbuf = create_string_buffer(fontpath)
        AddFontResourceEx = windll.gdi32.AddFontResourceExA

    elif isinstance(fontpath, str):
        pathbuf = create_unicode_buffer(fontpath)
        AddFontResourceEx = windll.gdi32.AddFontResourceExW
    ...

Try variants of the arguments private=False, enumerable=True and make sure you  have entered the font name correctly.

Run the function loadfont(...), like:

loadfont("path//to//font.ttf", private=False, enumerable=True)


问:
Immer data not updating in Vue
I'm trying to use Immer with Vue.  It appears that the state is updating, but Vue isn't updating the UI

// immutable.js
import produce, { applyPatches } from "immer"

let undo_buffer = []
export var state = { items: [] }
const handle_add_patch = (patch, inverse_patches) => {
  console.log("Inverse Patches: ", inverse_patches)
  undo_buffer.push(inverse_patches)
}
export const add_item = (item_name) => {
  console.log("Starting add_item call")
  const next_state = produce(
    state,
    draft => {
      draft.items.push({ name: item_name })
    },
    handle_add_patch
  )
  console.log("next state: ", next_state)
  state = next_state
}
export const undo = () => {
  const undo_patch = undo_buffer.pop()
  if (!undo_patch) return
  let new_state = applyPatches(state, undo_patch)
  console.log("New State: ", new_state)
  state = new_state
}
```

<pre class="lang-html prettyprint-override"><code><!-- item_list.Vue -->
<template>
  <div>
    <button @click.prevent="add_item()">Add Item</button>
      {{ items }}
    <button @click.prevent="undo()">Undo</button>
  </div>
</template>
<script>
import * as immutable from './immutable.js'
export default {
  computed: {
    items: function(){ return immutable.state.items }
  },
  methods: {
    add_item(){
      console.log("State Before: ", immutable.state)
      immutable.add_item("Hello")
      console.log("State After: ", immutable.state)
    },
    undo(){
      console.log("State Before: ", immutable.state)
      immutable.undo()
      console.log("State After: ", immutable.state)
    }
  }
}
</script>
</code>```

The console.log shows that the items array is changing, but the items in the Vue template just shows an empty array.  How can I make this visible within Vue?

答:
This issue is not related with Immer. vuejs caches the computed properties hence they do not update when your data updates. This is mentioned clearly in vuejs docs at https://v2.vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

Instead of a computed property, we can define the same function as a
method. For the end result, the two approaches are indeed exactly the
same. However, the difference is that computed properties are cached
based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.

Since Immer is not a reactive dependency, the computed property never runs again.

Solution for this would be to change the computed property to a method. This way it will not be cached and the method will run each time with updated value.

Title: Immer data not updating in Vue

Body:
I'm trying to use Immer with Vue.  It appears that the state is updating, but Vue isn't updating the UI

// immutable.js
import produce, { applyPatches } from "immer"

let undo_buffer = []
export var state = { items: [] }
const handle_add_patch = (patch, inverse_patches) => {
  console.log("Inverse Patches: ", inverse_patches)
  undo_buffer.push(inverse_patches)
}
export const add_item = (item_name) => {
  console.log("Starting add_item call")
  const next_state = produce(
    state,
    draft => {
      draft.items.push({ name: item_name })
    },
    handle_add_patch
  )
  console.log("next state: ", next_state)
  state = next_state
}
export const undo = () => {
  const undo_patch = undo_buffer.pop()
  if (!undo_patch) return
  let new_state = applyPatches(state, undo_patch)
  console.log("New State: ", new_state)
  state = new_state
}

<template>

    <button @click.prevent="add_item()">Add Item</button>
      {{ items }}
    <button @click.prevent="undo()">Undo</button>

</template>

The console.log shows that the items array is changing, but the items in the Vue template just shows an empty array.  How can I make this visible within Vue?


问:
Convert INT to VARCHAR SQL
I am using Sybase and I am doing a select which returns me a column called "iftype", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:

Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed.  Use the CONVERT function to run this query.

I dont know how to implement the function CONVERT. Can anyone help me, please ?

答:
CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

```<code>SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert INT to VARCHAR SQL

Body:
CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.

SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName


问:
pandas dataframe's `apply` slow when applied on index
I have a pandas dataframe df with an index of type DatetimeIndex with parameters: dtype='datetime64[ns]', name='DateTime', length=324336, freq=None. The dataframe has 22 columns, all numerical.
I want to create a new column Date with only the date-part of DateTime (to be used for grouping later).

My first attempt

df['Date'] = df.apply(lambda row: row.name.date(), axis=1)
```

<p>takes ca. 13.5 seconds.
But when I make <code>DateTime</code> a regular column, it goes faster, even including the index operations:</p>

<pre class="lang-py prettyprint-override"><code>df.reset_index(inplace=True)
df['Date'] = df.apply(lambda row: row['DateTime'].date(), axis=1)
df.set_index('DateTime')
</code>```

This takes ca. 6.3 s, i.e., it is twice as fast. Furthermore, applying apply directly on the series (since it depends only on one column) is faster still:

df.reset_index(inplace=True)
df['Date'] = df['DateTime'].apply(lambda dt: dt.date())
df.set_index('DateTime')
```

takes ca. 1.1 s, more than 10 times faster than the original solution.

This brings me to my questions:

Is applying apply on a series generally faster than doing it on the dataframe?

Is using apply on an index generally slower than on columns?

More general: what is the advantage of keeping a column as an index? Or, conversely, what would I loose by resetting the index before doing any operations?

Finally, is there an even better/faster way of adding the column?

答:
Use DatetimeIndex.date what should be faster solution:

```<code>df['Date'] = df.index.date
</code>```

Is applying apply on a series generally faster than doing it on the dataframe?

  Is using apply on an index generally slower than on columns

I think apply are loops under the hood, so it is obviously slowier like pandas methods

More general: what is the advantage of keeping a column as an index? Or, conversely, what would I loose by resetting the index before doing any operations?

You can check this:

Identifies data (i.e. provides metadata) using known indicators, important for analysis, visualization, and interactive console display.

  Enables automatic and explicit data alignment.

  Allows intuitive getting and setting of subsets of the data set.

Also if working time timeseries there are many methods like resample working with DatetimeIndex, also is possible use indexing with DatetimeIndex.

Body:
I have a pandas dataframe df with an index of type DatetimeIndex with parameters: dtype='datetime64[ns]', name='DateTime', length=324336, freq=None. The dataframe has 22 columns, all numerical.
I want to create a new column Date with only the date-part of DateTime (to be used for grouping later).

My first attempt

df['Date'] = df.apply(lambda row: row.name.date(), axis=1)

takes ca. 13.5 seconds.
But when I make DateTime a regular column, it goes faster, even including the index operations:

df.reset_index(inplace=True)
df['Date'] = df.apply(lambda row: row['DateTime'].date(), axis=1)
df.set_index('DateTime')

This takes ca. 6.3 s, i.e., it is twice as fast. Furthermore, applying apply directly on the series (since it depends only on one column) is faster still:

df.reset_index(inplace=True)
df['Date'] = df['DateTime'].apply(lambda dt: dt.date())
df.set_index('DateTime')

takes ca. 1.1 s, more than 10 times faster than the original solution.

This brings me to my questions:

Is applying apply on a series generally faster than doing it on the dataframe?

Is using apply on an index generally slower than on columns?

More general: what is the advantage of keeping a column as an index? Or, conversely, what would I loose by resetting the index before doing any operations?

Finally, is there an even better/faster way of adding the column?

Body:
Use DatetimeIndex.date what should be faster solution:

df['Date'] = df.index.date

Is applying apply on a series generally faster than doing it on the dataframe?

  Is using apply on an index generally slower than on columns

I think apply are loops under the hood, so it is obviously slowier like pandas methods

More general: what is the advantage of keeping a column as an index? Or, conversely, what would I loose by resetting the index before doing any operations?

You can check this:

Identifies data (i.e. provides metadata) using known indicators, important for analysis, visualization, and interactive console display.

  Enables automatic and explicit data alignment.

  Allows intuitive getting and setting of subsets of the data set.

Also if working time timeseries there are many methods like resample working with DatetimeIndex, also is possible use indexing with DatetimeIndex.


问:
Can't edit files in Vscode
I've just started using Vscode and have a created a WebAPI project. On trying to open any of the default code files (Startup.cs and Program.cs) whatever I type starts to appear in the blue bar as shown below instead of where I have placed the cursor. I have no idea what's going on or what that blue bar is.

I am able to add my own code files and edit these as I would expect.

I'm running Vscode 1.29.1 on Win 10 on a Dell Latitude 12 7275. The vscode extension

Enabled extensions :

答:
I'l leave this here for future readers

Basically, if I split files in tabs in VS Code, I could work with the files on the left hand side but could "read-only" all the files on the right hand side.

When I went to the extensions tabs I noticed that whatever I typed was being typed in the field in the extensions search bar. After deleting that, and clicking back on the "Files" tab, it went back to normal and can basically edit files on the both sides of my split screen.

If cannot type

Check where whatever you type is going (e.g. Extensions > Search bar)

Delete wherever it's being typed, and click back on the "Files tab"

Check if it works

Title: Can't edit files in Vscode


问:
How to scrape text from tables with the same class attribute?
I'm trying to scrape customer reviews on flights from airline quality.com and I'm running into a problem, as in the flights information all of the lines have the same 'review-value' class. I'm trying to solve it in the following way, usually all the comments have the same 4 flight description, except for the aircraft, which only appears in some. So, I did a if to determine that if there's no aircraft, then just append the next 'review-value', however, it's not working. Can you guys help me? The code can be found below:</p>

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd
from datetime import datetime

myProxy = {
            "http"  : "http://10.120.118.49:8080",
            "https"  : "https://10.120.118.49:8080"
            }

headers={'User-agent' : 'Mozilla/5.0'}

title_of_review=[]
details_about=[]
review_text=[]
type_of_traveller=[]
seat_type=[]
route_flown=[]
date_flown=[]
aircraft_flown=[]

url='https://www.airlinequality.com/airline-reviews/air-france/page/4/?sortby=post_date%3ADesc&pagesize=100'

page1 = requests.get(url, proxies=myProxy, headers=headers)
soup1 = BeautifulSoup(page1.text, 'lxml')
page1.close()

for review in soup1.findAll('div', attrs={'class': "body"}):
    title=review.find('h2', attrs={'class': "text_header"})
    if title is not None:
        title_of_review.append(title.text)
    else:
        title_of_review.append('')

    details=review.find('h3', attrs={'class': "text_sub_header userStatusWrapper"})
    if details is not None:
        details_about.append(details.text)
    else:
        details_about.append('')

    texto=review.find('div', attrs={'class': "text_content"})
    if texto is not None:
        review_text.append(texto.text.strip('✅ Verified Review |').strip('\r\n\r\n'))
    else:
        review_text.append('')

    aircrafts=review.findAll('td', attrs={'class': "review-rating-header aircraft"})
    #print(aircrafts)
    all_reviews=review.findAll('td', attrs={'class': "review-value"})
    aircraft=all_reviews[0]
    if aircrafts is None:
        aircraft_flown.append('')
    else:
        aircraft_flown.append(aircraft.text)
</code>```

答:
You can parse that table using pandas. The tricky part is the rating elements with multiple tags and attributes. But not to hard to remove the class "fill" and figure out the rating given. Here's a table of the output:

```<code>from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
from datetime import datetime

myProxy = {
            "http"  : "http://10.120.118.49:8080",
            "https"  : "https://10.120.118.49:8080"
            }

headers={'User-agent' : 'Mozilla/5.0'}

results_df = pd.DataFrame()
colsList = ['Aircraft', 'Type Of Traveller', 'Seat Type', 'Route', 'Date Flown',
            'Seat Comfort', 'Cabin Staff Service', 'Food & Beverages',
            'Inflight Entertainment', 'Ground Service', 'Value For Money,', 'Recommended']
url='https://www.airlinequality.com/airline-reviews/air-france/page/4/?sortby=post_date%3ADesc&pagesize=100'

page1 = requests.get(url, headers=headers)
soup1 = BeautifulSoup(page1.text, 'html.parser')
page1.close()

reviews = soup1.findAll('div', attrs={'class': "body"})
for review in reviews:
    for span in review.find_all("span", {'class':'star fill'}):
        span.decompose()

    title=review.find('h2', attrs={'class': "text_header"})
    if title is not None:
        title_of_review = title.text.strip()
    else:
        title_of_review = ''

    details=review.find('h3', attrs={'class': "text_sub_header userStatusWrapper"})
    if details is not None:
        details_about = details.text.strip()
    else:
        details_about = ''

    texto=review.find('div', attrs={'class': "text_content"})
    if texto is not None:
        review_text = texto.text.strip('✅ Verified Review |').strip('\r\n\r\n')
    else:
        review_text = ''

    temp_df_alpha = pd.DataFrame([[title_of_review, details_about, review_text]], columns=['Title','Details','Text'])

    temp_df_beta = pd.read_html(str(review))[0].T
    new_header = list(temp_df_beta.iloc[0])
    temp_df_beta = temp_df_beta[1:]
    temp_df_beta.columns = new_header
    cols = [ col for col in new_header if col in colsList]
    temp_df_beta = temp_df_beta[cols]

    temp_df = temp_df_alpha.merge(temp_df_beta.reset_index(drop=True), how='left', left_index=True, right_index=True)
    rateCols = ['Seat Comfort', 'Cabin Staff Service', 'Food & Beverages',
            'Inflight Entertainment', 'Ground Service', 'Value For Money']

    for col in rateCols:
        if col in temp_df.columns:
            try:
                temp_df[col] = int(temp_df.iloc[0][col][0]) - 1
            except:
                temp_df[col] = 5

    results_df = results_df.append(temp_df, sort=False).reset_index(drop=True)
</code>```

Output:

```<code>print (results_df.to_string())
                                              Title                                            Details                                               Text Type Of Traveller        Seat Type                                     Route      Date Flown  Seat Comfort  Cabin Staff Service  Food & Beverages  Inflight Entertainment  Ground Service Recommended                 Aircraft
0                          "I would fly them again"  1 reviews\n\n\n\nPeter-John de Kock (South Afr...  Trip Verified |  Cape Town to Los Angeles via ...          Business    Economy Class    Cape Town to Los Angeles via Paris CDG   December 2017           2.0                  3.0               3.0                     2.0             4.0         yes                      NaN
1               "service on board was just average"             Wenyu Zhao (France) 14th December 2017  Trip Verified | Flew Air France from Sydney to...      Solo Leisure    Economy Class          Sydney to Paris CDG via Shanghai     August 2017           3.0                  2.0               4.0                     3.0             2.0          no                      NaN
2                  "Enjoyed flying with Air France"      G Lamille (United Kingdom) 14th December 2017  Trip Verified |  Enjoyed flying with Air Franc...      Solo Leisure    Economy Class                        Paris to Vancouver    October 2017           5.0                  5.0               5.0                     5.0             4.0         yes         Boeing 777-200ER
3             "AF spreading this busline of theirs"       M Stanton (United States) 14th December 2017  Trip Verified |  Barcelona to Paris CDG. Ticke...          Business    Economy Class                    Barcelona to Paris CDG   December 2017           3.0                  3.0               1.0                     1.0             4.0          no                     A320
4                        "a good flying experience"  8 reviews\n\n\n\nS Lacey (United Kingdom) 12th...  Trip Verified | I had a pleasant flight with A...      Solo Leisure    Economy Class                      Hamburg to Paris CDG      March 2017           3.0                  4.0               4.0                     NaN             5.0         yes                A319/A320
5                   "horrible start to the holiday"    Luke Johnson (United Kingdom) 9th December 2017  Trip Verified | Flew Air France from London He...    Family Leisure    Economy Class    London Heathrow to Mauritius via Paris   December 2017           3.0                  3.0               2.0                     3.0             2.0          no                      NaN
6                      "it was Air France at fault"      Philip Jelovsek (Australia) 3rd December 2017  Trip Verified |  Paris to Abu Dhabi. My flight...      Solo Leisure    Economy Class                        Paris to Abu Dhabi   November 2017           NaN                  NaN               NaN                     NaN             1.0          no                      NaN
7         "not sure I will travel Air France again"  Luciana Queiroz (United States) 3rd December 2017  Trip Verified |  Nice to Paris. One person in ...    Family Leisure    Economy Class                             Nice to Paris   December 2017           1.0                  5.0               NaN                     NaN             1.0          no                      NaN
8                          "such a poor experience"       Francesco Lucchese (Italy) 2nd December 2017  Trip Verified | Bogota to Rome via Paris. It's...      Solo Leisure    Economy Class                  Bogota to Rome via Paris   November 2017           3.0                  1.0               3.0                     1.0             1.0          no                      NaN
9                        "Ridiculous and insulting"  25 reviews\n\n\n\nS Robinson (Austria) 1st Dec...  Trip Verified | Vienna - Paris CDG - London He...    Couple Leisure    Economy Class   Vienna to London Heathrow via Paris CDG   December 2016           4.0                  3.0               3.0                     NaN             1.0          no                      NaN
10             "experience very poor and stressful"          T Cody (United States) 25th November 2017  Trip Verified |  Air France accidentally cance...    Family Leisure    Economy Class            Barcelona to Atlanta via Paris    October 2017           1.0                  1.0               NaN                     NaN             1.0          no                      NaN
11                   "cabin staff were much better"  2 reviews\n\n\n\nSalal Bajwa (United Arab Emir...  Trip Verified |  London to Paris. Check in was...    Family Leisure    Economy Class                           London to Paris       June 2017           4.0                  5.0               4.0                     5.0             1.0         yes             Boeing 787-9
</code>```

Body:
I'm trying to scrape customer reviews on flights from airline quality.com and I'm running into a problem, as in the flights information all of the lines have the same 'review-value' class. I'm trying to solve it in the following way, usually all the comments have the same 4 flight description, except for the aircraft, which only appears in some. So, I did a if to determine that if there's no aircraft, then just append the next 'review-value', however, it's not working. Can you guys help me? The code can be found below:

from bs4 import BeautifulSoup
import requests
import pandas as pd
from datetime import datetime

myProxy = {
            "http"  : "http://10.120.118.49:8080",
            "https"  : "https://10.120.118.49:8080"
            }

headers={'User-agent' : 'Mozilla/5.0'}

title_of_review=[]
details_about=[]
review_text=[]
type_of_traveller=[]
seat_type=[]
route_flown=[]
date_flown=[]
aircraft_flown=[]

url='https://www.airlinequality.com/airline-reviews/air-france/page/4/?sortby=post_date%3ADesc&pagesize=100'

page1 = requests.get(url, proxies=myProxy, headers=headers)
soup1 = BeautifulSoup(page1.text, 'lxml')
page1.close()

for review in soup1.findAll('div', attrs={'class': "body"}):
    title=review.find('h2', attrs={'class': "text_header"})
    if title is not None:
        title_of_review.append(title.text)
    else:
        title_of_review.append('')

    details=review.find('h3', attrs={'class': "text_sub_header userStatusWrapper"})
    if details is not None:
        details_about.append(details.text)
    else:
        details_about.append('')

    texto=review.find('div', attrs={'class': "text_content"})
    if texto is not None:
        review_text.append(texto.text.strip('✅ Verified Review |').strip('\r\n\r\n'))
    else:
        review_text.append('')

    aircrafts=review.findAll('td', attrs={'class': "review-rating-header aircraft"})
    #print(aircrafts)
    all_reviews=review.findAll('td', attrs={'class': "review-value"})
    aircraft=all_reviews[0]
    if aircrafts is None:
        aircraft_flown.append('')
    else:
        aircraft_flown.append(aircraft.text)

Body:
You can parse that table using pandas. The tricky part is the rating elements with multiple tags and attributes. But not to hard to remove the class "fill" and figure out the rating given. Here's a table of the output:

from bs4 import BeautifulSoup
import requests
import pandas as pd
import numpy as np
from datetime import datetime

myProxy = {
            "http"  : "http://10.120.118.49:8080",
            "https"  : "https://10.120.118.49:8080"
            }

headers={'User-agent' : 'Mozilla/5.0'}

results_df = pd.DataFrame()
colsList = ['Aircraft', 'Type Of Traveller', 'Seat Type', 'Route', 'Date Flown',
            'Seat Comfort', 'Cabin Staff Service', 'Food & Beverages',
            'Inflight Entertainment', 'Ground Service', 'Value For Money,', 'Recommended']
url='https://www.airlinequality.com/airline-reviews/air-france/page/4/?sortby=post_date%3ADesc&pagesize=100'

page1 = requests.get(url, headers=headers)
soup1 = BeautifulSoup(page1.text, 'html.parser')
page1.close()

reviews = soup1.findAll('div', attrs={'class': "body"})
for review in reviews:
    for span in review.find_all("span", {'class':'star fill'}):
        span.decompose()

    title=review.find('h2', attrs={'class': "text_header"})
    if title is not None:
        title_of_review = title.text.strip()
    else:
        title_of_review = ''

    details=review.find('h3', attrs={'class': "text_sub_header userStatusWrapper"})
    if details is not None:
        details_about = details.text.strip()
    else:
        details_about = ''

    texto=review.find('div', attrs={'class': "text_content"})
    if texto is not None:
        review_text = texto.text.strip('✅ Verified Review |').strip('\r\n\r\n')
    else:
        review_text = ''

    temp_df_alpha = pd.DataFrame([[title_of_review, details_about, review_text]], columns=['Title','Details','Text'])

    temp_df_beta = pd.read_html(str(review))[0].T
    new_header = list(temp_df_beta.iloc[0])
    temp_df_beta = temp_df_beta[1:]
    temp_df_beta.columns = new_header
    cols = [ col for col in new_header if col in colsList]
    temp_df_beta = temp_df_beta[cols]

    temp_df = temp_df_alpha.merge(temp_df_beta.reset_index(drop=True), how='left', left_index=True, right_index=True)
    rateCols = ['Seat Comfort', 'Cabin Staff Service', 'Food & Beverages',
            'Inflight Entertainment', 'Ground Service', 'Value For Money']

    for col in rateCols:
        if col in temp_df.columns:
            try:
                temp_df[col] = int(temp_df.iloc[0][col][0]) - 1
            except:
                temp_df[col] = 5

    results_df = results_df.append(temp_df, sort=False).reset_index(drop=True)

Output:

print (results_df.to_string())
                                              Title                                            Details                                               Text Type Of Traveller        Seat Type                                     Route      Date Flown  Seat Comfort  Cabin Staff Service  Food & Beverages  Inflight Entertainment  Ground Service Recommended                 Aircraft
0                          "I would fly them again"  1 reviews\n\n\n\nPeter-John de Kock (South Afr...  Trip Verified |  Cape Town to Los Angeles via ...          Business    Economy Class    Cape Town to Los Angeles via Paris CDG   December 2017           2.0                  3.0               3.0                     2.0             4.0         yes                      NaN
1               "service on board was just average"             Wenyu Zhao (France) 14th December 2017  Trip Verified | Flew Air France from Sydney to...      Solo Leisure    Economy Class          Sydney to Paris CDG via Shanghai     August 2017           3.0                  2.0               4.0                     3.0             2.0          no                      NaN
2                  "Enjoyed flying with Air France"      G Lamille (United Kingdom) 14th December 2017  Trip Verified |  Enjoyed flying with Air Franc...      Solo Leisure    Economy Class                        Paris to Vancouver    October 2017           5.0                  5.0               5.0                     5.0             4.0         yes         Boeing 777-200ER
3             "AF spreading this busline of theirs"       M Stanton (United States) 14th December 2017  Trip Verified |  Barcelona to Paris CDG. Ticke...          Business    Economy Class                    Barcelona to Paris CDG   December 2017           3.0                  3.0               1.0                     1.0             4.0          no                     A320
4                        "a good flying experience"  8 reviews\n\n\n\nS Lacey (United Kingdom) 12th...  Trip Verified | I had a pleasant flight with A...      Solo Leisure    Economy Class                      Hamburg to Paris CDG      March 2017           3.0                  4.0               4.0                     NaN             5.0         yes                A319/A320
5                   "horrible start to the holiday"    Luke Johnson (United Kingdom) 9th December 2017  Trip Verified | Flew Air France from London He...    Family Leisure    Economy Class    London Heathrow to Mauritius via Paris   December 2017           3.0                  3.0               2.0                     3.0             2.0          no                      NaN
6                      "it was Air France at fault"      Philip Jelovsek (Australia) 3rd December 2017  Trip Verified |  Paris to Abu Dhabi. My flight...      Solo Leisure    Economy Class                        Paris to Abu Dhabi   November 2017           NaN                  NaN               NaN                     NaN             1.0          no                      NaN
7         "not sure I will travel Air France again"  Luciana Queiroz (United States) 3rd December 2017  Trip Verified |  Nice to Paris. One person in ...    Family Leisure    Economy Class                             Nice to Paris   December 2017           1.0                  5.0               NaN                     NaN             1.0          no                      NaN
8                          "such a poor experience"       Francesco Lucchese (Italy) 2nd December 2017  Trip Verified | Bogota to Rome via Paris. It's...      Solo Leisure    Economy Class                  Bogota to Rome via Paris   November 2017           3.0                  1.0               3.0                     1.0             1.0          no                      NaN
9                        "Ridiculous and insulting"  25 reviews\n\n\n\nS Robinson (Austria) 1st Dec...  Trip Verified | Vienna - Paris CDG - London He...    Couple Leisure    Economy Class   Vienna to London Heathrow via Paris CDG   December 2016           4.0                  3.0               3.0                     NaN             1.0          no                      NaN
10             "experience very poor and stressful"          T Cody (United States) 25th November 2017  Trip Verified |  Air France accidentally cance...    Family Leisure    Economy Class            Barcelona to Atlanta via Paris    October 2017           1.0                  1.0               NaN                     NaN             1.0          no                      NaN
11                   "cabin staff were much better"  2 reviews\n\n\n\nSalal Bajwa (United Arab Emir...  Trip Verified |  London to Paris. Check in was...    Family Leisure    Economy Class                           London to Paris       June 2017           4.0                  5.0               4.0                     5.0             1.0         yes             Boeing 787-9


问:
How to mock clock.millis() in Java
I have a code where I calculate the difference between current clock time and time saved in my db
If difference between the two is greater than certain value then I return result accordingly.
For this case I am trying to write test but is facing problem to mock Clock.millis(). I have referred some answers but none worked for me can someone help me with that.

For my test I want to mock this clock.millis() function with a fixed value so that each time I run test it takes that value only.

答:
A Clock is meant for providing access to the current instant, date and time using a time-zone. You don't really need to mock it. As your class needs to obtain the current instant, so it should receive an instance of the Clock in the constructor:

public class FooService {

    private final Clock clock;

    public FooService(Clock clock) {
        this.clock = clock;
    }

    public boolean isLocked() {
        long differenceInSecond = (clock.millis() - this.getLockedAt()) / 1000;
        return differenceInSecond < 7200;
    }

    private long getLockedAt() {
        ...
    }
}
```

<p>Then, in your test, you can use a <code>fixed()</code> clock, which will always return the same instant:</p>

<pre class="lang-java prettyprint-override"><code>@Test
public void isLocked_shouldReturnTrue_whenDifferenceInSecondIsSmallerThan7200() {

    // Create a fixed clock, which will always return the same instant
    Instant instant = Instant.parse("2020-01-01T00:00:00.00Z");
    Clock clock = Clock.fixed(instant, ZoneOffset.UTC);

    // Create a service instance with the fixed clock
    FooService fooService = new FooService(clock);

    // Invoke the service method and then assert the result
    boolean locked = fooService.isLocked();
    assertThat(locked).isTrue();
}
</code>```

In a Spring Boot application, you could expose a Clock as a @Bean:

@Bean
public Clock clock() {
    return Clock.systemDefaultZone();
}
```

<p>And then Spring will take care of injecting it into your service:</p>

<pre class="lang-java prettyprint-override"><code>@Service
public class FooService {

    private final Clock clock;

    public FooService(Clock clock) {
        this.clock = clock;
    }

    ...
}
</code>```

Title: How to mock clock.millis() in Java

Body:
A Clock is meant for providing access to the current instant, date and time using a time-zone. You don't really need to mock it. As your class needs to obtain the current instant, so it should receive an instance of the Clock in the constructor:

public class FooService {

    private final Clock clock;

    public FooService(Clock clock) {
        this.clock = clock;
    }

    public boolean isLocked() {
        long differenceInSecond = (clock.millis() - this.getLockedAt()) / 1000;
        return differenceInSecond < 7200;
    }

    private long getLockedAt() {
        ...
    }
}

Then, in your test, you can use a fixed() clock, which will always return the same instant:

@Test
public void isLocked_shouldReturnTrue_whenDifferenceInSecondIsSmallerThan7200() {

    // Create a fixed clock, which will always return the same instant
    Instant instant = Instant.parse("2020-01-01T00:00:00.00Z");
    Clock clock = Clock.fixed(instant, ZoneOffset.UTC);

    // Create a service instance with the fixed clock
    FooService fooService = new FooService(clock);

    // Invoke the service method and then assert the result
    boolean locked = fooService.isLocked();
    assertThat(locked).isTrue();
}

In a Spring Boot application, you could expose a Clock as a @Bean:

@Bean
public Clock clock() {
    return Clock.systemDefaultZone();
}

And then Spring will take care of injecting it into your service:

@Service
public class FooService {

    private final Clock clock;

    public FooService(Clock clock) {
        this.clock = clock;
    }

    ...
}


问:
How do I HTTP post stream data from memory in Ruby?
I would like to upload data I generated at runtime in Ruby, something like feeding the upload from a block.

All examples I found only show how to stream a file that must be on disk prior to the request but I do not want to buffer the file.

What is the best solution besides rolling my own socket connection?

This a pseudocode example:

```<code>post_stream('127.0.0.1', '/stream/') do |body|
  generate_xml do |segment|
    body << segment
  end
end
</code>```

答:
There's a Net::HTTPGenericRequest#body_stream=( obj.should respond_to?(:read) )

You use it more or less like this:

```<code>
class Producer
  def initialize
   @mutex = Mutex.new
   @body = ''
  end

  def read(size)
    @mutex.synchronize {
      @body.slice!(0,size)
    }
  end

  def produce(str)
    @mutex.synchronize {
      @body << str
    }
  end
end

# Create a producer thread

req = Net::HTTP::Post.new(url.path)
req.body_stream = producer
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
</code>```

Body:
I would like to upload data I generated at runtime in Ruby, something like feeding the upload from a block.

All examples I found only show how to stream a file that must be on disk prior to the request but I do not want to buffer the file.

What is the best solution besides rolling my own socket connection?

This a pseudocode example:

post_stream('127.0.0.1', '/stream/') do |body|
  generate_xml do |segment|
    body << segment
  end
end

Body:
There's a Net::HTTPGenericRequest#body_stream=( obj.should respond_to?(:read) )

You use it more or less like this:

class Producer
  def initialize
   @mutex = Mutex.new
   @body = ''
  end

  def read(size)
    @mutex.synchronize {
      @body.slice!(0,size)
    }
  end

  def produce(str)
    @mutex.synchronize {
      @body << str
    }
  end
end

# Create a producer thread

req = Net::HTTP::Post.new(url.path)
req.body_stream = producer
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }


问:
how to build docker image by docker-compose.yml
Here is my docker-compose.yml:

```<code>version: '2'
services:
web:
  build: .
  context: ./
  dockerfile: Dockerfile
  ports:
    - "8080:8080"
  container_name: demo
  volumes:
    - .:/images
</code>```

I got an error:

ERROR: The Compose file './docker-compose.yml' is invalid because:
  Unsupported config option for services.web: 'dockerfile'

So I would like to build the container and also run. I will have a few more containers to build and run. Is it possible by docker-compose?

答:
If I'm not mistaken the issue is after build you have a dot, the dockerfile and context are not correct idented. And I think the bar in the context should not be there.

```<code>version: "3.7"
services:
  api:
    image: image-name
    build:
      context: .
      dockerfile: path/to/Dockerfile
    container_name: container-name
</code>```

I think this resolves the issue you have, but couldn't test it.

Body:
Here is my docker-compose.yml:

version: '2'
services:
web:
  build: .
  context: ./
  dockerfile: Dockerfile
  ports:
    - "8080:8080"
  container_name: demo
  volumes:
    - .:/images

I got an error:

ERROR: The Compose file './docker-compose.yml' is invalid because:
  Unsupported config option for services.web: 'dockerfile'

So I would like to build the container and also run. I will have a few more containers to build and run. Is it possible by docker-compose?

Body:
If I'm not mistaken the issue is after build you have a dot, the dockerfile and context are not correct idented. And I think the bar in the context should not be there.

version: "3.7"
services:
  api:
    image: image-name
    build:
      context: .
      dockerfile: path/to/Dockerfile
    container_name: container-name

I think this resolves the issue you have, but couldn't test it.


问:
Infinite recursion ! how to convert?
I have following classes

```<code>class SomeClass{

    private String id;
    private String name;
    private List<SomeClass> history;

}
</code>```

```<code>class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;
}
</code>```

Now i want a method to convert this SomeClass Object to SomeClassDto.

答:
You can create a constructor in SomeClassDTO which takes SomeClass as a parameter and then do the conversion:

```<code>class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;

    public SomeClassDto(SomeClass someClass){
        this.name = someClass.getName();
        this.historyDto = new ArrayList<>();
        for(SomeClass sc: someClass.getHistory()){
            this.historyDto.add(new SomeClassDto(sc));
        }
    }
}
</code>```

Title: Infinite recursion ! how to convert?

Body:
I have following classes

class SomeClass{

    private String id;
    private String name;
    private List<SomeClass> history;

}

class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;
}

Now i want a method to convert this SomeClass Object to SomeClassDto.

Body:
You can create a constructor in SomeClassDTO which takes SomeClass as a parameter and then do the conversion:

class SomeClassDto{

    private String name;
    private List<SomeClassDto> historyDto;

    public SomeClassDto(SomeClass someClass){
        this.name = someClass.getName();
        this.historyDto = new ArrayList<>();
        for(SomeClass sc: someClass.getHistory()){
            this.historyDto.add(new SomeClassDto(sc));
        }
    }
}


问:
Floating QDockWidget resize - Change size of the resize handler/grip on the border
I have a simple Qt Mainwindow with a QDockWidget in it (Frameless Window).
Now when the QDockWidget is undocked it can be resized by clicking the border of it and drag to new size.

The problem is, that the border is only 1 or 2 pixels wide and it is almost impossible to catch it on a big high resolution screen.

Is there any way to set the size of the border that can be grabbed to more than 1 pixel?
(I do not want to use a QSizeGrip)

答:
Try :

```<code>QDockWidget > QWidget {
    border: 12px solid purple;
}
</code>```

Body:
Try :

QDockWidget > QWidget {
    border: 12px solid purple;
}


问:
How can you store a specific line from a file in an array in Groovy?
I am interested if there is a easy way to store a specific line from a file into an array in Groovy (i need it for GroovyAxis in Jenkins). The file would look like this:

```<code>var1="value1 value2 etc"

var2="a b etc"

var3="test1 test2 test3 etc"
</code>```

I would need test1 test2 test3 etc from var3 to be stored in an array. Right now i use this:

```<code>def words = []
new File( '/home/workstation/jenkins/params' ).eachLine { line ->
    words << line
}
</code>```

But it stores each line i have into an array, so i have to heavily workaround the config file to get the job done.

Thank you very much

答:
```<code>//cat /tmp/words.txt
//It's must be file Format
//SOME_DETAILS:1234-A0;1456-B1;2456-B0;3436-D0;4467-C0

stage("test"){

    def testArray=[]
    new File('/tmp/words.txt').splitEachLine("[:;]"){line->
        if(line[0]=='SOME_DETAILS')testArray=line[1..-1]
    }
    println testArray
}
</code>```

After Run it's Output you get

Body:
I am interested if there is a easy way to store a specific line from a file into an array in Groovy (i need it for GroovyAxis in Jenkins). The file would look like this:

var1="value1 value2 etc"

var2="a b etc"

var3="test1 test2 test3 etc"

I would need test1 test2 test3 etc from var3 to be stored in an array. Right now i use this:

def words = []
new File( '/home/workstation/jenkins/params' ).eachLine { line ->
    words << line
}

But it stores each line i have into an array, so i have to heavily workaround the config file to get the job done.

Thank you very much

Body:
//cat /tmp/words.txt
//It's must be file Format
//SOME_DETAILS:1234-A0;1456-B1;2456-B0;3436-D0;4467-C0

stage("test"){

    def testArray=[]
    new File('/tmp/words.txt').splitEachLine("[:;]"){line->
        if(line[0]=='SOME_DETAILS')testArray=line[1..-1]
    }
    println testArray
}

After Run it's Output you get


问:
Get Unix timestamp with C++
How do I get a uint unix timestamp in C++? I've googled a bit and it seems that most methods are looking for more convoluted ways to represent time. Can't I just get it as a uint?

答:
The most common advice is wrong, you can't just rely on time(). That's used for relative timing: ISO C++ doesn't specify that 1970-01-01T00:00Z is time_t(0)

What's worse is that you can't easily figure it out, either. Sure, you can find the calendar date of time_t(0) with gmtime, but what are you going to do if that's 2000-01-01T00:00Z ? How many seconds were there between 1970-01-01T00:00Z and 2000-01-01T00:00Z? It's certainly no multiple of 60, due to leap seconds.

Title: Get Unix timestamp with C++


问:
How to use stack navigation, drawer navigation and tab navigation simultaneously in react navigation v5
I'm looking to render the drawer navigation, tab navigation and stack navigation simultaneously in my app.
but I'm getting this error:

This is my root.js file content:

```<code>import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import {Like, Home, Search, Media, Profile, Direct, HeaderProfile, CustomDrawer } from './components/index';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createStackNavigator } from '@react-navigation/stack';
import { createDrawerNavigator } from '@react-navigation/drawer';
</code>```

This the tab navigation code:

```<code>const Tab =createMaterialTopTabNavigator();

const MyTabs=()=>{

return(

    <Tab.Navigator>
    <Tab.Screen name="Home" component={Home}/>
    <Tab.Screen name="Search" component={Search} />
    <Tab.Screen name="Media" component={Media} />
    <Tab.Screen name="Like" component={Like} />
    <Tab.Screen name="Profile" component={Profile} />

  </Tab.Navigator>
)}
</code>```

This the drawer navigation code:

```<code>
onst Drawer = createDrawerNavigator();

const MyDrawer=()=> {
  return (

      <Drawer.Navigator>

        <Drawer.Screen name="Home" component={Home} />

      </Drawer.Navigator>

  );}

</code>```

And this stack navigation code: (I've imported two above components into stack navigation)

```<code>
        const Stack= createStackNavigator();

        const MainStack=()=>{

        return(

        <NavigationContainer>
        <Stack.Navigator>

        <Stack.Screen name="MyTabs" component={MyTabs} options={{headerShown:false}}  />
        <Stack.Screen name="MyDrawer" component={MyDrawer}   />
        <Stack.Screen name="Direct" component={Direct} />

        </Stack.Navigator>
        </NavigationContainer>

        )}

</code>```

I should say when i remove drawer navigation, everything works without any problem

This the code i implemented to open drawer in profile.js :

```<code>const HeaderProfile = (props) => {

const {navigation}=props;

    return (

            <View >

                <TouchableWithoutFeedback
                onPress={()=>navigation.openDrawer()}

                />
           </View >
                    )}

</code>```

How can i fix this?

答:
i cant undrastand where you used HeaderProfile

but what you want to achieve is simple, just use the following structure:

DrawerNavigator
    StackNavigator
        TabNavigator

then from inside your stack navigator header you can open and

close drawer manually

Body:
I'm looking to render the drawer navigation, tab navigation and stack navigation simultaneously in my app.
but I'm getting this error:

This is my root.js file content:

import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import {Like, Home, Search, Media, Profile, Direct, HeaderProfile, CustomDrawer } from './components/index';
import Icon from 'react-native-vector-icons/FontAwesome';
import { createStackNavigator } from '@react-navigation/stack';
import { createDrawerNavigator } from '@react-navigation/drawer';

This the tab navigation code:

const Tab =createMaterialTopTabNavigator();

const MyTabs=()=>{

return(

    <Tab.Navigator>
    <Tab.Screen name="Home" component={Home}/>
    <Tab.Screen name="Search" component={Search} />
    <Tab.Screen name="Media" component={Media} />
    <Tab.Screen name="Like" component={Like} />
    <Tab.Screen name="Profile" component={Profile} />

  </Tab.Navigator>
)}

This the drawer navigation code:

onst Drawer = createDrawerNavigator();

const MyDrawer=()=> {
  return (

      <Drawer.Navigator>

        <Drawer.Screen name="Home" component={Home} />

      </Drawer.Navigator>

  );}

And this stack navigation code: (I've imported two above components into stack navigation)

        const Stack= createStackNavigator();

        const MainStack=()=>{

        return(

        <NavigationContainer>
        <Stack.Navigator>

        <Stack.Screen name="MyTabs" component={MyTabs} options={{headerShown:false}}  />
        <Stack.Screen name="MyDrawer" component={MyDrawer}   />
        <Stack.Screen name="Direct" component={Direct} />

        </Stack.Navigator>
        </NavigationContainer>

        )}

I should say when i remove drawer navigation, everything works without any problem

This the code i implemented to open drawer in profile.js :

const HeaderProfile = (props) => {

const {navigation}=props;

    return (

            <View >

                <TouchableWithoutFeedback
                onPress={()=>navigation.openDrawer()}

                />
           </View >
                    )}

How can i fix this?


问:
Sphinx, snippets and partial word matches
We're using sphinx and snippets to do a basic site search.

```<code>SELECT id FROM search WHERE MATCH('(@keywords corona)')
</code>```

And we're getting matches on "coronavirus" and "coronary" like we would expect.

But when we later use

```<code>CALL SNIPPETS(
    'Wuhan Novel Coronavirus - What you need to know',
    'search',
    'corona',
    '<span class="mark">' AS before_match,
    '</span>' AS after_match,
    '…' AS chunk_separator,
    800 AS limit,
    20 AS around,
    0 AS query_mode
)
</code>```

None of these partial matches are being highlighted.

If we search for a full word (replacing "corona" in the SELECT and CALL SNIPPETS with e.g. "coronavirus") then the full word results are highlighted correctly.

Is there a way we can get CALL SNIPPETS to highlight the partial word matches in the first example like it does with the full word results in the second example?

答:
I just appended "*" to the keyword in CALL SNIPPETS like this:

```<code>    'Wuhan Novel Coronavirus - What you need to know',
    'search',
    '*corona*',
    800 AS limit,
    20 AS around,
    0 AS query_mode
</code>```

But the comment from @barryhunter below makes more sense than my actual solution.

Body:
We're using sphinx and snippets to do a basic site search.

SELECT id FROM search WHERE MATCH('(@keywords corona)')

And we're getting matches on "coronavirus" and "coronary" like we would expect.

But when we later use

CALL SNIPPETS(
    'Wuhan Novel Coronavirus - What you need to know',
    'search',
    'corona',
    '' AS before_match,
    '' AS after_match,
    '…' AS chunk_separator,
    800 AS limit,
    20 AS around,
    0 AS query_mode
)

None of these partial matches are being highlighted.

If we search for a full word (replacing "corona" in the SELECT and CALL SNIPPETS with e.g. "coronavirus") then the full word results are highlighted correctly.

Is there a way we can get CALL SNIPPETS to highlight the partial word matches in the first example like it does with the full word results in the second example?

Body:
I just appended "*" to the keyword in CALL SNIPPETS like this:

    'Wuhan Novel Coronavirus - What you need to know',
    'search',
    '*corona*',
    800 AS limit,
    20 AS around,
    0 AS query_mode

But the comment from @barryhunter below makes more sense than my actual solution.


问:
How to properly set the value of a custom radiobutton control in an Angular reactive form?
I have a simple custom radio button control.  HTML:

```<code><label class="radiobutton-container" >
    <ng-content></ng-content>
    <input type="radio" [value]="value" [name]="name" [disabled]="disabled" (change)="handleChange($event)" [checked]="checked"/>
    <span [ngClass]="{'checkbase': true,
    'checkmark' : checked
    }"></span>
</label>
</code>```

In general it works fine, I can tell if it is checked and put it into groups, etc.  But - when I use it in a form, I just the value of the group as "true" instead of the value of the component:

```<code><form #form="ngForm" >
    <my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value1'" >Value 1</my-radiobutton>
    <my-radiobutton [ngModel]="mymodel"   [name]="'options'" [value]="'value2'" >Value 2</my-radiobutton>
    <my-radiobutton [ngModel]="mymodel"  [name]="'options'" [value]="'value3'" >Value 3</my-radiobutton>
</form>
<p>form value:</p>
```{{ form.value | json }}```
</code>```

When I print the value of the form, it is just "options: true", instead of "value1", "value2", etc.

Not sure what I am doing wrong.  Any help appreciated!

答:
Use array instead of calling the component again and again, Please refer the below code
App.component.html

```<code>`<form>
   <app-my-radiobutton [inputList]="radioList"
   (changedInput)="onValueChange($event)"></app-my-radiobutton>
</form>
<pre *ngIf="title">
   {{title.form.value | json}}
````
```

<p><strong>App.component.ts</strong></p>

<p><code>title: NgForm;</code></p>

<p><code>radioList = ['Male', 'Female'];</code></p>

<p><code>onValueChange(event) {
     this.title = event
    }</code></p>

<p><strong>Myradiobutton.Component</strong></p>

<p><code>@Input() inputList = [];</code></p>

<p><code>@Output() changedInput = new EventEmitter<any>();</code></p>

<p><code>inputData: string;</code>
  <code>constructor() { }</code></p>

<p><code>ngOnInit() {}</code></p>

<p><code>onChange(event, form) {
     this.changedInput.emit(form)
  }</code></p>

<p><strong>Myradiobutton.HTML</strong></p>

````

    <form #form="ngForm">

            <input type="radio" id="{{item+i}}" name="gender" value="{{item}}"
            [(ngModel)]="item" (change)="onChange($event, form)">
            {{item}}

    </form>

`
```

Output

{
  "gender": "Male"
} or {
  "gender": "FeMale"
}

Body:
I have a simple custom radio button control.  HTML:

    <ng-content></ng-content>
    <input type="radio" [value]="value" [name]="name" [disabled]="disabled" (change)="handleChange($event)" [checked]="checked"/>

In general it works fine, I can tell if it is checked and put it into groups, etc.  But - when I use it in a form, I just the value of the group as "true" instead of the value of the component:

<form #form="ngForm" >
    <my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value1'" >Value 1</my-radiobutton>
    <my-radiobutton [ngModel]="mymodel"   [name]="'options'" [value]="'value2'" >Value 2</my-radiobutton>
    <my-radiobutton [ngModel]="mymodel"  [name]="'options'" [value]="'value3'" >Value 3</my-radiobutton>
</form>

form value:

{{ form.value | json }}

When I print the value of the form, it is just "options: true", instead of "value1", "value2", etc.

Not sure what I am doing wrong.  Any help appreciated!

Body:
Use array instead of calling the component again and again, Please refer the below code
App.component.html

`<form>
   <app-my-radiobutton [inputList]="radioList"
   (changedInput)="onValueChange($event)"></app-my-radiobutton>
</form>
<pre *ngIf="title">
   {{title.form.value | json}}
</pre>`

App.component.ts

title: NgForm;

radioList = ['Male', 'Female'];

onValueChange(event) {
     this.title = event
    }

Myradiobutton.Component

@Input() inputList = [];

@Output() changedInput = new EventEmitter<any>();

inputData: string;
  constructor() { }

ngOnInit() {}

onChange(event, form) {
     this.changedInput.emit(form)
  }

Myradiobutton.HTML

`<div class="container">
    <form #form="ngForm">
        <div *ngFor="let item of inputList; let i = index">
            <input type="radio" id="{{item+i}}" name="gender" value="{{item}}"
            [(ngModel)]="item" (change)="onChange($event, form)">
            <label for="male">{{item}}</label><br>
        </div>
    </form>
</div>`

Output

{
  "gender": "Male"
} or {
  "gender": "FeMale"
}


问:
Setting default location for screenshots in Robot Framework using AppiumLibrary
I am using AppiumLibrary with Robot Framework and I want to set a default location for screenshots which were be taken when failure occurs.

The Capture Page Screenshot is the default keyword which will be executed on failure, but how can I set the default location for it?

I tried setting like this:
   Library         AppiumLibrary   run_on_failure=Capture Page Screenshot filename=path/to/file.png

In this case, the filename parameter won't be considered.

答:
Everything you need should be in the documentation https://serhatbolsu.github.io/robotframework-appiumlibrary/AppiumLibrary.html#Capture%20Page%20Screenshot

If you do not give an absolute path it is considered a relative path.


问:
Changing table row order using buttons not working every time
I have a table with 2
's per project, .project-row & .expandable-row. I'm trying to change the order of these projects using up/down buttons in .project-row, which I got to work, but not 100% of the time:

JSFiddle

For example: when I click down on project 1, it moves down as expected, but when I try to move it down again, I have to click it twice before it actually moves.

Why?

答:
The issue is because your chained use of next() and prev() is targeting the wrong rows - it goes to the middle of the target group instead of before/after it.

You can fix this and make the logic simpler by combining the event handlers which move the content and change their behaviour based on some data attributes. Try this:

jQuery(function($) {
  $(document).on('click', '.order-change', function() {
    $('.expandable-row').hide();

    var $trigger = $(this)
    var $row = $trigger.closest('tr');
    var $infoRow = $row.next('tr');

    if ($trigger.data('dir') === 'up') {
      $row.add($infoRow).insertBefore($row.prev());
    } else {
      $row.add($infoRow).insertAfter($infoRow.next());
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  border: 1px solid black;
  text-align: center;
}

td div {
  cursor: pointer;
}

.expandable-row {
  display: none;
}</code>```

up

down

      Project 1

      Project 1 info

up

down

      Project 2

      Project 2 info

up

down

      Project 3

      Project 3 info

```

Body:
The issue is because your chained use of next() and prev() is targeting the wrong rows - it goes to the middle of the target group instead of before/after it.

You can fix this and make the logic simpler by combining the event handlers which move the content and change their behaviour based on some data attributes. Try this:

jQuery(function($) {
  $(document).on('click', '.order-change', function() {
    $('.expandable-row').hide();

    var $trigger = $(this)
    var $row = $trigger.closest('tr');
    var $infoRow = $row.next('tr');

    if ($trigger.data('dir') === 'up') {
      $row.add($infoRow).insertBefore($row.prev());
    } else {
      $row.add($infoRow).insertAfter($infoRow.next());
    }
  });
});

td {
  border: 1px solid black;
  text-align: center;
}

td div {
  cursor: pointer;
}

.expandable-row {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr class="project-row" data-project-id="0">
      <td>
        <div class="order-change" data-dir="up">up</div>
        <div class="order-change" data-dir="down">down</div>
      </td>
      <td>Project 1</td>
    </tr>
    <tr class="expandable-row" data-project-id="0">
      <td>Project 1 info</td>
    </tr>
    <tr class="project-row" data-project-id="1">
      <td>
        <div class="order-change" data-dir="up">up</div>
        <div class="order-change" data-dir="down">down</div>
      </td>
      <td>Project 2</td>
    </tr>
    <tr class="expandable-row" data-project-id="1">
      <td>Project 2 info</td>
    </tr>
    <tr class="project-row" data-project-id="2">
      <td>
        <div class="order-change" data-dir="up">up</div>
        <div class="order-change" data-dir="down">down</div>
      </td>
      <td>Project 3</td>
    </tr>
    <tr class="expandable-row" data-project-id="2">
      <td>Project 3 info</td>
    </tr>
  </tbody>
</table>


问:
Chef Elementory OS (Error executing action `install` on resource 'package[apache2]')
```<code> * package[tree] action install[2020-02-18T15:27:02+05:30] INFO: Processing package[tree] action install (starter::default line 8)

    ================================================================================
    Error executing action `install` on resource 'package[tree]'
    ================================================================================

    Chef::Exceptions::ProviderNotFound
    ----------------------------------
    Cannot find a provider for package[tree] on elementary version 5.1.2

    Resource Declaration:
    ---------------------
    # In /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb

      8: package "tree"
      9:

    Compiled Resource:
    ------------------
    # Declared in /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb:8:in `from_file'
</code>```

Code:

```<code>package("tree") do
  package_name "tree"
  action [:install]
  default_guard_interpreter :default
  declared_type :package
  cookbook_name "starter"
  recipe_name "default"
end
</code>```

System Info:

```<code>chef_version=15.7.32
platform=elementary
platform_version=5.1.2
ruby=ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
program_name=/usr/bin/chef-client
executable=/opt/chef-workstation/bin/chef-client
</code>```

答:
finally i got the solution for this question ,refer this link https://docs.chef.io/resource_gem_package.html

it uses gem_package

Body:
 * package[tree] action install[2020-02-18T15:27:02+05:30] INFO: Processing package[tree] action install (starter::default line 8)

    ================================================================================
    Error executing action `install` on resource 'package[tree]'
    ================================================================================

    Chef::Exceptions::ProviderNotFound
    ----------------------------------
    Cannot find a provider for package[tree] on elementary version 5.1.2

    Resource Declaration:
    ---------------------
    # In /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb

      8: package "tree"
      9:

    Compiled Resource:
    ------------------
    # Declared in /home/mrunknown/Downloads/chef-repo/.chef/local-mode-cache/cache/cookbooks/starter/recipes/default.rb:8:in `from_file'

Code:

package("tree") do
  package_name "tree"
  action [:install]
  default_guard_interpreter :default
  declared_type :package
  cookbook_name "starter"
  recipe_name "default"
end

System Info:

chef_version=15.7.32
platform=elementary
platform_version=5.1.2
ruby=ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-linux]
program_name=/usr/bin/chef-client
executable=/opt/chef-workstation/bin/chef-client