问:
Any way to add lines to JList?
I am making a program that will allow the user to enter a name, which will then be added and displayed to a list in the jframe window, but cannot figure out how to add to the lsit using code.

I have tried several things, like:

```<code>lstNames.append(name);
lstNames.Add(name);
lstNames.add(name, this);
</code>```

(name is a string)

Currently my code looks like this:

```<code>DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
ArrayList<String> names;

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {

    String name = txtFirst.getText() + " " + txtLast.getText(); // works
    names.add(name); // works

    for (int i = 0; i < names.size(); i++) {
        model.add(i, names.get(i));
    }
    lstNames.setModel(model);

}
</code>```

I just want to add a name to a list, but all I get is errors, any help would be great.

Here are my errors:

```<code>Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javaapplication2.NewJFrame.btnAddActionPerformed(NewJFrame.java:99)
    at javaapplication2.NewJFrame.access$000(NewJFrame.java:12)
    at javaapplication2.NewJFrame$2.actionPerformed(NewJFrame.java:45)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
</code>```

No errors appear until, the button to run the code is pressed. Very basically, I want to add the user input to the jlist

答:
You're not initializing your list.

ArrayList<String> names;
```

<p>should be something like</p>

```ArrayList<String> names = new ArrayList<>();
```

Title: Any way to add lines to JList?

Body:
I am making a program that will allow the user to enter a name, which will then be added and displayed to a list in the jframe window, but cannot figure out how to add to the lsit using code.

I have tried several things, like:

lstNames.append(name);
lstNames.Add(name);
lstNames.add(name, this);

(name is a string)

Currently my code looks like this:

DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
ArrayList<String> names;

private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {

    String name = txtFirst.getText() + " " + txtLast.getText(); // works
    names.add(name); // works

    for (int i = 0; i < names.size(); i++) {
        model.add(i, names.get(i));
    }
    lstNames.setModel(model);

}

I just want to add a name to a list, but all I get is errors, any help would be great.

Here are my errors:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javaapplication2.NewJFrame.btnAddActionPerformed(NewJFrame.java:99)
    at javaapplication2.NewJFrame.access$000(NewJFrame.java:12)
    at javaapplication2.NewJFrame$2.actionPerformed(NewJFrame.java:45)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6298)
    at java.awt.Container.processEvent(Container.java:2236)
    at java.awt.Component.dispatchEventImpl(Component.java:4889)
    at java.awt.Container.dispatchEventImpl(Container.java:2294)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)
    at java.awt.Window.dispatchEventImpl(Window.java:2746)
    at java.awt.Component.dispatchEvent(Component.java:4711)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:731)
    at java.awt.EventQueue$4.run(EventQueue.java:729)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

No errors appear until, the button to run the code is pressed. Very basically, I want to add the user input to the jlist

Body:
You're not initializing your list.

ArrayList<String> names;

should be something like

ArrayList<String> names = new ArrayList<>();


来源: stackexchange

问:
Make: How to escape spaces in $(addprefix)?
Here's what I am trying to do:

```<code>EXTRA_INCLUDE_PATHS = ../dir1/path with spaces/ \
                      ../dir2/other path with spaces/
CPPFLAGS += $(addprefix -I,$(EXTRA_INCLUDE_PATHS))
</code>```

I want to get “-I../dir1/path with spaces/ […]”, but I get instead: “-I../dir/path -Iwith -Ispaces/ […]”.

How do I espace spaces in addprefix? I've tried doing this trick, but it produces same result:

```<code>space  =
space +=
#produces “-Isome -Ipath”
CPPFLAGS += $(addprefix -I,some$(space)path)
</code>```

答:
If all your include dirs start with the same character sequence, you can exploit this for use with the substitute command:

```<code>CPPFLAGS += $(subst  ..,-I ..,$(EXTRA_INCLUDE_PATHS))
</code>```

Check the result with:

```<code>$(info  ${CPPFLAGS})
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here's what I am trying to do:

EXTRA_INCLUDE_PATHS = ../dir1/path with spaces/ \
                      ../dir2/other path with spaces/
CPPFLAGS += $(addprefix -I,$(EXTRA_INCLUDE_PATHS))

I want to get “-I../dir1/path with spaces/ […]”, but I get instead: “-I../dir/path -Iwith -Ispaces/ […]”.

How do I espace spaces in addprefix? I've tried doing this trick, but it produces same result:

space  =
space +=
#produces “-Isome -Ipath”
CPPFLAGS += $(addprefix -I,some$(space)path)

Body:
If all your include dirs start with the same character sequence, you can exploit this for use with the substitute command:

CPPFLAGS += $(subst  ..,-I ..,$(EXTRA_INCLUDE_PATHS))

Check the result with:

$(info  ${CPPFLAGS})

ContentLicense: CC BY-SA 4.0


问:
Dockerfile COPY command puts an empty file in its container when overwriting another file
When copying files from host machine to container where a file already exists at the destination path, the copied file is empty.

I've attempted to copy the same files to a path with a different name and this works fine.

The two lines from my dockerfile that this issue happens on are:

```<code>COPY conf/policy.xml /etc/ImageMagick-6/

COPY conf/000-default.conf /etc/apache2/sites-available/
</code>```

Full dockerfile:

```<code>FROM php:7.3-apache
RUN docker-php-ext-install pdo_mysql && docker-php-ext-enable pdo_mysql
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli

RUN apt-get update && apt-get install -y \
  git libmagick++-dev \
  --no-install-recommends && \
  git clone https://github.com/mkoppanen/imagick.git && \
  cd imagick && git checkout master && phpize && ./configure && \
  make && make install && \
  docker-php-ext-enable imagick && \
  cd ../ && rm -rf imagick && \
  apt-get install -y ghostscript && rm -r /var/lib/apt/lists/*

RUN pecl install xdebug
RUN docker-php-ext-enable xdebug

COPY conf/php.ini /etc/php/7.3/fpm/conf.d/40-custom.ini
COPY conf/policy.xml /etc/ImageMagick-6/
COPY www/ /var/www/html/

COPY conf/000-default.conf /etc/apache2/sites-available/
COPY scripts/generate-ssl.sh /generate-ssl.sh

RUN chmod +x /generate-ssl.sh
RUN /bin/bash /generate-ssl.sh

EXPOSE 80 443
</code>```

Is this intended behavior ?

答:
From Docker Documentation - Docerfile Copy:

COPY src dest: If src is any kind of file, it is copied individually along with its metadata. In this case, if  ends with a trailing slash /, it will be considered a directory and the contents of  will be written at /base().

For your case try and specifiy the dest file:

```<code>COPY conf/policy.xml /etc/ImageMagick-6/policy.xml

COPY conf/000-default.conf /etc/apache2/sites-available/000-default.conf
</code>```

Otherwise i dont see anything wrong with your dockerfile

Body:
When copying files from host machine to container where a file already exists at the destination path, the copied file is empty.

I've attempted to copy the same files to a path with a different name and this works fine.

The two lines from my dockerfile that this issue happens on are:

COPY conf/policy.xml /etc/ImageMagick-6/

COPY conf/000-default.conf /etc/apache2/sites-available/

Full dockerfile:

FROM php:7.3-apache
RUN docker-php-ext-install pdo_mysql && docker-php-ext-enable pdo_mysql
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli

RUN apt-get update && apt-get install -y \
  git libmagick++-dev \
  --no-install-recommends && \
  git clone https://github.com/mkoppanen/imagick.git && \
  cd imagick && git checkout master && phpize && ./configure && \
  make && make install && \
  docker-php-ext-enable imagick && \
  cd ../ && rm -rf imagick && \
  apt-get install -y ghostscript && rm -r /var/lib/apt/lists/*

RUN pecl install xdebug
RUN docker-php-ext-enable xdebug

COPY conf/php.ini /etc/php/7.3/fpm/conf.d/40-custom.ini
COPY conf/policy.xml /etc/ImageMagick-6/
COPY www/ /var/www/html/

COPY conf/000-default.conf /etc/apache2/sites-available/
COPY scripts/generate-ssl.sh /generate-ssl.sh

RUN chmod +x /generate-ssl.sh
RUN /bin/bash /generate-ssl.sh

EXPOSE 80 443

Is this intended behavior ?

Body:
From Docker Documentation - Docerfile Copy:

COPY src dest: If src is any kind of file, it is copied individually along with its metadata. In this case, if  ends with a trailing slash /, it will be considered a directory and the contents of  will be written at /base().

For your case try and specifiy the dest file:

COPY conf/policy.xml /etc/ImageMagick-6/policy.xml

COPY conf/000-default.conf /etc/apache2/sites-available/000-default.conf

Otherwise i dont see anything wrong with your dockerfile


问:
browser automatically generate a launcher icon on home screen for web apps android
Is it possible to automatically generate a bookmark within the Android home screen using Javascript or a meta tag?</p>

答: This is really only possible if you write native code along with your mobile site. If you do, then you can write a webview inside of your native code that will allow your javascript to invoke your native code and add the shortcut by intent.</p>


Title: How to convert a character array to data frame

Body:
I have a character array dat which I want to convert to a data frame df but it is not working

 head(dat)
[1] "   1931   1    5.0     0.6      11    78.4    43.4"
[2] "   1931   2    6.7     0.7       7    48.9    63.6"
[3] "   1931   4   10.4     3.1       3    44.6   110.1"
[4] "   1931   5   13.2     6.1       1    63.7   167.4"
[5] "   1931   6   15.4     8.0       0    87.8   150.3"
[6] "   1931   7   17.3    10.6       0   121.4   111.2"

> df<-as.data.frame(dat)
> head(df)
                                                 dat
1    1931   1    5.0     0.6      11    78.4    43.4
2    1931   2    6.7     0.7       7    48.9    63.6
3    1931   4   10.4     3.1       3    44.6   110.1
4    1931   5   13.2     6.1       1    63.7   167.4
5    1931   6   15.4     8.0       0    87.8   150.3
6    1931   7   17.3    10.6       0   121.4   111.2

df[,c(3)]

Error in [.data.frame(df, , c(3)) : undefined columns selected

Body:
Reading with read.table: You can rename as desired.

df<-read.table(text = "                                                dat
1    1931   1    5.0     0.6      11    78.4    43.4
2    1931   2    6.7     0.7       7    48.9    63.6
3    1931   4   10.4     3.1       3    44.6   110.1
4    1931   5   13.2     6.1       1    63.7   167.4
5    1931   6   15.4     8.0       0    87.8   150.3
6    1931   7   17.3    10.6       0   121.4   111.2",
               header=F,fill=T,as.is=T,skip = 1)
df[3]
 V3
1  1
2  2
3  4
4  5
5  6
6  7


问:
How to count time between occurrences (and duration of occurrence)
I am dealing with the following challenge and would greatly appreciate any help.

Consider I have a data table with the following information.

```<code>Store   Day           In stock ?  Out of stock ?
Store A 01 - 01 - 19  1           0
Store A 02 - 01 - 19  0           1
Store A 03 - 01 - 19  0           1
Store A 04 - 01 - 19  1           0
Store A 05 - 01 - 19  1           0
Store A 06 - 01 - 19  0           1
Store A 07 - 01 - 19  0           1
Store A       …       0           1
Store B 01 - 01 - 19  1           0
Store B 02 - 01 - 19  0           1
Store B       …       0           1
</code>```

For each store, I want to count the number of days for which is has consecutively been in or out of stock. These two columns are binary, and mutually exclusive. So for store A, the result would be:

```<code>Store     Duration in stock   Duration out of stock
Store A   1
Store A                       2
Store A   2
Store A                       3
</code>```

I need to do this for a large dataset (hourly values for hundreds of stores), and thus would like to automate this. Furthermore, I want to do further analysis on the 'in stock duration' and 'out of stock duration', such as average values, extremes, percentiles etc. Therefore, the data needs to be organized in such a way that this would be possible.

I have not found a solution to this problem yet. Any insight would be nice!

Below comma seperated values:

```<code>Store;Day;In stock?;Out of stock?
Store A;01-01-19;1;0
Store A;02-01-19;0;1
Store A;03-01-19;0;1
Store A;04-01-19;1;0
Store A;05-01-19;1;0
Store A;06-01-19;0;1
Store A;07-01-19;0;1
Store A;…;0;1
Store B;01-01-19;1;0
Store B;02-01-19;0;1
Store B;…;0;1
</code>```

答:
Here's an approach with dplyr. First, I convert the date column into a date using lubridate, assuming that it's in day-month-year (hence dmy) order.

Then, for each store, count which "stock period" we're in, where it's a new one each time it switches between in and out of stock.

Using that and the store, I sum the numbers in each column.

```<code>library(dplyr)
df %>%
  mutate(Day = lubridate::dmy(Day)) %>%
  group_by(Store) %>%
  mutate(stock_period = cumsum(In_stock != lag(In_stock, default = ""))) %>%
  group_by(Store, stock_period) %>%
  summarise(start = min(Day),
            end   = max(Day),
            In_stock = sum(In_stock),
            Out_of_stock = sum(Out_of_stock))

# A tibble: 6 x 6
# Groups:   Store [2]
  Store   stock_period start      end        In_stock Out_of_stock
  <chr>          <int> <date>     <date>        <int>        <int>
1 Store A            1 2019-01-01 2019-01-01        1            0
2 Store A            2 2019-01-02 2019-01-03        0            2
3 Store A            3 2019-01-04 2019-01-05        2            0
4 Store A            4 2019-01-06 2019-01-07        0            2
5 Store B            1 2019-01-01 2019-01-01        1            0
6 Store B            2 2019-01-02 2019-01-02        0            1
</code>```

Using this source data:

```<code>df <- read.table(header = T, stringsAsFactors = F,
  text = "Store Day In_stock Out_of_stock
'Store A' 01-01-19 1 0
'Store A' 02-01-19 0 1
'Store A' 03-01-19 0 1
'Store A' 04-01-19 1 0
'Store A' 05-01-19 1 0
'Store A' 06-01-19 0 1
'Store A' 07-01-19 0 1
'Store B' 01-01-19 1 0
'Store B' 02-01-19 0 1")
</code>```

Body:
I am dealing with the following challenge and would greatly appreciate any help.

Consider I have a data table with the following information.

Store   Day           In stock ?  Out of stock ?
Store A 01 - 01 - 19  1           0
Store A 02 - 01 - 19  0           1
Store A 03 - 01 - 19  0           1
Store A 04 - 01 - 19  1           0
Store A 05 - 01 - 19  1           0
Store A 06 - 01 - 19  0           1
Store A 07 - 01 - 19  0           1
Store A       …       0           1
Store B 01 - 01 - 19  1           0
Store B 02 - 01 - 19  0           1
Store B       …       0           1

For each store, I want to count the number of days for which is has consecutively been in or out of stock. These two columns are binary, and mutually exclusive. So for store A, the result would be:

Store     Duration in stock   Duration out of stock
Store A   1
Store A                       2
Store A   2
Store A                       3

I need to do this for a large dataset (hourly values for hundreds of stores), and thus would like to automate this. Furthermore, I want to do further analysis on the 'in stock duration' and 'out of stock duration', such as average values, extremes, percentiles etc. Therefore, the data needs to be organized in such a way that this would be possible.

I have not found a solution to this problem yet. Any insight would be nice!

Below comma seperated values:

Store;Day;In stock?;Out of stock?
Store A;01-01-19;1;0
Store A;02-01-19;0;1
Store A;03-01-19;0;1
Store A;04-01-19;1;0
Store A;05-01-19;1;0
Store A;06-01-19;0;1
Store A;07-01-19;0;1
Store A;…;0;1
Store B;01-01-19;1;0
Store B;02-01-19;0;1
Store B;…;0;1

Body:
Here's an approach with dplyr. First, I convert the date column into a date using lubridate, assuming that it's in day-month-year (hence dmy) order.

Then, for each store, count which "stock period" we're in, where it's a new one each time it switches between in and out of stock.

Using that and the store, I sum the numbers in each column.

library(dplyr)
df %>%
  mutate(Day = lubridate::dmy(Day)) %>%
  group_by(Store) %>%
  mutate(stock_period = cumsum(In_stock != lag(In_stock, default = ""))) %>%
  group_by(Store, stock_period) %>%
  summarise(start = min(Day),
            end   = max(Day),
            In_stock = sum(In_stock),
            Out_of_stock = sum(Out_of_stock))

# A tibble: 6 x 6
# Groups:   Store [2]
  Store   stock_period start      end        In_stock Out_of_stock
  <chr>          <int> <date>     <date>        <int>        <int>
1 Store A            1 2019-01-01 2019-01-01        1            0
2 Store A            2 2019-01-02 2019-01-03        0            2
3 Store A            3 2019-01-04 2019-01-05        2            0
4 Store A            4 2019-01-06 2019-01-07        0            2
5 Store B            1 2019-01-01 2019-01-01        1            0
6 Store B            2 2019-01-02 2019-01-02        0            1

Using this source data:

df <- read.table(header = T, stringsAsFactors = F,
  text = "Store Day In_stock Out_of_stock
'Store A' 01-01-19 1 0
'Store A' 02-01-19 0 1
'Store A' 03-01-19 0 1
'Store A' 04-01-19 1 0
'Store A' 05-01-19 1 0
'Store A' 06-01-19 0 1
'Store A' 07-01-19 0 1
'Store B' 01-01-19 1 0
'Store B' 02-01-19 0 1")


问:
Measuring temperature while benchmarking on Linux
I want to measure the temperature and frequency of a two socket machine while performing the High-Performance Linpack benchmark.

I wrote a shell script sensor.sh that I start in the background with sh sensors.sh &  and then proceed to the benchmark.

```<code>for ((;;))
do
awk 'BEGIN{ORS=" ";} $2=="MHz" {print $4} END {print "\n"}' /proc/cpuinfo >> cpuf.dat

awk 'BEGIN{ORS=" ";} {print $1} END {print "\n"}' /sys/devices/platform/coretemp.?/hwmon/hwmon?/temp*_input >> cput.dat
 sleep .1
done
</code>```

I get my outputfiles, however the timestamps are not 0.1s apart from each other. I guess the system is busy and the shell script process is not executed that often. HPL says it has a runtime of ~1100s, in this time my temperature.dat file generated ~4600 entries.

Is there another way I can measure the temperature and frequency while performing my benchmark program and store the output in a .dat file?

答:
You could try running your code with high priority, so it will be less impacted by the load of the benchmark. But you need to run as root to be able to use negative niceness.</p>

```<code>nice -n -10 bash
for ((;;))
do
 sensors | grep Core | awk '{print $3}' | tr '+' ' '  | tr '°C' ' ' | xargs >> temperature.dat
 cat /proc/cpuinfo | grep "cpu MHz" | tr "cpu MHz : " " " | xargs >> frequency.dat
 sleep .1
done
exit
</code>```

Body:
I want to measure the temperature and frequency of a two socket machine while performing the High-Performance Linpack benchmark.

I wrote a shell script sensor.sh that I start in the background with sh sensors.sh &  and then proceed to the benchmark.

for ((;;))
do
awk 'BEGIN{ORS=" ";} $2=="MHz" {print $4} END {print "\n"}' /proc/cpuinfo >> cpuf.dat

awk 'BEGIN{ORS=" ";} {print $1} END {print "\n"}' /sys/devices/platform/coretemp.?/hwmon/hwmon?/temp*_input >> cput.dat
 sleep .1
done

I get my outputfiles, however the timestamps are not 0.1s apart from each other. I guess the system is busy and the shell script process is not executed that often. HPL says it has a runtime of ~1100s, in this time my temperature.dat file generated ~4600 entries.

Is there another way I can measure the temperature and frequency while performing my benchmark program and store the output in a .dat file?

Body:
You could try running your code with high priority, so it will be less impacted by the load of the benchmark. But you need to run as root to be able to use negative niceness.

nice -n -10 bash
for ((;;))
do
 sensors | grep Core | awk '{print $3}' | tr '+' ' '  | tr '°C' ' ' | xargs >> temperature.dat
 cat /proc/cpuinfo | grep "cpu MHz" | tr "cpu MHz : " " " | xargs >> frequency.dat
 sleep .1
done
exit


问:
How to select letters from a string until predefined point?
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

```<code>vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end
</code>```

答:
Notice your function and array have the same name, vowels. That's causing confusion--you may think you're calling include? on the global vowels array, but actually, your code attempts to call your identically-named function recursively without parameters, hence the error. Since Ruby permits function calls without parentheses, Ruby treats this line:

```<code>vowels.include?(letter)
</code>```

as

```<code>vowels().include?(letter) # <- wrong number of arguments!
</code>```

Changing your function name to something other than "vowels" causes this error, which makes more sense:

undefined local variable or method `vowels' for main:Object
(repl):7:in `block in function_formerly_known_as_vowels'
(repl):6:in `each'
(repl):6:in `function_formerly_known_as_vowels'
(repl):12:in `'
```
<p>This leads to the underlying cause: breaking encapsulation. The <code>vowels</code> function attempts to access state in the global scope. This is poor practice (and won't work in this code since the <code>vowels</code> array isn't actually global--it'd need a <code>$</code> prefix on the variable name or another way of making it visible inside the function scope--see this answer for details). Instead, pass the array of vowels into the function as a parameter (and probably generalize the function in the process), or hardcode it inside the function itself since we can assume vowels won't change.</p>
<p>Having resolved the scope issue, the next problem is that <code>until</code> is a loop. As soon as <code>letter</code> is a consonant, it'll be pushed repeatedly onto the <code>consonants</code> array until the program runs out of memory. You probably meant <code>unless</code>. Even here, you'll need to <code>break</code> or <code>return</code> to exit the loop upon finding a vowel.</p>
<p>Lastly, a couple semantic suggestions: <code>vowels</code> is not a very accurate function name. It returns consonants up to the first vowel, so title it as such! The parameter "words" is potentially misleading because it suggests an array or a series of words, when your function appears to operate on just one word (or string, generically).</p>
<p>Here's a re-write:</p>
```def front_consonants(word)
  vowels = "aeiou"
  consonants = []

  word.each_char do |letter|
    break if vowels.include? letter
    consonants << letter
  end

  consonants.join
end

p front_consonants "stack" # => "st"
```

Body:
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end

Body:
Notice your function and array have the same name, vowels. That's causing confusion--you may think you're calling include? on the global vowels array, but actually, your code attempts to call your identically-named function recursively without parameters, hence the error. Since Ruby permits function calls without parentheses, Ruby treats this line:

vowels.include?(letter)

as

vowels().include?(letter) # <- wrong number of arguments!

Changing your function name to something other than "vowels" causes this error, which makes more sense:

undefined local variable or method `vowels' for main:Object
(repl):7:in `block in function_formerly_known_as_vowels'
(repl):6:in `each'
(repl):6:in `function_formerly_known_as_vowels'
(repl):12:in `<main>'

This leads to the underlying cause: breaking encapsulation. The vowels function attempts to access state in the global scope. This is poor practice (and won't work in this code since the vowels array isn't actually global--it'd need a $ prefix on the variable name or another way of making it visible inside the function scope--see this answer for details). Instead, pass the array of vowels into the function as a parameter (and probably generalize the function in the process), or hardcode it inside the function itself since we can assume vowels won't change.

Having resolved the scope issue, the next problem is that until is a loop. As soon as letter is a consonant, it'll be pushed repeatedly onto the consonants array until the program runs out of memory. You probably meant unless. Even here, you'll need to break or return to exit the loop upon finding a vowel.

Lastly, a couple semantic suggestions: vowels is not a very accurate function name. It returns consonants up to the first vowel, so title it as such! The parameter "words" is potentially misleading because it suggests an array or a series of words, when your function appears to operate on just one word (or string, generically).

Here's a re-write:

def front_consonants(word)
  vowels = "aeiou"
  consonants = []

  word.each_char do |letter|
    break if vowels.include? letter
    consonants << letter
  end

  consonants.join
end

p front_consonants "stack" # => "st"


问:
how can we print the output of a code in gui , not in console?
i have a written piece of code of around 100 lines which is printing some output of around 20 lines. How can I print this output in GUI ??</p>

答:
I am a Python 3.x guy, but when it comes to tkinter, you can set labels with variables instead of using print(). So to get it on the GUI, you want to set labels with variables. This would look something like this:

```<code>from tkinter import *
window = Tk()
variable = StringVar()
variable.set(data_to_console) #You can use a variable with a string here or any string
label = Label(window, textvariable=variable)
label.grid(row=x, column=y)
</code>```

So you take the strings that would be output into the console and use .set() to put it into a String Variable that tkinter can use. The Labels will allow for the data that would be printed to be in the GUI. Hope this helps!

Body:
I am a Python 3.x guy, but when it comes to tkinter, you can set labels with variables instead of using print(). So to get it on the GUI, you want to set labels with variables. This would look something like this:

from tkinter import *
window = Tk()
variable = StringVar()
variable.set(data_to_console) #You can use a variable with a string here or any string
label = Label(window, textvariable=variable)
label.grid(row=x, column=y)

So you take the strings that would be output into the console and use .set() to put it into a String Variable that tkinter can use. The Labels will allow for the data that would be printed to be in the GUI. Hope this helps!


问:
Tool for helping with deduplication of Perl code?
I'm looking for some tool/library that would scan given project tree, and report on code duplicates - i.e. blocks of code that are repeated in various files.

Is there anything like this?

As it is now, I have to view them (files) all, and search for duplicates, but it doesn't strike me as very efficient.

答:
A System for Detecting Software Plagiarism might work; it supports Perl.

And here's a list.


问:
Material Instance Created in Car Model Prefab
I don't know why my car 3d model's mesh renderer creating own instances of all materials when I spawn it using prefab.
Please check below image for the same:

My environment models not creating own instances of materials but all cars models doing when I initialize via prefab.
I hope you are getting my point.

Here I am attaching an image for car model import settings:

So I want to stop these new materials instance creation process

After spawning of car model, it has own material instance created at runtime so I want to solve this problem.

I have created another demo project in that this kind of situation not get created. There is no new instance of material gets created within mesh renderer.

答:
At last, I can able to manage the problem myself.

As I understand and learn, if you change the material's any property say as per my case a Color then it will create a new instance of it because you changed something runtime compares to its core version.

In my case, I want to change a car chassis color runtime based on game player selection.
So that new instances of material get created runtime and I lost in access of chassis material to change color.

I require to runtime fetch the material of chassis to change its color.
Here is the code that I used:

```<code>GetCarChassisMaterial().color = DataCollection.CAR_COLOR_OPTIONS[colorIndex];

Material GetCarChassisMaterial()
{
    Material[] carSharedMats = carChassisMeshRenderers[currentCarIndex].sharedMaterials;
    for (int i = 0; i < carSharedMats.Length; i++)
    {
        if (RemoveInstanceFromName(carSharedMats[i].name).Equals(carsChasisMat[currentCarIndex].name))
            return carSharedMats[i];
    }

    return carsChasisMat[currentCarIndex];
}

// remove "(Instance)" word from runtime created material name
private string RemoveInstanceFromName(string name)
{
    return name.Split(new char[] { ' ' })[0];
}
</code>```

Body:
At last, I can able to manage the problem myself.

As I understand and learn, if you change the material's any property say as per my case a Color then it will create a new instance of it because you changed something runtime compares to its core version.

In my case, I want to change a car chassis color runtime based on game player selection.
So that new instances of material get created runtime and I lost in access of chassis material to change color.

I require to runtime fetch the material of chassis to change its color.
Here is the code that I used:

GetCarChassisMaterial().color = DataCollection.CAR_COLOR_OPTIONS[colorIndex];

Material GetCarChassisMaterial()
{
    Material[] carSharedMats = carChassisMeshRenderers[currentCarIndex].sharedMaterials;
    for (int i = 0; i < carSharedMats.Length; i++)
    {
        if (RemoveInstanceFromName(carSharedMats[i].name).Equals(carsChasisMat[currentCarIndex].name))
            return carSharedMats[i];
    }

    return carsChasisMat[currentCarIndex];
}

// remove "(Instance)" word from runtime created material name
private string RemoveInstanceFromName(string name)
{
    return name.Split(new char[] { ' ' })[0];
}


问:
What method should I use in Yii 1.1 to sum in MySQL?
What method mysql use in Yii 1.1 when adding?
Here is the code I use but the sum method does not work:

```<code>$query = Yii::app()->db->createCommand()->from('users_payouts');
sum = $query->sum('sum');
</code>```

In the browser, it gives an error:

In the CDbCommand class and its behaviors, no method or closure named "sum" was found.

答:
There is no shortcut for sum, you should define correct select:

```<code>$sum = Yii::app()->db->createCommand()
    ->select('SUM(some_column)')
    ->from('users_payouts')
    ->queryScalar();
</code>```

Body:
What method mysql use in Yii 1.1 when adding?
Here is the code I use but the sum method does not work:

$query = Yii::app()->db->createCommand()->from('users_payouts');
sum = $query->sum('sum');

In the browser, it gives an error:

In the CDbCommand class and its behaviors, no method or closure named "sum" was found.

Body:
There is no shortcut for sum, you should define correct select:

$sum = Yii::app()->db->createCommand()
    ->select('SUM(some_column)')
    ->from('users_payouts')
    ->queryScalar();


问:
how to call rest api inside aws lambda function using nodejs
i have created aws lambda function. i want to use rest api calls inside my lambda function.
Is there any reference how to connect it to rest api using nodejs</p>

答:
```<code>const superagent = require('superagent');

exports.handler =  async(event) => {
    return await startPoint();  // use promise function for api
}

function startPoint(){
    return new Promise(function(resolve,reject){
    superagent
    .get(apiEndPoint)
    .end((err, res) => {
        ...

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


问:
How to analyze the growth of the following code?
I already know that the worst case complexity is N, and the best case is Mlog(M) but I just don't see how. Can anybody explain to me why this is the case and what different inputs would cause each case?

```<code>public static Iterable<Integer> topM(int[] a, int M){
int N = a.length;
MinPQ<Integer> pq = new MinPQ<Integer>(M+1);
for(int i = 0; i < N; i++){
    if(pq.size() < M)
        pq.insert(a[i]);
    if(pq.min() <= a[i]){
        pq.insert(a[i]);
        pq.delMin();
    }
}
return pq;
</code>```

}

答:
The complexity is O(Nlog(M)). The worst case is when the array is sorted in a ascending order, in this case each element is inserted to the queue.
The best case is when the array is sorted in a descending order, in this case only the first M elements are inserted. The complexity in the best case is O(N+Mlog(M)).
p.s. the first comment is correct, the second if should be else if.

Body:
I already know that the worst case complexity is N, and the best case is Mlog(M) but I just don't see how. Can anybody explain to me why this is the case and what different inputs would cause each case?

public static Iterable<Integer> topM(int[] a, int M){
int N = a.length;
MinPQ<Integer> pq = new MinPQ<Integer>(M+1);
for(int i = 0; i < N; i++){
    if(pq.size() < M)
        pq.insert(a[i]);
    if(pq.min() <= a[i]){
        pq.insert(a[i]);
        pq.delMin();
    }
}
return pq;

}


问:
Write to file cut off
My goal is to take a file of sentences, apply some basic filtering, and output the remaining sentences to a file and the terminal. I'm using the Hunspell library.

Here's how I get sentences from the file:

```<code>    public static string[] sentencesFromFile_old(string path)
    {
        string s = "";
        using (StreamReader rdr = File.OpenText(path))
        {
            s = rdr.ReadToEnd();
        }
        s = s.Replace(Environment.NewLine, " ");
        s = Regex.Replace(s, @"\s+", " ");
        s = Regex.Replace(s, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty);
        string[] sentences = Regex.Split(s, @"(?<=\. |[!?]+ )");
        return sentences;
    }
</code>```

Here's the code that writes to file:

```<code>        List<string> sentences = new List<string>(Checker.sentencesFromFile_old(path));
        StreamWriter w = new StreamWriter(outFile);
        foreach(string x in xs)
            if(Checker.check(x, speller))
            {
                w.WriteLine("[{0}]", x);
                Console.WriteLine("[{0}]", x);
            }
</code>```

Here's the checker:

```<code>    public static bool check(string s, NHunspell.Hunspell speller)
    {
        char[] punctuation = {',', ':', ';', ' ', '.'};
        bool upper = false;
        // Check the string length.
        if(s.Length <= 50 || s.Length > 250)
            return false;
        // Check if the string contains only allowed punctuation and letters.
        // Also disallow words with multiple consecutive caps.
        for(int i = 0; i < s.Length; ++i)
        {
            if(punctuation.Contains(s[i]))
                continue;
            if(Char.IsUpper(s[i]))
            {
                if(upper)
                    return false;
                upper = true;
            }
            else if(Char.IsLower(s[i]))
            {
                upper = false;
            }
            else return false;
        }
        // Spellcheck each word.
        string[] words = s.Split(' ');
        foreach(string word in words)
            if(!speller.Spell(word))
                return false;
        return true;
    }
</code>```

The sentences are printed on the terminal just fine, but the text file cuts off mid-sentence at 2015 characters. What's up with that?

EDIT: When I remove some parts of the check method, the file is cut off at various lengths somewhere around either 2000 or 4000. Removing the spellcheck eliminates the cutoff entirely.

答:
Are you closing the StreamWriter after you are done writing?  You could try something like this:

```<code>using(StreamWriter w = new StreamWriter(outFile))
{
    foreach(string x in xs)
    {
        if(Checker.check(x, speller))
        {
            w.WriteLine("[{0}]", x);
            Console.WriteLine("[{0}]", x);
        }
    }
}
</code>```

The using statement will close the StreamWriter (by calling the Dispose method on the StreamWriter) after the code inside is done executing.

Title: Write to file cut off

Body:
My goal is to take a file of sentences, apply some basic filtering, and output the remaining sentences to a file and the terminal. I'm using the Hunspell library.

Here's how I get sentences from the file:

    public static string[] sentencesFromFile_old(string path)
    {
        string s = "";
        using (StreamReader rdr = File.OpenText(path))
        {
            s = rdr.ReadToEnd();
        }
        s = s.Replace(Environment.NewLine, " ");
        s = Regex.Replace(s, @"\s+", " ");
        s = Regex.Replace(s, @"\s*?(?:\(.*?\)|\[.*?\]|\{.*?\})", String.Empty);
        string[] sentences = Regex.Split(s, @"(?<=\. |[!?]+ )");
        return sentences;
    }

Here's the code that writes to file:

        List<string> sentences = new List<string>(Checker.sentencesFromFile_old(path));
        StreamWriter w = new StreamWriter(outFile);
        foreach(string x in xs)
            if(Checker.check(x, speller))
            {
                w.WriteLine("[{0}]", x);
                Console.WriteLine("[{0}]", x);
            }

Here's the checker:

    public static bool check(string s, NHunspell.Hunspell speller)
    {
        char[] punctuation = {',', ':', ';', ' ', '.'};
        bool upper = false;
        // Check the string length.
        if(s.Length <= 50 || s.Length > 250)
            return false;
        // Check if the string contains only allowed punctuation and letters.
        // Also disallow words with multiple consecutive caps.
        for(int i = 0; i < s.Length; ++i)
        {
            if(punctuation.Contains(s[i]))
                continue;
            if(Char.IsUpper(s[i]))
            {
                if(upper)
                    return false;
                upper = true;
            }
            else if(Char.IsLower(s[i]))
            {
                upper = false;
            }
            else return false;
        }
        // Spellcheck each word.
        string[] words = s.Split(' ');
        foreach(string word in words)
            if(!speller.Spell(word))
                return false;
        return true;
    }

The sentences are printed on the terminal just fine, but the text file cuts off mid-sentence at 2015 characters. What's up with that?

EDIT: When I remove some parts of the check method, the file is cut off at various lengths somewhere around either 2000 or 4000. Removing the spellcheck eliminates the cutoff entirely.

Body:
Are you closing the StreamWriter after you are done writing?  You could try something like this:

using(StreamWriter w = new StreamWriter(outFile))
{
    foreach(string x in xs)
    {
        if(Checker.check(x, speller))
        {
            w.WriteLine("[{0}]", x);
            Console.WriteLine("[{0}]", x);
        }
    }
}

The using statement will close the StreamWriter (by calling the Dispose method on the StreamWriter) after the code inside is done executing.


问:
Why does dplyr filter_all using all_vars > 0 work on a character string?
Given:

```<code>df <- structure(list(word = c("aaliyahmaxwell", "abasc", "abbslovesfed",
"abbycastro", "abc", "abccarpet", "abdul", "ability", "abnormile",
"abraham"), chardonnay = c(4, 0, 0, 0, 0, 0, 0, 0, 0, 0), coffee = c(0,
1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("word", "chardonnay",
"coffee"), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

Why does df %>% filter_all(all_vars(. > 0)) work?

I mean that my first column is of type character and can't be > 0.
I can understand why it works on the other two columns but need an explanation on why it works when I have a mixture of character and double type columns.

Please advise.

答:
Even though there is already a good answer, I think this can be made clearer with an example:

```<code>> c("a", 0)
[1] "a" "0"
</code>```

Here you can see what happens, the number gets coerced to a character.

Characters get compared lexically. Example:

```<code>> "b" > "a"
[1] TRUE

> "a" > "5"
[1] TRUE

> charvector <- sample(c(seq(1,9), LETTERS))
> charvector
 [1] "6" "D" "T" "U" "I" "R" "F" "S" "J" "W" "B" "A" "8" "E" "2" "7" "O" "Z" "V" "G" "9" "4" "H" "C" "Y" "1" "X" "5" "M" "K" "Q" "L" "N" "3" "P"
</code>```

The order becomes also clear when you sort that vector:

```<code>> sort(charvector)
 [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"
</code>```

Body:
Given:

df <- structure(list(word = c("aaliyahmaxwell", "abasc", "abbslovesfed",
"abbycastro", "abc", "abccarpet", "abdul", "ability", "abnormile",
"abraham"), chardonnay = c(4, 0, 0, 0, 0, 0, 0, 0, 0, 0), coffee = c(0,
1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("word", "chardonnay",
"coffee"), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))

Why does df %>% filter_all(all_vars(. > 0)) work?

I mean that my first column is of type character and can't be > 0.
I can understand why it works on the other two columns but need an explanation on why it works when I have a mixture of character and double type columns.

Please advise.

Body:
Even though there is already a good answer, I think this can be made clearer with an example:

> c("a", 0)
[1] "a" "0"

Here you can see what happens, the number gets coerced to a character.

Characters get compared lexically. Example:

> "b" > "a"
[1] TRUE

> "a" > "5"
[1] TRUE

> charvector <- sample(c(seq(1,9), LETTERS))
> charvector
 [1] "6" "D" "T" "U" "I" "R" "F" "S" "J" "W" "B" "A" "8" "E" "2" "7" "O" "Z" "V" "G" "9" "4" "H" "C" "Y" "1" "X" "5" "M" "K" "Q" "L" "N" "3" "P"

The order becomes also clear when you sort that vector:

> sort(charvector)
 [1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"


问:
Is there a way to refactor this code to make it more concise?
The code works fine and the app runs very smooth. But for the if statement, I feel that there is a way I could refactor it down to be more concise? The else clause is fine I think, I'm just not totally sure how to do it. I'd like it to be as concise as possible, but I can't find a different way to write it.
The difference between the 2 is the p element, it's a message that displays, then disappears once you create the first li. So in my if block, I have some of the same code as in the else clause. All the code in the if block is needed to run the app at the start. Thanks for any help!

```<code> if(guests.length < 1){
       return(

     <div className="App">
       <Header />
       <AddGuest
       guest={props.guest}
       addGuest={props.addGuest}
       updatePendingGuestValue={props.updatePendingGuestValue}
       pendingGuest={props.pendingGuest}
       />

       <p className='intro-message'>Invite some friends and family! Confirm your guests,
       change their names if needed, remove the guest or filter through your guest who
       have/have not confirmed. Get started above!</p>

       <PendingGuestLi
         pendingGuest={props.pendingGuest} />
     </div>
 )
  }else{
     return(
     <div className="App">
      <Header />
      <AddGuest
      guest={props.guest}
      addGuest={props.addGuest}
      updatePendingGuestValue={props.updatePendingGuestValue}
      pendingGuest={props.pendingGuest}
      />

     <div className='filter-checkbox-container'>
       <label className='filter-guests-label'>Hide all unconfirmed guest
         <input type='checkbox' className='filter-guests-checkbox'
         value={props.filterUnconfirmedGuest} onChange={props.toggleFilterUnconfirmedGuest} />
       </label>
     </div>

     <GuestList
       guest={props.guest}
       toggleGuestConfirmed={props.toggleGuestConfirmed}
       toggleEditGuest={props.toggleEditGuest}
       editGuest={props.editGuest}
       removeGuest={props.removeGuest}
       filterUnconfirmedGuest={props.filterUnconfirmedGuest}
        />
     <PendingGuestLi
       pendingGuest={props.pendingGuest} />
   </div>
     )
   }
</code>```

Thank you for checking it out!

答:
Separating what stays the same and what changes and placing it inside a block.</p>

```<code>
  return(
    <div className="App">
      <Header />
      <AddGuest
        guest={props.guest}
        addGuest={props.addGuest}
        updatePendingGuestValue={props.updatePendingGuestValue}
        pendingGuest={props.pendingGuest}
      />
      {(guests.length < 1) ?
          <p className='intro-message'>
            Invite some friends and family! Confirm your guests,
            change their names if needed, remove the guest or filter through your guest who
            have/have not confirmed. Get started above!
          </p>
        :
         <Fragment>
          <div className='filter-checkbox-container'>
            <label className='filter-guests-label'>Hide all unconfirmed guest
              <input type='checkbox' className='filter-guests-checkbox'
              value={props.filterUnconfirmedGuest} onChange={props.toggleFilterUnconfirmedGuest} />
            </label>
          </div>
          <GuestList
            guest={props.guest}
            toggleGuestConfirmed={props.toggleGuestConfirmed}
            toggleEditGuest={props.toggleEditGuest}
            editGuest={props.editGuest}
            removeGuest={props.removeGuest}
            filterUnconfirmedGuest={props.filterUnconfirmedGuest}
             />
          </Fragment>
      }
      <PendingGuestLi
        pendingGuest={props.pendingGuest} />
      </div>
  )
</code>```

Body:
The code works fine and the app runs very smooth. But for the if statement, I feel that there is a way I could refactor it down to be more concise? The else clause is fine I think, I'm just not totally sure how to do it. I'd like it to be as concise as possible, but I can't find a different way to write it.
The difference between the 2 is the p element, it's a message that displays, then disappears once you create the first li. So in my if block, I have some of the same code as in the else clause. All the code in the if block is needed to run the app at the start. Thanks for any help!

 if(guests.length < 1){
       return(

       <AddGuest
       guest={props.guest}
       addGuest={props.addGuest}
       updatePendingGuestValue={props.updatePendingGuestValue}
       pendingGuest={props.pendingGuest}
       />

Invite some friends and family! Confirm your guests,
       change their names if needed, remove the guest or filter through your guest who
       have/have not confirmed. Get started above!

       <PendingGuestLi
         pendingGuest={props.pendingGuest} />

 )
  }else{
     return(

      <AddGuest
      guest={props.guest}
      addGuest={props.addGuest}
      updatePendingGuestValue={props.updatePendingGuestValue}
      pendingGuest={props.pendingGuest}
      />

       Hide all unconfirmed guest
         <input type='checkbox' className='filter-guests-checkbox'
         value={props.filterUnconfirmedGuest} onChange={props.toggleFilterUnconfirmedGuest} />

     <GuestList
       guest={props.guest}
       toggleGuestConfirmed={props.toggleGuestConfirmed}
       toggleEditGuest={props.toggleEditGuest}
       editGuest={props.editGuest}
       removeGuest={props.removeGuest}
       filterUnconfirmedGuest={props.filterUnconfirmedGuest}
        />
     <PendingGuestLi
       pendingGuest={props.pendingGuest} />

     )
   }

Thank you for checking it out!

Body:
Separating what stays the same and what changes and placing it inside a block.

  return(
    <div className="App">
      <Header />
      <AddGuest
        guest={props.guest}
        addGuest={props.addGuest}
        updatePendingGuestValue={props.updatePendingGuestValue}
        pendingGuest={props.pendingGuest}
      />
      {(guests.length < 1) ?
          <p className='intro-message'>
            Invite some friends and family! Confirm your guests,
            change their names if needed, remove the guest or filter through your guest who
            have/have not confirmed. Get started above!
          </p>
        :
         <Fragment>
          <div className='filter-checkbox-container'>
            <label className='filter-guests-label'>Hide all unconfirmed guest
              <input type='checkbox' className='filter-guests-checkbox'
              value={props.filterUnconfirmedGuest} onChange={props.toggleFilterUnconfirmedGuest} />
            </label>
          </div>
          <GuestList
            guest={props.guest}
            toggleGuestConfirmed={props.toggleGuestConfirmed}
            toggleEditGuest={props.toggleEditGuest}
            editGuest={props.editGuest}
            removeGuest={props.removeGuest}
            filterUnconfirmedGuest={props.filterUnconfirmedGuest}
             />
          </Fragment>
      }
      <PendingGuestLi
        pendingGuest={props.pendingGuest} />
      </div>
  )


问:
elm-test does not recognise reporter flag
We decided to use JUnit xml files from our tests and upload them during CI as artifacts to Gitlab.

For elm, I followed https://www.npmjs.com/package/elm-test?activeTab=readme and used

```<code>./node_modules/.bin/elm-test --compiler ./node_modules/.bin/elm app/frontend/elm/tests/ --reporter=junit
</code>```

But it actually does nothing. Output is plain text.

```<code>MacBook-Pro-6:enectiva admin$ ./node_modules/.bin/elm-test --compiler ./node_modules/.bin/elm app/frontend/elm/tests/ --reporter=junit

elm-test 0.19.0
---------------

Running 286 tests. To reproduce these results, run: elm-test --fuzz 100 --seed 369554180583103 /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/BareTime/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/AllEnergies/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/ChartPort/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/Data/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/SingleEnergy/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Disableable/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Enectiva/Elm/I18n.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Enectiva/EntityTree/EntityTree.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Exports/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ExportStatePoller/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ExportTemplate/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/HourFilter/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/PriceListForm/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/SelectionState/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/SourceSelection2/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Visibility/Tests.elm

TEST RUN PASSED

Duration: 1049 ms
Passed:   286
Failed:   0
</code>```

The same with json.

As I see from output from reproduce part, it looks like elm-test did not even notice the reporter flag.

Does anyone have idea for solution?

答:
My bad.

Typo, there should be used report instead of reporter.

Body:
We decided to use JUnit xml files from our tests and upload them during CI as artifacts to Gitlab.

For elm, I followed https://www.npmjs.com/package/elm-test?activeTab=readme and used

./node_modules/.bin/elm-test --compiler ./node_modules/.bin/elm app/frontend/elm/tests/ --reporter=junit

But it actually does nothing. Output is plain text.

MacBook-Pro-6:enectiva admin$ ./node_modules/.bin/elm-test --compiler ./node_modules/.bin/elm app/frontend/elm/tests/ --reporter=junit

elm-test 0.19.0
---------------

Running 286 tests. To reproduce these results, run: elm-test --fuzz 100 --seed 369554180583103 /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/BareTime/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/AllEnergies/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/ChartPort/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/Data/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ChartAndControlSet/SingleEnergy/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Disableable/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Enectiva/Elm/I18n.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Enectiva/EntityTree/EntityTree.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Exports/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ExportStatePoller/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/ExportTemplate/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/HourFilter/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/PriceListForm/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/SelectionState/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/SourceSelection2/Tests.elm /Users/admin/go/src/enectiva.cz/enectiva/app/frontend/elm/tests/Visibility/Tests.elm

TEST RUN PASSED

Duration: 1049 ms
Passed:   286
Failed:   0

The same with json.

As I see from output from reproduce part, it looks like elm-test did not even notice the reporter flag.

Does anyone have idea for solution?


问:
How to get an list of element based on given N value
If N=4 than A=[  ]
A array should only get element in size of 4 and after getting N elements need to terminate and append into A[ ]

```<code>N=4
arr=range(N)
arr = [int(x) for x in input().split()]
print(arr)
</code>```

it allow more than 4 element as we enter...

N=4 ,than i need to get only  4 elements from user,after entering 4th element need to terminate and stop appeding ....

答:
Try this simple code.

You just need to iterate the loop 4 times & take the input from user.
The input function return the string. so you need to use the int function to type-cast the value in to integer.

Code :

```<code>N=4
arr = [int(input("Enter number : ")) for i in range(1,N+1)]
print(arr)
</code>```

Output :

```<code>Enter number : 5
Enter number : 6
Enter number : 3
Enter number : 2
[5, 6, 3, 2]
</code>```

Body:
If N=4 than A=[  ]
A array should only get element in size of 4 and after getting N elements need to terminate and append into A[ ]

N=4
arr=range(N)
arr = [int(x) for x in input().split()]
print(arr)

it allow more than 4 element as we enter...

N=4 ,than i need to get only  4 elements from user,after entering 4th element need to terminate and stop appeding ....

Body:
Try this simple code.

You just need to iterate the loop 4 times & take the input from user.
The input function return the string. so you need to use the int function to type-cast the value in to integer.

Code :

N=4
arr = [int(input("Enter number : ")) for i in range(1,N+1)]
print(arr)

Output :

Enter number : 5
Enter number : 6
Enter number : 3
Enter number : 2
[5, 6, 3, 2]


问:
How to combine two middleware and export as one?
I have a utility file which basically has two functions (one to detect user location and another to get user device details) acting as middlewares. Now I would like to know whether it is possible to combine both the middlewares together as one so that it could be used with other middlewares on the route. I would also like to have the freedom of using the functions in the utility file individually when required.

Utility file

```<code>const axios             = require("axios");
const requestIp         = require("request-ip");

const getDeviceLocation = async (req, res, next) => {
    try {
        // ToDO: Check if it works on production
        const clientIp  = requestIp.getClientIp(req);
        const ipToCheck = clientIp === "::1" || "127.0.0.1" ? "" : clientIp;

        const details = await axios.get("https://geoip-db.com/json/" + ipToCheck);

        // Attach returned results to the request body
        req.body.country    = details.data.country_name;
        req.body.state      = details.data.state;
        req.body.city       = details.data.city;

        // Run next middleware
        next();
    }
    catch(error) {
        return res.status(500).json({ message: "ERROR_OCCURRED" });
    }
};

const getDeviceClient = async (req, res, next) => {
    const userAgent = req.headers["user-agent"];

    console.log("Device UA: " + userAgent);
    next();
};

module.exports = { getDeviceLocation, getDeviceClient };
</code>```

Example Routes

```<code>app.post("/v1/register", [getDeviceLocation, getDeviceClient, Otp.verify], User.create);

app.post("/v1/auth/google", [getDeviceLocation, getDeviceClient, Auth.verifyGoogleIdToken], Auth.useGoogle);
</code>```

I would like to have getDeviceLocation and getDeviceClient combined into one say getDeviceInfo yet have the freedom to use getDeviceLocation and getDeviceClient individually when required on any route.

答:
In your case maybe you can use something simple like this

```<code>const getDeviceInfo = async (req, res, next) => {
    await getDeviceClient(req, res, async () => {
        await getDeviceLocation(req, res, next)
    })
}
</code>```

But you may need to handle error cases.

Body:
I have a utility file which basically has two functions (one to detect user location and another to get user device details) acting as middlewares. Now I would like to know whether it is possible to combine both the middlewares together as one so that it could be used with other middlewares on the route. I would also like to have the freedom of using the functions in the utility file individually when required.

Utility file

const axios             = require("axios");
const requestIp         = require("request-ip");

const getDeviceLocation = async (req, res, next) => {
    try {
        // ToDO: Check if it works on production
        const clientIp  = requestIp.getClientIp(req);
        const ipToCheck = clientIp === "::1" || "127.0.0.1" ? "" : clientIp;

        const details = await axios.get("https://geoip-db.com/json/" + ipToCheck);

        // Attach returned results to the request body
        req.body.country    = details.data.country_name;
        req.body.state      = details.data.state;
        req.body.city       = details.data.city;

        // Run next middleware
        next();
    }
    catch(error) {
        return res.status(500).json({ message: "ERROR_OCCURRED" });
    }
};

const getDeviceClient = async (req, res, next) => {
    const userAgent = req.headers["user-agent"];

    console.log("Device UA: " + userAgent);
    next();
};

module.exports = { getDeviceLocation, getDeviceClient };

Example Routes

app.post("/v1/register", [getDeviceLocation, getDeviceClient, Otp.verify], User.create);

app.post("/v1/auth/google", [getDeviceLocation, getDeviceClient, Auth.verifyGoogleIdToken], Auth.useGoogle);

I would like to have getDeviceLocation and getDeviceClient combined into one say getDeviceInfo yet have the freedom to use getDeviceLocation and getDeviceClient individually when required on any route.

Body:
In your case maybe you can use something simple like this

const getDeviceInfo = async (req, res, next) => {
    await getDeviceClient(req, res, async () => {
        await getDeviceLocation(req, res, next)
    })
}

But you may need to handle error cases.


问:
Redirect form input from a servlet to another form
I have a form created by a servlet which is supposed to fill out a text input field from a search. So the form is like this :

```<code><form name="form1">
  <input type="text" readonly="true" value="" /> <button href="/searchServlet />
</form>
</code>```

When the button is clicked, it opens up another form , which does the search and displays the results as list from which the user can pick any result. The picked result id populates some hidden fields in the form. Now do I get those hidden fields data in "form1"? Is there some Javascript for that purpose? Or can I redirect input from one servlet to another?

答:
JavaScript is indeed your friend here. Give the input a name as well and let the button open a dialog by window.open().

```<code><form name="form1">
  <input type="text" name="text1" readonly="true" />
  <button onclick="window.open('/searchServlet');">search</button>
</form>
</code>```

Then in the HTML generated by /searchServlet and its JSP in the dialog, you can use window.opener to get the parent window and then from there do the usual document stuff as if you're sitting in the parent window. Here's a basic kickoff example:

```<code><button onclick="window.opener.document.form1.text1.value='1'; window.close();">1</button>
<button onclick="window.opener.document.form1.text1.value='2'; window.close();">2</button>
<button onclick="window.opener.document.form1.text1.value='3'; window.close();">3</button>
</code>```

Of course you'd like to abstract/refactor the verbosity/duplication away in some function.

Body:
I have a form created by a servlet which is supposed to fill out a text input field from a search. So the form is like this :

<form name="form1">
  <input type="text" readonly="true" value="" /> <button href="/searchServlet />
</form>

When the button is clicked, it opens up another form , which does the search and displays the results as list from which the user can pick any result. The picked result id populates some hidden fields in the form. Now do I get those hidden fields data in "form1"? Is there some Javascript for that purpose? Or can I redirect input from one servlet to another?

Body:
JavaScript is indeed your friend here. Give the input a name as well and let the button open a dialog by window.open().

<form name="form1">
  <input type="text" name="text1" readonly="true" />
  <button onclick="window.open('/searchServlet');">search</button>
</form>

Then in the HTML generated by /searchServlet and its JSP in the dialog, you can use window.opener to get the parent window and then from there do the usual document stuff as if you're sitting in the parent window. Here's a basic kickoff example:

<button onclick="window.opener.document.form1.text1.value='1'; window.close();">1</button>
<button onclick="window.opener.document.form1.text1.value='2'; window.close();">2</button>
<button onclick="window.opener.document.form1.text1.value='3'; window.close();">3</button>

Of course you'd like to abstract/refactor the verbosity/duplication away in some function.


问:
Is there a way to determine the current breakpoint in Bootstrap without relying on Javascript?
There many examples (hacks) to determine the current breakpoint using Javascript, but I am in need of a solution that leverages CSS.</p>

答:
In the absence of a simple CSS solution to determine current breakpoint, a possible approach will be to create the logic to calculate the breakpoint in Javascript, and link the code to the page using

```<code>    <link rel="import" href="breakpoints.html">
</code>```

"breakpoints.html" should add a CSS class to the page BODY tag indicating the current breakpoint. e.g.:

```<code>   <body class="breakpoint-md">...</body>
</code>```

In that way the logic to determine the current breakpoint is outside of the page, and can be reused in any project, but you can simply add a "suffix" to your CSS selectors, instead of using complicated media query. e.g.:

```<code>.breakpoint-md #widget {
    color: red;
}

.breakpoint-lg #widget {
    color: blue;
}

</code>```

Here is the content of breakpoint.html

```<code><script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>

(function($) {

    function isBreakPoint(size) {
        var value = window.getComputedStyle(document.documentElement).getPropertyValue('--breakpoint-' + size);
        var matched = window.matchMedia("(min-width: "+ value +")").matches;
        return matched;
    }

    $( window ).resize(function() {
        if(isBreakPoint('xs')) {
            $(document.body).addClass('breakpoint-xs').removeClass('breakpoint-sm breakpoint-md breakpoint-lg breakpoint-xl');
        }
        if(isBreakPoint('sm')) {
            $(document.body).addClass('breakpoint-sm').removeClass('breakpoint-xs breakpoint-md breakpoint-lg breakpoint-xl');
        }
        if(isBreakPoint('md')) {
            $(document.body).addClass('breakpoint-md').removeClass('breakpoint-xs breakpoint-sm breakpoint-lg breakpoint-xl');
        }
        if(isBreakPoint('lg')) {
            $(document.body).addClass('breakpoint-lg').removeClass('breakpoint-xs breakpoint-sm breakpoint-md breakpoint-xl');
        }

        if(isBreakPoint('xl')) {
            $(document.body).addClass('breakpoint-xl').removeClass('breakpoint-xs breakpoint-sm breakpoint-md breakpoint-lg');
        }
    });

    $( window ).resize();

})(window.jQuery);
</script>
</code>```

Here is how the BODY tag is modified:

To add breakpoints.html to your page, anywhere in your HTML code you can add:

```<code><link re="import" href="breakpoints.htmt"/>
</code>```

Body:
In the absence of a simple CSS solution to determine current breakpoint, a possible approach will be to create the logic to calculate the breakpoint in Javascript, and link the code to the page using

    <link rel="import" href="breakpoints.html">

"breakpoints.html" should add a CSS class to the page BODY tag indicating the current breakpoint. e.g.:

   <body class="breakpoint-md">...</body>

In that way the logic to determine the current breakpoint is outside of the page, and can be reused in any project, but you can simply add a "suffix" to your CSS selectors, instead of using complicated media query. e.g.:

.breakpoint-md #widget {
    color: red;
}

.breakpoint-lg #widget {
    color: blue;
}

Here is the content of breakpoint.html

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>

(function($) {

    function isBreakPoint(size) {
        var value = window.getComputedStyle(document.documentElement).getPropertyValue('--breakpoint-' + size);
        var matched = window.matchMedia("(min-width: "+ value +")").matches;
        return matched;
    }

    $( window ).resize(function() {
        if(isBreakPoint('xs')) {
            $(document.body).addClass('breakpoint-xs').removeClass('breakpoint-sm breakpoint-md breakpoint-lg breakpoint-xl');
        }
        if(isBreakPoint('sm')) {
            $(document.body).addClass('breakpoint-sm').removeClass('breakpoint-xs breakpoint-md breakpoint-lg breakpoint-xl');
        }
        if(isBreakPoint('md')) {
            $(document.body).addClass('breakpoint-md').removeClass('breakpoint-xs breakpoint-sm breakpoint-lg breakpoint-xl');
        }
        if(isBreakPoint('lg')) {
            $(document.body).addClass('breakpoint-lg').removeClass('breakpoint-xs breakpoint-sm breakpoint-md breakpoint-xl');
        }

        if(isBreakPoint('xl')) {
            $(document.body).addClass('breakpoint-xl').removeClass('breakpoint-xs breakpoint-sm breakpoint-md breakpoint-lg');
        }
    });

    $( window ).resize();

})(window.jQuery);
</script>

Here is how the BODY tag is modified:

To add breakpoints.html to your page, anywhere in your HTML code you can add:

<link re="import" href="breakpoints.htmt"/>


问:
How to do Convert Latitude/Longitude To Address
I wrote some code this codes worked but only get latitude and longitude
but ı want  convert latitude and longitude from Street adress.

<!DOCTYPE html>

  <title>location</title>

```

答:
If you want to get latitude and longitude from an address, then the process is called geocoding and can be completed using the Google Maps API. Here is sample python code to run this conversion:

```<code>import requests
import json

def convert(address):
    URL = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=[INSERT API KEY]&callback=initMap'
    r = requests.get(URL).json()
    return r['results'][0]['geometry']['location']
</code>```

If instead you would like to get the address based on the latitude and longitude, reverse geocoding, also from the Google Maps API, is the way to go.

Body:
If you want to get latitude and longitude from an address, then the process is called geocoding and can be completed using the Google Maps API. Here is sample python code to run this conversion:

import requests
import json

def convert(address):
    URL = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=[INSERT API KEY]&callback=initMap'
    r = requests.get(URL).json()
    return r['results'][0]['geometry']['location']

If instead you would like to get the address based on the latitude and longitude, reverse geocoding, also from the Google Maps API, is the way to go.


问:
How to count time between occurrences (and duration of occurrence)
I am dealing with the following challenge and would greatly appreciate any help.

Consider I have a data table with the following information.

```<code>Store   Day           In stock ?  Out of stock ?
Store A 01 - 01 - 19  1           0
Store A 02 - 01 - 19  0           1
Store A 03 - 01 - 19  0           1
Store A 04 - 01 - 19  1           0
Store A 05 - 01 - 19  1           0
Store A 06 - 01 - 19  0           1
Store A 07 - 01 - 19  0           1
Store A       …       0           1
Store B 01 - 01 - 19  1           0
Store B 02 - 01 - 19  0           1
Store B       …       0           1
</code>```

For each store, I want to count the number of days for which is has consecutively been in or out of stock. These two columns are binary, and mutually exclusive. So for store A, the result would be:

```<code>Store     Duration in stock   Duration out of stock
Store A   1
Store A                       2
Store A   2
Store A                       3
</code>```

I need to do this for a large dataset (hourly values for hundreds of stores), and thus would like to automate this. Furthermore, I want to do further analysis on the 'in stock duration' and 'out of stock duration', such as average values, extremes, percentiles etc. Therefore, the data needs to be organized in such a way that this would be possible.

I have not found a solution to this problem yet. Any insight would be nice!

Below comma seperated values:

```<code>Store;Day;In stock?;Out of stock?
Store A;01-01-19;1;0
Store A;02-01-19;0;1
Store A;03-01-19;0;1
Store A;04-01-19;1;0
Store A;05-01-19;1;0
Store A;06-01-19;0;1
Store A;07-01-19;0;1
Store A;…;0;1
Store B;01-01-19;1;0
Store B;02-01-19;0;1
Store B;…;0;1
</code>```

答:
Hopefully this is close enough.

But first to clarify something.

When we say "show us your data", we don't demand a facsimile of what you're working with, but rather something that is functionally the same, or analogous, to your data. Often this means you just limit the number of rows you include, while other times it involves changing the names of column names or values due to privacy concerns, but the data is kept the same, as far as processing is concerned.

First my attempt at reproducing something resembling your data

```<code>set.seed(4)

Day <- as.Date(0:8, origin="2019-01-01")
Store <- rep(paste("Store", LETTERS[1:3]), each=length(Day))
In <- sample(c(0, 0, 1), length(Store), rep=TRUE)
Out <- abs(In - 1)
Day <- format(rep(Day, length=length(Store)), "%d - %m - %y")

dtf <- data.frame(Store, Day, In, Out)
head(dtf)
#     Store          Day In Out
# 1 Store A 01 - 01 - 19  0   1
# 2 Store A 02 - 01 - 19  0   1
# 3 Store A 03 - 01 - 19  0   1
# 4 Store A 04 - 01 - 19  0   1
# 5 Store A 05 - 01 - 19  1   0
</code>```

Given this data, the following should produce the desired result.

```<code>io <- with(dtf, tapply(In, Store, function(x) as.data.frame(rle(x)[1:2])))
io <- do.call(rbind, io)

iod <- with(io,
  data.frame(Store=gsub("\\.[0-9]?", "", rownames(io)),
             Duration.in.stock=lengths*values,
             Duration.out.of.stock=lengths*!values
  )
)

iod[iod == 0] <- ""

iod
#      Store Duration.in.stock Duration.out.of.stock
# 1  Store A                                       4
# 2  Store A                 1
# 3  Store A                                       1
# 4  Store A                 3
# 5  Store B                                       1
# 6  Store B                 1
# 7  Store B                                       2
# 8  Store B                 1
# 9  Store B                                       2
# 10 Store B                 1
# 11 Store B                                       1
# 12 Store C                 4
# 13 Store C                                       3
# 14 Store C                 1
</code>```

Body:
I am dealing with the following challenge and would greatly appreciate any help.

Consider I have a data table with the following information.

Store   Day           In stock ?  Out of stock ?
Store A 01 - 01 - 19  1           0
Store A 02 - 01 - 19  0           1
Store A 03 - 01 - 19  0           1
Store A 04 - 01 - 19  1           0
Store A 05 - 01 - 19  1           0
Store A 06 - 01 - 19  0           1
Store A 07 - 01 - 19  0           1
Store A       …       0           1
Store B 01 - 01 - 19  1           0
Store B 02 - 01 - 19  0           1
Store B       …       0           1

For each store, I want to count the number of days for which is has consecutively been in or out of stock. These two columns are binary, and mutually exclusive. So for store A, the result would be:

Store     Duration in stock   Duration out of stock
Store A   1
Store A                       2
Store A   2
Store A                       3

I need to do this for a large dataset (hourly values for hundreds of stores), and thus would like to automate this. Furthermore, I want to do further analysis on the 'in stock duration' and 'out of stock duration', such as average values, extremes, percentiles etc. Therefore, the data needs to be organized in such a way that this would be possible.

I have not found a solution to this problem yet. Any insight would be nice!

Below comma seperated values:

Store;Day;In stock?;Out of stock?
Store A;01-01-19;1;0
Store A;02-01-19;0;1
Store A;03-01-19;0;1
Store A;04-01-19;1;0
Store A;05-01-19;1;0
Store A;06-01-19;0;1
Store A;07-01-19;0;1
Store A;…;0;1
Store B;01-01-19;1;0
Store B;02-01-19;0;1
Store B;…;0;1

Body:
Hopefully this is close enough.

But first to clarify something.

When we say "show us your data", we don't demand a facsimile of what you're working with, but rather something that is functionally the same, or analogous, to your data. Often this means you just limit the number of rows you include, while other times it involves changing the names of column names or values due to privacy concerns, but the data is kept the same, as far as processing is concerned.

First my attempt at reproducing something resembling your data

set.seed(4)

Day <- as.Date(0:8, origin="2019-01-01")
Store <- rep(paste("Store", LETTERS[1:3]), each=length(Day))
In <- sample(c(0, 0, 1), length(Store), rep=TRUE)
Out <- abs(In - 1)
Day <- format(rep(Day, length=length(Store)), "%d - %m - %y")

dtf <- data.frame(Store, Day, In, Out)
head(dtf)
#     Store          Day In Out
# 1 Store A 01 - 01 - 19  0   1
# 2 Store A 02 - 01 - 19  0   1
# 3 Store A 03 - 01 - 19  0   1
# 4 Store A 04 - 01 - 19  0   1
# 5 Store A 05 - 01 - 19  1   0

Given this data, the following should produce the desired result.

io <- with(dtf, tapply(In, Store, function(x) as.data.frame(rle(x)[1:2])))
io <- do.call(rbind, io)

iod <- with(io,
  data.frame(Store=gsub("\\.[0-9]?", "", rownames(io)),
             Duration.in.stock=lengths*values,
             Duration.out.of.stock=lengths*!values
  )
)

iod[iod == 0] <- ""

iod
#      Store Duration.in.stock Duration.out.of.stock
# 1  Store A                                       4
# 2  Store A                 1
# 3  Store A                                       1
# 4  Store A                 3
# 5  Store B                                       1
# 6  Store B                 1
# 7  Store B                                       2
# 8  Store B                 1
# 9  Store B                                       2
# 10 Store B                 1
# 11 Store B                                       1
# 12 Store C                 4
# 13 Store C                                       3
# 14 Store C                 1


问:
Preprocess n files concurrently with tf.data API
I want to use tf.data.experimental.parallel_interleave to preprocess n files concurrently. cycle_length argument is used for this purpose but what is the maximum value of this argument? My CPU has 8 cores and 16 threads.

答:
As per official docs on tf.data.experimental.parallel_interleave

Unlike tf.data.Dataset.interleave, it gets elements from cycle_length
nested datasets in parallel

and

cycle_length: The number of input Datasets to interleave from in
parallel.

So basically, a reasonable argument would be number of dataset elements, which would be processed in parallel. In this way, it has no relation to CPU cores/threads


问:
Regex for date of birth
I am trying to implement a regex for date of birth in the format of MM/DD/YYYY.
I could not figure out how to force users in typing 01-12 for MM, 01-31 for day, and any four
digits for year.
I simply have a regex for MM/DD/YYYY which is @"^\d{2}/\d{2}/\d{4}$".
Any suggestions would be greatly appreciated.

Thanks

答:
I recently used this regex in one of my projects

```<code>^(0?[1-9]|1[0-2])/([0-2]?[1-9]|[1-3][01])/\d{4}$
</code>```

This obviously works for all dates in dd/MM/yyyy format but you may not specify '0' when it's not necessary. So you can write '01/01/2000' as well as '1/1/2000'.

Title: Regex for date of birth

Body:
I recently used this regex in one of my projects

^(0?[1-9]|1[0-2])/([0-2]?[1-9]|[1-3][01])/\d{4}$

This obviously works for all dates in dd/MM/yyyy format but you may not specify '0' when it's not necessary. So you can write '01/01/2000' as well as '1/1/2000'.


问:
I want to select a product with attribute without stock
I'm on prestashop 1.7.5.2 with PHP 7.0 and Apache.

I want to enable to select a product with an attribute without stock. Example :

Product 1 with 2 attributes.

Attribute 1 Stock = 1

Attribute 2 Stock = 0

When I select Attribute 2, the website doesn't select this attribute...

I want to select Attribute 2 and order it.

How Can I do this ? I don't want to disable the stock manager in Back-office.

答:
You can turn this on from the Admin Panel in Product Settings:

Also make sure you set this up correctly at a product level:

This can be set when you edit a product, in the Combinations tab, at the bottom.


问:
array return index from another array
suppose we have this two array. in some condition, I want to return the index of a second array.

```<code>let a = [1, 2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 , 12]
let b = [0, 1, 2, 3 , 4 , 5, 6 , 7 , 8, 9, 10, 11]

if (a[2]) ? return b[2] : return null
</code>```

why I need this? because I have a month number of the year that starts from 0 to 11. but I need to turn this 1 12 for storing in my database.
sry about the title of this question if someone has a better title I would be glad about changing it.

答:
Why make this harder than it needs to be? Just add 1 to the value you get from your initial array. Here is, per your comment, 10 years worth of values for the months with a +1 value.

let years = 10;
let months = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let allYears = [];

for(let i = 0; i < years; i++){
    let year = [];
    for(let x = 0; x < months.length; x++){
        year[x] = months[x] + 1;
    }
    allYears.push(year);
}

console.log(allYears);```

Title: array return index from another array

Body:
suppose we have this two array. in some condition, I want to return the index of a second array.

let a = [1, 2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 , 12]
let b = [0, 1, 2, 3 , 4 , 5, 6 , 7 , 8, 9, 10, 11]

if (a[2]) ? return b[2] : return null

why I need this? because I have a month number of the year that starts from 0 to 11. but I need to turn this 1 12 for storing in my database.
sry about the title of this question if someone has a better title I would be glad about changing it.


问:
Formatting Time/Date from different time zones in Powershell
I need to convert UTC time/date output to Eastern Standard Time in ISO 8601 (or similar) format using Powershell for use in a DOS Batch file.

I have very little experience with Powershell, but have previously modified existing Powershell commands for various DOS batch files.  Powershell can easily output time/date from numerous time zones, but it's not clear if it can readily display that output in a numerical format.

In a DOS batch file, Powershell can be called to display UTC time in this format --

```<code>echo | powershell (get-date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss')
</code>```

I need to call upon other time zones, but the output is 'FullDateTimePattern' which is spelled out --

```<code>echo | Powershell [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time')
</code>```

I was hoping that the previous commands could (somehow) be merged together, or if one of the 'Get-Date -format' specifiers could be applied to the second code sample, or if an offset value could be applied to the UTC time/date output, or if there is some other easy code solution (or utility) that I could incorporate into a DOS batch file.

答:
Much thanks for the helpful the replies.  I noticed one can apply the documented Microsoft Get-Date format specifiers to time zones in this manner (which wasn't obvious, given my lack of Powershell experience).

Testing most of these options on the widest spread time zones can be helpful.

Dateline Standard Time [(UTC-12:00) International Date Line West]

Line Islands Standard Time [(UTC+14:00) Kiritimati Island]

The following code was run on Saturday, June 01, 2019 1:01 PM Eastern Standard Time to convert to Line Islands Standard Time (UTC+14:00)

ShortDatePattern: Get-Date -format d equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('d')"
</code>```

6/2/2019

LongDatePattern: Get-Date -format D equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('D')"
</code>```

Sunday, June 02, 2019

Full date and time (long date and short time): Get-Date -format f equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('f')"
</code>```

Sunday, June 02, 2019 7:01 AM

FullDateTimePattern (long date and long time): Get-Date -format F equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('F')"
</code>```

Sunday, June 02, 2019 7:01:23 AM

General (short date and short time): Get-Date -format g equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('g')"
</code>```

6/2/2019 7:01 AM

General (short date and long time): Get-Date -format G equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('G')"
</code>```

6/2/2019 7:01:25 AM

MonthDayPattern: Get-Date -format m or Get-Date -format M equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('m')"
</code>```

June 2

Round-trip date/time pattern: Get-Date -format o equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('o')"
</code>```

2019-06-02T07:01:27.8492082

RFC1123Pattern: Get-Date -format r or Get-Date -format R equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('r')"
</code>```

Sun, 02 Jun 2019 07:01:28 GMT

SortableDateTimePattern (based on ISO 8601) using local time: Get-Date -format s equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('s')"
</code>```

2019-06-02T07:01:29

ShortTimePattern: Get-Date -format t equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('t')"
</code>```

7:01 AM

LongTimePattern: Get-Date -format T equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('T')"
</code>```

7:01:32 AM

UniversalSortableDateTimePattern using the format for universal time display:  Get-Date -format u equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('u')"
</code>```

2019-06-02 07:01:33Z

Full date and time (long date and long time) using universal time: Get-Date -format U equivalent

Applying this option to any time zone (other than UTC) seems to give a +4:00 offset (perhaps depending upon local time zone), which could be problematic.

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('U')"
</code>```

Sunday, June 02, 2019 11:01:34 AM

YearMonthPattern: Get-Date -format y or Get-Date -format Y equivalent

```<code>Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('y')"
</code>```

June, 2019

Body:
I need to convert UTC time/date output to Eastern Standard Time in ISO 8601 (or similar) format using Powershell for use in a DOS Batch file.

I have very little experience with Powershell, but have previously modified existing Powershell commands for various DOS batch files.  Powershell can easily output time/date from numerous time zones, but it's not clear if it can readily display that output in a numerical format.

In a DOS batch file, Powershell can be called to display UTC time in this format --

echo | powershell (get-date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss')

I need to call upon other time zones, but the output is 'FullDateTimePattern' which is spelled out --

echo | Powershell [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time')

I was hoping that the previous commands could (somehow) be merged together, or if one of the 'Get-Date -format' specifiers could be applied to the second code sample, or if an offset value could be applied to the UTC time/date output, or if there is some other easy code solution (or utility) that I could incorporate into a DOS batch file.

Body:
Much thanks for the helpful the replies.  I noticed one can apply the documented Microsoft Get-Date format specifiers to time zones in this manner (which wasn't obvious, given my lack of Powershell experience).

Testing most of these options on the widest spread time zones can be helpful.

Dateline Standard Time [(UTC-12:00) International Date Line West]

Line Islands Standard Time [(UTC+14:00) Kiritimati Island]

The following code was run on Saturday, June 01, 2019 1:01 PM Eastern Standard Time to convert to Line Islands Standard Time (UTC+14:00)

ShortDatePattern: Get-Date -format d equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('d')"

6/2/2019

LongDatePattern: Get-Date -format D equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('D')"

Sunday, June 02, 2019

Full date and time (long date and short time): Get-Date -format f equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('f')"

Sunday, June 02, 2019 7:01 AM

FullDateTimePattern (long date and long time): Get-Date -format F equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('F')"

Sunday, June 02, 2019 7:01:23 AM

General (short date and short time): Get-Date -format g equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('g')"

6/2/2019 7:01 AM

General (short date and long time): Get-Date -format G equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('G')"

6/2/2019 7:01:25 AM

MonthDayPattern: Get-Date -format m or Get-Date -format M equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('m')"

June 2

Round-trip date/time pattern: Get-Date -format o equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('o')"

2019-06-02T07:01:27.8492082

RFC1123Pattern: Get-Date -format r or Get-Date -format R equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('r')"

Sun, 02 Jun 2019 07:01:28 GMT

SortableDateTimePattern (based on ISO 8601) using local time: Get-Date -format s equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('s')"

2019-06-02T07:01:29

ShortTimePattern: Get-Date -format t equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('t')"

7:01 AM

LongTimePattern: Get-Date -format T equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('T')"

7:01:32 AM

UniversalSortableDateTimePattern using the format for universal time display:  Get-Date -format u equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('u')"

2019-06-02 07:01:33Z

Full date and time (long date and long time) using universal time: Get-Date -format U equivalent

Applying this option to any time zone (other than UTC) seems to give a +4:00 offset (perhaps depending upon local time zone), which could be problematic.

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('U')"

Sunday, June 02, 2019 11:01:34 AM

YearMonthPattern: Get-Date -format y or Get-Date -format Y equivalent

Powershell.exe -c "[System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'Line Islands Standard Time').ToString('y')"

June, 2019