问:
RecyclerView (No adapter attached;skipping layout) using retrofit and fragment
Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView

Conexion Class

```<code>public class Conexion {

    public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}
</code>```

EndPoint Interface

```<code>public interface EndPointsInterface {

    @GET("chef/{idUser}")
    Call<ChefResponse> GetChefsCercanos(@Path("idUser") Integer id_usuario);

}
</code>```

Entity Usuario

```<code>public class Usuario  {

    @SerializedName("id_usuario")
    private Integer id_usuario;
    @SerializedName("NombreUsuario")
    private String NombreUsuario;
    @SerializedName("ApellidoUsuario")
    private String ApellidoUsuario;
    @SerializedName("TelefonoUsuario")
    private String TelefonoUsuario;
    @SerializedName("Email")
    private String Email;
    @SerializedName("Contraseña")
    private String Contraseña;
    @SerializedName("pos_x")
    private Double pos_x;
    @SerializedName("pos_y")
    private Double pos_y;

    public Usuario(){}

    public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
        this.id_usuario=id_usuario;
        this.NombreUsuario=NombreUsuario;
        this.ApellidoUsuario=ApellidoUsuario;
        this.TelefonoUsuario=TelefonoUsuario;
        this.Contraseña=Contraseña;
        this.pos_x=pos_x;
        this.pos_y=pos_y;
    }

    public Integer getId_usuario() {
        return id_usuario;
    }

    public void setId_usuario(Integer id_usuario) {
        this.id_usuario = id_usuario;
    }

    public String getNombreUsuario() {
        return NombreUsuario;
    }

    public void setNombreUsuario(String nombreUsuario) {
        NombreUsuario = nombreUsuario;
    }

    public String getApellidoUsuario() {
        return ApellidoUsuario;
    }

    public void setApellidoUsuario(String apellidoUsuario) {
        ApellidoUsuario = apellidoUsuario;
    }

    public String getTelefonoUsuario() {
        return TelefonoUsuario;
    }

    public void setTelefonoUsuario(String telefonoUsuario) {
        TelefonoUsuario = telefonoUsuario;
    }

    public String getEmail() {
        return Email;
    }

    public void setEmail(String email) {
        Email = email;
    }

    public String getContraseña() {
        return Contraseña;
    }

    public void setContraseña(String contraseña) {
        Contraseña = contraseña;
    }

    public Double getPos_x() {
        return pos_x;
    }

    public void setPos_x(Double pos_x) {
        this.pos_x = pos_x;
    }

    public Double getPos_y() {
        return pos_y;
    }

    public void setPos_y(Double pos_y) {
        this.pos_y = pos_y;
    }
}
</code>```

Entity Chef

```<code>public class Chef extends Usuario{

    @SerializedName("id_chef")
    private Integer id_chef;
    @SerializedName("TipoServicio")
    private String TipoServicio;
    @SerializedName("Rating")
    private Double Rating;
    @SerializedName("EstadoChef")
    private Boolean EstadoChef;

    public Chef(){}

    public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
        super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
        this.id_chef=id_chef;
        this.TipoServicio=TipoServicio;
        this.Rating=Rating;
        this.EstadoChef=EstadoChef;
    }

    public Integer getId_chef() {
        return id_chef;
    }

    public void setId_chef(Integer id_chef) {
        this.id_chef = id_chef;
    }

    public String getTipoServicio() {
        return TipoServicio;
    }

    public void setTipoServicio(String tipoServicio) {
        TipoServicio = tipoServicio;
    }

    public Double getRating() {
        return Rating;
    }

    public void setRating(Double rating) {
        Rating = rating;
    }

    public Boolean getEstadoChef() {
        return EstadoChef;
    }

    public void setEstadoChef(Boolean estadoChef) {
        EstadoChef = estadoChef;
    }
}
</code>```

Chef Response

```<code>public class ChefResponse {

    @SerializedName("results")
    private Chef[] results;

    public Chef[] getresults(){
        return results;
    }
}
</code>```

RecyclerView Adapter

```<code>public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {

    private List<Chef> chefs;
    private List<Usuario> usuarios;
    private int rowLayout;
    private Context context;

    @Override
    public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
        return new ListaChefsCercanosViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
        holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
        holder.ratingchef.setText(chefs.get(position).getRating().toString());
    }

    @Override
    public int getItemCount() {

        return chefs.size();
    }

    public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
        LinearLayout chefslayout;
        TextView nombreschefscerca;
        TextView ratingchef;

        public ListaChefsCercanosViewHolder(View v){
            super(v);
            chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
            nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
            ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
        }
    }

    public ListaChefsCercanos(ArrayList <Chef> chefs){
        this.chefs=chefs;
        //this.rowLayout = rowLayout;
        //this.context = context;
    }

}
</code>```

and the fragment

```<code>public class RecomendadosFragment extends Fragment {

    private RatingBar ratingBar;

    //ListAdapter adapter;
    ArrayList<Chef> listachef;
    ListView lvLista;
    String tag_json_array="jarray req";
    RecyclerView recyclerviewChefsCarnos;
    ListaChefsCercanos mListaChefsCercanos;

    private ArrayList<Chef> data;
    private ListaChefsCercanos adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View x =  inflater.inflate(R.layout.recomendados,null);

        //ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
        recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
        recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));

        EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);

        Call<ChefResponse> call = apiService.GetChefsCercanos(5);
        call.enqueue(new Callback<ChefResponse>() {
            @Override
            public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
                int statusCode = response.code();

                  if (response.isSuccessful()) {

                ChefResponse jsonResponse = response.body();

                if(jsonResponse != null) {

                    data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
                    adapter= new ListaChefsCercanos(data);
                    recyclerviewChefsCarnos.setAdapter(adapter);

                }

            } else {
                // Do whatever you want if API is unsuccessful.
            }

               // List<Chef> chefs= response.body().getResults();
               // recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
            }

            @Override
            public void onFailure(Call<ChefResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());

            }

        });

        return x;
    }
</code>```

this is the error I found while Im debuging

```<code> E/RecyclerView: No adapter attached; skipping layout
</code>```

答:
Update: Use a empty adapter for the RecyclerView in the OncreateView()</p>

```<code>recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));
</code>```

Body:
Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView

Conexion Class

public class Conexion {

    public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

}

EndPoint Interface

public interface EndPointsInterface {

    @GET("chef/{idUser}")
    Call<ChefResponse> GetChefsCercanos(@Path("idUser") Integer id_usuario);

}

Entity Usuario

public class Usuario  {

    @SerializedName("id_usuario")
    private Integer id_usuario;
    @SerializedName("NombreUsuario")
    private String NombreUsuario;
    @SerializedName("ApellidoUsuario")
    private String ApellidoUsuario;
    @SerializedName("TelefonoUsuario")
    private String TelefonoUsuario;
    @SerializedName("Email")
    private String Email;
    @SerializedName("Contraseña")
    private String Contraseña;
    @SerializedName("pos_x")
    private Double pos_x;
    @SerializedName("pos_y")
    private Double pos_y;

    public Usuario(){}

    public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
        this.id_usuario=id_usuario;
        this.NombreUsuario=NombreUsuario;
        this.ApellidoUsuario=ApellidoUsuario;
        this.TelefonoUsuario=TelefonoUsuario;
        this.Contraseña=Contraseña;
        this.pos_x=pos_x;
        this.pos_y=pos_y;
    }

    public Integer getId_usuario() {
        return id_usuario;
    }

    public void setId_usuario(Integer id_usuario) {
        this.id_usuario = id_usuario;
    }

    public String getNombreUsuario() {
        return NombreUsuario;
    }

    public void setNombreUsuario(String nombreUsuario) {
        NombreUsuario = nombreUsuario;
    }

    public String getApellidoUsuario() {
        return ApellidoUsuario;
    }

    public void setApellidoUsuario(String apellidoUsuario) {
        ApellidoUsuario = apellidoUsuario;
    }

    public String getTelefonoUsuario() {
        return TelefonoUsuario;
    }

    public void setTelefonoUsuario(String telefonoUsuario) {
        TelefonoUsuario = telefonoUsuario;
    }

    public String getEmail() {
        return Email;
    }

    public void setEmail(String email) {
        Email = email;
    }

    public String getContraseña() {
        return Contraseña;
    }

    public void setContraseña(String contraseña) {
        Contraseña = contraseña;
    }

    public Double getPos_x() {
        return pos_x;
    }

    public void setPos_x(Double pos_x) {
        this.pos_x = pos_x;
    }

    public Double getPos_y() {
        return pos_y;
    }

    public void setPos_y(Double pos_y) {
        this.pos_y = pos_y;
    }
}

Entity Chef

public class Chef extends Usuario{

    @SerializedName("id_chef")
    private Integer id_chef;
    @SerializedName("TipoServicio")
    private String TipoServicio;
    @SerializedName("Rating")
    private Double Rating;
    @SerializedName("EstadoChef")
    private Boolean EstadoChef;

    public Chef(){}

    public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
        super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
        this.id_chef=id_chef;
        this.TipoServicio=TipoServicio;
        this.Rating=Rating;
        this.EstadoChef=EstadoChef;
    }

    public Integer getId_chef() {
        return id_chef;
    }

    public void setId_chef(Integer id_chef) {
        this.id_chef = id_chef;
    }

    public String getTipoServicio() {
        return TipoServicio;
    }

    public void setTipoServicio(String tipoServicio) {
        TipoServicio = tipoServicio;
    }

    public Double getRating() {
        return Rating;
    }

    public void setRating(Double rating) {
        Rating = rating;
    }

    public Boolean getEstadoChef() {
        return EstadoChef;
    }

    public void setEstadoChef(Boolean estadoChef) {
        EstadoChef = estadoChef;
    }
}

Chef Response

public class ChefResponse {

    @SerializedName("results")
    private Chef[] results;

    public Chef[] getresults(){
        return results;
    }
}

RecyclerView Adapter

public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {

    private List<Chef> chefs;
    private List<Usuario> usuarios;
    private int rowLayout;
    private Context context;

    @Override
    public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
        return new ListaChefsCercanosViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
        holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
        holder.ratingchef.setText(chefs.get(position).getRating().toString());
    }

    @Override
    public int getItemCount() {

        return chefs.size();
    }

    public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
        LinearLayout chefslayout;
        TextView nombreschefscerca;
        TextView ratingchef;

        public ListaChefsCercanosViewHolder(View v){
            super(v);
            chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
            nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
            ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
        }
    }

    public ListaChefsCercanos(ArrayList <Chef> chefs){
        this.chefs=chefs;
        //this.rowLayout = rowLayout;
        //this.context = context;
    }

}

and the fragment

public class RecomendadosFragment extends Fragment {

    private RatingBar ratingBar;

    //ListAdapter adapter;
    ArrayList<Chef> listachef;
    ListView lvLista;
    String tag_json_array="jarray req";
    RecyclerView recyclerviewChefsCarnos;
    ListaChefsCercanos mListaChefsCercanos;

    private ArrayList<Chef> data;
    private ListaChefsCercanos adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View x =  inflater.inflate(R.layout.recomendados,null);

        //ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
        recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
        recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));

        EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);

        Call<ChefResponse> call = apiService.GetChefsCercanos(5);
        call.enqueue(new Callback<ChefResponse>() {
            @Override
            public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
                int statusCode = response.code();

                  if (response.isSuccessful()) {

                ChefResponse jsonResponse = response.body();

                if(jsonResponse != null) {

                    data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
                    adapter= new ListaChefsCercanos(data);
                    recyclerviewChefsCarnos.setAdapter(adapter);

                }

            } else {
                // Do whatever you want if API is unsuccessful.
            }

               // List<Chef> chefs= response.body().getResults();
               // recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
            }

            @Override
            public void onFailure(Call<ChefResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());

            }

        });

        return x;
    }

this is the error I found while Im debuging

 E/RecyclerView: No adapter attached; skipping layout

Body:
Update: Use a empty adapter for the RecyclerView in the OncreateView()

recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));


来源: stackexchange

问:
Find where 1 condition a is positive and condition b negative
first time posting, I've done a search but don't seem to be able to find what I'm looking for.

I'm using Rails 5 and trying to search my db with 2 conditions, the problem I'm having however is that one of my conditions is a negative, I can't find out how to get this to work.

Currently I have this:

```<code>Case.where({source: 'online', status: 'working'})
</code>```

I want to find cases where the source is 'Online' and the status is not 'Working'

The above finds all cases where the source is Online and the status is Working. I tried the below but that doesn't seem to work.

```<code>Case.where({source: 'online', status: !'working'})
</code>```

Can anyone help me with this, or point me in the direction of documentation?

答:
You may use where.not condition:

```<code>Case.where(source: 'online').where.not(status: 'working')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
first time posting, I've done a search but don't seem to be able to find what I'm looking for.

I'm using Rails 5 and trying to search my db with 2 conditions, the problem I'm having however is that one of my conditions is a negative, I can't find out how to get this to work.

Currently I have this:

Case.where({source: 'online', status: 'working'})

I want to find cases where the source is 'Online' and the status is not 'Working'

The above finds all cases where the source is Online and the status is Working. I tried the below but that doesn't seem to work.

Case.where({source: 'online', status: !'working'})

Can anyone help me with this, or point me in the direction of documentation?

Body:
You may use where.not condition:

Case.where(source: 'online').where.not(status: 'working')


问:
Drop R data.frame columns based on Row Value
I have a dataFrame setup like this:

```<code>dfRiskChanges <<- data.frame(-1, -1, -1, -1, -1, -1, -1, -1)
colnames(dfRiskChanges) <<- c('Funcational', 'Steroid', 'HxCHF', 'SOB',
                            'HxCOPD', 'Smoker', 'DMAll', 'HTNMed')
</code>```

Then I replace the applicable dataFrame values with real numbers, so a final version of the dataFrame could be:

```<code>Funcational Steroid HxCHF SOB HxCOPD   Smoker    DMAll        HTNMed
-1          -1      -1     -1   -1        -1        1.983131    -1 0.6438011
</code>```

Now I want to drop all the columns where the value is -1.

I've been trying things like this:

```<code>dfRiskChanges.new <- dfRiskChanges[dfRiskChanges$units != -1, ]
</code>```

and

```<code>dfRiskChanges.new <<- dfRiskChanges %>% filter(units != -1)
</code>```

and

```<code>dfRiskChanges %>% select_if(function(col) all(col != -1))
</code>```

All without success. Any help would be appreciated!

答:
Let's add another column with a different value:

```<code>>dfRiskChanges$NoSmoke=0
> dfRiskChanges
  Funcational Steroid HxCHF SOB HxCOPD Smoker DMAll HTNMed NoSmoke
1          -1      -1    -1  -1     -1     -1    -1     -1       0
</code>```

Next, return only the columns that don't have -1 in them:

```<code>> df2=dfRiskChanges[!grepl(-1,dfRiskChanges)] #picks out all columns that don't contain -1
> df2
  NoSmoke
1       0
</code>```

Body:
I have a dataFrame setup like this:

dfRiskChanges <<- data.frame(-1, -1, -1, -1, -1, -1, -1, -1)
colnames(dfRiskChanges) <<- c('Funcational', 'Steroid', 'HxCHF', 'SOB',
                            'HxCOPD', 'Smoker', 'DMAll', 'HTNMed')

Then I replace the applicable dataFrame values with real numbers, so a final version of the dataFrame could be:

Funcational Steroid HxCHF SOB HxCOPD   Smoker    DMAll        HTNMed
-1          -1      -1     -1   -1        -1        1.983131    -1 0.6438011

Now I want to drop all the columns where the value is -1.

I've been trying things like this:

dfRiskChanges.new <- dfRiskChanges[dfRiskChanges$units != -1, ]

and

dfRiskChanges.new <<- dfRiskChanges %>% filter(units != -1)

and

dfRiskChanges %>% select_if(function(col) all(col != -1))

All without success. Any help would be appreciated!

Body:
Let's add another column with a different value:

>dfRiskChanges$NoSmoke=0
> dfRiskChanges
  Funcational Steroid HxCHF SOB HxCOPD Smoker DMAll HTNMed NoSmoke
1          -1      -1    -1  -1     -1     -1    -1     -1       0

Next, return only the columns that don't have -1 in them:

> df2=dfRiskChanges[!grepl(-1,dfRiskChanges)] #picks out all columns that don't contain -1
> df2
  NoSmoke
1       0


问:
SharedPreferences Logout not working
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

```<code>SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}
</code>```

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

```<code>void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
</code>```

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

答:
Put finish() here in the code of yours

```<code>SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}
</code>```

UPDATE

I went through your code and found a small mistake in it :

In your OnCreate method you are using :

```<code>SharedPreferences blockSession  = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isLoggedIn  = blockSession.getBoolean("logged_in", false);
    if(!isLoggedIn){
        Intent intent  = new Intent(this, Mainpage.class);
        startActivity(intent);
        finish();
    }
</code>```

Mistakes :

You are getting your sharedPreference value in on create method But when you are clearing sharedPreference on logout it doesn't have any shaved sharedPreference value . so it takes false as default value as you mentioned here :

```<code> boolean isLoggedIn  = blockSession.getBoolean("logged_in", false); // false is default value.
</code>```

And you if conditioned is always true because you have false value every time you logout.

Solution :

change if condition as follows :

```<code>if(isLoggedIn){
        Intent intent  = new Intent(this, Mainpage.class);
        startActivity(intent);
        finish();
    }
</code>```

Title: SharedPreferences Logout not working

Body:
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

Body:
Put finish() here in the code of yours

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
Intent intent = new Intent(this, Mainpage.class);
startActivity(intent);
finish();
}

UPDATE

I went through your code and found a small mistake in it :

In your OnCreate method you are using :

SharedPreferences blockSession  = PreferenceManager.getDefaultSharedPreferences(this);
    boolean isLoggedIn  = blockSession.getBoolean("logged_in", false);
    if(!isLoggedIn){
        Intent intent  = new Intent(this, Mainpage.class);
        startActivity(intent);
        finish();
    }

Mistakes :

You are getting your sharedPreference value in on create method But when you are clearing sharedPreference on logout it doesn't have any shaved sharedPreference value . so it takes false as default value as you mentioned here :

 boolean isLoggedIn  = blockSession.getBoolean("logged_in", false); // false is default value.

And you if conditioned is always true because you have false value every time you logout.

Solution :

change if condition as follows :

if(isLoggedIn){
        Intent intent  = new Intent(this, Mainpage.class);
        startActivity(intent);
        finish();
    }


问:
Where should I handle sorting in Redux App?
I have an action / reducer / components. In one of my components (component dump) I have a Select. I get information on what type of filter my store. Where can I handle it in action, or reducer?</p>

答:
IMO, the right place to sort data is not directly in the reducers but in the selectors.

From redux docs:

Computing Derived Data

Reselect is a simple library for creating memoized, composable selector functions. Reselect selectors can be used to efficiently compute derived data from the Redux store.

I'm currently using selectors to filter and sort data.

No data repetition in the state. You don't have to store a copy of the item sorted by one specific way.

The same data can be used in different components, each one using a different selector function to sort for example.

You can combine selector applying many data computations using selector that you already have in the application.

If you do right, your selectors will be pure functions, then you can easily test them.

Use the same selector in many components.

ContentLicense: CC BY-SA 4.0


问:
Does AWS CPP S3 SDK support "Transfer acceleration"
I enabled "Transfer acceleration" on my bucket. But I dont see any improvement in speed of Upload in my C++ application. I have waited for more than 20 minutes that is mentioned in AWS Documentation.

Does the SDK support "Transfer acceleration" by default or is there a run time flag or compiler flag? I did not spot anything in the SDK code.

thanks

答: Currently, there isn't a configuration option that simply turns on transfer acceleration. You can however, use endpoint override in the client configuration to set the accelerated endpoint.</p>


问:
Service to get/set current entity
I have a Project entity, which has a controller defining many routes:

projects/1
projects/1/foo
projects/1/bar

I need a service to provide the current project. The use case is that I have dependencies in my base twig templates which need to know the current project. i.e. a dropdown project selector that is outside the context of the template the current controller is serving.

I've tried creating a service getting route info with $container->get('router.request_context');, however, that only provides a path. I don't want to have to parse the path string if I don't have to.

What is the most proper approach?

答:
If I understood you correctly the solution for your problem is rendering/embedding controller. Of course it's simplest, yet somehow acceptable solution for rendering parts of html with some custom logic apart from current template.

You can read about rendering/embedding controllers.

Some snippets...

Define controller:action (obviously the logic in my example is pretty straight forward):

```<code>/**
 * Generate select input field.
 *
 * @Route("/widget", name="project_widget")
 * @Method("GET")
 */
public function widgetAction()
{
    $repo = $this->getDoctrine()
        ->getManager()
        ->getRepository('AppBundle:Project');

    // #NOTICE: Wee need master request info, because our widget
    //     is rendered and called as subrequest.
    $masterRequest = $this->get('request_stack')->getMasterRequest();

    // #NOTICE: You need second parameter as default value in case there is no id in masterRequest route.
    $currentProjectId = $masterRequest->get('id', 0);

    $currentProject = $repo->find($currentProjectId);
    $projects = $repo->findAll();

    return $this->render('project/widget.html.twig', [
        'currentProject' => $currentProject,
        'projects' => $projects,
    ]);
}
</code>```

Then you need to create the template project/widget.html.twig for it:

```<code><div class="widget_project_selection">
    {% if projects is not empty %}
        <select name="widget_project_selection" id="widget_project_selection">
            <option value="">None</option>
            {% for project in projects %}
                <option value="{{ project.id }}"
                    {# #NOTICE: If this is current project, select it #}
                    {{- currentProject and project.id == currentProject.id
                        ? 'selected="selected"'
                        : '' -}}
                >
                    {{- project.title -}}
                </option>
            {% endfor %}
        </select>
    {% else %}
        <span>{{ 'Sadly, no projects yet :('|trans }}</span>
    {% endif %}
</div>
</code>```

and at last (but not least) render it somewhere like in base.html.twig:

```<code>{{- render(controller('AppBundle:Project:widget')) -}}
</code>```

I've created for you a Github repo as reference. It's a small Symfony app with similar setup. You can even run it if you like, don't forget about dependencies and database update thou. Entry point is /app_dev.php/project/

Take a look at widgetAction, widget template and example usage in base.html.twig.

EDIT: But that's not everything. You said you need a service. If for some reason rendering/embedding controller is not an option for you or you really whant to use a Service (as in Dependency Container) you can extend Twig and use the full power of services.

I've also implemented a Twig Filter as example to show you the real power of Twig Extensions in here and here (usage in templates).

Check out Twig Extension and Extending Twig for more info about Twig Extensions.

Also check out service.yml for service and extension definitions - if you are not using Symfony3.3+, there will be some additional work to do - defining service and extension directly.

Title: Service to get/set current entity

Body:
If I understood you correctly the solution for your problem is rendering/embedding controller. Of course it's simplest, yet somehow acceptable solution for rendering parts of html with some custom logic apart from current template.

You can read about rendering/embedding controllers.

Some snippets...

Define controller:action (obviously the logic in my example is pretty straight forward):

/**
 * Generate select input field.
 *
 * @Route("/widget", name="project_widget")
 * @Method("GET")
 */
public function widgetAction()
{
    $repo = $this->getDoctrine()
        ->getManager()
        ->getRepository('AppBundle:Project');

    // #NOTICE: Wee need master request info, because our widget
    //     is rendered and called as subrequest.
    $masterRequest = $this->get('request_stack')->getMasterRequest();

    // #NOTICE: You need second parameter as default value in case there is no id in masterRequest route.
    $currentProjectId = $masterRequest->get('id', 0);

    $currentProject = $repo->find($currentProjectId);
    $projects = $repo->findAll();

    return $this->render('project/widget.html.twig', [
        'currentProject' => $currentProject,
        'projects' => $projects,
    ]);
}

Then you need to create the template project/widget.html.twig for it:

<div class="widget_project_selection">
    {% if projects is not empty %}
        <select name="widget_project_selection" id="widget_project_selection">
            <option value="">None</option>
            {% for project in projects %}
                <option value="{{ project.id }}"
                    {# #NOTICE: If this is current project, select it #}
                    {{- currentProject and project.id == currentProject.id
                        ? 'selected="selected"'
                        : '' -}}
                >
                    {{- project.title -}}
                </option>
            {% endfor %}
        </select>
    {% else %}
        <span>{{ 'Sadly, no projects yet :('|trans }}</span>
    {% endif %}
</div>

and at last (but not least) render it somewhere like in base.html.twig:

{{- render(controller('AppBundle:Project:widget')) -}}

I've created for you a Github repo as reference. It's a small Symfony app with similar setup. You can even run it if you like, don't forget about dependencies and database update thou. Entry point is /app_dev.php/project/

Take a look at widgetAction, widget template and example usage in base.html.twig.

EDIT: But that's not everything. You said you need a service. If for some reason rendering/embedding controller is not an option for you or you really whant to use a Service (as in Dependency Container) you can extend Twig and use the full power of services.

I've also implemented a Twig Filter as example to show you the real power of Twig Extensions in here and here (usage in templates).

Check out Twig Extension and Extending Twig for more info about Twig Extensions.

Also check out service.yml for service and extension definitions - if you are not using Symfony3.3+, there will be some additional work to do - defining service and extension directly.


问:
How can I implement automatic loading for JSON object in android?
I am working on an audio stream android app and I parsed JSON object from a server to a TextView to display 'now Playing'  for the song name and artist. So when the play button is clicked, the song name playing artist is displayed to the user. The problem is that I want this automatically loaded to the app view when JSON URL link is updated from the server. I don't want the user pressing pause and play to update the view from the app. How do I go about this because I don't want the user restarting the service each time a new song isPlaying to get song information.</p>

答:
You can either poll server in short intervals to check if song changed or open socket connection to server to make possible server initiating communication to device.

First approach in simplest form is a very bad practice, as it puts strain on both device and server to check it often enough.

However there is different way to use it, called long polling. With this, you send request to the server, and server does not respond immediately, but holds connection open until it has something to say. After getting reply instantaneously new request is created to make sure no delay is made by it.

The best approach is opening a socket connection, but not every server and program support it.

You can try libraries like SignalR (this one is for .NET mostly, but it's the first one that came to my mind) that choose which approach is the best and takes care of holding connection, reconnecting etc.


问:
How to make sure a button click is process by a webpage before continuing with automation selenium
I'm trying to automate the login process to a webpage using selenium and chrome driver. The webpage login button element looks like this;

```<code><div class="button small"><a class="btn-login" href="#">Login</a></div>
</code>```

So I click it using the following;

```<code>bot.FindElement(By.LinkText("Login")).Click()
</code>```

Where 'bot' is my chrome driver. This works, 100% of the time it clicks the button. I'd now like to automate the next step of the processes but here's where I hit a snag. Clicking the button doesn't load a new webpage, it just runs a script on the page where I need to click another button (basically select what area I want to log into). How can I wait until the webpage has processed the first click so I can process the next click. When I try the next click I get this error;

```<code>System.InvalidOperationException: 'unknown error: Element <a class="area-select" href="/page/area/start">...</a> is not clickable at point (542, 318). Other element would receive the click: <div class="right login">...</div>

 (Session info: chrome=58.0.3029.110)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 10.0.15063 x86_64)'
</code>```

I don't really know what this error means. It looks like it's saying the button I want to click isn't clickable (but I can manually click it in the browser) so I assume it means the element isn't activated when I send the command? If so how can I wait until this?

答:
Plz try the below code. It will include an implicit wait until the link you trying to click becomes enable/clickable:</p>

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until<IWebElement>((d) =>
{
 IWebElement element = d.FindElement(By.Id("myid"));
 if (element.Displayed && element.Enabled)
{
    return element;
}

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

Body:
I'm trying to automate the login process to a webpage using selenium and chrome driver. The webpage login button element looks like this;

Login

So I click it using the following;

bot.FindElement(By.LinkText("Login")).Click()

Where 'bot' is my chrome driver. This works, 100% of the time it clicks the button. I'd now like to automate the next step of the processes but here's where I hit a snag. Clicking the button doesn't load a new webpage, it just runs a script on the page where I need to click another button (basically select what area I want to log into). How can I wait until the webpage has processed the first click so I can process the next click. When I try the next click I get this error;

System.InvalidOperationException: 'unknown error: Element ... is not clickable at point (542, 318). Other element would receive the click:
...

 (Session info: chrome=58.0.3029.110)
  (Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 10.0.15063 x86_64)'

I don't really know what this error means. It looks like it's saying the button I want to click isn't clickable (but I can manually click it in the browser) so I assume it means the element isn't activated when I send the command? If so how can I wait until this?

Body:
Plz try the below code. It will include an implicit wait until the link you trying to click becomes enable/clickable:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until<IWebElement>((d) =>
{
 IWebElement element = d.FindElement(By.Id("myid"));
 if (element.Displayed && element.Enabled)
{
    return element;
}

return null;
});


问:
The Requested Operation has failed- Apache error
When I'm trying to start the Apache 2.2 server it is showing the following message: The Requested Operation has failed

In command Prompt it is showing as follows:

```<code>C:\Documents and Settings\amth>net start apache2.2
The Apache2.2 service is starting.
The Apache2.2 service could not be started.

A service specific error occurred: 1.

More help is available by typing NET HELPMSG 3547.
</code>```

答: I ran into the same error message on Windows Server 2008 R2. I was using SSL and realized that my signer certs, configured in ssl.conf, where placed in the wrong folders on the file system. I placed the certs in the correct spot and the service and Apache was working fine afterwards.</p>

Body:
When I'm trying to start the Apache 2.2 server it is showing the following message: The Requested Operation has failed

In command Prompt it is showing as follows:

C:\Documents and Settings\amth>net start apache2.2
The Apache2.2 service is starting.
The Apache2.2 service could not be started.

A service specific error occurred: 1.

More help is available by typing NET HELPMSG 3547.


问:
Facebook Ads Api : Remove users from Custom Audience does not have any effect to its matching size
I am using facebook python's ads api to add and remove user's emails from custom audience.

I have successfully added user's emails to audience using these lines of code (based on Facebook examples):

```<code>#Add users
#users is a dataframe. I am creating a list of emails like this
#['a@gmail.com','b@gmail.com',....]

users_email_list = users['email'].tolist()
CustomAudience(audience_id).add_users(CustomAudience.Schema.email_hash,
users_email_list)
</code>```

I have successfully removed, but with no effect, user's emails from audience using these lines of code (based on Facebook examples):

```<code>#Remove users

CustomAudience(audience_id).remove_users(CustomAudience.Schema.email_hash,
users_email_list)
</code>```

I have included 100 different Facebook emails for this audience where I have 100% match.
After adding users emails I am visiting facebook ads console (business.facebook.com) to inspect Custom Audience. There I can see that 100 rows have been added and the size indication is 100 (with Ready status-green).
After I am running the second block of code to remove the users emails I have added. In facebook ads console I can see that 100 rows have been removed but even after waiting a couple of days size remains the same 100, with Status Ready - green. (I have tried this also with less than 100 emails)

Is there something I am missing?

答: I have contacted with Facebook's targeting team, the above method works. It takes a couple of days to be updated.</p>

Body:
I am using facebook python's ads api to add and remove user's emails from custom audience.

I have successfully added user's emails to audience using these lines of code (based on Facebook examples):

#Add users
#users is a dataframe. I am creating a list of emails like this
#['a@gmail.com','b@gmail.com',....]

users_email_list = users['email'].tolist()
CustomAudience(audience_id).add_users(CustomAudience.Schema.email_hash,
users_email_list)

I have successfully removed, but with no effect, user's emails from audience using these lines of code (based on Facebook examples):

#Remove users

CustomAudience(audience_id).remove_users(CustomAudience.Schema.email_hash,
users_email_list)

I have included 100 different Facebook emails for this audience where I have 100% match.
After adding users emails I am visiting facebook ads console (business.facebook.com) to inspect Custom Audience. There I can see that 100 rows have been added and the size indication is 100 (with Ready status-green).
After I am running the second block of code to remove the users emails I have added. In facebook ads console I can see that 100 rows have been removed but even after waiting a couple of days size remains the same 100, with Status Ready - green. (I have tried this also with less than 100 emails)

Is there something I am missing?


问:
What does "File has no header" build warning in visual studio mean
I'm building my project fine but two of the files in my unit test project give a build warning "File has no header." they're unrelated and otherwise unremarkable .cs files.  I've googled but get swamped with results for
"SA1633: The file has no header, the header Xml is invalid, or the header is not ...."

These warnings do not have an error code, what could they mean?

答:
That´s a StyleCop code analysis violation.

This means that a C# source file is missing a file header.

The file header must begin on the first line of the file and must be formatted as a block of comments containing Xml, as follows:

```<code>//-----------------------------------------------------------------------
// <copyright file="NameOfFile.cs" company="CompanyName">
//     Company copyright tag.
// </copyright>
//-----------------------------------------------------------------------
</code>```

Body:
That´s a StyleCop code analysis violation.

This means that a C# source file is missing a file header.

The file header must begin on the first line of the file and must be formatted as a block of comments containing Xml, as follows:

//-----------------------------------------------------------------------
// <copyright file="NameOfFile.cs" company="CompanyName">
//     Company copyright tag.
// </copyright>
//-----------------------------------------------------------------------


问:
Using select query with like operator and parameters in java
I want to write this query:

```<code>SELECT * FROM products
WHERE name LIKE '%?%'
OR description LIKE '%?%'
</code>```

and execute it through java in spring web application. But here problem is when I use LIKE operator it has to be with literals, but when I write '%?%' java doesn't recognize ? like placeholders for parameters, when I add parameters I get error that there is no parameters in my query.

Also if I write %?% without literals I get syntax error.

答:
You can always use concat():

```<code>SELECT *
FROM products
WHERE name LIKE CONCAT('%', ?, '%') OR
      description LIKE CONCAT('%', ?, '%');
</code>```

Or use the application to put the wildcards in the pattern string.

Body:
I want to write this query:

SELECT * FROM products
WHERE name LIKE '%?%'
OR description LIKE '%?%'

and execute it through java in spring web application. But here problem is when I use LIKE operator it has to be with literals, but when I write '%?%' java doesn't recognize ? like placeholders for parameters, when I add parameters I get error that there is no parameters in my query.

Also if I write %?% without literals I get syntax error.

Body:
You can always use concat():

SELECT *
FROM products
WHERE name LIKE CONCAT('%', ?, '%') OR
      description LIKE CONCAT('%', ?, '%');

Or use the application to put the wildcards in the pattern string.


问:
How to find all documents with all specified array values in it in mongoDB?
This is my collection

```<code>{
    "_id" : ...,
    "name" : "sport",
}
{
    "_id" : ...,
    "name" : "art",
}
{
    "_id" : ...,
    "name" : "cars",
}
</code>```

This is an array I have got ["cars","sport"]
I just want to make sure that I have got cars and sport in my collection, if not(or just one doesn't exist) I would like to receive nothing.
I'm looking for a array-friendly like query like $in but and mode.

答:
Is this what you are looking ..??

db.colllection.find( {$and: [ {"name": {$in: ["cars"]}},
                       {"name": {$in: ["sports"]}}
                     ]
})

Body:
This is my collection

{
    "_id" : ...,
    "name" : "sport",
}
{
    "_id" : ...,
    "name" : "art",
}
{
    "_id" : ...,
    "name" : "cars",
}

This is an array I have got ["cars","sport"]
I just want to make sure that I have got cars and sport in my collection, if not(or just one doesn't exist) I would like to receive nothing.
I'm looking for a array-friendly like query like $in but and mode.


问:
OCaml Core List.Assoc.find
I am having trouble running some code from the book Real World OCaml. The code snippet is on github. In particular, I am getting a type error on line 6:

List.Assoc.find counts line

I am using OCaml 4.04.1 and according to utop, the type signature of List.Assoc.find is:

('a, 'b) List.Assoc.t -> equal:('a -> 'a -> bool) -> 'a -> 'b option =
<fun

Notice the non-optional parameter equal that is missing from the code snippet above. But, according to the latest (as of June 2017) documentation for List.Assoc.find, the equal parameter is optional.

What is the purpose of the equal parameter?

答:
The function looks through a list to find a pair whose first element is equal to the value you give. It returns Some (snd pair) or None if no equal element is found. The equal parameter allows you to specify a definition for equality in case you don't want the built-in =.

For what it's worth I currently use OCaml 4.03.0, and I installed Core with OPAM. The equal parameter is optional for me:

```<code># List.Assoc.find;;
- : ('a, 'b) Core.Std.List.Assoc.t ->
    ?equal:('a -> 'a -> bool) -> 'a -> 'b option
</code>```

Title: OCaml Core List.Assoc.find

Body:
The function looks through a list to find a pair whose first element is equal to the value you give. It returns Some (snd pair) or None if no equal element is found. The equal parameter allows you to specify a definition for equality in case you don't want the built-in =.

For what it's worth I currently use OCaml 4.03.0, and I installed Core with OPAM. The equal parameter is optional for me:

# List.Assoc.find;;
- : ('a, 'b) Core.Std.List.Assoc.t ->
    ?equal:('a -> 'a -> bool) -> 'a -> 'b option


问:
Search/filter for an array
I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.

How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.

What I have:

```<code>var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeydown = function(evt) {
      $("#autocomplete").empty();

      // INSERT CODE FOR SEARCH FUNCTION

}
</code>```

I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?

```<code>var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];

inputBox.onkeydown = function(evt) {
    $("#autocomplete").empty();

    var input, filter, a, i;
    input = document.getElementById("myInput");
    filter = inputBox.value.toUpperCase();
    for (i = 0; i < ingredienten.length; i++) {
        a = ingredienten[i];
        if (a.toUpperCase().indexOf(filter) > -1) {
        //console.log(a);
        $("#autocomplete").append("<li>" + a + "</li>");
        } else {
        }
    }
</code>```

答:
I think you should use the keyup event instead and you can make use of a regex and the filter function on the array of items:

var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeyup = function(evt) {
    $("#autocomplete").empty();

    var query = $('#ingredient').val();

    // escape regex
    query = query.replace(
      /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
    );
    var queryRegExp = new RegExp('^' + query, 'i');

    var results = ingredienten.filter(function(item) {
        return queryRegExp.test(item);
    });

    results.forEach(function(item) {
        $("#autocomplete").append("
" + item + "
");
    });

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="ingredient" />
<div id="autocomplete"></div></code>```

Title: Search/filter for an array

Body:
I am making a search function for an array. I have a input[text] where for example I put 'ban', then I need all results that start with 'ban' to show up, for example banana, banana milkshake, banana(fried), etc.

How would I go about doing this? I tried, but every time I try it isn't accurate. What I tried is below.

What I have:

var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeydown = function(evt) {
      $("#autocomplete").empty();

      // INSERT CODE FOR SEARCH FUNCTION

}

I had one that came very close, however when I typed 'ban' it came up with 'Aardbei'. Which is obviously wrong. Here it is, maybe I overlooked something?

var inputBox = document.getElementById('ingredient');
var ingredienten = ["banaan", "bananen", "baan", "banana", "baaanana"];

inputBox.onkeydown = function(evt) {
    $("#autocomplete").empty();

    var input, filter, a, i;
    input = document.getElementById("myInput");
    filter = inputBox.value.toUpperCase();
    for (i = 0; i < ingredienten.length; i++) {
        a = ingredienten[i];
        if (a.toUpperCase().indexOf(filter) > -1) {
        //console.log(a);
        $("#autocomplete").append("
" + a + "
");
        } else {
        }
    }

Body:
I think you should use the keyup event instead and you can make use of a regex and the filter function on the array of items:

var inputBox = document.getElementById('ingredient');
var ingredienten = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana"]

inputBox.onkeyup = function(evt) {
    $("#autocomplete").empty();

    var query = $('#ingredient').val();

    // escape regex
    query = query.replace(
      /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"
    );
    var queryRegExp = new RegExp('^' + query, 'i');

    var results = ingredienten.filter(function(item) {
        return queryRegExp.test(item);
    });

    results.forEach(function(item) {
        $("#autocomplete").append("<li>" + item + "</li>");
    });

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="ingredient" />
<div id="autocomplete"></div>


问:
I think I install the tomcat correctly , but why it can't run correctly?
I can visit my localhost, but there are many Error in my program.

答:
There is some configuration you did that is pointing to an non-exist directory path.

open your terminal and execute cd <error's dir path>


问:
Relative link to root of IIS Application
In IIS 8.5 I have a Default Web Site under which I have multiple Applications. Several of these Applications are actually the same website code deployed for different user groups, each pointing to different databases with different configurations and so on.

Is it possible to create a hyperlink in my website which links to the root of the APPLICATION rather than the WEBSITE? If I use something like Go Home then clicking on the link doesn't navigate to http://myserver/myapplication, it links to http://myserver.

Obviously I could hard code the link, but that would mean having to edit the code for each deployment of the website. I could probably get around that by storing the root URL in a configuration file, and maybe that's the only way to achieve what I'm looking for, but it seems overly complicated!

Additionally, when I'm running the website in debug on my development machine, the URL is something like http://localhost:12345 (i.e. there is no application name), so even if I did store the root URL somewhere, it wouldn't work in development without additional work.

I know I could use a relative path like Go Home to navigate upwards a certain number of levels, but I'm trying to use this link on a custom error page, so ideally I'd like it to work even if the user has somehow navigated to something like http://myserver/myapplication/foo/bar/foo/bar/foo/bar, in which case my link needs to navigate up six levels. The point is, I don't know how many levels down the page containing the link might be.

I naively assumed there'd be a shortcut in the manner of href="/"... to get to the application root, but it seems I was wrong!

答:
Prior to version 4 of asp.net-mvc, you would use the following code:

```<code><a href="Url.Content("~/") ">Root</a>
</code>```

With version 4 and higher, razor-2 automatically looks for tilde's so you can just:

```<code><a href="~/">Root</a>
</code>```

Body:
In IIS 8.5 I have a Default Web Site under which I have multiple Applications. Several of these Applications are actually the same website code deployed for different user groups, each pointing to different databases with different configurations and so on.

Is it possible to create a hyperlink in my website which links to the root of the APPLICATION rather than the WEBSITE? If I use something like Go Home then clicking on the link doesn't navigate to http://myserver/myapplication, it links to http://myserver.

Obviously I could hard code the link, but that would mean having to edit the code for each deployment of the website. I could probably get around that by storing the root URL in a configuration file, and maybe that's the only way to achieve what I'm looking for, but it seems overly complicated!

Additionally, when I'm running the website in debug on my development machine, the URL is something like http://localhost:12345 (i.e. there is no application name), so even if I did store the root URL somewhere, it wouldn't work in development without additional work.

I know I could use a relative path like Go Home to navigate upwards a certain number of levels, but I'm trying to use this link on a custom error page, so ideally I'd like it to work even if the user has somehow navigated to something like http://myserver/myapplication/foo/bar/foo/bar/foo/bar, in which case my link needs to navigate up six levels. The point is, I don't know how many levels down the page containing the link might be.

I naively assumed there'd be a shortcut in the manner of <a href="/"... to get to the application root, but it seems I was wrong!

Body:
Prior to version 4 of asp.net-mvc, you would use the following code:

<a href="Url.Content("~/") ">Root</a>

With version 4 and higher, razor-2 automatically looks for tilde's so you can just:

<a href="~/">Root</a>


问:
Android Java Viewpager loads in the same viewPager view position
I'm new in Java/Android programming.

I've got a Fragment with tabLayout and viewPager. This fragment get's a list of groupId/groupName from the server then needs to create one page for each groupId. It sends the value to the adapter (the fragment to show in the viewpager pages is always ContentRoster() but the groupId define the data to show)

My issue is that this ContentRoster() fragment only loads in position 0 of the viewpager. I can swipe and slect the tabs as expected, but all loads in the same view...

If I have two sets of groupId, the first one will load in position 0, then the second one groupId#2 (which is autoloaded to populate next view) update position 0 view and erase groupID#1 view.

```<code>    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        super.onPostExecute(result);

        TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
        final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        tabLayout.setupWithViewPager(viewPager);

        AdapterViewPager mCustomPagerAdapter = new AdapterViewPager(getChildFragmentManager());

        //add Fragment with specific arguments
        for(int i = 0; i < result.size() ; i++) {
            mCustomPagerAdapter.addFragment(new ContentRoster(), (result.get(i)).get("groupname"), (result.get(i)).get("groupid") );
        }

        //Set adapter if not null
        if (viewPager != null) {
            viewPager.setAdapter(mCustomPagerAdapter);
            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }
        });

    }
</code>```

The adapter looks like this :

```<code>import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class AdapterViewPager extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    private final List<String> mFragmentParamsList = new ArrayList<>();

    public void addFragment(Fragment fragment, String title, String params) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
        mFragmentParamsList.add(params);
    }

    public AdapterViewPager(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        String groupId = mFragmentParamsList.get(position);
        Fragment fragment = ContentRoster.newInstance(groupId);
        return fragment;
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}
</code>```

and the ContentRoster() Fragment is like this :
I retrieve the groupId from the bundle and 'LoadRosterList().execute(groupId)' charge the data and show only the groupId data in line with the selected tab.

```<code>   public static ContentRoster newInstance(String groupId) {
        ContentRoster ContentRoster = new ContentRoster();

        Bundle args = new Bundle();
        args.putString("groupId", groupId);
        ContentRoster.setArguments(args);

        return ContentRoster;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.content_listview, container, false);

        Bundle args = getArguments();
        groupId = args.getString("groupId");

        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        new LoadRosterList().execute(groupId);

        return view;
    }
</code>```

UPDATE :
Could this be link to the last part where I update the listview in the ContentRoster Fragment (which is shown in the viewPager)
As I get the listview Id from the activity?

```<code>protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
    super.onPostExecute(result);

    try {
        // Getting adapter by passing xml data ArrayList
        ListView mListView;
        mListView = (ListView) getActivity().findViewById(R.id.listView);

        AdapterRoster adapter = new AdapterRoster(getActivity().getApplicationContext(), result);
        mListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        progressBar.setVisibility(View.GONE); //Effacage du Progress Bar

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                // Send intent to SingleViewActivity
                Intent i = new Intent(getActivity().getApplicationContext(), ActivitySingleGuardian.class);
                // Pass image index
                i.putExtra("psnid", ((TextView) v.findViewById(R.id.psnid)).getText().toString());
                i.putExtra("rank", ((TextView) v.findViewById(R.id.rank)).getText().toString());
                i.putExtra("lastplay", ((TextView) v.findViewById(R.id.lastplay)).getText().toString());
                i.putExtra("bungiename", ((TextView) v.findViewById(R.id.bungiename)).getText().toString());
                i.putExtra("bungieid", ((TextView) v.findViewById(R.id.bungieid)).getText().toString());
                i.putExtra("picpath", ((TextView) v.findViewById(R.id.picpath)).getText().toString());
                i.putExtra("membershipType", ((TextView) v.findViewById(R.id.membershipType)).getText().toString());
                startActivity(i);
            }
        });

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}
</code>```

答:
Finally found the issue !
This was on my last part when I call the adapter inside the ContentRoster() Fragment which is part of the viewPager !

I was using :
mListView = (ListView) getActivity().findViewById(R.id.listView);

Instead of :
mListView = (ListView) getView().findViewById(R.id.listView);

The list now show in the right place!

Thanks for all guys !

Body:
I'm new in Java/Android programming.

I've got a Fragment with tabLayout and viewPager. This fragment get's a list of groupId/groupName from the server then needs to create one page for each groupId. It sends the value to the adapter (the fragment to show in the viewpager pages is always ContentRoster() but the groupId define the data to show)

My issue is that this ContentRoster() fragment only loads in position 0 of the viewpager. I can swipe and slect the tabs as expected, but all loads in the same view...

If I have two sets of groupId, the first one will load in position 0, then the second one groupId#2 (which is autoloaded to populate next view) update position 0 view and erase groupID#1 view.

    protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
        super.onPostExecute(result);

        TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.tabLayout);
        final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.viewPager);
        tabLayout.setupWithViewPager(viewPager);

        AdapterViewPager mCustomPagerAdapter = new AdapterViewPager(getChildFragmentManager());

        //add Fragment with specific arguments
        for(int i = 0; i < result.size() ; i++) {
            mCustomPagerAdapter.addFragment(new ContentRoster(), (result.get(i)).get("groupname"), (result.get(i)).get("groupid") );
        }

        //Set adapter if not null
        if (viewPager != null) {
            viewPager.setAdapter(mCustomPagerAdapter);
            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        }

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                if (viewPager != null) {
                    Log.i("#TAB_POS", "" + tab.getPosition());
                    viewPager.setCurrentItem(tab.getPosition());
                }
            }
        });

    }

The adapter looks like this :

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class AdapterViewPager extends FragmentPagerAdapter {

    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    private final List<String> mFragmentParamsList = new ArrayList<>();

    public void addFragment(Fragment fragment, String title, String params) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
        mFragmentParamsList.add(params);
    }

    public AdapterViewPager(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        String groupId = mFragmentParamsList.get(position);
        Fragment fragment = ContentRoster.newInstance(groupId);
        return fragment;
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }

}

and the ContentRoster() Fragment is like this :
I retrieve the groupId from the bundle and 'LoadRosterList().execute(groupId)' charge the data and show only the groupId data in line with the selected tab.

   public static ContentRoster newInstance(String groupId) {
        ContentRoster ContentRoster = new ContentRoster();

        Bundle args = new Bundle();
        args.putString("groupId", groupId);
        ContentRoster.setArguments(args);

        return ContentRoster;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.content_listview, container, false);

        Bundle args = getArguments();
        groupId = args.getString("groupId");

        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        new LoadRosterList().execute(groupId);

        return view;
    }

UPDATE :
Could this be link to the last part where I update the listview in the ContentRoster Fragment (which is shown in the viewPager)
As I get the listview Id from the activity?

protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
    super.onPostExecute(result);

    try {
        // Getting adapter by passing xml data ArrayList
        ListView mListView;
        mListView = (ListView) getActivity().findViewById(R.id.listView);

        AdapterRoster adapter = new AdapterRoster(getActivity().getApplicationContext(), result);
        mListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        progressBar.setVisibility(View.GONE); //Effacage du Progress Bar

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                // Send intent to SingleViewActivity
                Intent i = new Intent(getActivity().getApplicationContext(), ActivitySingleGuardian.class);
                // Pass image index
                i.putExtra("psnid", ((TextView) v.findViewById(R.id.psnid)).getText().toString());
                i.putExtra("rank", ((TextView) v.findViewById(R.id.rank)).getText().toString());
                i.putExtra("lastplay", ((TextView) v.findViewById(R.id.lastplay)).getText().toString());
                i.putExtra("bungiename", ((TextView) v.findViewById(R.id.bungiename)).getText().toString());
                i.putExtra("bungieid", ((TextView) v.findViewById(R.id.bungieid)).getText().toString());
                i.putExtra("picpath", ((TextView) v.findViewById(R.id.picpath)).getText().toString());
                i.putExtra("membershipType", ((TextView) v.findViewById(R.id.membershipType)).getText().toString());
                startActivity(i);
            }
        });

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}


问:
C++ 'wrapper class' for XML library
So I've been attempting to create some classes around the xerces XML library so I can 'hide' it from the rest of my project the underlying xml library stays independent from the rest of my project.

This was supposed to be a fairly easy task, however it seems entirely impossible to hide a library from the rest of a project by writing some classes around it.

Have I got the wrong approach or is my 'wrapper' idea completely silly?

I end up with something like this:

```<code>DOMElement* root();  //in my 'wrapper' class, however this DOMElement is part of the xerces library, at this point my 'wrapper' is broken.  Now I have to use the xerces library everywhere I want to use this function.
</code>```

Where is my thinking gone wrong?

答: I would recommend avoiding the wrapper in the first stage. Just make sure that the layers and their borders are clear, i.e. the network layer takes care of serializing/deserializing the XML, and from there on you only use your internal types. If you do this, and at a later stage you need to replace xerces with any other library, just replace the serialization layer. That is, instead of wrapping each XML object, just wrap the overall operation: serialize/deserialize.

ContentLicense: CC BY-SA 2.5

Title: C++ 'wrapper class' for XML library

Body:
So I've been attempting to create some classes around the xerces XML library so I can 'hide' it from the rest of my project the underlying xml library stays independent from the rest of my project.

This was supposed to be a fairly easy task, however it seems entirely impossible to hide a library from the rest of a project by writing some classes around it.

Have I got the wrong approach or is my 'wrapper' idea completely silly?

I end up with something like this:

DOMElement* root();  //in my 'wrapper' class, however this DOMElement is part of the xerces library, at this point my 'wrapper' is broken.  Now I have to use the xerces library everywhere I want to use this function.

Where is my thinking gone wrong?


问:
How to clear input field whitespace in live ajax search after I click on a result
I have a simple ajax live search script using PHP jQuery and ajax. It all works great but the input box does not clear completely so the results box doesn't disappear unless I manually clear it..

JS -

```<code><script type="text/javascript">
        $(document).ready(function(){
            $('.search-box input[type="text"]').on("keyup input", function(){
                /* Get input value on change */
                var inputVal = $(this).val();
                var resultDropdown = $(this).siblings(".result");
                if(inputVal.length){
                    $.get("backend-search.php", {term: inputVal}).done(function(data){
                        // Display the returned data in browser
                        resultDropdown.html(data);
                    });

                } else{
                    resultDropdown.empty();
                }
            });

            // Set search input value on click of result item
            $(document).on("click", ".result", function(){
                $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                $(this).parent(".result").empty();

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

PHP -

```<code>$user = $_GET['user'];

$term = mysqli_real_escape_string($conn, $_REQUEST['term']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM prospects WHERE dealer_name LIKE '" . $term . "%'";
if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $dealer_name = $row['dealer_name'];
            echo "<form method='post' class='editForm'>
             <input type='hidden' name='dealer' value='$dealer_name'/>
                        <input type='submit' id='subDealer' value='$dealer_name'/>
                    </form>";
        }
        // Close result set
    } else{
        echo "<p>No matches found</p>";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
</code>```

HTML -

```<code> <div class="search-box">
     <input type="text" id="searchBox" autocomplete="off" placeholder="Search dealer..." />
     <div class="result"></div>
 </div>
</code>```

Like it said it all works but there is blank whitespace in the input field (#searchBox) which will not allow the .result to clear..

Thanks!

答:
Use jQuery trim() function   </p>

```<code> <script type="text/javascript">
            $(document).ready(function(){
                $('.search-box input[type="text"]').on("keyup input", function(){
                    /* Get input value on change */
                    var inputVal1 = $(this).val();
                    var inputVal = $.trim(inputVal1);
                    var resultDropdown = $(this).siblings(".result");
                    if(inputVal.length){
                        $.get("backend-search.php", {term: inputVal}).done(function(data){
                            // Display the returned data in browser
                            resultDropdown.html(data);
                        });

                    } else{
                        resultDropdown.empty();
                    }
                });

                // Set search input value on click of result item
                $(document).on("click", ".result", function(){
                    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                    $(this).parent(".result").empty();

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

Body:
I have a simple ajax live search script using PHP jQuery and ajax. It all works great but the input box does not clear completely so the results box doesn't disappear unless I manually clear it..

JS -

PHP -

$user = $_GET['user'];

$term = mysqli_real_escape_string($conn, $_REQUEST['term']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM prospects WHERE dealer_name LIKE '" . $term . "%'";
if($result = mysqli_query($conn, $sql)){
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_array($result)){
            $dealer_name = $row['dealer_name'];
            echo "<form method='post' class='editForm'>
             <input type='hidden' name='dealer' value='$dealer_name'/>
                        <input type='submit' id='subDealer' value='$dealer_name'/>
                    </form>";
        }
        // Close result set
    } else{
        echo "
No matches found
";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}

HTML -

     <input type="text" id="searchBox" autocomplete="off" placeholder="Search dealer..." />

Like it said it all works but there is blank whitespace in the input field (#searchBox) which will not allow the .result to clear..

Thanks!

Body:
Use jQuery trim() function

 <script type="text/javascript">
            $(document).ready(function(){
                $('.search-box input[type="text"]').on("keyup input", function(){
                    /* Get input value on change */
                    var inputVal1 = $(this).val();
                    var inputVal = $.trim(inputVal1);
                    var resultDropdown = $(this).siblings(".result");
                    if(inputVal.length){
                        $.get("backend-search.php", {term: inputVal}).done(function(data){
                            // Display the returned data in browser
                            resultDropdown.html(data);
                        });

                    } else{
                        resultDropdown.empty();
                    }
                });

                // Set search input value on click of result item
                $(document).on("click", ".result", function(){
                    $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
                    $(this).parent(".result").empty();

                });
            });
        </script>


答: Are you fetching this JSON metadata every time the song is played? If so, that doesn't sound like a good idea. The ideal would be to add song metadata when adding a song to the playlist, then either update it periodically (once a couple of days perhaps) and save that information into a SQLite database for later retrieval.  </p>

Title: How can I implement automatic loading for JSON object in android?

Body: I am working on an audio stream android app and I parsed JSON object from a server to a TextView to display 'now Playing'  for the song name and artist. So when the play button is clicked, the song name playing artist is displayed to the user. The problem is that I want this automatically loaded to the app view when JSON URL link is updated from the server. I don't want the user pressing pause and play to update the view from the app. How do I go about this because I don't want the user restarting the service each time a new song isPlaying to get song information.


问:
CRM OData DateTime Timezone Issue
I am running into an issue where CRM doesn't appear to be treating the DateTime correctly with OData.  Specifically, we are trying to create a custom record called new_vod with a start and end time (and a few other attributes that I have removed from here for simplicity) using a JavaScript call to the CrmRestKit.  When the user performing this function is not in the same time zone as the server, the time is incorrect by whatever the offset between the server and the user happens to be.

For example, if my CRM user is in Mountain Time and the Server is in Eastern Time, the Start Time will be 2 hours from now (even though it should be now) when looking at the newly created record in CRM.  The user's computer's timezone doesn't seem to have any impact on the result.  (I'm comparing the "new_starttime" against the "Created On" time to confirm I'm not just viewing the data wrong, and the created on time is 2 hours before the start time in this scenario).

Here is the relevant snippet:

```<code>var startTime = new Date();

//Add 90 minutes to the current date/time
var endTime = new Date();
endTime.setMinutes(startTime.getMinutes() + 90);

//Create a cvt_VOD record
var newVOD = {
    'new_starttime': startTime,
    'new_endtime': endTime
};

var createdVOD = CrmRestKit.Create('new_vod', newVOD)
...
</code>```

I noticed that when I debug the create of the new_vod record in a pre-stage plugin, the "conversion" to UTC has already occurred incorrectly, so it leads me to believe that the Rest Call itself isn't right.

Can anyone shed any light on why this would be happening?

FYI, We're on CRM 2015 on-premise.

答:
Try this working solution by Somesh:

https://community.dynamics.com/crm/b/dynamicscrmbestpractices/archive/2014/12/04/crm-timezone-issue-using-javascript

Title: CRM OData DateTime Timezone Issue

Body:
I am running into an issue where CRM doesn't appear to be treating the DateTime correctly with OData.  Specifically, we are trying to create a custom record called new_vod with a start and end time (and a few other attributes that I have removed from here for simplicity) using a JavaScript call to the CrmRestKit.  When the user performing this function is not in the same time zone as the server, the time is incorrect by whatever the offset between the server and the user happens to be.

For example, if my CRM user is in Mountain Time and the Server is in Eastern Time, the Start Time will be 2 hours from now (even though it should be now) when looking at the newly created record in CRM.  The user's computer's timezone doesn't seem to have any impact on the result.  (I'm comparing the "new_starttime" against the "Created On" time to confirm I'm not just viewing the data wrong, and the created on time is 2 hours before the start time in this scenario).

Here is the relevant snippet:

var startTime = new Date();

//Add 90 minutes to the current date/time
var endTime = new Date();
endTime.setMinutes(startTime.getMinutes() + 90);

//Create a cvt_VOD record
var newVOD = {
    'new_starttime': startTime,
    'new_endtime': endTime
};

var createdVOD = CrmRestKit.Create('new_vod', newVOD)
...

I noticed that when I debug the create of the new_vod record in a pre-stage plugin, the "conversion" to UTC has already occurred incorrectly, so it leads me to believe that the Rest Call itself isn't right.

Can anyone shed any light on why this would be happening?

FYI, We're on CRM 2015 on-premise.


问:
Algorithm to find subset within two sets of integers whose sums match
I'm looking for an algorithm which can take two sets of integers (both positive and negative) and find subsets within each that have the same sum.

The problem is similar to the subset sum problem except that I'm looking for subsets on both sides.

Here's an example:

List A {4, 5, 9, 10, 1}

List B {21, 7, -4, 180}

So the only match here is:
{10, 1, 4, 9} <=> {21, 7, -4}

Does anyone know if there are existing algorithms for this kinda problems?

So far, the only solution I have is a brute force approach which tries every combination but it performs in Exponential time and I've had to put a hard limit on the number of elements to consider to avoid it from taking too long.

The only other solution I can think of is to run a factorial on both lists and look for equalities there but that is still not very efficient and takes exponentially longer as the lists get bigger.

答: subset sum is Np-complete and you can polynomially reduce your problem to it, so your problem is NP-complete too.</p>

OwnerDisplayName: theburningmonk

LastEditorDisplayName: Andrew Rollings

OwnerDisplayName: Meidan Alon


问:
What are some example javascript frameworks that people use?
I am really big fan of jQuery, but I don't see it as a framework for a site, more like a library.  I am looking for some sort of framework that will give me the tools to build really structured applications in javaScript.  I have found backbone.js, but find it somewhat confusing.  Is that a good one, and are there others similar to it?  an MVC pattern would be really cool, but I havent found anything.</p>

答:
jQuery and YUI 3: A Tale of Two JavaScript Libraries is a story about a jQuery developer that found that YUI3 was more "framework-like" and apt for his project.

I've been using YUI2 for years and it never disappointed me.


问:
Send automated email for specific value of a drop down column
I have tried many different codes to send an email alert when column F in my Google sheet has the value "Yes". I am selecting this value from a drop down. But no emails are sent. I have tried different emails also. Nothing works. This is the code I am trying right now. </p>

```<code>function Email(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName("FY");
  var row = s.getActiveRange().getRow();
  var status = s.getRange(row,6).getValue();
  var subject = 'subject';   var message = 'body';
  var email ="";
  if (e.value === "Yes" && e.range.getColumn() === 6) {
   GmailApp.sendEmail(email,subject,message);
  }
};
</code>```

答:
You need to use an installed trigger see here to use this on edit script.

Go to 'Edit' -> 'Current project's triggers' and set a trigger as shown below.

Code:

```<code>function onEdit(e){
   var getRange = e.range;
   var getValue = getRange.getValue();
   var getCol = getRange.getColumn();

    if(getValue == "Yes" && getCol == 6){
       var subject = 'subject';
       var message = 'body';
       var email = "---------------";
    MailApp.sendEmail(email, subject, message);
  }
 }
</code>```

Body:
I have tried many different codes to send an email alert when column F in my Google sheet has the value "Yes". I am selecting this value from a drop down. But no emails are sent. I have tried different emails also. Nothing works. This is the code I am trying right now.

function Email(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName("FY");
  var row = s.getActiveRange().getRow();
  var status = s.getRange(row,6).getValue();
  var subject = 'subject';   var message = 'body';
  var email ="";
  if (e.value === "Yes" && e.range.getColumn() === 6) {
   GmailApp.sendEmail(email,subject,message);
  }
};

Body:
You need to use an installed trigger see here to use this on edit script.

Go to 'Edit' -> 'Current project's triggers' and set a trigger as shown below.

Code:

function onEdit(e){
   var getRange = e.range;
   var getValue = getRange.getValue();
   var getCol = getRange.getColumn();

    if(getValue == "Yes" && getCol == 6){
       var subject = 'subject';
       var message = 'body';
       var email = "---------------";
    MailApp.sendEmail(email, subject, message);
  }
 }


问:
Bootstrap-table css not loading after ajax call
i'm having trouble loading CSS to bootstrap-table after I call it by Ajax.

This table is appended to my view by Ajax for each click event fired, but the bootstrap-table CSS hasn't been loaded to each one:

```<code><div id="sala_2">
  <h3>Sala 2</h3>
  <table id="tb_sala_2"
     data-toggle="table"
     data-toolbar="#toolbar"
     data-click-to-select="true"
     data-single-select="true">
    <thead>
      <tr>
        <th data-field="state" data-checkbox="true" data-halign="center" data-align="center"></th>
        <th data-field="id" data-halign="center" data-align="center">ID</th>
        <th data-field="cargo_id" class="hidden_field" data-halign="center" data-align="center">Cargo ID</th>
        <th data-field="cargo" data-halign="center" data-align="center">Cargo</th>
        <th data-field="quantidade_de_candidatos" data-halign="center" data-align="center">Quantidade de candidatos</th>
      </tr>
    </thead>
    <tbody>
        <% i = 0 %>
        <% @cargos.each do |cargo| %>
          <tr>
            <td></td>
            <td><%= i %></td>
            <% i = i + 1 %>
            <td class="hidden_field"><%= cargo.id %></td>
            <td><%= cargo.nome %></td>
            <td class="quantidade_de_candidatos"> 0 </td>
          </tr>
       <% end %>
   </tbody>
 </table>
</div>
</code>```

Application.js:

```<code>//= require jquery
//= require jquery_ujs
//= require bootstrap-table
//= require turbolinks
//= require_tree .
</code>```

Application.css:

```<code>*= require bootstrap-table
*= require_tree .
*= require_self
</code>```

Observation: When the page is loaded for the first time, the bootstrap-table CSS has been loaded right. The problem happen when I use ajax to append another table. So, I believe that the issue is the way rails works loading assets.

答:
I was able to solve the problem calling this method in Ajax success function:

```<code>$('#table').bootstrapTable();
</code>```

With that, the default methods and styles from the gem were filled out.

Body:
i'm having trouble loading CSS to bootstrap-table after I call it by Ajax.

This table is appended to my view by Ajax for each click event fired, but the bootstrap-table CSS hasn't been loaded to each one:

Sala 2

        ID
        Cargo ID
        Cargo
        Quantidade de candidatos

        <% i = 0 %>
        <% @cargos.each do |cargo| %>

            <%= i %>
            <% i = i + 1 %>
            <%= cargo.id %>
            <%= cargo.nome %>
             0

       <% end %>

Application.js:

//= require jquery
//= require jquery_ujs
//= require bootstrap-table
//= require turbolinks
//= require_tree .

Application.css:

*= require bootstrap-table
*= require_tree .
*= require_self

Observation: When the page is loaded for the first time, the bootstrap-table CSS has been loaded right. The problem happen when I use ajax to append another table. So, I believe that the issue is the way rails works loading assets.

Body:
I was able to solve the problem calling this method in Ajax success function:

$('#table').bootstrapTable();

With that, the default methods and styles from the gem were filled out.


问:
How can I list all databases and all tables of my databases with a final "Attach" and list total row of each table in SQL Server?
I did this. But unfortunately that return all in many table. I want to return all in one unique table. Maybe using "UNION" but I don't know the way to do.

This is my code:

```<code>EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
 from [?].sys.tables t inner join [?].sys.schemas s
 on t.schema_id = s.schema_id
 inner join [?].sys.partitions si on t.object_id  = si.object_id
 where t.name like "%ATTACH" group by s.name,t.name'`
</code>```

答:
You cannot do it in a single query.

You could query the sys.databases table to get a temporary table of all your databases, and then run a dynamic query on each database to store the results of the query in your question all in another temporary table.

Then at the end, you just select all rows from the last temporary table.

Body:
I did this. But unfortunately that return all in many table. I want to return all in one unique table. Maybe using "UNION" but I don't know the way to do.

This is my code:

EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
 from [?].sys.tables t inner join [?].sys.schemas s
 on t.schema_id = s.schema_id
 inner join [?].sys.partitions si on t.object_id  = si.object_id
 where t.name like "%ATTACH" group by s.name,t.name'`


问:
Running a program on uninstall
I want to run a program when my software is being un-installed, it is a simple form that should gather some feedback on why people are un-installing my software.

I found some WiX examples that works to some degree.

It works pretty fine with a standard windows program (notepad), but when I try to run my own program, it does not work. I think the problems is that the program is removed, before it has been run.

I have tried to print the logs, but they did not give me any clues of what to do.

My code so far:

```<code><CustomAction Id="LaunchFeedBackForm"
 ExeCommand="notepad.exe" Directory="INSTALLDIR"
 Return="asyncWait" >REMOVE="ALL"</CustomAction>

<InstallExecuteSequence>
    <Custom Action="LaunchFeedBackForm" After="InstallValidate"/>
</InstallExecuteSequence>
</code>```

So I need in some way the un-install process to halt or what ever, until the user has closed the feedback form. After the form has been closed, it should continue and remove all software including the feedback form program.

答:
So I need in some way the un-install process to halt or what ever,
  until the user has closed the feedback form. After the form has been
  closed, it should continue and remove all software including the
  feedback form program.

To do this one would set After="InstallValidate"

```<code><InstallExecuteSequence>
<Custom Action="InstallCustomLogic" After="InstallFinalize" />
<Custom Action="UninstallCustomLogic"
After="InstallValidate" >
NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")
</Custom>
</InstallExecuteSequence>
</code>```

Set Return attribute to check so that the installer will halt until the specified executable returns.

```<code><CustomAction Id="UninstallCustomLogic"
Directory="INSTALLFOLDER"
ExeCommand="[INSTALLFOLDER]\RetailConnectCustomLogic.exe uninstall"
Return="check"
/>
</code>```

This is useful in the event where you need to run something located in the program directory before uninstalling the program. One could also set the attribute to ignore if it doesn't return 0

Title: Running a program on uninstall

Body:
I want to run a program when my software is being un-installed, it is a simple form that should gather some feedback on why people are un-installing my software.

I found some WiX examples that works to some degree.

It works pretty fine with a standard windows program (notepad), but when I try to run my own program, it does not work. I think the problems is that the program is removed, before it has been run.

I have tried to print the logs, but they did not give me any clues of what to do.

My code so far:

<CustomAction Id="LaunchFeedBackForm"
 ExeCommand="notepad.exe" Directory="INSTALLDIR"
 Return="asyncWait" >REMOVE="ALL"</CustomAction>

<InstallExecuteSequence>
    <Custom Action="LaunchFeedBackForm" After="InstallValidate"/>
</InstallExecuteSequence>

So I need in some way the un-install process to halt or what ever, until the user has closed the feedback form. After the form has been closed, it should continue and remove all software including the feedback form program.

Body:
So I need in some way the un-install process to halt or what ever,
  until the user has closed the feedback form. After the form has been
  closed, it should continue and remove all software including the
  feedback form program.

To do this one would set After="InstallValidate"

<InstallExecuteSequence>
<Custom Action="InstallCustomLogic" After="InstallFinalize" />
<Custom Action="UninstallCustomLogic"
After="InstallValidate" >
NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")
</Custom>
</InstallExecuteSequence>

Set Return attribute to check so that the installer will halt until the specified executable returns.

<CustomAction Id="UninstallCustomLogic"
Directory="INSTALLFOLDER"
ExeCommand="[INSTALLFOLDER]\RetailConnectCustomLogic.exe uninstall"
Return="check"
/>

This is useful in the event where you need to run something located in the program directory before uninstalling the program. One could also set the attribute to ignore if it doesn't return 0