问:
How to deploy distributed h2o flow cluster with docker?
I'm able to deploy a h2o cluster with ec2 instances and having the private ip in the flatfile. Doing the same with docker works but I can't figure out what to enter into the flatfile so they can create the cluster. Private IP the container is running on is not working</p>

答:
Ultimately, the solution for running H2O in docker may be to use a network plugin like weave, because weave can use multicasting (unlike docker overlay).

But I managed to hack together a solution for running H2O in docker swarm on an overlay network and a flatfile. The issue with running in swarm is that docker assigns each H2O instance two IP addresses: one resolvable as the stack_service and the other seen as $HOSTNAME from within the instance. H2O needs to use the $HOSTNAME IP, but it is difficult to determine this IP in advance for the flatfile. So instead, pass a config file with the stack_service names and then change them to IP addresses using a script before launching H2O in each instance.

So, for example, use a docker-compose file that defines three services:

```<code>services:
  h2o_worker1:
    image: [h2o image]
    configs:
      - source: flatfile
        target: /flatfile
    deploy:
      placement:
        constraints:
          - node.hostname == [node1]
    ...
  h2o_worker2:
    image: [h2o image]
    configs:
      - source: flatfile
        target: /flatfile
    deploy:
      placement:
        constraints:
          - node.hostname == [node1]
    ...
  h2o_worker3:
    image: [h2o image]
    configs:
      - source: flatfile
        target: /flatfile
    deploy:
      placement:
        constraints:
          - node.hostname == [node1]
    ...

##### Configs #####
configs:
  flatfile:
    file: flatfile
</code>```

Where ... is other docker compose parameters you need to enter, and [] represents things you need to define for your setup.

Now create a flatfile based on the service names that will be imported by the config:

```<code>h2o_worker1:54321
h2o_worker2:54321
h2o_worker3:54321
</code>```

Obviously, change the ports if necessary. Then use an entrypoint script to lookup each service name's IP, and then add 1 to get the $HOSTNAME IP for each service. I just use sleep here to make sure all the services have started so that the IP lookup works. Docker always appears to assign the two IPS per service sequentially, but YMMV. As I said, this is a hack and probably not a great production-level solution. My entrypoint script looks something like this:

```<code>echo "Moving flatfile to ${H2O_HOME}"
cp /flatfile ${H2O_HOME}

sleep 60
echo "Replacing hostnames in flatfile with IP addresses."
grep -o -P '.*(?=:)' ${H2O_HOME}/flatfile > ${H2O_HOME}/hostnames
grep -o -P '(?<=:).*' ${H2O_HOME}/flatfile > ${H2O_HOME}/ports
dig +short $(cat ${H2O_HOME}/hostnames) > ${H2O_HOME}/hostnames_ip
cat ${H2O_HOME}/hostnames_ip | awk -F"." '{printf "%d.%d.%d.%d\n", $1, $2, $3, $4 + 1}' > ${H2O_HOME}/new_ips
paste -d ":" ${H2O_HOME}/new_ips ${H2O_HOME}/ports > ${H2O_HOME}/new_flatfile

echo "Starting H2O..."
bash -c "java -Xmx${H2O_NODE_MEMORY:-1g} -jar ${H2O_HOME}/h2o.jar -flatfile ${H2O_HOME}/new_flatfile"
</code>```

The key here is using dig to retrieve the IP addresses for each service host, and then incrementing by one to get the secondary address that we need to pass to H2O. Note I  define an environment variable in my Dockerfile so I can vary the node memory in the docker compose file. You don't need to do that. And the Dockerfile also sets a variable for the install location for H2O, to simplify things.

This lets me deploy the containers using docker swarm, and H2O in fact finds all the nodes correctly. Because H2O does not permit additions or deletions of nodes after the initial setup, it is not a big deal (at least for me) to define most of this in advance. That said, I may yet try to move to weave or another network plugin that avoids some of these issues.

Body:
Ultimately, the solution for running H2O in docker may be to use a network plugin like weave, because weave can use multicasting (unlike docker overlay).

But I managed to hack together a solution for running H2O in docker swarm on an overlay network and a flatfile. The issue with running in swarm is that docker assigns each H2O instance two IP addresses: one resolvable as the stack_service and the other seen as $HOSTNAME from within the instance. H2O needs to use the $HOSTNAME IP, but it is difficult to determine this IP in advance for the flatfile. So instead, pass a config file with the stack_service names and then change them to IP addresses using a script before launching H2O in each instance.

So, for example, use a docker-compose file that defines three services:

services:
  h2o_worker1:
    image: [h2o image]
    configs:
      - source: flatfile
        target: /flatfile
    deploy:
      placement:
        constraints:
          - node.hostname == [node1]
    ...
  h2o_worker2:
    image: [h2o image]
    configs:
      - source: flatfile
        target: /flatfile
    deploy:
      placement:
        constraints:
          - node.hostname == [node1]
    ...
  h2o_worker3:
    image: [h2o image]
    configs:
      - source: flatfile
        target: /flatfile
    deploy:
      placement:
        constraints:
          - node.hostname == [node1]
    ...

##### Configs #####
configs:
  flatfile:
    file: flatfile

Where ... is other docker compose parameters you need to enter, and [] represents things you need to define for your setup.

Now create a flatfile based on the service names that will be imported by the config:

h2o_worker1:54321
h2o_worker2:54321
h2o_worker3:54321

Obviously, change the ports if necessary. Then use an entrypoint script to lookup each service name's IP, and then add 1 to get the $HOSTNAME IP for each service. I just use sleep here to make sure all the services have started so that the IP lookup works. Docker always appears to assign the two IPS per service sequentially, but YMMV. As I said, this is a hack and probably not a great production-level solution. My entrypoint script looks something like this:

echo "Moving flatfile to ${H2O_HOME}"
cp /flatfile ${H2O_HOME}

sleep 60
echo "Replacing hostnames in flatfile with IP addresses."
grep -o -P '.*(?=:)' ${H2O_HOME}/flatfile > ${H2O_HOME}/hostnames
grep -o -P '(?<=:).*' ${H2O_HOME}/flatfile > ${H2O_HOME}/ports
dig +short $(cat ${H2O_HOME}/hostnames) > ${H2O_HOME}/hostnames_ip
cat ${H2O_HOME}/hostnames_ip | awk -F"." '{printf "%d.%d.%d.%d\n", $1, $2, $3, $4 + 1}' > ${H2O_HOME}/new_ips
paste -d ":" ${H2O_HOME}/new_ips ${H2O_HOME}/ports > ${H2O_HOME}/new_flatfile

echo "Starting H2O..."
bash -c "java -Xmx${H2O_NODE_MEMORY:-1g} -jar ${H2O_HOME}/h2o.jar -flatfile ${H2O_HOME}/new_flatfile"

The key here is using dig to retrieve the IP addresses for each service host, and then incrementing by one to get the secondary address that we need to pass to H2O. Note I  define an environment variable in my Dockerfile so I can vary the node memory in the docker compose file. You don't need to do that. And the Dockerfile also sets a variable for the install location for H2O, to simplify things.

This lets me deploy the containers using docker swarm, and H2O in fact finds all the nodes correctly. Because H2O does not permit additions or deletions of nodes after the initial setup, it is not a big deal (at least for me) to define most of this in advance. That said, I may yet try to move to weave or another network plugin that avoids some of these issues.


来源: stackexchange

问:
2 router in cascade with 2 DHCP and remote access
The installation is in a holidays house (so no permanent internet access)
I have a 4g-Routerm (ROUTER-1 = huawei B525-b23) that enable the internet access. I switch it on one day a week.
I have another router (ROUTER-2 = GL-MT300N-V2).

ROUTER-2 is always plugged on electricity.
On ROUTER-2 is connected through ethernet port a Raspberry-Pi3 (with Home Assistant on it).
On ROUTER-2 is connected through WIFI a Camera IP

ROUTER-1 and ROUTER-2 are connected together through ethernet.

When ROUTER-1 is not plug to electricity, none have acces to internet, but it's not an issue.

The camera save picture on the Rapbery Pi3, the Home Assistat is recording some sensor data.

When I switch on the electricity on the ROUTER-1, everyone have access to internet.

What I want is to have remote Access to my router-2 and my Rasberry and my Camera when ROUTER-1 is online

How should I do ?

答:
Hi I can think of two solutions for this setup but both involve buying a second hand cheap router.

I think the use of a single router would make this setup a lot easier. Any router would work that supports:a USB 4g Modem to be attached to it, and has support for setting up a openvpn server and you need to be OK with leaving the Internet on all the time just make sure you dont have any services running that use up bandwidth and you should be ok. You can can connect both raspberry pi and IP camera to that router. Setup Openvpn server open the UDP port required and download the certificates, You should be able to vpn into your network and manage it through SSH or something remotely.
The second option is tailored to you but still requires swapping the 4G Modem with another one that supports these things: Wake on LAN, openvpn server, supports ssh into it over LAN and either has 4G support through a sim card slot or a usb port with modem support.

You can then have it setup so this new Router-1 is switched off with wake on lan configured on it and the raspberry pi to send the magic packet. You can use something like this to get an idea of how WoL https://www.lifewire.com/wake-on-lan-4149800. You can use cron on your raspberry pi to send WoL signal to Router 1 once a week which would eventually give you internet access once the router is up. You have to setup a vpn server on it and forward the required port and download the certificates. When your scheduled WoL cron runs make sure you are able to connect through vpn then access network resources you wish, at the end when you are done you can ssh into the router-1 and turn it off.

I hope this helps. I had a look at the router models you are using and it doesnt leave you with many options. You can get cheap second hand routers online that support everything that is required.

ContentLicense: CC BY-SA 4.0


问:
VBA: Removing an empty placeholder XML Ribbon Tab from Excel
I have a workbook which had a custom XML ribbon. I removed all the code using the Custom UI Editor for Microsoft Office and now I have an empty tab (no header and content) sitting in my ribbon. How can I get rid of that empty tab? I'm using Office 2016.

Here are some screenshots:

I removed the XML completely

Here's the tab I need removed

Thanks in advance!

答:
You may try to remove the tab manually. Follow the steps:

Change the workbook extension .xlsm to .zip.

Unzip the contents.

Open file \customUI\customUI.xml.

Remove unnecessary <tab> node, save changes.

Zip the contents back.

Rename extension .zip to .xlsm.


问:
5 Column background DIV to fill empty space
I need all of my columns on a page to appear be the same height. I'd be fine doing this if there were just one background colour but there are 5, taking up 20% of the width each on a desktop.

.container {
    display: table;
    float: left;
    width: 100%;
    background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
}

.col1 {
    float: left;
    width: 20%;
    background-color: #91F5AD;
}

@media only screen and (max-width: 500px) {
.col1{
    float: left;
    width: 100%;
    background-color: #91F5AD;
}
}

.col2 {
    float: left;
    width: 20%;
    background-color: #8FBFE0;
}

@media only screen and (max-width: 500px) {
.col2{
    float: left;
    width: 100%;
    background-color: #8FBFE0;
}
}

.col3 {
    float: left;
    width: 20%;
    background-color: #7C77B9;
}

@media only screen and (max-width: 500px) {
.col3{
    float: left;
    width: 100%;
    background-color: #7C77B9;
}
}

.col4 {
    float: left;
    width: 20%;
    background-color: #0BC9CD;
}

@media only screen and (max-width: 500px) {
.col4{
    float: left;
    width: 100%;
    background-color: #0BC9CD;
}
}

.col5 {
    float: left;
    width: 20%;
    background-color: #05A8AA;
}

@media only screen and (max-width: 500px) {
.col5{
    float: left;
    width: 100%;
    background-color: #05A8AA;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="col1"><br></div>
<div class="col2"><br></div>
<div class="col3"><br></div>
<div class="col4"><br></div>
<div class="col5"><br></div>
</div></code>```

I need the container to replicate the pattern of the DIV backgrounds in order to make it seem as though they're all the same height.

If you see below, you'll see the issue.

    .container {
        display: table;
        float: left;
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
    }

    .col1 {
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="col1"><br></div>
<div class="col2"><br></div>
<div class="col3"><br></div>
<div class="col4"><br></div>
<div class="col5"><br></div>
<br><br>
</div>
<p>The green is fine but the rest don't match above themselves</p></code>```

Any help would be appreciated. Thanks in advance.

答:
You did not properly set your gradient in the first place.

you need to set the start and stop value for the colors, you did set all of them at 20%.

it should more like : background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #8FBFE0 40%, #7C77B9 40%,#7C77B9 60%, #0BC9CD 60%,  #0BC9CD 80%, #05A8AA 80%); (0% and 100% do not need to be written since it is not mixing with another color)

infos here: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient .

See snippet below

.container {
        float: left;/* or display:table is fine to deal with floatting child , both is not necessary */
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #8FBFE0 40%, #7C77B9 40%,#7C77B9 60%, #0BC9CD 60%,  #0BC9CD 80%, #05A8AA 80%);
    }

    .col1 {
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }
    .container>div {background:none!important;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
<div class="col1"><br></div>
<div class="col2"><br></div>
<div class="col3"><br></div>
<div class="col4"><br></div>
<div class="col5"><br></div>
<br><br>
</div>
<p>The green is fine and also the other gradient colors once start/stop values are set</p></code>```

For infos , this is a method that was called the "faux-columns" when almost only float was avalaible .https://alistapart.com/article/fauxcolumns/

Body:
I need all of my columns on a page to appear be the same height. I'd be fine doing this if there were just one background colour but there are 5, taking up 20% of the width each on a desktop.

.container {
    display: table;
    float: left;
    width: 100%;
    background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
}

.col1 {
    float: left;
    width: 20%;
    background-color: #91F5AD;
}

@media only screen and (max-width: 500px) {
.col1{
    float: left;
    width: 100%;
    background-color: #91F5AD;
}
}

.col2 {
    float: left;
    width: 20%;
    background-color: #8FBFE0;
}

@media only screen and (max-width: 500px) {
.col2{
    float: left;
    width: 100%;
    background-color: #8FBFE0;
}
}

.col3 {
    float: left;
    width: 20%;
    background-color: #7C77B9;
}

@media only screen and (max-width: 500px) {
.col3{
    float: left;
    width: 100%;
    background-color: #7C77B9;
}
}

.col4 {
    float: left;
    width: 20%;
    background-color: #0BC9CD;
}

@media only screen and (max-width: 500px) {
.col4{
    float: left;
    width: 100%;
    background-color: #0BC9CD;
}
}

.col5 {
    float: left;
    width: 20%;
    background-color: #05A8AA;
}

@media only screen and (max-width: 500px) {
.col5{
    float: left;
    width: 100%;
    background-color: #05A8AA;
}
}

I need the container to replicate the pattern of the DIV backgrounds in order to make it seem as though they're all the same height.

If you see below, you'll see the issue.

    .container {
        display: table;
        float: left;
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #7C77B9 20%, #0BC9CD 20%, #05A8AA 20%);
    }

    .col1 {
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }

The green is fine but the rest don't match above themselves

Any help would be appreciated. Thanks in advance.

Body:
You did not properly set your gradient in the first place.

you need to set the start and stop value for the colors, you did set all of them at 20%.

it should more like : background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #8FBFE0 40%, #7C77B9 40%,#7C77B9 60%, #0BC9CD 60%,  #0BC9CD 80%, #05A8AA 80%); (0% and 100% do not need to be written since it is not mixing with another color)

infos here: https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient .

See snippet below

.container {
        float: left;/* or display:table is fine to deal with floatting child , both is not necessary */
        width: 100%;
        background: linear-gradient(to right,  #91F5AD 20%, #8FBFE0 20%, #8FBFE0 40%, #7C77B9 40%,#7C77B9 60%, #0BC9CD 60%,  #0BC9CD 80%, #05A8AA 80%);
    }

    .col1 {
        float: left;
        width: 20%;
        background-color: #91F5AD;
    }

    @media only screen and (max-width: 500px) {
    .col1{
        float: left;
        width: 100%;
        background-color: #91F5AD;
    }
    }

    .col2 {
        float: left;
        width: 20%;
        background-color: #8FBFE0;
    }

    @media only screen and (max-width: 500px) {
    .col2{
        float: left;
        width: 100%;
        background-color: #8FBFE0;
    }
    }

    .col3 {
        float: left;
        width: 20%;
        background-color: #7C77B9;
    }

    @media only screen and (max-width: 500px) {
    .col3{
        float: left;
        width: 100%;
        background-color: #7C77B9;
    }
    }

    .col4 {
        float: left;
        width: 20%;
        background-color: #0BC9CD;
    }

    @media only screen and (max-width: 500px) {
    .col4{
        float: left;
        width: 100%;
        background-color: #0BC9CD;
    }
    }

    .col5 {
        float: left;
        width: 20%;
        background-color: #05A8AA;
    }

    @media only screen and (max-width: 500px) {
    .col5{
        float: left;
        width: 100%;
        background-color: #05A8AA;
    }
    }
    .container>div {background:none!important;}

<div class="container">
<div class="col1"><br></div>
<div class="col2"><br></div>
<div class="col3"><br></div>
<div class="col4"><br></div>
<div class="col5"><br></div>
<br><br>
</div>
<p>The green is fine and also the other gradient colors once start/stop values are set</p>

For infos , this is a method that was called the "faux-columns" when almost only float was avalaible .https://alistapart.com/article/fauxcolumns/


问:
Is there a way to write this “if” list in a more elegant way?
Suppose I have an object POJO style and for some of its attributes I have to check if are equals to a particular value; if so I have to add this attribute to a list and throw an exception (just once if one of the attributes is equal to the particular value). Is there a better way to do it than this way?</p>

```<code>// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
     list.add(object.getAttributeA());
     haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
    list.add(object.getAttributeB());
    haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
    list.add(object.getAttributeC());
    haveToThrowException = true;
}//and so on

if (haveToThrownException) {
    throw new Exception(list.toString());
}
</code>```

答:
Yes?  I think the Strategy Pattern would work great in this case.

This solution has A LOT more code then the other solutions, but has the advantage of not changing the calling class if you have to check more attributes in the future.

Here is some pseudo code...

```<code>public class ThrowsException {

    private Strategy strategy;

    public ThrowsException(Strategy strategy) {

        this.strategy = strategy;
    }

    public void doYourMethod(Object object) {

        List<String> values = this.strategy.checkObject(object);

        if (!values.isEmpty) {

            throw new Exception(values.toString());
        }
    }
}
</code>```

A class that will iterate of individual strategies so that the calling class doesn't know that there can be more than one strategy.

```<code>public class ForLoopStrategy implements Strategy {

    private List<CheckObjectStrategy> strategies

    public ForLoopStrategy(List<CheckObjectStrategy> strategies) {

       this.strategies = strategies;
    }

    public List<String> checkObject(Object object) {

        List<String> values = new ArrayList<>();

        for (CheckObjectStrategy strategy : this.strategies) {

            String value = strategy.checkObject(object);

            if (value != null) {

                values.add(value);
            }
        }
    }
}
</code>```

The actual class that will check a specific attribute.  One will be needed for every attribute that you want to check.

```<code>public class CheckAttributeA implements CheckObjectStrategy {

    public String checkObject(Object object) {

        String value = null;

        if (object.getAttributeA().equals("0")) {
            value = object.getAttributeA();
        }

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

BTW, I am sure that there is something simpler here if you could use reflection to call the different attributes...

Body:
Suppose I have an object POJO style and for some of its attributes I have to check if are equals to a particular value; if so I have to add this attribute to a list and throw an exception (just once if one of the attributes is equal to the particular value). Is there a better way to do it than this way?

// pseudocode
List<String> list = new ArrayList<String>();
boolean haveToThrowException = false;
if (object.getAttributeA().equals(“0”) {
     list.add(object.getAttributeA());
     haveToThrowException = true;
}
if (object.getAttributeB().equals(“0”) {
    list.add(object.getAttributeB());
    haveToThrowException = true;
}
if (object.getAttributeC().equals(“0”) {
    list.add(object.getAttributeC());
    haveToThrowException = true;
}//and so on

if (haveToThrownException) {
    throw new Exception(list.toString());
}

Body:
Yes?  I think the Strategy Pattern would work great in this case.

This solution has A LOT more code then the other solutions, but has the advantage of not changing the calling class if you have to check more attributes in the future.

Here is some pseudo code...

public class ThrowsException {

    private Strategy strategy;

    public ThrowsException(Strategy strategy) {

        this.strategy = strategy;
    }

    public void doYourMethod(Object object) {

        List<String> values = this.strategy.checkObject(object);

        if (!values.isEmpty) {

            throw new Exception(values.toString());
        }
    }
}

A class that will iterate of individual strategies so that the calling class doesn't know that there can be more than one strategy.

public class ForLoopStrategy implements Strategy {

    private List<CheckObjectStrategy> strategies

    public ForLoopStrategy(List<CheckObjectStrategy> strategies) {

       this.strategies = strategies;
    }

    public List<String> checkObject(Object object) {

        List<String> values = new ArrayList<>();

        for (CheckObjectStrategy strategy : this.strategies) {

            String value = strategy.checkObject(object);

            if (value != null) {

                values.add(value);
            }
        }
    }
}

The actual class that will check a specific attribute.  One will be needed for every attribute that you want to check.

public class CheckAttributeA implements CheckObjectStrategy {

    public String checkObject(Object object) {

        String value = null;

        if (object.getAttributeA().equals("0")) {
            value = object.getAttributeA();
        }

        return value;
    }
}

BTW, I am sure that there is something simpler here if you could use reflection to call the different attributes...


问:
How to Convert CSS Grid Template Columns to Rows Responsively
I am trying to display a 3 column layout on desktop and a single column layout on mobile using CSS Grid.

However, when I try the following a 3 column layout persists with a viewport smaller than 650px.

```<code>.page {
  display: grid;
  grid-template-columns: 33% 34% 33%
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 100%;
  }
}
</code>```

How do I transition between a 3 column wide layout to single column stacked layout responsively with CSS Grid?

答:
You can add a grid-template-area property as follows:

```<code>.page {
  display: grid;
  grid-template-area: "a b c";
  grid-template-columns: 33% 34% 33%
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 100%;
    grid-template-area:
      "a"
      "b"
      "c";
  }
}
</code>```

Where string delimiters denote new rows.

Body:
I am trying to display a 3 column layout on desktop and a single column layout on mobile using CSS Grid.

However, when I try the following a 3 column layout persists with a viewport smaller than 650px.

.page {
  display: grid;
  grid-template-columns: 33% 34% 33%
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 100%;
  }
}

How do I transition between a 3 column wide layout to single column stacked layout responsively with CSS Grid?

Body:
You can add a grid-template-area property as follows:

.page {
  display: grid;
  grid-template-area: "a b c";
  grid-template-columns: 33% 34% 33%
}

@media (max-width: 650px) {
  .page {
    grid-template-columns: 100%;
    grid-template-area:
      "a"
      "b"
      "c";
  }
}

Where string delimiters denote new rows.


问:
How do I resize one specific image in custom Wordpress theme?
Please note that I am new to wordpress and I apologize in advance if I am asking a poorly formed question or am leaving out details. I will follow up with anything you need as an answerer.

Problem: I have an image that's spilling over the div, container, etc? (I'm also new to CSS) in Wordpress. Here is the image:

I'd like it to fit in the image. Also note that the image shows another image when a mouse hovers over it. Strangely that image has no issues with resizing. I've tried a variety of solutions including.

```<code>img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain
}
</code>```

And I've tried editing the image dimensions in the media page. Part of the problem is it's a custom theme. And custom themes are a little harder to work with when it comes to custom CSS (or so I've learned). Any suggestions on the matter are greatly appreciated. Please let me know if you have further details.

答: Turns out custom CSS wasn't necessary. The image itself was actually formatted incorrectly. I didn't check that option because I thought to myself, "It couldn't possibly be that." Leaving this as a possible answer for people who've tried everything. </p>

Body:
Please note that I am new to wordpress and I apologize in advance if I am asking a poorly formed question or am leaving out details. I will follow up with anything you need as an answerer.

Problem: I have an image that's spilling over the div, container, etc? (I'm also new to CSS) in Wordpress. Here is the image:

I'd like it to fit in the image. Also note that the image shows another image when a mouse hovers over it. Strangely that image has no issues with resizing. I've tried a variety of solutions including.

img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain
}

And I've tried editing the image dimensions in the media page. Part of the problem is it's a custom theme. And custom themes are a little harder to work with when it comes to custom CSS (or so I've learned). Any suggestions on the matter are greatly appreciated. Please let me know if you have further details.


问:
How come my code only returns the first element from my list?
How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?</p>

```<code>def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))
</code>```

答:
You can reach your goal by creating an empty list inside your function and appending it.

Like so:

```<code>def show_magicians(magicians):

    new_list = []
    for magician in magicians:
        new_list.append(magician)

    return new_list

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))
</code>```

But then you'd be returning the list with same values as your argument.

Body:
How come when I call the function I get only the first element from the list printed, but when I replace "return" for "print" inside the function and then call it I get the full list?

def show_magicians(magicians):

    for magician in magicians:
        return(magician)

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))

Body:
You can reach your goal by creating an empty list inside your function and appending it.

Like so:

def show_magicians(magicians):

    new_list = []
    for magician in magicians:
        new_list.append(magician)

    return new_list

magicians = ["a", "b", "c", "d", "e","f", "g"]
print(show_magicians(magicians))

But then you'd be returning the list with same values as your argument.


问:
R - image of a pixel matrix?
How would you you make an image from a matrix in R?

Matrix values would correspond to pixel intensity on image (although I am just interested in 0,1 values white or black at the moment.), while column and row numbers correspond to vertical and horizontal location on the image.

By make an image I mean display it on the screen and save it as a jpg.

答:
You can create a heatmap of the matrix.

```<code>library(pheatmap)

# Create a 10x10 matrix of random numbers
m = matrix(runif(100), 10, 10)

# Save output to jpeg
jpeg("heatmap.jpg")

pheatmap(m, cluster_row = FALSE, cluster_col = FALSE, color=gray.colors(2,start=1,end=0))

dev.off()
</code>```

See ?pheatmap for more options.

ContentLicense: CC BY-SA 3.0

Title: R - image of a pixel matrix?

Body:
You can create a heatmap of the matrix.

library(pheatmap)

# Create a 10x10 matrix of random numbers
m = matrix(runif(100), 10, 10)

# Save output to jpeg
jpeg("heatmap.jpg")

pheatmap(m, cluster_row = FALSE, cluster_col = FALSE, color=gray.colors(2,start=1,end=0))

dev.off()

See ?pheatmap for more options.


问:
Split ActivatedRoute queryParams subscription into multiple subscriptions
I want to get Angular ActivatedRoute queryParams changes and execute a function just once and other function every time.

So far the way I found is subscribing twice but I want a better way to do it, maybe using some pipe operator.

```<code>// DO SOMETHING THE FIRST TIME
this.activatedRoute.queryParamMap
      .pipe(
        first(),
        switchMap(params => {
          // HTTP CALL
        })
      )
      .subscribe((data: any) => {
        // DO SOMETHING
      });

// DO SOMETHING ALWAYS
this.activatedRoute.queryParamMap
      .subscribe((params: any) => {
        // DO SOMETHING
      });
</code>```

Is there any other way do this, something like splitSubscription operator??

答:
One approach can be something like this,

```<code>visited = false;
this.activatedRoute.queryParamMap.pipe(
  tap(_ => {
    //do your always thing
  }),
  filter(_ => !this.visited),
  tap(_ => {
    this.visited = true;
    // do your one time thing
  })
).subscribe();
</code>```

Instead of tap, you can have your own set of operators, the thing to notice is, filtering this way will allow only once to go down and there you can have your one-time implementation.

Body:
I want to get Angular ActivatedRoute queryParams changes and execute a function just once and other function every time.

So far the way I found is subscribing twice but I want a better way to do it, maybe using some pipe operator.

// DO SOMETHING THE FIRST TIME
this.activatedRoute.queryParamMap
      .pipe(
        first(),
        switchMap(params => {
          // HTTP CALL
        })
      )
      .subscribe((data: any) => {
        // DO SOMETHING
      });

// DO SOMETHING ALWAYS
this.activatedRoute.queryParamMap
      .subscribe((params: any) => {
        // DO SOMETHING
      });

Is there any other way do this, something like splitSubscription operator??

Body:
One approach can be something like this,

visited = false;
this.activatedRoute.queryParamMap.pipe(
  tap(_ => {
    //do your always thing
  }),
  filter(_ => !this.visited),
  tap(_ => {
    this.visited = true;
    // do your one time thing
  })
).subscribe();

Instead of tap, you can have your own set of operators, the thing to notice is, filtering this way will allow only once to go down and there you can have your one-time implementation.


问:
Tkinter open and close Toplevel windows
Iam new in Python, and my set goal is trying to create an application for myself to list and manipulate some data; in my case some coins.
I am self teaching code, but there are many thing I do not understand yet.

Iam organizing the code as best as I could, but I have reached some of my limits.

My code is showing a Tk window which is containing the data that you enter in a second window using Toplevel. When you use the ADD button it shows the window, but if you happen to close it and open it again, it shows an error. Iam sure it is because my instance of the window is destroyed but I would love to have your input about how I should solve this issue. What would you suggest ?

Thanks for your time !

from tkinter import *  # tkinter package import
from tkinter import ttk

window_size = '480x600+0+0'

############################ Window 1 configuration ############################
window = Tk()
window.title('Coin Collector')  # title of the window
window.geometry(window_size)  #taille de la fenetre
window.config(background='white')

#searchbar
search_bar_txt = Label(window, text='Search :')
search_bar_txt.place(height=40,width=70,x=1,y=1)
search_bar_entry = Entry(window)
search_bar_entry.place(height=40,width=410,x=71,y=1)

# tree view setup
tree=ttk.Treeview(window)
tree['columns']=('one','two','three')
tree.column('#0', width=29, minwidth=80)
tree.column('one', width=150, minwidth=80)
tree.column('two', width=150, minwidth=80)
tree.column('three', width=147, minwidth=80)

tree.heading('#0',text='#ID')
tree.heading('one', text='COIN')
tree.heading('two', text='YEAR')
tree.heading('three', text='PRICE')

tree.place(height= 510,x=0, y=50)

def show_window2():
    window_2.deiconify()

###### BUTTONS ########
Button_add = Button(window, text='ADD', command=show_window2)
Button_add.place(height=40, width=120, x=0, y=560)

Button_remove = Button(window, text='REMOVE')
Button_remove.place(height=40, width=120, x=120, y=560)

Button_edit = Button(window, text='EDIT')
Button_edit.place(height=40, width=120, x=240, y=560)

Button_exit = Button(window, text='EXIT', command=exit)
Button_exit.place(height=40, width=120, x=360, y=560)

############################ Window 2 configuration ############################
window_2 = Toplevel()
window_2.title('Edit coin')
window_2.geometry('300x500+480+0')
window_2.config(background='white')
window_2.iconify()
window_2.protocol('WM_DELETE_WINDOW', window_2.destroy);#Changes close button

#coin type
coin_type_txt = Label(window_2, text='Coin Name :')
coin_type_txt.place(x=0, y=0)
coin_type_value = Entry(window_2)
coin_type_value.place(height=30, width=165, x=130, y=0)

#coin year
coin_year_txt = Label(window_2, text='Coin year :')
coin_year_txt.place(x=0, y=35)
coin_year_value = Entry(window_2)
coin_year_value.place(height=30, width=165, x=130, y=35)

#coin price
coin_price_txt = Label(window_2, text='Coin price :')
coin_price_txt.place(x=0, y=70)
coin_price_value = Entry(window_2,width=10)
coin_price_value.place(height=30, width=165, x=130, y=70)

def save_coin(): #create function to execute when clicked
    tree.insert('','end',text='',values=(coin_type_value.get(),coin_year_value.get(),coin_price_value.get()))

#save coin
coin_save_button = Button(window_2, text='save', command=save_coin)
coin_save_button.place(height=40, width=300, x=0, y=460)

######FUNCTIONS######

def exit():
    window.destroy()

window.mainloop()

```

答:
Hey thanks for the answer. It is working !

I now have created a function Addcoin_window(), and I call it from a button ADD which is located just some lines after.

Is there any way to organise my code, so that all my functions could be located at the end of my program ? Its just that I find it "messy" to have the function Addcoin_window() located on what I considered my main window organisation. Is that the Python way ?

Once again thanks for your help.

from tkinter import *  # tkinter package import
from tkinter import ttk

window_size = '480x600+0+0'

############################ Window 1 configuration ############################
window = Tk()
window.title('Coin Collector')  # title of the window
window.geometry(window_size)  #taille de la fenetre
window.config(background='white')

#searchbar
search_bar_txt = Label(window, text='Search :')
search_bar_txt.place(height=40,width=70,x=1,y=1)
search_bar_entry = Entry(window)
search_bar_entry.place(height=40,width=410,x=71,y=1)

# tree view setup
tree=ttk.Treeview(window)
tree['columns']=('one','two','three')
tree.column('#0', width=29, minwidth=80)
tree.column('one', width=150, minwidth=80)
tree.column('two', width=150, minwidth=80)
tree.column('three', width=147, minwidth=80)

tree.heading('#0',text='#ID')
tree.heading('one', text='COIN')
tree.heading('two', text='YEAR')
tree.heading('three', text='PRICE')

tree.place(height= 510,x=0, y=50)

def Addcoin_window():
    window_2 = Toplevel()
    window_2.title('Edit coin')
    window_2.geometry('300x500+480+0')
    window_2.config(background='white')
    #window_2.iconify()
    window_2.protocol('WM_DELETE_WINDOW', window_2.destroy);#Changes close button

    #coin type
    coin_type_txt = Label(window_2, text='Coin Name :')
    coin_type_txt.place(x=0, y=0)
    coin_type_value = Entry(window_2)
    coin_type_value.place(height=30, width=165, x=130, y=0)

    #coin year
    coin_year_txt = Label(window_2, text='Coin year :')
    coin_year_txt.place(x=0, y=35)
    coin_year_value = Entry(window_2)
    coin_year_value.place(height=30, width=165, x=130, y=35)

    #coin price
    coin_price_txt = Label(window_2, text='Coin price :')
    coin_price_txt.place(x=0, y=70)
    coin_price_value = Entry(window_2,width=10)
    coin_price_value.place(height=30, width=165, x=130, y=70)

    def save_coin(): #create function to execute when clicked
        tree.insert('','end',text='',values=(coin_type_value.get(),coin_year_value.get(),coin_price_value.get()))

    #save coin
    coin_save_button = Button(window_2, text='SAVE', command=save_coin)
    coin_save_button.place(height=40, width=300, x=0, y=460)

###### BUTTONS ########
Button_add = Button(window, text='ADD', command=Addcoin_window)
Button_add.place(height=40, width=120, x=0, y=560)

Button_remove = Button(window, text='REMOVE')
Button_remove.place(height=40, width=120, x=120, y=560)

Button_edit = Button(window, text='EDIT')
Button_edit.place(height=40, width=120, x=240, y=560)

Button_exit = Button(window, text='EXIT', command=exit)
Button_exit.place(height=40, width=120, x=360, y=560)

######FUNCTIONS######

def exit():
    window.destroy()

window.mainloop()

```

Title: Tkinter open and close Toplevel windows


问:
slf4j logger doesn't print full package name
I have a project with some classes using org.slf4j.Logger to log some information. The loggers in all other classes are working OK and print full class name, e.g. INFO com.myapp.gca.servlet.LoginServlet - Entering login. But for one class, it doesn't print full class name, e.g. INFO c.m.gca.servlet.HealthCheckServlet - GCA health check OK, where com.myapp. is replaced by c.m..

I couldn't find any difference in this particular class from others. The logger is defined like

```<code> private static Logger log = LoggerFactory.getLogger(HealthCheckServlet.class);
</code>```

What may be the reason?

答:
See the Conversion Word table at the official documentation. You have to configure the logger to the length of at least 40 because of the combined package and class name length:

```<code>%logger{40}
</code>```

However, the %logger would be better which always provides the full name.

Body:
I have a project with some classes using org.slf4j.Logger to log some information. The loggers in all other classes are working OK and print full class name, e.g. INFO com.myapp.gca.servlet.LoginServlet - Entering login. But for one class, it doesn't print full class name, e.g. INFO c.m.gca.servlet.HealthCheckServlet - GCA health check OK, where com.myapp. is replaced by c.m..

I couldn't find any difference in this particular class from others. The logger is defined like

 private static Logger log = LoggerFactory.getLogger(HealthCheckServlet.class);

What may be the reason?

Body:
See the Conversion Word table at the official documentation. You have to configure the logger to the length of at least 40 because of the combined package and class name length:

%logger{40}

However, the %logger would be better which always provides the full name.


问:
How to replace string into numbers using sed?
I am trying to replace string into number from the file
So, I have variable &FLOW which need to change to 001, ex :

```<code>cat file.txt
This is file ' PISP &FLOW'
PISD.DATA.CYCLE&FLOW..ONE
</code>```

desired output

```<code>This is file ' PISP 001'
PISD.DATA.CYCLE001.ONE
</code>```

I tried below commands in a script :

```<code>for item in file.txt
do
sed 's/\&FLOW/\./001/g' $item
sed 's/\&FLOW/001/g' $item
done
</code>```

It is giving error. The second sed command is working, but I need to run first the beginning sed command otherwise after running first the second sed command, it would ignore the beginning sed command.

Any help would be appreciated!

答:
try this:

```<code>for item in file.txt
do
  sed 's/\&FLOW\./001/g' $item
  sed 's/\&FLOW/001/g' $item
done
</code>```

You had a redundant / in after FLOW

This might also work:

```<code>  sed -i 's/\&FLOW[\.]?/001/g' file.txt
</code>```

Body:
I am trying to replace string into number from the file
So, I have variable &FLOW which need to change to 001, ex :

cat file.txt
This is file ' PISP &FLOW'
PISD.DATA.CYCLE&FLOW..ONE

desired output

This is file ' PISP 001'
PISD.DATA.CYCLE001.ONE

I tried below commands in a script :

for item in file.txt
do
sed 's/\&FLOW/\./001/g' $item
sed 's/\&FLOW/001/g' $item
done

It is giving error. The second sed command is working, but I need to run first the beginning sed command otherwise after running first the second sed command, it would ignore the beginning sed command.

Any help would be appreciated!

Body:
try this:

for item in file.txt
do
  sed 's/\&FLOW\./001/g' $item
  sed 's/\&FLOW/001/g' $item
done

You had a redundant / in after FLOW

This might also work:

  sed -i 's/\&FLOW[\.]?/001/g' file.txt


问:
angular service ready flag
i'm try to rewrite my angularJS app to angular2
so i got service which download i18n labels from different endpoints
and i need to know when all of data is ready.

in my angularJS components i can do like so

vm.loading = true;
backend.ready.then(() => {
   loading = false;
   backend.getAlias('anyLabel')
})
```

<p>so when loading === false i'm hide loader and can get aliases
But i can't figure out how i can do it with angular2 services and observables. Now i have something like this:</p>

<pre class="lang-js prettyprint-override"><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, zip, of, Subject } from 'rxjs';

export interface Alias {
    code: string;
    value: string;
}

@Injectable({
    providedIn: 'root'
})
export class BackendService {
    private aliases: Alias[];
    private aliasDeclaration: Alias[];
    public ready: Observable<boolean>;

    constructor(private http: HttpClient) {
        this.aliases = [];
        this.aliasDeclaration = [];
        this.ready = new Observable<boolean>();
    }

    private getAliases(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/json/get-aliases?lang=ru');
    }

    private getDeclarations(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/themes/backend/aliases-declaration.json');
    }

    public init(): void {
        zip(this.getAliases(), this.getDeclarations()).subscribe(([aliases, declarations]) => {
            this.aliases = aliases;
            this.aliasDeclaration = declarations;
            // i need to set ready = true here, but can't figure out how :)
        });
    }

    public getAlias(code): Alias {
        return this.aliases.find(alias => alias.code === code);
    }

    public getAliasDeclaration(code): Alias {
        return this.aliasDeclaration.find(alias => alias.code === code);
    }
}

</code>```

答:
use a behaviorSubject

```<code>public ready= new BehaviorSubject(false);
</code>```

to make ready emit

```<code>public init(): void {
        zip(this.getAliases(), this.getDeclarations()).subscribe(([aliases, declarations]) => {
            this.aliases = aliases;
            this.aliasDeclaration = declarations;
            // i need to set ready = true here, but can't figure out how :)
this.ready.next(true)

        });
    }
</code>```

Title: angular service ready flag

Body:
i'm try to rewrite my angularJS app to angular2
so i got service which download i18n labels from different endpoints
and i need to know when all of data is ready.

in my angularJS components i can do like so

vm.loading = true;
backend.ready.then(() => {
   loading = false;
   backend.getAlias('anyLabel')
})

so when loading === false i'm hide loader and can get aliases
But i can't figure out how i can do it with angular2 services and observables. Now i have something like this:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, zip, of, Subject } from 'rxjs';

export interface Alias {
    code: string;
    value: string;
}

@Injectable({
    providedIn: 'root'
})
export class BackendService {
    private aliases: Alias[];
    private aliasDeclaration: Alias[];
    public ready: Observable<boolean>;

    constructor(private http: HttpClient) {
        this.aliases = [];
        this.aliasDeclaration = [];
        this.ready = new Observable<boolean>();
    }

    private getAliases(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/json/get-aliases?lang=ru');
    }

    private getDeclarations(): Observable<Alias[]> {
        return this.http.get<Alias[]>('/themes/backend/aliases-declaration.json');
    }

    public init(): void {
        zip(this.getAliases(), this.getDeclarations()).subscribe(([aliases, declarations]) => {
            this.aliases = aliases;
            this.aliasDeclaration = declarations;
            // i need to set ready = true here, but can't figure out how :)
        });
    }

    public getAlias(code): Alias {
        return this.aliases.find(alias => alias.code === code);
    }

    public getAliasDeclaration(code): Alias {
        return this.aliasDeclaration.find(alias => alias.code === code);
    }
}

Body:
use a behaviorSubject

public ready= new BehaviorSubject(false);

to make ready emit

public init(): void {
        zip(this.getAliases(), this.getDeclarations()).subscribe(([aliases, declarations]) => {
            this.aliases = aliases;
            this.aliasDeclaration = declarations;
            // i need to set ready = true here, but can't figure out how :)
this.ready.next(true)

        });
    }


问:
Using multiple values for iQuery method .css() throws error: 'missing )'. However its not missing
Error says I'm missing a parenthesis. However the syntax is identical to w3Schools and Mozilla. .css() works if im only setting one style, but break when setting more than 1.

jQuery

```<code> <script>
      $(document).ready( function(){

          // event-handler to create new element
          function createContainer() {

              // variables store values from <select> element
              var elementType = $('select').val();

              // string containing markup for use with .append()
              var elementTypeStr = $(` <${elementType}> This is a ${elementType} </${elementType}> `);
              // this throws error, while setting single style doesn't
              $('#layout_demo').append( elementTypeStr );
              elementTypeStr.css("background-color":" blue" , "height": "100px");

          } // end createContainer()

          // ---------------------------- event handlers ---------------------

          $('#btn').click( createContainer );
          // button to delete latest element or selected element

      }); // end ready

  </script>

</code>```

HTML:

```<code><section id="form">
  <!-- select element --->
  <label for="container"> Please select type of container to add</label>
  <select id= "container">
    <option value= "div" > &ltdiv&gt </option>
    <option value= "p"> &ltp&gt </option>
    <option value= "section"> &ltsection&gt </option>

  </select>
  <!-- Seperate container to hold now elements -->

  <button id="btn" > Create Container </button>
</section>

<div id="layout_demo">

</div>
</code>```

答:
Multiple .css() properties need to be inside an Object.

$(document).ready(function() {

  // event-handler to create new element
  function createContainer() {

    // variables store values from <select> element
    var elementType = $('select').val();

    // string containing markup for use with .append()
    var elementTypeStr = $(` <${elementType}> This is a ${elementType} </${elementType}> `);
    // this throws error, while setting single style doesn't
    $('#layout_demo').append(elementTypeStr);
    elementTypeStr.css({
      "background-color": " blue",
      "height": "100px"
    });

  } // end createContainer()

  // ---------------------------- event handlers ---------------------

  $('#btn').click(createContainer);
  // button to delete latest element or selected element

}); // end ready```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="form">
  <!-- select element --->
  <label for="container"> Please select type of container to add</label>
  <select id="container">
    <option value="div"> &ltdiv&gt </option>
    <option value="p"> &ltp&gt </option>
    <option value="section"> &ltsection&gt </option>

  </select>
  <!-- Seperate container to hold now elements -->

  <button id="btn"> Create Container </button>
</section>

<div id="layout_demo">

</div></code>```

Body:
Error says I'm missing a parenthesis. However the syntax is identical to w3Schools and Mozilla. .css() works if im only setting one style, but break when setting more than 1.

jQuery

HTML:

   Please select type of container to add
  <select id= "container">
    <option value= "div" > &ltdiv&gt </option>
    <option value= "p"> &ltp&gt </option>
    <option value= "section"> &ltsection&gt </option>

  </select>

  <button id="btn" > Create Container </button>

Body:
Multiple .css() properties need to be inside an Object.

$(document).ready(function() {

  // event-handler to create new element
  function createContainer() {

    // variables store values from <select> element
    var elementType = $('select').val();

    // string containing markup for use with .append()
    var elementTypeStr = $(` <${elementType}> This is a ${elementType} </${elementType}> `);
    // this throws error, while setting single style doesn't
    $('#layout_demo').append(elementTypeStr);
    elementTypeStr.css({
      "background-color": " blue",
      "height": "100px"
    });

  } // end createContainer()

  // ---------------------------- event handlers ---------------------

  $('#btn').click(createContainer);
  // button to delete latest element or selected element

}); // end ready

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="form">
  <!-- select element --->
  <label for="container"> Please select type of container to add</label>
  <select id="container">
    <option value="div"> &ltdiv&gt </option>
    <option value="p"> &ltp&gt </option>
    <option value="section"> &ltsection&gt </option>

  </select>
  <!-- Seperate container to hold now elements -->

  <button id="btn"> Create Container </button>
</section>

<div id="layout_demo">

</div>


问:
Changing FontSize in Summernote very Buggy
I am having trouble using the fontsize feature of Summernote.  It seems to work best in Chrome- but even then I must type the text first, highlight it, then select the fontsize I want from the Summernote Text Editor to change it.  Other browsers don't seem to work at all.

I thought this might be caused by some class that's overwriting the font-size so I tried using the Developer Tool in IE to undo any suspect classes and then try changing the font again, but with no luck.  I have also searched all over the internet and found very little which leads me to believe it must be something wrong with my particular installation of Summernote.  Moreover, I can't seem to find a demo of Summernote anywhere online- which would be helpful in determining if this is just a 'me' issue or part of a much larger problem.

Any help is very much appreciated

```<code><textarea class="loneTextArea" style="width: 400px; height: 60px;"></textarea>
</code>```

How I instantiate Summernote:

```<code>$(document).ready(function () {

    $('.loneTextArea').summernote({
        toolbar: [
          ['style', ['bold', 'italic', 'underline', 'clear']],
          ['font', ['strikethrough']],
          ['fontsize', ['fontsize']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['height', ['height']],
          ['codeview', ['codeview']]
        ],
        height: 60,
        width: 400,
    });

});
</code>```

答:
try this:

```<code>$(document).ready(function () {

 $('.loneTextArea').summernote({
    toolbar: [
      ['style', ['bold', 'italic', 'underline', 'clear']],
      ['font', ['strikethrough']],
      ['fontsize', ['fontsize']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['height', ['height']],
      ['codeview', ['codeview']]
    ],
    fontSizes: [ '12', '16', '18', '24'], //here set the font size options you want
    height: 60,
    width: 400,
 });

});
</code>```

OR, try this:

```<code>$('.loneTextArea').summernote('fontSize', 20);
</code>```

Body:
I am having trouble using the fontsize feature of Summernote.  It seems to work best in Chrome- but even then I must type the text first, highlight it, then select the fontsize I want from the Summernote Text Editor to change it.  Other browsers don't seem to work at all.

I thought this might be caused by some class that's overwriting the font-size so I tried using the Developer Tool in IE to undo any suspect classes and then try changing the font again, but with no luck.  I have also searched all over the internet and found very little which leads me to believe it must be something wrong with my particular installation of Summernote.  Moreover, I can't seem to find a demo of Summernote anywhere online- which would be helpful in determining if this is just a 'me' issue or part of a much larger problem.

Any help is very much appreciated

<textarea class="loneTextArea" style="width: 400px; height: 60px;"></textarea>

How I instantiate Summernote:

$(document).ready(function () {

    $('.loneTextArea').summernote({
        toolbar: [
          ['style', ['bold', 'italic', 'underline', 'clear']],
          ['font', ['strikethrough']],
          ['fontsize', ['fontsize']],
          ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']],
          ['height', ['height']],
          ['codeview', ['codeview']]
        ],
        height: 60,
        width: 400,
    });

});

Body:
try this:

$(document).ready(function () {

 $('.loneTextArea').summernote({
    toolbar: [
      ['style', ['bold', 'italic', 'underline', 'clear']],
      ['font', ['strikethrough']],
      ['fontsize', ['fontsize']],
      ['color', ['color']],
      ['para', ['ul', 'ol', 'paragraph']],
      ['height', ['height']],
      ['codeview', ['codeview']]
    ],
    fontSizes: [ '12', '16', '18', '24'], //here set the font size options you want
    height: 60,
    width: 400,
 });

});

OR, try this:

$('.loneTextArea').summernote('fontSize', 20);


问:
Leveraging FusionAuth login / verify screens
We have two administrative SPAs that can make easy use of the FusionAuth templated login / verify screens. This is useful as the screens automatically reflect our social logins as those are configured,

The third SPA is carefully designed and places the login fields on a dynamic splash page. I'm considering an attempt to html embed the FusionAuth login panel on our splash page but would need to strip away the nav bar and background container. I think this would be a global change to the FusionAuth UI web layout, forcing the use of embeds in all our apps.

We have FusionAuth running on a subdomain so an embed might not cause much CORS difficulty. Are there any other reasons that embedding the login panel directly from the FusionAuth server into our pages might not be a workable solution?

答:
You can modify the FusionAuth login UI without impacting the administration UI. If you go to Settings -> System -> UI, you will see that the Login UI templates can all be modified.

If you have different login UI elements for different Applications, you can use the variable client_id in the templates to control the layout. This is the OAuth client_id that for the FusionAuth Application. These templates are FreeMarker, so a conditional statement might look like this:

```<code>[#if client_id == 'ee31103f-2fc1-4bb5-ba95-ac543693503e']
  Embeddable HTML/CSS goes here
[#else]
  Standard HTML/CSS goes here
[/#if]
</code>```

That being said, the OAuth login UI of FusionAuth might not be easily embeddable in your third SPA depending on if you are using an iframe or AJAX. It is still probably a better idea to skin the login UI to match your UI instead and leverage the OAuth login workflow if possible.

The other solution is to use your own login page and then call the FusionAuth APIs to authenticate the user.

We have been exploring adding an embeddable login system. If you want to open a feature request for this, you can add it on our Github Issue tracker here: https://github.com/FusionAuth/fusionauth-issues

Body:
You can modify the FusionAuth login UI without impacting the administration UI. If you go to Settings -> System -> UI, you will see that the Login UI templates can all be modified.

If you have different login UI elements for different Applications, you can use the variable client_id in the templates to control the layout. This is the OAuth client_id that for the FusionAuth Application. These templates are FreeMarker, so a conditional statement might look like this:

[#if client_id == 'ee31103f-2fc1-4bb5-ba95-ac543693503e']
  Embeddable HTML/CSS goes here
[#else]
  Standard HTML/CSS goes here
[/#if]

That being said, the OAuth login UI of FusionAuth might not be easily embeddable in your third SPA depending on if you are using an iframe or AJAX. It is still probably a better idea to skin the login UI to match your UI instead and leverage the OAuth login workflow if possible.

The other solution is to use your own login page and then call the FusionAuth APIs to authenticate the user.

We have been exploring adding an embeddable login system. If you want to open a feature request for this, you can add it on our Github Issue tracker here: https://github.com/FusionAuth/fusionauth-issues


问:
Selecting an option element from a dropdown by its text value
Given an HTML form element like:

```<code><select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>
</code>```

I know I can select the first option with

```<code>document.getElementById("mydropdown").value='foo'
</code>```

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

答:
I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.</p>

```<code>document.getElementById("mydropdown").text = 'Eggs';
</code>```

Body:
Given an HTML form element like:

<select id='mydropdown'>
  <option value='foo'>Spam</option>
  <option value='bar'>Eggs</option>
</select>

I know I can select the first option with

document.getElementById("mydropdown").value='foo'

However, say I have a variable with the value "Spam"; can I select a dropdown item by its text rather than by its value?

Body:
I'd use the selectedIndex or a loop to select the option by text, the code below doesn't work.

document.getElementById("mydropdown").text = 'Eggs';


问:
XML Parsing Error: no root element found Location in Console FF
I'm use ASP.NET MVC end I take this error only in FF. Why I take this error message?  What is the cause of this?
I don't understand where the source of this error. Anyone have any thoughts?

Next Error:

答:
We were getting this error when POSTing an axios call. And our test server was not in the

```<code>allowed-origin:
</code>```

list of hosts. Adding our server to allowed-origin in the application.yml resolved the issue.

Body:
We were getting this error when POSTing an axios call. And our test server was not in the

allowed-origin:

list of hosts. Adding our server to allowed-origin in the application.yml resolved the issue.


问:
TestCafe .click doesn't trigger onClick event within an iFrame
I'm attempting to automate a payment system, where the "Pay with PayPal" button is within an iFrame. I've searched through TestCafe's support pages, and can't seem to resolve the issue.

TestCafe believes it has clicked on the button, and so fails at the next step (enter email address).

What I'm using:

const payPalFrame = Selector('#paypal-button iframe');
const payPalButton = Selector('[name="paypal"]')

async payWithPaypal () {
    await t
        .switchToIframe(payPalFrame)
        .click(payPalButton)
        .switchToMainWindow();
}
```

I tried to write a ClientFunction, but still relatively new to JS/Node and couldn't get anything to work.

答: There is a bug in testcafe that the iframes sometimes doesn't load their stylesheets therefore you may want to check if the tag which needs to be clicked in the iframe has the proper width, height and position.</p>

Body:
I'm attempting to automate a payment system, where the "Pay with PayPal" button is within an iFrame. I've searched through TestCafe's support pages, and can't seem to resolve the issue.

TestCafe believes it has clicked on the button, and so fails at the next step (enter email address).

What I'm using:

const payPalFrame = Selector('#paypal-button iframe');
const payPalButton = Selector('[name="paypal"]')

async payWithPaypal () {
    await t
        .switchToIframe(payPalFrame)
        .click(payPalButton)
        .switchToMainWindow();
}

I tried to write a ClientFunction, but still relatively new to JS/Node and couldn't get anything to work.


问:
Create a Table(s) with Users and Groups
I'm building a rental application for school. There will be three groups will have access to this application. Managers, Associates and Owner. Each group may have restrictions on the functionality. My issue is that I created a login form and I need to redirect the user(according to their group) to another form. I need to create a table with users and groups to be able to cal a certain group when the user enters their Username and Password.

I've tried to create a table, but then I got stuck on which data should I  put as a foreign key.

```<code>CREATE TABLE Users (
                UserID INT NOT NULL,
                PASSWORD VARCHAR(50),
                PRIMARY KEY(UserID)
                );

CREATE TABLE Groups (
                    GroupID INT,
                    GroupName VARCHAR,
                    PRIMARY KEY(GroupID)
                    );

CREATE TABLE User_Groups (
                        UserID INT,
                        GroupID INT,
                        );
</code>```

答:
If a user belongs exactly to one group, and it looks like this is the case here, you better put the group ID in the user table. Constraint it as a foreign key to the ID in the groups table, to be sure only valid group IDs can be inserted, and as not null, to enforce that it has to be set.</p>

```<code>CREATE TABLE groups
             (grouid integer,
              groupname varchar(50),
              PRIMARY KEY (groupid));

CREATE TABLE users
             (userid integer,
              username varchar(50),
              password varchar(50),
              grouid integer NOT NULL,
              PRIMARY KEY (userid),
              FOREIGN KEY (groupid)
                          REFERENCES groups
                                     (groupid));
</code>```

Title: Create a Table(s) with Users and Groups

Body:
I'm building a rental application for school. There will be three groups will have access to this application. Managers, Associates and Owner. Each group may have restrictions on the functionality. My issue is that I created a login form and I need to redirect the user(according to their group) to another form. I need to create a table with users and groups to be able to cal a certain group when the user enters their Username and Password.

I've tried to create a table, but then I got stuck on which data should I  put as a foreign key.

CREATE TABLE Users (
                UserID INT NOT NULL,
                PASSWORD VARCHAR(50),
                PRIMARY KEY(UserID)
                );

CREATE TABLE Groups (
                    GroupID INT,
                    GroupName VARCHAR,
                    PRIMARY KEY(GroupID)
                    );

CREATE TABLE User_Groups (
                        UserID INT,
                        GroupID INT,
                        );

Body:
If a user belongs exactly to one group, and it looks like this is the case here, you better put the group ID in the user table. Constraint it as a foreign key to the ID in the groups table, to be sure only valid group IDs can be inserted, and as not null, to enforce that it has to be set.

CREATE TABLE groups
             (grouid integer,
              groupname varchar(50),
              PRIMARY KEY (groupid));

CREATE TABLE users
             (userid integer,
              username varchar(50),
              password varchar(50),
              grouid integer NOT NULL,
              PRIMARY KEY (userid),
              FOREIGN KEY (groupid)
                          REFERENCES groups
                                     (groupid));


问:
The movie game - skipping "The" at the beginning of a movie
The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.

The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.

How can I remove "The" from the movie title?

```<code>def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()
</code>```

答:
You could do this:

```<code>if lastInput.lower().startswith("the "): lastInput = lastInput[4:]
</code>```

Using the startswith() method of strings, you can test for the first word directly (including the space that follows it).  In order to support various capitalisation, turning the string to lowercase (using lower()) allows you to only perform one test for any combinations of upper/lower case variants (e.g. "The ", "the ", "THE ").

I also noticed that you are not applying this exclusion logic to the userChoice variable which is where I would have expected this to be used rather than on the lastInput variable.

Body:
The Movie Game is a game played by two people, and goes as follows. The first player names a movie. The second player then names a new movie whose title starts with the last letter of the movie the first player named.

The game we will ignore the definite article "the" So if a player names the movie "Her Alibi" the next player can name the movie "The Incredibles," since the article "the" is ignored.

How can I remove "The" from the movie title?

def userInput(lastInput):
    if lastInput == None:
            return str(input("Enter a movie title: ")).lower()
    if lastInput[:4] == "The ": # doesn't work
        lastInput = lastInput[4:] # doesn't work
    while True:
        userChoice = str(input("Enter a movie title: ")).lower()
        if userChoice[0] == lastInput[-1]:
            return userChoice
        else:
            print("\nInvalid input, what would you like to do?")
            instructions()

Body:
You could do this:

if lastInput.lower().startswith("the "): lastInput = lastInput[4:]

Using the startswith() method of strings, you can test for the first word directly (including the space that follows it).  In order to support various capitalisation, turning the string to lowercase (using lower()) allows you to only perform one test for any combinations of upper/lower case variants (e.g. "The ", "the ", "THE ").

I also noticed that you are not applying this exclusion logic to the userChoice variable which is where I would have expected this to be used rather than on the lastInput variable.


答: I am not sure what are you looking to do with 'ready' if you just want to assign a value the you can use  this.ready = Observable.of(true); and add an import for Observable from import { Observable } from 'rxjs';

Title: angular service ready flag


问:
I'm trying to make a GET request to a public API, however, I get No 'Access-Control-Allow-Origin' header is present on the requested resource
I've literally just created a new project and made a single route:

```<code>Route::get('/getSummoner', 'RiotController@getSummoner');
</code>```

That executes this function:

```<code>public function getSummoner(){

$get = file_get_contents("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/RiotSchmick?api_key=");
$result = json_decode($get);

return response()->json([
    'result' => $result,
], 201);

}
</code>```

and on the front-end, I get the following error:

```<code>Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
</code>```

I understand this happens when the I make a request to a different domain than what my page is on but since the API is not mine, I can't really make a request from the same domain, can I?

答: That message indicates that their API is not allowing your site to access it.  It may be allowing you to access it via Postman, direct site visit via URL, or some other direct method...but you need the Access-Control-Allow-Origin header to specifically allow your web domain (which in this case seems to be internal to you) in order to be able to access it.</p>

Body:
I've literally just created a new project and made a single route:

Route::get('/getSummoner', 'RiotController@getSummoner');

That executes this function:

public function getSummoner(){

$get = file_get_contents("https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/RiotSchmick?api_key=");
$result = json_decode($get);

return response()->json([
    'result' => $result,
], 201);

}

and on the front-end, I get the following error:

Access to XMLHttpRequest at 'url' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I understand this happens when the I make a request to a different domain than what my page is on but since the API is not mine, I can't really make a request from the same domain, can I?


问:
How can I use "float: left" in a div without breaking the containing element's height?
It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="portfoliosite">
    <div class="portfoliothumbnail"><!-- Img tag goes here --></div>
    <p class="portfoliotitle">AwesomeSite.Com</p>
    <p class="portfoliodescription">An awesome site I did. It launched on Jan 1, 2009</p>
</div></code>```

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

答:
Yes. You should clear your float when div's closing.</p>

```<code><div>
  <div style="float:left">Floated Div</div>
  <div style="clear:both;" />
</div>
</code>```

OwnerDisplayName: Joshua Carmody

Body:
It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}

AwesomeSite.Com

An awesome site I did. It launched on Jan 1, 2009

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

LastEditorDisplayName: Joshua Carmody

Body:
Yes. You should clear your float when div's closing.

<div>
  <div style="float:left">Floated Div</div>
  <div style="clear:both;" />
</div>

OwnerDisplayName: David

ContentLicense: CC BY-SA 2.5


答:
Use a single sed command and use -i to actually modify the file contents and you need to pass file.txt as the input for the sed command:

```<code>sed -i 's/&FLOW\.\{0,1\}/001/g' file.txt
</code>```

See the online demo. If you are using it in Mac OS, you need sed -i '' 's/&FLOW\.\{0,1\}/001/g' file.txt. Also see sed edit file in place.

Pattern details

It is a POSIX BRE compliant pattern matching

&FLOW - a literal &FLOW substring

\.\{0,1\} - 0 or 1 occurrence of a . char.

Title: How to replace string into numbers using sed?

Body:
I am trying to replace string into number from the file
So, I have variable &FLOW which need to change to 001, ex :

cat file.txt
This is file ' PISP &FLOW'
PISD.DATA.CYCLE&FLOW..ONE

desired output

This is file ' PISP 001'
PISD.DATA.CYCLE001.ONE

I tried below commands in a script :

for item in file.txt
do
sed 's/\&FLOW/\./001/g' $item
sed 's/\&FLOW/001/g' $item
done

It is giving error. The second sed command is working, but I need to run first the beginning sed command otherwise after running first the second sed command, it would ignore the beginning sed command.

Any help would be appreciated!

Body:
Use a single sed command and use -i to actually modify the file contents and you need to pass file.txt as the input for the sed command:

sed -i 's/&FLOW\.\{0,1\}/001/g' file.txt

See the online demo. If you are using it in Mac OS, you need sed -i '' 's/&FLOW\.\{0,1\}/001/g' file.txt. Also see sed edit file in place.

Pattern details

It is a POSIX BRE compliant pattern matching

&FLOW - a literal &FLOW substring

\.\{0,1\} - 0 or 1 occurrence of a . char.


问:
Jquery : How to get all value of inputs element with array names?
I have html code which looks like below :

```<code><input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">
</code>```

How do I select all the fruits and get their respective values? I'm looking for an object like

```<code>{
  "apple": true,
  "orange": false,
  "mango": true
}
</code>```

答:
You can select elements which start with fruits[, and map to their values:

const vals = $('[name^="fruits["]')
  .map((_, input) => input.value)
  .get();
console.log(vals);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true"></code>```

Keep in mind that the .value of inputs are strings - if you need booleans instead, you'll have to do so more explicitly:

const vals = $('[name^="fruits["]')
  .map((_, input) => input.value === 'true')
  .get();
console.log(vals);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true"></code>```

If you need the unique part of the name as well, then reduce into an object of key-value pairs (and may as well drop the jQuery if using reduce):

const vals = [...document.querySelectorAll('[name^="fruits["]')]
  .reduce((a, { name, value }) => {
    const key = name.match(/[^[]+(?=\])/)[0];
    a[key] = value === 'true';
    return a;
  }, {});
console.log(vals);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true"></code>```

Body:
I have html code which looks like below :

<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">

How do I select all the fruits and get their respective values? I'm looking for an object like

{
  "apple": true,
  "orange": false,
  "mango": true
}

Body:
You can select elements which start with fruits[, and map to their values:

const vals = $('[name^="fruits["]')
  .map((_, input) => input.value)
  .get();
console.log(vals);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">

Keep in mind that the .value of inputs are strings - if you need booleans instead, you'll have to do so more explicitly:

const vals = $('[name^="fruits["]')
  .map((_, input) => input.value === 'true')
  .get();
console.log(vals);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">

If you need the unique part of the name as well, then reduce into an object of key-value pairs (and may as well drop the jQuery if using reduce):

const vals = [...document.querySelectorAll('[name^="fruits["]')]
  .reduce((a, { name, value }) => {
    const key = name.match(/[^[]+(?=\])/)[0];
    a[key] = value === 'true';
    return a;
  }, {});
console.log(vals);

<input type="text" name="fruits[apple]" value="true">
<input type="text" name="fruits[orange]" value="false">
<input type="text" name="fruits[mango]" value="true">


问:
Can I display multiple rows from a selected cell value?
I am building off of a previous question I asked. My problem is I want to create an automated email system that notifies my when a certain cell gets updated relative to a specific person. See Can I automate an email off google sheets based on specific updated columns and rows? for my previous post.

I have the code and it is working great. However, now I am looking to display another Column from the edited row.

Is there a way to display another column from that Row? Like if X12 was edited. Can I also Display B12 and H12. That way it displays my control ID as well as my Control owner?

```<code>function sendNotification(e){
  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellvalue = e.range.getValue();
  var subject = 'SUBJECT'+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue(); //get column 9 for current row
  var ControlID = e.col(2).getvalue();

 if (name === 'NAME' && (col === 23 || col === 24 || col === 31 ||
col === 32) === true) {

MailApp.sendEmail({
  to: "EMAIL",
  subject: subject,
  htmlBody: "<br><br>"+
  "The following cell has been updated. <br><br>"+
  "<font size=\"2.5\" color=\"black\"><b> Cell: </b></font>" +
  cell + "<br><br>" + "Control ID: " + col +
  "<br>Update: " + cellvalue + "<br>" +
  "<br><br>Thank you. <br>"
})
} }
</code>```

So in the email it would state: if X12 was the updated cell

The following control was updated B12. The owner is H12

The updated Cellvalue = X12

I can format how it looks but I can't figure out how to display the same row but a different column of the updated value.

答:
Me again - yeah this is totally possible. All you need to do is pass variable row to a getRange() and use the number of the column you're trying to get the values from.

This script should do the trick.

```<code>function sendNotification(e){
  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellValue = e.range.getValue();
  var subject = 'SUBJECT'+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue(); //get column 9 for current row

  if (name === 'NAME' && (col === 23 || col === 24 || col === 31 || col === 32) === true) {
    var control = ss.getRange(row, 2).getValue(); //get value for column B in current row
    var owner = ss.getRange(row, 8).getValue();   //get value for column H in current row

    MailApp.sendEmail({
      to: "EMAIL",
      subject: subject,
      htmlBody: "The following cell has been updated:<br>"+
      "<font size=\"2.5\" color=\"black\"><b> Cell: </b></font>" + cell +
      "<br><br>" + "The following control was updated: " + control + ", the owner is: " + owner +
      "<br>Update: " + cellValue + "<br>" +
      "<br><br>Thank you. <br>"
    });
  }
}
</code>```

All I've done is added two variables, using getRange() like I mentioned earlier:

```<code>var control = ss.getRange(row, 2).getValue(); //get value for column B in current row
var owner = ss.getRange(row, 8).getValue();   //get value for column H in current row
</code>```

Once you've got var control and var owner, you can use these in your email body, I have also added that to the script above. You can play around with the formatting but I based it off of the template you provided in your question. The email should end up looking something like this (note: 'b4' and 'h4' are just the examples values I entered into the cell itself):

Hope this helps achieve your goal.

Body:
I am building off of a previous question I asked. My problem is I want to create an automated email system that notifies my when a certain cell gets updated relative to a specific person. See Can I automate an email off google sheets based on specific updated columns and rows? for my previous post.

I have the code and it is working great. However, now I am looking to display another Column from the edited row.

Is there a way to display another column from that Row? Like if X12 was edited. Can I also Display B12 and H12. That way it displays my control ID as well as my Control owner?

function sendNotification(e){
  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellvalue = e.range.getValue();
  var subject = 'SUBJECT'+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue(); //get column 9 for current row
  var ControlID = e.col(2).getvalue();

 if (name === 'NAME' && (col === 23 || col === 24 || col === 31 ||
col === 32) === true) {

MailApp.sendEmail({
  to: "EMAIL",
  subject: subject,
  htmlBody: "

"+
  "The following cell has been updated.

"+
  " Cell: " +
  cell + "

" + "Control ID: " + col +
  "
Update: " + cellvalue + "
" +
  "

Thank you.
"
})
} }

So in the email it would state: if X12 was the updated cell

The following control was updated B12. The owner is H12

The updated Cellvalue = X12

I can format how it looks but I can't figure out how to display the same row but a different column of the updated value.

Body:
Me again - yeah this is totally possible. All you need to do is pass variable row to a getRange() and use the number of the column you're trying to get the values from.

This script should do the trick.

function sendNotification(e){
  var ss = e.source.getSheetByName('Datasheet');
  var cell = e.range.getA1Notation();
  var row = e.range.getRow();
  var col = e.range.getColumn();
  var cellValue = e.range.getValue();
  var subject = 'SUBJECT'+ ss.getSheetName();
  var name = ss.getRange(row, 9).getValue(); //get column 9 for current row

  if (name === 'NAME' && (col === 23 || col === 24 || col === 31 || col === 32) === true) {
    var control = ss.getRange(row, 2).getValue(); //get value for column B in current row
    var owner = ss.getRange(row, 8).getValue();   //get value for column H in current row

    MailApp.sendEmail({
      to: "EMAIL",
      subject: subject,
      htmlBody: "The following cell has been updated:<br>"+
      "<font size=\"2.5\" color=\"black\"><b> Cell: </b></font>" + cell +
      "<br><br>" + "The following control was updated: " + control + ", the owner is: " + owner +
      "<br>Update: " + cellValue + "<br>" +
      "<br><br>Thank you. <br>"
    });
  }
}

All I've done is added two variables, using getRange() like I mentioned earlier:

var control = ss.getRange(row, 2).getValue(); //get value for column B in current row
var owner = ss.getRange(row, 8).getValue();   //get value for column H in current row

Once you've got var control and var owner, you can use these in your email body, I have also added that to the script above. You can play around with the formatting but I based it off of the template you provided in your question. The email should end up looking something like this (note: 'b4' and 'h4' are just the examples values I entered into the cell itself):

Hope this helps achieve your goal.


问:
issues with lapply; subscript out of bounds (and can't figure out where the issue is)
Can somebody help!

I am trying to use lapply to loop lstrends() across a large list, yet I received the error and can't think of a fix

Error :

"Error in data[[var]] : subscript out of bounds"

Code :

```<code>    ## Test data
  Tissue=c("Normal","Normal","Normal","Normal","Tumor","Tumor","Tumor","Tumor")
    GeneY = c(34,12,11,8,53,32,39,80)
    GeneZ = c(4,7,3,9,44,32,56,77)
    GeneX = c(42,54,59,22,35,12,22,40)
    dvList <- c("GeneY", "GeneZ")
    breast = data.frame(Tissue, GeneX,GeneY,GeneZ)

    ## linear regression lapply works fine
    model = lapply(dvList, function(x) {
        lm(substitute(i~GeneX*Tissue, list(i = as.name(x))), data = breast)})
    library(lsmeans)

    ## selecting individual components of the list works fine
    m.lst = as.data.frame(lstrends(model[[2]], "Tissue", var="GeneX"))

    ## lapply for lstrends doesn't work for me
    m.lst = lapply(model, function(x) {
       as.data.frame(lstrends(model, "Tissue", var="GeneX"))})
</code>```

答:
small typo:

```<code>m.lst = lapply(model, function(x) {
  as.data.frame(lstrends(x, "Tissue", var="GeneX"))})
</code>```

credit to reddit user suspicious_gardener

Body:
Can somebody help!

I am trying to use lapply to loop lstrends() across a large list, yet I received the error and can't think of a fix

Error :

"Error in data[[var]] : subscript out of bounds"

Code :

    ## Test data
  Tissue=c("Normal","Normal","Normal","Normal","Tumor","Tumor","Tumor","Tumor")
    GeneY = c(34,12,11,8,53,32,39,80)
    GeneZ = c(4,7,3,9,44,32,56,77)
    GeneX = c(42,54,59,22,35,12,22,40)
    dvList <- c("GeneY", "GeneZ")
    breast = data.frame(Tissue, GeneX,GeneY,GeneZ)

    ## linear regression lapply works fine
    model = lapply(dvList, function(x) {
        lm(substitute(i~GeneX*Tissue, list(i = as.name(x))), data = breast)})
    library(lsmeans)

    ## selecting individual components of the list works fine
    m.lst = as.data.frame(lstrends(model[[2]], "Tissue", var="GeneX"))

    ## lapply for lstrends doesn't work for me
    m.lst = lapply(model, function(x) {
       as.data.frame(lstrends(model, "Tissue", var="GeneX"))})

Body:
small typo:

m.lst = lapply(model, function(x) {
  as.data.frame(lstrends(x, "Tissue", var="GeneX"))})

credit to reddit user suspicious_gardener