问:
Mapstruct self defined mapper AND automatically generated one
I understand Mapstruct allows me to define my own mapper logic, I am doing it like this:

```<code>@Mapper(componentModel = "spring")
public abstract class ProjectMapper {

    public ProjectInfo map(ProjectEntity projectEntity) {
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setName(projectEntity.getName());
        projectInfo.setDescription(projectEntity.getDescription());

        // Specific logic that forces me to define it myself
        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }
        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
        return projectInfo;
    }
}
</code>```

It works just fine, but I also want Mapstruct's generated mappers, but they have to be defined in an interface, is there a way to group up both of these mapper types?

答:
NOTE: Untested. I used the following solution once in a Spring-Boot project using MapStruct version 1.0.0.Final.

Customizing standard mapping process is fairly well documented.

One of the way to customize your mappings are 'AfterMapping' and 'BeforeMapping' hooks:

```<code>@Mapper
public abstract class ProjectMapperExtension {

    @AfterMapping
    public void mapProjectEntityToProjectInfo(ProjectEntity projectEntity, @MappingTarget ProjectInfo projectInfo) {

        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }

        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
    }
}
</code>```

Then annotate the standard mapper interface with uses and exclude the custom mapped fields from the standard mapping:

```<code>@Mapper(componentModel = "spring", uses = {ProjectMapperExtension.class})
public interface ProjectMapper {

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "organisation", ignore = true)
    ProjectInfo mapProjectEntityToProjectInfo(ProjectEntity projectEntity);
}
</code>```

Body:
I understand Mapstruct allows me to define my own mapper logic, I am doing it like this:

@Mapper(componentModel = "spring")
public abstract class ProjectMapper {

    public ProjectInfo map(ProjectEntity projectEntity) {
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setName(projectEntity.getName());
        projectInfo.setDescription(projectEntity.getDescription());

        // Specific logic that forces me to define it myself
        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }
        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
        return projectInfo;
    }
}

It works just fine, but I also want Mapstruct's generated mappers, but they have to be defined in an interface, is there a way to group up both of these mapper types?

Body:
NOTE: Untested. I used the following solution once in a Spring-Boot project using MapStruct version 1.0.0.Final.

Customizing standard mapping process is fairly well documented.

One of the way to customize your mappings are 'AfterMapping' and 'BeforeMapping' hooks:

@Mapper
public abstract class ProjectMapperExtension {

    @AfterMapping
    public void mapProjectEntityToProjectInfo(ProjectEntity projectEntity, @MappingTarget ProjectInfo projectInfo) {

        if (projectEntity.getId() != null) {
            projectInfo.setId(projectEntity.getId());
        }

        if (projectEntity.getOrganisation() != null) {
            projectInfo.setOrganisation(projectEntity.getOrganisation().getName());
        }
    }
}

Then annotate the standard mapper interface with uses and exclude the custom mapped fields from the standard mapping:

@Mapper(componentModel = "spring", uses = {ProjectMapperExtension.class})
public interface ProjectMapper {

    @Mapping(target = "id", ignore = true)
    @Mapping(target = "organisation", ignore = true)
    ProjectInfo mapProjectEntityToProjectInfo(ProjectEntity projectEntity);
}


来源: stackexchange

问:
Ionic notifications information
I'm trying to obtain information about a sent notification. But i don't know exactly how to proceed. This is my javascript code:

```<code>    function obtenerInformacion(uuid){
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText);

      }
    });

    xhr.open("POST", "https://api.ionic.io/push/notifications/"+uuid);
    xhr.setRequestHeader("Access-Control-Allow-Origin","*");
    xhr.setRequestHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS");
    xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type");
    xhr.setRequestHeader("content-type", "application/json");
    xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
    xhr.send();
}
</code>```

I'm getting this error:error

Sorry for my english.

EDIT: Fixed. Apparently the request had to be made by GET

```<code>xhr.open("GET", "https://api.ionic.io/push/notifications/"+uuid);

xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
xhr.send();
</code>```

Thank you very much to all

答: Try downloading and enabling this chrome plugin.</p>

ContentLicense: CC BY-SA 3.0

Title: Ionic notifications information

Body:
I'm trying to obtain information about a sent notification. But i don't know exactly how to proceed. This is my javascript code:

    function obtenerInformacion(uuid){
        var xhr = new XMLHttpRequest();
        xhr.withCredentials = true;

        xhr.addEventListener("readystatechange", function () {
          if (this.readyState === 4) {
            console.log(this.responseText);

      }
    });

    xhr.open("POST", "https://api.ionic.io/push/notifications/"+uuid);
    xhr.setRequestHeader("Access-Control-Allow-Origin","*");
    xhr.setRequestHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS");
    xhr.setRequestHeader("Access-Control-Allow-Headers","Content-Type");
    xhr.setRequestHeader("content-type", "application/json");
    xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
    xhr.send();
}

I'm getting this error:error

Sorry for my english.

EDIT: Fixed. Apparently the request had to be made by GET

xhr.open("GET", "https://api.ionic.io/push/notifications/"+uuid);

xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxN2FlYWZlMC02ZTg4LTQ3NDItOWMxMC04ZTczY2IwNWU4NGMifQ.n25i9yTWdqFauTd6xnfW0Uats_x7EvnB42KhoFu8E04");
xhr.send();

Thank you very much to all


问:
Angular form reset is clearing the default selected value
Im using angular 4 for my app and have a select inside my reactive form like this:

```<code>  <select class="form-control" formControlName="persons">
    <option value="" selected>Select default</option>
     <option *ngFor="let p of persons" [value]="p">{{p}}</option>
   </select>
</code>```

It works nice, first time it renders with the Select default option selected. But when i do a myForm.reset(), the form goes to initial state as expected, but the selected default value is no more selected. How can i reset the form and keep de default value selected?

答:
Assuming you initialize the form in the constructor with default values, just set it back to the same thing.

For example, if in your constructor you set the form as such:

```<code>constructor() {
    this.heroForm = this.fb.group({
        name: ['Joe', Validators.required ],
    });
}
</code>```

then set it the same when you "reset" it.

```<code>public resetForm() {
    this.heroForm = this.fb.group({
        name: ['Joe', Validators.required ],
    });
}
</code>```

Body:
Im using angular 4 for my app and have a select inside my reactive form like this:

  <select class="form-control" formControlName="persons">
    <option value="" selected>Select default</option>
     <option *ngFor="let p of persons" [value]="p">{{p}}</option>
   </select>

It works nice, first time it renders with the Select default option selected. But when i do a myForm.reset(), the form goes to initial state as expected, but the selected default value is no more selected. How can i reset the form and keep de default value selected?

Body:
Assuming you initialize the form in the constructor with default values, just set it back to the same thing.

For example, if in your constructor you set the form as such:

constructor() {
    this.heroForm = this.fb.group({
        name: ['Joe', Validators.required ],
    });
}

then set it the same when you "reset" it.

public resetForm() {
    this.heroForm = this.fb.group({
        name: ['Joe', Validators.required ],
    });
}


问:
better understanding type promotion of variadic parameters in c
When a variable argument function is called in c the integer parameters are promoted to int and floating point parameters are promoted to double

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int).

int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

And, again, I wonder what append when I pass a long double variable to printf with %Lf format (no matter if on 32 or 64 bit machines).

[Edited]

on a 32 bit machine, I tried this:

```<code>#include <stdio.h>

int main(void)
{
    printf("sizeof(int) %d\n", sizeof(int));
    printf("sizeof(long int) %d\n", sizeof(long int));
    printf("sizeof(long long int) %d\n", sizeof(long long int));
    printf("%lld\n", 1LL<<33);

    printf("sizeof(float) %d\n", sizeof(float));
    printf("sizeof(double) %d\n", sizeof(double));
    printf("sizeof(long double) %d\n", sizeof(long double));
    return 0;
}
</code>```

The result is:

```<code>sizeof(int) 4
sizeof(long int) 4
sizeof(long long int) 8
8589934592
sizeof(float) 4
sizeof(double) 8
sizeof(long double) 12
</code>```

this makes me think that not all parameters are promoted to int, otherwise I would get printed 0 instead of 8589934592.

Maybe only arguments smaller than int are promoted to int. And something similar could be for floating point types.

[Edited]

on a 64 bit machine I run this:

```<code>int main(void)
{
    printf("sizeof(int) %lu\n", sizeof(int));
    printf("sizeof(long) %lu\n", sizeof(long));
    printf("sizeof(long long) %lu\n", sizeof(long long));
    return 0;
}
</code>```

and get

```<code>sizeof(int) 4
sizeof(long) 8
sizeof(long long) 8
</code>```

if I understand well the standard, only char and short are promoted to int. I wonder what happen in smaller architecture, such like 16 bit or 8 bit MCU. I think that int size is dependent by architecture, but I wonder if sizeof(int) can be 1 on 8 bit architecture. In this case promotion of short to int could be impossible unless loosing some bits

答:
int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

Probably not. First of all, C makes no guarantees about the size of int, apart from stating that it must be at least 2 bytes (capable of at least holding the value 2^16/2 - 1 = 32767). Nothing in C prevents int from being 8 bytes, but that's not very convenient.

The convention is: all 8- and 16 bit computers use 16 bit int. All other computers use 32 bit int. This is industry de facto standard. Any deviations from this convention would be very exotic, although in theory allowed by C.

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

You get a long long int. No promotion takes place, because the variable is not one of the mentioned small types. The format specifier used is irrelevant to the promotion rules.

this makes me think that not all parameters are promoted to int

Indeed. Only the types that the standard mentions are promoted. The formal definition of the default argument promotions can be found in C11 6.5.2.2/6:

...the integer promotions are performed on each argument, and
  arguments that have type float are promoted to double. These are
  called the default argument promotions.

Meaning that only the small integer types (see the integer promotion rule) and float gets promoted. No other types.

Why you think that your examples printing various type sizes have any relevance in relation to the default argument promotions, I have no idea.

Body:
When a variable argument function is called in c the integer parameters are promoted to int and floating point parameters are promoted to double

Since the prototype doesn’t specify types for optional arguments, in a call to a variadic function the default argument promotions are performed on the optional argument values. This means the objects of type char or short int (whether signed or not) are promoted to either int or unsigned int, as appropriate; and that objects of type float are promoted to type double. So, if the caller passes a char as an optional argument, it is promoted to an int, and the function can access it with va_arg (ap, int).

int type should be 4 byte on 32 bit machines and 8 byte on 64 bit machines, is that right?

So I wonder what append when I pass a long long int to a variable argument function like printf with %lld format.

And, again, I wonder what append when I pass a long double variable to printf with %Lf format (no matter if on 32 or 64 bit machines).

[Edited]

on a 32 bit machine, I tried this:

#include <stdio.h>

int main(void)
{
    printf("sizeof(int) %d\n", sizeof(int));
    printf("sizeof(long int) %d\n", sizeof(long int));
    printf("sizeof(long long int) %d\n", sizeof(long long int));
    printf("%lld\n", 1LL<<33);

    printf("sizeof(float) %d\n", sizeof(float));
    printf("sizeof(double) %d\n", sizeof(double));
    printf("sizeof(long double) %d\n", sizeof(long double));
    return 0;
}

The result is:

sizeof(int) 4
sizeof(long int) 4
sizeof(long long int) 8
8589934592
sizeof(float) 4
sizeof(double) 8
sizeof(long double) 12

this makes me think that not all parameters are promoted to int, otherwise I would get printed 0 instead of 8589934592.

Maybe only arguments smaller than int are promoted to int. And something similar could be for floating point types.

[Edited]

on a 64 bit machine I run this:

int main(void)
{
    printf("sizeof(int) %lu\n", sizeof(int));
    printf("sizeof(long) %lu\n", sizeof(long));
    printf("sizeof(long long) %lu\n", sizeof(long long));
    return 0;
}

and get

sizeof(int) 4
sizeof(long) 8
sizeof(long long) 8

if I understand well the standard, only char and short are promoted to int. I wonder what happen in smaller architecture, such like 16 bit or 8 bit MCU. I think that int size is dependent by architecture, but I wonder if sizeof(int) can be 1 on 8 bit architecture. In this case promotion of short to int could be impossible unless loosing some bits


问:
Escape dots in Groovy GPath
I am using the RestAssured framework in Java, whose documentation contains this note

Note that the "json path" syntax uses Groovy's GPath notation and is not to be confused with Jayway's JsonPath syntax.

I need to validate the following JSON:

"_source": {
    "logSource": {
      "logger.name": "LogbackLogger",
    },
}
```

And the selectors like

_source.logSource.logger.name or

_source.logSource.logger.name[0] return no result.

I assume this is due to the dot in the logger.name property.
If no escaping is done, logger.name is interpreted as if name was under the logger, which is not true.

How do I correctly escape the dot character in the GPath, so that logger.name is considered as a single property name?

Thanks!

答:
You have a trivial issue.

Just wrap it in between single quote i.e., 'logger.name'
as there is special character.

Here is complete example :

```<code>def string = """{  "_source": {
       "logSource": {
          "logger.name": "LogbackLogger",
      }
    }
}"""

def json = new groovy.json.JsonSlurper().parseText(string)
println json.'_source'.logSource.'logger.name'
</code>```

Title: Escape dots in Groovy GPath

Body:
I am using the RestAssured framework in Java, whose documentation contains this note

Note that the "json path" syntax uses Groovy's GPath notation and is not to be confused with Jayway's JsonPath syntax.

I need to validate the following JSON:

"_source": {
    "logSource": {
      "logger.name": "LogbackLogger",
    },
}

And the selectors like

_source.logSource.logger.name or

_source.logSource.logger.name[0] return no result.

I assume this is due to the dot in the logger.name property.
If no escaping is done, logger.name is interpreted as if name was under the logger, which is not true.

How do I correctly escape the dot character in the GPath, so that logger.name is considered as a single property name?

Thanks!

Body:
You have a trivial issue.

Just wrap it in between single quote i.e., 'logger.name'
as there is special character.

Here is complete example :

def string = """{  "_source": {
       "logSource": {
          "logger.name": "LogbackLogger",
      }
    }
}"""

def json = new groovy.json.JsonSlurper().parseText(string)
println json.'_source'.logSource.'logger.name'


问:
"RecyclerView.setHasFixedSize(boolean)' on a null object reference" Recyclerview into fragment
I've a tabbed activity, I want to show in the first fragment (Tab1History) a Recyclerview and Cardview. I've created a XML file for CardView, and in the fragment XML I've insert the Recyclerview. I've also created the adapter:

```<code>public class CespiteAdapter extends RecyclerView.Adapter<CespiteAdapter.ViewHolder>
{
    private List<CespiteOgg> cespiteOggList;
    private Context context;

public CespiteAdapter(List<CespiteOgg> cespiteOggList, Context context) {
    this.cespiteOggList = cespiteOggList;
    this.context = context;
}

public class ViewHolder extends RecyclerView.ViewHolder
{
    public CardView cv;
    public TextView txtNumInventario;
    public TextView txtNomeCespite;
    public TextView txtDtCatalogazione;
    public TextView txtAula;
    public TextView txtNomeUser;

    ViewHolder(View itemView)
    {
        super (itemView);
        //cv = (CardView) itemView.findViewById(R.id.cardView);
        txtNumInventario = (TextView) itemView.findViewById(R.id.txtNumeroInventario);
        txtNomeCespite = (TextView) itemView.findViewById(R.id.txtNomeCespite);
        txtDtCatalogazione = (TextView) itemView.findViewById(R.id.txtDataCatalogazione);
        txtAula = (TextView) itemView.findViewById(R.id.txtAula);
        txtNomeUser= (TextView) itemView.findViewById(R.id.txtNomeUser);

    }
}

@Override
public CespiteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    View cespiteView = inflater.inflate(R.layout.cespite_card_view, parent, false);

    return new ViewHolder(cespiteView);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    CespiteOgg cespiteOgg = cespiteOggList.get(position);

    holder.txtNumInventario.setText(cespiteOgg.getNumInventario());
    holder.txtNomeCespite.setText(cespiteOgg.getNomeCespite());
    holder.txtDtCatalogazione.setText(cespiteOgg.getDtCatalogazione().toString());
    holder.txtAula.setText(cespiteOgg.getAula());
    holder.txtNomeUser.setText(cespiteOgg.getNomeUser());

}

@Override
public int getItemCount()
{
    return cespiteOggList.size();
}
}
</code>```

And here's the fragment:

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

 private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

private List<CespiteOgg> cespiteOggList;
private Date location;
Date date = new Date(location.getTime());

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.cespite_card_view, container, false);

    recyclerView = (RecyclerView) getView().findViewById(R.id.RecyclerView);
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    cespiteOggList = new ArrayList<>();

    for(int i=0; i<=10; i++)
    {
        CespiteOgg cespiteOgg = new CespiteOgg("heading"+(i+1), "Lorem ipsum", date, "sdjijsad", "jdkjd");

        cespiteOggList.add(cespiteOgg);

    }

    adapter = new CespiteAdapter(cespiteOggList, getContext());

    recyclerView.setAdapter(adapter);

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

And it's the stacktrace:

```<code>FATAL EXCEPTION: main
                                                                       Process: com.example.arslan.qrcode, PID: 14311
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference
</code>```

Here's cespite_card_view XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/cardView">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgCespite"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="16dp"
        android:src="@mipmap/thebigger" />

    <TextView
        android:id="@+id/txtNumeroInventario"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text1" />

    <TextView
        android:id="@+id/txtNomeCespite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtNumeroInventario"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text2" />

    <TextView
        android:id="@+id/txtDataCatalogazione"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtNomeCespite"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text3" />

    <TextView
        android:id="@+id/txtAula"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtDataCatalogazione"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text4" />

    <TextView
        android:id="@+id/txtNomeUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtAula"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text5" />

</RelativeLayout>
</code>```

And it's the fragment layout:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.arslan.qrcode.Main"
android:layout_weight="1"
>

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

</RelativeLayout>
</code>```

答:
Change this line :

```<code>recyclerView = (RecyclerView) getView().findViewById(R.id.RecyclerView);
</code>```

To this:

```<code>recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerView);
</code>```

Also, you are using the same layout for your RecyclerView.Adapter and your Fragment in this line:

```<code> View rootView = inflater.inflate(R.layout.cespite_card_view, container, false);
</code>```

You should have a layout file for your fragment that contains your RecyclerView widget inside it, like this:

```<code><android.support.v7.widget.RecyclerView
 android:id="@+id/recyclerView"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="#e9e9e9 />
</code>```

Body:
I've a tabbed activity, I want to show in the first fragment (Tab1History) a Recyclerview and Cardview. I've created a XML file for CardView, and in the fragment XML I've insert the Recyclerview. I've also created the adapter:

public class CespiteAdapter extends RecyclerView.Adapter<CespiteAdapter.ViewHolder>
{
    private List<CespiteOgg> cespiteOggList;
    private Context context;

public CespiteAdapter(List<CespiteOgg> cespiteOggList, Context context) {
    this.cespiteOggList = cespiteOggList;
    this.context = context;
}

public class ViewHolder extends RecyclerView.ViewHolder
{
    public CardView cv;
    public TextView txtNumInventario;
    public TextView txtNomeCespite;
    public TextView txtDtCatalogazione;
    public TextView txtAula;
    public TextView txtNomeUser;

    ViewHolder(View itemView)
    {
        super (itemView);
        //cv = (CardView) itemView.findViewById(R.id.cardView);
        txtNumInventario = (TextView) itemView.findViewById(R.id.txtNumeroInventario);
        txtNomeCespite = (TextView) itemView.findViewById(R.id.txtNomeCespite);
        txtDtCatalogazione = (TextView) itemView.findViewById(R.id.txtDataCatalogazione);
        txtAula = (TextView) itemView.findViewById(R.id.txtAula);
        txtNomeUser= (TextView) itemView.findViewById(R.id.txtNomeUser);

    }
}

@Override
public CespiteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());

    View cespiteView = inflater.inflate(R.layout.cespite_card_view, parent, false);

    return new ViewHolder(cespiteView);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    CespiteOgg cespiteOgg = cespiteOggList.get(position);

    holder.txtNumInventario.setText(cespiteOgg.getNumInventario());
    holder.txtNomeCespite.setText(cespiteOgg.getNomeCespite());
    holder.txtDtCatalogazione.setText(cespiteOgg.getDtCatalogazione().toString());
    holder.txtAula.setText(cespiteOgg.getAula());
    holder.txtNomeUser.setText(cespiteOgg.getNomeUser());

}

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

And here's the fragment:

 public class Tab1History extends Fragment
{

 private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

private List<CespiteOgg> cespiteOggList;
private Date location;
Date date = new Date(location.getTime());

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.cespite_card_view, container, false);

    recyclerView = (RecyclerView) getView().findViewById(R.id.RecyclerView);
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    cespiteOggList = new ArrayList<>();

    for(int i=0; i<=10; i++)
    {
        CespiteOgg cespiteOgg = new CespiteOgg("heading"+(i+1), "Lorem ipsum", date, "sdjijsad", "jdkjd");

        cespiteOggList.add(cespiteOgg);

    }

    adapter = new CespiteAdapter(cespiteOggList, getContext());

    recyclerView.setAdapter(adapter);

            return rootView;
}
}

And it's the stacktrace:

FATAL EXCEPTION: main
                                                                       Process: com.example.arslan.qrcode, PID: 14311
                                                                       java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)' on a null object reference

Here's cespite_card_view XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/cardView">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imgCespite"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="16dp"
        android:src="@mipmap/thebigger" />

    <TextView
        android:id="@+id/txtNumeroInventario"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text1" />

    <TextView
        android:id="@+id/txtNomeCespite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtNumeroInventario"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text2" />

    <TextView
        android:id="@+id/txtDataCatalogazione"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtNomeCespite"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text3" />

    <TextView
        android:id="@+id/txtAula"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtDataCatalogazione"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text4" />

    <TextView
        android:id="@+id/txtNomeUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txtAula"
        android:layout_toRightOf="@id/imgCespite"
        android:text="text5" />

</RelativeLayout>

And it's the fragment layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.arslan.qrcode.Main"
android:layout_weight="1"
>

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

</RelativeLayout>

Body:
Change this line :

recyclerView = (RecyclerView) getView().findViewById(R.id.RecyclerView);

To this:

recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerView);

Also, you are using the same layout for your RecyclerView.Adapter and your Fragment in this line:

 View rootView = inflater.inflate(R.layout.cespite_card_view, container, false);

You should have a layout file for your fragment that contains your RecyclerView widget inside it, like this:

<android.support.v7.widget.RecyclerView
 android:id="@+id/recyclerView"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:background="#e9e9e9 />


答:
Change getView() into rootView

getView - Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.cespite_card_view, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerView);
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    cespiteOggList = new ArrayList<>();

    for(int i=0; i<=10; i++)
    {
        CespiteOgg cespiteOgg = new CespiteOgg("heading"+(i+1), "Lorem ipsum", date, "sdjijsad", "jdkjd");

        cespiteOggList.add(cespiteOgg);

    }

    adapter = new CespiteAdapter(cespiteOggList, getContext());

    recyclerView.setAdapter(adapter);

            return rootView;
}
</code>```

Title: "RecyclerView.setHasFixedSize(boolean)' on a null object reference" Recyclerview into fragment

Body:
Change getView() into rootView

getView - Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    View rootView = inflater.inflate(R.layout.cespite_card_view, container, false);

    recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerView);
    recyclerView.setHasFixedSize(true);//every item of the RecyclerView has a fix size
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    cespiteOggList = new ArrayList<>();

    for(int i=0; i<=10; i++)
    {
        CespiteOgg cespiteOgg = new CespiteOgg("heading"+(i+1), "Lorem ipsum", date, "sdjijsad", "jdkjd");

        cespiteOggList.add(cespiteOgg);

    }

    adapter = new CespiteAdapter(cespiteOggList, getContext());

    recyclerView.setAdapter(adapter);

            return rootView;
}


问:
jQuery select data from row onChange to option menu
I created Admin page which displays all users details from Database.
The table is populated using Spring + Hibernate.
I made attempt to select value of option menu but I have no idea how to select username of a given row.

Later I want to make a call to Controller to change the user role.

```<code><div class="list">
    <table class="table-list">
        <tr>
            <th>Id</th>
            <th>Username</th>
            <th>Password</th>
            <th>Email</th>
            <th>Roles</th>
            <th>Change role</th>
        </tr>
        <c:forEach var="users" items="${users}">
            <tr class="userdetails">
                <td><c:out value="${users.id }" /></td>
                <td class="username"><c:out value="${users.username }" /></td>
                <td><c:out value="${users.password }" /></td>
                <td><c:out value="${users.email }" /></td>
                <c:forEach var="roles" items="${users.usersRoles }">
                    <td><c:out value="${roles.role }" /></td>
                </c:forEach>
                <td><select id="change-role"><c:forEach var='changeRole'
                            items='${roles}'>

                            <option value="${changeRole.role}"><c:out
                                    value='${changeRole.role}' /></option>

                        </c:forEach></select></td>
            </tr>
        </c:forEach>
    </table>
</div>
</code>```

答:
You can achieve it by using HTML5 data- attribute to your select option like </p>

```<code><select id="change-role">
   <c:forEach var='changeRole' items='${roles}'>
      <option value="${changeRole.role}" data-userid="${users.id }" data-username="${users.username }">
       <c:out value='${changeRole.role}' />
       </option>
   </c:forEach>
</select>
</code>```

<p>And in the change event of your Select use jquery/javascript code to fetch username and userid of selected row </p>

```<code>$('#change-role').change(function(e){
  var userid=$(this).find('option:selected').data('userid');
  var username=$(this).find('option:selected').data('username');

  //You code to use Userid and Username

 });
</code>```

Body:
I created Admin page which displays all users details from Database.
The table is populated using Spring + Hibernate.
I made attempt to select value of option menu but I have no idea how to select username of a given row.

Later I want to make a call to Controller to change the user role.

            Id
            Username
            Password
            Email
            Roles
            Change role

        <c:forEach var="users" items="${users}">

                <c:out value="${users.id }" />
                <c:out value="${users.username }" />
                <c:out value="${users.password }" />
                <c:out value="${users.email }" />
                <c:forEach var="roles" items="${users.usersRoles }">
                    <c:out value="${roles.role }" />
                </c:forEach>
                <select id="change-role"><c:forEach var='changeRole'
                            items='${roles}'>

                            <option value="${changeRole.role}"><c:out
                                    value='${changeRole.role}' /></option>

                        </c:forEach></select>

        </c:forEach>

Body:
You can achieve it by using HTML5 data- attribute to your select option like

<select id="change-role">
   <c:forEach var='changeRole' items='${roles}'>
      <option value="${changeRole.role}" data-userid="${users.id }" data-username="${users.username }">
       <c:out value='${changeRole.role}' />
       </option>
   </c:forEach>
</select>

And in the change event of your Select use jquery/javascript code to fetch username and userid of selected row

$('#change-role').change(function(e){
  var userid=$(this).find('option:selected').data('userid');
  var username=$(this).find('option:selected').data('username');

  //You code to use Userid and Username

 });


问:
hadoop fs –put Unknown command
Created a folder [LOAN_DATA] with below command

```<code>hadoop fs -mkdir hdfs://masterNode:8020/tmp/hadoop-hadoop/dfs/LOAN_DATA
</code>```

Now using the web UI when I list the contents of directory /tmp/hadoop-hadoop/dfs, it shows LOAN_DATA.

But when I want to store some Data from a TXT file to the LOAN_DATA directory using put or copyFromLocal I get

put: Unknown command

Command used:

```<code>hadoop fs –put '/home/hadoop/my_work/Acquisition_2012Q1.txt' hdfs://masterNode:8020/tmp/hadoop-hadoop/dfs/LOAN_DATA
</code>```

How to resolve this issue?

答:
This issue may occur when you copy-paste a command and use it. It is because of the change in font (or character set) used in the document from where it was copied.

For example:

If you copy/paste and execute the command -

hdfs dfs -put workflow.xml /testfile/workflow.xml

You may get-

```<code>–put: Unknown command
</code>```

OR

```<code>–p-t: Unknown command
</code>```

This happens because the copy is done from a UTF-8 file and the - or u (or any of the characters) copied may be of different character set.

So just type the command on the terminal (don't copy/paste) and you should be fine.

Alternatively, if you are running a shell script which was copied from
  some other editor then run a dos2unix on the script before running it
  on the Linux terminal.

Eg: dos2unix <shell_script.sh>

ContentLicense: CC BY-SA 4.0

Title: hadoop fs –put Unknown command

Body:
Created a folder [LOAN_DATA] with below command

hadoop fs -mkdir hdfs://masterNode:8020/tmp/hadoop-hadoop/dfs/LOAN_DATA

Now using the web UI when I list the contents of directory /tmp/hadoop-hadoop/dfs, it shows LOAN_DATA.

But when I want to store some Data from a TXT file to the LOAN_DATA directory using put or copyFromLocal I get

put: Unknown command

Command used:

hadoop fs –put '/home/hadoop/my_work/Acquisition_2012Q1.txt' hdfs://masterNode:8020/tmp/hadoop-hadoop/dfs/LOAN_DATA

How to resolve this issue?

Body:
This issue may occur when you copy-paste a command and use it. It is because of the change in font (or character set) used in the document from where it was copied.

For example:

If you copy/paste and execute the command -

hdfs dfs -put workflow.xml /testfile/workflow.xml

You may get-

–put: Unknown command

OR

–p-t: Unknown command

This happens because the copy is done from a UTF-8 file and the - or u (or any of the characters) copied may be of different character set.

So just type the command on the terminal (don't copy/paste) and you should be fine.

Alternatively, if you are running a shell script which was copied from
  some other editor then run a dos2unix on the script before running it
  on the Linux terminal.

Eg: dos2unix <shell_script.sh>


问:
SecureSocial in play framework. Is that possible to use multiple logins in one account?
SecureSocial in play framework.
Is that possible to use multiple logins in one account?
I have website which allow login to by Twitter, Facebook, Google+.
The same website allows load account’s data from any of those social media services.
Because of that I must make available login for example by Facebook to my page
and second login, to for example Twitter, to load account data.</p>

答:
Yes, it is possible but you have to link those accounts in your application.

I´ve created a "User Profile" entity that has user information, such as name, e-mail, date of birth and other user information that the system requires.

Then I've created another entity "Profile Login", that is related 1-N with User Profile. That entity contains information of each login provider (user/pass, G+, FB...).

That make possible a User profile have multiples logins.

Inside the application I've created a "Link to another accounts" page, so the user can connect his account with other services.


问:
Why is Scala promoting List[Any] to List[Long]?
In the following code:

```<code>def test(list: List[Any]): Unit = {
  list.foreach {
    v =>
    v match {
      case r: AnyRef => println(r + ": " + r.getClass.getName)
      case d: Double => println(d + ": Double")
      case f: Float=> println(f + ": Float")
      case b: Byte => println(b + ": Byte")
      case c: Char => println(c + ": Char")
      case s: Short => println(s + ": Short")
      case i: Int => println(i + ": Int")
      case l: Long=> println(l + ": Long")
      case b: Boolean => println(b + ": Boolean")
      case _ => throw new IllegalArgumentException("Unknown type: " + v)
    }
  }
}

test(List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short]))
</code>```

here is the output (Scala 2.8.1):

```<code>0: java.lang.Long
1: java.lang.Long
2: java.lang.Long
</code>```

Why are the numbers being promoted to java.lang.Long? How can I do this so that they either keep their AnyVal types or get "boxed" to the equivalent AnyRef type?

答:
Type inference works by starting with the most restrictive type (e.g. Nothing) and widening until one type can contain everything.  For numeric values, this means widening from Int to Long.  But now, since the call is effectively to List[Long](ls: Long*) all the numeric values are promoted in advance.

So, for instance, all of these give the same list:

```<code>List(1, 2: Byte, 3: Long)
List(1L, 2, 3: Short)
List(1: Byte, 2: Long, 3: Byte)
</code>```

namely a List[Long](1L, 2L, 3L).  Now, if you don't like this behavior, specify the type of the list as AnyVal or Any:

```<code>List[Any](1, 2: Byte, 3: Long)
List.head.asInstanceOf[AnyRef].getClass   // java.lang.Integer
</code>```

Edit: P.S. if you are specifying a constant of a certain type, you should just state the type (e.g. (2: Short)) instead of casting it to that type (e.g. 2.asInstanceOf[Short]).

ContentLicense: CC BY-SA 2.5

Body:
In the following code:

def test(list: List[Any]): Unit = {
  list.foreach {
    v =>
    v match {
      case r: AnyRef => println(r + ": " + r.getClass.getName)
      case d: Double => println(d + ": Double")
      case f: Float=> println(f + ": Float")
      case b: Byte => println(b + ": Byte")
      case c: Char => println(c + ": Char")
      case s: Short => println(s + ": Short")
      case i: Int => println(i + ": Int")
      case l: Long=> println(l + ": Long")
      case b: Boolean => println(b + ": Boolean")
      case _ => throw new IllegalArgumentException("Unknown type: " + v)
    }
  }
}

test(List(0L, 1.asInstanceOf[Int], 2.asInstanceOf[Short]))

here is the output (Scala 2.8.1):

0: java.lang.Long
1: java.lang.Long
2: java.lang.Long

Why are the numbers being promoted to java.lang.Long? How can I do this so that they either keep their AnyVal types or get "boxed" to the equivalent AnyRef type?

Body:
Type inference works by starting with the most restrictive type (e.g. Nothing) and widening until one type can contain everything.  For numeric values, this means widening from Int to Long.  But now, since the call is effectively to List[Long](ls: Long*) all the numeric values are promoted in advance.

So, for instance, all of these give the same list:

List(1, 2: Byte, 3: Long)
List(1L, 2, 3: Short)
List(1: Byte, 2: Long, 3: Byte)

namely a List[Long](1L, 2L, 3L).  Now, if you don't like this behavior, specify the type of the list as AnyVal or Any:

List[Any](1, 2: Byte, 3: Long)
List.head.asInstanceOf[AnyRef].getClass   // java.lang.Integer

Edit: P.S. if you are specifying a constant of a certain type, you should just state the type (e.g. (2: Short)) instead of casting it to that type (e.g. 2.asInstanceOf[Short]).


问:
su and sudo in a shell script
There is a shell script (/bin/sh, not bash) that requires root permissions for execution.

If it is ran by a normal user it should ask user a password to get root access and re-run itself.

Now it uses the following code:

if [ $(id -u) -ne 0 ]; then su root -- $0 $@ ; ... fi

That works fine, but there are some OS like Ubuntu that has no root password at all. On the other hand, a lot of systems use sudo for root permissions.

The question is: how can the script detect whether to use su or sudo without asking the user to enter too much passwords (e.g. enter sudo password, if it fails - run su).

答:
Create one more .sh file from this file call your original <code>.sh</code> file like - </p>

```<code>su - oracle /u01/enlightics/Enlightiks/UploadFTP/ExportScript2.sh
</code>```

Title: su and sudo in a shell script

Body:
Create one more .sh file from this file call your original .sh file like -

su - oracle /u01/enlightics/Enlightiks/UploadFTP/ExportScript2.sh


问:
Simple Python+OpenGL Transform Feedback
Closely following this tutorial for transform feedback, but in python.  Given a simple transform feedback vertex shader,

```<code>#version 400 core
in float inValue;
out float outValue;

void main()
{
  outValue = 5*inValue+6;
}
</code>```

and the surrounding python code to call it,

```<code>...

varyings = ctypes.create_string_buffer('outValue')
varyings_pp = POINTER(POINTER(c_char))(ctypes.cast(varyings, POINTER(c_char)))
gl.glTransformFeedbackVaryings(program, 1, varyings_pp, gl.GL_INTERLEAVED_ATTRIBS);

gl.glLinkProgram(program)
gl.glUseProgram(program)

vao = gl.glGenVertexArrays(1)
gl.glBindVertexArray(vao)

data = np.array([1.,2.,3.,4.,5.], dtype=np.float32)
vbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_STATIC_DRAW)

inputAttrib = gl.glGetAttribLocation(program, "inValue")
gl.glEnableVertexAttribArray(inputAttrib)
gl.glVertexAttribPointer(inputAttrib, 1, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)

data = np.array([-1.,-2.,-3.,-4.,-5.], dtype=np.float32)
tbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_TRANSFORM_FEEDBACK_BUFFER, tbo)
gl.glBufferData(gl.GL_TRANSFORM_FEEDBACK_BUFFER, data.nbytes, data, gl.GL_STATIC_READ)

gl.glEnable(gl.GL_RASTERIZER_DISCARD)

gl.glBindBufferBase(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo)

gl.glBeginTransformFeedback(gl.GL_POINTS)
gl.glDrawArrays(gl.GL_POINTS, 0, 3)
gl.glEndTransformFeedback()

gl.glFlush()

r_data = np.empty_like(data)
gl.glGetBufferSubData(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, data.nbytes, r_data)
print r_data
</code>```

I get the output [6. 6. 6. -4. -5.].  Thus it appears that inValue is constantly 0.  However, if I read back the GL_ARRAY_BUFFER, I get my input data.  Have I bound the buffer to the vertex arrays incorrectly?  At no point are any glErrors being raised, and the shader has no compile errors (error checking code omitted for aesthetic purposes).

答:
The solution is simple, and easy to miss due to dynamic typing.  This line here

```<code>gl.glVertexAttribPointer(inputAttrib, 1, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)
</code>```

should read

```<code>gl.glVertexAttribPointer(inputAttrib, 1, gl.GL_FLOAT, gl.GL_FALSE, 0, ctypes.c_void_p(0))
</code>```

Title: Simple Python+OpenGL Transform Feedback

Body:
Closely following this tutorial for transform feedback, but in python.  Given a simple transform feedback vertex shader,

#version 400 core
in float inValue;
out float outValue;

void main()
{
  outValue = 5*inValue+6;
}

and the surrounding python code to call it,

...

varyings = ctypes.create_string_buffer('outValue')
varyings_pp = POINTER(POINTER(c_char))(ctypes.cast(varyings, POINTER(c_char)))
gl.glTransformFeedbackVaryings(program, 1, varyings_pp, gl.GL_INTERLEAVED_ATTRIBS);

gl.glLinkProgram(program)
gl.glUseProgram(program)

vao = gl.glGenVertexArrays(1)
gl.glBindVertexArray(vao)

data = np.array([1.,2.,3.,4.,5.], dtype=np.float32)
vbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
gl.glBufferData(gl.GL_ARRAY_BUFFER, data.nbytes, data, gl.GL_STATIC_DRAW)

inputAttrib = gl.glGetAttribLocation(program, "inValue")
gl.glEnableVertexAttribArray(inputAttrib)
gl.glVertexAttribPointer(inputAttrib, 1, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)

data = np.array([-1.,-2.,-3.,-4.,-5.], dtype=np.float32)
tbo = gl.glGenBuffers(1)
gl.glBindBuffer(gl.GL_TRANSFORM_FEEDBACK_BUFFER, tbo)
gl.glBufferData(gl.GL_TRANSFORM_FEEDBACK_BUFFER, data.nbytes, data, gl.GL_STATIC_READ)

gl.glEnable(gl.GL_RASTERIZER_DISCARD)

gl.glBindBufferBase(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, tbo)

gl.glBeginTransformFeedback(gl.GL_POINTS)
gl.glDrawArrays(gl.GL_POINTS, 0, 3)
gl.glEndTransformFeedback()

gl.glFlush()

r_data = np.empty_like(data)
gl.glGetBufferSubData(gl.GL_TRANSFORM_FEEDBACK_BUFFER, 0, data.nbytes, r_data)
print r_data

I get the output [6. 6. 6. -4. -5.].  Thus it appears that inValue is constantly 0.  However, if I read back the GL_ARRAY_BUFFER, I get my input data.  Have I bound the buffer to the vertex arrays incorrectly?  At no point are any glErrors being raised, and the shader has no compile errors (error checking code omitted for aesthetic purposes).

Body:
The solution is simple, and easy to miss due to dynamic typing.  This line here

gl.glVertexAttribPointer(inputAttrib, 1, gl.GL_FLOAT, gl.GL_FALSE, 0, 0)

should read

gl.glVertexAttribPointer(inputAttrib, 1, gl.GL_FLOAT, gl.GL_FALSE, 0, ctypes.c_void_p(0))


答:
You should find your view from inflated view.
Use:

```<code>recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerView);
</code>```

instead of:

```<code>recyclerView = (RecyclerView) getView().findViewById(R.id.RecyclerView);
</code>```

Good luck.

Body:
You should find your view from inflated view.
Use:

recyclerView = (RecyclerView) rootView.findViewById(R.id.RecyclerView);

instead of:

recyclerView = (RecyclerView) getView().findViewById(R.id.RecyclerView);

Good luck.


问:
Google Tag Manager js widget tracking for multiple properties
We are developing a widget that is implemented on multiple customer's websites as 3rd party element. On those websites the widget is only present on some of the sites. The widget uses Google Analytics for tracking everything that is happening there.

In the next step, we want to move from Google Analytics to Google Tag Manager. Many of the host sites we are implemented on already use Google Analytics or Google Tag Manager.

The requirement is to be able to distribute tracking data through the Google Tag Manager in a certain way:

We want to see all of the tracking information in our own Google Analytics property (this is pretty easy)

We want to send SOME of the data to the Google Analytics property our customers are using so they can view it in their own tracking.

We want to make sure that the tracking data the customer receives is not inconsistent with the tracking that is already going on. In other words: We need to avoid that users are counted twice and we want to make sure that a user that has taken a certain widget action can be viewed in the customers property with the entire browsing history (effectively inject widget activities in the regular tracking)

We don't want to pollute our own tracking by receiving a lot of data from the host site into our own property.

My initial idea how to do this (not sure if it will work):

create another instance of google tag manager (namespaced)

gather all widget events in our own tag manager

create a lookup table to distribute the tracked data to different Google Analytics properties using the hostnameas filter

So can you help me figuring out if this could work especially for (3.) and (4.) and how it should be architected?

答:
Being your GTM powered customer I'd definitely prefer your widget not to send data to my analytics but just send event pushes to dataLayer so I could configure and customize my tags firing. This would let to avoid data inconsistency in (.3) .
Using your own GTM container alongside customer's container could lead to some data pollution since both containers will use the same dataLayer in default configuration.
To keep your own data clean you can stick to default analytics.js implementation with your separate settings and only send data to your GA account.


问:
How to Pin Data in Toad for Oracle
How to Pin a result set so it is not overwritten by a subsequent query in TOAD for Oracle (Expert).
   I have checked out all options, but unable to pin data.</p>

```<code>        Thanks
</code>```

答:
You can open multiple Schema Browser windows (Database | Schema browser) in the particular session (connection). And multiple Editor windows (Database | Editor) too. In each Editor window you can open multiple SQL tabs.
(Toad for Oracle Xpert 9.7.2.5)</p>

Title: How to Pin Data in Toad for Oracle

Body:
How to Pin a result set so it is not overwritten by a subsequent query in TOAD for Oracle (Expert).
   I have checked out all options, but unable to pin data.

        Thanks


问:
Wi-Fi Direct and iOS Support
I want to use Wi-Fi Direct in a solution, but I'm unsure which platforms support it.

Does Wi-Fi Direct depend on iPhone/iOS version?

Can I develop an application with Wi-Fi Direct feature on a iPhone 4s with iOS 8.

答:
The official list of current iOS Wi-Fi Management APIs

There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.

QA1942 - iOS Wi-Fi Management APIs

Entitlement option

This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.

NEHotspotHelper

MFi Program options

These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.

Wireless Accessory Configuration (WAC)

HomeKit

Peer-to-peer between Apple devices

These APIs come close to what you want, but they're Apple-to-Apple only.

NSNetService

Multipeer Connectivity

WiTap Example Code

iOS 11 NEHotspotConfiguration

Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.

Title: Wi-Fi Direct and iOS Support


问:
Can I revert a range of lines in a file with mercurial?
I often notice a few unwanted changes when I review my working copy (with hg status and hg diff) right before a commit. For example, I might have temporarily added or remove some code just for the duration of a debugging session.

I know I can use hg revert to remove unwanted changes, but this removes all the changes in the entire file. Is there a way to revert just a part of a file?

答: I'm not sure if you can revert individual lines explicitly, but what I do in situation like yours is to commit the good code and revert the rest (the bad code). This workflow is easy using Mercurial's record or crecord extension (I recommend the latter one).


问:
NServiceBus support .NetCore or not?
I read some article about NServiceBus and i want use it, but i dont know it fully supported the .NetCore or not, i googled about it (and found some information like This), but it could not help me much, any one can help me?

答: Update: Particular Software announced upcoming support for .NET Core 2.0 on their company blog here: https://particular.net/blog/nservicebus-on-net-core-its-time</p>

Title: NServiceBus support .NetCore or not?


问:
Why my javascript throws function not defined error?
Just started JS.

I have a button and it calls a function which should loop through an array and show me each item but it doesn't. It says that:

showWorthSum() function is not defined.

```<code>   function addWorth()
    {

        var table1= document.getElementById("tableNetWorths");

        var rowCount1= table1.rows.length;

        var row1= table1.insertRow(rowCount1);

        var arr= [];

       for(count = 0; count < rowCount1; count++)
       {
            arr.push(table1.rows[count].cells[1].innerHTML);
       }

       arr.shift();
       return arr;

    }

    function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(int count = 0; count < arrCount; count++)
        {
             //totalWorth= totalWorth+ returnedArr[count];

            document.write(returnedArr[count]);
            //debugger;
        }

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

Button:

```<code>   <button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
</code>```

And yes I have taken care of script tags etc, just stripped those for the purpose of posting.

Update: (Full code)

```<code><!DOCTYPE html>
<html>
<head>
<link href="css/basic.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">

<script>
    function alterTable()
    {

        //Textboxes code

        var tBoxCompany= document.getElementById("txtboxCompany");
        var tBoxAmount= document.getElementById("txtboxAmount");

        //table code

        var table= document.getElementById("tableNetWorths");

        var rowCount= table.rows.length;

        var row= table.insertRow(rowCount);

        var Cell1= row.insertCell(0);
        var Cell2= row.insertCell(1);

        Cell1.innerHTML= tBoxCompany.value;
        Cell2.innerHTML= tBoxAmount.value;

    }

    function addWorth()
    {

        var table1= document.getElementById("tableNetWorths");

        var rowCount1= table1.rows.length;

        var row1= table1.insertRow(rowCount1);

        var arr= [];

       for(count = 0; count < rowCount1; count++)
       {
            arr.push(table1.rows[count].cells[1].innerHTML);
       }

       arr.shift();
       return arr;

    }

    function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(int count = 0; count < arrCount; count++)
        {
             //totalWorth= totalWorth+ returnedArr[count];

            document.write(returnedArr[count]);
            //debugger;
        }

        //return totalWorth;
    }

</script>

</head>
<body>
<div class="container-fluid">
<div class="row">
 <div class="col-md-12">

<table id="tableNetWorths">
<tr>
<th>Company</th>
<th>Net Worth ($)</th>

</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>100</td>

</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>200</td>

</tr>
<tr>
<td>Ernst Handel</td>
<td>344</td>

</tr>
<tr>
<td>Island Trading</td>
<td>22</td>

</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>122</td>

</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>99</td>

</tr>
</table>

</div>
</div>

<div class="row">
   <br>
   <div class="col-md-3">
       <input type="text" id="txtboxCompany" class="form-control"/>
   </div>
   <div class="col-md-3">
       <input type="text" id="txtboxAmount" class="form-control"/>
   </div>
   <div class="col-md-3">
        <button class="btn btn-primary" onclick="alterTable()" type="button">Add Rows</button>
   </div>
    <div class="col-md-3">
        <button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>
   </div>
</div>

</div>
<script src="js/bootstrap.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
</code>```

Update: (ShowWorthSum function modified, still not working)

```<code> function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(count = 0; count < arrCount; count++)
        {
             totalWorth= totalWorth+ returnedArr[count];

        }

        return totalWorth;
    }
</code>```

答:
remove 'int' from your for loop definition. You have:

```<code>for(int count = 0; count < arrCount; count++)
</code>```

you need:

```<code>for(count = 0; count < arrCount; count++)
</code>```

Also, your loop will return a series of 'undefined' results as it iterates past the number of elements in your actual array. You have six elements, you're looping a fixed 10 times. So once you get past the 6th element, all the rest return (correctly) as undefined.

Body:
Just started JS.

I have a button and it calls a function which should loop through an array and show me each item but it doesn't. It says that:

showWorthSum() function is not defined.

   function addWorth()
    {

        var table1= document.getElementById("tableNetWorths");

        var rowCount1= table1.rows.length;

        var row1= table1.insertRow(rowCount1);

        var arr= [];

       for(count = 0; count < rowCount1; count++)
       {
            arr.push(table1.rows[count].cells[1].innerHTML);
       }

       arr.shift();
       return arr;

    }

    function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(int count = 0; count < arrCount; count++)
        {
             //totalWorth= totalWorth+ returnedArr[count];

            document.write(returnedArr[count]);
            //debugger;
        }

        //return totalWorth;
    }

Button:

   <button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>

And yes I have taken care of script tags etc, just stripped those for the purpose of posting.

Update: (Full code)

<!DOCTYPE html>

<link href="css/basic.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">

Company
Net Worth ($)

Alfreds Futterkiste
100

Centro comercial Moctezuma
200

Ernst Handel
344

Island Trading
22

Laughing Bacchus Winecellars
122

Magazzini Alimentari Riuniti
99

       <input type="text" id="txtboxCompany" class="form-control"/>

       <input type="text" id="txtboxAmount" class="form-control"/>

        <button class="btn btn-primary" onclick="alterTable()" type="button">Add Rows</button>

        <button class="btn btn-primary" onclick="document.write(showWorthSum())" type="button">Show Sum</button>

Update: (ShowWorthSum function modified, still not working)

 function showWorthSum()
    {
        var returnedArr= [];

        returnedArr.push(addWorth());

        var totalWorth= 0;

        var arrCount= 10 ;

        for(count = 0; count < arrCount; count++)
        {
             totalWorth= totalWorth+ returnedArr[count];

        }

        return totalWorth;
    }

Body:
remove 'int' from your for loop definition. You have:

for(int count = 0; count < arrCount; count++)

you need:

for(count = 0; count < arrCount; count++)

Also, your loop will return a series of 'undefined' results as it iterates past the number of elements in your actual array. You have six elements, you're looping a fixed 10 times. So once you get past the 6th element, all the rest return (correctly) as undefined.


答:
The problem is that you re not defining your variable count. Use this :

```<code>for(var count = 0; count < arrCount; count++){ ...
</code>```

And with JS, no matter if your var is a string or an int, you allways declare your variable using var

Title: Why my javascript throws function not defined error?

Body:
The problem is that you re not defining your variable count. Use this :

for(var count = 0; count < arrCount; count++){ ...

And with JS, no matter if your var is a string or an int, you allways declare your variable using var


问:
echache3 XML parsing issue
For some reason, I can't add the expiry element into the ehcache3 configuration xml.
without the expiry element, it works fine.

```<code>  <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>

  <service>
    <jsr107:defaults>
      <jsr107:cache name="people" template="heap-cache"/>
    </jsr107:defaults>
  </service>

  <cache-template name="heap-cache">
    <listeners>
        <listener>
          <class>org.terracotta.ehcache.EventLogger</class>
          <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
          <event-ordering-mode>UNORDERED</event-ordering-mode>
          <events-to-fire-on>CREATED</events-to-fire-on>
          <events-to-fire-on>UPDATED</events-to-fire-on>
          <events-to-fire-on>EXPIRED</events-to-fire-on>
          <events-to-fire-on>REMOVED</events-to-fire-on>
          <events-to-fire-on>EVICTED</events-to-fire-on>
        </listener>
    </listeners>
     <expiry>
        <ttl unit="seconds">10</ttl>
    </expiry>
    <resources>
      <heap unit="entries">2000</heap>
      <offheap unit="MB">100</offheap> <!-- unit of measure is case sensitive! -->
    </resources>
  </cache-template>
</config>
</code>```

the error message is:

```<code>org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'expiry'. One of '{"http://www.ehcache.org/v3":heap, "http://www.ehcache.org/v3":resources, "http://www.ehcache.org/v3":heap-store-settings, "http://www.ehcache.org/v3":disk-store-settings, "http://www.ehcache.org/v3":service-configuration}' is expected.
</code>```

but looking at this xsd:
http://www.ehcache.org/schema/ehcache-core.xsd
I don't see anything wrong the tag, anyone has any idea?

答:
Ehcache 3 strictly enforces the XSD, so the elements inside a cache or cache-template must be in the following order:

key-type

value-type

expiry

eviction-advisor

loader-writer

listeners

resources OR heap

more ...

with all elements being optional aside from the sizing (place 7) which is optional in a cache-template though.

Title: echache3 XML parsing issue

Body:
For some reason, I can't add the expiry element into the ehcache3 configuration xml.
without the expiry element, it works fine.

  <config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns='http://www.ehcache.org/v3'
    xmlns:jsr107='http://www.ehcache.org/v3/jsr107'>

  <service>
    <jsr107:defaults>
      <jsr107:cache name="people" template="heap-cache"/>
    </jsr107:defaults>
  </service>

  <cache-template name="heap-cache">
    <listeners>
        <listener>
          <class>org.terracotta.ehcache.EventLogger</class>
          <event-firing-mode>ASYNCHRONOUS</event-firing-mode>
          <event-ordering-mode>UNORDERED</event-ordering-mode>
          <events-to-fire-on>CREATED</events-to-fire-on>
          <events-to-fire-on>UPDATED</events-to-fire-on>
          <events-to-fire-on>EXPIRED</events-to-fire-on>
          <events-to-fire-on>REMOVED</events-to-fire-on>
          <events-to-fire-on>EVICTED</events-to-fire-on>
        </listener>
    </listeners>
     <expiry>
        <ttl unit="seconds">10</ttl>
    </expiry>
    <resources>
      <heap unit="entries">2000</heap>
      <offheap unit="MB">100</offheap>
    </resources>
  </cache-template>
</config>

the error message is:

org.xml.sax.SAXParseException: cvc-complex-type.2.4.a: Invalid content was found starting with element 'expiry'. One of '{"http://www.ehcache.org/v3":heap, "http://www.ehcache.org/v3":resources, "http://www.ehcache.org/v3":heap-store-settings, "http://www.ehcache.org/v3":disk-store-settings, "http://www.ehcache.org/v3":service-configuration}' is expected.

but looking at this xsd:
http://www.ehcache.org/schema/ehcache-core.xsd
I don't see anything wrong the tag, anyone has any idea?


问:
Logout in case of a bad request
thanks for the amazing job you've done with AOR, this have been a great source of inspiration for me, especially in how to implement a proper redux store.

My question :
If I make a bad request, (code 400), AOR log me out of the app.
How can I prevent this and instead show a notification to my user ?

答:
You can follow the instructions to achieve it:</p>

```<code>import { AUTH_ERROR } from 'admin-on-rest';

export default (type, params) => {
    if (type === AUTH_ERROR) {
        // As I noticed, this code is executed for any error, not only for auth-one.
        // So process the error as you wish (show message), don't log out.
    }
    // Then resolve the promise.
    return Promise.resolve();
};
</code>```

Title: Logout in case of a bad request

Body:
You can follow the instructions to achieve it:

import { AUTH_ERROR } from 'admin-on-rest';

export default (type, params) => {
    if (type === AUTH_ERROR) {
        // As I noticed, this code is executed for any error, not only for auth-one.
        // So process the error as you wish (show message), don't log out.
    }
    // Then resolve the promise.
    return Promise.resolve();
};


问:
How to make google map 'fit to markers'?
I am using google-map-react to render maps in my react app.I am displaying dynamic number of markers on the map.I need to fit the view of map so that it just encloses all the markers.I went through this thread but found it a bit complicated.Can anyone please give me an overview of how this can be done?</p>

答:
It happens that I had to do the exact same thing recently. I found that existing libs were more getting on my way than actually helping so I just went with writing my own component.

In case you decide going the same way - here's how to do what you want:

First - you need to get the bounds object enclosing all your markers. Here we assume that this.state.markers contains an array of google.maps.Marker objects

Your component could have the following method to do that:

```<code>  getObjectsBounds(){

    let objectsBounds = new google.maps.LatLngBounds();

    Object.values(this.state.markers).map((marker) => {
      let lat   = parseFloat(marker.getPosition().lat());
      let long  = parseFloat(marker.getPosition().lng());
      let point = new google.maps.LatLng(lat, long);
      objectsBounds.extend(point);
    });

    return objectsBounds;
  }
</code>```

Now we just use fitBounds on the above funtion's return results. Here we assume that this.map is your gmap, i.e. what google.maps.Map( ... your args ... ) returns.

```<code>  fitBounds(){
    let bounds = this.getObjectsBounds();
    this.map.fitBounds(bounds);
  }
</code>```

Body:
It happens that I had to do the exact same thing recently. I found that existing libs were more getting on my way than actually helping so I just went with writing my own component.

In case you decide going the same way - here's how to do what you want:

First - you need to get the bounds object enclosing all your markers. Here we assume that this.state.markers contains an array of google.maps.Marker objects

Your component could have the following method to do that:

  getObjectsBounds(){

    let objectsBounds = new google.maps.LatLngBounds();

    Object.values(this.state.markers).map((marker) => {
      let lat   = parseFloat(marker.getPosition().lat());
      let long  = parseFloat(marker.getPosition().lng());
      let point = new google.maps.LatLng(lat, long);
      objectsBounds.extend(point);
    });

    return objectsBounds;
  }

Now we just use fitBounds on the above funtion's return results. Here we assume that this.map is your gmap, i.e. what google.maps.Map( ... your args ... ) returns.

  fitBounds(){
    let bounds = this.getObjectsBounds();
    this.map.fitBounds(bounds);
  }


问:
ASP.NET MVC - Remove dependency from DAL in GUI
I'm building a MVC web app that consist of 3 projects. One for the GUI, one for the BusinessLogic and one for the Data access.

For my Data access I have a generated file by EF and therefore I have a generated class named "Customer". To make validation attributes for this class I need to make MetaDataType (which needs to be done in the same namespace and therefore I'm bound to do it in the DAL layer) - by doing this I refer to the Data access layer from my GUI which spoils the whole idea of splitting the project up, because that my GUI now refer both my DAL and BL layer. Is there anyhow I can keep my GUI and DAL layers seperated but still be abe to use Validation attributes like [Required] and so on?

Thanks in advance.

答:
If you're using .NET 4 (EF 2) you can generate POCO entities in a separate class library that can be shared across projects.  That won't require a dependency to the DAL.  See my previous answer:

ASP.Net Layered app - Share Entity Data Model amongst layers

Especially 3. POCO templates, including how to move to separate project: http://blogs.msdn.com/adonet/pages/feature-ctp-walkthrough-poco-templates-for-the-entity-framework.aspx


问:
Using while loop to repeat a function that generates random numbers
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

```<code>def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i
</code>```

答:
This should do the trick!

```<code>from random import shuffle
abc = ["a", "b", "c", "d", "e"]
your_list=[]
your_list.extend(abc)
shuffle(your_list)
print(your_list)
</code>```

output:

```<code>['e', 'd', 'a', 'c', 'b']
</code>```

Well if you want a new list from an old list with elements changed in random order.

That is if you want abc = ['a','b','c'] to be shuffled into say ['c','a','b']
in a random manner then use shuffle()

Body:
I am having trouble when using a while loop to repeat a function.

I am not an American student so please be understanding of my English.
I have no clue of what is going wrong and hope I can get some help.
I am aware that I can append the random number in the function and return it.

The question is:

There is a dice with 5 sides and each side says a , b , c , d ,e. If I get a d or an e, I throw again and I log this until I get an a,b or a c. ex) if I throw the dice 5times I can get: d, e, d, d, a or something like this. In my program, I want to simulate this process. I want it so that the function randomnumbers can generate random numbers from 0~4. I want the main program to loop the process of getting random numbers via this function(mandatory). Then, I want the main program to retrieve these values and use it to determine what these numbers mean(0=a, 1=b, 2=c, 3=d, 4=e) on the dice and append them to a separate list. Finally I want to print the values in the list where I logged the values I got.

I specifically have to do the following:

The function should only return one random number, not a list

The main program should be responsible for making a list and printing the value retrieved from the function.

def randomnumbers():
    r = 0
    import random
    r = random.randrange(0,5)
    return r

abc = ["a", "b", "c", "d", "e"]

List = []
while randomnumbers()>=3:
    List.append(abc[randomnumbers()])

for i in List:
    print i

Body:
This should do the trick!

from random import shuffle
abc = ["a", "b", "c", "d", "e"]
your_list=[]
your_list.extend(abc)
shuffle(your_list)
print(your_list)

output:

['e', 'd', 'a', 'c', 'b']

Well if you want a new list from an old list with elements changed in random order.

That is if you want abc = ['a','b','c'] to be shuffled into say ['c','a','b']
in a random manner then use shuffle()


问:
Dependency added to pom.xml causing multiple SLF4J bindings
I added a new dependency (browsermob-proxy) to my pom.xml and apparently it contains some slf4j binding. As a result, when I execute my code it prints out the following warning messages:

```<code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/PATH/.m2/repository/net/lightbody/bmp/browsermob-proxy/2.1.4/browsermob-proxy-2.1.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/PATH/.m2/repository/org/slf4j/slf4j-jcl/1.7.6/slf4j-jcl-1.7.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
</code>```

I attempted to exclude all the dependencies that had anything to do with slf4j or logging from the new dependency (browsermob-proxy) like this:

```<code><dependency>
        <groupId>net.lightbody.bmp</groupId>
        <artifactId>browsermob-proxy</artifactId>
        <version>2.1.4</version>

        <exclusions>

            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-slf4j-impl</artifactId>
            </exclusion>

        </exclusions>
</dependency>
</code>```

To discover all these dependencies I just looked inside the browsermob-proxy pom.xml.

However doing all that didn't help and I am still getting exactly the same warnings. Am I missing something?

答:
I think the warn means there is a StaticLoggerBinder.class in browsermob-proxy-2.1.4.jar, not it's dependencies. But I can't find this jar in maven central repo, so can't verify that at the moment.

You'd better check the jar, and see if org/slf4j/impl/StaticLoggerBinder exists

Body:
I added a new dependency (browsermob-proxy) to my pom.xml and apparently it contains some slf4j binding. As a result, when I execute my code it prints out the following warning messages:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/PATH/.m2/repository/net/lightbody/bmp/browsermob-proxy/2.1.4/browsermob-proxy-2.1.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/PATH/.m2/repository/org/slf4j/slf4j-jcl/1.7.6/slf4j-jcl-1.7.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.apache.logging.slf4j.Log4jLoggerFactory]
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.

I attempted to exclude all the dependencies that had anything to do with slf4j or logging from the new dependency (browsermob-proxy) like this:

<dependency>
        <groupId>net.lightbody.bmp</groupId>
        <artifactId>browsermob-proxy</artifactId>
        <version>2.1.4</version>

        <exclusions>

            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-api</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-core</artifactId>
            </exclusion>

            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-slf4j-impl</artifactId>
            </exclusion>

        </exclusions>
</dependency>

To discover all these dependencies I just looked inside the browsermob-proxy pom.xml.

However doing all that didn't help and I am still getting exactly the same warnings. Am I missing something?


问:
Select the key:value pairs from a dictionary in Python
I have a Python Dict like as follows:

```<code>a = {"a":1,"b":2,"c":3,"f":4,"d":5}
</code>```

and I have a list like as follows:

```<code>b= ["b","c"]
</code>```

What I want to do is selecting the key:value pairs from the dict a with keys in b.
So the output should be a dictionary like:

```<code>out = {"b":2,"c":3}
</code>```

I could simply create another dictionary and update it using the key:value pair with iteration but I have RAM problems and the dictionary a is very large. b includes a few points so I thought popping from a does not work. What can I do to solve this issue?

Edit: Out is actually an update on a. So I will update the a as out.

Thanks :)

答:
You could do this,

```<code>a = {"a":1,"b":2,"c":3,"f":4,"d":5}
b= ["b","c"]

out = {item:a.get(item)for item in b}
</code>```

This won't raise any error, but adds '' if the item is not in a.

Body:
I have a Python Dict like as follows:

a = {"a":1,"b":2,"c":3,"f":4,"d":5}

and I have a list like as follows:

b= ["b","c"]

What I want to do is selecting the key:value pairs from the dict a with keys in b.
So the output should be a dictionary like:

out = {"b":2,"c":3}

I could simply create another dictionary and update it using the key:value pair with iteration but I have RAM problems and the dictionary a is very large. b includes a few points so I thought popping from a does not work. What can I do to solve this issue?

Edit: Out is actually an update on a. So I will update the a as out.

Thanks :)

Body:
You could do this,

a = {"a":1,"b":2,"c":3,"f":4,"d":5}
b= ["b","c"]

out = {item:a.get(item)for item in b}

This won't raise any error, but adds '' if the item is not in a.


问:
How to do autocomplete for Dynamic Inputs in Jquery, Laravel
I am doing Accounts Project in Laravel. In Payments Entry Screen, i want to add multiple ledger in this screen using autocomplete. i do autocomplete only first field based on id. How to do Remaining Field based on dynamic id or suggest any good method.    </p>

```<code>     <table class="table table-bordered" style="margin-bottom:0px;">
         <tr>
         <td width="50%">
        <input type="text" class="form-control boxed" name="transledger[]" id="transledger1" ></td>
         <td width="50%">
         <input type="text" class="form-control boxed" name="creditamt[]" id="creditamt1">
         </td>
         </tr>
    <tr>
         <td width="50%">
        <input type="text" class="form-control boxed" name="transledger[]" id="transledger2" ></td>
         <td width="50%">
         <input type="text" class="form-control boxed" name="creditamt[]" id="creditamt2">
         </td>
         </tr>

    <tr>
         <td width="50%">
        <input type="text" class="form-control boxed" name="transledger[]" id="transledger3" ></td>
         <td width="50%">
         <input type="text" class="form-control boxed" name="creditamt[]" id="creditamt3">
         </td>
         </tr>
    .......
...........
...........
..........
    </table>
</code>```

<p>autocomplete Query </p>

```<code> <script>

   $(document).ready(function() {

    src = "{{ url('searchajax') }}";
     $("#transledger1").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: src,
                dataType: "json",
                data: {
                    term : request.term
                },
                success: function(data) {
                    response(data);

                }
            });
        },
        minLength: 3,

    });
});

</script>
</code>```

答:
This example shows you how you can use autocomplete.

https://jqueryui.com/autocomplete/ is a great resource to implement "autocomplete".

<!doctype html>

      <meta charset = "utf-8">
      <title>jQuery UI Autocomplete functionality</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">

Type "m" or "j"

         Tags:
         <input id = "automp">

```

Body:
I am doing Accounts Project in Laravel. In Payments Entry Screen, i want to add multiple ledger in this screen using autocomplete. i do autocomplete only first field based on id. How to do Remaining Field based on dynamic id or suggest any good method.

        <input type="text" class="form-control boxed" name="transledger[]" id="transledger1" >

         <input type="text" class="form-control boxed" name="creditamt[]" id="creditamt1">

        <input type="text" class="form-control boxed" name="transledger[]" id="transledger2" >

         <input type="text" class="form-control boxed" name="creditamt[]" id="creditamt2">

        <input type="text" class="form-control boxed" name="transledger[]" id="transledger3" >

         <input type="text" class="form-control boxed" name="creditamt[]" id="creditamt3">

    .......
...........
...........
..........

autocomplete Query

Body:
This example shows you how you can use autocomplete.

https://jqueryui.com/autocomplete/ is a great resource to implement "autocomplete".

<!doctype html>
<html lang = "en">
   <head>
      <meta charset = "utf-8">
      <title>jQuery UI Autocomplete functionality</title>
      <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
         rel = "stylesheet">
      <script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
      <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

      <!-- Javascript -->
      <script>
         $(function() {
            var availableTutorials  =  [
               "Javascript",
               "Jquery",
               "Vue.js",
               "Meteor.js",
            ];
            $( "#automp" ).autocomplete({
               source: availableTutorials
            });
         });
      </script>
   </head>

   <body>
      <!-- HTML -->
      <div class = "ui-widget">
         <p>Type "m" or "j"</p>
         <label for = "autocomp">Tags: </label>
         <input id = "automp">
      </div>
   </body>
</html>


问:
How do I read double quotes(") or single quotes(') through command line into my perl program?
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

```<code>#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";
</code>```

Upon running the above code:

```<code>perl test1.pl name1 "name2 and name3"
</code>```

I am getting the following output:

```<code>name1 name2 and name3
</code>```

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

答:
The behavior you are seeing is a function of the shell you are using, and does not have anything to do with perl. You would see the same results whether you used Python or C or some other language.

It is up to you to understand how the programming environment you chose works before starting to program. For example, with this script:

```<code>#!/usr/bin/env perl

use strict;
use warnings;

print join('|', @ARGV), "\n";
</code>```

in zsh:

```<code> ./1tt.pl name1 "name2 and name3"
name1|name2 and name3
</code>```

That is, the script gets two arguments. name1 and name2 and name3. The double-quoted string is passed as a single argument. On the other hand, see:

```<code>$ ./1tt.pl name1 "name2 and name3"
name1|name2 and name3
$ ./1tt.pl name1 "\"name2 and name3\""
name1|"name2 and name3"
$ ./1tt.pl name1 '"name2 and name3"'
name1|"name2 and name3"
$ ./1tt.pl name1 "'name2 and name3'"
name1|'name2 and name3'
</code>```

On the other hand, on Windows 10, in a cmd.exe window:

```<code>C:\> perl t.pl name1 "name2 and name3"
name1|name2 and name3
C:\> perl t.pl name1 """name2 and name3"""
name1|"name2 and name3"
C:\> perl t.pl name1 "\"name2 and name3\""
name1|"name2 and name3"
C:\> perl t.pl name1 '"name2 and name3"'
name1|'name2 and name3'
</code>```

etc

Body:
I am trying to use use arguments passed as command line arguments into my script, But while doing so the double quotes(") and single quotes(') vanishes.
for example on running the following:

#!usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

my $argument_list = join(" ",@ARGV);

print "$argument\n";

Upon running the above code:

perl test1.pl name1 "name2 and name3"

I am getting the following output:

name1 name2 and name3

Is there any way to include the double quotes along with the command line arguments so that the final argument is "name2 and name3" and not just name2 and name3 ?

I have tried using '\' to escape double quotes perl test1.pl name1 \"name2 and name3\" but it only makes it worse by considering "name2 as a separate argument and as a separate argument and name3" as another argument.

Body:
The behavior you are seeing is a function of the shell you are using, and does not have anything to do with perl. You would see the same results whether you used Python or C or some other language.

It is up to you to understand how the programming environment you chose works before starting to program. For example, with this script:

#!/usr/bin/env perl

use strict;
use warnings;

print join('|', @ARGV), "\n";

in zsh:

 ./1tt.pl name1 "name2 and name3"
name1|name2 and name3

That is, the script gets two arguments. name1 and name2 and name3. The double-quoted string is passed as a single argument. On the other hand, see:

$ ./1tt.pl name1 "name2 and name3"
name1|name2 and name3
$ ./1tt.pl name1 "\"name2 and name3\""
name1|"name2 and name3"
$ ./1tt.pl name1 '"name2 and name3"'
name1|"name2 and name3"
$ ./1tt.pl name1 "'name2 and name3'"
name1|'name2 and name3'

On the other hand, on Windows 10, in a cmd.exe window:

C:\> perl t.pl name1 "name2 and name3"
name1|name2 and name3
C:\> perl t.pl name1 """name2 and name3"""
name1|"name2 and name3"
C:\> perl t.pl name1 "\"name2 and name3\""
name1|"name2 and name3"
C:\> perl t.pl name1 '"name2 and name3"'
name1|'name2 and name3'

etc


问:
Transform SearchHit to Java Object in ElasticSearch
I am trying to retrieve data form ES query and I am confused about how can I transform each hit of retrieved data to Java Object.
Until now, I can get each hit in JSON format using Gson but I think is useless to transform from Hit to JSON and then to Java Object.

My current code is:

```<code>TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    Settings settings = Settings.builder()
            .put("cluster.name", "elasticsearch")
            .put("path.home", "/Users/user/Apps/elasticsearch-5.4.1")
            .build();

    QueryBuilder qb = termQuery("price", 12);
    SearchResponse response = client.prepareSearch("kal").setTypes("products")
            .setSearchType(SearchType.DEFAULT)
            .setQuery(qb)
            .get();

    SearchHit[] results = response.getHits().getHits();
    for (SearchHit hit : results) {
        String sourceAsString = hit.getSourceAsString();
        Map<String, SearchHitField> responseFields = hit.getFields();
        if (sourceAsString != null) {
            Gson gson = new GsonBuilder().setDateFormat(sourceAsString)
                    .create();
        }
    }
</code>```

答:
I implemented this solution but I am not sure if this is the proper way or not.</p>

```<code>SearchHit[] results = response.getHits().getHits();
    for (SearchHit hit : results) {
        String sourceAsString = hit.getSourceAsString();
        Map<String, SearchHitField> responseFields = hit.getFields();
        SearchHitField field = responseFields.get("product_id");
        Map map = hit.getSource();
        System.out.println(map.toString());
    }
</code>```

Body:
I am trying to retrieve data form ES query and I am confused about how can I transform each hit of retrieved data to Java Object.
Until now, I can get each hit in JSON format using Gson but I think is useless to transform from Hit to JSON and then to Java Object.

My current code is:

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
            .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
    Settings settings = Settings.builder()
            .put("cluster.name", "elasticsearch")
            .put("path.home", "/Users/user/Apps/elasticsearch-5.4.1")
            .build();

    QueryBuilder qb = termQuery("price", 12);
    SearchResponse response = client.prepareSearch("kal").setTypes("products")
            .setSearchType(SearchType.DEFAULT)
            .setQuery(qb)
            .get();

    SearchHit[] results = response.getHits().getHits();
    for (SearchHit hit : results) {
        String sourceAsString = hit.getSourceAsString();
        Map<String, SearchHitField> responseFields = hit.getFields();
        if (sourceAsString != null) {
            Gson gson = new GsonBuilder().setDateFormat(sourceAsString)
                    .create();
        }
    }

Body:
I implemented this solution but I am not sure if this is the proper way or not.

SearchHit[] results = response.getHits().getHits();
    for (SearchHit hit : results) {
        String sourceAsString = hit.getSourceAsString();
        Map<String, SearchHitField> responseFields = hit.getFields();
        SearchHitField field = responseFields.get("product_id");
        Map map = hit.getSource();
        System.out.println(map.toString());
    }