问:
How to count rows between 2 non empty cells with their intermediary empty cells in Google Sheets?
I'm trying to count each rows of empty cells between two non-empy cells and adding the upper non empty-cell count (or the lower non-empty cells count)  to the result when the empty cells/rows numbers are variable and irregular in this manner:

```<code>A1 Empty
A2 Non-empty
A3 Empty
A4 Empty
A5 Empty
A6 Empty
A7 Non-empty
</code>```

(with A2 to A5 being irregular — could be any number of intermediary empty rows/cells — i.e. 10, 2, 30, 5, etc., and variable — could be located in any location within Column A)

The result should return as follow:

```<code>=IFS(

AND(A2="",A3=""),"",

AND(A2="",A3<>""),"",

AND(A2<>"",A3<>""),ROWS(A2),

AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))
</code>```

How do we program Google Sheets to count rows "UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next ono empty row(-1)) when the emppty intermediary rows' count is variable/unknown for each occurence and irregular/can be any number of intremediary rows?

I have this data as example:

So far, I've come up with this partial solution:

```<code>=IFS(AND(A2="",A3=""),"", AND(A2="",A3<>""),"", AND(A2<>"",A3<>""),ROWS(A2), AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))))
</code>```

The expected result should return as follows:

The Sheet copy:
https://docs.google.com/spreadsheets/d/1eLXdFINKVtS5Fxon8mIQDmBUTZokyY_Fb6tfWJRDOVI/edit?usp=sharing

答:
In the mean time I did some simplification of my previous Monster formula and learned the ArrayFormula application in the process.

1st I tried to shorten the big blank cells intervals into ranges formulations to see if it still worked.

For example I changed:

```<code>AND(A1<>"",A2="",A3="",A4<>""),ROWS(A1:A4)-1,
</code>```

into

```<code>AND(A1<>"",A2:A3="",A4<>""),ROWS(A1:A4)-1,
</code>```

And it shortened my formula from this:

to this:

But then when pasting the new formula I got a #VALUE! error  'an array value could not be found'.

After further tests, I used the ArrayFormula and it worked by adapting the simple 'ranges' previously used to Arrays:

from this

```<code>AND(A1<>"",A2:A3="",A4<>""),ROWS(A1:A4)-1,
</code>```

into this

```<code>AND(A1<>"",ArrayFormula(A2:A3=""),A4<>""),ROWS(A1:A4)-1,
</code>```

With this final result:

```<code>=IFS(AND(A1="",A2=""),"",AND(A1="",A2<>""),"",AND(A1<>"",A2<>""),ROWS(A1),AND(A1<>"",A2="",A3<>""),ROWS(A1:A3)-1,AND(A1<>"",ArrayFormula(A2:A3=""),A4<>""),ROWS(A1:A4)-1,AND(A1<>"",ArrayFormula(A2:A4=""),A5<>""),ROWS(A1:A5)-1,AND(A1<>"",ArrayFormula(A2:A5=""),A6<>""),ROWS(A1:A6)-1,AND(A1<>"",ArrayFormula(A2:A6=""),A7<>""),ROWS(A1:A7)-1,AND(A1<>"",ArrayFormula(A2:A7=""),A8<>""),ROWS(A1:A8)-1,AND(A1<>"",ArrayFormula(A2:A8=""),A9<>""),ROWS(A1:A9)-1,AND(A1<>"",ArrayFormula(A2:A9=""),A10<>""),ROWS(A1:A10)-1,AND(A1<>"",ArrayFormula(A2:A10=""),A11<>""),ROWS(A1:A11)-1,AND(A1<>"",ArrayFormula(A2:A11=""),A12<>""),ROWS(A1:A12)-1,AND(A1<>"",ArrayFormula(A2:A12=""),A13<>""),ROWS(A1:A13)-1,AND(A1<>"",ArrayFormula(A2:A13=""),A14<>""),ROWS(A1:A14)-1,AND(A1<>"",ArrayFormula(A2:A14=""),A15<>""),ROWS(A1:A15)-1,AND(A1<>"",ArrayFormula(A2:A15=""),A16<>""),ROWS(A1:A16)-1,AND(A1<>"",ArrayFormula(A2:A16=""),A17<>""),ROWS(A1:A17)-1,AND(A1<>"",ArrayFormula(A2:A17=""),A18<>""),ROWS(A1:A18)-1,AND(A1<>"",ArrayFormula(A2:A18=""),A19<>""),ROWS(A1:A19)-1,AND(A1<>"",ArrayFormula(A2:A19=""),A20<>""),ROWS(A1:A20)-1,AND(A1<>"",ArrayFormula(A2:A20=""),A21<>""),ROWS(A1:A21)-1,AND(A1<>"",ArrayFormula(A2:A21=""),A22<>""),ROWS(A1:A22)-1,AND(A1<>"",ArrayFormula(A2:A22=""),A23<>""),ROWS(A1:A23)-1,AND(A1<>"",ArrayFormula(A2:A23=""),A24<>""),ROWS(A1:A24)-1,AND(A1<>"",ArrayFormula(A2:A24=""),A25<>""),ROWS(A1:A25)-1,AND(A1<>"",ArrayFormula(A2:A25=""),A26<>""),ROWS(A1:A26)-1,AND(A1<>"",ArrayFormula(A2:A26=""),A27<>""),ROWS(A1:A27)-1,AND(A1<>"",ArrayFormula(A2:A27=""),A28<>""),ROWS(A1:A28)-1,AND(A1<>"",ArrayFormula(A2:A28=""),A29<>""),ROWS(A1:A29)-1,AND(A1<>"",ArrayFormula(A2:A29=""),A30<>""),ROWS(A1:A30)-1,AND(A1<>"",ArrayFormula(A2:A30=""),A31<>""),ROWS(A1:A31)-1,AND(A1<>"",ArrayFormula(A2:A31=""),A32<>""),ROWS(A1:A32)-1,AND(A1<>"",ArrayFormula(A2:A32=""),A33<>""),ROWS(A1:A33)-1,AND(A1<>"",ArrayFormula(A2:A33=""),A34<>""),ROWS(A1:A34)-1,AND(A1<>"",ArrayFormula(A2:A34=""),A35<>""),ROWS(A1:A35)-1,AND(A1<>"",ArrayFormula(A2:A35=""),A36<>""),ROWS(A1:A36)-1,AND(A1<>"",ArrayFormula(A2:A36=""),A37<>""),ROWS(A1:A37)-1,AND(A1<>"",ArrayFormula(A2:A37=""),A38<>""),ROWS(A1:A38)-1,AND(A1<>"",ArrayFormula(A2:A38=""),A39<>""),ROWS(A1:A39)-1,AND(A1<>"",ArrayFormula(A2:A39=""),A40<>""),ROWS(A1:A40)-1,AND(A1<>"",ArrayFormula(A2:A40=""),A41<>""),ROWS(A1:A41)-1,AND(A1<>"",ArrayFormula(A2:A41=""),A42<>""),ROWS(A1:A42)-1,AND(A1<>"",ArrayFormula(A2:A42=""),A43<>""),ROWS(A1:A43)-1,AND(A1<>"",ArrayFormula(A2:A43=""),A44<>""),ROWS(A1:A44)-1,AND(A1<>"",ArrayFormula(A2:A44=""),A45<>""),ROWS(A1:A45)-1,AND(A1<>"",ArrayFormula(A2:A45=""),A46<>""),ROWS(A1:A46)-1,AND(A1<>"",ArrayFormula(A2:A46=""),A47<>""),ROWS(A1:A47)-1,AND(A1<>"",ArrayFormula(A2:A47=""),A48<>""),ROWS(A1:A48)-1, AND(A1<>"",ArrayFormula(A2:A48=""),A49<>""),ROWS(A1:A49)-1, AND(A1<>"",ArrayFormula(A2:A49=""),A50<>""),ROWS(A1:A50)-1)
</code>```

New Sheet here

Body:
I'm trying to count each rows of empty cells between two non-empy cells and adding the upper non empty-cell count (or the lower non-empty cells count)  to the result when the empty cells/rows numbers are variable and irregular in this manner:

A1 Empty
A2 Non-empty
A3 Empty
A4 Empty
A5 Empty
A6 Empty
A7 Non-empty

(with A2 to A5 being irregular — could be any number of intermediary empty rows/cells — i.e. 10, 2, 30, 5, etc., and variable — could be located in any location within Column A)

The result should return as follow:

=IFS(

AND(A2="",A3=""),"",

AND(A2="",A3<>""),"",

AND(A2<>"",A3<>""),ROWS(A2),

AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))

How do we program Google Sheets to count rows "UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next ono empty row(-1)) when the emppty intermediary rows' count is variable/unknown for each occurence and irregular/can be any number of intremediary rows?

I have this data as example:

So far, I've come up with this partial solution:

=IFS(AND(A2="",A3=""),"", AND(A2="",A3<>""),"", AND(A2<>"",A3<>""),ROWS(A2), AND(A2<>"",A3=""),ROWS(A2:UP TO NEXT NON-EMPTY ROW BENEATH (NOT COMPRISED (or minus the next non-empty row(-1)))))

The expected result should return as follows:

The Sheet copy:
https://docs.google.com/spreadsheets/d/1eLXdFINKVtS5Fxon8mIQDmBUTZokyY_Fb6tfWJRDOVI/edit?usp=sharing

Body:
In the mean time I did some simplification of my previous Monster formula and learned the ArrayFormula application in the process.

1st I tried to shorten the big blank cells intervals into ranges formulations to see if it still worked.

For example I changed:

AND(A1<>"",A2="",A3="",A4<>""),ROWS(A1:A4)-1,

into

AND(A1<>"",A2:A3="",A4<>""),ROWS(A1:A4)-1,

And it shortened my formula from this:

to this:

But then when pasting the new formula I got a #VALUE! error  'an array value could not be found'.

After further tests, I used the ArrayFormula and it worked by adapting the simple 'ranges' previously used to Arrays:

from this

AND(A1<>"",A2:A3="",A4<>""),ROWS(A1:A4)-1,

into this

AND(A1<>"",ArrayFormula(A2:A3=""),A4<>""),ROWS(A1:A4)-1,

With this final result:

=IFS(AND(A1="",A2=""),"",AND(A1="",A2<>""),"",AND(A1<>"",A2<>""),ROWS(A1),AND(A1<>"",A2="",A3<>""),ROWS(A1:A3)-1,AND(A1<>"",ArrayFormula(A2:A3=""),A4<>""),ROWS(A1:A4)-1,AND(A1<>"",ArrayFormula(A2:A4=""),A5<>""),ROWS(A1:A5)-1,AND(A1<>"",ArrayFormula(A2:A5=""),A6<>""),ROWS(A1:A6)-1,AND(A1<>"",ArrayFormula(A2:A6=""),A7<>""),ROWS(A1:A7)-1,AND(A1<>"",ArrayFormula(A2:A7=""),A8<>""),ROWS(A1:A8)-1,AND(A1<>"",ArrayFormula(A2:A8=""),A9<>""),ROWS(A1:A9)-1,AND(A1<>"",ArrayFormula(A2:A9=""),A10<>""),ROWS(A1:A10)-1,AND(A1<>"",ArrayFormula(A2:A10=""),A11<>""),ROWS(A1:A11)-1,AND(A1<>"",ArrayFormula(A2:A11=""),A12<>""),ROWS(A1:A12)-1,AND(A1<>"",ArrayFormula(A2:A12=""),A13<>""),ROWS(A1:A13)-1,AND(A1<>"",ArrayFormula(A2:A13=""),A14<>""),ROWS(A1:A14)-1,AND(A1<>"",ArrayFormula(A2:A14=""),A15<>""),ROWS(A1:A15)-1,AND(A1<>"",ArrayFormula(A2:A15=""),A16<>""),ROWS(A1:A16)-1,AND(A1<>"",ArrayFormula(A2:A16=""),A17<>""),ROWS(A1:A17)-1,AND(A1<>"",ArrayFormula(A2:A17=""),A18<>""),ROWS(A1:A18)-1,AND(A1<>"",ArrayFormula(A2:A18=""),A19<>""),ROWS(A1:A19)-1,AND(A1<>"",ArrayFormula(A2:A19=""),A20<>""),ROWS(A1:A20)-1,AND(A1<>"",ArrayFormula(A2:A20=""),A21<>""),ROWS(A1:A21)-1,AND(A1<>"",ArrayFormula(A2:A21=""),A22<>""),ROWS(A1:A22)-1,AND(A1<>"",ArrayFormula(A2:A22=""),A23<>""),ROWS(A1:A23)-1,AND(A1<>"",ArrayFormula(A2:A23=""),A24<>""),ROWS(A1:A24)-1,AND(A1<>"",ArrayFormula(A2:A24=""),A25<>""),ROWS(A1:A25)-1,AND(A1<>"",ArrayFormula(A2:A25=""),A26<>""),ROWS(A1:A26)-1,AND(A1<>"",ArrayFormula(A2:A26=""),A27<>""),ROWS(A1:A27)-1,AND(A1<>"",ArrayFormula(A2:A27=""),A28<>""),ROWS(A1:A28)-1,AND(A1<>"",ArrayFormula(A2:A28=""),A29<>""),ROWS(A1:A29)-1,AND(A1<>"",ArrayFormula(A2:A29=""),A30<>""),ROWS(A1:A30)-1,AND(A1<>"",ArrayFormula(A2:A30=""),A31<>""),ROWS(A1:A31)-1,AND(A1<>"",ArrayFormula(A2:A31=""),A32<>""),ROWS(A1:A32)-1,AND(A1<>"",ArrayFormula(A2:A32=""),A33<>""),ROWS(A1:A33)-1,AND(A1<>"",ArrayFormula(A2:A33=""),A34<>""),ROWS(A1:A34)-1,AND(A1<>"",ArrayFormula(A2:A34=""),A35<>""),ROWS(A1:A35)-1,AND(A1<>"",ArrayFormula(A2:A35=""),A36<>""),ROWS(A1:A36)-1,AND(A1<>"",ArrayFormula(A2:A36=""),A37<>""),ROWS(A1:A37)-1,AND(A1<>"",ArrayFormula(A2:A37=""),A38<>""),ROWS(A1:A38)-1,AND(A1<>"",ArrayFormula(A2:A38=""),A39<>""),ROWS(A1:A39)-1,AND(A1<>"",ArrayFormula(A2:A39=""),A40<>""),ROWS(A1:A40)-1,AND(A1<>"",ArrayFormula(A2:A40=""),A41<>""),ROWS(A1:A41)-1,AND(A1<>"",ArrayFormula(A2:A41=""),A42<>""),ROWS(A1:A42)-1,AND(A1<>"",ArrayFormula(A2:A42=""),A43<>""),ROWS(A1:A43)-1,AND(A1<>"",ArrayFormula(A2:A43=""),A44<>""),ROWS(A1:A44)-1,AND(A1<>"",ArrayFormula(A2:A44=""),A45<>""),ROWS(A1:A45)-1,AND(A1<>"",ArrayFormula(A2:A45=""),A46<>""),ROWS(A1:A46)-1,AND(A1<>"",ArrayFormula(A2:A46=""),A47<>""),ROWS(A1:A47)-1,AND(A1<>"",ArrayFormula(A2:A47=""),A48<>""),ROWS(A1:A48)-1, AND(A1<>"",ArrayFormula(A2:A48=""),A49<>""),ROWS(A1:A49)-1, AND(A1<>"",ArrayFormula(A2:A49=""),A50<>""),ROWS(A1:A50)-1)

New Sheet here


来源: stackexchange

问:
Why is my formula returning a number instead of a date?
When trying to add days to a date in another column the value returns as a number, not a date.

I have tried to set the column format as the date for both columns B and C. I also tried using the DATEVALUE() function, but I don't think I used it properly.

```<code>=ARRAYFORMULA(IF(ROW(B:B)=1,"Second Notification",IF(LEN(B:B), B:B+1,)))
</code>```

I want the value in column C to return as a date.

答:
use this with TEXT formula:

```<code>={"Second Notification";
 ARRAYFORMULA(IF(LEN(B2:B), TEXT(B2:B+1, "MM/dd/yyyy hh:mm:ss"), ))}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When trying to add days to a date in another column the value returns as a number, not a date.

I have tried to set the column format as the date for both columns B and C. I also tried using the DATEVALUE() function, but I don't think I used it properly.

=ARRAYFORMULA(IF(ROW(B:B)=1,"Second Notification",IF(LEN(B:B), B:B+1,)))

I want the value in column C to return as a date.

Body:
use this with TEXT formula:

={"Second Notification";
 ARRAYFORMULA(IF(LEN(B2:B), TEXT(B2:B+1, "MM/dd/yyyy hh:mm:ss"), ))}


问:
Windowed/ sliding mean filter accounting for valid members at boundary
Is there a similar function to scipy.ndimage's uniform_filter or convolve (similar problem with Numpy Two-Dimensional Moving Average), but the average is calculated using only the values in the input array (disregard count of fill values for corner and edge cells). A similar function wherein the fill value can be set to np.nan and the resulting average is calculated as np.nanmean?

My initial code loops over the array to get the neighbors and calculate the resulting mean, but this method takes too long. I have tried both uniform_filter or convolve, but the results are not what I needed since the resulting corner and edge values are too low (due to filling the edges with 0).

For example, if I have the array:

a = np.ones((4,5))
```

<p>Calculating the mean value from a moving 3x3 array should also result to:</p>

<pre class="lang-py prettyprint-override"><code>array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])
</code>```

uniform_filter gives:

uniform_filter(a, size=3, mode='constant', cval=0.0)

array([[0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444]])
```

<p>I have tried setting cval=np.nan but the resulting values of the cell edges are nan.</p>

<p>For another array, b</p>

<pre class="lang-py prettyprint-override"><code>array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
</code>```

I want to obtain an array, using a 3x3 averaging-window, as

array([[0.25      , 0.16666667, 0.        ],
       [0.16666667, 0.11111111, 0.        ],
       [0.        , 0.        , 0.        ]])
```

The values are calculated as shown in this
illustration

答:
Try changing the code as

```<code>uniform_filter(a, size=3, mode='wrap')
</code>```

This should avoid the problem of padding with zeros for the edge values

Check out this for other modes which you might prefer:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter.html

Body:
Is there a similar function to scipy.ndimage's uniform_filter or convolve (similar problem with Numpy Two-Dimensional Moving Average), but the average is calculated using only the values in the input array (disregard count of fill values for corner and edge cells). A similar function wherein the fill value can be set to np.nan and the resulting average is calculated as np.nanmean?

My initial code loops over the array to get the neighbors and calculate the resulting mean, but this method takes too long. I have tried both uniform_filter or convolve, but the results are not what I needed since the resulting corner and edge values are too low (due to filling the edges with 0).

For example, if I have the array:

a = np.ones((4,5))

Calculating the mean value from a moving 3x3 array should also result to:

array([[1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.],
       [1., 1., 1., 1., 1.]])

uniform_filter gives:

uniform_filter(a, size=3, mode='constant', cval=0.0)

array([[0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.66666667, 1.        , 1.        , 1.        , 0.66666667],
       [0.44444444, 0.66666667, 0.66666667, 0.66666667, 0.44444444]])

I have tried setting cval=np.nan but the resulting values of the cell edges are nan.

For another array, b

array([[1., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])

I want to obtain an array, using a 3x3 averaging-window, as

array([[0.25      , 0.16666667, 0.        ],
       [0.16666667, 0.11111111, 0.        ],
       [0.        , 0.        , 0.        ]])

The values are calculated as shown in this
illustration

Body:
Try changing the code as

uniform_filter(a, size=3, mode='wrap')

This should avoid the problem of padding with zeros for the edge values

Check out this for other modes which you might prefer:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.uniform_filter.html


问:
Ubuntu 16.04 Compile VLC for Android Failed
Dears,
Recently, I am confused with how to compile vlc for android successful. I try to https://wiki.videolan.org/AndroidCompile on my Ubuntu 16.04, but failed. I get the tips like:

```<code>make[2]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/po'
Making install in share
make[2]: Entering directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
  GEN      vlc.appdata.xml
make[3]: Entering directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
make[3]: Nothing to be done for `install-exec-am'.
  GEN      vlc.appdata.xml
 /bin/mkdir -p '/home/vlc-android/vlc/build-android-arm-linux-androideabi/install/share/metainfo'
 /usr/bin/install -c -m 644 ../../share/vlc.appdata.xml '/home/vlc-android/vlc/build-android-arm-linux-androideabi/install/share/metainfo'
/usr/bin/install: cannot stat '../../share/vlc.appdata.xml': No such file or directory
make[3]: *** [install-appdataDATA] Error 1
make[3]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
make[2]: *** [install-am] Error 2
make[2]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
make[1]: *** [install-recursive] Error 1
make[1]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi'
make: *** [install] Error 2
vlc: make install failed
</code>```

I had upgrade protobuf to version 3.6.1.

答:
I was able to get a build by running cp vlc/share/vlc.appdata.xml.in.in vlc/share/vlc.appdata.xml

Have yet to test the built library

Body:
Dears,
Recently, I am confused with how to compile vlc for android successful. I try to https://wiki.videolan.org/AndroidCompile on my Ubuntu 16.04, but failed. I get the tips like:

make[2]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/po'
Making install in share
make[2]: Entering directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
  GEN      vlc.appdata.xml
make[3]: Entering directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
make[3]: Nothing to be done for `install-exec-am'.
  GEN      vlc.appdata.xml
 /bin/mkdir -p '/home/vlc-android/vlc/build-android-arm-linux-androideabi/install/share/metainfo'
 /usr/bin/install -c -m 644 ../../share/vlc.appdata.xml '/home/vlc-android/vlc/build-android-arm-linux-androideabi/install/share/metainfo'
/usr/bin/install: cannot stat '../../share/vlc.appdata.xml': No such file or directory
make[3]: *** [install-appdataDATA] Error 1
make[3]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
make[2]: *** [install-am] Error 2
make[2]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi/share'
make[1]: *** [install-recursive] Error 1
make[1]: Leaving directory `/home/vlc-android/vlc/build-android-arm-linux-androideabi'
make: *** [install] Error 2
vlc: make install failed

I had upgrade protobuf to version 3.6.1.


问:
Flex box rendering like a column when it should be a row
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

```

I've used flex box plenty of times before, but never seen it behave like this.

答:
In nav a {...} replace display: flex; out of display: inline-flex;

Here's the effect:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

```

Body:
I am putting together what should be a simple nav bar and styling with flex box. For some reason, instead of displaying as a row (horizontal), it is showing as a column (vertical).

I can make the links go horizontal using float:left, but then they don't stretch evenly to fill the nav bar.

My understanding is that flex-grow:1 should make each item occupy an equal amount of space. But this is not happening.

There are four declarations that are not working as expected:

flex-direction The links within the nav bar are in a column instead of a row

padding Although the nav bar's padding is set to zero, it still appears to have padding

text-align The text within each
 is not getting horizontally centered

flex-grow The links are not spacing out evenly

I'm not sure if they are all stemming from to one problem, or each separate problems.

Here is a simplified snippet:

<!doctype html>

<meta charset="utf-8">
<title>Curse of the Nav Bar</title>

Once

Upon

A Time

There

Was

A Problematic

Nav Bar

I've used flex box plenty of times before, but never seen it behave like this.

Body:
In nav a {...} replace display: flex; out of display: inline-flex;

Here's the effect:

<!doctype html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>Curse of the Nav Bar</title>
<style>
nav {
 display: flex;
 flex-direction: row; /* not working */
 background-color: #d2d6d6;
 padding: 0; /* not working */
}
nav a {
 display: inline-flex;
 text-decoration: none;
 list-style: none;
 border: 2px solid #727171;
 color: #727171;
 background-color: #c4c4c4;
 padding: 4px;
 margin: 2px;
 text-align: center; /* not working */
 flex-grow: 1; /* not working */
}
nav a:hover,
nav a:active {
 background-color: #aaa;
}
</style>
</head>

<body>
<nav>
 <ul>
  <a href="#"><li>Once</li></a>
  <a href="#"><li>Upon</li></a>
  <a href="#"><li>A Time</li></a>
  <a href="#"><li>There</li></a>
  <a href="#"><li>Was</li></a>
  <a href="#"><li>A Problematic</li></a>
  <a href="#"><li>Nav Bar</li></a>
 </ul>
</nav>
</body>
</html>


问:
Responsive background images bootstrap 3
I am using bootstrap and am trying to make my background images responsive, but its just not working! Here is my code...

html

```<code><div class="row">
    <div class="bg">
        <img src="../img/home_bg.jpg" alt="home background image">
    </div><!-- /.bg -->
</div><!-- /.row -->
</code>```

css

```<code>.bg {
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
</code>```

Please help me! Thank you!

答:
            body, html {
                height: 100%;
                margin: 0;
            }

            .bg {
                /* Full height */
                height: 100%;

                /* The image used */
                background-image: url("https://picsum.photos/id/1/200/300");

                /* Center and scale the image nicely */
                background-position: center;
                background-repeat: no-repeat;
                background-size: cover;
            }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div class="container-fluid bg" >

    </div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using bootstrap and am trying to make my background images responsive, but its just not working! Here is my code...

html

css

.bg {
    background-repeat: no-repeat;
    background-position: center center;
    background-attachment: fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Please help me! Thank you!

Body:
            body, html {
                height: 100%;
                margin: 0;
            }

            .bg {
                /* Full height */
                height: 100%;

                /* The image used */
                background-image: url("https://picsum.photos/id/1/200/300");

                /* Center and scale the image nicely */
                background-position: center;
                background-repeat: no-repeat;
                background-size: cover;
            }

    <div class="container-fluid bg" >

    </div>


问:
How to populate Dynamic UITableview Inside dynamic UITableviewCell in swift?
I need to implement the dynamic UITableView inside dynamic UITableviewcell like the below screenshot. Also, all values are dynamic which is coming from the server.

答:
yes exactly you need inner tableview to do this.
  first you have main tableview with card layout cell this should be dynamic cell height.
  in this cell you have topview, inner tableview, bottom view all this view you can take fix height as your layout i see e.g top view is 80 height, bottom view is 80 height and tableview has dynamic height based on number of cell like cell height is 100 and you have total 3 cell so table height is 300 you need to make outlet of tableview height and update it programmatically.

hope this helps you!


问:
How to pass both object and hashmap to model attribute in spring MVC so i can use them at the same time?
I am trying to create an "add Employee form" with basic attributes like name gender email etc which users can fill in

in the form, there will be a  drop down options for departments available where the list will be pre-populated by a linkedhashmap that will be sent over from the controller

I have already added an attribute object type "Employee" onto my model so when i fill in the form

and return to controller, the employee object will be set automatically

Controller.java

```<code>@GetMapping("/showFormForAdd")

public String showFormForAdd(Model theModel) {

    //fetch new list(if any) of departments added
    List<Department> theDepartments = departmentService.getDepartments();

    //Create a linkedhash map to hold our department_id-department name information
    final LinkedHashMap<Integer, String> departmentOptions = departmentService.generateDepartmentOptions(theDepartments);

    // create new employee object and attach to our model atrribute.

            //how to add multiple objects?? doing this so i can pre-populate available departments for selection
    theModel.addAttribute("employee", departmentOptions);

    Employee theEmployee = new Employee();
            //how to add multiple objects?? doing this so when program return control to controller it will help me set the attribute of employees so I can save it into the database
    theModel.addAttribute("employee", theEmployee);

    return "customer-form";
}
</code>```

The problem:
How do i add multiple attributes for example, the employee object and the linkedhashmap onto my model so I can prepopulate the selection box and at the same time have methods available for my controller to set attributes for my employee object and save into my database when I return control to the controller?

any help will be appreciated..thanks!

EDIT:
just an update, every answer provided works..i was getting mixed up.

答:
Instead of using same key to add different object, use different key for different object
for example :</p>

```<code>//use key "departmentOptions" for LinkedHashMap
theModel.addAttribute("departmentOptions", departmentOptions);

Employee theEmployee = new Employee();
//use key "employee" for employee object
theModel.addAttribute("employee", theEmployee);
</code>```

Body:
I am trying to create an "add Employee form" with basic attributes like name gender email etc which users can fill in

in the form, there will be a  drop down options for departments available where the list will be pre-populated by a linkedhashmap that will be sent over from the controller

I have already added an attribute object type "Employee" onto my model so when i fill in the form

and return to controller, the employee object will be set automatically

Controller.java

@GetMapping("/showFormForAdd")

public String showFormForAdd(Model theModel) {

    //fetch new list(if any) of departments added
    List<Department> theDepartments = departmentService.getDepartments();

    //Create a linkedhash map to hold our department_id-department name information
    final LinkedHashMap<Integer, String> departmentOptions = departmentService.generateDepartmentOptions(theDepartments);

    // create new employee object and attach to our model atrribute.

            //how to add multiple objects?? doing this so i can pre-populate available departments for selection
    theModel.addAttribute("employee", departmentOptions);

    Employee theEmployee = new Employee();
            //how to add multiple objects?? doing this so when program return control to controller it will help me set the attribute of employees so I can save it into the database
    theModel.addAttribute("employee", theEmployee);

    return "customer-form";
}

The problem:
How do i add multiple attributes for example, the employee object and the linkedhashmap onto my model so I can prepopulate the selection box and at the same time have methods available for my controller to set attributes for my employee object and save into my database when I return control to the controller?

any help will be appreciated..thanks!

EDIT:
just an update, every answer provided works..i was getting mixed up.

Body:
Instead of using same key to add different object, use different key for different object
for example :

//use key "departmentOptions" for LinkedHashMap
theModel.addAttribute("departmentOptions", departmentOptions);

Employee theEmployee = new Employee();
//use key "employee" for employee object
theModel.addAttribute("employee", theEmployee);


问:
POST Request to upload multipart file in Spring Boot
I'm using spring boot, I need to upload a multipart file (jpg or png file). I need to send a (POST request to upload the multi part file using "postman"), can anyone provide a screen shot of  "postman" of how to set it up to do that or tell me? Thanks.

method :

@RequestMapping(method = RequestMethod.POST, value = "/upload")
 @ResponseBody
 ResponseEntity<?> writeUserProfilePhoto(@PathVariable Long user,  @RequestPart("file") MultipartFile file) throws Throwable {

  byte bytesForProfilePhoto[] = FileCopyUtils.copyToByteArray(file.getInputStream()); //Return an InputStream to read the contents of the file from.

  this.crmService.writeUserProfilePhoto(user, MediaType.parseMediaType(file.getContentType()),bytesForProfilePhoto);

  HttpHeaders httpHeaders = new HttpHeaders();

  URI uriOfPhoto = ServletUriComponentsBuilder.fromCurrentContextPath()
    .pathSegment(("/users" + "/{user}" + "/photo").substring(1))
    .buildAndExpand(Collections.singletonMap("user", user)).toUri();

  httpHeaders.setLocation(uriOfPhoto);
  return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
 }```
</div>
</div>
</p>

<p>and this is how I sent the POST request:<img src="https://i.stack.imgur.com/0xVzO.png" alt="enter image description here"></p>

<p>my configuration class:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@Configuration
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "multipart", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {

 @Autowired
 private MultipartProperties multipartProperties = new MultipartProperties();

 @Bean
 @ConditionalOnMissingBean
 public MultipartConfigElement multipartConfigElement() {
  return this.multipartProperties.createMultipartConfig();
 }

 @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
 @ConditionalOnMissingBean(MultipartResolver.class)
 public StandardServletMultipartResolver multipartResolver() {
  return new StandardServletMultipartResolver();
 }

}</code>```

答:
```<code>@Override
public Response uploadImage(String token, MultipartFile file) {

    long id=tokenUtil.decodeToken(token);
    Optional<User> user=userRepo.findById(id);
    if(!user.isPresent()) {
        throw new UserException(-5, "User does not exists");

    }
    UUID uuid=UUID.randomUUID();
    String uniqueUserId=uuid.toString();
    try {

        Files.copy(file.getInputStream(), fileLocation.resolve(uniqueUserId), StandardCopyOption.REPLACE_EXISTING);
        user.get().setProfilePic(uniqueUserId);
        userRepo.save(user.get());
    }catch (IOException e) {
        e.printStackTrace();
        // TODO: handle exception
    }
    return ResponseHelper.statusResponse(200, "Profile Pic Uploaded Successfully");

}
</code>```

Body:
I'm using spring boot, I need to upload a multipart file (jpg or png file). I need to send a (POST request to upload the multi part file using "postman"), can anyone provide a screen shot of  "postman" of how to set it up to do that or tell me? Thanks.

method :

@RequestMapping(method = RequestMethod.POST, value = "/upload")
 @ResponseBody
 ResponseEntity<?> writeUserProfilePhoto(@PathVariable Long user,  @RequestPart("file") MultipartFile file) throws Throwable {

  byte bytesForProfilePhoto[] = FileCopyUtils.copyToByteArray(file.getInputStream()); //Return an InputStream to read the contents of the file from.

  this.crmService.writeUserProfilePhoto(user, MediaType.parseMediaType(file.getContentType()),bytesForProfilePhoto);

  HttpHeaders httpHeaders = new HttpHeaders();

  URI uriOfPhoto = ServletUriComponentsBuilder.fromCurrentContextPath()
    .pathSegment(("/users" + "/{user}" + "/photo").substring(1))
    .buildAndExpand(Collections.singletonMap("user", user)).toUri();

  httpHeaders.setLocation(uriOfPhoto);
  return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
 }

and this is how I sent the POST request:

my configuration class:

@Configuration
@ConditionalOnClass({ Servlet.class, StandardServletMultipartResolver.class, MultipartConfigElement.class })
@ConditionalOnProperty(prefix = "multipart", name = "enabled", matchIfMissing = true)
@EnableConfigurationProperties(MultipartProperties.class)
public class MultipartAutoConfiguration {

 @Autowired
 private MultipartProperties multipartProperties = new MultipartProperties();

 @Bean
 @ConditionalOnMissingBean
 public MultipartConfigElement multipartConfigElement() {
  return this.multipartProperties.createMultipartConfig();
 }

 @Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
 @ConditionalOnMissingBean(MultipartResolver.class)
 public StandardServletMultipartResolver multipartResolver() {
  return new StandardServletMultipartResolver();
 }

}


问:
Model free or model based deep reinforcement learning for car racing?
I'm new in the field of reinforcement learning. So I'm quite confused with "model based" or "model free" terms.

For example, in a video game, if I want to train an agent (a car) to drive on a racetrack.

If my input is a 256x256x3 first person image of the game, should I use a model free RL algorithm ?

And if I want to do the same, but with a 3rd person view above the racetrack, knowing coordinates, speed of the car and all obstacles, etc..., should I use model based RL ?

Thank you for your time.

答:
In model-based you learn a model of the dynamics of your system and use it for planning or for generating "fake" samples. If you can learn the dynamics well, it can be extremely helpful, but if your model is wrong then it can me disastrous.

That said, there is no general rule for when to use model-free or model-based. Usually it depends on how much prior knowledge you have that can help you learning a good dynamics model.


问:
vim + janus / indent a perl block
using vim + janus (https://github.com/carlhuda/janus)
is enabled by default  in .vim/vimrc

filetype plugin indent on

i'm writing perl, every newline is indented by default.

how i can select a block (or the full document) and
reindent automatically?

答:
To apply the same formatting to the whole document you can use:
gg=G which means "go to the beginning", "reformat" until "end of document".

You can use :help = to get more information on reformatting.

If your block is a paragraph separated by empty line you, can use vip to select it quickly.

See :help text-objects for more information.

Title: vim + janus / indent a perl block


问:
Need to get Array Element
I have a need to get element in the array.</p>

```<code>States =[MiN_LENGTH = 2, MIN_PWD_LENGTH = 8]

var result =  this.States.map(t=> t.MIN_PWD_LENGTH);
</code>```

答:
Hope this stackblitz will help you.

.ts

```<code> States = [{ MiN_LENGTH: 2, MIN_PWD_LENGTH: 8 }];
 test;

ngOnInit() {
 var result = this.States.map(t => t.MIN_PWD_LENGTH);
 this.test = this.States.map(t => t.MIN_PWD_LENGTH);
 console.log('result', result);
}
</code>```

Title: Need to get Array Element

Body:
I have a need to get element in the array.

States =[MiN_LENGTH = 2, MIN_PWD_LENGTH = 8]

var result =  this.States.map(t=> t.MIN_PWD_LENGTH);

Body:
Hope this stackblitz will help you.

.ts

 States = [{ MiN_LENGTH: 2, MIN_PWD_LENGTH: 8 }];
 test;

ngOnInit() {
 var result = this.States.map(t => t.MIN_PWD_LENGTH);
 this.test = this.States.map(t => t.MIN_PWD_LENGTH);
 console.log('result', result);
}


问:
High ram usage and same process showing multiple times?
I made a mediaplayer in Android Studio which uses a Service to control playback.

Now everything works fine and i don't notice any lag even though my logcat says 123 frames where skipped during startup.

I read somewhere that this message can be ignored if it doesn't exceed 300+ frames skipped, but now i'm not so sure anymore because i now read that even 1 frame skipped is too much.

I also compared the ram usage with a mp3 player from the store and i noticed most mediaplayers stay below 10mb memory usage.

But mine exceeds almost 50mb and i have no idea why but if you see at details you can see that there are processes with the same name and alot 'sandboxed_processes'.

So my question is if it's ok that my app almost consumes 50mb memory and what those 'sandboxed_processes' mean.

答:
Question 1 :

it depends on how many resources your application are using and needing .you should really take memory seriously, and you should use as little as possible. Garbage collector will help you to recycle the allocated memory, but you should think about the lifespan of any instance of objects you create, and also about their design so to minimize the structures. Last but not least, Studio allows you to profile the memory allocation of your app, so use it :) .

Question 2 :

Application Sandbox from the official documentation

The Android platform takes advantage of the Linux user-based
  protection to identify and isolate app resources. This isolates apps
  from each other and protects apps and the system from malicious apps.
  To do this, Android assigns a unique user ID (UID) to each Android
  application and runs it in its own process.

Android uses this UID to set up a kernel-level Application Sandbox.
  The kernel enforces security between apps and the system at the
  process level through standard Linux facilities, such as user and
  group IDs that are assigned to apps. By default, apps can't interact
  with each other and have limited access to the operating system. For
  example, if application A tries to do something malicious, such as
  read application B's data or dial the phone without permission (which
  is a separate application), then the operating system protects against
  this behavior because application A does not have the appropriate user
  privileges. The sandbox is simple, auditable, and based on decades-old
  UNIX-style user separation of processes and file permissions.

Because the Application Sandbox is in the kernel, this security model
  extends to native code and to operating system applications. All of
  the software above the kernel, such as operating system libraries,
  application framework, application runtime, and all applications, run
  within the Application Sandbox. On some platforms, developers are
  constrained to a specific development framework, set of APIs, or
  language in order to enforce security. On Android, there are no
  restrictions on how an application can be written that are required to
  enforce security; in this respect, native code is as sandboxed as
  interpreted code.


问:
Trying the find a more semantic way for writing Spring Entity in Kotlin
I have an Spring entity written in Kotlin:

```<code>@Entity
class Book(
    @Id
    var id: Long? = null,
    var title: String? = null, // cannot actually be null, immutable
    var isInStock: Boolean? = null, // cannot actually be null
    var description: String? = null,
 )
</code>```

All the fields must be nullable, because Spring needs to initialize empty objects.

However, this makes using the entity complicated, because I always have to convert the nullable types to their not nullable equivalents. This is not semantic: I would like to really see, which fields can actually be nullable and which ones cannot (or can only be null during the initialization process).

Furthermore, some fields are mutable, but some should never be altered after the entity has been created. It would be nice to use Kotlin's val and var to make this distinction.

So, I would like to work with the following class:

```<code>class BetterBook(
    val id: Long,
    val title: String,
    var isInStock: Boolean,
    var description: String? = null,
 )
</code>```

This way it is very clear which fields are mutable and which fields can be null.

I pondered upon creating a wrapper around Book. Has anybody had a similar thought? Would it be a good solution architecturally?

答:
JPA (not Spring) requires no argument constructors and mutable attributes so there really isn't much you can do on that front.

You could convert or wrap your JPA entities into something that looks more like the classes you actually want, but the likely outcome is that it will just bloat your code without making things easier to use.

You might consider a completely different persistence layer which is more flexible when it comes to constructors. Spring Data JDBC might actually fit the bill. It has some support for immutable entities. It is also very different than JPA which might be a good or a bad thing depending on your opinion about JPA.

Read these two article to get an idea of the basic concepts behind it: https://spring.io/blog/2018/09/17/introducing-spring-data-jdbc and https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates

Body:
I have an Spring entity written in Kotlin:

@Entity
class Book(
    @Id
    var id: Long? = null,
    var title: String? = null, // cannot actually be null, immutable
    var isInStock: Boolean? = null, // cannot actually be null
    var description: String? = null,
 )

All the fields must be nullable, because Spring needs to initialize empty objects.

However, this makes using the entity complicated, because I always have to convert the nullable types to their not nullable equivalents. This is not semantic: I would like to really see, which fields can actually be nullable and which ones cannot (or can only be null during the initialization process).

Furthermore, some fields are mutable, but some should never be altered after the entity has been created. It would be nice to use Kotlin's val and var to make this distinction.

So, I would like to work with the following class:

class BetterBook(
    val id: Long,
    val title: String,
    var isInStock: Boolean,
    var description: String? = null,
 )

This way it is very clear which fields are mutable and which fields can be null.

I pondered upon creating a wrapper around Book. Has anybody had a similar thought? Would it be a good solution architecturally?


问:
Multiple value assignment
```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b
</code>```

and

```<code>a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b
</code>```

Both give different output.
What is the difference between   a, b = b, a+b  and a = b; b = a+b?

答:
This is not comma separated values. You are doing tuple unpacking.

```<code>a, b, n = 0, 1, 500
</code>```

Is the same as:

```<code>a, b, n = (0, 1, 500)
</code>```

The reason they are different is the first line assigns b to a then adds a and b together. It’s essentially the same as:

```<code>a = b
b = a+b
</code>```

Title: Multiple value assignment

Body:
a, b, n = 0, 1, 500
while a < n:
    print(a)
    a, b = b, a+b

and

a, b, n = 0, 1, 500
while a < n:
    print(a)
    a = b
    b = a+b

Both give different output.
What is the difference between   a, b = b, a+b  and a = b; b = a+b?

Body:
This is not comma separated values. You are doing tuple unpacking.

a, b, n = 0, 1, 500

Is the same as:

a, b, n = (0, 1, 500)

The reason they are different is the first line assigns b to a then adds a and b together. It’s essentially the same as:

a = b
b = a+b


问:
creating Spring boot starter project
When i create my spring Boot starter project im getting error as maven configuration problem. Please help me to solve.

enter image description here

答:
Similar Bug was reported in eclipse: https://bugs.eclipse.org/bugs/show_bug.cgi?id=547340

You can fix this by temporary downgrading the maven jar plugin version to 3.1.1 from 3.1.2. Add this to the properties section:

```<code><maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</code>```

In your pom.xml

```<code><properties>
    <java.version>1.8</java.version>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
</code>```

Update: A fix has been released. Click Help > Check for updates in Eclipse/STS and install the newest m2e connector.

Title: creating Spring boot starter project

Body:
Similar Bug was reported in eclipse: https://bugs.eclipse.org/bugs/show_bug.cgi?id=547340

You can fix this by temporary downgrading the maven jar plugin version to 3.1.1 from 3.1.2. Add this to the properties section:

<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>

In your pom.xml

<properties>
    <java.version>1.8</java.version>
    <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>

Update: A fix has been released. Click Help > Check for updates in Eclipse/STS and install the newest m2e connector.


问:
If a bash command accepts a filename as the last arg, can piping be used to provide file content?
Say a command takes a filename as its last argument:

```<code>count-words "$word" file.txt
</code>```

Is there a way to use pipe in order to provide file content rather than writing to a temp file?

答:
Each argument, regardless of position, is a character string which the program handles itself after bash executes it. bash can't intervene in that.

Individual programs may provide an option to read from standard input, or do so by default, but if the program doesn't do that you need to point it at a file on the file system.

Body:
Say a command takes a filename as its last argument:

count-words "$word" file.txt

Is there a way to use pipe in order to provide file content rather than writing to a temp file?


问:
How to show notification from broadcast receiver?
I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?

This is Service:

```<code>public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final int NOTIF_ID = 1;

@Override
public void onCreate() {

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
    mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
    registerReceiver(mReceiver, filter);
    super.onCreate();

}
private void startForeground() {
    startForeground(NOTIF_ID, getMyActivityNotification(""));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.startForeground();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {

    if (mReceiver != null) {
        unregisterReceiver(mReceiver);
        mReceiver = null;

        Log.i("onDestroy Reciever", "Called");

    }
    super.onDestroy();

}

public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}

private Notification getMyActivityNotification(String text) {

    CharSequence title = "new";

    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.abc)
                .setContentTitle("Service running")
                .setContentText("new")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();

    }
    return notification;
}
     /*  public void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIF_ID, notification);
      }*/

   }
</code>```

And this is broadcast receiver:

```<code>public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();

private final static String TAG = "LocationProviderChanged";

boolean isGpsEnabled;
boolean isNetworkEnabled;
@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        Log.i(TAG, "Location Providers changed");

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //Start your Activity if location was enabled:
        if (isGpsEnabled || isNetworkEnabled) {

            Log.i(TAG, "Location Providers on");
       }

       else {

              Log.i(TAG, "Location Providers off");
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
                String channelName = "My Background Service";
                NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                chan.setLightColor(Color.BLUE);
                chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(chan);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, notification);

            }
        }
    }
</code>```

I can see logcat messages on changing location status but notification is not created

答:
So basically you need to create a foreground notification and update its contents on location change.

You can use the code below to create a foreground notification:-

```<code>  //for foreground service notification
public Notification showForegroundNotification(String notificationTitle, String notificationBody, Intent intent, ServiceName serviceName) {
    String id = mContext.getString(R.string.upload_notification_channel_id);
    PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
    NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = mContext.getString(R.string.upload_notification_channel_name);
        String description = mContext.getString(R.string.upload_notification_channel_description); //user visible
        int importance = NotificationManager.IMPORTANCE_LOW;

        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(false);
        mChannel.enableVibration(false);
        mChannel.setVibrationPattern(new long[]{0L});
        mChannel.setSound(null, att);

        if (mNotifyManager != null) {
            mNotifyManager.createNotificationChannel(mChannel);
        }

        notificationBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVibrate(new long[]{0L})
                .setSound(null)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setContentTitle(notificationTitle)
                .setAutoCancel(true)
                .setContentIntent(lowIntent);

    } else {
        notificationBuilder.setContentTitle(notificationTitle)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVibrate(new long[]{0L})
                .setSound(null)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setAutoCancel(true)
                .setContentIntent(lowIntent);
    }

    if (notificationBody != null) {
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody));
    }

    notificationBuilder.setContentText(notificationBody);

    return notificationBuilder.build();

}
</code>```

and you need to call startForegroundService();

```<code>  private void startForegroundService(){
        String dataTitle = SharedPrefer.getLastUpdatedLocationName();
        String dataContent = SharedPrefer.getLastUpdatedLocation();

        Intent intent = new Intent(WITHU.getAppContext(), MapLocateActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        startForeground(121, showNotification.showForegroundNotification(dataTitle, dataContent, intent, ServiceName.SMART_LOCATION, -1, false));
    }
</code>```

So it will pass the updated location name and location which you can collect from SharedPreference or also can be called directly onLocationChanged.

Body:
I am registering a broadcast receiver from a service. I need to show notification to user if location of device is off the code works fine but receiver does not create notification. I can see logcat messages on changing location status but notification is not created Please check the issue ! And is there any way to update the current notification of the service?

This is Service:

public class LockService extends Service {
BroadcastReceiver mReceiver;
Handler handler;
LocationManager locationManager;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private static final int NOTIF_ID = 1;

@Override
public void onCreate() {

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    filter.addAction(Intent.ACTION_USER_PRESENT);
    filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
    mReceiver = new com.example.fizatanveerkhan.citycops.ScreenReceiver();
    registerReceiver(mReceiver, filter);
    super.onCreate();

}
private void startForeground() {
    startForeground(NOTIF_ID, getMyActivityNotification(""));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.startForeground();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {

    if (mReceiver != null) {
        unregisterReceiver(mReceiver);
        mReceiver = null;

        Log.i("onDestroy Reciever", "Called");

    }
    super.onDestroy();

}

public class LocalBinder extends Binder {
    LockService getService() {
        return LockService.this;
    }
}

private Notification getMyActivityNotification(String text) {

    CharSequence title = "new";

    Notification notification = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.drawable.abc)
                .setContentTitle("Service running")
                .setContentText("new")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();

    }
    return notification;
}
     /*  public void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(NOTIF_ID, notification);
      }*/

   }

And this is broadcast receiver:

public class ScreenReceiver extends BroadcastReceiver {

public static boolean wasScreenOn = true;

private static final int POWER_OFF_TIMEOUT = 500;
private Handler handler = new Handler();
private Runnable powerOffCounterReset = new PowerOfTimeoutReset();
private int countPowerOff = 0;
private boolean screenOff;
//private LockService updateService = new LockService();

private final static String TAG = "LocationProviderChanged";

boolean isGpsEnabled;
boolean isNetworkEnabled;
@Override
public void onReceive(final Context context, final Intent intent) {
    if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
        Log.i(TAG, "Location Providers changed");

        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        //Start your Activity if location was enabled:
        if (isGpsEnabled || isNetworkEnabled) {

            Log.i(TAG, "Location Providers on");
       }

       else {

              Log.i(TAG, "Location Providers off");
            Notification notification = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String NOTIFICATION_CHANNEL_ID = " com.example.fizatanveerkhan.citycops";
                String channelName = "My Background Service";
                NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
                chan.setLightColor(Color.BLUE);
                chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                assert manager != null;
                manager.createNotificationChannel(chan);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
                notification = notificationBuilder.setOngoing(true)
                        .setSmallIcon(R.drawable.abc)
                        .setContentTitle("Service running")
                        .setContentText("new")
                        .setPriority(NotificationManager.IMPORTANCE_MIN)
                        .setCategory(Notification.CATEGORY_SERVICE)
                        .build();
                NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                mNotificationManager.notify(1, notification);

            }
        }
    }

I can see logcat messages on changing location status but notification is not created

Body:
So basically you need to create a foreground notification and update its contents on location change.

You can use the code below to create a foreground notification:-

  //for foreground service notification
public Notification showForegroundNotification(String notificationTitle, String notificationBody, Intent intent, ServiceName serviceName) {
    String id = mContext.getString(R.string.upload_notification_channel_id);
    PendingIntent lowIntent = PendingIntent.getActivity(mContext, 100, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext, id);
    NotificationManager mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = mContext.getString(R.string.upload_notification_channel_name);
        String description = mContext.getString(R.string.upload_notification_channel_description); //user visible
        int importance = NotificationManager.IMPORTANCE_LOW;

        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build();

        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
        mChannel.setDescription(description);
        mChannel.enableLights(false);
        mChannel.enableVibration(false);
        mChannel.setVibrationPattern(new long[]{0L});
        mChannel.setSound(null, att);

        if (mNotifyManager != null) {
            mNotifyManager.createNotificationChannel(mChannel);
        }

        notificationBuilder
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVibrate(new long[]{0L})
                .setSound(null)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setContentTitle(notificationTitle)
                .setAutoCancel(true)
                .setContentIntent(lowIntent);

    } else {
        notificationBuilder.setContentTitle(notificationTitle)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCategory(NotificationCompat.CATEGORY_SERVICE)
                .setVibrate(new long[]{0L})
                .setSound(null)
                .setColor(ContextCompat.getColor(mContext, R.color.colorPrimary))
                .setAutoCancel(true)
                .setContentIntent(lowIntent);
    }

    if (notificationBody != null) {
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationBody));
    }

    notificationBuilder.setContentText(notificationBody);

    return notificationBuilder.build();

}

and you need to call startForegroundService();

  private void startForegroundService(){
        String dataTitle = SharedPrefer.getLastUpdatedLocationName();
        String dataContent = SharedPrefer.getLastUpdatedLocation();

        Intent intent = new Intent(WITHU.getAppContext(), MapLocateActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
        startForeground(121, showNotification.showForegroundNotification(dataTitle, dataContent, intent, ServiceName.SMART_LOCATION, -1, false));
    }

So it will pass the updated location name and location which you can collect from SharedPreference or also can be called directly onLocationChanged.


问:
Flat File Destination Failed the pre-execute phase. Cannot open the datafile
I am executing a SSIS Package from a C# WinForm project.  It executes and runs about halfway when it tries to create/write a file (An Expression in the Flat File Manager).

When I check the SSISDB Catalog on the SQL Server, I see the following errors for the package:

Flat File Destination failed the pre-execute phase and returned error
code 0xC020200E.

PO Header:Error: Cannot open the datafile "\Server\path\Admin Shared
Folders\Information
Systems\Projects\projectPath\filepath\636943168325507712-1070-15175.txt".

Based on the path and filename, the expression resolved fine.  When I run the SSIS package directly it runs fine, so it appears to be a permission issue.

I am using Integration Services (MS SQL Server 2014) and right now I am using windows authentication in my connect string:

```<code>Integrated Security=SSPI;
</code>```

However, the group who will be using the app will not have full permissions, so a specific user account will be created in SQL Server that I will use to connect.  That said, assuming that this is a permission issue, how does the SQL Server account need to be created / what permissions and considerations need to be applied?  What other permission issues/considerations need to be taken into account?

ie, we have no idea how to create the account to make this work and need help!

答: I think you are ask for run with SQL agent and hit permission issue, you can do this, in Windows service there are a service name call SQL Server Agent, and Log on with a special account, likely you create a individual account, and give this account to your folder permission.</p>

Body:
I am executing a SSIS Package from a C# WinForm project.  It executes and runs about halfway when it tries to create/write a file (An Expression in the Flat File Manager).

When I check the SSISDB Catalog on the SQL Server, I see the following errors for the package:

Flat File Destination failed the pre-execute phase and returned error
code 0xC020200E.

PO Header:Error: Cannot open the datafile "\Server\path\Admin Shared
Folders\Information
Systems\Projects\projectPath\filepath\636943168325507712-1070-15175.txt".

Based on the path and filename, the expression resolved fine.  When I run the SSIS package directly it runs fine, so it appears to be a permission issue.

I am using Integration Services (MS SQL Server 2014) and right now I am using windows authentication in my connect string:

Integrated Security=SSPI;

However, the group who will be using the app will not have full permissions, so a specific user account will be created in SQL Server that I will use to connect.  That said, assuming that this is a permission issue, how does the SQL Server account need to be created / what permissions and considerations need to be applied?  What other permission issues/considerations need to be taken into account?

ie, we have no idea how to create the account to make this work and need help!


问:
How to find pairs in the below given table
Find all pairs of frequent words that occur in the same document id and report the number of documents the pair occurs in. Report the pairs in decreasing order of frequency.

Note there should not be any replicated entries like
o (truck, boat) (truck, boat)

Note you should not have the same pair occurring twice in opposite order. Only one
of the following should occur:
o (truck, boat) (boat, truck)

```<code>+-------+-----+-----+---------+
|vocabId|docId|count|     word|
+-------+-----+-----+---------+
|      1|    1| 1000|    plane|
|      1|    3|  100|    plane|
|      3|    1| 1200|motorbike|
|      3|    2|  702|motorbike|
|      3|    3|  600|motorbike|
|      5|    3| 2000|     boat|
|      5|    2|  200|     boat|
+-------+-----+-----+---------+
</code>```

I have used this query but it is giving me the wrong result

```<code>select r1.word,r2.word, count(*)
from result_T r1
JOIN result_T r2 ON r1.docId = r2.docId
and r1.word = r2.word group by r1.word, r2.word
</code>```

Expected Ouput:

```<code>boat, motorbike, 2
motorbike, plane, 2
boat, plane, 1
</code>```

答:
Try below query:</p>

```<code>declare @tbl table (docId int, word varchar(20));
insert into @tbl values
( 1,'plane'),
( 3,'plane'),
( 1,'motorbike'),
( 2,'motorbike'),
( 3,'motorbike'),
( 3,'boat'),
( 2,'boat');

select words, count(*) from (
    select distinct t1.docId,
           case when t1.word < t2.word then t1.word else t2.word end + ',' +
           case when t1.word >= t2.word then t1.word else t2.word end words
    from @tbl t1
    join @tbl t2 on t1.docId = t2.docId and t1.word <> t2.word
) a group by words
order by count(*) desc
</code>```

Body:
Find all pairs of frequent words that occur in the same document id and report the number of documents the pair occurs in. Report the pairs in decreasing order of frequency.

Note there should not be any replicated entries like
o (truck, boat) (truck, boat)

Note you should not have the same pair occurring twice in opposite order. Only one
of the following should occur:
o (truck, boat) (boat, truck)

+-------+-----+-----+---------+
|vocabId|docId|count|     word|
+-------+-----+-----+---------+
|      1|    1| 1000|    plane|
|      1|    3|  100|    plane|
|      3|    1| 1200|motorbike|
|      3|    2|  702|motorbike|
|      3|    3|  600|motorbike|
|      5|    3| 2000|     boat|
|      5|    2|  200|     boat|
+-------+-----+-----+---------+

I have used this query but it is giving me the wrong result

select r1.word,r2.word, count(*)
from result_T r1
JOIN result_T r2 ON r1.docId = r2.docId
and r1.word = r2.word group by r1.word, r2.word

Expected Ouput:

boat, motorbike, 2
motorbike, plane, 2
boat, plane, 1

Body:
Try below query:

declare @tbl table (docId int, word varchar(20));
insert into @tbl values
( 1,'plane'),
( 3,'plane'),
( 1,'motorbike'),
( 2,'motorbike'),
( 3,'motorbike'),
( 3,'boat'),
( 2,'boat');

select words, count(*) from (
    select distinct t1.docId,
           case when t1.word < t2.word then t1.word else t2.word end + ',' +
           case when t1.word >= t2.word then t1.word else t2.word end words
    from @tbl t1
    join @tbl t2 on t1.docId = t2.docId and t1.word <> t2.word
) a group by words
order by count(*) desc


问:
Where is the aws key management plugin for MariaDB on Ubuntu 18.04?
I followed the instructions here https://mariadb.com/kb/en/library/aws-key-management-encryption-plugin-setup-guide/#installation and added the appropriate repository for MariaDB to my Ubuntu 18.04 installation. I then tried to install the aws key management plugin, but that package can't be found. I've spent a lot of time on Google trying to figure out where it is, and I still can't figure out how to install it.

Has anyone run into this issue and/or does anyone know how I can get this plugin installed? I've downloaded the list of packages and can't find anything related to aws.

答:
For those of you that use Docker, I created a Docker image that builds the AWS Key Management Plugin from source. The resulting aws_key_management.so is compatible with the Docker official images for MariaDB.

To make aws_key_management.so, do the following:

```<code>docker run --name aws_key_management_build creemama/mariadb-aws_key_management-plugin-build:latest
docker cp aws_key_management_build:/usr/local/src/build-mariadb/plugin/aws_key_management/aws_key_management.so .
</code>```

Examine the Dockerfile for the steps used to build the plugin.

Body:
For those of you that use Docker, I created a Docker image that builds the AWS Key Management Plugin from source. The resulting aws_key_management.so is compatible with the Docker official images for MariaDB.

To make aws_key_management.so, do the following:

docker run --name aws_key_management_build creemama/mariadb-aws_key_management-plugin-build:latest
docker cp aws_key_management_build:/usr/local/src/build-mariadb/plugin/aws_key_management/aws_key_management.so .

Examine the Dockerfile for the steps used to build the plugin.


问:
Where to sync redux store and firebase?
I recently started learning react and redux and am confused as how to sync the data? I'm using create-react-app and redux-thunk.

Suppose I'm making a todolist. So should I add a task into redux and update the entire store to firebase using store.subscribe in index.js?

Or should I update the firebase store and then update the redux store? I think this would be the better method as the application would move only in response to the firebase store. But this approach slows the application re-render as the data change has to wait for the async request to finish which isn't good on a slow internet connection. And would make the user experience slow.
Like this.

```<code>export const startAddTaskAction = (task) => {
  return (dispatch, getState) => {
    database.ref('tasks').push(task)
        .then(() => {
            dispatch(addTaskAction(task));
        });
  };
};
</code>```

Or do I update both simultaneously in the redux store and in firebase in the dispatch? But then what if the users internet connection fails? Firebase won't be able to write to itself but redux would show the task as saved?
Like this:

```<code>export const startAddTaskAction = (task) => {
  return (dispatch, getState) => {
    database.ref('tasks').push(task);
    dispatch(addTaskAction(task));
  };
};
</code>```

Which way should I do this and why is it better then the others?

答:
Go with First one you should wait until you push the data into firebase that is the best practice to do.

Let me explain the cases why you should do in this way

What if there is no connection at all user able to add all tasks but at the end when he reload the page he will be surprised that there is no data at all.

For all crud we use _id which is generated by databases if you don't hit the server you don't even get data at all.

Rather than giving unpredictable results to users it's better to let him wait put some time interval to api if it exceeds show some message net connection is slow

Title: Where to sync redux store and firebase?

Body:
I recently started learning react and redux and am confused as how to sync the data? I'm using create-react-app and redux-thunk.

Suppose I'm making a todolist. So should I add a task into redux and update the entire store to firebase using store.subscribe in index.js?

Or should I update the firebase store and then update the redux store? I think this would be the better method as the application would move only in response to the firebase store. But this approach slows the application re-render as the data change has to wait for the async request to finish which isn't good on a slow internet connection. And would make the user experience slow.
Like this.

export const startAddTaskAction = (task) => {
  return (dispatch, getState) => {
    database.ref('tasks').push(task)
        .then(() => {
            dispatch(addTaskAction(task));
        });
  };
};

Or do I update both simultaneously in the redux store and in firebase in the dispatch? But then what if the users internet connection fails? Firebase won't be able to write to itself but redux would show the task as saved?
Like this:

export const startAddTaskAction = (task) => {
  return (dispatch, getState) => {
    database.ref('tasks').push(task);
    dispatch(addTaskAction(task));
  };
};

Which way should I do this and why is it better then the others?


问:
How to replace all newlines after reading a file
How can I replace a newline in a string with a ','? I have a string that is read from a file:

```<code>const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);
</code>```

It takes a string from a file:

```<code>a,b,c,d,e,f
,,,,,
g,h,i,j,k,l
</code>```

I'm able to detect the newline with this:

```<code>if (char === '\n')
</code>```

But replacing \n like this doesn't work

```<code>str = csvString.replace('/\n/g');
</code>```

I want to get the string to look like this:

```<code>a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,
</code>```

答:
You may try out like,

// Let us have some sentences havin linebreaks as \n.

let statements = " Programming is so cool. \n We love to code. \n We can built what we want. \n :)";

// We will console it and see that they are working fine.
console.log(statements);

// We may replace the string via various methods which are as follows,

// FIRST IS USING SPLIT AND JOIN
let statementsWithComma1 = statements.split("\n").join(",");

// RESULT
console.log("RESULT1 : ", statementsWithComma1);

// SECOND IS USING REGEX
let statementsWithComma2 = statements.replace(/\n/gi, ',');

// RESULT
console.log("RESULT2 : ", statementsWithComma2);

// THIRS IS USING FOR LOOP
let statementsWithComma3 = "";

for(let i=0; i < statements.length; i++){
  if(statements[i] === "\n")
    statementsWithComma3 += ','
  else
    statementsWithComma3 += statements[i]
}

// RESULT
console.log("RESULT3 : ", statementsWithComma3);```

Body:
How can I replace a newline in a string with a ','? I have a string that is read from a file:

const fileText = (<FileReader>fileLoadedEvent.target).result.toString();
file.readCSV(fileText);

It takes a string from a file:

a,b,c,d,e,f
,,,,,
g,h,i,j,k,l

I'm able to detect the newline with this:

if (char === '\n')

But replacing \n like this doesn't work

str = csvString.replace('/\n/g');

I want to get the string to look like this:

a,b,c,d,e,f,
,,,,,,
g,h,i,j,k,l,


问:
How to routing for mobile view in express
I want to change the URL for mobile. www.example.com to m.example.com

I use isMobile function to detect device type.
I do not know what to do for routing.
for example: m.example.com/index

please help me

in app.js

```<code>function isMobile(req, res, next) {
if ((/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(req.headers["user-agent"]))) {
res.redirect('//m.' + req.host+ req.path);
} else {
next()
}
}

app.get('/',isMobile,routes.index);
</code>```

If device is a mobile,i want to run routes.mobileindex. How?

答:
If you want to render a separate view for mobile devices in the same application then it would be pretty straigh forward. it is a just a matter of creating another view file and you can apply your separate layout and CSS style to design it.

```<code>var express = require("express");
var router = express.Router();

function isMobile(req, res, next) {
  if (
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(
      req.headers["user-agent"]
    )
  ) {
    // Instead of redirecting to another view you can also render a separate
    // view for mobile view e.g. res.render('mobileview');

    res.redirect("/mobile/device");
  } else {
    next();
  }
}

/* GET home page. */
router.get("/", function(req, res, next) {
  res.render("index", {
    title: "Express"
  });
});

router.get("/device", isMobile, function(req, res, next) {
  res.json("normal view is rendered");
});

router.get("/mobile/device", function(req, res, next) {
  res.render("mobile");
});
module.exports = router;
</code>```

I have set a redirection here but this is not the best way if you are in the same application, because you can directly hit /mobile/device view, in that case you also need a middleware or can reuse the isMobile middleware to redirect to normal view. I would rather suggest to use res.render('yourviewname')

Hope this gives you an idea to proceed futher!

Body:
I want to change the URL for mobile. www.example.com to m.example.com

I use isMobile function to detect device type.
I do not know what to do for routing.
for example: m.example.com/index

please help me

in app.js

function isMobile(req, res, next) {
if ((/Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(req.headers["user-agent"]))) {
res.redirect('//m.' + req.host+ req.path);
} else {
next()
}
}

app.get('/',isMobile,routes.index);

If device is a mobile,i want to run routes.mobileindex. How?

Body:
If you want to render a separate view for mobile devices in the same application then it would be pretty straigh forward. it is a just a matter of creating another view file and you can apply your separate layout and CSS style to design it.

var express = require("express");
var router = express.Router();

function isMobile(req, res, next) {
  if (
    /Android|webOS|iPhone|iPad|iPod|BlackBerry|BB|PlayBook|IEMobile|Windows Phone|Kindle|Silk|Opera Mini/i.test(
      req.headers["user-agent"]
    )
  ) {
    // Instead of redirecting to another view you can also render a separate
    // view for mobile view e.g. res.render('mobileview');

    res.redirect("/mobile/device");
  } else {
    next();
  }
}

/* GET home page. */
router.get("/", function(req, res, next) {
  res.render("index", {
    title: "Express"
  });
});

router.get("/device", isMobile, function(req, res, next) {
  res.json("normal view is rendered");
});

router.get("/mobile/device", function(req, res, next) {
  res.render("mobile");
});
module.exports = router;

I have set a redirection here but this is not the best way if you are in the same application, because you can directly hit /mobile/device view, in that case you also need a middleware or can reuse the isMobile middleware to redirect to normal view. I would rather suggest to use res.render('yourviewname')

Hope this gives you an idea to proceed futher!


问:
How can I individually replace each occurence of a string?
I am trying to replace every occurrence of a space with two random characters (out of 103). The problem is that it is always the same 2 characters every time, which makes sense if you look at the code

I'm pretty new to  Swift and Xcode and I've already tried a bunch of things, like using a "for" loop.

```<code>newSentence = passedSentence.replacingOccurrences(of: " ", with: " \(randomArray[Int.random(in: 0...103)]) \(randomArray[Int.random(in: 0...103)]) ")
resultText.text = newSentence
</code>```

As I said before, it is always the same 2 characters when I want it to "refresh" for every occurrence of a space.

答:
Yes, your behavior is expected given your code. The parameter passed in with: is only executed once so if it generates "SX", that will be used to replace ALL the occurrences of " "(space) in your passedSentence.

To get your expected behavior, you would have to loop:

```<code>var rangeOfEmptyString = passedSentence.range(of: " ")
while rangeOfEmptyString != nil {
   let randomModifier = "\(randomArray[Int.random(in: 0...103)])\(randomArray[Int.random(in: 0...103)])"
   passedSentence = passedSentence.replacingCharacters(in: rangeOfEmptyString!, with: randomModifier)
   rangeOfEmptyString = passedSentence.range(of: " ")
}

</code>```

Body:
I am trying to replace every occurrence of a space with two random characters (out of 103). The problem is that it is always the same 2 characters every time, which makes sense if you look at the code

I'm pretty new to  Swift and Xcode and I've already tried a bunch of things, like using a "for" loop.

newSentence = passedSentence.replacingOccurrences(of: " ", with: " \(randomArray[Int.random(in: 0...103)]) \(randomArray[Int.random(in: 0...103)]) ")
resultText.text = newSentence

As I said before, it is always the same 2 characters when I want it to "refresh" for every occurrence of a space.

Body:
Yes, your behavior is expected given your code. The parameter passed in with: is only executed once so if it generates "SX", that will be used to replace ALL the occurrences of " "(space) in your passedSentence.

To get your expected behavior, you would have to loop:

var rangeOfEmptyString = passedSentence.range(of: " ")
while rangeOfEmptyString != nil {
   let randomModifier = "\(randomArray[Int.random(in: 0...103)])\(randomArray[Int.random(in: 0...103)])"
   passedSentence = passedSentence.replacingCharacters(in: rangeOfEmptyString!, with: randomModifier)
   rangeOfEmptyString = passedSentence.range(of: " ")
}


问:
Renaming columns in pandas dataframe during groupby operation
I tried to rename the column that has been obtained as the result of groupby & count operation like below:

```<code>dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()
print(dfa[:1])
</code>```

the output obtained is

```<code> Product_ID     0
0  P00000142  1130
</code>```

The column names are not what I specified. So I changed it again using the below command

```<code>dfa.columns =['product','sales']
print(dfa[:1])

 product  sales
0  P00000142   1130
</code>```

Then I got the expected column names. However I believe it shall be obtained during the first method dataframe.rename itself. What is wrong in the 1st code snippet dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()that I did not get the expected output.

答:
As mentioned in comments, you need:</p>

```<code>df.groupby('Product_ID').size().reset_index(name='sales_count')
</code>```

Body:
I tried to rename the column that has been obtained as the result of groupby & count operation like below:

dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()
print(dfa[:1])

the output obtained is

 Product_ID     0
0  P00000142  1130

The column names are not what I specified. So I changed it again using the below command

dfa.columns =['product','sales']
print(dfa[:1])

 product  sales
0  P00000142   1130

Then I got the expected column names. However I believe it shall be obtained during the first method dataframe.rename itself. What is wrong in the 1st code snippet dfa = df.groupby('Product_ID').Product_ID.count().rename(columns={0: "Product",1:"Sale_count"}).reset_index()that I did not get the expected output.

Body:
As mentioned in comments, you need:

df.groupby('Product_ID').size().reset_index(name='sales_count')


问:
Need to swap 2 lines
For each instance of the below code (have many) I need to swap the "userId" line with the "screen_name" line so "screen_name" line is above "userId" line.</p>

```<code>{
  active: true,
  userId: '14053424',
  screen_name: '0xstark',
  maxTopTweets: 2,
  minLikesCount: 2,
  keywordsToReject: [],
  keywords: [],
  useDefaultKeywords: true,
  useDefaultRejectKeywords: true,
  useStrictKeywords: false,
  defaultPhoto: null,
},
</code>```

答:
This might work for you  (GNU sed):

```<code>sed '/userId:/{h;d};/screen_name:/G' file
</code>```

Save the userId line in the hold space and append it to the screen_name line.

N.B. Assumes the userId always precedes the screen_name line.

Title: Need to swap 2 lines

Body:
For each instance of the below code (have many) I need to swap the "userId" line with the "screen_name" line so "screen_name" line is above "userId" line.

{
  active: true,
  userId: '14053424',
  screen_name: '0xstark',
  maxTopTweets: 2,
  minLikesCount: 2,
  keywordsToReject: [],
  keywords: [],
  useDefaultKeywords: true,
  useDefaultRejectKeywords: true,
  useStrictKeywords: false,
  defaultPhoto: null,
},

Body:
This might work for you  (GNU sed):

sed '/userId:/{h;d};/screen_name:/G' file

Save the userId line in the hold space and append it to the screen_name line.

N.B. Assumes the userId always precedes the screen_name line.


问:
logical problem for finding the probability
hi to all

 I want to know how to find the solution for this problem. consider in a Jar there are 10 papers numbered 1 to 10. we have to take 2 papers from that. what is the probability that 2 numbers are consecutive numbers.

答: It's a probability to choose one of 9 consecutive pairs from C(10, 2) possible pairs. Thus its 9 / (10*9 / 2) = 1 /5 </p>


问:
Selenium - Maven/TestNG: how can we add testng parameters in Java class while adding "main method" to create executable /runnable.jar file?
I have project with TestNG, Maven.

I am passing parameters in testng.xml file. Added "main method" for testng config to create executable .jar file.

I have referred -- Running TestNG programmatically. But no method is present there for passing parameters or maybe I have missed that one.

This is how my main method looks like:

```<code>public static void main(String[] args) {
 ExtentReportListener extentReport = new ExtentReportListener();
 TestNG testng = new TestNG();
 testng.setTestClasses(new Class[] {FirstTest.class});
 testng.addListener(extentReport);
 testng.run();
}
</code>```

Please help me out to pass parameters in main method itself. Let me know if you need more info.

答:
First of all you have String[] args. It's array of passed parameters. So if you're running:

java -jar your_jar.jar param1 param2

you automatically obtain args[0]="param1" and args[1]="param2"

You also can use a system properties.

Running

java -jar your_jar.jar -Dparam1=12 -Dparam2=13

You can call System.getProperty("param1") from anywhere and it will return you "12".

And... Imho the best way to run TestNG project programmaticaly is using of maven/gradle surefire plugin.

Body:
I have project with TestNG, Maven.

I am passing parameters in testng.xml file. Added "main method" for testng config to create executable .jar file.

I have referred -- Running TestNG programmatically. But no method is present there for passing parameters or maybe I have missed that one.

This is how my main method looks like:

public static void main(String[] args) {
 ExtentReportListener extentReport = new ExtentReportListener();
 TestNG testng = new TestNG();
 testng.setTestClasses(new Class[] {FirstTest.class});
 testng.addListener(extentReport);
 testng.run();
}

Please help me out to pass parameters in main method itself. Let me know if you need more info.


问:
Unable to import databinding class in Android Studio
I am unable to import the databinding class.

Here's my build.gradle

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.test1"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        dataBinding {
            enabled = true
        }

    }

      .......
</code>```

And here's my MainActivity.kt

```<code>package com.example.test1

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.example.test1.databinding // <-- Shows ERROR in this line

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
</code>```

here's my activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
<android.support.constraint.ConstraintLayout

        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>
</layout>

</code>```

I have synced the Gradle, I have also tried restarting Android Studio, but it simply won't work.

What should I do??

答:
Change binding position:</p>

```<code>android {
    compileSdkVersion 28
    dataBinding {
        enabled = true
    }

    defaultConfig {
        applicationId "com.example.test1"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
</code>```

Body:
I am unable to import the databinding class.

Here's my build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.test1"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        dataBinding {
            enabled = true
        }

    }

      .......

And here's my MainActivity.kt

package com.example.test1

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.example.test1.databinding // <-- Shows ERROR in this line

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

here's my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">
<android.support.constraint.ConstraintLayout

        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</android.support.constraint.ConstraintLayout>
</layout>

I have synced the Gradle, I have also tried restarting Android Studio, but it simply won't work.

What should I do??

Body:
Change binding position:

android {
    compileSdkVersion 28
    dataBinding {
        enabled = true
    }

    defaultConfig {
        applicationId "com.example.test1"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}