问:
Fill missing dates-hours on dataframe with empty values
I have a dataframe with data from several supermarkets, with the following structure:

```<code>       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  15:00:00  808.60   19       29
329    21         Fruits  2019-02-24  22:00:00  267.54   8        8
330    21         Fruits  2019-02-26  17:00:00  350.89   10       14
331    21         Dairy   2019-02-26  07:00:00  72.89    2        2
332    21         Dairy   2019-03-03  15:00:00  122.69   4        4
</code>```

Some notes:

[HOUR] goes from "00:00:00" to "23:00:00" (24 entries per date).

My "composite key" would be a combination of [MARKET_ID],
[SECTOR], [DATE] and [HOUR], but I do not use MultiIndex in that dataframe.

Hours with no sales (revenue, coupons or items) do not appear as
lines in the data I receive.

I would like to fill those missing lines in my dataframe, such as below:

```<code>       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  14:00:00  0        0        0
</code>```

While searching I came across solutions using reindex or grouper, but I'm not sure if those will fit my problem. Any suggestions?

Thanks for the attention.

Body:
I have a dataframe with data from several supermarkets, with the following structure:

       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  15:00:00  808.60   19       29
329    21         Fruits  2019-02-24  22:00:00  267.54   8        8
330    21         Fruits  2019-02-26  17:00:00  350.89   10       14
331    21         Dairy   2019-02-26  07:00:00  72.89    2        2
332    21         Dairy   2019-03-03  15:00:00  122.69   4        4

Some notes:

[HOUR] goes from "00:00:00" to "23:00:00" (24 entries per date).

My "composite key" would be a combination of [MARKET_ID],
[SECTOR], [DATE] and [HOUR], but I do not use MultiIndex in that dataframe.

Hours with no sales (revenue, coupons or items) do not appear as
lines in the data I receive.

I would like to fill those missing lines in my dataframe, such as below:

       MARKET_ID  SECTOR  DATE        HOUR      REVENUE  COUPONS  ITEMS
328    21         Fruits  2019-02-24  14:00:00  0        0        0

While searching I came across solutions using reindex or grouper, but I'm not sure if those will fit my problem. Any suggestions?

Thanks for the attention.

Body:
You can use resample here:

# df['DATE'] = pd.to_datetime(df['DATE'])
# df['HOUR'] = pd.to_timedelta(df['HOUR'])

grp = df.set_index(df['DATE']+df['HOUR']).groupby(['MARKET_ID', 'SECTOR'],
                                                  sort=False).resample('H').sum().reset_index(level=1)

                               SECTOR  MARKET_ID  REVENUE  COUPONS  ITEMS
MARKET_ID
21        2019-02-24 15:00:00  Fruits         21   808.60       19     29
          2019-02-24 16:00:00  Fruits          0     0.00        0      0
          2019-02-24 17:00:00  Fruits          0     0.00        0      0
          2019-02-24 18:00:00  Fruits          0     0.00        0      0
          2019-02-24 19:00:00  Fruits          0     0.00        0      0
          2019-02-24 20:00:00  Fruits          0     0.00        0      0
          2019-02-24 21:00:00  Fruits          0     0.00        0      0
          2019-02-24 22:00:00  Fruits         21   267.54        8      8
          2019-02-24 23:00:00  Fruits          0     0.00        0      0
          2019-02-25 00:00:00  Fruits          0     0.00        0      0
          2019-02-25 01:00:00  Fruits          0     0.00        0      0
          2019-02-25 02:00:00  Fruits          0     0.00        0      0
          2019-02-25 03:00:00  Fruits          0     0.00        0      0
          2019-02-25 04:00:00  Fruits          0     0.00        0      0
          2019-02-25 05:00:00  Fruits          0     0.00        0      0
          2019-02-25 06:00:00  Fruits          0     0.00        0      0
          2019-02-25 07:00:00  Fruits          0     0.00        0      0
          2019-02-25 08:00:00  Fruits          0     0.00        0      0
          2019-02-25 09:00:00  Fruits          0     0.00        0      0
          2019-02-25 10:00:00  Fruits          0     0.00        0      0
          2019-02-25 11:00:00  Fruits          0     0.00        0      0
          2019-02-25 12:00:00  Fruits          0     0.00        0      0
          2019-02-25 13:00:00  Fruits          0     0.00        0      0
          2019-02-25 14:00:00  Fruits          0     0.00        0      0
          2019-02-25 15:00:00  Fruits          0     0.00        0      0
          2019-02-25 16:00:00  Fruits          0     0.00        0      0
          2019-02-25 17:00:00  Fruits          0     0.00        0      0
          2019-02-25 18:00:00  Fruits          0     0.00        0      0
          2019-02-25 19:00:00  Fruits          0     0.00        0      0
          2019-02-25 20:00:00  Fruits          0     0.00        0      0
          2019-02-25 21:00:00  Fruits          0     0.00        0      0
          2019-02-25 22:00:00  Fruits          0     0.00        0      0
          2019-02-25 23:00:00  Fruits          0     0.00        0      0
          2019-02-26 00:00:00  Fruits          0     0.00        0      0
          2019-02-26 01:00:00  Fruits          0     0.00        0      0
          2019-02-26 02:00:00  Fruits          0     0.00        0      0
          2019-02-26 03:00:00  Fruits          0     0.00        0      0
          2019-02-26 04:00:00  Fruits          0     0.00        0      0
          2019-02-26 05:00:00  Fruits          0     0.00        0      0
          2019-02-26 06:00:00  Fruits          0     0.00        0      0
          2019-02-26 07:00:00  Fruits          0     0.00        0      0
          2019-02-26 08:00:00  Fruits          0     0.00        0      0
          2019-02-26 09:00:00  Fruits          0     0.00        0      0
          2019-02-26 10:00:00  Fruits          0     0.00        0      0
          2019-02-26 11:00:00  Fruits          0     0.00        0      0
          2019-02-26 12:00:00  Fruits          0     0.00        0      0
          2019-02-26 13:00:00  Fruits          0     0.00        0      0
          2019-02-26 14:00:00  Fruits          0     0.00        0      0
          2019-02-26 15:00:00  Fruits          0     0.00        0      0
          2019-02-26 16:00:00  Fruits          0     0.00        0      0
...                               ...        ...      ...      ...    ...
          2019-03-01 14:00:00   Dairy          0     0.00        0      0
          2019-03-01 15:00:00   Dairy          0     0.00        0      0
          2019-03-01 16:00:00   Dairy          0     0.00        0      0
          2019-03-01 17:00:00   Dairy          0     0.00        0      0
          2019-03-01 18:00:00   Dairy          0     0.00        0      0
          2019-03-01 19:00:00   Dairy          0     0.00        0      0
          2019-03-01 20:00:00   Dairy          0     0.00        0      0
          2019-03-01 21:00:00   Dairy          0     0.00        0      0
          2019-03-01 22:00:00   Dairy          0     0.00        0      0
          2019-03-01 23:00:00   Dairy          0     0.00        0      0
          2019-03-02 00:00:00   Dairy          0     0.00        0      0
          2019-03-02 01:00:00   Dairy          0     0.00        0      0
          2019-03-02 02:00:00   Dairy          0     0.00        0      0
          2019-03-02 03:00:00   Dairy          0     0.00        0      0
          2019-03-02 04:00:00   Dairy          0     0.00        0      0
          2019-03-02 05:00:00   Dairy          0     0.00        0      0
          2019-03-02 06:00:00   Dairy          0     0.00        0      0
          2019-03-02 07:00:00   Dairy          0     0.00        0      0
          2019-03-02 08:00:00   Dairy          0     0.00        0      0
          2019-03-02 09:00:00   Dairy          0     0.00        0      0
          2019-03-02 10:00:00   Dairy          0     0.00        0      0
          2019-03-02 11:00:00   Dairy          0     0.00        0      0
          2019-03-02 12:00:00   Dairy          0     0.00        0      0
          2019-03-02 13:00:00   Dairy          0     0.00        0      0
          2019-03-02 14:00:00   Dairy          0     0.00        0      0
          2019-03-02 15:00:00   Dairy          0     0.00        0      0
          2019-03-02 16:00:00   Dairy          0     0.00        0      0
          2019-03-02 17:00:00   Dairy          0     0.00        0      0
          2019-03-02 18:00:00   Dairy          0     0.00        0      0
          2019-03-02 19:00:00   Dairy          0     0.00        0      0
          2019-03-02 20:00:00   Dairy          0     0.00        0      0
          2019-03-02 21:00:00   Dairy          0     0.00        0      0
          2019-03-02 22:00:00   Dairy          0     0.00        0      0
          2019-03-02 23:00:00   Dairy          0     0.00        0      0
          2019-03-03 00:00:00   Dairy          0     0.00        0      0
          2019-03-03 01:00:00   Dairy          0     0.00        0      0
          2019-03-03 02:00:00   Dairy          0     0.00        0      0
          2019-03-03 03:00:00   Dairy          0     0.00        0      0
          2019-03-03 04:00:00   Dairy          0     0.00        0      0
          2019-03-03 05:00:00   Dairy          0     0.00        0      0
          2019-03-03 06:00:00   Dairy          0     0.00        0      0
          2019-03-03 07:00:00   Dairy          0     0.00        0      0
          2019-03-03 08:00:00   Dairy          0     0.00        0      0
          2019-03-03 09:00:00   Dairy          0     0.00        0      0
          2019-03-03 10:00:00   Dairy          0     0.00        0      0
          2019-03-03 11:00:00   Dairy          0     0.00        0      0
          2019-03-03 12:00:00   Dairy          0     0.00        0      0
          2019-03-03 13:00:00   Dairy          0     0.00        0      0
          2019-03-03 14:00:00   Dairy          0     0.00        0      0
          2019-03-03 15:00:00   Dairy         21   122.69        4      4

[180 rows x 5 columns]


来源: stackexchange

问:
Read text file in angular line by line
I have this text file:

"u901_humext  ""2019-02-10 00:00""    99.97   99.97   99.97"

"u901_radpar   ""2019-02-10 15:40""    1002.9  1068.4  1034.3943396226"

And I want to take the data from the line like:

name = u901_humext date = 2019-02-10 00:00 min = 99.97 avg = 99.97 max = 99.97

I have this class with the function but only can display all the data:

    export class LeerArchivoComponent implements OnInit {
      private fileText;
      private nombre:String;
      constructor() { }

      ngOnInit() {
      }

      fileUpload(event){
        var reader = new FileReader();
        reader.readAsText(event.srcElement.files[0]);
        var me = this;
        var nombre:String;
        reader.onload = function (){
          me.fileText = reader.result;

        }
      }
```

<p>And the html like: </p>

<pre class="lang-html prettyprint-override"><code>    <input id="file-upload"
      type="file"
      accept=".txt"
      (change)="fileUpload($event)">
    <textarea rows="4" cols="50">{{fileText}}</textarea>
</code>```

答:
Convert the ArrayBuffer to string, After try to split your text by lines like:

```<code>function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

const text = ab2str(reader.result);
const lines = text.split(/\r?\n/);
</code>```

Afterwards you can split every line by a space to read every individual value:

```<code>lines.forEach(line => {
   const vars = line.split(' ');
   console.log(vars);
});
</code>```

ab2str source

ContentLicense: CC BY-SA 4.0

Title: Read text file in angular line by line

Body:
I have this text file:

"u901_humext  ""2019-02-10 00:00""    99.97   99.97   99.97"

"u901_radpar   ""2019-02-10 15:40""    1002.9  1068.4  1034.3943396226"

And I want to take the data from the line like:

name = u901_humext date = 2019-02-10 00:00 min = 99.97 avg = 99.97 max = 99.97

I have this class with the function but only can display all the data:

    export class LeerArchivoComponent implements OnInit {
      private fileText;
      private nombre:String;
      constructor() { }

      ngOnInit() {
      }

      fileUpload(event){
        var reader = new FileReader();
        reader.readAsText(event.srcElement.files[0]);
        var me = this;
        var nombre:String;
        reader.onload = function (){
          me.fileText = reader.result;

        }
      }

And the html like:

    <input id="file-upload"
      type="file"
      accept=".txt"
      (change)="fileUpload($event)">
    <textarea rows="4" cols="50">{{fileText}}</textarea>

Body:
Convert the ArrayBuffer to string, After try to split your text by lines like:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

const text = ab2str(reader.result);
const lines = text.split(/\r?\n/);

Afterwards you can split every line by a space to read every individual value:

lines.forEach(line => {
   const vars = line.split(' ');
   console.log(vars);
});

ab2str source


问:
How to install Debian packages on Alpine?
How to install Debian packages on Alpine?

For example:

```<code>wget https://dl.influxdata.com/influxdb/releases/influxdb_0.13.0_armhf.deb
sudo dpkg -i influxdb_0.13.0_armhf.deb
</code>```

答:
Good news:

alpine now has dpkg package available in its repository and you can install it by apk add dpkg and you can use dpkg -i *.deb to install the deb you want.

Body:
How to install Debian packages on Alpine?

For example:

wget https://dl.influxdata.com/influxdb/releases/influxdb_0.13.0_armhf.deb
sudo dpkg -i influxdb_0.13.0_armhf.deb


问:
Looking for a Product Guarantee registration form (Wordpress Plugin)
I want to create a form where users can register their product guarantees on our website.

Does anyone know of a good wordpress plugin that might be able to accommodate this? This is a standalone website without WooCommerce and essentially acts as a contact form where users enter information about the products they wish to register.

The objective is for us to be able to retrieve and retain the information sent in that we can access via the wordpress dashboard.

This also needs to notify us via email when a registration has been sent in and needs to notify users of their registration via an automated email that gets sent when they click 'submit'.

I have set up a new page that I want this to sit on but is there a way to create such a form?

Thanks

答:
This question is opinion based but I will try and suggest you use one of the many form management plugins.

Just search for forms in plugins.
https://en-ca.wordpress.org/plugins/search/forms/

Contact-form 7, Ninja Forms and Gravity Forms come to mind and should be able to do what you are requesting.


问:
Error with RecyclerView: No adapter attached; skipping layout
I can't get my code work
I'm trying to get a list of my database activities.

A lot of research here and none of the answers helped me

My Adapter

```<code>public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {

    private Context mCtx;
    private List<Atividades> atividadesList;

    public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
        this.mCtx = mCtx;
        this.atividadesList = atividadesList;
    }

    @Override
    public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.atividades_lista, null);
        return new AtividadesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AtividadesViewHolder holder, int position) {
        Atividades atividades = atividadesList.get(position);
        holder.textViewAtividade.setText(atividades.getAtividade());
        holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
        holder.textViewHora.setText(String.valueOf(atividades.getHora()));
        holder.textViewDestinatarios.setText(atividades.getDestinatarios());
    }

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

    class AtividadesViewHolder extends RecyclerView.ViewHolder {

        TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;

        public AtividadesViewHolder(View itemView) {
            super(itemView);
            textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
            textViewData = itemView.findViewById(R.id.textViewData);
            textViewHora = itemView.findViewById(R.id.textViewHora);
            textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
        }
    }
}
</code>```

My activity

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

private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        loadAtividades();
    }

    private void loadAtividades() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject a = array.getJSONObject(i);
                                Log.d("Valores", a.getString("Atividade"));
                                atividadesList.add(new Atividades(
                                        a.getInt("idAtividade"),
                                        a.getString("Atividade"),
                                        java.sql.Date.valueOf(a.getString("dataPrevista")),
                                        java.sql.Time.valueOf(a.getString("hora")),
                                        a.getString("Destinatarios"),
                                        a.getString("Local")
                                ));
                            }
                            AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
                            recyclerView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        Volley.newRequestQueue(this).add(stringRequest);
    }
}
</code>```

Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.

答:
Add to your adapter:

```<code>public AtividadesAdapter(Context mCtx) {
    this.mCtx = mCtx;
}

public void setItems(@NonNull final List<Atividades> items) {

    if (atividadesList != null) {
        atividadesList.clear();
    } else {
        atividadesList = new ArrayList<>();
    }
    atividadesList.addAll(items);
}
</code>```

onCreate of the activity should be as follows:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.atividadesrecyclerview);
    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setHasFixedSize(true);
    mAdapter = new AtividadesAdapter(AtividadesActivity.this);
    recyclerView.setAdapter(mAdapter);
    loadAtividades();
}
</code>```

In loadAtividades() call to setItems:

```<code>mAdapter.setItems(atividadesList);
</code>```

Body:
I can't get my code work
I'm trying to get a list of my database activities.

A lot of research here and none of the answers helped me

My Adapter

public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {

    private Context mCtx;
    private List<Atividades> atividadesList;

    public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
        this.mCtx = mCtx;
        this.atividadesList = atividadesList;
    }

    @Override
    public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.atividades_lista, null);
        return new AtividadesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AtividadesViewHolder holder, int position) {
        Atividades atividades = atividadesList.get(position);
        holder.textViewAtividade.setText(atividades.getAtividade());
        holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
        holder.textViewHora.setText(String.valueOf(atividades.getHora()));
        holder.textViewDestinatarios.setText(atividades.getDestinatarios());
    }

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

    class AtividadesViewHolder extends RecyclerView.ViewHolder {

        TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;

        public AtividadesViewHolder(View itemView) {
            super(itemView);
            textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
            textViewData = itemView.findViewById(R.id.textViewData);
            textViewHora = itemView.findViewById(R.id.textViewHora);
            textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
        }
    }
}

My activity

public class AtividadesActivity extends AppCompatActivity {

private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        loadAtividades();
    }

    private void loadAtividades() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject a = array.getJSONObject(i);
                                Log.d("Valores", a.getString("Atividade"));
                                atividadesList.add(new Atividades(
                                        a.getInt("idAtividade"),
                                        a.getString("Atividade"),
                                        java.sql.Date.valueOf(a.getString("dataPrevista")),
                                        java.sql.Time.valueOf(a.getString("hora")),
                                        a.getString("Destinatarios"),
                                        a.getString("Local")
                                ));
                            }
                            AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
                            recyclerView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        Volley.newRequestQueue(this).add(stringRequest);
    }
}

Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.

Body:
Add to your adapter:

public AtividadesAdapter(Context mCtx) {
    this.mCtx = mCtx;
}

public void setItems(@NonNull final List<Atividades> items) {

    if (atividadesList != null) {
        atividadesList.clear();
    } else {
        atividadesList = new ArrayList<>();
    }
    atividadesList.addAll(items);
}

onCreate of the activity should be as follows:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.atividadesrecyclerview);
    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setHasFixedSize(true);
    mAdapter = new AtividadesAdapter(AtividadesActivity.this);
    recyclerView.setAdapter(mAdapter);
    loadAtividades();
}

In loadAtividades() call to setItems:

mAdapter.setItems(atividadesList);


问:
How do I send data from Struts action to javascript?
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

```<code>List<MarkerClass> markers;
</code>```

MarkerClass is defined acoprding to belove:

```<code>final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}
</code>```

The action also includes a getter for markers:

```<code>public List<MarkerClass> getMarkers()
{
    return markers;
}
</code>```

In my jsp-file I have tried doing this:

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">

function initialize()
{
    var titel = "";
    for(var i, "${markers}")
    {
        titel = titel+ "${markers[i].street}";
    }
}
</code>```

The browser substitutes "${markers}" with "[se.fubar.test.MarkerClass@37a4, se.fubar.test.MarkerClass@9ad97c]"

I'm guessing there is a better and smarter way to do this but since I'm a bit new to Struts and is trying to code while under the influence of a migrane the answer elludes me.

答: You could convert the object to json on the server (see http://www.json.org/java/index.html ) and then call eval() on the string to get a javascript representation of your object.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a webb application using Struts 2 and javascript and I'm having some trouble passing data from my action into my javascript.

This is the list I'm trying to send/access:

List<MarkerClass> markers;

MarkerClass is defined acoprding to belove:

final class MarkerClass
{
    public Integer objectId;
    public String street;
    public String streetNumber;
    public String zip;
    public String city;
    public Integer statusId;
    public Float lattitude;
    public Float longitude;
}

The action also includes a getter for markers:

public List<MarkerClass> getMarkers()
{
    return markers;
}

In my jsp-file I have tried doing this:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>


问:
how to iterate a function over multiple lists?
I have the following function:

```<code>def calc(X: float, Y: float, z: float) -> dict:
    n1 = X*Y
    n2 = Y*z
    n3 = z**2
    return {"c": n1, "d" : n2, "e" : n3}
</code>```

I can take a list such as [10,10,20] and input it into the function using the *args approach:

```<code>list_1 = [10,10,20]
calc(*list_1)

#results
{'c' : 100, 'd': 200, 'e': 400}
</code>```

However, let's assume I want to pass an array or multiple lists into the function, such as:

```<code>list_2 = [[10,10,20],
          [20,25,30],
          [35,40,45]]
</code>```

where I want the function to iterate over each individual list.

I have thought about using a loop, but cannot get how to iterate over each aspect of the multi-dimensional list.

I have tried potentially using the index by doing the following:

```<code>for x in len(list_2):
      call(*list_2[x])
</code>```

but I get the following error:

```<code>'int' object is not ierable
</code>```

Ideally, I would like this to be vectorized and avoid using loops, but any input or direction is much appreciated!

答:
You can use map function (https://docs.python.org/3.5/library/functions.html#map), so you can do:

print(list(map(calc, *list_2)))
```

<p>and the output will be:</p>

<pre class="lang-py prettyprint-override"><code>[{'c': 200, 'd': 700, 'e': 1225}, {'c': 250, 'd': 1000, 'e': 1600}, {'c': 600, 'd
': 1350, 'e': 2025}]
</code>```

Body:
I have the following function:

def calc(X: float, Y: float, z: float) -> dict:
    n1 = X*Y
    n2 = Y*z
    n3 = z**2
    return {"c": n1, "d" : n2, "e" : n3}

I can take a list such as [10,10,20] and input it into the function using the *args approach:

list_1 = [10,10,20]
calc(*list_1)

#results
{'c' : 100, 'd': 200, 'e': 400}

However, let's assume I want to pass an array or multiple lists into the function, such as:

list_2 = [[10,10,20],
          [20,25,30],
          [35,40,45]]

where I want the function to iterate over each individual list.

I have thought about using a loop, but cannot get how to iterate over each aspect of the multi-dimensional list.

I have tried potentially using the index by doing the following:

for x in len(list_2):
      call(*list_2[x])

but I get the following error:

'int' object is not ierable

Ideally, I would like this to be vectorized and avoid using loops, but any input or direction is much appreciated!

Body:
You can use map function (https://docs.python.org/3.5/library/functions.html#map), so you can do:

print(list(map(calc, *list_2)))

and the output will be:

[{'c': 200, 'd': 700, 'e': 1225}, {'c': 250, 'd': 1000, 'e': 1600}, {'c': 600, 'd
': 1350, 'e': 2025}]


问:
Java 7zip compression of a String
I would like to compress an String manually defined to 7z in Java. So then I could convert it to base64. I found many examples compressing files to 7z and then saving into new File.

I just try the next code, and it takes correctly the file and compress it:

```<code>private static void addToArchiveCompression(SevenZOutputFile out, File file, String dir) throws IOException {
        String name = dir + File.separator + file.getName();
        if (file.isFile()){
            SevenZArchiveEntry entry = out.createArchiveEntry(file, name);
            out.putArchiveEntry(entry);

            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int count = 0;
            while ((count = in.read(b)) > 0) {
                out.write(b, 0, count);
            }
            out.closeArchiveEntry();

        } else if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null){
                for (File child : children){
                    addToArchiveCompression(out, child, name);
                }
            }
        } else {
            System.out.println(file.getName() + " is not supported");
        }
    }
</code>```

But how can I compress an manually defined String to 7z and convert it to byte[]? So then I can convert the byte[] to base64 and print it, without generating or reading new Files?

答:
You will of course have to apply several changes to the code you posted. That code is meant to compress a file or directory whereas your case is much simpler. You definitely won't need a for loop, for example.

I break down the various parts you'll have to look into and leave the coding to you.

Converting a String to data for 7z:

One of the options is to use a ByteArrayInputStream instead of a FileInputStream. The ByteArrayInputStream will have to be initialised with the bytes corresponding to the String.

See the following article for an example on how to do this conversion:

https://www.baeldung.com/convert-string-to-input-stream

Converting output bytes to Base64:

There are several approaches, detailed in this StackOverflow thread:

How do I convert a byte array to Base64 in Java?

Outputting 7z to memory instead of File:

You will have to use the SevenZOutputFile constructor taking a SeekableByteChannel interface as input. Your implementation of SeekableByteChannel will have to be backed by a byte array or stream of sorts. You can use the following implementation:

https://commons.apache.org/proper/commons-compress/apidocs/org/apache/commons/compress/utils/SeekableInMemoryByteChannel.html

Obtaining a SevenZArchiveEntry from something other than a file:

Although the SevenZOutputFile class doesn't seem to provide a facility to do that, if you look at its sourcecode you'll notice that you can manually create a SevenZArchiveEntry without any intermediation, as it has an empty constructor. You'll have to "pretend" it's still an actual file, but that shouldn't be a problem.

Sourcecode of SevenZArchiveEntry:

https://commons.apache.org/proper/commons-compress/apidocs/src-html/org/apache/commons/compress/archivers/sevenz/SevenZOutputFile.html

Title: Java 7zip compression of a String

Body:
I would like to compress an String manually defined to 7z in Java. So then I could convert it to base64. I found many examples compressing files to 7z and then saving into new File.

I just try the next code, and it takes correctly the file and compress it:

private static void addToArchiveCompression(SevenZOutputFile out, File file, String dir) throws IOException {
        String name = dir + File.separator + file.getName();
        if (file.isFile()){
            SevenZArchiveEntry entry = out.createArchiveEntry(file, name);
            out.putArchiveEntry(entry);

            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int count = 0;
            while ((count = in.read(b)) > 0) {
                out.write(b, 0, count);
            }
            out.closeArchiveEntry();

        } else if (file.isDirectory()) {
            File[] children = file.listFiles();
            if (children != null){
                for (File child : children){
                    addToArchiveCompression(out, child, name);
                }
            }
        } else {
            System.out.println(file.getName() + " is not supported");
        }
    }

But how can I compress an manually defined String to 7z and convert it to byte[]? So then I can convert the byte[] to base64 and print it, without generating or reading new Files?


问:
Using roles with jwt / zizaco/entrust
In my new Laravel 5.8 app I read next article to use roles with jwt extention :
https://scotch.io/tutorials/role-based-authentication-in-laravel-with-jwt
and in seed I add several roles, like :

```<code>\DB::table('roles')->insert(array (
    0 =>
        array (
            'id' => 1,
            'name' => 'Admin',
            'display_name' => 'Admin',
            'description' => 'Administrator. Can do all operations in system',
            'created_at' => '2019-04-29 11:03:50',
        ),
    1 =>
        array (
            'id' => 2,
            'name' => 'Manager',
            'display_name' => 'Manager. Can do all operations in frontend and CRUD for Hostels/CMS items in Backend',
            'description' => 'Manager description...',
            'created_at' => '2019-04-29 11:03:50',
        ),
    2 =>
        array (
            'id' => 3,
            'name' => 'Customer',
            'display_name' => 'Customer. Can do all operations in frontend',
            'description' => 'Customer description...',
            'created_at' => '2019-04-29 11:03:50',
        ),
));
</code>```

and I see  assignRole method, when I need to assign  some role to user.
What is unclear for me what for Permissions and “permission_role” data.
Do I need them for my simple app structure? If yes, please provide some examples...

Thanks!

答:
We can't answer your question if you don't specify what your application needs to do. You can have roles without permissions or permissions without roles depending on your application. But if you want the provided tutorial to work you need them.

Permissions are specific actions of a role.

Example Permisson table data:

```<code>Permission-id: 1
Permission-name: 'Create Blog Post'
</code>```

You can assign this permission to a role 'Admin' (Role-id: 1).

Your permission_role table contains the relationship between those two. So for the above example:

```<code>permission_role
'permission_id': 1, 'role_id': 1;
</code>```

Which means that The admin role can 'Create Blog Post' in this case.

Title: Using roles with jwt / zizaco/entrust

Body:
In my new Laravel 5.8 app I read next article to use roles with jwt extention :
https://scotch.io/tutorials/role-based-authentication-in-laravel-with-jwt
and in seed I add several roles, like :

\DB::table('roles')->insert(array (
    0 =>
        array (
            'id' => 1,
            'name' => 'Admin',
            'display_name' => 'Admin',
            'description' => 'Administrator. Can do all operations in system',
            'created_at' => '2019-04-29 11:03:50',
        ),
    1 =>
        array (
            'id' => 2,
            'name' => 'Manager',
            'display_name' => 'Manager. Can do all operations in frontend and CRUD for Hostels/CMS items in Backend',
            'description' => 'Manager description...',
            'created_at' => '2019-04-29 11:03:50',
        ),
    2 =>
        array (
            'id' => 3,
            'name' => 'Customer',
            'display_name' => 'Customer. Can do all operations in frontend',
            'description' => 'Customer description...',
            'created_at' => '2019-04-29 11:03:50',
        ),
));

and I see  assignRole method, when I need to assign  some role to user.
What is unclear for me what for Permissions and “permission_role” data.
Do I need them for my simple app structure? If yes, please provide some examples...

Thanks!

Body:
We can't answer your question if you don't specify what your application needs to do. You can have roles without permissions or permissions without roles depending on your application. But if you want the provided tutorial to work you need them.

Permissions are specific actions of a role.

Example Permisson table data:

Permission-id: 1
Permission-name: 'Create Blog Post'

You can assign this permission to a role 'Admin' (Role-id: 1).

Your permission_role table contains the relationship between those two. So for the above example:

permission_role
'permission_id': 1, 'role_id': 1;

Which means that The admin role can 'Create Blog Post' in this case.


问:
How can I write in Google Sheets my Firebase data?
I have a database in Firebase, and I want to get the data from there and put them in a Google SpreadSheet.

```<code>function getData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Database");
var data = getFirebaseData('contacts');
var [rows, columns] = [sheet.getLastRow(), sheet.getLastColumn()];
var range = sheet.getRange(1,1,1,1);
Logger.log(data)
range.setValue(data)
}

function getFirebaseData(data){
var firebaseUrl = "https://XXXXX.firebaseio.com/";
var secret = 'XXXXXXXX';
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var result = base.getData('contacts');
for(var i in data) {
    Logger.log(data[i].eMail + ' ' + data[i].title);
return result;
 }
}
</code>```

and here the image:

No data is shown, and I cannot understand why

答:
Your problem should be solved by completing several steps:

In your getFirebaseData() function, move the return statement outside of the loop;

Instead of looping over data, loop over result (currently, you iterate over each property of the "contacts" String);

Optionally, add checks for getData() returning null or invalid firebaseUrl (in the last case, getData() will cause an error, use try...catch to account for that);

Change base.getData('contacts') to base.getData(data) (isn't it
the reason you pass data to the function?);

Body:
I have a database in Firebase, and I want to get the data from there and put them in a Google SpreadSheet.

function getData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Database");
var data = getFirebaseData('contacts');
var [rows, columns] = [sheet.getLastRow(), sheet.getLastColumn()];
var range = sheet.getRange(1,1,1,1);
Logger.log(data)
range.setValue(data)
}

function getFirebaseData(data){
var firebaseUrl = "https://XXXXX.firebaseio.com/";
var secret = 'XXXXXXXX';
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl, secret);
var result = base.getData('contacts');
for(var i in data) {
    Logger.log(data[i].eMail + ' ' + data[i].title);
return result;
 }
}

and here the image:

No data is shown, and I cannot understand why


问:
Embed UIViewController inside a UIView
I want to embed a UIViewController inside a UIView. I want to create this programmatically. I have created the UIViewController inside the storyboard.

My code to create a empty UIView:

```<code>let myNewView=UIView(frame: CGRect(x: (0 + screenHeight / 2), y: leftView.frame.origin.y, width: screenHeight / 2, height: leftView.frame.height))
myNewView.backgroundColor=UIColor.lightGray

self.view.addSubview(myNewView)
</code>```

And the code to append the UIViewController to the view:

```<code>let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController
myNewView.addSubview(controller.view)
</code>```

This displays the view inside my UIView, but not at the correct way. The UIView is in this case 512 pixels wide. While the (embeded) UIViewcontroller thinks that is is 1024 pixels wide (the full screen width).

How can I fix it that the embeded view gets the width and height from its parent (the UIView)?

答:
You can have a generic method like:

```<code>func embed(_ viewController:UIViewController, inParent controller:UIViewController, inView view:UIView){
   viewController.willMove(toParent: controller)
   viewController.view.frame = view.bounds
   view.addSubview(viewController.view)
   controller.addChild(viewController)
   viewController.didMove(toParent: controller)
}
</code>```

Hope it helps

Title: Embed UIViewController inside a UIView

Body:
I want to embed a UIViewController inside a UIView. I want to create this programmatically. I have created the UIViewController inside the storyboard.

My code to create a empty UIView:

let myNewView=UIView(frame: CGRect(x: (0 + screenHeight / 2), y: leftView.frame.origin.y, width: screenHeight / 2, height: leftView.frame.height))
myNewView.backgroundColor=UIColor.lightGray

self.view.addSubview(myNewView)

And the code to append the UIViewController to the view:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
var controller: UIViewController = storyboard.instantiateViewController(withIdentifier: "testView") as UIViewController
myNewView.addSubview(controller.view)

This displays the view inside my UIView, but not at the correct way. The UIView is in this case 512 pixels wide. While the (embeded) UIViewcontroller thinks that is is 1024 pixels wide (the full screen width).

How can I fix it that the embeded view gets the width and height from its parent (the UIView)?

Body:
You can have a generic method like:

func embed(_ viewController:UIViewController, inParent controller:UIViewController, inView view:UIView){
   viewController.willMove(toParent: controller)
   viewController.view.frame = view.bounds
   view.addSubview(viewController.view)
   controller.addChild(viewController)
   viewController.didMove(toParent: controller)
}

Hope it helps


问:
Bean mapper with @SqlQuery and @RegisterBeanMapper cant instantiate JDBI V3
I cant not use Jdbi with a Dao Interface as the documentation shows, see http://jdbi.org/#_reflection_mappers
it throws next exception:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: A bean, model.tipolog.TipoLog, was mapped which was not instantiable
</code>```

List<TipoLog> tipoLogs1=jdbi.withExtension(TipoLogDao.class,dao->{
        return dao.listAllLogs();
});

public interface TipoLogDao {
    @SqlQuery("SELECT * FROM tamble")
    @RegisterBeanMapper(TipoLog.class)
    List<TipoLog> listAllLogs();
}

public class TipoLog {

    private String IdTipoLog;
    private String Nombre;
    private String Descripcion;
    private String Activo;

    @ConstructorProperties({"IdTipoLog", "Nombre", "Descripcion", "Activo"})
    public TipoLog(String IdTipoLog, String Nombre, String Descripcion, String Activo) {
        this.IdTipoLog = IdTipoLog;
        this.Nombre = Nombre;
        this.Descripcion = Descripcion;
        this.Activo = Activo;
    }
}
```

答:
Note: This solution works, but if you want to use a specific constructor (not the default one), then this answer is not the one you are looking for. As said by Jigar Shah, Use @RegisterConstructorMapper instead of @RegisterBeanMapper. A BeanMapper uses only the default constructor and set properties values. To use a specific constructor, the solution is to use a ConstructorMapper.

Your TipoLog class needs a default constructor. This works:

User.java

import java.beans.ConstructorProperties;

public class User {
    int id;
    String name;

    // required default constructor
    public User() {
        super();
    }

    @ConstructorProperties({ "id", "name" })
    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    // getter, setter, hashCode, equals, toString
}
```
<p><code>UserDao.java</code></p>
<pre class="lang-java prettyprint-override"><code>import java.util.List;

import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;

public interface UserDao {
    @SqlUpdate("CREATE TABLE user (id INTEGER PRIMARY KEY, name VARCHAR)")
    void createTable();

    @SqlUpdate("INSERT INTO user(id, name) VALUES (?, ?)")
    void insertPositional(int id, String name);

    @SqlQuery("SELECT * FROM user ORDER BY name")
    @RegisterBeanMapper(User.class)
    List<User> listUsers();
}
</code>```

ConstructorPropertiesExplore.java

import java.util.List;
import static org.assertj.core.api.Assertions.*;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;

public class ConstructorPropertiesExplore {

    public static void main(String[] args) {
        Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test");
        jdbi.installPlugin(new SqlObjectPlugin());

        List<User> users = jdbi.withExtension(UserDao.class, dao -> {
            dao.createTable();
            dao.insertPositional(0, "Alice");
            dao.insertPositional(1, "Bob");
            dao.insertPositional(2, "Clarice");
            dao.insertPositional(3, "David");

            return dao.listUsers();
        });

        assertThat(users).containsExactly(new User(0, "Alice"), new User(1, "Bob"), new User(2, "Clarice"),
                new User(3, "David"));
    }

}
```

Body:
I cant not use Jdbi with a Dao Interface as the documentation shows, see http://jdbi.org/#_reflection_mappers
it throws next exception:

Exception in thread "main" java.lang.IllegalArgumentException: A bean, model.tipolog.TipoLog, was mapped which was not instantiable

List<TipoLog> tipoLogs1=jdbi.withExtension(TipoLogDao.class,dao->{
        return dao.listAllLogs();
});

public interface TipoLogDao {
    @SqlQuery("SELECT * FROM tamble")
    @RegisterBeanMapper(TipoLog.class)
    List<TipoLog> listAllLogs();
}

public class TipoLog {

    private String IdTipoLog;
    private String Nombre;
    private String Descripcion;
    private String Activo;

    @ConstructorProperties({"IdTipoLog", "Nombre", "Descripcion", "Activo"})
    public TipoLog(String IdTipoLog, String Nombre, String Descripcion, String Activo) {
        this.IdTipoLog = IdTipoLog;
        this.Nombre = Nombre;
        this.Descripcion = Descripcion;
        this.Activo = Activo;
    }
}

Body:
Note: This solution works, but if you want to use a specific constructor (not the default one), then this answer is not the one you are looking for. As said by Jigar Shah, Use @RegisterConstructorMapper instead of @RegisterBeanMapper. A BeanMapper uses only the default constructor and set properties values. To use a specific constructor, the solution is to use a ConstructorMapper.

Your TipoLog class needs a default constructor. This works:

User.java

import java.beans.ConstructorProperties;

public class User {
    int id;
    String name;

    // required default constructor
    public User() {
        super();
    }

    @ConstructorProperties({ "id", "name" })
    public User(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    // getter, setter, hashCode, equals, toString
}

UserDao.java

import java.util.List;

import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;

public interface UserDao {
    @SqlUpdate("CREATE TABLE user (id INTEGER PRIMARY KEY, name VARCHAR)")
    void createTable();

    @SqlUpdate("INSERT INTO user(id, name) VALUES (?, ?)")
    void insertPositional(int id, String name);

    @SqlQuery("SELECT * FROM user ORDER BY name")
    @RegisterBeanMapper(User.class)
    List<User> listUsers();
}

ConstructorPropertiesExplore.java

import java.util.List;
import static org.assertj.core.api.Assertions.*;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;

public class ConstructorPropertiesExplore {

    public static void main(String[] args) {
        Jdbi jdbi = Jdbi.create("jdbc:h2:mem:test");
        jdbi.installPlugin(new SqlObjectPlugin());

        List<User> users = jdbi.withExtension(UserDao.class, dao -> {
            dao.createTable();
            dao.insertPositional(0, "Alice");
            dao.insertPositional(1, "Bob");
            dao.insertPositional(2, "Clarice");
            dao.insertPositional(3, "David");

            return dao.listUsers();
        });

        assertThat(users).containsExactly(new User(0, "Alice"), new User(1, "Bob"), new User(2, "Clarice"),
                new User(3, "David"));
    }

}


问:
Windows 10 UWP : Unable to stop Looping of Pivot Control
I am trying to stop looping of Pivot Control in my Windows 10 UWP application.
I am no where found any solution for that.

Anyone have any idea about this to stop looping pivot control.

Also i want to stop direct navigation.
Suppose, we are having 6 Pivot Items in my pivot and I don't want to jump directly to Pivot Item 1 to Pivot Item 4. It should be step forward process i.e Pivotitem 1 to PivotItem 2 or PivotItem 2 to PivotItem 3.

I tried to do on selection Changed Event of Pivot Control but it didn't works for me.

```<code>var currentPivot = ((Pivot)sender);
var count = e.AddedItems.Count;

if ((currentPivot.SelectedIndex) > count)
{
    Pager.SelectedIndex = count - 1;
}
</code>```

Any response would be appreciated !

答:
Starting with SDK 14393, Win10 1607, this it now possible:</p>

```<code><Pivot IsHeaderItemsCarouselEnabled="False"/>
</code>```

Body:
I am trying to stop looping of Pivot Control in my Windows 10 UWP application.
I am no where found any solution for that.

Anyone have any idea about this to stop looping pivot control.

Also i want to stop direct navigation.
Suppose, we are having 6 Pivot Items in my pivot and I don't want to jump directly to Pivot Item 1 to Pivot Item 4. It should be step forward process i.e Pivotitem 1 to PivotItem 2 or PivotItem 2 to PivotItem 3.

I tried to do on selection Changed Event of Pivot Control but it didn't works for me.

var currentPivot = ((Pivot)sender);
var count = e.AddedItems.Count;

if ((currentPivot.SelectedIndex) > count)
{
    Pager.SelectedIndex = count - 1;
}

Any response would be appreciated !

Body:
Starting with SDK 14393, Win10 1607, this it now possible:

<Pivot IsHeaderItemsCarouselEnabled="False"/>


问:
rails: checking which controller method was called from within the model
Is there a way to check which controller method was called from within the model?

Example:
Say the controller create method was called:

```<code>def create
     do something
end
</code>```

Then in the model do something only when create in the controller was called

```<code>if create?
      do something
end
</code>```

答:
Check</p>

```<code>if params[:action] == 'create'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to check which controller method was called from within the model?

Example:
Say the controller create method was called:

def create
     do something
end

Then in the model do something only when create in the controller was called

if create?
      do something
end

Body:
Check

if params[:action] == 'create'


问:
Execute method after all promises inside of a given method resolved
In a Vue.js component, I have some methods that use axios to call an API.

In different cases, I need to execute some code once the call in this method has resolved, but I don't want to add a bunch of if statements in the .then() chained to the axios call.

```<code>methods: {
  callApi() {
    axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something
  },
  secondMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something else
  }
}
</code>```

As you can see, firstMethod and secondMethod both rely on callApi but are supposed to do a different thing once the request is done. I prefer to split this logic in different functions instead of using conditions in the callApi method.
Is there a way to do this without having to add this logic inside of the
callApi ?

答:
Promises chain, so you need to take the promise that Axios returns, perform any handling you might need to do, then return it from your callApi method. In your other methods where you're calling callApi you handle the returned promise and put any code that has to run after the API has responded in the handler function.

```<code>callApi() {
  return axios.get('/api')
   .then(() => {
     // this gets handled first
   })
},
firstMethod() {
  this.callApi()
  .then(() => {
    // this gets handled second
  })
},
secondMethod() {
  this.callApi()
  .then(() => {
    // or this gets handled second
  })
}
</code>```

Body:
In a Vue.js component, I have some methods that use axios to call an API.

In different cases, I need to execute some code once the call in this method has resolved, but I don't want to add a bunch of if statements in the .then() chained to the axios call.

methods: {
  callApi() {
    axios.get('/api')
     .then(() => {
       // call has resolved, request is done
     })
  },
  firstMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something
  },
  secondMethod() {
    this.callApi()
    // Need to wait for the call to resolve
    // Do something else
  }
}

As you can see, firstMethod and secondMethod both rely on callApi but are supposed to do a different thing once the request is done. I prefer to split this logic in different functions instead of using conditions in the callApi method.
Is there a way to do this without having to add this logic inside of the
callApi ?

Body:
Promises chain, so you need to take the promise that Axios returns, perform any handling you might need to do, then return it from your callApi method. In your other methods where you're calling callApi you handle the returned promise and put any code that has to run after the API has responded in the handler function.

callApi() {
  return axios.get('/api')
   .then(() => {
     // this gets handled first
   })
},
firstMethod() {
  this.callApi()
  .then(() => {
    // this gets handled second
  })
},
secondMethod() {
  this.callApi()
  .then(() => {
    // or this gets handled second
  })
}


问:
Uncaught TypeError: Cannot read property 'split' of undefined - bootstrap datepicker
i am using bootstrap datepicker for the input in bootstrap modal window. When I opened this windows for the first time, everything is ok and datepicker works fine. When I close this modal window and opened it again, my js console says Uncaught TypeError: Cannot read property 'split' of undefined

I'm loading form in modal window with ajax.

This is my modal window:

```<code><div id="finalModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h3 id="myModalLabel">Final date</h3>
            </div>
            <div class="modal-body" id="finalModalBody">

            </div>
            <div class="modal-footer">
                <button id="finalSubmit" class="btn btn-success">Save</button>
            </div>
</code>```

After loading this window, this script is started:

```<code>$('.datepicker').datepicker({
           format: "dd.mm.yyyy"
})
</code>```

And this is my formin modal window:

```<code><form>
<p><select onfocus="this.onmousewheel=function(){return false}" class="prereservationSelect" name="prereservation" id="frmfinalForm-prereservation"><option value="89">15. 7. 2014 - 19. 7. 2014</option><option value="0">second date</option></select></p>
<div id="otherDate" style="display: none">
    <p><strong><label for="frmfinalForm-otherDate">Zvolte jiný termín:</label></strong></p>
    <p style="float: left"><input type="text" class="datepicker text" name="otherDate" id="frmfinalForm-otherDate" value=""></p>
    <p style="margin-top: 15px; margin-left: 250px" id="date"></p>
</div>
</form>
</code>```

Thanks for any advice.

答: For me resolved add input to select $('input.datepicker') because i had another element on the code that had datepicker as class too.</p>

Body:
i am using bootstrap datepicker for the input in bootstrap modal window. When I opened this windows for the first time, everything is ok and datepicker works fine. When I close this modal window and opened it again, my js console says Uncaught TypeError: Cannot read property 'split' of undefined

I'm loading form in modal window with ajax.

This is my modal window:

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Final date

                <button id="finalSubmit" class="btn btn-success">Save</button>

After loading this window, this script is started:

$('.datepicker').datepicker({
           format: "dd.mm.yyyy"
})

And this is my formin modal window:

<form>

<select onfocus="this.onmousewheel=function(){return false}" class="prereservationSelect" name="prereservation" id="frmfinalForm-prereservation"><option value="89">15. 7. 2014 - 19. 7. 2014</option><option value="0">second date</option></select>

Zvolte jiný termín:

<input type="text" class="datepicker text" name="otherDate" id="frmfinalForm-otherDate" value="">

</form>

Thanks for any advice.


问:
np array shape for conv1d input
I have a model with conv1d as the first layer.
My data is time series data where each sample consists of 41 time steps where each time step has 4 features.
I have about 1000 samples.
I have specified the input shape of the conve1d layer to be (41,4) as it supposed to be.
However, I keep getting the following error: Input 0 is incompatible with layer conv1d_48: expected ndim=3, found ndim=2.

I suspect that the problem is that the shape of X is (1000,) while the shape of X[0] is (41,4). Has anyone encountered this problem?
Thanks.

```<code>l1=Input(shape=(41,4))
x=Conv1D(64,(4))(l1)
x=GlobalMaxPooling1D()(x)
x=Dense(1)(x)
model=Model(l1,x)
model.compile('rmsprop','binary_crossentropy',metrics=['acc'])
model.fit(X,y,32,10)
</code>```

答:
You defined an expected input on your Conv1D to be be 2D -> (41, 4)

But you give to it an input of shape (41,), be consistant in your definitions !

If you specify the input_shape in your Conv1D layer, you don't need to feed an Input layer to it.

Or you can change the shape of this Input layer to be consistant with this input_shape.

Title: np array shape for conv1d input

Body:
I have a model with conv1d as the first layer.
My data is time series data where each sample consists of 41 time steps where each time step has 4 features.
I have about 1000 samples.
I have specified the input shape of the conve1d layer to be (41,4) as it supposed to be.
However, I keep getting the following error: Input 0 is incompatible with layer conv1d_48: expected ndim=3, found ndim=2.

I suspect that the problem is that the shape of X is (1000,) while the shape of X[0] is (41,4). Has anyone encountered this problem?
Thanks.

l1=Input(shape=(41,4))
x=Conv1D(64,(4))(l1)
x=GlobalMaxPooling1D()(x)
x=Dense(1)(x)
model=Model(l1,x)
model.compile('rmsprop','binary_crossentropy',metrics=['acc'])
model.fit(X,y,32,10)


问:
Bitbucket Pipeline is supported in AWS china region?
I am planning to make use of Bitbucket pipeline for China AWS (lambda, Beanstalk) deployments. Is this possible?

Is there any technical difficulty for this - in terms of connectivity? We have HTTP/HTTPS port open with ICP procedure.

答:
Bitbucket Pipelines is currently running in a US AWS region. I'm not sure what restrictions you might have deploying to AWS China.

Perhaps you can set up an EC2 instance to SSH into and verify connectivity behaves as necessary.


问:
Jupyter Notebook: %%time magic loses global variables
Variables declared inside a %% time cell in jupyter do not show up in subsequent cells.

```<code>In [1]: %%time
        a = 2

In [2]: print(a)

NameError     Traceback (most recent call last)
<ipython-input-5-bca0e2660b9f> in <module>
----> 1 print(a)

NameError: name 'a' is not defined
</code>```

Is this a bug or by design? I don't remember facing this issue before.

I am using Python 3.7.3 with Jupyter 4.4.0 and IPython 7.4.0 on Windows 10.

答:
For folks running into this issue in the future, this is a bug in Ipython 7.4. The bug report is here - https://github.com/ipython/ipython/issues/11659

It got fixed in Ipython 7.5.

Updating ipython to 7.5 using conda update ipython solved the issue.

Body:
Variables declared inside a %% time cell in jupyter do not show up in subsequent cells.

In [1]: %%time
        a = 2

In [2]: print(a)

NameError     Traceback (most recent call last)
<ipython-input-5-bca0e2660b9f> in <module>
----> 1 print(a)

NameError: name 'a' is not defined

Is this a bug or by design? I don't remember facing this issue before.

I am using Python 3.7.3 with Jupyter 4.4.0 and IPython 7.4.0 on Windows 10.


问:
Apply styles in a PrimeNG dialog
I'm having troubles trying to apply styles in a PrimeNG dialog.

I have a component which have a PrimeNG dialog:

```<code><p-dialog header="Filters" [(visible)]="display" width="1000" height="1000" modal="modal">
...
</p-dialog>
</code>```

I also have a scss file where I have the styles of the component. The background-color of the dialog is transparent but I want to set it to white. So I've tried to apply the style in different ways in my scss file:

```<code>.ui-dialog {
    background-color: #fff;
}
</code>```

Adding styleClass to the dialog and trying to apply styles to it:

```<code><p-dialog styleClass="dialog-filters" header="Filters" [(visible)]="display" width="1000" height="1000" modal="modal">

.dialog-filters {
    background-color: #fff;
}
</code>```

None of them works. Any idea?

答:
If you are looking for modifying an existing class from html.

```<code> <p-confirmDialog
                header="Confirmation"
                appendTo="body"
                width="425"
                icon="pi pi-exclamation-triangle"
                >
<style type="text/css">
            .ui-widget-overlay.ui-dialog-mask {
               opacity: 0 !important;
            }
</style>

 </p-confirmDialog>
</code>```

Also make sure to set: encapsulation value

```<code>@Component({
    encapsulation: ViewEncapsulation.None
})
</code>```

Title: Apply styles in a PrimeNG dialog

Body:
I'm having troubles trying to apply styles in a PrimeNG dialog.

I have a component which have a PrimeNG dialog:

...

I also have a scss file where I have the styles of the component. The background-color of the dialog is transparent but I want to set it to white. So I've tried to apply the style in different ways in my scss file:

.ui-dialog {
    background-color: #fff;
}

Adding styleClass to the dialog and trying to apply styles to it:

.dialog-filters {
    background-color: #fff;
}

None of them works. Any idea?

Body:
If you are looking for modifying an existing class from html.

 <p-confirmDialog
                header="Confirmation"
                appendTo="body"
                width="425"
                icon="pi pi-exclamation-triangle"
                >
<style type="text/css">
            .ui-widget-overlay.ui-dialog-mask {
               opacity: 0 !important;
            }
</style>

 </p-confirmDialog>

Also make sure to set: encapsulation value

@Component({
    encapsulation: ViewEncapsulation.None
})


问:
How to loop through two lists simultaneously?
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

```<code>For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next
</code>```

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

答:
Your question indicates that you need a Join operation, because it's not that you want to iterate over two lists, but you also want to match like items from one list to the other.

```<code>    Dim joinedLists = From item1 In list1 _
                    Join item2 In list2 _
                    On item1.Bar Equals item2.Bar _
                    Select New With {item1, item2}

    For Each pair In joinedLists
        'Do work on combined item here'
        'pair.item1'
        'pair.item2'
    Next
</code>```

Other answers recommend Zip. That is simply a function that takes two sequences and produces a single result, much like join, but it is geared to work in a FIFO method over both lists. If you need connections made based on an equality, Join is the specifically built to be right tool for this job.

Body:
I have referred to the following question at: Using foreach loop to iterate through two lists. My question is this, with regards to the chosen answer: Can the o.DoSomething be a comparison? As in:

For Each a in ListA.Concat(ListB)
    If(a from ListA=a from ListB) Then
        Do Something here
    End If
Next

As you might've guessed, I'm using VB.Net and would like to know how I can do what I have shown here. That would basically be to iterate through a joined list separately/independently. Thanks!

Body:
Your question indicates that you need a Join operation, because it's not that you want to iterate over two lists, but you also want to match like items from one list to the other.

    Dim joinedLists = From item1 In list1 _
                    Join item2 In list2 _
                    On item1.Bar Equals item2.Bar _
                    Select New With {item1, item2}

    For Each pair In joinedLists
        'Do work on combined item here'
        'pair.item1'
        'pair.item2'
    Next

Other answers recommend Zip. That is simply a function that takes two sequences and produces a single result, much like join, but it is geared to work in a FIFO method over both lists. If you need connections made based on an equality, Join is the specifically built to be right tool for this job.


问:
New-SPWebApplication application pool account is not found
I am trying to create a new web application using PowerShell. I keep getting the error application pool account is not found! How do I solve this?

I tried adding the new web application to DefaultAppPool as follows:

```<code>New-SPWebApplication -Name "Test WebApp" -ApplicationPool "DefaultAppPool" -ApplicationPoolAccount (Get-SPManagedAccount "WIN2K8R2SPTEST\Administrator")
</code>```

But the Cmdlet Get-SPManagedAccount seems to return an empty string. I also tried to change the ApplicationPool to SharePoint 80.

I am running SharePoint Foundation 2010 on a standalone installation. How can I fix this error?

答:
In my case I already have the script as posted above by @romanrozinov. But it still didn't work. I realized I have to create a user account in the AD users. Steps can be followed here - http://www.mustbegeek.com/create-user-account-in-windows-server-2008-r2/

I'm an absolute beginner with Sharepoint, adding a user and then running below script fixed the issue:

```<code> $cred = get-credential //enter user name and password
$devAccount = New-SPManagedAccount -Credential $cred
New-SPWebApplication -Name 'Test Webapp' -ApplicationPool "DefaultAppPool" -
ApplicationPoolAccount $devAccount
</code>```

Body:
I am trying to create a new web application using PowerShell. I keep getting the error application pool account is not found! How do I solve this?

I tried adding the new web application to DefaultAppPool as follows:

New-SPWebApplication -Name "Test WebApp" -ApplicationPool "DefaultAppPool" -ApplicationPoolAccount (Get-SPManagedAccount "WIN2K8R2SPTEST\Administrator")

But the Cmdlet Get-SPManagedAccount seems to return an empty string. I also tried to change the ApplicationPool to SharePoint 80.

I am running SharePoint Foundation 2010 on a standalone installation. How can I fix this error?

Body:
In my case I already have the script as posted above by @romanrozinov. But it still didn't work. I realized I have to create a user account in the AD users. Steps can be followed here - http://www.mustbegeek.com/create-user-account-in-windows-server-2008-r2/

I'm an absolute beginner with Sharepoint, adding a user and then running below script fixed the issue:

 $cred = get-credential //enter user name and password
$devAccount = New-SPManagedAccount -Credential $cred
New-SPWebApplication -Name 'Test Webapp' -ApplicationPool "DefaultAppPool" -
ApplicationPoolAccount $devAccount


问:
GraphQL type 'Object'?
I have a MongoDB mongoose schema like this:

```<code>const playerSchema = Schema({
    conditions: { type : Object },
    date: String
})
</code>```

With a collection like this:

```<code>{
 _id: 5cee935cb56d5f794b452d78,
 conditions:
 {
    condition_a: [5.9, 6.0],
    condition_b: [6.1, 4.9],
    condition_c: [4.9, 4.0]
 },
 date: 'Wed May 29 2019 16:45:00 GMT+0200 (GMT+02:00)',
},
{
 _id: 5cee935cb56d5f794b452d70,
 conditions:
 {
    condition_a: [5.8, 6.1],
    condition_c: [4.3, 3.0]
 },
 date: 'Wed May 29 2019 16:47:00 GMT+0200 (GMT+02:00)',
},
[...]
</code>```

How I can make GraphQL Schema for this?
I've tried something like this

```<code>buildSchema(`
 type Player {
    _id: ID!
    condition: Object
    date: String
 }
`)
</code>```

Also tried: [[String]] , {} , {String} ... with no lucky

Make a collection with conditions and relations to Player is not a option.

答:
Solved with:</p>

```<code>type Condition {
    condition_a: [String],
    condition_b: [String],
    condition_c: [String],
}

type Player {
    _id: ID!
    condition: Condition
    date: String
 }
</code>```

Title: GraphQL type 'Object'?

Body:
I have a MongoDB mongoose schema like this:

const playerSchema = Schema({
    conditions: { type : Object },
    date: String
})

With a collection like this:

{
 _id: 5cee935cb56d5f794b452d78,
 conditions:
 {
    condition_a: [5.9, 6.0],
    condition_b: [6.1, 4.9],
    condition_c: [4.9, 4.0]
 },
 date: 'Wed May 29 2019 16:45:00 GMT+0200 (GMT+02:00)',
},
{
 _id: 5cee935cb56d5f794b452d70,
 conditions:
 {
    condition_a: [5.8, 6.1],
    condition_c: [4.3, 3.0]
 },
 date: 'Wed May 29 2019 16:47:00 GMT+0200 (GMT+02:00)',
},
[...]

How I can make GraphQL Schema for this?
I've tried something like this

buildSchema(`
 type Player {
    _id: ID!
    condition: Object
    date: String
 }
`)

Also tried: [[String]] , {} , {String} ... with no lucky

Make a collection with conditions and relations to Player is not a option.

Body:
Solved with:

type Condition {
    condition_a: [String],
    condition_b: [String],
    condition_c: [String],
}

type Player {
    _id: ID!
    condition: Condition
    date: String
 }


问:
catching response of post request after post's succeeded
I am creating a post request and it's executing successfully and I can see that response in the network tab.

I am trying to store that response so that I can use that further ahead, but I am not able to do so. I don't exactly know how can I store that response, can anyone guide me about that?

I have created a post like below sample and I was trying to put .then after but I think it just hadn't worked for me.

```<code>const current = api();
await current.post(`/sampleUrl`,formData);
</code>```

答:
As I do not know what's your current stack for managing XHR requests, I make a general example supposing your abstraction returns a promise:

```<code>const current = api();

getAPI = async () => {
    let res = await current.post(`/sampleUrl`,formData);
    let { data } = await res.data;
    console.log(data); // logs the response
};
</code>```

Body:
I am creating a post request and it's executing successfully and I can see that response in the network tab.

I am trying to store that response so that I can use that further ahead, but I am not able to do so. I don't exactly know how can I store that response, can anyone guide me about that?

I have created a post like below sample and I was trying to put .then after but I think it just hadn't worked for me.

const current = api();
await current.post(`/sampleUrl`,formData);

Body:
As I do not know what's your current stack for managing XHR requests, I make a general example supposing your abstraction returns a promise:

const current = api();

getAPI = async () => {
    let res = await current.post(`/sampleUrl`,formData);
    let { data } = await res.data;
    console.log(data); // logs the response
};


问:
Filter with set.has doesn't work as expected
I'm trying to filter array by Set.has like this:

const input = [
  { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' },
  { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' },
  { nick: 'Some name', x: 22, y: 27, grp: 11, id: '19344' },
  { nick: 'Some name', x: 22, y: 30, grp: 11, id: '19350' },
  { nick: 'Some name', x: 22, y: 12, grp: 23, id: '19374' },
  { nick: 'Some name', x: 22, y: 29, grp: 23, id: '19377' }
];

const grpToOmit = [ 11, 23 ];
const groupToOmitSet = new Set(grpToOmit);

input.filter(it => {
  console.log(groupToOmitSet.has(it.grp))
  return !groupToOmitSet.has(it.grp);
});

console.log(input)```

So I create collections of unique values from grpToOmit array and then I'm checking it within filter function.

This filter doesn't do anything and input array is not changing although console.log(groupToOmitSet.has(it.grp)) console true few times (I'm using oposit in next line).

答:
.filter produces a new array, it doesn't mutate the existing one. You need to assign the result to a variable.

const input = [
    { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' },
    { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' },
    { nick: 'Some name', x: 22, y: 27, grp: 11, id: '19344' },
    { nick: 'Some name', x: 22, y: 30, grp: 11, id: '19350' },
    { nick: 'Some name', x: 22, y: 12, grp: 23, id: '19374' },
    { nick: 'Some name', x: 22, y: 29, grp: 23, id: '19377' }
];

const grpToOmit = [ 11, 23 ];
const groupToOmitSet = new Set(grpToOmit);

const output = input.filter(it => {
  return !groupToOmitSet.has(it.grp);
});

console.log(output)```

Body:
I'm trying to filter array by Set.has like this:

const input = [
  { nick: 'Some name', x: 19, y: 24, grp: 4, id: '19340' },
  { nick: 'Some name', x: 20, y: 27, grp: 11, id: '19343' },
  { nick: 'Some name', x: 22, y: 27, grp: 11, id: '19344' },
  { nick: 'Some name', x: 22, y: 30, grp: 11, id: '19350' },
  { nick: 'Some name', x: 22, y: 12, grp: 23, id: '19374' },
  { nick: 'Some name', x: 22, y: 29, grp: 23, id: '19377' }
];

const grpToOmit = [ 11, 23 ];
const groupToOmitSet = new Set(grpToOmit);

input.filter(it => {
  console.log(groupToOmitSet.has(it.grp))
  return !groupToOmitSet.has(it.grp);
});

console.log(input)

So I create collections of unique values from grpToOmit array and then I'm checking it within filter function.

This filter doesn't do anything and input array is not changing although console.log(groupToOmitSet.has(it.grp)) console true few times (I'm using oposit in next line).


问:
Ansible jinja2 not concatenating to list using with_items
Why is new_list not being concatenated too?

```<code>---
- hosts: localhost
  gather_facts: False

  tasks:
  - name: Set init list
    set_fact:
      init_list:
       - 1
       - 2
       - 3

  - name: New list from with_items
    set_fact:
      new_list: "{{ new_list|default([]) + [ item ] }}"
    with_items: "{{ init_list }}"

  - debug:
      var: new_list
</code>```

When I run this short script I get the following output:

```<code>TASK [Set init list]
*************************************************************************
ok: [localhost]

TASK [New list from with_items]
*************************************************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)

TASK [debug]
*************************************************************************
ok: [localhost] => {
    "new_list": [
        3
    ]
}
</code>```

I am expecting new_list to contain 1,2,3. The concatenation is working but overwriting each time. I was sure this was working before (Ubuntu 16.04, unsure of Ansible version) and I am wondering if this is an Ansible version issue.

```<code># Ubuntu 18.04
# Ansible --version
ansible 2.5.1
  python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]
</code>```

Note: I know there are other jinja2 filters that could potentially work around this e.g. map, list, etc, but they are not easily applicable in my production code.

答:
I have finally found the correct answer. This is broken in Ansible version 2.5.1 which is unfortunately the version that comes by default in Ubuntu 18.04.

The current latest (2.5.5) does not have the issue.

sudo -H pip install ansible==2.5.5

Body:
Why is new_list not being concatenated too?

---
- hosts: localhost
  gather_facts: False

  tasks:
  - name: Set init list
    set_fact:
      init_list:
       - 1
       - 2
       - 3

  - name: New list from with_items
    set_fact:
      new_list: "{{ new_list|default([]) + [ item ] }}"
    with_items: "{{ init_list }}"

  - debug:
      var: new_list

When I run this short script I get the following output:

TASK [Set init list]
*************************************************************************
ok: [localhost]

TASK [New list from with_items]
*************************************************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)

TASK [debug]
*************************************************************************
ok: [localhost] => {
    "new_list": [
        3
    ]
}

I am expecting new_list to contain 1,2,3. The concatenation is working but overwriting each time. I was sure this was working before (Ubuntu 16.04, unsure of Ansible version) and I am wondering if this is an Ansible version issue.

# Ubuntu 18.04
# Ansible --version
ansible 2.5.1
  python version = 2.7.15rc1 (default, Nov 12 2018, 14:31:15) [GCC 7.3.0]

Note: I know there are other jinja2 filters that could potentially work around this e.g. map, list, etc, but they are not easily applicable in my production code.


问:
Selenium RC click command gets stuck
Solution:
Today (2011-04-13) handles Selenium RC the confirmation boxes under Firefox 4 badly.
I had to change back to Firefox 3.16 and then this problem disappears. Thanks again.

Original Question:

Hello Selenium gurus,

I am trying to execute an automated browser test from Java using Selenium 2.0b3 as the Java client and standalone server too.

The server starts a Firefox 4 with a specific profile.

The test is stuck at a "click" command; it waits and no timeout/exception/any error happens. During this click comes up a confirmation box, so I guess that is the problem, but I do not know why this gets stuck. In Selenium IDE comes not this confirmation box, only in RC.

The problem is not that, that the click does not happens (because the confirmation box appears), but that this confirmation box hangs.
I tried these but did not help:

```<code>selenium.click("css=div[id=command_Delete]");
selenium.click("id=command_Delete");
String JSscript = "jQuery('#command_Delete').click();" // See http://api.jquery.com/click/
selenium.runScript(JSscript);
</code>```

These are just ways how to start the click.
Maybe I have to start a different Thread according these link: http://www.sqaforums.com/showflat.php?Cat=0&Number=567974&an=&page=0&vc=1

Thanks: Andras

Java code:

```<code>selenium.click("//div[@id='command_Delete']/span");
//stucks here
//so this is not reached:
String confirmation = selenium.getConfirmation();
</code>```

HTML:

```<code><div id="command_Delete" class="...">
    <div>...</div>
    <span>Delete</span>
    <div>...</div>
    <br><br>
</div>
</code>```

Javascript:

```<code><script type="text/javascript">
    $('command_Delete').addEvent('click',function(){
        var isConfirmTrue = confirm('Do you want to delete?');
        if (isConfirmTrue) {
            var myForm = getFormObj(document, "deleteForm");
            submitForm(myForm);
        }
    });
</script>
</code>```

And in the Java, it hangs waiting the selenium rc to answer:

```<code>HttpURLConnection.getInputStream() line: 912 [local variables unavailable]
HttpURLConnection(HttpURLConnection).getResponseCode() line: 367 [local variables unavailable]
HttpCommandProcessor.getResponseCode(HttpURLConnection) line: 147
HttpCommandProcessor.getCommandResponseAsString(String) line: 167
HttpCommandProcessor.executeCommandOnServlet(String) line: 107
HttpCommandProcessor.doCommand(String, String[]) line: 89
DefaultSelenium.click(String) line: 167
...
</code>```

答:
If a confirmation box is popping up the test will block until that confirmation box has been removed.  You can do a quick manual test to see if this is your problem.

Run your test and when the confirmation box comes up manuall y interact with it, if everything else is fine the test should continue from that point as per normal.

Selenium is waiting for the page to load, but the pop up box is blocking the page from loading which is eventually resulting in a timeout.

You can try and work around this using selenium.chooseOkOnNextConfirmation(); before your click.

Title: Selenium RC click command gets stuck

Body:
Solution:
Today (2011-04-13) handles Selenium RC the confirmation boxes under Firefox 4 badly.
I had to change back to Firefox 3.16 and then this problem disappears. Thanks again.

Original Question:

Hello Selenium gurus,

I am trying to execute an automated browser test from Java using Selenium 2.0b3 as the Java client and standalone server too.

The server starts a Firefox 4 with a specific profile.

The test is stuck at a "click" command; it waits and no timeout/exception/any error happens. During this click comes up a confirmation box, so I guess that is the problem, but I do not know why this gets stuck. In Selenium IDE comes not this confirmation box, only in RC.

The problem is not that, that the click does not happens (because the confirmation box appears), but that this confirmation box hangs.
I tried these but did not help:

selenium.click("css=div[id=command_Delete]");
selenium.click("id=command_Delete");
String JSscript = "jQuery('#command_Delete').click();" // See http://api.jquery.com/click/
selenium.runScript(JSscript);

These are just ways how to start the click.
Maybe I have to start a different Thread according these link: http://www.sqaforums.com/showflat.php?Cat=0&Number=567974&an=&page=0&vc=1

Thanks: Andras

Java code:

selenium.click("//div[@id='command_Delete']/span");
//stucks here
//so this is not reached:
String confirmation = selenium.getConfirmation();

HTML:

...

    Delete

...

Javascript:

And in the Java, it hangs waiting the selenium rc to answer:

HttpURLConnection.getInputStream() line: 912 [local variables unavailable]
HttpURLConnection(HttpURLConnection).getResponseCode() line: 367 [local variables unavailable]
HttpCommandProcessor.getResponseCode(HttpURLConnection) line: 147
HttpCommandProcessor.getCommandResponseAsString(String) line: 167
HttpCommandProcessor.executeCommandOnServlet(String) line: 107
HttpCommandProcessor.doCommand(String, String[]) line: 89
DefaultSelenium.click(String) line: 167
...


问:
Testing apache poi generating excel content
I have a problem with testing apache poi generating excel method. My method returns Resource (org.springframework.core.io.Resource) and now i want to cast this to for example InputStream to create Workbook and test content file. How to do that?

For now i tested only if file exists but not content :

```<code>ResponseEntity<Resource> response = myService.createExcel();
ByteArrayResource responseBody = (ByteArrayResource) response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseBody).isNotNull();
assertThat(responseBody.contentLength()).isGreaterThan(0);
</code>```

答: You have no choice but parse the content with POI again just like your server end had done.</p>

Body:
I have a problem with testing apache poi generating excel method. My method returns Resource (org.springframework.core.io.Resource) and now i want to cast this to for example InputStream to create Workbook and test content file. How to do that?

For now i tested only if file exists but not content :

ResponseEntity<Resource> response = myService.createExcel();
ByteArrayResource responseBody = (ByteArrayResource) response.getBody();
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(responseBody).isNotNull();
assertThat(responseBody.contentLength()).isGreaterThan(0);


问:
Molecule test has stopped working with my ansible role
I just started with molecule, followed a nice simple tutorial and I generated a role and did a molecule test and it worked as intended. I rebooted my machine the following day and it's stopped working again. ERROR: 'molecule/*/molecule.yml' glob failed.  Exiting.

I am using a macbook pro 10.13.6 and below are necessary information.

```<code>do-enr-mac-4:default joseph$ ansible --version
ansible 2.7.7
config file = /Users/joseph/.ansible.cfg
configured module search path =
['/Users/joseph/.ansible/plugins/modules',
'/usr/share/ansible/plugins/modules']
ansible python module location =
/Users/joseph/.pyenv/versions/3.6.3/lib/python3.6/site-packages/ansible
executable location = /Users/joseph/.pyenv/versions/3.6.3/bin/ansible
python version = 3.6.3 (default, Dec 20 2017, 08:10:54) [GCC 4.2.1
Compatible Apple LLVM 9.0.0 (clang-900.0.38)]
do-enr-mac-4:default joseph$
do-enr-mac-4:default joseph$
do-enr-mac-4:default joseph$ molecule --version
molecule, version 2.20.1
do-enr-mac-4:default joseph$ vagrant --version
Vagrant 2.2.4
do-enr-mac-4:default joseph$ pip freeze | grep vagrant
python-vagrant==0.5.15
do-enr-mac-4:default joseph$ pip freeze | grep molecule
molecule==2.20.1
do-enr-mac-4:default joseph$ ls
INSTALL.rst     molecule.yml    playbook.yml    prepare.yml     tests
do-enr-mac-4:default joseph$ molecule --debug test
 ERROR: 'molecule/*/molecule.yml' glob failed.  Exiting.
do-enr-mac-4:default joseph$ python --version
Python 3.6.3
</code>```

problem is all search on google shows this issue way back in 2017 and it has to do with versions people used which are all different from mine right now. The debug switch is not of the molecule command is not being helpful currently so I have no information to solve this. I wanted to find out if anybody has been through this before . Thanks in advance.

答:
I infer from your ls command above and your prompt that you are launching molecule from inside your default scenario dir.

Just go back two levels (cd ../..) inside your root role dir and you're back on track.

Body:
I just started with molecule, followed a nice simple tutorial and I generated a role and did a molecule test and it worked as intended. I rebooted my machine the following day and it's stopped working again. ERROR: 'molecule/*/molecule.yml' glob failed.  Exiting.

I am using a macbook pro 10.13.6 and below are necessary information.

do-enr-mac-4:default joseph$ ansible --version
ansible 2.7.7
config file = /Users/joseph/.ansible.cfg
configured module search path =
['/Users/joseph/.ansible/plugins/modules',
'/usr/share/ansible/plugins/modules']
ansible python module location =
/Users/joseph/.pyenv/versions/3.6.3/lib/python3.6/site-packages/ansible
executable location = /Users/joseph/.pyenv/versions/3.6.3/bin/ansible
python version = 3.6.3 (default, Dec 20 2017, 08:10:54) [GCC 4.2.1
Compatible Apple LLVM 9.0.0 (clang-900.0.38)]
do-enr-mac-4:default joseph$
do-enr-mac-4:default joseph$
do-enr-mac-4:default joseph$ molecule --version
molecule, version 2.20.1
do-enr-mac-4:default joseph$ vagrant --version
Vagrant 2.2.4
do-enr-mac-4:default joseph$ pip freeze | grep vagrant
python-vagrant==0.5.15
do-enr-mac-4:default joseph$ pip freeze | grep molecule
molecule==2.20.1
do-enr-mac-4:default joseph$ ls
INSTALL.rst     molecule.yml    playbook.yml    prepare.yml     tests
do-enr-mac-4:default joseph$ molecule --debug test
 ERROR: 'molecule/*/molecule.yml' glob failed.  Exiting.
do-enr-mac-4:default joseph$ python --version
Python 3.6.3

problem is all search on google shows this issue way back in 2017 and it has to do with versions people used which are all different from mine right now. The debug switch is not of the molecule command is not being helpful currently so I have no information to solve this. I wanted to find out if anybody has been through this before . Thanks in advance.


问:
GMail and IMAP access
I would like to disable POP and IMAP for Gmail, but enable it if IMAP connection is from an approved list of IP Addresses. Is this possible? I have looked at the GSuite Admin Page: https://support.google.com/a/answer/105694, but that only allows configuration at a Gmail user basis. What I need is "all users in the domain" have access from IMAP, but the user needs to be on the corporate intranet (with approved IP addresses). Is there a way to enforce this? Thanks!</p>

答:
No there is no such option at this moment. I was just looking into the same thing. I need to limit G Suite access to employees outside a specific IP range. Employees should be able to login from within the building, but not from outside. Same applies to IMAP/POP3 access.

G Suite support suggested to turn off IMAP/POP3 and use SSO third party application or make our own SSO endpoint and control access this way, but no solution if you want to block access to IMAP or POP3 ports.

It looks like G Suite does not have any firewall options for it's users at all.

Title: GMail and IMAP access


问:
JButton is drawing behind an image
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:

```<code>    public void drawStartScreen(){
    startScreenOn = true;
    Graphics2D b = buffer.createGraphics();
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start,0,0,null);

    setLayout( null );
    button = new JButton("Start Game");
    button.setBounds(10,10,100,100);
    button.setVisible( true );
    add(button);
}
</code>```

It draws the image first, and then the Button, but the button still draws behind the image.

答: You are mixing painting and adding of components and you definitely shouldn't be doing this.  Instead add components when you create the screen or when you first need them but make sure you are only doing this once.   Then separate modify the components that need painting changes inside the paintComponent() method.

Title: JButton is drawing behind an image

Body:
I am making a starting screen, and it's working out pretty fine, got a background image when it starts, now I am trying to draw a JButton on the startmenu, which is a JFrame. But when I run my program, the button appears behind the background picture. If I hover above the area where the button is placed, it's flickering, and when I click it that happens too. Is there any way to draw the Button INFRONT of the background? I made the button as last in the code. My code to draw the background and button:

    public void drawStartScreen(){
    startScreenOn = true;
    Graphics2D b = buffer.createGraphics();
    b.setColor( Color.WHITE );
    b.fillRect(0, 0, 800, 600);
    b.drawImage(start,0,0,null);

    setLayout( null );
    button = new JButton("Start Game");
    button.setBounds(10,10,100,100);
    button.setVisible( true );
    add(button);
}

It draws the image first, and then the Button, but the button still draws behind the image.


问:
Openlayers unable to vertically scroll page when touch and dragging the map

I am using Openlayers with Angular, and have embedded a simple map on the screen. I have disabled interactions like so:

```<code>this.map = new Map({
  target: 'map',
  interactions: [],
  layers: [this.layer],
  view: this.view
});
</code>```

This prevents the map from panning when it is touched & dragged, which is what I need. However, I would like to be able to vertically scroll the browser page  down by pressing & dragging the map so the user is able to see content below the map. At the moment, it is only possible to scroll the page by touching & dragging an area outside of the map.

There are github issues relating to this:

https://github.com/openlayers/openlayers/issues/6767

https://github.com/openlayers/openlayers/issues/8458

But I could not get it to work. Anyone able to help with this?

Thanks

答:
There are several ways to achieve this. My preferred way is to configure the map with

```<code>import Map from 'ol/Map';
import {defaults as defaultInteractions} from 'ol/interaction';

new Map({
  target: 'map',
  interactions: defaultInteractions({
    onFocusOnly: true
  }),
  // ...
});
</code>```

The target element for the map in the markup needs to have a tabindex attribute, e.g.

```<code><div tabindex="1" id="map"></div>
</code>```

You can see that in action here: https://openlayers.org/en/latest/examples/interaction-options.html. The idea is that as long as the map does not have the focus, you can pan and scroll the page. Only when it has the focus (e.g. after a click on the map), pan and scroll gestures will modify the map view.

Body:
I am using Openlayers with Angular, and have embedded a simple map on the screen. I have disabled interactions like so:

this.map = new Map({
  target: 'map',
  interactions: [],
  layers: [this.layer],
  view: this.view
});

This prevents the map from panning when it is touched & dragged, which is what I need. However, I would like to be able to vertically scroll the browser page  down by pressing & dragging the map so the user is able to see content below the map. At the moment, it is only possible to scroll the page by touching & dragging an area outside of the map.

There are github issues relating to this:

https://github.com/openlayers/openlayers/issues/6767

https://github.com/openlayers/openlayers/issues/8458

But I could not get it to work. Anyone able to help with this?

Thanks

Body:
There are several ways to achieve this. My preferred way is to configure the map with

import Map from 'ol/Map';
import {defaults as defaultInteractions} from 'ol/interaction';

new Map({
  target: 'map',
  interactions: defaultInteractions({
    onFocusOnly: true
  }),
  // ...
});

The target element for the map in the markup needs to have a tabindex attribute, e.g.

<div tabindex="1" id="map"></div>

You can see that in action here: https://openlayers.org/en/latest/examples/interaction-options.html. The idea is that as long as the map does not have the focus, you can pan and scroll the page. Only when it has the focus (e.g. after a click on the map), pan and scroll gestures will modify the map view.


问:
Looking for a Product Guarantee registration form (Wordpress Plugin)
I want to create a form where users can register their product guarantees on our website.

Does anyone know of a good wordpress plugin that might be able to accommodate this? This is a standalone website without WooCommerce and essentially acts as a contact form where users enter information about the products they wish to register.

The objective is for us to be able to retrieve and retain the information sent in that we can access via the wordpress dashboard.

This also needs to notify us via email when a registration has been sent in and needs to notify users of their registration via an automated email that gets sent when they click 'submit'.

I have set up a new page that I want this to sit on but is there a way to create such a form?

Thanks

答:
I've had good luck with these two:

Contact Form 7

Gravity Forms