问:
Generating regex-based string with RandExp
I need to generate a string based on regex which would result random letters and numbers, 4 dashes at random places in 36-character string.

Example:

123A5678-01B3C5F7-901R345-789F1-3456

I've figured out a regex that seems to validate given string well:

(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+

...but using the same for generating string in RandExp ends  up in a mess. It generates 36-character string and adds 5 random-length groups:

new RandExp(/(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+/).gen()

M78QMOC6OGIF5OAJAJCG68CQWJGT5FX43CTKZ9CS9GXWLEKUKZMG602U5HPR4CEKO7OIX45CMLB7DS5RHZBI8KE8HGO9ET6OWS9A-PQSHN9E36KIMW328A1L0BHXCFOJVCD2ZT11-KD03XTZ375WP7CR7YSF4CTSX-0FBJ3MZ4RNDLA5UZOHI5QWVY66PTUDDRCG-OH4F688VM1

Should I just settle for fixed-width groups for my string using something like:

([0-9A-Z]{6}-){4}[0-9A-Z]{8}

... or is there any way I could improve the original regex?

答:
It seems impossible to use a whole string length restricting lookahead with Randexp. I also tried with your pattern, and it generates a string with n chars of any type, like $>Qa MG4XT@#j{3#&[+V4=^"VQLI*|b%bp~@ (1).

It is even more strange when you apply anchors, new RandExp(/^(?=.{36}$)(?:[0-9A-Z]+-){4}[0-9A-Z]+$/) will also produce some ~30 chars of various types at the start of the string. It might be related to the fact that $ is not used at the final pattern position, and is ignored (see Bad Regular Expressions). It looks like a bug to me.

Removing the lookahead and adding ^ start-of-string anchor at the start and $ end-of-string anchor at the end makes it generate somewhat better strings (2). However, you might really want to only use fixed length groups (3).

document.body.innerHTML = "(1) " + new RandExp(/(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+/).gen();
document.body.innerHTML += "

(2) " + new RandExp(/^(?:[0-9A-Z]+-){4}[0-9A-Z]+$/).gen();
document.body.innerHTML += "

(3) " + new RandExp(/^(?:[0-9A-Z]{6}-){4}[0-9A-Z]{8}$/).gen();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://github.com/fent/randexp.js/releases/download/v0.4.1/randexp.min.js"></script></code>```

You may then try to work around that problem by using /^(?:[0-9A-Z]{6,8}-){4}[0-9A-Z]{6,8}$/ regex in a loop and only return a result if the string is 36 chars long:

var rdx = new RandExp(/^(?:[0-9A-Z]{6,8}-){4}[0-9A-Z]{6,8}$/);
var res = rdx.gen();
while (res.length !== 36) {
    res = rdx.gen();
}
document.body.innerHTML = res;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://github.com/fent/randexp.js/releases/download/v0.4.1/randexp.min.js"></script></code>```

Body:
It seems impossible to use a whole string length restricting lookahead with Randexp. I also tried with your pattern, and it generates a string with n chars of any type, like $>Qa MG4XT@#j{3#&[+V4=^"VQLI*|b%bp~@ (1).

It is even more strange when you apply anchors, new RandExp(/^(?=.{36}$)(?:[0-9A-Z]+-){4}[0-9A-Z]+$/) will also produce some ~30 chars of various types at the start of the string. It might be related to the fact that $ is not used at the final pattern position, and is ignored (see Bad Regular Expressions). It looks like a bug to me.

Removing the lookahead and adding ^ start-of-string anchor at the start and $ end-of-string anchor at the end makes it generate somewhat better strings (2). However, you might really want to only use fixed length groups (3).

document.body.innerHTML = "(1)&nbsp;" + new RandExp(/(?=.{36}$)([0-9A-Z]+-){4}([0-9A-Z])+/).gen();
document.body.innerHTML += "<br/><br/>(2)&nbsp;" + new RandExp(/^(?:[0-9A-Z]+-){4}[0-9A-Z]+$/).gen();
document.body.innerHTML += "<br/><br/>(3)&nbsp;" + new RandExp(/^(?:[0-9A-Z]{6}-){4}[0-9A-Z]{8}$/).gen();

<script src="https://github.com/fent/randexp.js/releases/download/v0.4.1/randexp.min.js"></script>

You may then try to work around that problem by using /^(?:[0-9A-Z]{6,8}-){4}[0-9A-Z]{6,8}$/ regex in a loop and only return a result if the string is 36 chars long:

var rdx = new RandExp(/^(?:[0-9A-Z]{6,8}-){4}[0-9A-Z]{6,8}$/);
var res = rdx.gen();
while (res.length !== 36) {
    res = rdx.gen();
}
document.body.innerHTML = res;

<script src="https://github.com/fent/randexp.js/releases/download/v0.4.1/randexp.min.js"></script>


来源: stackexchange

问:
Optimize code to find the median of values of past 4 to 6 days for each row in a DataFrame
Given a dataframe of timestamp data, I would like to compute the median of certain variable of past 4-6 days.
Median of past 1-3 days can be computed by pd.pandas.DataFrame.rolling, but I couldn't find how to use rolling to compute the median of past 4-6 days.

```<code>import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame()
df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='6H')
df['timestamp'] = df.timestamp.astype(pd.Timestamp)
np.random.seed(1)
df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))
</code>```

Data looks like this. In my real data, there are gaps in time and maybe more data points in one day.

```<code>              timestamp       var
0   2011-01-01 00:00:00  1.624345
1   2011-01-01 06:00:00 -0.611756
2   2011-01-01 12:00:00 -0.528172
3   2011-01-01 18:00:00 -1.072969
4   2011-01-02 00:00:00  0.865408
5   2011-01-02 06:00:00 -2.301539
6   2011-01-02 12:00:00  1.744812
7   2011-01-02 18:00:00 -0.761207
8   2011-01-03 00:00:00  0.319039
9   2011-01-03 06:00:00 -0.249370
10  2011-01-03 12:00:00  1.462108
</code>```

Desired output:

```<code>              timestamp       var  past4d-6d_var_median
0   2011-01-01 00:00:00  1.624345                   NaN # no data in past 4-6 days
1   2011-01-01 06:00:00 -0.611756                   NaN # no data in past 4-6 days
2   2011-01-01 12:00:00 -0.528172                   NaN # no data in past 4-6 days
3   2011-01-01 18:00:00 -1.072969                   NaN # no data in past 4-6 days
4   2011-01-02 00:00:00  0.865408                   NaN # no data in past 4-6 days
5   2011-01-02 06:00:00 -2.301539                   NaN # no data in past 4-6 days
6   2011-01-02 12:00:00  1.744812                   NaN # no data in past 4-6 days
7   2011-01-02 18:00:00 -0.761207                   NaN # no data in past 4-6 days
8   2011-01-03 00:00:00  0.319039                   NaN # no data in past 4-6 days
9   2011-01-03 06:00:00 -0.249370                   NaN # no data in past 4-6 days
10  2011-01-03 12:00:00  1.462108                   NaN # no data in past 4-6 days
11  2011-01-03 18:00:00 -2.060141                   NaN # no data in past 4-6 days
12  2011-01-04 00:00:00 -0.322417                   NaN # no data in past 4-6 days
13  2011-01-04 06:00:00 -0.384054                   NaN # no data in past 4-6 days
14  2011-01-04 12:00:00  1.133769                   NaN # no data in past 4-6 days
15  2011-01-04 18:00:00 -1.099891                   NaN # no data in past 4-6 days
16  2011-01-05 00:00:00 -0.172428                   NaN # only 4 data in past 4-6 days
17  2011-01-05 06:00:00 -0.877858             -0.528172
18  2011-01-05 12:00:00  0.042214             -0.569964
19  2011-01-05 18:00:00  0.582815             -0.528172
20  2011-01-06 00:00:00 -1.100619             -0.569964
21  2011-01-06 06:00:00  1.144724             -0.528172
22  2011-01-06 12:00:00  0.901591             -0.388771
23  2011-01-06 18:00:00  0.502494             -0.249370
</code>```

My current code:

```<code>def findPastVar2(df, var='var' ,window=3, method='median'):
    # window= # of past days
    for i in xrange(len(df)):
        pastVar2 = df[var].loc[(df['timestamp'] - df['timestamp'].loc[i] < datetime.timedelta(days=-window)) & (df['timestamp'] - df['timestamp'].loc[i] >= datetime.timedelta(days=-window*2))]
        if pastVar2.shape[0]>=5: # At least 5 data points
            if method == 'median':
                df.loc[i,'past{}d-{}d_{}_median'.format(window+1,window*2,var)] = np.median(pastVar2.values)
    return(df)
</code>```

Current speed:

```<code>In [35]: %timeit df2 = findPastVar2(df)
1 loop, best of 3: 821 ms per loop
</code>```

I edited the post so that I can clearly show my expected output of at least 5 data points. I've set the random seed so that everyone should be able to get the same input and show the same output. As far as I know simple rolling and shift does not work for the case of multiple data in the same day.

答:
The min_period should be 2 instead of 5 because you should not count window size in. (5 - 3 = 2)

```<code>import pandas as pd
import numpy as np
import datetime
np.random.seed(1)  # set random seed for easier comparison
df = pd.DataFrame()
df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='D')
df['timestamp'] = df.timestamp.astype(pd.Timestamp)
df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))

def first():
    df['past4d-6d_var_median'] = [np.nan]*3 + df.rolling(window=3, min_periods=2).median()[:-3]['var'].tolist()
    return df
</code>```

```<code>%timeit -n1000 first()
1000 loops, best of 3: 6.23 ms per loop
</code>```

My first try didn't use shift(), but then I saw Noobie's answer.

I made the following one with shift(), which is much faster than previous one.

```<code>def test():
    df['past4d-6d_var_median'] = df['var'].rolling(window=3, min_periods=2).median().shift(3)
    return df
</code>```

```<code>%timeit -n1000 test()
1000 loops, best of 3: 1.66 ms per loop
</code>```

The second one is around 4 times as fast as the first one.

These two function creates the same result, which looks like this:

```<code>df2 = test()
df2
                  timestamp       var   past4d-6d_var_median
    0   2011-01-01 00:00:00  1.624345                    NaN
    1   2011-01-02 00:00:00 -0.611756                    NaN
    2   2011-01-03 00:00:00 -0.528172                    NaN
    3   2011-01-04 00:00:00 -1.072969                    NaN
    4   2011-01-05 00:00:00  0.865408               0.506294
    5   2011-01-06 00:00:00 -2.301539              -0.528172
    6   2011-01-07 00:00:00  1.744812              -0.611756
    ...         ...            ...             ...
    93  2011-04-04 00:00:00 -0.638730               1.129484
    94  2011-04-05 00:00:00  0.423494               1.129484
    95  2011-04-06 00:00:00  0.077340               0.185156
    96  2011-04-07 00:00:00 -0.343854              -0.375285
    97  2011-04-08 00:00:00  0.043597              -0.375285
    98  2011-04-09 00:00:00 -0.620001               0.077340
    99  2011-04-10 00:00:00  0.698032               0.077340
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given a dataframe of timestamp data, I would like to compute the median of certain variable of past 4-6 days.
Median of past 1-3 days can be computed by pd.pandas.DataFrame.rolling, but I couldn't find how to use rolling to compute the median of past 4-6 days.

import pandas as pd
import numpy as np
import datetime
df = pd.DataFrame()
df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='6H')
df['timestamp'] = df.timestamp.astype(pd.Timestamp)
np.random.seed(1)
df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))

Data looks like this. In my real data, there are gaps in time and maybe more data points in one day.

              timestamp       var
0   2011-01-01 00:00:00  1.624345
1   2011-01-01 06:00:00 -0.611756
2   2011-01-01 12:00:00 -0.528172
3   2011-01-01 18:00:00 -1.072969
4   2011-01-02 00:00:00  0.865408
5   2011-01-02 06:00:00 -2.301539
6   2011-01-02 12:00:00  1.744812
7   2011-01-02 18:00:00 -0.761207
8   2011-01-03 00:00:00  0.319039
9   2011-01-03 06:00:00 -0.249370
10  2011-01-03 12:00:00  1.462108

Desired output:

              timestamp       var  past4d-6d_var_median
0   2011-01-01 00:00:00  1.624345                   NaN # no data in past 4-6 days
1   2011-01-01 06:00:00 -0.611756                   NaN # no data in past 4-6 days
2   2011-01-01 12:00:00 -0.528172                   NaN # no data in past 4-6 days
3   2011-01-01 18:00:00 -1.072969                   NaN # no data in past 4-6 days
4   2011-01-02 00:00:00  0.865408                   NaN # no data in past 4-6 days
5   2011-01-02 06:00:00 -2.301539                   NaN # no data in past 4-6 days
6   2011-01-02 12:00:00  1.744812                   NaN # no data in past 4-6 days
7   2011-01-02 18:00:00 -0.761207                   NaN # no data in past 4-6 days
8   2011-01-03 00:00:00  0.319039                   NaN # no data in past 4-6 days
9   2011-01-03 06:00:00 -0.249370                   NaN # no data in past 4-6 days
10  2011-01-03 12:00:00  1.462108                   NaN # no data in past 4-6 days
11  2011-01-03 18:00:00 -2.060141                   NaN # no data in past 4-6 days
12  2011-01-04 00:00:00 -0.322417                   NaN # no data in past 4-6 days
13  2011-01-04 06:00:00 -0.384054                   NaN # no data in past 4-6 days
14  2011-01-04 12:00:00  1.133769                   NaN # no data in past 4-6 days
15  2011-01-04 18:00:00 -1.099891                   NaN # no data in past 4-6 days
16  2011-01-05 00:00:00 -0.172428                   NaN # only 4 data in past 4-6 days
17  2011-01-05 06:00:00 -0.877858             -0.528172
18  2011-01-05 12:00:00  0.042214             -0.569964
19  2011-01-05 18:00:00  0.582815             -0.528172
20  2011-01-06 00:00:00 -1.100619             -0.569964
21  2011-01-06 06:00:00  1.144724             -0.528172
22  2011-01-06 12:00:00  0.901591             -0.388771
23  2011-01-06 18:00:00  0.502494             -0.249370

My current code:

def findPastVar2(df, var='var' ,window=3, method='median'):
    # window= # of past days
    for i in xrange(len(df)):
        pastVar2 = df[var].loc[(df['timestamp'] - df['timestamp'].loc[i] < datetime.timedelta(days=-window)) & (df['timestamp'] - df['timestamp'].loc[i] >= datetime.timedelta(days=-window*2))]
        if pastVar2.shape[0]>=5: # At least 5 data points
            if method == 'median':
                df.loc[i,'past{}d-{}d_{}_median'.format(window+1,window*2,var)] = np.median(pastVar2.values)
    return(df)

Current speed:

In [35]: %timeit df2 = findPastVar2(df)
1 loop, best of 3: 821 ms per loop

I edited the post so that I can clearly show my expected output of at least 5 data points. I've set the random seed so that everyone should be able to get the same input and show the same output. As far as I know simple rolling and shift does not work for the case of multiple data in the same day.

Body:
The min_period should be 2 instead of 5 because you should not count window size in. (5 - 3 = 2)

import pandas as pd
import numpy as np
import datetime
np.random.seed(1)  # set random seed for easier comparison
df = pd.DataFrame()
df['timestamp'] = pd.date_range('1/1/2011', periods=100, freq='D')
df['timestamp'] = df.timestamp.astype(pd.Timestamp)
df['var'] = pd.Series(np.random.randn(len(df['timestamp'])))

def first():
    df['past4d-6d_var_median'] = [np.nan]*3 + df.rolling(window=3, min_periods=2).median()[:-3]['var'].tolist()
    return df

%timeit -n1000 first()
1000 loops, best of 3: 6.23 ms per loop

My first try didn't use shift(), but then I saw Noobie's answer.

I made the following one with shift(), which is much faster than previous one.

def test():
    df['past4d-6d_var_median'] = df['var'].rolling(window=3, min_periods=2).median().shift(3)
    return df

%timeit -n1000 test()
1000 loops, best of 3: 1.66 ms per loop

The second one is around 4 times as fast as the first one.

These two function creates the same result, which looks like this:

df2 = test()
df2
                  timestamp       var   past4d-6d_var_median
    0   2011-01-01 00:00:00  1.624345                    NaN
    1   2011-01-02 00:00:00 -0.611756                    NaN
    2   2011-01-03 00:00:00 -0.528172                    NaN
    3   2011-01-04 00:00:00 -1.072969                    NaN
    4   2011-01-05 00:00:00  0.865408               0.506294
    5   2011-01-06 00:00:00 -2.301539              -0.528172
    6   2011-01-07 00:00:00  1.744812              -0.611756
    ...         ...            ...             ...
    93  2011-04-04 00:00:00 -0.638730               1.129484
    94  2011-04-05 00:00:00  0.423494               1.129484
    95  2011-04-06 00:00:00  0.077340               0.185156
    96  2011-04-07 00:00:00 -0.343854              -0.375285
    97  2011-04-08 00:00:00  0.043597              -0.375285
    98  2011-04-09 00:00:00 -0.620001               0.077340
    99  2011-04-10 00:00:00  0.698032               0.077340


问:
On Error goto <label> (incorrectly works)
When “run-time error 1004” occurs I want the program to skip a part of the code and work further . With the first variable it works normally , but with the second “run-time error 1004”  again pops up.</p>

```<code>    Sub связатьцифирь14()
    Dim book1 As Workbook
    Dim book2 As Workbook
    Dim r As Range
    Dim firstAddress As String
    Dim n, m, e, t As Long
    Dim A()
    Dim B()
    Dim D()
    Dim F()
    Dim G As String
    Dim H As String
    Dim intBe As Integer
    Dim varValue1 As Variant
    Dim varValue2 As Variant

    'сезон (прошлый,допрошлый,додопрошлый)
    A = Array("прошлый", "допрошлый", "додопрошлый")
    'страна
    D = Array("Англия", "Испания", "Италия", "Германия", "Голландия", "Франция", "Португалия", "Россия", "Украина")
   'место (1,2,3,4,5,6)
    B = Array("1", "2", "3", "4", "5", "6")
    'номер условия
    F = Array("6", "7", "8", "16", "17", "21", "22", "23", "25", "26", "29", "30", "31", "54", "55", "56", "57", "58", "59")
   'Общ п/пр
    G = "AP100"
    'Общ
    H = "AO100"

    Set book1 = Workbooks.Open("E:\Super M\Проект ставки\Решение\цифирь.xlsx")

    'переходим в активную страницу откуда надо скопировать данные'
    'массив условие
     For t = 0 To 18
    'массив страна
     For m = 0 To 8
    'массив сезон
    For n = 0 To 2
    'массив место
    For e = 0 To 5

   'пропускаем ошибку
   On Error GoTo Label1
   Set book2 = Workbooks.Open("E:\Super M\Проект ставки\Поиск решения\Усов 4\БАЗА ДАННЫХ\" & A(n) & " сезон\" & D(m) & "\" & B(e) & "-ое место\" & F(t) & ".xlsx")

   intBe = CInt(B(e)) + 5
   varValue1 = book2.Worksheets("" & F(t) & "").Range("" & G & "").Value
   varValue2 = book2.Worksheets("" & F(t) & "").Range("" & H & "").Value
   'ищемс
   With book1.Worksheets("Лист1").Range("A1:CV808")

    Set r = .Find(What:="" & F(t) & "", LookAt:=xlWhole, LookIn:=xlValues)
    If Not r Is Nothing Then
        firstAddress = r.Address
        Do
         'условие для страны
         'прошлый сезон
         If r.Offset(3, 0).Text = D(m) And A(n) = "прошлый" Then
         r.Offset(intBe, 5).Value = varValue1
         r.Offset(intBe, 6).Value = varValue2
         End If
         'допрошлый сезон
        If r.Offset(3, 0).Text = D(m) And A(n) = "допрошлый" Then
        r.Offset(intBe, 3).Value = varValue1
        r.Offset(intBe, 4).Value = varValue2
        End If
         'додопрошлый сезон
         If r.Offset(3, 0).Text = D(m) And A(n) = "додопрошлый" Then
        r.Offset(intBe, 1).Value = varValue1
        r.Offset(intBe, 2).Value = varValue2
        End If

        Set r = .FindNext(r)

        Loop While Not r Is Nothing And r.Address <> firstAddress
    End If
    End With
    book2.Close
    Next e
   book1.Save
   Label2:
   Next n
   Next m
   Next t
   book1.Save
   book1.Close
   Exit Sub
   Label1:
   On Error Resume Next
   GoTo Label2
   End Sub
</code>```

答:
You are not exiting from your error-handler correctly - you are using a GoTo instead of a Resume.  Because you were effectively still within the error-handling code when you encountered the second error, the error was not able to be trapped.

Therefore, change

```<code>GoTo Label2
</code>```

to

```<code>Resume Label2
</code>```

Body:
When “run-time error 1004” occurs I want the program to skip a part of the code and work further . With the first variable it works normally , but with the second “run-time error 1004”  again pops up.

    Sub связатьцифирь14()
    Dim book1 As Workbook
    Dim book2 As Workbook
    Dim r As Range
    Dim firstAddress As String
    Dim n, m, e, t As Long
    Dim A()
    Dim B()
    Dim D()
    Dim F()
    Dim G As String
    Dim H As String
    Dim intBe As Integer
    Dim varValue1 As Variant
    Dim varValue2 As Variant

    'сезон (прошлый,допрошлый,додопрошлый)
    A = Array("прошлый", "допрошлый", "додопрошлый")
    'страна
    D = Array("Англия", "Испания", "Италия", "Германия", "Голландия", "Франция", "Португалия", "Россия", "Украина")
   'место (1,2,3,4,5,6)
    B = Array("1", "2", "3", "4", "5", "6")
    'номер условия
    F = Array("6", "7", "8", "16", "17", "21", "22", "23", "25", "26", "29", "30", "31", "54", "55", "56", "57", "58", "59")
   'Общ п/пр
    G = "AP100"
    'Общ
    H = "AO100"

    Set book1 = Workbooks.Open("E:\Super M\Проект ставки\Решение\цифирь.xlsx")

    'переходим в активную страницу откуда надо скопировать данные'
    'массив условие
     For t = 0 To 18
    'массив страна
     For m = 0 To 8
    'массив сезон
    For n = 0 To 2
    'массив место
    For e = 0 To 5

   'пропускаем ошибку
   On Error GoTo Label1
   Set book2 = Workbooks.Open("E:\Super M\Проект ставки\Поиск решения\Усов 4\БАЗА ДАННЫХ\" & A(n) & " сезон\" & D(m) & "\" & B(e) & "-ое место\" & F(t) & ".xlsx")

   intBe = CInt(B(e)) + 5
   varValue1 = book2.Worksheets("" & F(t) & "").Range("" & G & "").Value
   varValue2 = book2.Worksheets("" & F(t) & "").Range("" & H & "").Value
   'ищемс
   With book1.Worksheets("Лист1").Range("A1:CV808")

    Set r = .Find(What:="" & F(t) & "", LookAt:=xlWhole, LookIn:=xlValues)
    If Not r Is Nothing Then
        firstAddress = r.Address
        Do
         'условие для страны
         'прошлый сезон
         If r.Offset(3, 0).Text = D(m) And A(n) = "прошлый" Then
         r.Offset(intBe, 5).Value = varValue1
         r.Offset(intBe, 6).Value = varValue2
         End If
         'допрошлый сезон
        If r.Offset(3, 0).Text = D(m) And A(n) = "допрошлый" Then
        r.Offset(intBe, 3).Value = varValue1
        r.Offset(intBe, 4).Value = varValue2
        End If
         'додопрошлый сезон
         If r.Offset(3, 0).Text = D(m) And A(n) = "додопрошлый" Then
        r.Offset(intBe, 1).Value = varValue1
        r.Offset(intBe, 2).Value = varValue2
        End If

        Set r = .FindNext(r)

        Loop While Not r Is Nothing And r.Address <> firstAddress
    End If
    End With
    book2.Close
    Next e
   book1.Save
   Label2:
   Next n
   Next m
   Next t
   book1.Save
   book1.Close
   Exit Sub
   Label1:
   On Error Resume Next
   GoTo Label2
   End Sub

Body:
You are not exiting from your error-handler correctly - you are using a GoTo instead of a Resume.  Because you were effectively still within the error-handling code when you encountered the second error, the error was not able to be trapped.

Therefore, change

GoTo Label2

to

Resume Label2


问:
SQL query to get the count by applying group by
I want to get the below result:

source table :

```<code>Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE
</code>```

Result:

```<code>Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE
</code>```

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

答:
Solution for Oracle - substr(B,0,instr(B,'/',1)-1) B

Put this both in select and groupby

Body:
I want to get the below result:

source table :

Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE

Result:

Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)


问:
JSON from yahoo financial API SyntaxError when is given as parameter to google chart table
I use yahoo financial API to get data from it and then I want to input the data in google chart, but it seems that I have a problem with the JSON  object. So, I tried everything which I read , but unfortunately still unsuccessful.

Error

index.html:1 Uncaught SyntaxError: Unexpected token u in JSON at
  position 0
      at JSON.parse ()
      at drawChart (main.js:18)
      at Object.google.a.c.Ac (loader.js:155)
      at Object.google.a.c.Pa (loader.js:155)
      at f (loader.js:152)
      at Object.google.l.m.kj (loader.js:229)
      at Object.google.l.m.ce (loader.js:229)
      at loader.js:228

JavaScript

```<code>google.charts.load('current', {
'packages': ['corechart']
});

google.charts.setOnLoadCallback(drawChart);

var options = {
    'title': 'Today is not my day',
    'width': 400,
    'height': 300
};

var input = getData();

function drawChart() {
    var chartData = google.visualization.arrayToDataTable(JSON.parse(input));
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(chartData, options);
};

function getData() {
   dataArray = [
    ['Name', 'Volume'],
  ];

  var BASE_URL = "https://query.yahooapis.com/v1/public/yql?q=";
  var yql_query = 'select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")';
  var yql_query_str = encodeURI(BASE_URL + yql_query);
  var result = yql_query_str + "&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

  $.getJSON(result, function(data){
    var object = data.query.results.quote;
    for (var i = 0; i < object.length; i++) {
      var currentObj = object[i];
      var pushedArray = [currentObj.Name, parseFloat(currentObj.Volume)];
      dataArray[i+1] = pushedArray;
    }
    return dataArray;
  });
};
</code>```

HTML

```<code><html>
  <head>
    <meta charset="UTF-8">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- <script type="text/javascript" src="js/request.js"></script> -->
    <script type="text/javascript" src="js/main.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="row">
        <div class="col-md-12" id="chart_div"></div>
      </div>
    </div>

    <script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
  </body>
</html>
</code>```

答:
As it is written above, getData() synchronously returns undefined, so inside of drawChart() you're essentially trying to JSON.parse(undefined), which leads to the SyntaxError you received (JSON.parse() casts undefined to the string "undefined", which is invalid JSON).

dataArray is being returned from within the callback to $.getJSON() after the request returns; there is no way it could currently be accessible inside of the drawChart() function.

You need to refactor the code so that drawChart() is called after the $getJSON() request has returned, and so it has access to dataArray either lexically or through a closure.

Body:
I use yahoo financial API to get data from it and then I want to input the data in google chart, but it seems that I have a problem with the JSON  object. So, I tried everything which I read , but unfortunately still unsuccessful.

Error

index.html:1 Uncaught SyntaxError: Unexpected token u in JSON at
  position 0
      at JSON.parse ()
      at drawChart (main.js:18)
      at Object.google.a.c.Ac (loader.js:155)
      at Object.google.a.c.Pa (loader.js:155)
      at f (loader.js:152)
      at Object.google.l.m.kj (loader.js:229)
      at Object.google.l.m.ce (loader.js:229)
      at loader.js:228

JavaScript

google.charts.load('current', {
'packages': ['corechart']
});

google.charts.setOnLoadCallback(drawChart);

var options = {
    'title': 'Today is not my day',
    'width': 400,
    'height': 300
};

var input = getData();

function drawChart() {
    var chartData = google.visualization.arrayToDataTable(JSON.parse(input));
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(chartData, options);
};

function getData() {
   dataArray = [
    ['Name', 'Volume'],
  ];

  var BASE_URL = "https://query.yahooapis.com/v1/public/yql?q=";
  var yql_query = 'select * from yahoo.finance.quote where symbol in ("YHOO","AAPL","GOOG","MSFT")';
  var yql_query_str = encodeURI(BASE_URL + yql_query);
  var result = yql_query_str + "&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";

  $.getJSON(result, function(data){
    var object = data.query.results.quote;
    for (var i = 0; i < object.length; i++) {
      var currentObj = object[i];
      var pushedArray = [currentObj.Name, parseFloat(currentObj.Volume)];
      dataArray[i+1] = pushedArray;
    }
    return dataArray;
  });
};

HTML

    <meta charset="UTF-8">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">


问:
Unable to open Eclipse (configuration area .. error)
When try to start my Eclipse I am getting the following error:

The configuration area at '/usr/lib/eclipse/configuration' could not
  be created. Please choose a writable location

Can anyone help me out in this?

答:
Check if your disk quota was exceeded, I faced the same issue and tried all the suggestions on this thread.

Finally, I found out that the disk free space was 0.

Hope that it helped.


问:
Stream Analytics - query nested arrays returns 0 results
I have an array of messages; within each message is another array of start/stop values. I can get the array of messages fine, but getting the next level of nested start/stop values returns 0 records while executing a stream analytics query in Azure.

Here is the Stream Analytics query.

```<code>WITH
main AS
(
    SELECT          message.ArrayValue.header.messageId,
                    message.ArrayValue.startStopBlock as SSBlock

    FROM            IoTHub i
    CROSS APPLY     GetArrayElements(i.[STARTSTOPTIME:topic].message) AS
message
)

SELECT              m.messageId,
                    SSEntry.ArrayValue.start,
                    SSEntry.ArrayValue.stop

FROM            main m
CROSS APPLY     GetArrayElements(m.SSBLOCK.ArrayValue.startStop) AS SSEntry
</code>```

Here is the json

{
 "@xsi:schemaLocation" : "",
 "nextBuffer" : {
  "url" : "",
  "moreData" : "false"
 },
 "message" : [{
   "header" : {
    "messageId" : "951262328",
   },
   "totalStartStops" : "2",
   "startStopBlock" : {
    "startStop" : [{
      "start" : "2017-05-16 14:11:01",
      "stop" : "2017-05-16 14:14:16",
      "operatorId" : "0"
     }, {
      "start" : "2017-05-16 14:38:45",
      "stop" : "2017-05-16 14:44:19",
      "operatorId" : "0"
     }
    ]
   }
  }, {
   "header" : {
    "messageId" : "951266462",
   },
   "totalStartStops" : "2",
   "startStopBlock" : {
    "startStop" : [{
      "start" : "2017-05-16 14:08:09",
      "stop" : "2017-05-16 14:08:20",
      "operatorId" : "-1"
     }, {
      "start" : "2017-05-16 14:54:38",
      "stop" : "2017-05-16 15:01:17",
      "operatorId" : "-1"
     }
    ]
   }
  }
 ]
}```

答:
Per my understanding, you could try to retrieve the nested arrays in your first query by changing message.ArrayValue.startStopBlock as SSBlock to message.ArrayValue.startStopBlock.startStop as SSBlock. Here is my test, you could refer to it:

Query

WITH main AS
(
    SELECT
      message.ArrayValue.header.messageId,
      message.ArrayValue.startStopBlock.startStop as SSBlock
    FROM IoTHub i
    CROSS APPLY GetArrayElements(i.message) AS message
)

SELECT
  m.messageId,
  SSEntry.ArrayValue.start,
  SSEntry.ArrayValue.stop
FROM main m
CROSS APPLY GetArrayElements(m.SSBLOCK) AS SSEntry
```

Result

Body:
I have an array of messages; within each message is another array of start/stop values. I can get the array of messages fine, but getting the next level of nested start/stop values returns 0 records while executing a stream analytics query in Azure.

Here is the Stream Analytics query.

WITH
main AS
(
    SELECT          message.ArrayValue.header.messageId,
                    message.ArrayValue.startStopBlock as SSBlock

    FROM            IoTHub i
    CROSS APPLY     GetArrayElements(i.[STARTSTOPTIME:topic].message) AS
message
)

SELECT              m.messageId,
                    SSEntry.ArrayValue.start,
                    SSEntry.ArrayValue.stop

FROM            main m
CROSS APPLY     GetArrayElements(m.SSBLOCK.ArrayValue.startStop) AS SSEntry

Here is the json

{
 "@xsi:schemaLocation" : "",
 "nextBuffer" : {
  "url" : "",
  "moreData" : "false"
 },
 "message" : [{
   "header" : {
    "messageId" : "951262328",
   },
   "totalStartStops" : "2",
   "startStopBlock" : {
    "startStop" : [{
      "start" : "2017-05-16 14:11:01",
      "stop" : "2017-05-16 14:14:16",
      "operatorId" : "0"
     }, {
      "start" : "2017-05-16 14:38:45",
      "stop" : "2017-05-16 14:44:19",
      "operatorId" : "0"
     }
    ]
   }
  }, {
   "header" : {
    "messageId" : "951266462",
   },
   "totalStartStops" : "2",
   "startStopBlock" : {
    "startStop" : [{
      "start" : "2017-05-16 14:08:09",
      "stop" : "2017-05-16 14:08:20",
      "operatorId" : "-1"
     }, {
      "start" : "2017-05-16 14:54:38",
      "stop" : "2017-05-16 15:01:17",
      "operatorId" : "-1"
     }
    ]
   }
  }
 ]
}

Body:
Per my understanding, you could try to retrieve the nested arrays in your first query by changing message.ArrayValue.startStopBlock as SSBlock to message.ArrayValue.startStopBlock.startStop as SSBlock. Here is my test, you could refer to it:

Query

WITH main AS
(
    SELECT
      message.ArrayValue.header.messageId,
      message.ArrayValue.startStopBlock.startStop as SSBlock
    FROM IoTHub i
    CROSS APPLY GetArrayElements(i.message) AS message
)

SELECT
  m.messageId,
  SSEntry.ArrayValue.start,
  SSEntry.ArrayValue.stop
FROM main m
CROSS APPLY GetArrayElements(m.SSBLOCK) AS SSEntry

Result


问:
Html/Css dynamic centering
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="center-container">
      <div class="inner-container">
          <div class="group-container">
              <div class="element"></div>
              <div class="element"></div>
              <div class="element"></div>
          </div>
          <div class="group-container">
              <div class="element"></div>
              <div class="element"></div>
              <div class="element"></div>
          </div>
      </div>
  </div>
</div></code>```

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)

答: Add text-align: center to the parent(inner-container). You should be sorted.

Title: Html/Css dynamic centering

Body:
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)


问:
django checkbox select all by jquery
I want to select all checkbox when i click the top check,
below is my code:

run.html

```<code><script language="JavaScript" src="media/js/jquery-1.4.2.min.js"></script>
<script language="javascript">
$("#selectAll").change(function() {
  $(".xxx:checkbox").attr('checked', this.checked);
});
</script>
Select All: <input type="checkbox" id="selectAll"><br />
<br />

One: <input type="checkbox" class="xxx" /><br />
Two: <input type="checkbox" class="xxx" /><br />
Three: <input type="checkbox" class="xxx" />
</code>```

but why it not work?

答:
Here is a simple example for select all Checkbox.....

```<code><ul>
<li><input type="checkbox" id="select_all"/> Selecct All</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 1</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 2</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 3</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 4</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 5</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 6</li>
</code>```

```<code><script>
  var select_all = document.getElementById("select_all"); //select all checkbox
   var checkboxes = document.getElementsByClassName("checkbox");
   //checkbox items

  //select all checkboxes
  select_all.addEventListener("change", function(e){
  for (i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = select_all.checked;
 }
});

for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
    //uncheck "select all", if one of the listed checkbox item is unchecked
    if(this.checked == false){
        select_all.checked = false;
    }
    //check "select all" if all checkbox items are checked
    if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
        select_all.checked = true;
    }
});
 }
 </script>
</code>```

ContentLicense: CC BY-SA 2.5

Title: django checkbox select all by jquery

Body:
I want to select all checkbox when i click the top check,
below is my code:

run.html

Select All: <input type="checkbox" id="selectAll">

One: <input type="checkbox" class="xxx" />

Two: <input type="checkbox" class="xxx" />

Three: <input type="checkbox" class="xxx" />

but why it not work?

Body:
Here is a simple example for select all Checkbox.....

<ul>
<li><input type="checkbox" id="select_all"/> Selecct All</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 1</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 2</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 3</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 4</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 5</li>
<li><input class="checkbox" type="checkbox" name="check[]"> This is Item 6</li>

<script>
  var select_all = document.getElementById("select_all"); //select all checkbox
   var checkboxes = document.getElementsByClassName("checkbox");
   //checkbox items

  //select all checkboxes
  select_all.addEventListener("change", function(e){
  for (i = 0; i < checkboxes.length; i++) {
    checkboxes[i].checked = select_all.checked;
 }
});

for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('change', function(e){ //".checkbox" change
    //uncheck "select all", if one of the listed checkbox item is unchecked
    if(this.checked == false){
        select_all.checked = false;
    }
    //check "select all" if all checkbox items are checked
    if(document.querySelectorAll('.checkbox:checked').length == checkboxes.length){
        select_all.checked = true;
    }
});
 }
 </script>


问:
android -kotlin -java.lang.ClassCastException
RecyclerView Multi viewType Error

```<code>FATAL EXCEPTION: main
       Process: com.example.expertsaraqeb.myapplication, PID: 4329
       java.lang.ClassCastException: com.example.expertsaraqeb.myapplication.Madapter$MyHolder cannot be cast to com.example.expertsaraqeb.myapplication.MyViewH
06-05 07:00:35.897 4329-4329/com.example.expertsaraqeb.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.expertsaraqeb.myapplication, PID: 4329
   java.lang.ClassCastException: com.example.expertsaraqeb.myapplication.Madapter$MyHolder cannot be cast to com.example.expertsaraqeb.myapplication.MyViewH
       at com.example.expertsaraqeb.myapplication.Madapter.onBindViewHolder(Madapter.kt:27)
       at com.example.expertsaraqeb.myapplication.Madapter.onBindViewHolder(Madapter.kt:11)
       at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6356)
       at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6389)
       at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5335)
       at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5598)
       at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440)
       at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436)
       at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
       at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
       at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
       at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595)
       at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
       at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3025)
       at android.view.View.measure(View.java:16749)
       at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934)
       at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973)
       at android.view.View.measure(View.java:16749)
       at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
       at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
       at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1391)
       at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
       at android.view.View.measure(View.java:16749)
       at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1413)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:696)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:589)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1413)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:696)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:589)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2439)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2072)
    at android.
</code>```

Code:

```<code>package com.example.expertsaraqeb.myapplication

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class Madapter (val context: Context, val array:ArrayList<ModelItem>): RecyclerView.Adapter<Madapter.MyHolder>() {
    var TYPE1=15
    var TYPE2=28
    override fun getItemViewType(position: Int): Int {
        if (position==0){
            return TYPE1
        }else{
            return TYPE2
        }
    }
    override fun getItemCount(): Int {
       return array.size
    }

    override fun onBindViewHolder(p0: MyHolder?, p1: Int) {
        if (p0!!.itemViewType==TYPE1){
            val my= p0 as MyViewH //Error here

            Log.d("walidalhasn","p"+getItemViewType(p1))

        }else if (p0.itemViewType==TYPE1){
            Log.d("walidalhasn","j"+getItemViewType(p1))

        }
    }

    override fun onCreateViewHolder(p0: ViewGroup?, p1: Int): MyHolder {
        if (getItemViewType(p1)==TYPE1){
            val view= LayoutInflater.from(context).inflate(R.layout.row_no_color,p0,false)
            return MyViewH(view)
        }else {
            val view= LayoutInflater.from(context).inflate(R.layout.home_row,p0,false)
            return MyHolder(view)

        }

    }

    open class MyHolder (view: View):RecyclerView.ViewHolder(view)

}

class MyViewH(view: View?) : Madapter.MyHolder(view!!)
</code>```

答:
In onCreateViewHolder(p0: ViewGroup?, p1: Int), p1 represents viewType.

Should be

```<code>if (p1 == TYPE1) {
</code>```

instead of

```<code>if (getItemViewType(p1) == TYPE1) {
</code>```

Also, you may want to return array.size + 1 from getItemCount, because you've added header view.

Body:
RecyclerView Multi viewType Error

FATAL EXCEPTION: main
       Process: com.example.expertsaraqeb.myapplication, PID: 4329
       java.lang.ClassCastException: com.example.expertsaraqeb.myapplication.Madapter$MyHolder cannot be cast to com.example.expertsaraqeb.myapplication.MyViewH
06-05 07:00:35.897 4329-4329/com.example.expertsaraqeb.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.expertsaraqeb.myapplication, PID: 4329
   java.lang.ClassCastException: com.example.expertsaraqeb.myapplication.Madapter$MyHolder cannot be cast to com.example.expertsaraqeb.myapplication.MyViewH
       at com.example.expertsaraqeb.myapplication.Madapter.onBindViewHolder(Madapter.kt:27)
       at com.example.expertsaraqeb.myapplication.Madapter.onBindViewHolder(Madapter.kt:11)
       at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6356)
       at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6389)
       at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5335)
       at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5598)
       at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5440)
       at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5436)
       at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2224)
       at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1551)
       at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1511)
       at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:595)
       at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3583)
       at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3025)
       at android.view.View.measure(View.java:16749)
       at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:934)
       at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:973)
       at android.view.View.measure(View.java:16749)
       at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1658)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:714)
       at android.support.design.widget.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:90)
       at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1391)
       at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:784)
       at android.view.View.measure(View.java:16749)
       at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:1081)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1413)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:696)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:589)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1413)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:696)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:589)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5295)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
       at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2439)
       at android.view.View.measure(View.java:16749)
       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2072)
    at android.

Code:

package com.example.expertsaraqeb.myapplication

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class Madapter (val context: Context, val array:ArrayList<ModelItem>): RecyclerView.Adapter<Madapter.MyHolder>() {
    var TYPE1=15
    var TYPE2=28
    override fun getItemViewType(position: Int): Int {
        if (position==0){
            return TYPE1
        }else{
            return TYPE2
        }
    }
    override fun getItemCount(): Int {
       return array.size
    }

    override fun onBindViewHolder(p0: MyHolder?, p1: Int) {
        if (p0!!.itemViewType==TYPE1){
            val my= p0 as MyViewH //Error here

            Log.d("walidalhasn","p"+getItemViewType(p1))

        }else if (p0.itemViewType==TYPE1){
            Log.d("walidalhasn","j"+getItemViewType(p1))

        }
    }

    override fun onCreateViewHolder(p0: ViewGroup?, p1: Int): MyHolder {
        if (getItemViewType(p1)==TYPE1){
            val view= LayoutInflater.from(context).inflate(R.layout.row_no_color,p0,false)
            return MyViewH(view)
        }else {
            val view= LayoutInflater.from(context).inflate(R.layout.home_row,p0,false)
            return MyHolder(view)

        }

    }

    open class MyHolder (view: View):RecyclerView.ViewHolder(view)

}

class MyViewH(view: View?) : Madapter.MyHolder(view!!)

Body:
In onCreateViewHolder(p0: ViewGroup?, p1: Int), p1 represents viewType.

Should be

if (p1 == TYPE1) {

instead of

if (getItemViewType(p1) == TYPE1) {

Also, you may want to return array.size + 1 from getItemCount, because you've added header view.


问:
Transferring an SQL query from the workbench to a .java class
I'm trying to transfer an SQL query into java from my workbench.
I wrote this query in the mySQL workbench and it executed fine with the results I wanted.

SELECT committee_member.member_CAN#, member.first_name, member.last_name, committee_member.member_status, committee_member.start_year, committee_member.end_year, committee_member.added_notes
FROM committee_member LEFT JOIN member
ON committee_member.member_CAN# = CAN#

Here is my .java class code.  I am trying to print a table that displays this information.
I keep getting an error that reads "Unknown table 'committee_member' in field list" in eclipse, so i'm guessing that my query syntax is wrong.

```<code>package model;

import java.sql.*;
import java.util.ArrayList;

public class ViewCommitteeMember {

private Connection connection;
private ArrayList<CommitteeMember> members;

public ViewCommitteeMember(){
members = new ArrayList<CommitteeMember>();
makeConnection();
}

public void viewMembers(){
String query =  "SELECT `committee_member`.`member_CAN#`, `member`.`first_name`,           `member`.`last_name`, `committee_member`.`member_status`, `committee_member`.`start_year`, `committee_member`.`end_year`, `committee_member`.`added_notes` FROM committee_member LEFT JOIN member ON `committee_member`.`member_CAN#` = `CAN#`";

PreparedStatement ps;
try {
 ps = connection.prepareStatement(query);

  ResultSet rs = ps.executeQuery();

  while (rs.next()){ //while the query is running, loop through all of the members
    CommitteeMember member = new CommitteeMember(); //create a new member for each entry so info may be displayed
    member.setID(rs.getInt(1)); //pulls the ID
    member.setFirstname(rs.getString(2));
    member.setLastname(rs.getString(3));
    member.setMemStat(rs.getString(4)); //pulls the status
    member.setStartYear(rs.getInt(5)); //pulls the start year
    member.setEndYear(rs.getInt(6)); //pulls the end year
    member.setNotes(rs.getString(7)); //pulls the additional notes

    members.add(member); //add the member to the array list "members"
  }

  } catch (SQLException e) {
 // TODO Auto-generated catch block
  e.printStackTrace();

 } finally {
   this.closeConnection();
 }
 }

  private void makeConnection(){
  // get connection
  String url = "jdbc:mysql://localhost:3306/committee_database";
  String user = "root";
  String pwd = "coolman";
  try {
  connection = DriverManager.getConnection(url, user, pwd);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }

  private void closeConnection(){
 try {
  connection.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }

  /**
  * @return the agents
  */
  public ArrayList<CommitteeMember> getMembers() {  //list of all the members
  return members;
  }

  }
</code>```

答:
Connection conn = null;

```<code>Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcURL="jdbc:mysql://localhost:3306/jsp";
conn = DriverManager.getConnection(jdbcURL,"root", "");

PreparedStatement psSelectRecord=null;
ResultSet rsSelectRecord=null;
String sqlSelectRecord=null;

sqlSelectRecord="SELECT s.iEmpID, s.sStaffName, s.sStaffDept, s.iStaffPhone,"+
                    "d.sAddress FROM staff_register s " +
                        "left join staff_details d on d.iEmpID=s.iEmpID";

psSelectRecord=conn.prepareStatement(sqlSelectRecord);
rsSelectRecord=psSelectRecord.executeQuery();
</code>```

this is the sample of left join try it..

Body:
I'm trying to transfer an SQL query into java from my workbench.
I wrote this query in the mySQL workbench and it executed fine with the results I wanted.

SELECT committee_member.member_CAN#, member.first_name, member.last_name, committee_member.member_status, committee_member.start_year, committee_member.end_year, committee_member.added_notes
FROM committee_member LEFT JOIN member
ON committee_member.member_CAN# = CAN#

Here is my .java class code.  I am trying to print a table that displays this information.
I keep getting an error that reads "Unknown table 'committee_member' in field list" in eclipse, so i'm guessing that my query syntax is wrong.

package model;

import java.sql.*;
import java.util.ArrayList;

public class ViewCommitteeMember {

private Connection connection;
private ArrayList<CommitteeMember> members;

public ViewCommitteeMember(){
members = new ArrayList<CommitteeMember>();
makeConnection();
}

public void viewMembers(){
String query =  "SELECT `committee_member`.`member_CAN#`, `member`.`first_name`,           `member`.`last_name`, `committee_member`.`member_status`, `committee_member`.`start_year`, `committee_member`.`end_year`, `committee_member`.`added_notes` FROM committee_member LEFT JOIN member ON `committee_member`.`member_CAN#` = `CAN#`";

PreparedStatement ps;
try {
 ps = connection.prepareStatement(query);

  ResultSet rs = ps.executeQuery();

  while (rs.next()){ //while the query is running, loop through all of the members
    CommitteeMember member = new CommitteeMember(); //create a new member for each entry so info may be displayed
    member.setID(rs.getInt(1)); //pulls the ID
    member.setFirstname(rs.getString(2));
    member.setLastname(rs.getString(3));
    member.setMemStat(rs.getString(4)); //pulls the status
    member.setStartYear(rs.getInt(5)); //pulls the start year
    member.setEndYear(rs.getInt(6)); //pulls the end year
    member.setNotes(rs.getString(7)); //pulls the additional notes

    members.add(member); //add the member to the array list "members"
  }

  } catch (SQLException e) {
 // TODO Auto-generated catch block
  e.printStackTrace();

 } finally {
   this.closeConnection();
 }
 }

  private void makeConnection(){
  // get connection
  String url = "jdbc:mysql://localhost:3306/committee_database";
  String user = "root";
  String pwd = "coolman";
  try {
  connection = DriverManager.getConnection(url, user, pwd);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
   e.printStackTrace();
  }
  }

  private void closeConnection(){
 try {
  connection.close();
  } catch (SQLException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  }
  }

  /**
  * @return the agents
  */
  public ArrayList<CommitteeMember> getMembers() {  //list of all the members
  return members;
  }

  }

Body:
Connection conn = null;

Class.forName("com.mysql.jdbc.Driver").newInstance();
String jdbcURL="jdbc:mysql://localhost:3306/jsp";
conn = DriverManager.getConnection(jdbcURL,"root", "");

PreparedStatement psSelectRecord=null;
ResultSet rsSelectRecord=null;
String sqlSelectRecord=null;

sqlSelectRecord="SELECT s.iEmpID, s.sStaffName, s.sStaffDept, s.iStaffPhone,"+
                    "d.sAddress FROM staff_register s " +
                        "left join staff_details d on d.iEmpID=s.iEmpID";

psSelectRecord=conn.prepareStatement(sqlSelectRecord);
rsSelectRecord=psSelectRecord.executeQuery();

this is the sample of left join try it..


问:
Display the selected category when selecting from a drop down
I want to show the name of the category selected from a drop-down when someone searches in the category.

The page should show search results for "category name here."

I tried using get_search_query(); but it shows only the results from the search form, doesn't work on drop-downs.

答:
You will get all queried object with this function:

```<code> <?php
 $queried_object = get_queried_object();
 var_dump( $queried_object );
 ?>
</code>```

Thanks

Body:
You will get all queried object with this function:

 <?php
 $queried_object = get_queried_object();
 var_dump( $queried_object );
 ?>

Thanks


问:
how to apply active class using ng-class for list elements(mutli-select)?
I have a scenario,that I have static list elements,where I need to add active class using ng-class,when I click on list element,the active class would be added.

Here is my code:

```<code>vm.idArry = [];
vm.selectedFunc = function (item) {
    item.selected = !item.selected;
    if(vm.idArry.indexOf(item) == -1){
        vm.idArry.push(item);

    }
    else {
        var index =  vm.idArry.indexOf(item);
         vm.idArry.splice(index, 1);
    }
  }
</code>```

Html:

```<code><ul>
            <li id="one"><a ng-class="{'active':item.selected}" ng-click="selectedrFunc(1)" ></a></li>
            <li id="two"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(2)" ></a></li>
            <li id="three"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(3)"></a></li>
            <li id="four"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(4)" ></a></li>
            <li id="five"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(5)"></a></li>
            <li id="six"><a ng-class="{'active':item.selected}" ng-click="selectedFunc(6)" ></a></li>
</code>```

for the above code,I have to get append active class when I click on list elements(i.e; multiple list must be added active class when I clicked on multiple list elements).

Thanks in advance.
Any help would be appreciated.

答:
Remove usage of item.selected and use following code:

```<code><li id="one"><a ng-class="{'active': vm.idArry.indexOf(1) != -1}" ng-click="selectedFunc(1)" >A</a></li>
</code>```

This checks for item existence in vm.idArray; Also remove item.selected on vm.selectedFunc

So your vm.selectedFunc should look like this:

```<code>vm.selectedFunc = function (item) {
    if(vm.idArry.indexOf(item) == -1){
        vm.idArry.push(item);

    }
    else {
        var index =  vm.idArry.indexOf(item);
         vm.idArry.splice(index, 1);
    }
  }
</code>```

Body:
I have a scenario,that I have static list elements,where I need to add active class using ng-class,when I click on list element,the active class would be added.

Here is my code:

vm.idArry = [];
vm.selectedFunc = function (item) {
    item.selected = !item.selected;
    if(vm.idArry.indexOf(item) == -1){
        vm.idArry.push(item);

    }
    else {
        var index =  vm.idArry.indexOf(item);
         vm.idArry.splice(index, 1);
    }
  }

Html:

for the above code,I have to get append active class when I click on list elements(i.e; multiple list must be added active class when I clicked on multiple list elements).

Thanks in advance.
Any help would be appreciated.

Body:
Remove usage of item.selected and use following code:

<li id="one"><a ng-class="{'active': vm.idArry.indexOf(1) != -1}" ng-click="selectedFunc(1)" >A</a></li>

This checks for item existence in vm.idArray; Also remove item.selected on vm.selectedFunc

So your vm.selectedFunc should look like this:

vm.selectedFunc = function (item) {
    if(vm.idArry.indexOf(item) == -1){
        vm.idArry.push(item);

    }
    else {
        var index =  vm.idArry.indexOf(item);
         vm.idArry.splice(index, 1);
    }
  }


问:
How to make the title of the text shift away from the mouse
How to make the title of the text shift away from the mouse, when the mouse is directed to the title of the text in java.</p>

答:
You need to use mouseExit and mouseEntered actionListener's to do this:

Simple Example:

```<code>import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Shift {
    JFrame frame;
    JLabel label;
    Shift(){
        initComp();
    }

    public void initComp(){
        frame = new JFrame("Example");
        frame.setSize(300,200);

        label = new JLabel("Hello");
        label.setSize(10, 10);
        label.setBackground(Color.RED);

        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent evt) {
                labelToMiddle(evt);
            }

            @Override
            public void mouseExited(MouseEvent evt) {
                labelToEdge(evt);
            }
        });

        frame.add(label);
        frame.setVisible(true);
    }

    private void labelToEdge(MouseEvent evt) {
        label.setForeground(Color.RED);
        label.setLocation(0,0);
        label.repaint();
    }

    private void labelToMiddle(MouseEvent evt) {
        label.setForeground(Color.GREEN);
        label.setLocation(100,0);
        label.repaint();
    }

    public static void main(String[] args) {
        Shift s = new Shift();
    }
}
</code>```

Body:
You need to use mouseExit and mouseEntered actionListener's to do this:

Simple Example:

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Shift {
    JFrame frame;
    JLabel label;
    Shift(){
        initComp();
    }

    public void initComp(){
        frame = new JFrame("Example");
        frame.setSize(300,200);

        label = new JLabel("Hello");
        label.setSize(10, 10);
        label.setBackground(Color.RED);

        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent evt) {
                labelToMiddle(evt);
            }

            @Override
            public void mouseExited(MouseEvent evt) {
                labelToEdge(evt);
            }
        });

        frame.add(label);
        frame.setVisible(true);
    }

    private void labelToEdge(MouseEvent evt) {
        label.setForeground(Color.RED);
        label.setLocation(0,0);
        label.repaint();
    }

    private void labelToMiddle(MouseEvent evt) {
        label.setForeground(Color.GREEN);
        label.setLocation(100,0);
        label.repaint();
    }

    public static void main(String[] args) {
        Shift s = new Shift();
    }
}


Title: IF function and nested function

Body:
Please help with this formula

=if(C27>=16000,16M,if(C27,=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

Body:
=if(C27>=16000,16M,if(C27 ,= 16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

the character before 16999 shows the wrong syntax, perhaps it's like this

=if(C27>=16000,16M,if(C27<=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))


问:
Django: My Register_Lost page not showing up
Still newbie in django, please help me

Urls.py :

```<code>from django.conf.urls import url

from . import views

app_name = 'lostfound'

urlpatterns = [

# /lostfound/
url(r'^$', views.IndexView.as_view(), name='index'),

# /lostfound/lostitems
url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),
</code>```

this is the main problem of my url, i can't display my register_lost.html

```<code># /lostfound/lostitems/addlostitems
url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),`
</code>```

Views.py :

```<code>from django.views import generic
from .models import Wallet

class IndexView(generic.ListView):
model = Wallet
template_name = 'lostfound/index.html'

class LostItemsView(generic.ListView):
model = Wallet
template_name = 'lostfound/lost_items.html'

class RegisterLostView(generic.ListView):
model = Wallet
template_name = 'lostfound/register_lost.html'
</code>```

lost_items.html :

```<code> <div class="menu-button z-depth-3 right">
                                        <a class="waves-effect waves-light btn" href="{% url 'lostfound:register_lost' %}">
                                            <i class="medium material-icons right">playlist_add</i>Tambah Data
                                        </a>
                                    </div>
</code>```

this is my register_lost.html that i want process

register_lost.html :

```<code>{% extends 'lostfound/base.html' %}
{% extends 'lostfound/lost_items.html' %}
{% block title %}Register Lost Items{% endblock %}

{% block content %}
    {% load staticfiles %}
    {% block sign_in %}
    {% endblock %}
     <h1>Hello</h1>

{% endblock %}
</code>```

答:
Try to switch lines in the urlpatterns list

this:

```<code>url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
</code>```

before this:

```<code>url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),
</code>```

Body:
Still newbie in django, please help me

Urls.py :

from django.conf.urls import url

from . import views

app_name = 'lostfound'

urlpatterns = [

# /lostfound/
url(r'^$', views.IndexView.as_view(), name='index'),

# /lostfound/lostitems
url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),

this is the main problem of my url, i can't display my register_lost.html

# /lostfound/lostitems/addlostitems
url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),`

Views.py :

from django.views import generic
from .models import Wallet

class IndexView(generic.ListView):
model = Wallet
template_name = 'lostfound/index.html'

class LostItemsView(generic.ListView):
model = Wallet
template_name = 'lostfound/lost_items.html'

class RegisterLostView(generic.ListView):
model = Wallet
template_name = 'lostfound/register_lost.html'

lost_items.html :

                                            playlist_addTambah Data

this is my register_lost.html that i want process

register_lost.html :

{% extends 'lostfound/base.html' %}
{% extends 'lostfound/lost_items.html' %}
{% block title %}Register Lost Items{% endblock %}

{% block content %}
    {% load staticfiles %}
    {% block sign_in %}
    {% endblock %}

Hello

{% endblock %}

Body:
Try to switch lines in the urlpatterns list

this:

url(r'/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),

before this:

url(r'lostitems/', views.LostItemsView.as_view(), name='lost_items'),


问:
Confirm User to Change Route without saving details while editing Angular 2
If the user is editing something and try to change the route without saving details.

in this condition I want to alter the user that 'your changes are not saved do you want to go away'. according to the user can we prevent component to destroy the component.

I try a guard but guard run before ngOnDestroy method run.
So what should I do?

答: i have Used CanDeactivate for the same functionality and it is working great. </p>


问:
n*n (not nested) for loop complexity
I know that the pattern for algorithm complexity when looking at nested loops is generally n^(m+1), where m is the loop nesting factor (loop within a loop).

But what about this simple case, where

```<code>for (i=0; i<n*n; i++) {
    ...
}
</code>```

is the complexity O(n^2)?

Because the amount of executions is the same as it would be for a normal nested for loop.

答:
Assuming the work done in each iteration of the for loop is O(1) then the complexity of the for loop is indeed O(n^2) since you iterate n^2 times. And yes, you assume correctly it would be of the same complexity as:</p>

```<code>for(i=0;i<n;i++) {
    for(j=0;j<n;j++) {
        ...
    }
}
</code>```

Title: n*n (not nested) for loop complexity

Body:
I know that the pattern for algorithm complexity when looking at nested loops is generally n^(m+1), where m is the loop nesting factor (loop within a loop).

But what about this simple case, where

for (i=0; i<n*n; i++) {
    ...
}

is the complexity O(n^2)?

Because the amount of executions is the same as it would be for a normal nested for loop.

Body:
Assuming the work done in each iteration of the for loop is O(1) then the complexity of the for loop is indeed O(n^2) since you iterate n^2 times. And yes, you assume correctly it would be of the same complexity as:

for(i=0;i<n;i++) {
    for(j=0;j<n;j++) {
        ...
    }
}


答:
Just add this in your CSS and you are done. :)

```<code>.inner-container {
     text-align: center;
}
</code>```

You can refer to my link as well if you need.

https://jsfiddle.net/Dhruvil21_04/hadu5my3/

Title: Html/Css dynamic centering

Body:
what I want to achieve is the following,
I have 6 divs in the bottom which are aligned horizontal and have the rest of the screen size as equal margin left and right.

Now when the screen's width is to small to display them in one row, I want to display them in two rows (with 3 divs each). All of this is working right now, but when it becomes a two row layout the equal margin left and right is gone and they clip at the left of the screen.

Am I missing something ?

.container{
  z-index: 3;
  bottom: 20px;
  width: 100%;
  position: absolute;
}

.center-container{
  display: table;
  margin-right: auto;
  margin-left: auto;
}

.inner-container{
  display: inline-block;
}

.group-container{
  display: inline-block;
  margin-right: auto;
  margin-left: auto;
}

.element{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: #000000
}

JsFiddle example of working one row layout: https://jsfiddle.net/7ef7xLhu/

JsFiddle example of non working two row layout: https://jsfiddle.net/9oc19oky/

Thank you in advance :)

Body:
Just add this in your CSS and you are done. :)

.inner-container {
     text-align: center;
}

You can refer to my link as well if you need.

https://jsfiddle.net/Dhruvil21_04/hadu5my3/


问:
Does anyone know how succesfully use preprocessing on J2ME?
I'll try to better explain my problem.
Using Eclipse and MTJ (Mobile Tools for Java) plugin you can set some directives for the preprocessor in order to create different builds of your code, like in C/C++.
My problem is that i'm unable to use this feature. I mean, when i build my sources, the resulting output contains every line of code, even ones contained within

```<code>//#mdebug info
...
//#enddebug
</code>```

directive. I have "Enable preprocessing" option checked and i've changed the debug level to every possible setup (lower, equals and higher than "info") and the result is always the same: the directives are simply ignored.

答:
Are you using v0.9.1 (or an even more recent version) of MTJ?  This wiki shows their planning for MTJ and mdebug and debug were not supported until 0.9.1.

For anyone that might come across this, here is the setup instruction page for preprocessing.

Body:
I'll try to better explain my problem.
Using Eclipse and MTJ (Mobile Tools for Java) plugin you can set some directives for the preprocessor in order to create different builds of your code, like in C/C++.
My problem is that i'm unable to use this feature. I mean, when i build my sources, the resulting output contains every line of code, even ones contained within

//#mdebug info
...
//#enddebug

directive. I have "Enable preprocessing" option checked and i've changed the debug level to every possible setup (lower, equals and higher than "info") and the result is always the same: the directives are simply ignored.

OwnerDisplayName: Fostah

LastEditorDisplayName: Fostah


问:
Construct dynamic-sized array in R
I was wondering about what are the ways to construct dynamic-size array in R.

For one example, I want to construct a n-vector but its dimension n is dynamically determined. The following code will work:

```<code>> x=NULL
> n=2;
> for (i in 1:n) x[i]=i;
> x
[1] 1 2
</code>```

For another example, I want to construct a n by 2 matrix where the number of rows n is dynamically determined. But I fail even at assigning the first row:

```<code>> tmp=c(1,2)
> x=NULL
> x[1,]=tmp
Error in x[1, ] = tmp : incorrect number of subscripts on matrix
> x[1,:]=tmp
Error: unexpected ':' in "x[1,:"
</code>```

Thanks and regards!

Title: Construct dynamic-sized array in R

Body:
I was wondering about what are the ways to construct dynamic-size array in R.

For one example, I want to construct a n-vector but its dimension n is dynamically determined. The following code will work:

> x=NULL
> n=2;
> for (i in 1:n) x[i]=i;
> x
[1] 1 2

For another example, I want to construct a n by 2 matrix where the number of rows n is dynamically determined. But I fail even at assigning the first row:

> tmp=c(1,2)
> x=NULL
> x[1,]=tmp
Error in x[1, ] = tmp : incorrect number of subscripts on matrix
> x[1,:]=tmp
Error: unexpected ':' in "x[1,:"

Thanks and regards!

Body:
n = 5
x = c(1,2) %o% rep(1,n)
x
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    1    1    1    1
# [2,]    2    2    2    2    2

x = rep(1,n) %o% c(1,2)
x
#      [,1] [,2]
# [1,]    1    2
# [2,]    1    2
# [3,]    1    2
# [4,]    1    2
# [5,]    1    2


问:
How can i change div contenteditable = "false" to "true"?
I am playing around with angular2. I want to change the value of a div-
Need to change all contenteditable="false" to contenteditable="true" which are there on my HTML page.

Please note sometimes the contenteditable="false" will be added to a DIV tag and sometimes to P, h1 tag or some other.

The html looks as following:

```<code><button (click)="selectDiv()">select div</button>
<section>
      <div class="content">
        <h1 contenteditable="false" >Resize your browser and see how they adapt.</h1>
        <h1 contenteditable="false" >text2.</h1>
      </div>
      <div class="content" contenteditable="false">
        <p>Content 2.</p>
        <h1>text2.</h1>
      </div>
</section>
</code>```

Please guide me what should i write in explore.ts so that when i click the button, selectDiv() is called and the function is executed and all the contenteditable="false" becomes "true"

Please note there can be any number of contenteditable="false" in my code.

```<code>selectDiv(){
//what should i write here
}
</code>```

答:
You can query for the attribute and use attr property to update it's value.

Here all h1 will be selected which have the contenteditable attribute

function selectDiv() {
  $("h1[contenteditable='false']").attr('contenteditable', true)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="selectDiv()">
  select div</button>
<section>

  <div class="content">
    <h1 contenteditable="false">Resize your browser and see how they adapt.</h1>
    <h1 contenteditable="false">text2.</h1>
  </div>

  <div class="content" contenteditable="false">
    <p>Content 2.</p>
    <h1>text2.</h1>
  </div>

</section></code>```

Body:
I am playing around with angular2. I want to change the value of a div-
Need to change all contenteditable="false" to contenteditable="true" which are there on my HTML page.

Please note sometimes the contenteditable="false" will be added to a DIV tag and sometimes to P, h1 tag or some other.

The html looks as following:

<button (click)="selectDiv()">select div</button>

Resize your browser and see how they adapt.

text2.

Content 2.

text2.

Please guide me what should i write in explore.ts so that when i click the button, selectDiv() is called and the function is executed and all the contenteditable="false" becomes "true"

Please note there can be any number of contenteditable="false" in my code.

selectDiv(){
//what should i write here
}

Body:
You can query for the attribute and use attr property to update it's value.

Here all h1 will be selected which have the contenteditable attribute

function selectDiv() {
  $("h1[contenteditable='false']").attr('contenteditable', true)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="selectDiv()">
  select div</button>
<section>

  <div class="content">
    <h1 contenteditable="false">Resize your browser and see how they adapt.</h1>
    <h1 contenteditable="false">text2.</h1>
  </div>

  <div class="content" contenteditable="false">
    <p>Content 2.</p>
    <h1>text2.</h1>
  </div>

</section>


问:
How to enabling Google Play App Signing without keystore password
This question is not duplicate because, this question is regarding Google Play App Signing, answers mentioned in the other question doesn't solve this question.

I have an active app on playstore with 500,000+ downloads, I have backed up my keystore file but unfortunately I forgot my keystore password, is there any way I can Enable Google Play App Signing, upload my new apk & release new version.

I tried all ways to find the keystore password but no luck.

答:
unfortunately I forgot my keystore password

This is a problem that has come up many times. If you have lost the password, you cannot use the keystore. You can, however, use brute force apps on the password to crack it. But that may take a while. IF oyu have a "standard" password you used/use a lot, try using this/these passwords and see if that is the right one.

So, without the password you cannot do anything - not enable google play app signing, and you cannot sign it yourself.

And a tip for the future: Write down the password, or use one you know you will remember. The password doesn't have to be very complex, personally I don't even understand why there is a password. But when you have lost the password you have two options (after trying different possibilities): Brute force it or create a new keystore and upload your app as a new one.

Without the keystore password, you cannot use Google Play App signing or sign it yourself. SO you need to get a hold of that password

Or you can see if it is in a temporary gradle file at this location:

```<code>..Project\.gradle\2.4\taskArtifacts\taskArtifacts.bin
</code>```

One brute force option

SO question on the topic

one SO question on losing the keystore password

another SO question on losing the keystore password

Body:
unfortunately I forgot my keystore password

This is a problem that has come up many times. If you have lost the password, you cannot use the keystore. You can, however, use brute force apps on the password to crack it. But that may take a while. IF oyu have a "standard" password you used/use a lot, try using this/these passwords and see if that is the right one.

So, without the password you cannot do anything - not enable google play app signing, and you cannot sign it yourself.

And a tip for the future: Write down the password, or use one you know you will remember. The password doesn't have to be very complex, personally I don't even understand why there is a password. But when you have lost the password you have two options (after trying different possibilities): Brute force it or create a new keystore and upload your app as a new one.

Without the keystore password, you cannot use Google Play App signing or sign it yourself. SO you need to get a hold of that password

Or you can see if it is in a temporary gradle file at this location:

..Project\.gradle\2.4\taskArtifacts\taskArtifacts.bin

One brute force option

SO question on the topic

one SO question on losing the keystore password

another SO question on losing the keystore password


问:
cakephp 2.9.7 data validation is not working
The problem is very simple but why it is complicating for me.I have written data validation also.But for empty fields also it is accepting the input.please check whether any error in my action.php.

Model/action.php

```<code><?php
App::uses('AppModel', 'Model');

class Actions extends AppModel {
  public $validate = array(
        'value_to_plot' => array(
          'required'=>true,
            'message' => 'atleast select one measure'
        ),
        'column_name' => array(
          'required'=>true,
            'rule'=>array('notBlank'),
            'message' => 'atleast select one table'
          )

      );
}

?>
</code>```

View/Actions/index.ctp

```<code><div align="center">
<fieldset>
  <?php  echo $this->Form->create('valueToSend',array('type' => 'get'));?>
    <?php if(isset($_GET['table_name'])){ ?>
      <table class="table table-bordered table-hover table-striped">
        <?php echo $this->Form->hidden('table_name', array('hiddenField' => true, 'value'=> $_GET['table_name'],'id'=>'table_name'));
       echo $this->Form->hidden('chart', array('hiddenField' => true, 'value'=> "column3d",'id'=>"chart"));
        ?>
          <tr>
            <th>MEASURES</th>
            <td>
              <?php  echo $this->Form->select('value_to_plot',$measures1,array('class'=>'form-control','id'=>'measures','required'=>true),['empty' => 'choose one']);?>
            </td>

          </tr>
          <tr>
            <th>DIMENSIONS</th>
            <td>
              <?php echo  $this->Form->select('column_name[]',$measures2,array('multiple'=>'true','class'=>'form-control','id'=>'dimensions','required'=>true),['empty' =>'choose one']);?>
            </td>

          </tr>
        </table>
      <div style="text-align:center">
        <?php  echo $this->Form->end('submit'); ?>
      </div>
    <?php } ?>
</fieldset>
</div>
</code>```

Controller/ActionsController.php

```<code><?php
App::uses('AppController', 'Controller');

class ActionsController extends AppController {

  public function beforeFilter() {
    if(!isset($_SESSION['Auth']) && empty($_SESSION['Auth'])) {
    $userId = $_SESSION['Auth[User[id]]'];
    return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
  }
}

  public Function index(){
    App::import('Model', 'ConnectionManager');
    $con = new ConnectionManager;
    $cn = $con->getDataSource('default');

    $tablequery="SELECT TABLE_NAME as table_name
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='phygital_visualize' AND TABLE_NAME != 'report'";
    $rows = $cn->query($tablequery);
    //$rows = $result->fetchAll('assoc');
    $dataToTable = [];
     foreach ($rows as $row) {
         $dataToTable[$row['TABLES']['table_name']] = $row['TABLES']['table_name'];
     }
   $this->set('table',$dataToTable);

   if(isset($_GET['table_name'])){
     $table_name = $_GET['table_name'];
     $column = "select column_name as name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='$table_name' ";
     $result = $cn->query($column) ;
     foreach ($result as $key => $value) {
       foreach($value as $key => $value) {
        foreach($value as $key =>$value){
         $column_counts[$value] = $value;
         }
       }
    }

    $column_counts = array_unique($column_counts);
    //print_r($column_counts);
     $measures1=array();
     $measures2=array();
     $diff=array();
       foreach($column_counts as $key => $value){

         $sql="select * from $table_name where concat('',$value * 1 ) = $value limit 1";
        $resultset = $cn->query($sql) ;
        if(!empty($resultset)){

                if(!in_array($value, $measures1)){
                  $measures1[$value]= $value;
                }
        }

   }

   $measures2 = array_diff($column_counts,$measures1);
   $this->set('measures1',$measures1);
    $this->set('measures2',$measures2);
   }

   }
}

?>
</code>```

答:
This will validate and save your data</p>

```<code>if ($this->request->is('post')) {
     $this->Actions->set($this->request->data);
     if ($this->Actions->save($this->request->data)) {
            // Set a session flash message and redirect.
     }
}
</code>```

Body:
The problem is very simple but why it is complicating for me.I have written data validation also.But for empty fields also it is accepting the input.please check whether any error in my action.php.

Model/action.php

<?php
App::uses('AppModel', 'Model');

class Actions extends AppModel {
  public $validate = array(
        'value_to_plot' => array(
          'required'=>true,
            'message' => 'atleast select one measure'
        ),
        'column_name' => array(
          'required'=>true,
            'rule'=>array('notBlank'),
            'message' => 'atleast select one table'
          )

      );
}

?>

View/Actions/index.ctp

<fieldset>
  <?php  echo $this->Form->create('valueToSend',array('type' => 'get'));?>
    <?php if(isset($_GET['table_name'])){ ?>

        <?php echo $this->Form->hidden('table_name', array('hiddenField' => true, 'value'=> $_GET['table_name'],'id'=>'table_name'));
       echo $this->Form->hidden('chart', array('hiddenField' => true, 'value'=> "column3d",'id'=>"chart"));
        ?>

            MEASURES

              <?php  echo $this->Form->select('value_to_plot',$measures1,array('class'=>'form-control','id'=>'measures','required'=>true),['empty' => 'choose one']);?>

            DIMENSIONS

              <?php echo  $this->Form->select('column_name[]',$measures2,array('multiple'=>'true','class'=>'form-control','id'=>'dimensions','required'=>true),['empty' =>'choose one']);?>

        <?php  echo $this->Form->end('submit'); ?>

    <?php } ?>
</fieldset>

Controller/ActionsController.php

<?php
App::uses('AppController', 'Controller');

class ActionsController extends AppController {

  public function beforeFilter() {
    if(!isset($_SESSION['Auth']) && empty($_SESSION['Auth'])) {
    $userId = $_SESSION['Auth[User[id]]'];
    return $this->redirect(array('controller' => 'Users', 'action' => 'login'));
  }
}

  public Function index(){
    App::import('Model', 'ConnectionManager');
    $con = new ConnectionManager;
    $cn = $con->getDataSource('default');

    $tablequery="SELECT TABLE_NAME as table_name
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_SCHEMA='phygital_visualize' AND TABLE_NAME != 'report'";
    $rows = $cn->query($tablequery);
    //$rows = $result->fetchAll('assoc');
    $dataToTable = [];
     foreach ($rows as $row) {
         $dataToTable[$row['TABLES']['table_name']] = $row['TABLES']['table_name'];
     }
   $this->set('table',$dataToTable);

   if(isset($_GET['table_name'])){
     $table_name = $_GET['table_name'];
     $column = "select column_name as name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='$table_name' ";
     $result = $cn->query($column) ;
     foreach ($result as $key => $value) {
       foreach($value as $key => $value) {
        foreach($value as $key =>$value){
         $column_counts[$value] = $value;
         }
       }
    }

    $column_counts = array_unique($column_counts);
    //print_r($column_counts);
     $measures1=array();
     $measures2=array();
     $diff=array();
       foreach($column_counts as $key => $value){

         $sql="select * from $table_name where concat('',$value * 1 ) = $value limit 1";
        $resultset = $cn->query($sql) ;
        if(!empty($resultset)){

                if(!in_array($value, $measures1)){
                  $measures1[$value]= $value;
                }
        }

   }

   $measures2 = array_diff($column_counts,$measures1);
   $this->set('measures1',$measures1);
    $this->set('measures2',$measures2);
   }

   }
}

?>

Body:
This will validate and save your data

if ($this->request->is('post')) {
     $this->Actions->set($this->request->data);
     if ($this->Actions->save($this->request->data)) {
            // Set a session flash message and redirect.
     }
}


Title: Inserting elements into a list of elements element

Body:
How can I insert the values of the collisions into the results table?
This is what Ive tried doing:

for elements in collisions:
    for i in results:
        for j in i:
            results[i][j] = elements

collisions = [26, 12, 16, 17, 12, 16, 14, 8, 4, 2, 8, 5, 3, 4, 5, 3, 2, 3, 2, 6, 2, 2, 2, 3, 0, 0, 0, 0]

result = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

Want:

[[26, 12, 4, 3, 2, 2, 0], [12, 16, 2, 4, 3, 2, 0], [16, 14, 8, 5, 2, 2, 0], [17, 8, 5, 3, 6, 3, 0]]

Thanks in advance

Body:
Here is a simple method breaking the list into sub-lists.

x=0
result = []
collisions = [26, 12, 16, 17, 12, 16, 14, 8, 4, 2, 8, 5, 3, 4, 5, 3, 2, 3, 2, 6, 2, 2, 2, 3, 0, 0, 0, 0]
while x < len(collisions)/7:
    sub_list = []
    for i in range(x,len(collisions),4):
        sub_list.append(collisions[i])
    result.append(sub_list)
    x += 1
print collisions
print result
[26, 12, 16, 17, 12, 16, 14, 8, 4, 2, 8, 5, 3, 4, 5, 3, 2, 3, 2, 6, 2, 2, 2, 3, 0, 0, 0, 0]
[[26, 12, 4, 3, 2, 2, 0], [12, 16, 2, 4, 3, 2, 0], [16, 14, 8, 5, 2, 2, 0], [17, 8, 5, 3, 6, 3, 0]]

Note: no error checking


问:
How to refer to a cell outside of cellForRowAtIndexPath
I am trying to update a label in a cell outside of

```<code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
</code>```

by using

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell
</code>```

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell
</code>```

that does not return an error, but the label cell.time.text is not updated.

答:
Step1:

update the data of the model

Step2:

reload indexPath

```<code> let indexPathToRefresh = IndexPath(row: 0, section: 0)
 tableView.reloadRows(at: [indexPathToRefresh], with: .none)
</code>```

Body:
I am trying to update a label in a cell outside of

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

by using

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell

that does not return an error, but the label cell.time.text is not updated.

Body:
Step1:

update the data of the model

Step2:

reload indexPath

 let indexPathToRefresh = IndexPath(row: 0, section: 0)
 tableView.reloadRows(at: [indexPathToRefresh], with: .none)