答:
A short sample bytestring substitute for a file:

```<code>In [168]: txt = b"""Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81
     ...: """
</code>```

Minimal load with correct delimiter.  Note the first column is nan, because it can't convert the strings to float.

```<code>In [169]: np.genfromtxt(txt.splitlines(),delimiter='\t')
Out[169]:
array([[  nan, -0.22, -0.12, -0.29, -0.51, -0.81],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81]])
</code>```

with dtype=None it sets each column dtype automatically, creating a structured array:

```<code>In [170]: np.genfromtxt(txt.splitlines(),delimiter='\t',dtype=None)
Out[170]:
array([(b'Y7C', -0.22, -0.12, -0.29, -0.51, -0.81),
       (b'Y7C', -0.22, -0.12, -0.29, -0.51, -0.81),
       (b'Y7C', -0.22, -0.12, -0.29, -0.51, -0.81)],
      dtype=[('f0', 'S3'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8'), ('f5', '<f8')])
</code>```

Spell out the columns to use, skipping the first:

```<code>In [172]: np.genfromtxt(txt.splitlines(),delimiter='\t',usecols=np.arange(1,6))
Out[172]:
array([[-0.22, -0.12, -0.29, -0.51, -0.81],
       [-0.22, -0.12, -0.29, -0.51, -0.81],
       [-0.22, -0.12, -0.29, -0.51, -0.81]])
</code>```

But if I ask for more columns that it finds I get an error, like yours:

```<code>In [173]: np.genfromtxt(txt.splitlines(),delimiter='\t',usecols=np.arange(1,7))
---------------------------------------------------------------------------
....
ValueError: Some errors were detected !
    Line #1 (got 6 columns instead of 6)
    Line #2 (got 6 columns instead of 6)
    Line #3 (got 6 columns instead of 6)
</code>```

Your missing_values parameters doesn't help; that's the wrong use for that

This is the correct use of missing_values - to detect the string value and replace it with a valid float value:

```<code>In [177]: np.genfromtxt(txt.splitlines(),delimiter='\t',missing_values='Y7C',filling_val
     ...: ues=0)
Out[177]:
array([[ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81]])
</code>```

If the file has sufficient delimiters, it can treat those as missing values

```<code>In [178]: txt = b"""Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81\t\t
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81\t\t
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81\t\t
     ...: """
In [179]: np.genfromtxt(txt.splitlines(),delimiter='\t')
Out[179]:
array([[  nan, -0.22, -0.12, -0.29, -0.51, -0.81,   nan,   nan],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81,   nan,   nan],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81,   nan,   nan]])
In [180]: np.genfromtxt(txt.splitlines(),delimiter='\t',filling_values=0)
Out[180]:
array([[ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81,  0.  ,  0.  ],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81,  0.  ,  0.  ],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81,  0.  ,  0.  ]])
</code>```

I believe the pandas csv reader can handle 'ragged' columns and missing values better.

Title: loading my data in numpy genfromtxt get errors

Body:
I have my data file contain 7500 lines with :

Y1C 1.53    -0.06   0.58    0.52    0.42    0.16    0.79        -0.6    -0.3
-0.78   -0.14   0.38    0.34    0.23    0.26    -1.8    -0.1    -0.17   0.3
0.6 0.9 0.71    0.5 0.49    1.06    0.25    0.96    -0.39   0.24    0.69
0.41    0.7 -0.16   -0.39   0.6 1.04    0.4 -0.04   0.36    0.23    -0.14
-0.09   0.15    -0.46   -0.05   0.32    -0.54   -0.28   -0.15   1.34    0.29
0.59    -0.43   -0.55   -0.18   -0.01   0.68        -0.06   -0.11   -0.67
-0.25   -0.34   -0.38   0.02    -0.21   0.12    0.01    0.07    0.15    0.14
0.15    -0.11   0.07    -0.41   -0.2    0.24    0.06    0.12    0.12    0.11
0.1 0.24    -0.71   0.22    -0.02   0.15    0.84    1.39    0.13    0.48
0.19    -0.23   -0.12   0.33    0.37    0.18    0.06    0.32    0.09
-0.09   0.02    -0.01   -0.06   -0.23   0.52    0.14    0.24    -0.05   0.37
0.1 0.45    0.38    1.34    0.74    0.5 0.92    0.91    1.34    1.78    2.26
0.05    0.29    0.53    0.17    0.41    0.47    0.47    1.21    0.87    0.68
1.08    0.89    0.13    0.5 0.57    -0.5    -0.78   -0.34   -0.3    0.54
0.31    0.64    1.23    0.335   0.36    -0.65   0.39    0.39    0.31    0.73
0.54    0.3 0.26    0.47    0.13    0.24    -0.6    0.02    0.11    0.27
0.21    -0.3    -1  -0.44   -0.15   -0.51   0.3 0.14    -0.15   -0.27   -0.27

Y2W -0.01   -0.3    0.23    0.01    -0.15   0.45    -0.04   0.14    -1.16
-0.14   -0.56   -0.13   0.77    0.77    -0.57   0.48    0.22    -0.08
-1.81   -0.46   -0.17   0.2 -0.18   -0.45   -0.4    1.35    0.81    1.21
0.52    0.02    -0.06   0.37    0   -0.38   -0.02   0.48    0   0.58    0.81
0.54    0.18    -0.11   0.03    0.1 -0.38   0.17    0.37    -0.05   0.13
-0.01   -0.17   0.36    0.22    0   -1.4    -0.67   -0.45   -0.62   -0.58
-0.47   -0.86   -1.12   -0.43   0.1 0.06    -0.45   -0.14   0.68    -0.16
0.14    0.14    0.18    0.14    0.17    0.13    0.07    0.05    0.04    0.07
-0.01   0.03    0.05    0.02    0.12    0.34    -0.04   -0.75   1.68    0.23
0.49    0.38    -0.57   0.17    -0.04   0.19    0.22    0.29    -0.04   -0.3
0.18    0.04    0.3 -0.06   -0.07   -0.21   -0.01   0.51    -0.04   -0.04
-0.23   0.06    0.9 -0.14   0.19    2.5 2.84    3.27    2.13    2.5 2.66
4.16    3.52    -0.12   0.13    0.44    0.32    0.44    0.46    0.7 0.68
0.99    0.83    0.74    0.51    0.33    0.22    0.01    0.33    -0.19   0.4
0.41    0.07    0.18    -0.01   0.45    -0.37   -0.49   1.02    -0.59
-1.44   -1.53   -0.74   -1.48   0.12    0.05    0.02    -0.1    0.57
-0.36   0.1 -0.16   -0.23   -0.34   -0.61   -0.37   -0.14   -0.22   -0.27
-0.08   -0.08   -0.17   0.18    -0.74

Y3W 0.15    -0.07   -0.25   -0.3    -1.12   -0.67   -0.15   -0.43   0.63
0.92    0.25    0.33    0.81    -0.12   -0.12   0.67    0.86    0.86
1.54    -0.3    0   -0.29   -0.74   0.15    0.59    0.15    0.34    0.23
0.5 0.52    0.25    0.86    0.53    0.51    0.25        -1.29   -1.79
-0.45   -0.64   0.01    -0.58   -0.51   -0.74   -1.32               -0.47
-0.81   0.55    -0.09   0.46    -0.3    -0.2    -0.81   -1.56   -2.74   1.03
1   1.01    0.29    -0.64   -1.03   0.07    0.46    0.33    0.04    -0.6
-0.64   -0.51   -0.36   -0.1    0.13    -1.4    -1.17   -0.64   -0.16   -0.5
-0.47   0.75    0.62    0.7 1.06    0.93    0.56    -2.25   -0.94   -0.09
0.08    -0.15   -1.6    -1.43   -0.84   -0.25   -1.22   -0.92   -1.22
-0.97   -0.84   -0.89   0.24    0   -0.04   -0.64   -0.94   -1.56   -2.32
0.63    -0.17   -3.06   -2.4    -2  -1.4    -0.81   -1.6    -3.06   -1.79
0.17    0.28    -0.67   -2.82   -1.47   -1.82   -1.69   -1.38   -1.96
-1.88   -2.34   -3.06   -0.18   0.5 -0.03   -0.49   -0.61   -0.54   -0.37
0.1 -0.92   -1.79   -0.03   -0.54   0.94    -1  0.15    0.95    0.55
-0.36   0.4 -0.73   0.85    -0.26   0.55    0.14    -0.36   0.38    0.87
0.62    0.66    0.79    -0.67   0.48    0.62    0.48    0.72    0.73    0.29
-0.3    -0.81

Y4W 0.24    0.76    0.2 0.34    0.11    0.07    0.01    0.36    0.4 -0.25
-0.45   0.09    -0.97   0.19    0.28    -1.81   -0.64   -0.49   -1.27
-0.95   -0.1    0.12    -0.1    0   -0.08   0.77    1.02    0.92    0.56
0.1 0.7 0.57    0.16    1.29    0.82    0.55    0.5 1.83    1.79    0.01
0.24    -0.67   -0.85   -0.42   -0.37   0.2 0.07    -0.01   -0.17   -0.2
-0.43   -0.34   0.12    -0.21   -0.23   -0.22   -0.1    -0.07   -0.61
-0.14   -0.43   -0.97   0.27    0.7 0.54    0.11    -0.5    -0.39   0.01
0.61    0.88    1   0.35    0.67    0.6 0.78    0.46    0.09    -0.06
-0.35   0.08    -0.14   -0.32   -0.11   0   0.01    0.02    0.77    0.18
0.36    -1.15   -0.42   -0.19   0.06    -0.25   -0.81   -0.63   -1.43
-0.85   -0.88   -0.68   -0.59   -1.01   -0.68   -0.71   0.15    0.08    0.08
-0.03   -0.2    0.03    -0.18   -0.01   -0.08   -1.61   -0.67   -0.74
-0.54   -0.8    -1.02   -0.84   -1.91   -0.22   -0.02   0.05    -0.84
-0.65   -0.82   -0.4    -0.83   -0.9    -1.04   -1.23   -0.91   0.28    0.68
0.57    -0.02   0.4 -1.52   0.17    0.44    -1.18   0.04    0.17    0.16
0.04    -0.26   0.04    0.1 -0.11   -0.64   -0.09   -0.16   0.16    -0.05
0.39    0.39    -0.06   0.46    0.2 -0.45   -0.35   -1.3    -0.26   -0.29
0.02    0.16    0.18    -0.35   -0.45   -1.04   -0.69

Y5C 2.85    3.34                            -1  -0.47   -0.66   -0.03   1.41
0.8 0   0.41    -0.14   -0.86   -0.79   -1.69       0           0   1.52
1.29    0.84    0.58    1.02    1.35    0.45    1.02    1.47    0.82    0.46
0.25    0.77    0.93            -0.58   -0.67   -0.18   -0.56   -0.01   0.25
-0.71   -0.49           -0.43   0   -1.06   0.44    -0.29   0.26    -0.04
-0.14   -0.1    -0.12   -1.6    0.33    0.62    0.52    0.7 -0.22   0.44
-0.6    0.86    1.19    1.58    0.93    1   0.85    1.24    1.06    0.49
0.26    0.18    0.3 -0.09   -0.42   0.05    0.54    0.24    0.37    0.86
0.9 0.49    -1.47   -0.2    -0.43   0.2 0.1 -0.81   -0.74   -1.36   -0.97
-0.94   -0.86   -1.56   -1.89   -1.89   -1.06   0.12    0.06    0.04
-0.01   -0.12   0.01    -0.15   0.76    0.89    0.71    -1.12   0.03
-0.86   0.26    0   -0.25   -0.06   0.19    0.41    0.58    -0.46   0.01
-0.15   0.04    -1.01   -0.57   -0.71   -0.3    -1.01       1.83    0.59
1.04    -1.43   0.38    0.65    -6.64   -0.42   0.24    0.46    0.96    0.24
0.7 1.21    0.6 0.12    0.77    -0.03   0.53    0.31    0.46    0.51
-0.45   0.23    0.32    -0.34   -0.1    0.1 -0.45   0.74    -0.06   0.21
0.29    0.45    0.68    0.29    0.45

Y7C -0.22   -0.12   -0.29   -0.51   -0.81   -0.47   0.28    -0.1    0.15
0.38    0.18    -0.27   0.12    -0.15   0.43    0.25    0.19    0.33    0.67
0.86    -0.56   -0.29   -0.36   -0.42   0.08    0.04    -0.04   0.15    0.38
-0.07   -0.1    -0.2    -0.03   -0.29   0.06    0.65    0.58    0.86    2.05
0.3 0.33    -0.29   -0.23   -0.15   -0.32   0.08    0.34    0.15    0
-0.01   0.28    0.36    0.25    0.46    0.4     0.7 0.49    0.97    1.04
0.36    -0.47   -0.29   0.77    0.57    0.45    0.77    0.24    -0.23   0.12
0.49    0.62    0.49    0.84    0.89    1.08    0.87    -0.18   -0.43
-0.39   -0.18   -0.02   0.01    0.2 -0.2    -0.03   0.01    0.25    0.1
-0.07   -1.43   -0.2    -0.4    0.32    0.72    -0.42   -0.3    -0.38
-0.22   -0.81   -1.15   -1.6    -1.89   -2.06   -2.4    0.08    0.34    0.1
-0.15   -0.06   -0.17   -0.47   -0.4    0.15    -1.22   -1.43   -1.03
-1.03   -1.64   -1.84   -2.64   -2  0.05    0.4 0.88    -1.54   -1.21
-1.46   -1.92   -1.52   -1.92   -1.7    -1.94   -1.86   -0.1    -0.02
-0.22   -0.34   -0.48   0.28    0   0.14    0.4 -0.29   -0.27   -0.3
-0.67   -0.09   0.23    0.33    0.23    0.1 0.38    -0.51   0.23    -0.73
0.22    -0.47   0.24    0.68    0.53    0.23    -0.1    0.11    -0.18   0.16
0.68    0.55    0.28    -0.03   0.03    0.08    0.12

There is a missing value, I wanted to load it as matrix I used :

data = np.genfromtxt("This_data.txt", delimiter='\t', missing_values=np.nan)

When I print data I get :

Traceback (most recent call last):
  File "matrix.py", line 8, in <module>
    data = np.genfromtxt("This_data.txt", delimiter='\t', missing_values=np.nan ,usecols=np.arange(0,174))
  File "/home/anaconda2/lib/python2.7/numpy/lib/npyio.py", line 1769, in genfromtxt
    raise ValueError(errmsg)
ValueError: Some errors were detected !
    Line #25 (got 172 columns instead of 174)

I used to put:

data = np.genfromtxt("This_data.txt", delimiter='\t', missing_values=np.nan ,usecols=np.arange(0,174))

But I have same errors. Any suggestion?

Body:
A short sample bytestring substitute for a file:

In [168]: txt = b"""Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81
     ...: """

Minimal load with correct delimiter.  Note the first column is nan, because it can't convert the strings to float.

In [169]: np.genfromtxt(txt.splitlines(),delimiter='\t')
Out[169]:
array([[  nan, -0.22, -0.12, -0.29, -0.51, -0.81],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81]])

with dtype=None it sets each column dtype automatically, creating a structured array:

In [170]: np.genfromtxt(txt.splitlines(),delimiter='\t',dtype=None)
Out[170]:
array([(b'Y7C', -0.22, -0.12, -0.29, -0.51, -0.81),
       (b'Y7C', -0.22, -0.12, -0.29, -0.51, -0.81),
       (b'Y7C', -0.22, -0.12, -0.29, -0.51, -0.81)],
      dtype=[('f0', 'S3'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8'), ('f4', '<f8'), ('f5', '<f8')])

Spell out the columns to use, skipping the first:

In [172]: np.genfromtxt(txt.splitlines(),delimiter='\t',usecols=np.arange(1,6))
Out[172]:
array([[-0.22, -0.12, -0.29, -0.51, -0.81],
       [-0.22, -0.12, -0.29, -0.51, -0.81],
       [-0.22, -0.12, -0.29, -0.51, -0.81]])

But if I ask for more columns that it finds I get an error, like yours:

In [173]: np.genfromtxt(txt.splitlines(),delimiter='\t',usecols=np.arange(1,7))
---------------------------------------------------------------------------
....
ValueError: Some errors were detected !
    Line #1 (got 6 columns instead of 6)
    Line #2 (got 6 columns instead of 6)
    Line #3 (got 6 columns instead of 6)

Your missing_values parameters doesn't help; that's the wrong use for that

This is the correct use of missing_values - to detect the string value and replace it with a valid float value:

In [177]: np.genfromtxt(txt.splitlines(),delimiter='\t',missing_values='Y7C',filling_val
     ...: ues=0)
Out[177]:
array([[ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81]])

If the file has sufficient delimiters, it can treat those as missing values

In [178]: txt = b"""Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81\t\t
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81\t\t
     ...: Y7C\t-0.22\t-0.12\t-0.29\t-0.51\t-0.81\t\t
     ...: """
In [179]: np.genfromtxt(txt.splitlines(),delimiter='\t')
Out[179]:
array([[  nan, -0.22, -0.12, -0.29, -0.51, -0.81,   nan,   nan],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81,   nan,   nan],
       [  nan, -0.22, -0.12, -0.29, -0.51, -0.81,   nan,   nan]])
In [180]: np.genfromtxt(txt.splitlines(),delimiter='\t',filling_values=0)
Out[180]:
array([[ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81,  0.  ,  0.  ],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81,  0.  ,  0.  ],
       [ 0.  , -0.22, -0.12, -0.29, -0.51, -0.81,  0.  ,  0.  ]])

I believe the pandas csv reader can handle 'ragged' columns and missing values better.


来源: stackexchange

问:
WPF Changing ListBox background color, enabled and disabled
I'm searching how to change the background color of my WPF Listbox, nothing worked...  I don't want to change the background of the Item Template, but of the ListBox himself.

I tried the differents solutions answered here Answers

Here is my Listbox :

```<code><ListBox Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="myListBox_SelectionChanged" Background="#FFC3DDF7" Margin="0,0,0,10">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Value.IsOk}" Value="True">
                                <Setter Property="Background" Value="Green"/>
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Width="200">
                                <TextBlock FontSize="10" FontWeight="Bold" VerticalAlignment="Center" Text="{Binding Path=Key}" />
                                <TextBlock FontSize="10" VerticalAlignment="Center" TextWrapping="Wrap">
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="{}{0} {1} {2}">
                                            <Binding Path="Value.TextA" />
                                            <Binding Path="Value.TextB" />
                                            <Binding Path="Value.TextC" />
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
</code>```

Maybe the item template is on the foreground ?

Tried these codes :

```<code><ListBox.Style>
<Style TargetType="{x:Type ListBox}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Blue"/>
    </Style.Resources>
</Style>
</code>```

and

```<code> <ListBox>
    <ListBox.Style>
        <Style TargetType="{x:Type ListBox}">
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Background" Value="Blue" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.Style>
</ListBox>
</code>```

Not working. The down right corner, between the two scrollbars, became blue... But that's all !

答:
The reason why your linked answer does not work is because you have the background of the listbox set to #FFC3DDF7 on the element itself. If you wish to change the initial background color of your listbox this would need to be moved into the style. If you do not move this then the rule for "closest" defined value would be the one on the element itself and the style can't override this.</p>

```<code><ListBox Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="myListBox_SelectionChanged" Margin="0,0,0,10">
        <ListBox.Style>
            <Style TargetType="{x:Type ListBox}">
                <Setter Property="Background" Value="#FFC3DDF7"/>

                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Foreground" Value="LightGray" />
                        <Setter Property="Background" Value="LightGray" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.Style>

        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Value.IsOk}" Value="True">
                        <Setter Property="Background" Value="Green"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <StackPanel Width="200">
                        <TextBlock FontSize="10" FontWeight="Bold" VerticalAlignment="Center" Text="{Binding Path=Key}" />
                        <TextBlock FontSize="10" VerticalAlignment="Center" TextWrapping="Wrap">
                            <TextBlock.Text>
                                <MultiBinding StringFormat="{}{0} {1} {2}">
                                    <Binding Path="Value.TextA" />
                                    <Binding Path="Value.TextB" />
                                    <Binding Path="Value.TextC" />
                                </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm searching how to change the background color of my WPF Listbox, nothing worked...  I don't want to change the background of the Item Template, but of the ListBox himself.

I tried the differents solutions answered here Answers

Here is my Listbox :

<ListBox Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="myListBox_SelectionChanged" Background="#FFC3DDF7" Margin="0,0,0,10">
                <ListBox.ItemContainerStyle>

                    </Style>
                </ListBox.ItemContainerStyle>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <StackPanel Width="200">
                                <TextBlock FontSize="10" FontWeight="Bold" VerticalAlignment="Center" Text="{Binding Path=Key}" />
                                <TextBlock FontSize="10" VerticalAlignment="Center" TextWrapping="Wrap">
                                    <TextBlock.Text>
                                        <MultiBinding StringFormat="{}{0} {1} {2}">
                                            <Binding Path="Value.TextA" />
                                            <Binding Path="Value.TextB" />
                                            <Binding Path="Value.TextC" />
                                        </MultiBinding>
                                    </TextBlock.Text>
                                </TextBlock>
                            </StackPanel>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

Maybe the item template is on the foreground ?

Tried these codes :

<ListBox.Style>

</Style>

and

 <ListBox>
    <ListBox.Style>

        </Style>
    </ListBox.Style>
</ListBox>

Not working. The down right corner, between the two scrollbars, became blue... But that's all !

Body:
The reason why your linked answer does not work is because you have the background of the listbox set to #FFC3DDF7 on the element itself. If you wish to change the initial background color of your listbox this would need to be moved into the style. If you do not move this then the rule for "closest" defined value would be the one on the element itself and the style can't override this.

<ListBox Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Visible" SelectionChanged="myListBox_SelectionChanged" Margin="0,0,0,10">
        <ListBox.Style>
            <Style TargetType="{x:Type ListBox}">
                <Setter Property="Background" Value="#FFC3DDF7"/>

                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Foreground" Value="LightGray" />
                        <Setter Property="Background" Value="LightGray" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.Style>

        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Value.IsOk}" Value="True">
                        <Setter Property="Background" Value="Green"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <StackPanel Width="200">
                        <TextBlock FontSize="10" FontWeight="Bold" VerticalAlignment="Center" Text="{Binding Path=Key}" />
                        <TextBlock FontSize="10" VerticalAlignment="Center" TextWrapping="Wrap">
                            <TextBlock.Text>
                                <MultiBinding StringFormat="{}{0} {1} {2}">
                                    <Binding Path="Value.TextA" />
                                    <Binding Path="Value.TextB" />
                                    <Binding Path="Value.TextC" />
                                </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>


问:
drawing rectangle
I am writing a program that accepts coordinates from the user and drawing some shapes on the screen with stars(*)

e.g Rectangle i.e rectangle=100,150,50,50 as x,y,width,height. how can I do it??

答: I think that this tutorial is very useful for you: http://download.oracle.com/javase/tutorial/2d/geometry/primitives.html</p>

OwnerDisplayName: marry

ContentLicense: CC BY-SA 2.5

Title: drawing rectangle


问:
Trigger fake error 105
I am trying to find a way to make my page look like it doesn't exist if a unique URL query not given. Can't find any solution. I've tried a PHP's trigger_error function, but it can't trigger

ERR_NAME_NOT_RESOLVED.

I could include not existing domain, but lol, it's not impossible. I am looking to do this in PHP, so I'm looking to know if that's possible at all. Or maybe someone can suggest a working solution?

Thanks!

答: If the URL query is not given, you should the 'user' redirect to a custom 404 page or a diffrent error page</p>

Title: Trigger fake error 105


问:
Background image using the background-image property not appearing so not able to get the desired display
I am new to html/css and I do not understand why my background image is not showing up over the button in the search box on the right. I want to display an image of magnifying glass over the right button in the search box?

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight: normal;
  cursor: auto;
  position: relative;

}

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

  <head>
    <link rel="stylesheet" href="css/facebook.css">
  </head>

  <body>
    <button value="1" class="tools" aria-label="Search" type="submit">
  <i class=fb></i>
</button>
    <input type="text" class="sbox" placeholder="Search " arial-label="Search" />
  </body>

</html></code>```

答:
Your  has no text content. Unless you specify some height and width in your CSS, your button will remain unaffected. Try adding this to .fb

```<code>.fb{
    height:50px; /*Assuming 50px because your background-size is 50px*/
    width:50px;
    display:block; /*Because height won't take effect on 'inline' elements*/
}
</code>```

Let me know how it goes.

Body:
I am new to html/css and I do not understand why my background image is not showing up over the button in the search box on the right. I want to display an image of magnifying glass over the right button in the search box?

.sbox {
  width: 297.297px;
  height: 25px;
  background-color: rgba (0, 0, 0, 0);
  font-family: Helvetica, Arial, sans-serif;
  font-size: 14px;
  font-stretch: normal;
  font-style: normal;
  font-variant-caps: normal;
  font-variant-ligatures: normal;
  font-variant-numeric: normal;
  font-weight: normal;
  cursor: auto;
  position: relative;

}

.fb {
  background: url("../img/mag.png") no-repeat 0 0;
  background-size: 50px 50px;
  }

<!DOCTYPE html>

    <link rel="stylesheet" href="css/facebook.css">

    <button value="1" class="tools" aria-label="Search" type="submit">

</button>
    <input type="text" class="sbox" placeholder="Search " arial-label="Search" />

Body:
Your <i class=fb></i> has no text content. Unless you specify some height and width in your CSS, your button will remain unaffected. Try adding this to .fb

.fb{
    height:50px; /*Assuming 50px because your background-size is 50px*/
    width:50px;
    display:block; /*Because height won't take effect on 'inline' elements*/
}

Let me know how it goes.


问:
Put for if in one line python
Say i have one list:

```<code>v=['one','','two','three','',]
</code>```

Now i want to filter out all the empty values:

```<code>for i in v:
  if i==''
    pass
  else:
    print(i)
</code>```

I want to do this in one line :

```<code>vr=[i if i!='' else pass for i in v]
</code>```

getting bellow error.

```<code> File "<console>", line 1
 vr=[i if i!='' else pass for i in vt1]
                     ^
 SyntaxError: invalid syntax
</code>```

Kindly suggest .

答:
You can do the following</p>

```<code>>>> v=['one','','two','three','',]
>>> vr = [i for i in v if i]
>>> vr
['one', 'two', 'three']
</code>```

Title: Put for if in one line python

Body:
Say i have one list:

v=['one','','two','three','',]

Now i want to filter out all the empty values:

for i in v:
  if i==''
    pass
  else:
    print(i)

I want to do this in one line :

vr=[i if i!='' else pass for i in v]

getting bellow error.

 File "<console>", line 1
 vr=[i if i!='' else pass for i in vt1]
                     ^
 SyntaxError: invalid syntax

Kindly suggest .

Body:
You can do the following

>>> v=['one','','two','three','',]
>>> vr = [i for i in v if i]
>>> vr
['one', 'two', 'three']


问:
SQL Server cannot execute query
When I try to execute any query in sql server, I get this error message many times:

Cannot execute script - Additional information: The process cannot access the file 'C:\Users\AppData\Local\Temp\tmpC9BA.tmp' because it is being used by another process. (mscorlib)".

I then have to click ok and run the query again and it will work fine.

答:
It seems there is an answer to this over at SQL Server Central:

Check your anti-virus

Here's the main part of the answer there for future reference:
"
This sounds a lot like an Anti-Virus problem.

It's unlikely that two processes would use the same temp file name - and especially to keep doing it.

I suppose it's also possible that you have an Add-in or extension in SSMS that is somehow locking the file - try making sure you have removed any and test again.

Another thing to try is open Resource Monitor, go to the CPU tab, then search the Associated Handles section for .tmp to see if you can spot it. "

Title: SQL Server cannot execute query


问:
Which constructor should I use for the StringBuilder class?
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

```<code>Dim sb = New StringBuilder(averageCharacterCount * items.Count)
</code>```

instead of

```<code>Dim sb = New StringBuilder()
</code>```

even if the specified capacity is just a guess?

答: Unless it's the only thing that your app does, you won't notice that.</p>

Body:
I'm building a large string from a list of items.  Each item will generate a string which is approximately 200 characters long (plus or minus 100%).

Will I get a (noticeable) performance benefit from using

Dim sb = New StringBuilder(averageCharacterCount * items.Count)

instead of

Dim sb = New StringBuilder()

even if the specified capacity is just a guess?


问:
Code not functioning with larger lists
I am coding for a problem on project euler. Problem 50 https://projecteuler.net/problem=50

The problem is my code works fine with small lists, specifically a list of primes under a few thousand, however, it fails to work with a list of primes under 1 million (with is around the 80000th prime) which is an issue in getting the answer.

There are two main problems:

It is horrendously slow with larger lists such roughly greater than 20000  (10 - 20mins)

It does not produce the correct answer

Even if the logic is correct and finishes running the answer is incorrect, is this a memory issue? I would like to know why my code only works with smaller data and how to improve my efficiency

Also, if I am asking a bad question let me know.

```<code>def primes(n):

   sieve = [True] * n
    for i in range(3,int(n**0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * int((n - i * i - 1)/(2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

primes = primes(1000)
start = 0
answer = 0
x = 0
count = y = 2

while len(primes[x:y - 1]) < len(primes):
    summed = sum(primes[x:y])
    length = len(primes[x:y])
    if summed in primes and length > start:
        start = length
        answer = summed
    x += 1
    y += 1
    if y - 1 == len(primes):
        count += 1
        x = 0
        y = count

print(start)
print(answer)
</code>```

答:
I took another approach

I checked from each elements in the list of primes if there is a consecutive series, longer than the longest series found until then for which the sum is a prime

generate the primes

```<code>import itertools
def primes(n):
    found_primes = [True] * (n + 1)
    for i in range(2, n + 1):
        if found_primes[i]:
            yield i
            for j in itertools.takewhile(lambda x: x * i <= n, itertools.count(1)):
                found_primes[j * i] = False
</code>```

Find a longer consecutive sum

```<code>def find_longer_consecutive_sums(elements):
    n = len(elements)
    elements_set = set(elements)
    max_elements = 1
    max_prime = elements[-1]
    for i in range(len(elements) - 1):
        if sum(elements[i: i + max_elements]) > max_prime:
            return
        for j, k in enumerate(itertools.islice(itertools.accumulate(elements[i:]), max_elements, len(elements)), max_elements + 1):
            if k in elements_set:
                max_elements = j
                yield i, j, k
</code>```

I used a set to check whether it was in because sets have fixed time search

I stopped the iteration if there was not a possibility of a longer set which did not exceed the largest looked for prime

I used some itertools magic with enumerate, accumulate and islice to:

look for an ever longer series: (itertools.islice(x, max_elements, len(elements))

in the sums starting at a particular place in the list of primes: itertools.accumulate(elements[i:])

Tying it together

```<code>primes_list = list(primes(1000000))
results_longer = {}
for i, j, k in find_longer_consecutive_sums(primes_list):
    selected_primes = primes_list[i:i+j]
    print(i, j, k, sum(selected_primes), selected_primes)
    results_longer[(j, i, k)] = selected_primes
</code>```

returns in slightly over a second:

```<code>0 2 5 5 [2, 3]
0 4 17 17 [2, 3, 5, 7]
0 6 41 41 [2, 3, 5, 7, 11, 13]
0 12 197 197 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...
0 14 281 281 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...
0 60 7699 7699 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31...
0 64 8893 8893 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31...
0 96 22039 22039 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
0 100 24133 24133 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 102 25237 25237 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 108 28697 28697 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 114 32353 32353 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 122 37561 37561 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 124 38921 38921 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 130 43201 43201 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 132 44683 44683 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 146 55837 55837 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 152 61027 61027 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 158 66463 66463 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 162 70241 70241 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 178 86453 86453 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 192 102001 102001 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 198 109147 109147 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 204 116533 116533 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 206 119069 119069 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 208 121631 121631 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 214 129419 129419 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 216 132059 132059 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 296 263171 263171 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 308 287137 287137 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 326 325019 325019 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 328 329401 329401 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 330 333821 333821 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 332 338279 338279 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 334 342761 342761 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 342 360979 360979 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 350 379667 379667 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 356 393961 393961 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 358 398771 398771 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 426 581921 581921 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 446 642869 642869 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 458 681257 681257 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 460 687767 687767 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 464 700897 700897 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 480 754573 754573 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 484 768373 768373 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 488 782263 782263 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 512 868151 868151 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 530 935507 935507 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 536 958577 958577 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
2 537 970219 970219 [5, 7, 11, 13, 17, 19, 23, 29, 31,...
2 539 978037 978037 [5, 7, 11, 13, 17, 19, 23, 29, 31,...
3 543 997651 997651 [7, 11, 13, 17, 19, 23, 29, 31, 37...
</code>```

Title: Code not functioning with larger lists

Body:
I am coding for a problem on project euler. Problem 50 https://projecteuler.net/problem=50

The problem is my code works fine with small lists, specifically a list of primes under a few thousand, however, it fails to work with a list of primes under 1 million (with is around the 80000th prime) which is an issue in getting the answer.

There are two main problems:

It is horrendously slow with larger lists such roughly greater than 20000  (10 - 20mins)

It does not produce the correct answer

Even if the logic is correct and finishes running the answer is incorrect, is this a memory issue? I would like to know why my code only works with smaller data and how to improve my efficiency

Also, if I am asking a bad question let me know.

def primes(n):

   sieve = [True] * n
    for i in range(3,int(n**0.5) + 1, 2):
        if sieve[i]:
            sieve[i * i :: 2 * i] = [False] * int((n - i * i - 1)/(2 * i) + 1)
    return [2] + [i for i in range(3, n, 2) if sieve[i]]

primes = primes(1000)
start = 0
answer = 0
x = 0
count = y = 2

while len(primes[x:y - 1]) < len(primes):
    summed = sum(primes[x:y])
    length = len(primes[x:y])
    if summed in primes and length > start:
        start = length
        answer = summed
    x += 1
    y += 1
    if y - 1 == len(primes):
        count += 1
        x = 0
        y = count

print(start)
print(answer)

Body:
I took another approach

I checked from each elements in the list of primes if there is a consecutive series, longer than the longest series found until then for which the sum is a prime

generate the primes

import itertools
def primes(n):
    found_primes = [True] * (n + 1)
    for i in range(2, n + 1):
        if found_primes[i]:
            yield i
            for j in itertools.takewhile(lambda x: x * i <= n, itertools.count(1)):
                found_primes[j * i] = False

Find a longer consecutive sum

def find_longer_consecutive_sums(elements):
    n = len(elements)
    elements_set = set(elements)
    max_elements = 1
    max_prime = elements[-1]
    for i in range(len(elements) - 1):
        if sum(elements[i: i + max_elements]) > max_prime:
            return
        for j, k in enumerate(itertools.islice(itertools.accumulate(elements[i:]), max_elements, len(elements)), max_elements + 1):
            if k in elements_set:
                max_elements = j
                yield i, j, k

I used a set to check whether it was in because sets have fixed time search

I stopped the iteration if there was not a possibility of a longer set which did not exceed the largest looked for prime

I used some itertools magic with enumerate, accumulate and islice to:

look for an ever longer series: (itertools.islice(x, max_elements, len(elements))

in the sums starting at a particular place in the list of primes: itertools.accumulate(elements[i:])

Tying it together

primes_list = list(primes(1000000))
results_longer = {}
for i, j, k in find_longer_consecutive_sums(primes_list):
    selected_primes = primes_list[i:i+j]
    print(i, j, k, sum(selected_primes), selected_primes)
    results_longer[(j, i, k)] = selected_primes

returns in slightly over a second:

0 2 5 5 [2, 3]
0 4 17 17 [2, 3, 5, 7]
0 6 41 41 [2, 3, 5, 7, 11, 13]
0 12 197 197 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...
0 14 281 281 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, ...
0 60 7699 7699 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31...
0 64 8893 8893 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31...
0 96 22039 22039 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, ...
0 100 24133 24133 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 102 25237 25237 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 108 28697 28697 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 114 32353 32353 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 122 37561 37561 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 124 38921 38921 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 130 43201 43201 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 132 44683 44683 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 146 55837 55837 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 152 61027 61027 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 158 66463 66463 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 162 70241 70241 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 178 86453 86453 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29,...
0 192 102001 102001 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 198 109147 109147 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 204 116533 116533 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 206 119069 119069 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 208 121631 121631 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 214 129419 129419 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 216 132059 132059 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 296 263171 263171 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 308 287137 287137 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 326 325019 325019 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 328 329401 329401 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 330 333821 333821 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 332 338279 338279 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 334 342761 342761 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 342 360979 360979 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 350 379667 379667 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 356 393961 393961 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 358 398771 398771 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 426 581921 581921 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 446 642869 642869 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 458 681257 681257 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 460 687767 687767 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 464 700897 700897 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 480 754573 754573 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 484 768373 768373 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 488 782263 782263 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 512 868151 868151 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 530 935507 935507 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
0 536 958577 958577 [2, 3, 5, 7, 11, 13, 17, 19, 23, 2...
2 537 970219 970219 [5, 7, 11, 13, 17, 19, 23, 29, 31,...
2 539 978037 978037 [5, 7, 11, 13, 17, 19, 23, 29, 31,...
3 543 997651 997651 [7, 11, 13, 17, 19, 23, 29, 31, 37...


问:
Best way of chaining reduce with Java 8
I have the following code that I'm trying to improve:

```<code>BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);
</code>```

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

答:
The words "better" or "best" should refer to some metric. Performance? Readability? Elegance?

The answer by Eran shows one approach, namely creating small streams containing the property values A, B, C and D for each associate, and flat-mapping these values into a larger stream. The order of summation in this approach is

```<code>A0 + B0 + C0 + D0  +  A1 + B1 + C1 + D1  + ... +  An + Bn + Cn + Dn
</code>```

Another option would be to create individual streams of the properties A, B, C and D, and concatenating these streams before applying the reduction. This could be done with nested Stream#concat calls, but more elegantly and flexibly using flatMap with an identity function:

```<code>Stream<BigDecimal> stream = Stream.of(
    entity.getAssociate().stream().map(Associates::getPropertyA),
    entity.getAssociate().stream().map(Associates::getPropertyB),
    entity.getAssociate().stream().map(Associates::getPropertyA),
    entity.getAssociate().stream().map(Associates::getPropertyC))
    .flatMap(Function.identity());

BigDecimal total = stream.reduce(BigDecimal.ZERO, BigDecimal::add);
</code>```

The key point is that in this case, the summation order is

```<code>A0 + A1 + ... + An + B0 + B1 + ... + Bn + C0 + C1 + ... + Cn
</code>```

(It may not technically make a large difference. But it is an approach that is conceptually different to the ones that have been proposed so far (in terms of the summation order), and thus, may be worth mentioning as one option - additionally, it is more similar to the approach that you currently use, but without the broken identity value for the reduction)

Title: Best way of chaining reduce with Java 8

Body:
I have the following code that I'm trying to improve:

BigDecimal total = entity.getAssociate().stream().map(Associates::getPropertyA)
    .reduce(BigDecimal.ZERO, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyB)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyC)
    .reduce(total, BigDecimal::add);
total = entity.getAssociate().stream().map(Associates::getPropertyD)
    .reduce(total, BigDecimal::add);

It works, but it really feels like there is a better way of doing this. Can anybody enlighten me on the matter?

Body:
The words "better" or "best" should refer to some metric. Performance? Readability? Elegance?

The answer by Eran shows one approach, namely creating small streams containing the property values A, B, C and D for each associate, and flat-mapping these values into a larger stream. The order of summation in this approach is

A0 + B0 + C0 + D0  +  A1 + B1 + C1 + D1  + ... +  An + Bn + Cn + Dn

Another option would be to create individual streams of the properties A, B, C and D, and concatenating these streams before applying the reduction. This could be done with nested Stream#concat calls, but more elegantly and flexibly using flatMap with an identity function:

Stream<BigDecimal> stream = Stream.of(
    entity.getAssociate().stream().map(Associates::getPropertyA),
    entity.getAssociate().stream().map(Associates::getPropertyB),
    entity.getAssociate().stream().map(Associates::getPropertyA),
    entity.getAssociate().stream().map(Associates::getPropertyC))
    .flatMap(Function.identity());

BigDecimal total = stream.reduce(BigDecimal.ZERO, BigDecimal::add);

The key point is that in this case, the summation order is

A0 + A1 + ... + An + B0 + B1 + ... + Bn + C0 + C1 + ... + Cn

(It may not technically make a large difference. But it is an approach that is conceptually different to the ones that have been proposed so far (in terms of the summation order), and thus, may be worth mentioning as one option - additionally, it is more similar to the approach that you currently use, but without the broken identity value for the reduction)


问:
How do I run two while True statements in python?
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

```<code>import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()
</code>```

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

```<code>import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()
</code>```

(UPDATE) Also, below is my attempt at threading:

```<code>import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()
</code>```

答:
You need to pass your thread functions as the target arguments, not their return values:

```<code>import sleep

f1 = Thread(target=doorsensor) # Remove parentheses after doorsensor
f1.daemon = True
f1.start()
f2 = Thread(target=cardreader) # Remove parentheses after cardreader
f2.daemon = True
f2.start()

# Use a try block to catch Ctrl+C
try:
    # Use a while loop to keep the program from exiting and killing the threads
    while True:
        time.sleep(1.0)
except KeyboardInterrupt:
    pass

gpio.cleanup()
</code>```

The daemon property is set on each thread so that the program will exit when only the daemon threads are left:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

Body:
I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.

Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring

import time
import RPi.GPIO as gpio

led = 37
buzzer = 11
door = 16

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

while True:
    if gpio.input(door):
        time.sleep(3)
        for i in range(0,5):
                blink(led)
        for i in range (0,5):
                blink(buzzer)
    else:
        gpio.output(buzzer, False)

gpio.cleanup()

2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken

import datetime
import time
import os
import RPi.GPIO as gpio

led = 37
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)

def blink(led):
    gpio.output(led, True)
    time.sleep(0.1)
    gpio.output(led, False)
    time.sleep(0.1)

while True:
    card = raw_input()
    f = open("Laptop Sign Out" + '.txt', 'a')
    f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
    f.write('\n')
    f.write(';')
    f.write('\n')
    f.close()
    time.sleep(1)
    for i in range(0,3):
        blink(led)
    os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
    time.sleep(3)

gpio.cleanup()

(UPDATE) Also, below is my attempt at threading:

import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread

led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()

gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)

def blink(buzzer):
    gpio.output(buzzer, True)
    time.sleep(0.1)
    gpio.output(buzzer, False)
    time.sleep(0.1)
    return

def blink(led):
    gpio.output(led, True)
    time.sleep(1)
    gpio.output(led, False)
    time.sleep(1)
    return

def doorsensor():
    while True:
        if gpio.input(door):
            time.sleep(3)
            for i in range(0,5):
                    blink(led)
            for i in range (0,5):
                    blink(buzzer)
        else:
            gpio.output(buzzer, False)

def cardreader():
    while True:
        card = raw_input()
        f = open("Laptop Sign Out" + '.txt', 'a')
        f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
        f.write('\n')
        f.write(';')
        f.write('\n')
        f.close()
        time.sleep(1)
        for i in range(0,3):
            blink(led)
        os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
        time.sleep(3)

f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())

f2.start()
f1.start()

gpio.cleanup()

Body:
You need to pass your thread functions as the target arguments, not their return values:

import sleep

f1 = Thread(target=doorsensor) # Remove parentheses after doorsensor
f1.daemon = True
f1.start()
f2 = Thread(target=cardreader) # Remove parentheses after cardreader
f2.daemon = True
f2.start()

# Use a try block to catch Ctrl+C
try:
    # Use a while loop to keep the program from exiting and killing the threads
    while True:
        time.sleep(1.0)
except KeyboardInterrupt:
    pass

gpio.cleanup()

The daemon property is set on each thread so that the program will exit when only the daemon threads are left:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.


问:
Sabre REST API OTA_AirLowFareSearchRQ get nonstops flights
I'm using the BFM service in the SABRE REST API. Im trying get only direct flights (Non Stops Flights) using the objects: TPA_Extensions.DiversityParameters.AdditionalNonStopsPercentage
TravelPreferences.FlightTypePref.FlightType

but the answers allways is: 400 Bad Request

```<code>{
"status": "NotProcessed",
"type": "Validation",
"errorCode": "ERR.RAF.VALIDATION",
"timeStamp": "2016-02-10T14:24:13+00:00",
"message": "[{\"level\":\"error\",\"schema\":{\"loadingURI\":\"#\",\"pointer\":\"/definitions/org.opentravel.ota._2003._05.OTAAirLowFareSearchRQ.TPAExtensions\"},\"instance\":{\"pointer\":\"/OTA_AirLowFareSearchRQ/TPA_Extensions\"},\"domain\":\"validation\",\"keyword\":\"additionalProperties\",\"message\":\"object instance has properties which are not allowed by the schema: [\\\"DiversityParameters\\\"]\",\"unwanted\":[\"DiversityParameters\"]}]"
</code>```

}

There are somebody had the same issue?

thanx in advance

答:
Try this

```<code>"DiversityParameters" : {
    "AdditionalNonStopsPercentage" : 20
}
</code>```

or

```<code>"DiversityParameters" : {
    "AdditionalNonStopsNumber" : 5
}
</code>```

This code works balancing the BFM results.

Body:
I'm using the BFM service in the SABRE REST API. Im trying get only direct flights (Non Stops Flights) using the objects: TPA_Extensions.DiversityParameters.AdditionalNonStopsPercentage
TravelPreferences.FlightTypePref.FlightType

but the answers allways is: 400 Bad Request

{
"status": "NotProcessed",
"type": "Validation",
"errorCode": "ERR.RAF.VALIDATION",
"timeStamp": "2016-02-10T14:24:13+00:00",
"message": "[{\"level\":\"error\",\"schema\":{\"loadingURI\":\"#\",\"pointer\":\"/definitions/org.opentravel.ota._2003._05.OTAAirLowFareSearchRQ.TPAExtensions\"},\"instance\":{\"pointer\":\"/OTA_AirLowFareSearchRQ/TPA_Extensions\"},\"domain\":\"validation\",\"keyword\":\"additionalProperties\",\"message\":\"object instance has properties which are not allowed by the schema: [\\\"DiversityParameters\\\"]\",\"unwanted\":[\"DiversityParameters\"]}]"

}

There are somebody had the same issue?

thanx in advance

Body:
Try this

"DiversityParameters" : {
    "AdditionalNonStopsPercentage" : 20
}

or

"DiversityParameters" : {
    "AdditionalNonStopsNumber" : 5
}

This code works balancing the BFM results.


答: vr=[i for i in v if i!=''] boom

Title: Put for if in one line python

Body: vr=[i for i in v if i!=''] boom


问:
git log usage: finding the most frequent committers for a given time period
For a given sub-directory in a git repository, how can I find who are the most frequent committers for a given period of time?

As of now I used git shortlog as follows:

```<code>git shortlog -sn -- path/to/subdir
</code>```

But problem is this is giving data since beginning. I am trying to find this data for a window of time, e.g., last 1 year.

答:
Combine with since for a time limit:

```<code>git --no-pager shortlog -sn --since="2017-01-12T16:36:00-07:00" -- path/to/dir
</code>```

Is what you need. since can be a year back. If there are a ton of authors (more than display height) then pipe this into head or less.

Body:
For a given sub-directory in a git repository, how can I find who are the most frequent committers for a given period of time?

As of now I used git shortlog as follows:

git shortlog -sn -- path/to/subdir

But problem is this is giving data since beginning. I am trying to find this data for a window of time, e.g., last 1 year.

Body:
Combine with since for a time limit:

git --no-pager shortlog -sn --since="2017-01-12T16:36:00-07:00" -- path/to/dir

Is what you need. since can be a year back. If there are a ton of authors (more than display height) then pipe this into head or less.


问:
Splitting divs into 2 columns
I have a code like this:

title1

article1

title2

article2

title3

article3

title4

article4

```
</div>
</div>
</p>

<p>and I want to transform this 1 lined column into 2 columns like this:</p>

<p><img src="https://i.stack.imgur.com/NKI4c.png" alt="example image"></p>

<p>I already tried to use this code, but is there any different way to split the div?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex-grow: 1;
  flex-basis: 50%;
}

.article:after {
  content: "";
  flex: auto;
}</code>```

title1

article1

title2

article2

title3

article3

title4

article4

```

It's different from this other question Split Div Into 2 Columns Using CSS, the "article" arrangement from this question is different. Anyone got the idea?

答:
Here's one way using float/clear:

.article {
  float: left;
  width: 50%;
}

.article:nth-child(odd) {
  clear: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="article-container">
  <div class="article">
    <h3>title1</h3>
    <p>article1</p>
  </div>
  <div class="article">
    <h3>title2</h3>
    <p>article2</p>
  </div>
  <div class="article">
    <h3>title3</h3>
    <p>article3</p>
  </div>
  <div class="article">
    <h3>title4</h3>
    <p>article4</p>
  </div>
</div></code>```

Title: Splitting divs into 2 columns

Body:
I have a code like this:

title1

article1

title2

article2

title3

article3

title4

article4

and I want to transform this 1 lined column into 2 columns like this:

I already tried to use this code, but is there any different way to split the div?

.article-container {
  display: flex;
  flex-wrap: wrap;
}

.article {
  flex-grow: 1;
  flex-basis: 50%;
}

.article:after {
  content: "";
  flex: auto;
}

title1

article1

title2

article2

title3

article3

title4

article4

It's different from this other question Split Div Into 2 Columns Using CSS, the "article" arrangement from this question is different. Anyone got the idea?

Body:
Here's one way using float/clear:

.article {
  float: left;
  width: 50%;
}

.article:nth-child(odd) {
  clear: left;
}

<div class="article-container">
  <div class="article">
    <h3>title1</h3>
    <p>article1</p>
  </div>
  <div class="article">
    <h3>title2</h3>
    <p>article2</p>
  </div>
  <div class="article">
    <h3>title3</h3>
    <p>article3</p>
  </div>
  <div class="article">
    <h3>title4</h3>
    <p>article4</p>
  </div>
</div>


问:
keep values after submit
I know how I can keep my form where I have a select list is not deleted after a submit?

This is the line I use to fill the select list:

```<code><% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. style a.estilo]}%>
</code>```

please help me

Thanks in advance

答:
You need to set what option is selected. This case the 2nd one is selected:

```<code><%=  options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
</code>```

See here for explanation

Title: keep values after submit

Body:
I know how I can keep my form where I have a select list is not deleted after a submit?

This is the line I use to fill the select list:

<% = select: search,: style, [[All, ""]] + Proyect.all (: group => "style",: order => "style"). collect {| a | [a. style a.estilo]}%>

please help me

Thanks in advance

Body:
You need to set what option is selected. This case the 2nd one is selected:

<%=  options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>

See here for explanation


问:
putting the checkboxes values in arrays without ng-repeat
I have some checkboxes:-

```<code><label>CHANNELS</label>
   <md-checkbox  ng-model="channel[0]" class="md-primary md-hue-2" ng-checked="selected.indexOf(channel[0]) > -1" ng-click="toggleSelection(channel[0])" value="channel[0]">CHANNEL A</md-checkbox>
   <md-checkbox ng-model="channel[1]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[1]) > -1" ng-click="toggleSelection(channel[1])" value="channel[1]">CHANNEL B</md-checkbox>
   <md-checkbox ng-model="channel[2]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[2]) > -1" ng-click="toggleSelection(channel[2])" value="channel[2]">CHANNEL C</md-checkbox>
   <md-checkbox ng-model="channel[3]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[3]) > -1" ng-click="toggleSelection(channel[3])" value="channel[3]">CHANNEL D</md-checkbox>
   <md-checkbox ng-model="channel[4]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[4]) > -1" ng-click="toggleSelection(channel[4])" value="channel[4]">CHANNEL E</md-checkbox>
</code>```

I am trying to put the values in an array.
My directive code is:-

```<code>scope.channels = ['CHANNEL A','CHANNEL B','CHANNEL C','CHANNEL D','CHANNEL E'];
                     scope.selected = [];

             scope.toggleSelection = function toggleSelection(channel) {
              console.log(channel);
               var idx = scope.selected.indexOf(channel);
                     console.log(idx);
               if (idx > -1) {
                 scope.selected.splice(idx, 1);
               }

               else {
                 scope.selected.push(channel);
               }
             };
</code>```

I know by using ng-repeat it will work better but by using that I have some other css issues which is difficult to correct.I only want this method to be work. Can any one tell me how I can I make it work without using ng-repeat.

答:
I'd also recommend making ngRepeat work, but to answer the question asked...

Don't use ngModel and ngChecked together.

Try this:

```<code><label>CHANNELS</label>
   <md-checkbox ng-model="selected[0]" class="md-primary md-hue-2" ng-true-value="channel[0]" ng-false-value="null">CHANNEL A</md-checkbox>
   <md-checkbox ng-model="selected[1]" class="md-primary md-hue-2" ng-true-value="channel[1]" ng-false-value="null">CHANNEL B</md-checkbox>
   <md-checkbox ng-model="selected[2]" class="md-primary md-hue-2" ng-true-value="channel[2]" ng-false-value="null">CHANNEL C</md-checkbox>
   <md-checkbox ng-model="selected[3]" class="md-primary md-hue-2" ng-true-value="channel[3]" ng-false-value="null">CHANNEL D</md-checkbox>
   <md-checkbox ng-model="selected[4]" class="md-primary md-hue-2" ng-true-value="channel[4]" ng-false-value="null">CHANNEL E</md-checkbox>
</code>```

This will set the values of the selected array to the corresponding value of the channel array if the box is checked. Note: You can't use selected.length to determine if anything is checked because the selected array will always have 4 members, some of which may be null.

Body:
I have some checkboxes:-

CHANNELS
   <md-checkbox  ng-model="channel[0]" class="md-primary md-hue-2" ng-checked="selected.indexOf(channel[0]) > -1" ng-click="toggleSelection(channel[0])" value="channel[0]">CHANNEL A</md-checkbox>
   <md-checkbox ng-model="channel[1]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[1]) > -1" ng-click="toggleSelection(channel[1])" value="channel[1]">CHANNEL B</md-checkbox>
   <md-checkbox ng-model="channel[2]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[2]) > -1" ng-click="toggleSelection(channel[2])" value="channel[2]">CHANNEL C</md-checkbox>
   <md-checkbox ng-model="channel[3]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[3]) > -1" ng-click="toggleSelection(channel[3])" value="channel[3]">CHANNEL D</md-checkbox>
   <md-checkbox ng-model="channel[4]" class="margin-left-1 md-primary md-hue-2" ng-checked="selected.indexOf(channel[4]) > -1" ng-click="toggleSelection(channel[4])" value="channel[4]">CHANNEL E</md-checkbox>

I am trying to put the values in an array.
My directive code is:-

scope.channels = ['CHANNEL A','CHANNEL B','CHANNEL C','CHANNEL D','CHANNEL E'];
                     scope.selected = [];

             scope.toggleSelection = function toggleSelection(channel) {
              console.log(channel);
               var idx = scope.selected.indexOf(channel);
                     console.log(idx);
               if (idx > -1) {
                 scope.selected.splice(idx, 1);
               }

               else {
                 scope.selected.push(channel);
               }
             };

I know by using ng-repeat it will work better but by using that I have some other css issues which is difficult to correct.I only want this method to be work. Can any one tell me how I can I make it work without using ng-repeat.

Body:
I'd also recommend making ngRepeat work, but to answer the question asked...

Don't use ngModel and ngChecked together.

Try this:

<label>CHANNELS</label>
   <md-checkbox ng-model="selected[0]" class="md-primary md-hue-2" ng-true-value="channel[0]" ng-false-value="null">CHANNEL A</md-checkbox>
   <md-checkbox ng-model="selected[1]" class="md-primary md-hue-2" ng-true-value="channel[1]" ng-false-value="null">CHANNEL B</md-checkbox>
   <md-checkbox ng-model="selected[2]" class="md-primary md-hue-2" ng-true-value="channel[2]" ng-false-value="null">CHANNEL C</md-checkbox>
   <md-checkbox ng-model="selected[3]" class="md-primary md-hue-2" ng-true-value="channel[3]" ng-false-value="null">CHANNEL D</md-checkbox>
   <md-checkbox ng-model="selected[4]" class="md-primary md-hue-2" ng-true-value="channel[4]" ng-false-value="null">CHANNEL E</md-checkbox>

This will set the values of the selected array to the corresponding value of the channel array if the box is checked. Note: You can't use selected.length to determine if anything is checked because the selected array will always have 4 members, some of which may be null.


答:
```<code>v=['one','','two','three','',]
print(*[i for i in v if i], sep='\n')
</code>```

Title: Put for if in one line python

Body:
Say i have one list:

v=['one','','two','three','',]

Now i want to filter out all the empty values:

for i in v:
  if i==''
    pass
  else:
    print(i)

I want to do this in one line :

vr=[i if i!='' else pass for i in v]

getting bellow error.

 File "<console>", line 1
 vr=[i if i!='' else pass for i in vt1]
                     ^
 SyntaxError: invalid syntax

Kindly suggest .


问:
d3 v4: How to find position of rotated elements?
I have a bunch of dots that I'm placing at even intervals around a circle. I'm doing this by setting their cx and cy attributes to the initial position, then iterating over each dot and giving it a transform(rotate) to move it to where I want it.

```<code>var dot = dotPlaces.append("circle")
                    .attr("cx", dotOriginX )
                    .attr("cy", dotOriginY )
                    .attr("r", 20 / 2)
                    .attr("opacity", 1)
                    .attr("id", function(d) { return d.name; })
                    .attr('fill', function(d) {
                        return color(d.type);
                    })
                    .attr("transform", function(d,i) {
                        return "rotate("+ (i * (360/actualData.length)) +"," + originX + "," + originY + ")";
                    })
                    .attr("stroke", "white");
</code>```

My problem arrives when later in the code I want to draw lines to these dots. Whether I get their cx/cy attributes or their bounding box, it always references the original pre-transform position. I need their post-transform position. Apparently in d3 v3 there was a transform call that could be used, but in v4 this has vanished. Since I'm using a rotation and not a simple translation, this is less trivial than just adding some x and y offset.

This is what I'm using now, for reference:

```<code>var x = svg2.select("#"+key).node().getAttribute("cx");
var y = svg2.select("#"+key).node().getAttribute("cy");
//alternatively node().getBBox(); which also fails to give post-transform position.
</code>```

答:
As long as you only need to figure out the position relative to the <svg> element (or, to be precise, to the nearest viewport element), you can use the SVG interface .getCTM(). It gets you the transform matrix you can then apply to the cx/cy attributes.

var circle = d3.select('circle');
var cx = circle.attr('cx');
var cy = circle.attr('cy');
var ctm = circle.node().getCTM();
var x = cx * ctm.a + cy * ctm.c + ctm.e;
var y = cx * ctm.b + cy * ctm.d + ctm.f;
d3.select('p').text(x + ',' + y);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3-selection.v1.min.js"></script>
<svg width="200" height="100">
    <circle cx="30" cy="30" r="10" transform="rotate(90 100 100)" />
</svg>
<p></p></code>```

Body:
I have a bunch of dots that I'm placing at even intervals around a circle. I'm doing this by setting their cx and cy attributes to the initial position, then iterating over each dot and giving it a transform(rotate) to move it to where I want it.

var dot = dotPlaces.append("circle")
                    .attr("cx", dotOriginX )
                    .attr("cy", dotOriginY )
                    .attr("r", 20 / 2)
                    .attr("opacity", 1)
                    .attr("id", function(d) { return d.name; })
                    .attr('fill', function(d) {
                        return color(d.type);
                    })
                    .attr("transform", function(d,i) {
                        return "rotate("+ (i * (360/actualData.length)) +"," + originX + "," + originY + ")";
                    })
                    .attr("stroke", "white");

My problem arrives when later in the code I want to draw lines to these dots. Whether I get their cx/cy attributes or their bounding box, it always references the original pre-transform position. I need their post-transform position. Apparently in d3 v3 there was a transform call that could be used, but in v4 this has vanished. Since I'm using a rotation and not a simple translation, this is less trivial than just adding some x and y offset.

This is what I'm using now, for reference:

var x = svg2.select("#"+key).node().getAttribute("cx");
var y = svg2.select("#"+key).node().getAttribute("cy");
//alternatively node().getBBox(); which also fails to give post-transform position.

Body:
As long as you only need to figure out the position relative to the <svg> element (or, to be precise, to the nearest viewport element), you can use the SVG interface .getCTM(). It gets you the transform matrix you can then apply to the cx/cy attributes.

var circle = d3.select('circle');
var cx = circle.attr('cx');
var cy = circle.attr('cy');
var ctm = circle.node().getCTM();
var x = cx * ctm.a + cy * ctm.c + ctm.e;
var y = cx * ctm.b + cy * ctm.d + ctm.f;
d3.select('p').text(x + ',' + y);

<script src="https://d3js.org/d3-selection.v1.min.js"></script>
<svg width="200" height="100">
    <circle cx="30" cy="30" r="10" transform="rotate(90 100 100)" />
</svg>
<p></p>


问:
How to get value from A3 in Laravel Excel maatwebsite
I use Laravel Excel and I have data at ''A3'' cell. How to get it? I take this code is not working. It's show all data in that sheet.  Reference</p>

```<code> $sheet = $doc->getSheetByName('data');
 $sheet->getCell('A3');
</code>```

答:
I'm using it too.You can check the array by dd, and get needed cell. </p>

```<code>        public function loadExcel(Request $request)
        {
            $path = $request->file('file')->getRealPath();

            $records = \Excel::load($path, function ($reader) {
                  $reader->noHeading();
            })->get()[0]->toArray();

            dd($records);

          //When you find the index of needed cell just $needed_cell = $records['index'];
    }
</code>```

Body:
I use Laravel Excel and I have data at ''A3'' cell. How to get it? I take this code is not working. It's show all data in that sheet.  Reference

 $sheet = $doc->getSheetByName('data');
 $sheet->getCell('A3');

Body:
I'm using it too.You can check the array by dd, and get needed cell.

        public function loadExcel(Request $request)
        {
            $path = $request->file('file')->getRealPath();

            $records = \Excel::load($path, function ($reader) {
                  $reader->noHeading();
            })->get()[0]->toArray();

            dd($records);

          //When you find the index of needed cell just $needed_cell = $records['index'];
    }


问:
How to use the same spark context in a loop in Pyspark
I have a shell script that invokes a pyspark job and creates tables in Hive. The script works fine. Now want to reduce the time taken for the script to run while invoking as cron jobs for more than 100 tables.

The import.sh script is below.

```<code>#!/bin/bash
source /home/$USER/source.sh

[ $# -ne 1 ] && { echo "Usage : $0  table "; exit 1; }

table=$1

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log

function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
                #echo "Please find the attached log file for more details"
                exit 1
                else
                    echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
                fi
}

#Executing Spark job with python script
spark-submit --name "SparkJob" --driver-memory 2g --executor-memory 4g --num-executors 3 --conf "spark.yarn.executor.memoryOverhead=709" --conf "spark.yarn.driver.memoryOverhead=209"   /home/$USER/import.py ${table} ${mysqldb} ${hivedb} ${domain} ${port} ${username} ${password}

g_STATUS=$?
log_status $g_STATUS "SPARKJOB ${table} EXECUTION"

echo "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-"
</code>```

The import.py pyspark script is below

```<code>#!/usr/bin/env python
import sys
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext
conf = SparkConf()
sc = SparkContext(conf=conf)
sqlContext = HiveContext(sc)

#Condition to specify exact number of arguments in the spark-submit command line
if len(sys.argv) != 8:
     print "Invalid number of args......"
     print "Usage: spark-submit file.py Input_path Output_path"
     exit()
table=sys.argv[1]
mysqldb=sys.argv[2]
hivedb=sys.argv[3]
domain=sys.argv[4]
port=sys.argv[5]
username=sys.argv[6]
password=sys.argv[7]

#Get table from MYSQL as a Data Frame into Spark
df = sqlContext.read.format("jdbc").option("url", "{}:{}/{}".format(domain,port,mysqldb)).option("driver", "com.mysql.jdbc.Driver").option("dbtable","{}".format(table)).option("user", "{}".format(username)).option("password", "{}".format(password)).load()

df.registerTempTable('mytempTable')

# Create Table in Hive using the temptable
sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))

sc.stop()
</code>```

I am getting the desired results with my above scripts.

I am able to get data from MYSQL database to PYSPARK and then able to create tables in HIVE. Also I am able to collect the logs for each sparkjob.

For example I have 100 tables to import from MYSQL to HIVE.

I am scheduling this shell script as a cronjob. This shell script will run 10 times in parallel in a loop.

I mean ./import.sh table1, ./import.sh table2,./import.sh table3,./import.sh table4 and so on 10 times

Now my question

Each time the shell script is invoked a spark context is being opened. It takes around 10-12 seconds for a spark context to open. Now at the end we are closing the spark context using sc.stop().

So If I want to run the script I have to open 100 spark context and close them after completing the job.

What I want is instead of closing the spark context after completion of the job, Can we reuse the same sparkContext for another table in loop.

I mean when I do this ./import.sh table1 I want to use the sparkcontext that was opened in this job for the table that comes next in the loop. I mean for the table 11.

Is this possible?

If yes then How can I achieve that?

答:
It si possible to do, but you need to change some process.

The easy way is to install the Spark Job Server (Git).

This will allow you to submit multiple spark jobs, and with proper configuration even share DataFrames between applications.

I suggest you to go with this.

Body:
I have a shell script that invokes a pyspark job and creates tables in Hive. The script works fine. Now want to reduce the time taken for the script to run while invoking as cron jobs for more than 100 tables.

The import.sh script is below.

#!/bin/bash
source /home/$USER/source.sh

[ $# -ne 1 ] && { echo "Usage : $0  table "; exit 1; }

table=$1

TIMESTAMP=`date "+%Y-%m-%d"`
touch /home/$USER/logs/${TIMESTAMP}.success_log
touch /home/$USER/logs/${TIMESTAMP}.fail_log
success_logs=/home/$USER/logs/${TIMESTAMP}.success_log
failed_logs=/home/$USER/logs/${TIMESTAMP}.fail_log

function log_status
{
       status=$1
       message=$2
       if [ "$status" -ne 0 ]; then
                echo "`date +\"%Y-%m-%d %H:%M:%S\"` [ERROR] $message [Status] $status : failed" | tee -a "${failed_logs}"
                #echo "Please find the attached log file for more details"
                exit 1
                else
                    echo "`date +\"%Y-%m-%d %H:%M:%S\"` [INFO] $message [Status] $status : success" | tee -a "${success_logs}"
                fi
}

#Executing Spark job with python script
spark-submit --name "SparkJob" --driver-memory 2g --executor-memory 4g --num-executors 3 --conf "spark.yarn.executor.memoryOverhead=709" --conf "spark.yarn.driver.memoryOverhead=209"   /home/$USER/import.py ${table} ${mysqldb} ${hivedb} ${domain} ${port} ${username} ${password}

g_STATUS=$?
log_status $g_STATUS "SPARKJOB ${table} EXECUTION"

echo "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-"

The import.py pyspark script is below

#!/usr/bin/env python
import sys
from pyspark import SparkContext, SparkConf
from pyspark.sql import HiveContext
conf = SparkConf()
sc = SparkContext(conf=conf)
sqlContext = HiveContext(sc)

#Condition to specify exact number of arguments in the spark-submit command line
if len(sys.argv) != 8:
     print "Invalid number of args......"
     print "Usage: spark-submit file.py Input_path Output_path"
     exit()
table=sys.argv[1]
mysqldb=sys.argv[2]
hivedb=sys.argv[3]
domain=sys.argv[4]
port=sys.argv[5]
username=sys.argv[6]
password=sys.argv[7]

#Get table from MYSQL as a Data Frame into Spark
df = sqlContext.read.format("jdbc").option("url", "{}:{}/{}".format(domain,port,mysqldb)).option("driver", "com.mysql.jdbc.Driver").option("dbtable","{}".format(table)).option("user", "{}".format(username)).option("password", "{}".format(password)).load()

df.registerTempTable('mytempTable')

# Create Table in Hive using the temptable
sqlContext.sql("create table {}.`{}` as select * from mytempTable".format(hivedb,table))

sc.stop()

I am getting the desired results with my above scripts.

I am able to get data from MYSQL database to PYSPARK and then able to create tables in HIVE. Also I am able to collect the logs for each sparkjob.

For example I have 100 tables to import from MYSQL to HIVE.

I am scheduling this shell script as a cronjob. This shell script will run 10 times in parallel in a loop.

I mean ./import.sh table1, ./import.sh table2,./import.sh table3,./import.sh table4 and so on 10 times

Now my question

Each time the shell script is invoked a spark context is being opened. It takes around 10-12 seconds for a spark context to open. Now at the end we are closing the spark context using sc.stop().

So If I want to run the script I have to open 100 spark context and close them after completing the job.

What I want is instead of closing the spark context after completion of the job, Can we reuse the same sparkContext for another table in loop.

I mean when I do this ./import.sh table1 I want to use the sparkcontext that was opened in this job for the table that comes next in the loop. I mean for the table 11.

Is this possible?

If yes then How can I achieve that?


问:
SQL - all patients who had only dental visits in 2010
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

```<code>AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )
</code>```

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)

答:
If you are using SQL Server 2005 or later, you can use EXCEPT to exclude a group of records from another query.

So basically write your larger query (show me ALL the patients that had a visit this year!), then...

```<code>...
EXCEPT
SELECT pv1.PatientVisitID
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
</code>```

Something to bear in mind with this is you need to have the same columns in both queries (there can be SOME differences, but for our purposes make sure both the first SELECT and the EXCEPT query return the same fields).

Body:
I have a T-SQL query that's giving me the most recent office visit in 2010 that wasn't a dental visit. The relevant part of the query is:

AND pv.PatientVisitId IN (
    SELECT Max(pv1.PatientVisitID)
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'
    )

Now, I want to flip that around to get the most recent office visit for the patients who only had dental appointments. I keep hitting the wall here, though. Can anyone bust me through to the other side? :-)

Body:
If you are using SQL Server 2005 or later, you can use EXCEPT to exclude a group of records from another query.

So basically write your larger query (show me ALL the patients that had a visit this year!), then...

...
EXCEPT
SELECT pv1.PatientVisitID
        FROM PatientVisit pv1
            JOIN DoctorFacility df1 ON pv1.FacilityID = df1.DoctorFacilityID
            JOIN PatientVisitResource pvr1 ON pv1.PatientVisitId = pvr1.PatientVisitId
                JOIN DoctorFacility dfr ON pvr1.ResourceId = dfr.DoctorFacilityId
        WHERE pv1.PatientProfileID = pp.PatientProfileID
            AND pv1.Visit < '2011-01-01'
            AND df1.ListName NOT LIKE '%Dental%'

Something to bear in mind with this is you need to have the same columns in both queries (there can be SOME differences, but for our purposes make sure both the first SELECT and the EXCEPT query return the same fields).


问:
CSS Font Style Changes Not Working in Chrome
Could someone clarify why the below font style settings is not working in chrome, but working in IE and FireFox.

My website has the same problem, it does not pick up the CSS font settings (where normal is mentioned), hence I tested with the CSS test environment from W3Schools and the behavior is same.

CSS Snippet:

Working only in IE/FireFox: font-family: Arial, Helvetica, sans-serif normal;

Working in All Browsers: font-family: Arial, Helvetica, sans-serif;

Try in Chrome and IE to see difference.

body {
  font-family: "Times New Roman", serif;
}
p.serif {
  font-family: Arial, Helvetica, sans-serif;
}
p.sansserif {
  font-family: Arial, Helvetica, sans-serif normal;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>CSS font-family</h1>
<p class="serif">This is a paragraph, shown in Arial Without Normal.</p>
<p class="sansserif">This is a paragraph, shown in Arial With Normal</p></code>```

Below are the questions:

Could you clarify why the behavior difference between these two browsers?

How to ensure my CSS font styles are picked by Chrome and IE/FireFox (Should I remove normal from all my CSS files or is there any better way to do it)?

答:
Arguably invalid font-family declaration

If you open your browser's inspector (Ctrl+Shift+i in Chrome) you will see that the CSS rule

```<code>p.sansserif {
    font-family: Arial, Helvetica, sans-serif normal;
}
</code>```

is not applied.

Per the CSS specifications, an invalid rule is ignored, and whatever would have been applied (backwards up the cascade) is applied instead or more accurately, not overruled.

The result is "Times New Roman" in this case - as seen in the "Computed Styles".

To set the font-style (-variant, -weight, -stretch or line-height (whichever you were trying to set to normal)) of text, we can either use exactly that, or use the font shorthand.

The font CSS property is either a shorthand property for setting font-style, font-variant, font-weight, font-size, line-height, and font-family...

(with caveats).

As for the difference between IE(and FF) and Chrome

Chrome recognises in the comma delimited assertion that sans-serif normal is not a font-family, whereas IE doesn't.

If you simplify the rule to:

```<code>p.sansserif {
    font-family: sans-serif normal;
}
</code>```

and view the result in IE, you'll see the
 is in "Times New Roman" since, although IE accepts the declaration, it can't do anything sensible with it.

More from the specs:

...it is recommended to quote font family names that contain white space, digits, or punctuation characters other than hyphens.

Font family names that happen to be the same as a keyword value (‘inherit’, ‘serif’, ‘sans-serif’, ‘monospace’, ‘fantasy’, and ‘cursive’) must be quoted to prevent confusion with the keywords with the same names.

So it is recommended that a font family called sans-serif normal be quoted as "sans-serif normal".

And if a font family is using the same name as a keyword it must be quoted.

Both Chrome and IE will accept Comic Sans MS or Times New Roman etc. with or without quotes, and apply them correctly.

Chrome rejects the unquoted use of the keyword sans-serif where it finds it combined with normal, but will accept both if quoted, although it won't be able to apply that font unless it can find one with that name.

IE accepts sans-serif normal as a possibly unquoted font family name, and this is arguably correct, since the keyword is only part of the presumed family name, rather than the whole thing.

Chrome, arguably incorrectly, rejects what it presumes is a malformed assertion.

ContentLicense: CC BY-SA 4.0

Body:
Could someone clarify why the below font style settings is not working in chrome, but working in IE and FireFox.

My website has the same problem, it does not pick up the CSS font settings (where normal is mentioned), hence I tested with the CSS test environment from W3Schools and the behavior is same.

CSS Snippet:

Working only in IE/FireFox: font-family: Arial, Helvetica, sans-serif normal;

Working in All Browsers: font-family: Arial, Helvetica, sans-serif;

Try in Chrome and IE to see difference.

body {
  font-family: "Times New Roman", serif;
}
p.serif {
  font-family: Arial, Helvetica, sans-serif;
}
p.sansserif {
  font-family: Arial, Helvetica, sans-serif normal;
}

CSS font-family

This is a paragraph, shown in Arial Without Normal.

This is a paragraph, shown in Arial With Normal

Below are the questions:

Could you clarify why the behavior difference between these two browsers?

How to ensure my CSS font styles are picked by Chrome and IE/FireFox (Should I remove normal from all my CSS files or is there any better way to do it)?

Body:
Arguably invalid font-family declaration

If you open your browser's inspector (Ctrl+Shift+i in Chrome) you will see that the CSS rule

p.sansserif {
    font-family: Arial, Helvetica, sans-serif normal;
}

is not applied.

Per the CSS specifications, an invalid rule is ignored, and whatever would have been applied (backwards up the cascade) is applied instead or more accurately, not overruled.

The result is "Times New Roman" in this case - as seen in the "Computed Styles".

To set the font-style (-variant, -weight, -stretch or line-height (whichever you were trying to set to normal)) of text, we can either use exactly that, or use the font shorthand.

The font CSS property is either a shorthand property for setting font-style, font-variant, font-weight, font-size, line-height, and font-family...

(with caveats).

As for the difference between IE(and FF) and Chrome

Chrome recognises in the comma delimited assertion that sans-serif normal is not a font-family, whereas IE doesn't.

If you simplify the rule to:

p.sansserif {
    font-family: sans-serif normal;
}

and view the result in IE, you'll see the <p> is in "Times New Roman" since, although IE accepts the declaration, it can't do anything sensible with it.

More from the specs:

...it is recommended to quote font family names that contain white space, digits, or punctuation characters other than hyphens.

Font family names that happen to be the same as a keyword value (‘inherit’, ‘serif’, ‘sans-serif’, ‘monospace’, ‘fantasy’, and ‘cursive’) must be quoted to prevent confusion with the keywords with the same names.

So it is recommended that a font family called sans-serif normal be quoted as "sans-serif normal".

And if a font family is using the same name as a keyword it must be quoted.

Both Chrome and IE will accept Comic Sans MS or Times New Roman etc. with or without quotes, and apply them correctly.

Chrome rejects the unquoted use of the keyword sans-serif where it finds it combined with normal, but will accept both if quoted, although it won't be able to apply that font unless it can find one with that name.

IE accepts sans-serif normal as a possibly unquoted font family name, and this is arguably correct, since the keyword is only part of the presumed family name, rather than the whole thing.

Chrome, arguably incorrectly, rejects what it presumes is a malformed assertion.