问:
I can't see analysis results of SonarQube
I am using sonarqube with jenkins. The execution is successful but I don´t see any report or result. Everything is 0.

I think the problem is here, but I am not sure.

```<code>16:01:05 16:01:05.380 WARN: This may lead to missing/broken features in SonarQube
16:01:05 16:01:05.380 INFO: Sensor SCM Sensor (wrapped) (done) | time=625ms
16:01:05 16:01:05.380 INFO: Sensor C# (wrapped)
16:01:05 16:01:05.396 INFO: Importing analysis results from C:\Jenkins\jobs\firecom_backend\workspace\null\output-cs
16:01:05 16:01:05.411 WARN: Protobuf file not found: null\output-cs\encoding.pb
16:01:05 16:01:05.427 WARN: Protobuf file not found: null\output-cs\metrics.pb
16:01:05 16:01:05.427 WARN: Protobuf file not found: null\output-cs\issues.pb
16:01:05 16:01:05.427 WARN: Protobuf file not found: null\output-cs\token-type.pb
16:01:05 16:01:05.442 WARN: Protobuf file not found: null\output-cs\symrefs.pb
16:01:05 16:01:05.442 WARN: Protobuf file not found: null\output-cs\token-cpd.pb
16:01:05 16:01:05.442 INFO: Sensor C# (wrapped) (done) | time=62ms
16:01:05 16:01:05.442 INFO: Sensor C# Unit Tests Coverage Report Import (wrapped)
16:01:05 16:01:05.442 DEBUG: No coverage property. Skip Sensor
16:01:05 16:01:05.442 INFO: Sensor C# Unit Tests Coverage Report Import (wrapped) (done) | time=0ms
16:01:05 16:01:05.442 INFO: Sensor C# Integration Tests Coverage Report Import (wrapped)
16:01:05 16:01:05.442 DEBUG: No coverage property. Skip Sensor
16:01:05 16:01:05.442 INFO: Sensor C# Integration Tests Coverage Report Import (wrapped) (done) | time=0ms
16:01:05 16:01:05.442 INFO: Sensor C# Unit Test Results Import (wrapped)
16:01:05 16:01:05.442 DEBUG: No unit test results property. Skip Sensor
16:01:05 16:01:05.442 INFO: Sensor C# Unit Test Results Import (wrapped) (done) | time=0ms
16:01:05 16:01:05.442 INFO: Sensor Zero Coverage Sensor (wrapped)
16:01:05 16:01:05.474 INFO: Sensor Zero Coverage Sensor (wrapped) (done) | time=32ms
16:01:05 16:01:05.474 INFO: Sensor Code Colorizer Sensor (wrapped)
16:01:05 16:01:05.505 INFO: Sensor Code Colorizer Sensor (wrapped) (done) | time=31ms
16:01:05 16:01:05.505 INFO: Sensor CPD Block Indexer (wrapped)
16:01:05 16:01:05.505 INFO: DefaultCpdBlockIndexer is used for cs
16:01:05 16:01:05.505 DEBUG: No CpdMapping for language cs
16:01:05 16:01:05.505 INFO: Sensor CPD Block Indexer (wrapped) (done) | time=0ms
16:01:05 16:01:05.505 INFO: Calculating CPD for 0 files
16:01:05 16:01:05.505 INFO: CPD calculation finished
16:01:08 16:01:08.692 INFO: Analysis report generated in 3094ms, dir size=276 KB
16:01:09 16:01:09.364 INFO: Analysis reports compressed in 672ms, zip size=150 KB
16:01:09 16:01:09.364 INFO: Analysis report generated in C:\Jenkins\jobs\firecom_backend\workspace\.scannerwork\batch-report
16:01:09 16:01:09.364 DEBUG: Upload report
</code>```

There is a folder called null, maybe this is the problem but I don't know solve it.

My sonar.properties are:

```<code>sonar.projectKey=mykey
sonar.projectName=myproject
sonar.projectVersion=1.0
sonar.sources=.
sonar.language=cs
sonar.sourceEncoding=UTF-8

sonar.analysis.mode
sonar.verbose=true
</code>```

UPDATE:

I am trying to downgrade the plugin of C# but I do not find where.

How can I do it?

答:
I guess you are using sonar-scanner (w/o MsBuild).
Since version 6.0 of sonar-csharp-plugin, it supports only
sonar-scanner-msbuild.

You should migrate to MsBuild scanner or downgrade to 5.X.X version of plugin.

Body:
I am using sonarqube with jenkins. The execution is successful but I don´t see any report or result. Everything is 0.

I think the problem is here, but I am not sure.

16:01:05 16:01:05.380 WARN: This may lead to missing/broken features in SonarQube
16:01:05 16:01:05.380 INFO: Sensor SCM Sensor (wrapped) (done) | time=625ms
16:01:05 16:01:05.380 INFO: Sensor C# (wrapped)
16:01:05 16:01:05.396 INFO: Importing analysis results from C:\Jenkins\jobs\firecom_backend\workspace\null\output-cs
16:01:05 16:01:05.411 WARN: Protobuf file not found: null\output-cs\encoding.pb
16:01:05 16:01:05.427 WARN: Protobuf file not found: null\output-cs\metrics.pb
16:01:05 16:01:05.427 WARN: Protobuf file not found: null\output-cs\issues.pb
16:01:05 16:01:05.427 WARN: Protobuf file not found: null\output-cs\token-type.pb
16:01:05 16:01:05.442 WARN: Protobuf file not found: null\output-cs\symrefs.pb
16:01:05 16:01:05.442 WARN: Protobuf file not found: null\output-cs\token-cpd.pb
16:01:05 16:01:05.442 INFO: Sensor C# (wrapped) (done) | time=62ms
16:01:05 16:01:05.442 INFO: Sensor C# Unit Tests Coverage Report Import (wrapped)
16:01:05 16:01:05.442 DEBUG: No coverage property. Skip Sensor
16:01:05 16:01:05.442 INFO: Sensor C# Unit Tests Coverage Report Import (wrapped) (done) | time=0ms
16:01:05 16:01:05.442 INFO: Sensor C# Integration Tests Coverage Report Import (wrapped)
16:01:05 16:01:05.442 DEBUG: No coverage property. Skip Sensor
16:01:05 16:01:05.442 INFO: Sensor C# Integration Tests Coverage Report Import (wrapped) (done) | time=0ms
16:01:05 16:01:05.442 INFO: Sensor C# Unit Test Results Import (wrapped)
16:01:05 16:01:05.442 DEBUG: No unit test results property. Skip Sensor
16:01:05 16:01:05.442 INFO: Sensor C# Unit Test Results Import (wrapped) (done) | time=0ms
16:01:05 16:01:05.442 INFO: Sensor Zero Coverage Sensor (wrapped)
16:01:05 16:01:05.474 INFO: Sensor Zero Coverage Sensor (wrapped) (done) | time=32ms
16:01:05 16:01:05.474 INFO: Sensor Code Colorizer Sensor (wrapped)
16:01:05 16:01:05.505 INFO: Sensor Code Colorizer Sensor (wrapped) (done) | time=31ms
16:01:05 16:01:05.505 INFO: Sensor CPD Block Indexer (wrapped)
16:01:05 16:01:05.505 INFO: DefaultCpdBlockIndexer is used for cs
16:01:05 16:01:05.505 DEBUG: No CpdMapping for language cs
16:01:05 16:01:05.505 INFO: Sensor CPD Block Indexer (wrapped) (done) | time=0ms
16:01:05 16:01:05.505 INFO: Calculating CPD for 0 files
16:01:05 16:01:05.505 INFO: CPD calculation finished
16:01:08 16:01:08.692 INFO: Analysis report generated in 3094ms, dir size=276 KB
16:01:09 16:01:09.364 INFO: Analysis reports compressed in 672ms, zip size=150 KB
16:01:09 16:01:09.364 INFO: Analysis report generated in C:\Jenkins\jobs\firecom_backend\workspace\.scannerwork\batch-report
16:01:09 16:01:09.364 DEBUG: Upload report

There is a folder called null, maybe this is the problem but I don't know solve it.

My sonar.properties are:

sonar.projectKey=mykey
sonar.projectName=myproject
sonar.projectVersion=1.0
sonar.sources=.
sonar.language=cs
sonar.sourceEncoding=UTF-8

sonar.analysis.mode
sonar.verbose=true

UPDATE:

I am trying to downgrade the plugin of C# but I do not find where.

How can I do it?


来源: stackexchange

问:
How to draw text over filled rectangle by XOR-ing its color with GDI?
I'm not sure if I'm expressing it right with words. The best way is to show it with an image. I'm trying to fill a rectangle while inverting the text color in it. Just like an edit control does:

So here's a drawing code (called from WM_PAINT):

```<code>//Erase background
::FillRect(hDC, &rcClient, ::GetSysColorBrush(COLOR_WINDOW));

//Draw text
::DrawText(hDC, text, text.size(), &rc,
    DT_LEFT | DT_TOP | DT_EDITCONTROL | DT_NOPREFIX | DT_SINGLELINE);

//Draw highlighted rect & invert text
HGDIOBJ hOldBrush = ::SelectObject(hDC, ::GetSysColorBrush(COLOR_HIGHLIGHT));
::PatBlt(hDC, rcDrawFrame.left, rcDrawFrame.top, rcDrawFrame.Width(), rcDrawFrame.Height(), DSTINVERT);
::SelectObject(hDC, hOldBrush);
</code>```

But for some reason the background rectangle comes out as black, and I know that COLOR_HIGHLIGHT is blue on this system:

So what am I doing wrong here?

答: You might want to consider a different strategy; drawing the text twice with inverted clipped region.</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure if I'm expressing it right with words. The best way is to show it with an image. I'm trying to fill a rectangle while inverting the text color in it. Just like an edit control does:

So here's a drawing code (called from WM_PAINT):

//Erase background
::FillRect(hDC, &rcClient, ::GetSysColorBrush(COLOR_WINDOW));

//Draw text
::DrawText(hDC, text, text.size(), &rc,
    DT_LEFT | DT_TOP | DT_EDITCONTROL | DT_NOPREFIX | DT_SINGLELINE);

//Draw highlighted rect & invert text
HGDIOBJ hOldBrush = ::SelectObject(hDC, ::GetSysColorBrush(COLOR_HIGHLIGHT));
::PatBlt(hDC, rcDrawFrame.left, rcDrawFrame.top, rcDrawFrame.Width(), rcDrawFrame.Height(), DSTINVERT);
::SelectObject(hDC, hOldBrush);

But for some reason the background rectangle comes out as black, and I know that COLOR_HIGHLIGHT is blue on this system:

So what am I doing wrong here?


问:
And Condition with join is similar to where condition after join
Is it similar to have and condition with join and where condition after join?

for example

will it give me same result for below two queries

```<code>1) SELECT COUNT(*)
FROM language_message_mapping lm
 LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
  AND lm.user_profile_id_fk IS NOT NULL

2) SELECT COUNT(*)
FROM language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
where lm.user_profile_id_fk IS NOT NULL
</code>```

I want to update rows which I get from above query
please tell me below update query is correct or not

```<code>UPDATE language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
SET lm.user_account_id_fk=up.user_account_id_fk
AND lm.user_profile_id_fk IS NOT NULL;
</code>```

答:
No, this is not the same for a left join (it would be the same for an inner join though).

The first query gets all records from the first table and adds data from the second table according to your conditions in the JOIN ON clause.

The second query gets not all records of the first table - only the data that matches the where clause.

Body:
Is it similar to have and condition with join and where condition after join?

for example

will it give me same result for below two queries

1) SELECT COUNT(*)
FROM language_message_mapping lm
 LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
  AND lm.user_profile_id_fk IS NOT NULL

2) SELECT COUNT(*)
FROM language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
where lm.user_profile_id_fk IS NOT NULL

I want to update rows which I get from above query
please tell me below update query is correct or not

UPDATE language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
SET lm.user_account_id_fk=up.user_account_id_fk
AND lm.user_profile_id_fk IS NOT NULL;


问:
C# switch statement limitations - why?
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

```<code>  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }
</code>```

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

答:
wrote:

"The switch statement does a constant time branch regardless of how many cases you have."

Since the language allows the string type to be used in a switch statement I presume the compiler is unable to generate code for a constant time branch implementation for this type and needs to generate an if-then style.

@mweerden - Ah I see. Thanks.

I do not have a lot of experience in C# and .NET but it seems the language designers do not allow static access to the type system except in narrow circumstances. The typeof keyword returns an object so this is accessible at run-time only.

OwnerDisplayName: kronoz

Title: C# switch statement limitations - why?

Body:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.

For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!),

  Type t = typeof(int);

  switch (t) {

    case typeof(int):
      Console.WriteLine("int!");
      break;

    case typeof(string):
      Console.WriteLine("string!");
      break;

    default:
      Console.WriteLine("unknown!");
      break;
  }

Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.

Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is,  primitive). What is the justification?

LastEditorDisplayName: ecleel

OwnerDisplayName: Henk

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Henk


问:
Efficient way to conditionally populate elements in a pandas groupby object (possibly by applying a function)
I'm having a problem about performance when trying to apply a function to a groupby object derived from a dataframe that has about 150,000 rows.

For simplicity, let's work on the dummy dataframe a

```<code>arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
a[1] = pd.date_range('2017-07-02', periods=10, freq='5min')

a
Out[24]:
                     0                   1
first second
bar   one     0.821371 2017-07-02 00:00:00
      one     0.312364 2017-07-02 00:05:00
      two     0.104821 2017-07-02 00:10:00
baz   one     0.839370 2017-07-02 00:15:00
      two     0.307262 2017-07-02 00:20:00
foo   one     0.719300 2017-07-02 00:25:00
      two     0.371118 2017-07-02 00:30:00
      two     0.765483 2017-07-02 00:35:00
qux   one     0.794236 2017-07-02 00:40:00
      two     0.571231 2017-07-02 00:45:00
</code>```

I want to conditionally populate the bottom element of the 0th column in each first-second group according to the logic described in this function

```<code>def myfunc(g):

if( len(g) >= 2): # if each group's length is greater than or equal to 2, then:

    if ((g.loc[g.index[-1], 0] > 0.5)): # If the last element of the 0th column of the group > 0.5, then:

        time_gap = g.loc[g.index[-1], 1] - g.loc[g.index[-2], 1] # Find the time difference between the last two records in 1st column

        g.loc[g.index[-1], 0] = time_gap # and assign it to the last element in the 0th column of that group

    else:
        g.loc[g.index[-1], 0] = 'ELSE' # Assign ELSE to the last element of the 0th column of the group

return g
</code>```

Applying this function yields,

```<code>a.reset_index().groupby(['first', 'second']).apply(myfunc)
Out[23]:
  first second                0                   1
0   bar    one         0.821371 2017-07-02 00:00:00
1   bar    one             ELSE 2017-07-02 00:05:00  correct
2   bar    two         0.104821 2017-07-02 00:10:00
3   baz    one          0.83937 2017-07-02 00:15:00
4   baz    two         0.307262 2017-07-02 00:20:00
5   foo    one           0.7193 2017-07-02 00:25:00
6   foo    two         0.371118 2017-07-02 00:30:00
7   foo    two  0 days 00:05:00 2017-07-02 00:35:00  correct
8   qux    one         0.794236 2017-07-02 00:40:00
9   qux    two         0.571231 2017-07-02 00:45:00
</code>```

The above result is exactly what I wanted. The problem is that this approach is freezing my 16GB/i5-6200U CPU @ 2.3GHz computer when applied to the dataframe where I have about 150,000 rows.

What is the most efficient way to conditionally populate such elements where (possibly) I need to write a function?

NB: I ran this in a jupyter notebook on windows 10 - if that is important

答:
i came up with a vectorized version to perform your transformation in several steps. If you have a rather complex transformation as you have here i would advice you to try to split it in several steps you can perfrom in pandas.

Your first step would be finding more then two entrys in a group:

```<code>to_check = df.groupby(['first','second']).size().apply(lambda x: True if x > 1 else False)
first  second
bar    one        True
       two       False
baz    one       False
       two       False
foo    one       False
       two        True
qux    one       False
       two       False
dtype: bool
</code>```

Now we can merge (on the index) the results back onto the original df:

```<code>df = df.merge(to_check.rename('check').to_frame(), left_index=True, right_index=True)
                   one                 two  check
first second
bar   one     0.821371 2017-07-02 00:00:00   True
      one     0.312364 2017-07-02 00:05:00   True
      two     0.104821 2017-07-02 00:10:00  False
baz   one     0.839370 2017-07-02 00:15:00  False
      two     0.307262 2017-07-02 00:20:00  False
foo   one     0.719300 2017-07-02 00:25:00  False
      two     0.371118 2017-07-02 00:30:00   True
      two     0.765483 2017-07-02 00:35:00   True
qux   one     0.794236 2017-07-02 00:40:00  False
      two     0.571231 2017-07-02 00:45:00  False
</code>```

Now we can use the 'check' column to locate the groups we are interested and see if we should perform a calculation:

```<code>to_calc = df.loc[df['check'], 'one'].groupby(['first','second']).apply(lambda x: 1 if x[-1] > 0.5 else 'Else')
first  second
bar    one           Else
foo    two       0.394365
</code>```

Now that we have the results we can merge them back onto the df:

```<code>df = df.merge(to_calc.to_frame(), left_index=True, right_index=True, how='outer')
                   one                 two  check to_calc
first second
bar   one     0.821371 2017-07-02 00:00:00   True    Else
      one     0.312364 2017-07-02 00:05:00   True    Else
      two     0.104821 2017-07-02 00:10:00  False     NaN
baz   one     0.839370 2017-07-02 00:15:00  False     NaN
      two     0.307262 2017-07-02 00:20:00  False     NaN
foo   one     0.719300 2017-07-02 00:25:00  False     NaN
      two     0.371118 2017-07-02 00:30:00   True       1
      two     0.765483 2017-07-02 00:35:00   True       1
qux   one     0.794236 2017-07-02 00:40:00  False     NaN
      two     0.571231 2017-07-02 00:45:00  False     NaN
</code>```

This we can use to perform the actual calculation:

```<code>df_calc = df.loc[df['to_calc']==1,'two'].groupby(level=['first','second']).apply(lambda x: x[-1]-x[-2])
df = df.merge(df_calc.rename('calc').to_frame(), left_index=True, right_index=True, how='outer')
                   one                 two  check to_calc     calc
first second
bar   one     0.821371 2017-07-02 00:00:00   True    Else      NaT
      one     0.312364 2017-07-02 00:05:00   True    Else      NaT
      two     0.104821 2017-07-02 00:10:00  False     NaN      NaT
baz   one     0.839370 2017-07-02 00:15:00  False     NaN      NaT
      two     0.307262 2017-07-02 00:20:00  False     NaN      NaT
foo   one     0.719300 2017-07-02 00:25:00  False     NaN      NaT
      two     0.371118 2017-07-02 00:30:00   True       1 00:05:00
      two     0.765483 2017-07-02 00:35:00   True       1 00:05:00
qux   one     0.794236 2017-07-02 00:40:00  False     NaN      NaT
      two     0.571231 2017-07-02 00:45:00  False     NaN      NaT
</code>```

To write the result only into the last field of every group is rather tricky now, but can be achieved by combining pandas nan and duplicated test:

```<code>calc_select = (~pd.isnull(df['calc']))&~(
       df.duplicated(subset=['first','second'],keep='last'))
else_select = (df['to_calc']=='Else')&~(
       df.duplicated(subset=['first','second'],keep='last'))
df.loc[else_select, 'one'] =  df.loc[else_select, 'to_calc']
df.loc[calc_select, 'one'] = df.loc[calc_select, calc'].astype('O')

first second              one                 two  check to_calc     calc
0   bar    one         0.821371 2017-07-02 00:00:00   True    Else      NaT
1   bar    one             Else 2017-07-02 00:05:00   True    Else      NaT
2   bar    two         0.104821 2017-07-02 00:10:00  False     NaN      NaT
3   baz    one          0.83937 2017-07-02 00:15:00  False     NaN      NaT
4   baz    two         0.307262 2017-07-02 00:20:00  False     NaN      NaT
5   foo    one           0.7193 2017-07-02 00:25:00  False     NaN      NaT
6   foo    two         0.371118 2017-07-02 00:30:00   True       1 00:05:00
7   foo    two  0 days 00:05:00 2017-07-02 00:35:00   True       1 00:05:00
8   qux    one         0.794236 2017-07-02 00:40:00  False     NaN      NaT
9   qux    two         0.571231 2017-07-02 00:45:00  False     NaN      NaT
</code>```

My solution actually runs slower then yours (18.4 ms compared to yours with 7.08 ms) for the test data but i would assume that the vectorized solutions runs much faster on a bigger dataset. I would really be interested if you could provide some timings with your dataset.

Body:
I'm having a problem about performance when trying to apply a function to a groupby object derived from a dataframe that has about 150,000 rows.

For simplicity, let's work on the dummy dataframe a

arrays = [['bar', 'bar','bar', 'baz', 'baz', 'foo', 'foo', 'foo', 'qux', 'qux'],
             ['one', 'one','two', 'one', 'two', 'one', 'two', 'two', 'one', 'two']]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
a = pd.DataFrame(np.random.random((10,)), index = index)
a[1] = pd.date_range('2017-07-02', periods=10, freq='5min')

a
Out[24]:
                     0                   1
first second
bar   one     0.821371 2017-07-02 00:00:00
      one     0.312364 2017-07-02 00:05:00
      two     0.104821 2017-07-02 00:10:00
baz   one     0.839370 2017-07-02 00:15:00
      two     0.307262 2017-07-02 00:20:00
foo   one     0.719300 2017-07-02 00:25:00
      two     0.371118 2017-07-02 00:30:00
      two     0.765483 2017-07-02 00:35:00
qux   one     0.794236 2017-07-02 00:40:00
      two     0.571231 2017-07-02 00:45:00

I want to conditionally populate the bottom element of the 0th column in each first-second group according to the logic described in this function

def myfunc(g):

if( len(g) >= 2): # if each group's length is greater than or equal to 2, then:

    if ((g.loc[g.index[-1], 0] > 0.5)): # If the last element of the 0th column of the group > 0.5, then:

        time_gap = g.loc[g.index[-1], 1] - g.loc[g.index[-2], 1] # Find the time difference between the last two records in 1st column

        g.loc[g.index[-1], 0] = time_gap # and assign it to the last element in the 0th column of that group

    else:
        g.loc[g.index[-1], 0] = 'ELSE' # Assign ELSE to the last element of the 0th column of the group

return g

Applying this function yields,

a.reset_index().groupby(['first', 'second']).apply(myfunc)
Out[23]:
  first second                0                   1
0   bar    one         0.821371 2017-07-02 00:00:00
1   bar    one             ELSE 2017-07-02 00:05:00  correct
2   bar    two         0.104821 2017-07-02 00:10:00
3   baz    one          0.83937 2017-07-02 00:15:00
4   baz    two         0.307262 2017-07-02 00:20:00
5   foo    one           0.7193 2017-07-02 00:25:00
6   foo    two         0.371118 2017-07-02 00:30:00
7   foo    two  0 days 00:05:00 2017-07-02 00:35:00  correct
8   qux    one         0.794236 2017-07-02 00:40:00
9   qux    two         0.571231 2017-07-02 00:45:00

The above result is exactly what I wanted. The problem is that this approach is freezing my 16GB/i5-6200U CPU @ 2.3GHz computer when applied to the dataframe where I have about 150,000 rows.

What is the most efficient way to conditionally populate such elements where (possibly) I need to write a function?

NB: I ran this in a jupyter notebook on windows 10 - if that is important

Body:
i came up with a vectorized version to perform your transformation in several steps. If you have a rather complex transformation as you have here i would advice you to try to split it in several steps you can perfrom in pandas.

Your first step would be finding more then two entrys in a group:

to_check = df.groupby(['first','second']).size().apply(lambda x: True if x > 1 else False)
first  second
bar    one        True
       two       False
baz    one       False
       two       False
foo    one       False
       two        True
qux    one       False
       two       False
dtype: bool

Now we can merge (on the index) the results back onto the original df:

df = df.merge(to_check.rename('check').to_frame(), left_index=True, right_index=True)
                   one                 two  check
first second
bar   one     0.821371 2017-07-02 00:00:00   True
      one     0.312364 2017-07-02 00:05:00   True
      two     0.104821 2017-07-02 00:10:00  False
baz   one     0.839370 2017-07-02 00:15:00  False
      two     0.307262 2017-07-02 00:20:00  False
foo   one     0.719300 2017-07-02 00:25:00  False
      two     0.371118 2017-07-02 00:30:00   True
      two     0.765483 2017-07-02 00:35:00   True
qux   one     0.794236 2017-07-02 00:40:00  False
      two     0.571231 2017-07-02 00:45:00  False

Now we can use the 'check' column to locate the groups we are interested and see if we should perform a calculation:

to_calc = df.loc[df['check'], 'one'].groupby(['first','second']).apply(lambda x: 1 if x[-1] > 0.5 else 'Else')
first  second
bar    one           Else
foo    two       0.394365

Now that we have the results we can merge them back onto the df:

df = df.merge(to_calc.to_frame(), left_index=True, right_index=True, how='outer')
                   one                 two  check to_calc
first second
bar   one     0.821371 2017-07-02 00:00:00   True    Else
      one     0.312364 2017-07-02 00:05:00   True    Else
      two     0.104821 2017-07-02 00:10:00  False     NaN
baz   one     0.839370 2017-07-02 00:15:00  False     NaN
      two     0.307262 2017-07-02 00:20:00  False     NaN
foo   one     0.719300 2017-07-02 00:25:00  False     NaN
      two     0.371118 2017-07-02 00:30:00   True       1
      two     0.765483 2017-07-02 00:35:00   True       1
qux   one     0.794236 2017-07-02 00:40:00  False     NaN
      two     0.571231 2017-07-02 00:45:00  False     NaN

This we can use to perform the actual calculation:

df_calc = df.loc[df['to_calc']==1,'two'].groupby(level=['first','second']).apply(lambda x: x[-1]-x[-2])
df = df.merge(df_calc.rename('calc').to_frame(), left_index=True, right_index=True, how='outer')
                   one                 two  check to_calc     calc
first second
bar   one     0.821371 2017-07-02 00:00:00   True    Else      NaT
      one     0.312364 2017-07-02 00:05:00   True    Else      NaT
      two     0.104821 2017-07-02 00:10:00  False     NaN      NaT
baz   one     0.839370 2017-07-02 00:15:00  False     NaN      NaT
      two     0.307262 2017-07-02 00:20:00  False     NaN      NaT
foo   one     0.719300 2017-07-02 00:25:00  False     NaN      NaT
      two     0.371118 2017-07-02 00:30:00   True       1 00:05:00
      two     0.765483 2017-07-02 00:35:00   True       1 00:05:00
qux   one     0.794236 2017-07-02 00:40:00  False     NaN      NaT
      two     0.571231 2017-07-02 00:45:00  False     NaN      NaT

To write the result only into the last field of every group is rather tricky now, but can be achieved by combining pandas nan and duplicated test:

calc_select = (~pd.isnull(df['calc']))&~(
       df.duplicated(subset=['first','second'],keep='last'))
else_select = (df['to_calc']=='Else')&~(
       df.duplicated(subset=['first','second'],keep='last'))
df.loc[else_select, 'one'] =  df.loc[else_select, 'to_calc']
df.loc[calc_select, 'one'] = df.loc[calc_select, calc'].astype('O')

first second              one                 two  check to_calc     calc
0   bar    one         0.821371 2017-07-02 00:00:00   True    Else      NaT
1   bar    one             Else 2017-07-02 00:05:00   True    Else      NaT
2   bar    two         0.104821 2017-07-02 00:10:00  False     NaN      NaT
3   baz    one          0.83937 2017-07-02 00:15:00  False     NaN      NaT
4   baz    two         0.307262 2017-07-02 00:20:00  False     NaN      NaT
5   foo    one           0.7193 2017-07-02 00:25:00  False     NaN      NaT
6   foo    two         0.371118 2017-07-02 00:30:00   True       1 00:05:00
7   foo    two  0 days 00:05:00 2017-07-02 00:35:00   True       1 00:05:00
8   qux    one         0.794236 2017-07-02 00:40:00  False     NaN      NaT
9   qux    two         0.571231 2017-07-02 00:45:00  False     NaN      NaT

My solution actually runs slower then yours (18.4 ms compared to yours with 7.08 ms) for the test data but i would assume that the vectorized solutions runs much faster on a bigger dataset. I would really be interested if you could provide some timings with your dataset.


问:
Trying to Start a function causes Runtime Error 424
I am trying to start the following function

```<code>Function MitteOben(Bereich As Range)

    With Bereich
        .VerticalAlignment = xlTop
        .HorizontalAlignment = xlCenter
    End With

    With Bereich.Font
        .Name = "Tahoma"
        .Size = 10
        .ThemeColor = xlThemeColorLight1
    End With

End Function
</code>```

When I try to define a range and start the function it creates Runtime Error 424.

I am trying to start it this way:

```<code>Set Hlpr = Range(Cells(ObjStartRow, 14), Cells(ObjStartRow, 28))
MitteOben (Hlpr)
Fett (Hlpr)
</code>```

I have also tried to Swap "ObjStartRow" with a number or Change the whole range to: Range("N29:AC29") both have failed.

答:
It should be a Sub, not a function. In genreal, functions return values, subs do something.

Having said that, as a VBA person working in Germany, I beg you to start naming your Functions, Variables and Subs in English. It really saves a lot of passive anger from the next person working over your code. And it makes your code better.

```<code>Public Sub MitteOben(Bereich As Range)

    With Bereich
        .VerticalAlignment = xlTop
        .HorizontalAlignment = xlCenter
    End With

    With Bereich.Font
        .name = "Tahoma"
        .Size = 10
        .ThemeColor = xlThemeColorLight1
    End With

End Sub
</code>```

This is how to call it:
call MitteOben(selection) or MitteOben selection

Body:
I am trying to start the following function

Function MitteOben(Bereich As Range)

    With Bereich
        .VerticalAlignment = xlTop
        .HorizontalAlignment = xlCenter
    End With

    With Bereich.Font
        .Name = "Tahoma"
        .Size = 10
        .ThemeColor = xlThemeColorLight1
    End With

End Function

When I try to define a range and start the function it creates Runtime Error 424.

I am trying to start it this way:

Set Hlpr = Range(Cells(ObjStartRow, 14), Cells(ObjStartRow, 28))
MitteOben (Hlpr)
Fett (Hlpr)

I have also tried to Swap "ObjStartRow" with a number or Change the whole range to: Range("N29:AC29") both have failed.

Body:
It should be a Sub, not a function. In genreal, functions return values, subs do something.

Having said that, as a VBA person working in Germany, I beg you to start naming your Functions, Variables and Subs in English. It really saves a lot of passive anger from the next person working over your code. And it makes your code better.

Public Sub MitteOben(Bereich As Range)

    With Bereich
        .VerticalAlignment = xlTop
        .HorizontalAlignment = xlCenter
    End With

    With Bereich.Font
        .name = "Tahoma"
        .Size = 10
        .ThemeColor = xlThemeColorLight1
    End With

End Sub

This is how to call it:
call MitteOben(selection) or MitteOben selection


问:
Cant Fully Install Hawq on Ambari
Im trying to run Pivotal Hawq with Ambari. I add the Hawq repository and install the Hawq and PXF through ambari. I have 4 nodes and so the configuration would be 1 Hawq master and 3 segment. The master is started correctly, but i only can start 2 of the 3 segments, one of the segments is always giving the error represented on the image  error_img. The error its like no hawq service is not installed.
Can someons give some help?</p>

答: I managed to start the hawq segment. I had to remove all haqwq components and then add the segment manually on ambari, then it worked</p>

Title: Cant Fully Install Hawq on Ambari


问:
kibana timelion time zone issue
sorry if this is a newbie question but i have been having a very weird issue with my installation of kibana:

setting dateFormat:tz is set to UTC.
searches are working great and data is shown exactly as expected when the last minute in the graph is 3 hours before my local time (i'm at GMT+3 so it's accurate)

in time lion on the other hand I've been having an issue where i run a very basic time series like .es(*) and what i get is a graph where the last 3 hours is showing 0 entries. it seems that the timelion is not using the configured time zone for the graph limits but it is using the tz on the data.

any thoughts?

答:
You need to set your data time field</p>

```<code>.es(timefield=YOURFIELDNAME)
</code>```

Title: kibana timelion time zone issue

Body:
You need to set your data time field

.es(timefield=YOURFIELDNAME)


问:
Javascript number.toLocaleString currency without currency sign
Suppose we have

```<code>var number = 123456.789;
</code>```

What I want is to display this number in locale 'de-DE' as

```<code>123.456,79
</code>```

in locale 'ja-JP' as

```<code>123,457
</code>```

in locale 'en-US' as

```<code>123,456.79
</code>```

and so on according to user's locale. The problem is that Javascript's number.toLocaleString requires to specify currency sign and I can't find out how to tell to not display it at all.

What I tried:

```<code>number.toLocaleString('de-DE', { style: 'currency' }));
// TypeError: undefined currency in NumberFormat() with currency style

number.toLocaleString('de-DE', { style: 'currency', currency: '' }));
// RangeError: invalid currency code in NumberFormat():

number.toLocaleString('de-DE', { style: 'currency', currency: false }));
// RangeError: invalid currency code in NumberFormat(): false

number.toLocaleString('de-DE', { style: 'currency', currency: null }));
// RangeError: invalid currency code in NumberFormat(): null
</code>```

The function also has option currencyDisplay. I tried the same values as above with currency option but with same result.

UPDATE (2020-11-25)

A few people pointed to .resolvedOptions(). It basically solves the question:

```<code>const currencyFractionDigits = new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: 'EUR',
}).resolvedOptions().maximumFractionDigits;

const value = (12345.678).toLocaleString('de-DE', {
    maximumFractionDigits: currencyFractionDigits
});

console.log(value); // prints 12.345,68
</code>```

Thank you.

答: Do you need the currency sign? If not number.toLocaleString('de-DE') should do the trick.

ContentLicense: CC BY-SA 4.0

Body:
Suppose we have

var number = 123456.789;

What I want is to display this number in locale 'de-DE' as

123.456,79

in locale 'ja-JP' as

123,457

in locale 'en-US' as

123,456.79

and so on according to user's locale. The problem is that Javascript's number.toLocaleString requires to specify currency sign and I can't find out how to tell to not display it at all.

What I tried:

number.toLocaleString('de-DE', { style: 'currency' }));
// TypeError: undefined currency in NumberFormat() with currency style

number.toLocaleString('de-DE', { style: 'currency', currency: '' }));
// RangeError: invalid currency code in NumberFormat():

number.toLocaleString('de-DE', { style: 'currency', currency: false }));
// RangeError: invalid currency code in NumberFormat(): false

number.toLocaleString('de-DE', { style: 'currency', currency: null }));
// RangeError: invalid currency code in NumberFormat(): null

The function also has option currencyDisplay. I tried the same values as above with currency option but with same result.

UPDATE (2020-11-25)

A few people pointed to .resolvedOptions(). It basically solves the question:

const currencyFractionDigits = new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: 'EUR',
}).resolvedOptions().maximumFractionDigits;

const value = (12345.678).toLocaleString('de-DE', {
    maximumFractionDigits: currencyFractionDigits
});

console.log(value); // prints 12.345,68

Thank you.


问:
Why are non-placement `new` and `delete` built into the language and not just regular functions?
Why were the non-placement new expression and the delete expression implemented as language built-in instead of regular functions?

If we have...

a way of requesting/giving back memory to the OS

a way of explicitly invoking a constructor (placement new)

a way of explicitly invoking a destructor (~T())

...why couldn't non-placement new and delete just be regular functions in the Standard Library? Example:

```<code>template <typename T, typename... Ts>
T* library_new(Ts&&... xs)
{
    auto* ptr = /* request enough memory for `T` from OS */;
    new (ptr) T(std::forward<Ts>(xs)...);
    return ptr;
}

template <typename T>
void library_delete(T* ptr)
{
    ptr->~T();
    /* reclaim memory for `T` from OS */
}
</code>```

答:
If they were already provided as standalone functions then it would be impossible to provide user-defined replacement for them.

e.g. right now according to standard it is legel to write my own globl new and delete they will be used thoughout the program.

18.6.2 Storage allocation and deallocation [new.delete]

2 Replaceable: A C ++ program may define functions with either of these function signatures, and thereby displace the default versions defined by the C ++ standard library.

If those were supplied just like the rest of library functions then every normal call to new or delete would result "more than one instance of overloaded function matches arguments" error.

Body:
Why were the non-placement new expression and the delete expression implemented as language built-in instead of regular functions?

If we have...

a way of requesting/giving back memory to the OS

a way of explicitly invoking a constructor (placement new)

a way of explicitly invoking a destructor (~T())

...why couldn't non-placement new and delete just be regular functions in the Standard Library? Example:

template <typename T, typename... Ts>
T* library_new(Ts&&... xs)
{
    auto* ptr = /* request enough memory for `T` from OS */;
    new (ptr) T(std::forward<Ts>(xs)...);
    return ptr;
}

template <typename T>
void library_delete(T* ptr)
{
    ptr->~T();
    /* reclaim memory for `T` from OS */
}


答:
The first query will apply the lm.user_profile_id_fk IS NOT NULL statement in the join operation of both tables, so it will exclude the rows where lm.user_profile_id_fk IS NOT NULL.

The second query will do the join, and once the join is applied for all rows will extract those where lm.user_profile_id_fk IS NOT NULL

About performance it depens of table size, indexes, and others.

Title: And Condition with join is similar to where condition after join


问:
How get timezone offset from spring request?
I have class:

```<code>    @RestController
    @RequestMapping("/api/user")
    public class UserCtrl {
      @RequestMapping(value = "/update", method = RequestMethod.POST)
      public ResponseEntity updateUser(@RequestBody StringModel updateModel) {

    }
  }
</code>```

How I can get Timezone offset with this request? It's possible?

It writes a date to update a user, but needs to save a time zone, or rather its offset, to correctly present the result.

答:
```<code>    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    Locale locale = request.getLocale();
    Calendar calenda = Calendar.getInstance(locale);
    TimeZone timeZone = calenda.getTimeZone();
    int rawOffset = timeZone.getRawOffset();
    ZoneId zoneId = timeZone.toZoneId();
    ZoneRules rules = zoneId.getRules();
</code>```

rawOffset have time in milliseconds, e.g 3600000 -> +01:00

Body:
I have class:

    @RestController
    @RequestMapping("/api/user")
    public class UserCtrl {
      @RequestMapping(value = "/update", method = RequestMethod.POST)
      public ResponseEntity updateUser(@RequestBody StringModel updateModel) {

    }
  }

How I can get Timezone offset with this request? It's possible?

It writes a date to update a user, but needs to save a time zone, or rather its offset, to correctly present the result.

Body:
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    Locale locale = request.getLocale();
    Calendar calenda = Calendar.getInstance(locale);
    TimeZone timeZone = calenda.getTimeZone();
    int rawOffset = timeZone.getRawOffset();
    ZoneId zoneId = timeZone.toZoneId();
    ZoneRules rules = zoneId.getRules();

rawOffset have time in milliseconds, e.g 3600000 -> +01:00


问:
Why does postgres (with sequelize) count 1 if there is no value?
I'm using sequelize to count the number of messages that a device received during the last 24 hours.

Sequelize is going to execute the following request (I attached sequelize code at the end)

```<code>SELECT "device"."id", COUNT('records.id') AS "count"
FROM "device" AS "device"
  LEFT OUTER JOIN "record" AS "records" ON "device"."id" = "records"."deviceId" AND "records"."date" > '2017-07-06 08:09:40.468 +00:00'
WHERE "device"."typeId" = '2'
GROUP BY "device"."id";
</code>```

which return

```<code>id   count
24  25790
163 1
95  1
</code>```

the value for the id 24 is correct, but the other values should be 0.

I then manually execute this SQL query

```<code>SELECT device.id, COUNT(record.id) AS count
FROM device AS device
  LEFT OUTER JOIN record ON device.id = record."deviceId" AND record.date > '2017-07-06 08:09:40.468 +00:00'
WHERE device."typeId" = '2'
GROUP BY device.id;
</code>```

which gives me the expected result.

I'm not able to see the difference between the two queries. Does someone know why the second is working?

The sequelize request is the following

```<code>const devices = await this.database.model('device').findAll({
  where: {
    typeId: req.params.id,
  },
  attributes: {
    include: [
      'id',
      [this.database.fn('COUNT', 'records.id'), 'count'],
    ],
  },
  include: [{
    model: this.database.model('record'),
    where: {
      date: {
        $gt: oneDayAgo,
      },
    },
    attributes: [],
    required: false,
  }],
  group: ['device.id'],
})
</code>```

答:
The SQL has single quotes around records.id, so SQL is counting a string value (which is never NULL).  You want:

```<code>SELECT "device"."id", COUNT(records.id) AS "count"
</code>```

I don't know how to express this in sequelize, but the problem is the single quotes.

Body:
I'm using sequelize to count the number of messages that a device received during the last 24 hours.

Sequelize is going to execute the following request (I attached sequelize code at the end)

SELECT "device"."id", COUNT('records.id') AS "count"
FROM "device" AS "device"
  LEFT OUTER JOIN "record" AS "records" ON "device"."id" = "records"."deviceId" AND "records"."date" > '2017-07-06 08:09:40.468 +00:00'
WHERE "device"."typeId" = '2'
GROUP BY "device"."id";

which return

id   count
24  25790
163 1
95  1

the value for the id 24 is correct, but the other values should be 0.

I then manually execute this SQL query

SELECT device.id, COUNT(record.id) AS count
FROM device AS device
  LEFT OUTER JOIN record ON device.id = record."deviceId" AND record.date > '2017-07-06 08:09:40.468 +00:00'
WHERE device."typeId" = '2'
GROUP BY device.id;

which gives me the expected result.

I'm not able to see the difference between the two queries. Does someone know why the second is working?

The sequelize request is the following

const devices = await this.database.model('device').findAll({
  where: {
    typeId: req.params.id,
  },
  attributes: {
    include: [
      'id',
      [this.database.fn('COUNT', 'records.id'), 'count'],
    ],
  },
  include: [{
    model: this.database.model('record'),
    where: {
      date: {
        $gt: oneDayAgo,
      },
    },
    attributes: [],
    required: false,
  }],
  group: ['device.id'],
})

Body:
The SQL has single quotes around records.id, so SQL is counting a string value (which is never NULL).  You want:

SELECT "device"."id", COUNT(records.id) AS "count"

I don't know how to express this in sequelize, but the problem is the single quotes.


问:
Error run scrapy after install docker
I want to crawl from dynamic content using scrapy. I get from the internet that I must install docker. But after installing it, I always get error when I run:

```<code>scrapy runspider example.py
</code>```

or other scrapy command. Then I uninstall docker. But the error is still showed. This is the error:

then I try to install pypiwin32, there is an error too:

How to solve it?

答:
Maybe it's just a permission denied because pip is trying to set files in a directory which need more privileges.

Try to run your console with administration privileges and executing:

```<code>pip install pypiwin32
</code>```

Then try again to run your script, without admin privileges.

Edit:

If you don't want to run cmd as admin, you could try something like:

```<code>python -m pip install pypiwin32
</code>```

But I'm not sure if it will work.

Title: Error run scrapy after install docker

Body:
I want to crawl from dynamic content using scrapy. I get from the internet that I must install docker. But after installing it, I always get error when I run:

scrapy runspider example.py

or other scrapy command. Then I uninstall docker. But the error is still showed. This is the error:

then I try to install pypiwin32, there is an error too:

How to solve it?

Body:
Maybe it's just a permission denied because pip is trying to set files in a directory which need more privileges.

Try to run your console with administration privileges and executing:

pip install pypiwin32

Then try again to run your script, without admin privileges.

Edit:

If you don't want to run cmd as admin, you could try something like:

python -m pip install pypiwin32

But I'm not sure if it will work.


问:
Multiple rows update without select
An old question for Linq 2 Entities. I'm just asking it again, in case someone has came up with the solution.

I want to perform query that does this:

```<code>UPDATE dbo.Products WHERE Category = 1 SET Category = 5
</code>```

And I want to do it with Entity Framework 4.3.1.

This is just an example, I have a tons of records I just want 1 column to change value, nothing else. Loading to DbContext with Where(...).Select(...), changing all elements, and then saving with SaveChanges() does not work well for me.

Should I stick with ExecuteCommand and send direct query as it is written above (of course make it reusable) or is there another nice way to do it from Linq 2 Entities / Fluent.

Thanks!

答:
Yes, ExecuteCommand() is definitely the way to do it without fetching all the rows' data and letting ChangeTracker sort it out. Just to provide an example:

Will result in all rows being fetched and an update performed for each row changed:

```<code>    using (YourDBContext yourDB = new YourDBContext()) {
        yourDB.Products.Where(p => p.Category = 1).ToList().ForEach(p => p.Category = 5);
        yourDB.SaveChanges();
    }
</code>```

Just a single update:

```<code>    using (YourDBContext yourDB = new YourDBContext()) {
        var sql = "UPDATE dbo.Products WHERE Category = @oldcategory SET Category = @newcategory";
        var oldcp = new SqlParameter { ParameterName = "oldcategory", DbType = DbType.Int32, Value = 1 };
        var newcp = new SqlParameter { ParameterName = "newcategory", DbType = DbType.Int32, Value = 5 };
        yourDB.Database.ExecuteSqlCommand(sql, oldcp, newcp);
    }
</code>```

Title: Multiple rows update without select

Body:
An old question for Linq 2 Entities. I'm just asking it again, in case someone has came up with the solution.

I want to perform query that does this:

UPDATE dbo.Products WHERE Category = 1 SET Category = 5

And I want to do it with Entity Framework 4.3.1.

This is just an example, I have a tons of records I just want 1 column to change value, nothing else. Loading to DbContext with Where(...).Select(...), changing all elements, and then saving with SaveChanges() does not work well for me.

Should I stick with ExecuteCommand and send direct query as it is written above (of course make it reusable) or is there another nice way to do it from Linq 2 Entities / Fluent.

Thanks!

Body:
Yes, ExecuteCommand() is definitely the way to do it without fetching all the rows' data and letting ChangeTracker sort it out. Just to provide an example:

Will result in all rows being fetched and an update performed for each row changed:

    using (YourDBContext yourDB = new YourDBContext()) {
        yourDB.Products.Where(p => p.Category = 1).ToList().ForEach(p => p.Category = 5);
        yourDB.SaveChanges();
    }

Just a single update:

    using (YourDBContext yourDB = new YourDBContext()) {
        var sql = "UPDATE dbo.Products WHERE Category = @oldcategory SET Category = @newcategory";
        var oldcp = new SqlParameter { ParameterName = "oldcategory", DbType = DbType.Int32, Value = 1 };
        var newcp = new SqlParameter { ParameterName = "newcategory", DbType = DbType.Int32, Value = 5 };
        yourDB.Database.ExecuteSqlCommand(sql, oldcp, newcp);
    }


问:
How do I get one element to respond to the click of another element? - CSS/jQuery
The question is simple, but in my implementation something has gone awry.

You can see my implementation here.

So what I want to happen is, when you click on one of the names in box #1, the dotted line and the #1 in a dotted circle both turn black and solid. The dotted line is not a border. The same should happen when you click any other data in the other corresponding boxes.

The main issue I am facing is that when I do a use the .css function in jQuery to manually change the color and the border, it works nicely. However, I would like to modify it with the toggle class (because I couldn't get toggle() to work with the css function) - so that when you click it once, you see the element clicked highlighted (with a 1px border - this functionality is already there), and the corresponding number for the box (and dotted line) turned to solid black.

Thanks.

答:
It looks like the JavaScript was fine. The only thing I could see messing things up was this line:

```<code>$('#bc1 dashed-circle').toggleClass('bc-dashed-to-solid-circle');
</code>```

You'll want to change that selector to #bc1 .dashed-circle.

The reason the dashes and number aren't changing color is because of specificity. You declare their normal color (#bdbebf) with the selector #blank-dashboard-breadcrumb span -- an id and an element. You declare the "selected" color (black) with .bc-dotted-to-solid or .bc-dashed-to-solid-circle -- simple classes. Even when the dash and the 1 have the appropriate classes, they still have a more specific selector telling them to remain gray.

Body:
It looks like the JavaScript was fine. The only thing I could see messing things up was this line:

$('#bc1 dashed-circle').toggleClass('bc-dashed-to-solid-circle');

You'll want to change that selector to #bc1 .dashed-circle.

The reason the dashes and number aren't changing color is because of specificity. You declare their normal color (#bdbebf) with the selector #blank-dashboard-breadcrumb span -- an id and an element. You declare the "selected" color (black) with .bc-dotted-to-solid or .bc-dashed-to-solid-circle -- simple classes. Even when the dash and the 1 have the appropriate classes, they still have a more specific selector telling them to remain gray.


问:
Bootstrap table not working good with ng-repeat
```<code><div ng-controller="reportCtrl">
      <table class="table table-hover">
          <thead class="row col-md-3">
              <tr class="row">
                  <th class="col-md-6">Key </th>
                  <th class="col-md-6"> Value</th>
              </tr>
          </thead>
          <tbody ng-repeat="param in params" class="row col-md-3">
              <tr class="row">
                  <td class="col-md-6 info">{{param.key}}</td>
                  <td class="col-md-6 info">{{param.val}}</td>
              </tr>
          </tbody>
      </table>
</div>
</code>```

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

答:
You do not need to add the row col-md-3 classes to the table-body or the row class to the tr elements. Also if you are repeating the items your ng-repeat needs to be on the tr element, if it is on the tbody element you are going to have multiple unnecessary tbody elements.

Please see working example

If you just want a simple table:

```<code><div ng-controller="TestController as vm">
  <table class="table table-bordered table-striped table-hover">
    <thead>
      <tr>
        <th>Key </th>
        <th> Value</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in vm.items">
        <td>{{$index}}</td>
        <td>{{item}}</td>
      </tr>
    </tbody>
  </table>
</div>
</code>```

JS:

```<code>var myApp = angular.module('myApp',[])
.controller('TestController', ['$scope', function($scope) {
  var self = this;

  self.items = ['one', 'two', 'three', 'four'];
}])
</code>```

If you do not need the table element you can use the bootstrap row and col-* classes

```<code><div class="row">
    <div class="col-sm-6">
      <h1>Key</h1>
    </div>
    <div class="col-sm-6">
      <h1>Value</h1>
    </div>
  </div>
  <div class="row" ng-repeat="item in vm.items">
    <div class="col-sm-6">
      {{$index}}
    </div>
    <div class="col-sm-6">
      {{item}}
    </div>
  </div>
</code>```

Body:
                  Key
                   Value

                  {{param.key}}
                  {{param.val}}

I have this table, when i'm using the bootstrap grid system with ng-repeat the results are very strange..

I've tried to play with the grid system but it dosent seem that it helps..

Body:
You do not need to add the row col-md-3 classes to the table-body or the row class to the tr elements. Also if you are repeating the items your ng-repeat needs to be on the tr element, if it is on the tbody element you are going to have multiple unnecessary tbody elements.

Please see working example

If you just want a simple table:

<div ng-controller="TestController as vm">
  <table class="table table-bordered table-striped table-hover">
    <thead>
      <tr>
        <th>Key </th>
        <th> Value</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in vm.items">
        <td>{{$index}}</td>
        <td>{{item}}</td>
      </tr>
    </tbody>
  </table>
</div>

JS:

var myApp = angular.module('myApp',[])
.controller('TestController', ['$scope', function($scope) {
  var self = this;

  self.items = ['one', 'two', 'three', 'four'];
}])

If you do not need the table element you can use the bootstrap row and col-* classes

<div class="row">
    <div class="col-sm-6">
      <h1>Key</h1>
    </div>
    <div class="col-sm-6">
      <h1>Value</h1>
    </div>
  </div>
  <div class="row" ng-repeat="item in vm.items">
    <div class="col-sm-6">
      {{$index}}
    </div>
    <div class="col-sm-6">
      {{item}}
    </div>
  </div>


问:
how to use an array in php mysql query?
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

```<code>$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";
</code>```

Can anyone help me with this?

答:
```<code>$query = "select * from sites where site_keywords in (".implode(",",$keywords).") order by rank DESC ";
</code>```

Title: how to use an array in php mysql query?

Body:
I've been trying to retrieve all site_keywords from the database, using where site_keywords in $keyword. But it doesn't show any error or output.

$user_query = $_REQUEST['user_query'];
$search=preg_split('/\s+/',$user_query);
$keywords = join(",",$search);
$query = "select * from sites where site_keywords in ('%$keywords%') order by rank DESC ";

Can anyone help me with this?


问:
Python log reader
I'm trying to create an asynchronous function that reads the constantly updating log file and gets every line of it. That's what I have for now:

```<code>async def log_reader():
    with open(LOG_PATH, "r", encoding='utf-8', errors='ignore') as logfile:
        logfile.seek(0, os.SEEK_END)
        while True:
            line = logfile.readline()
            if not line:
                await asyncio.sleep(0.2)
                continue
            # do stuff
</code>```

It works fine until the file is restarted. I was thinking about checking whether the file's size became smaller than it was, that would mean that it was refreshed, but I feel there must be a better option for that.

Any tips are welcome.

答:
For refreshing the file, you can check it's inode. Get it from the path using os.stat and then extract the inode number. If the inode you get is different than the previous one, you'll have to reopen the file. (so doing this using a with block may not be easy)

To optimise it a bit so you don't query the file all the time, you could implement some timeout which you can easily accept, but which is higher than the usual delay between the log lines.

This will work if the file has been replaced, which is the usual method of rotating logfiles. It will not work if the file has only been truncated.

Title: Python log reader

Body:
I'm trying to create an asynchronous function that reads the constantly updating log file and gets every line of it. That's what I have for now:

async def log_reader():
    with open(LOG_PATH, "r", encoding='utf-8', errors='ignore') as logfile:
        logfile.seek(0, os.SEEK_END)
        while True:
            line = logfile.readline()
            if not line:
                await asyncio.sleep(0.2)
                continue
            # do stuff

It works fine until the file is restarted. I was thinking about checking whether the file's size became smaller than it was, that would mean that it was refreshed, but I feel there must be a better option for that.

Any tips are welcome.


问:
Generating density/heat maps like SpatialKey
SpatialKey generates some really nice looking heatmaps, and we're looking into what's involved in doing this for an internal project to visualize large amounts of points. I'm looking for feedback on some ideas on where to get started (and it's just a really interesting problem).

SpatialKey heatmap http://img697.imageshack.us/img697/7964/resolutiondays508x17550.jpg

We know that they're using Flash, and from what we can tell, the heatmaps are interactive rather than being rendered from a tile server. Our first guess at how this is implemented is that the server provides their Flash client with a grid - each cell having a count computed by the server. The Flash client then does some interpolation based on the cell values in the grid to make the pretty output you see above.

At this stage, I'm just interested in how they could possibly generate the grid efficiently server-side (if our assumption on their implementation is even correct). It seems that it would involve:

Performing a query for what's currently in map bounds

Performing an aggregation subquery for each cell within those bounds (doing a count, sum, or average as in the example above).

Throw doing this at multiple zoom levels at a sane grid resolution and it seems like you'd need a custom spatial index to make this efficient.

Any takers on explaining an alternative route? If it matters, we're accustomed here to storing our data in PostgreSQL with PostGIS for the spatial index, but I'm open to trying anything.

答: MapReduce for your actual aggregate map totals, and something with Geospatial Indexing for the database - to feed these MapReduce jobs. I'm looking into implementing this exact same approach, but for interfaces instead of maps :) MongoDB seems to be a good fit at the moment.</p>


问:
Unhandled exception at 0x0F828F0E (ucrtbased.dll) in Hello World.exe: 0xC0000005: Access violation writing location 0x00000002
I am new in C++ and I've started to learn last night

I need help with the following error:

Unhandled exception at 0x0F828F0E (ucrtbased.dll) in Hello World.exe: 0xC0000005: Access violation writing location 0x00000002.

My code so far:

```<code>#include <iostream>
#include <conio.h>
#include <stdio.h>

using namespace std;

int main() {

    cout << "CUMPARATURI" << endl;

    int mere = 3 + 1;
    int banane = 16 / 4;

    cout << endl;
    cout << "Avem " << mere << " mere" << endl;
    cout << "Avem " << banane << " banane" << endl;

    int a = 16, b = 18;

    cout << endl;
    cout << "Valoarea lui a este " << a << endl;
    cout << "Dati o valoarea noua lui a : "; cin >> a;
    cout << "Noua valoarea a lui a este : " << a << endl;

    cout << endl;
    cout << "Acesta este primul rand \nAcesta este al 2-lea \nAcesta este al 3-lea";
    cout << endl;

    printf("\nAceasta este valoarea lui a: %d ", a);
    printf("\nLocatia lui a este %d \nDa-i valoare noua lui a : ", &a);
    scanf_s("%d", a);
    printf("Noua valoare a lui a este : %d",a);

    _getche();
    return 0;
};
</code>```

答:
If you take a look at the scanf_s documentation, you'll see that the variables you want to read data into are written after a &. The & takes the address of the variable, in fact scanf_s needs to know where to write the result in memory.

So, you should fix your code like this:

```<code>// Note '&a' instead of 'a'
scanf_s("%d", &a);
</code>```

That said, in C++ you may want to consider std::cin for reading data into variables, e.g.:

```<code>int a{};
std::cin >> a;
</code>```

Note that in this case there's no need to use the & (address-of) operator.

Body:
I am new in C++ and I've started to learn last night

I need help with the following error:

Unhandled exception at 0x0F828F0E (ucrtbased.dll) in Hello World.exe: 0xC0000005: Access violation writing location 0x00000002.

My code so far:

#include <iostream>
#include <conio.h>
#include <stdio.h>

using namespace std;

int main() {

    cout << "CUMPARATURI" << endl;

    int mere = 3 + 1;
    int banane = 16 / 4;

    cout << endl;
    cout << "Avem " << mere << " mere" << endl;
    cout << "Avem " << banane << " banane" << endl;

    int a = 16, b = 18;

    cout << endl;
    cout << "Valoarea lui a este " << a << endl;
    cout << "Dati o valoarea noua lui a : "; cin >> a;
    cout << "Noua valoarea a lui a este : " << a << endl;

    cout << endl;
    cout << "Acesta este primul rand \nAcesta este al 2-lea \nAcesta este al 3-lea";
    cout << endl;

    printf("\nAceasta este valoarea lui a: %d ", a);
    printf("\nLocatia lui a este %d \nDa-i valoare noua lui a : ", &a);
    scanf_s("%d", a);
    printf("Noua valoare a lui a este : %d",a);

    _getche();
    return 0;
};

Body:
If you take a look at the scanf_s documentation, you'll see that the variables you want to read data into are written after a &. The & takes the address of the variable, in fact scanf_s needs to know where to write the result in memory.

So, you should fix your code like this:

// Note '&a' instead of 'a'
scanf_s("%d", &a);

That said, in C++ you may want to consider std::cin for reading data into variables, e.g.:

int a{};
std::cin >> a;

Note that in this case there's no need to use the & (address-of) operator.


问:
Keytool generate version 3 certificates
Is there way to make keytool generate version 3 certificates?
I'm following this tutorial Tutorial and in the end i have version 1 certificates. But then in my application i get exception that is caused by :

```<code>Caused by: java.security.cert.CertPathValidatorException: Version 1 certificates can't be used as CA ones.
</code>```

I use keytool from jdk8.

EDIT:
Command

```<code>openssl x509 -signkey cakey.pem -req -days 3650 -in careq.pem -out caroot.cer -extensions v3_ca
</code>```

changes version of certificate.

答:
Solved, it was not problem in keytool, but in openssl changing version.
I needed to specify -extfile v3.ext where v3.ext file contained

```<code>authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
</code>```

according to thist post.

Title: Keytool generate version 3 certificates

Body:
Is there way to make keytool generate version 3 certificates?
I'm following this tutorial Tutorial and in the end i have version 1 certificates. But then in my application i get exception that is caused by :

Caused by: java.security.cert.CertPathValidatorException: Version 1 certificates can't be used as CA ones.

I use keytool from jdk8.

EDIT:
Command

openssl x509 -signkey cakey.pem -req -days 3650 -in careq.pem -out caroot.cer -extensions v3_ca

changes version of certificate.

Body:
Solved, it was not problem in keytool, but in openssl changing version.
I needed to specify -extfile v3.ext where v3.ext file contained

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment

according to thist post.


问:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
When trying to reference a managed bean in EL like so #{bean.entity.property}, sometimes a javax.el.PropertyNotFoundException: Target Unreachable exception is being thrown, usually when a bean property is to be set, or when a bean action is to be invoked.

There seem to be five different kinds of messages:

Target Unreachable, identifier 'bean' resolved to null

Target Unreachable, 'entity' returned null

Target Unreachable, 'null' returned null

Target Unreachable, ''0'' returned null

Target Unreachable, 'BracketSuffix' returned null

What do they all mean? How are they caused and how should they be solved?

答:
I decided to share my finding on this error after resolving it myself.

First of all, BalusC solutions should be taken seriously but then there is another likely issue in Netbeans to be aware of especially when building an Enterprise Application Project(EAR) using Maven.

Netbeans generates, a parent POM file, an EAR project, an EJB project and a WAR project.
Everything else in my project was fine, and I almost assumed the problem is a bug in probably GlassFish 4.0(I had to install and plug it into Netbeans) because GlassFish 4.1 has a Weld CDI bug which makes the embedded GlassFish 4.1 in Netbeans 8.0.2 unusable except through a patch.

Solution:

To resolve the "Target Unreachable, identifier 'bean' resolved to null"
error-

I Right-click the parent POM project, and select Properties. A Project Properties Dialog appears, click "Sources", you will be surprised to see the "Source/Binary Format" set to 1.5 and "Encoding" set to Windows 1250.
Change the "Source/Binary Format" to 1.6 0r 1.7, whichever you prefer to make your project CDI compliant, and "Encoding" to UTF-8.

Do the same for all the other subprojects(EAR, EJB, WAR) if they are not already compartible.
Run your project, and you won't get that error again.

I hope this helps someone out there having similar error.


问:
How to install certain node version from command line
I want to install node 6.9.4.

In windows console I try with this:

```<code>npm install node@v6.9.4
</code>```

And it throws this error:

```<code>npm ERR! No compatible version found: node@v6.9.4
npm ERR! Valid install targets:
npm ERR! 0.0.0
</code>```

In linux the result is similar. I try with

```<code>sudo npm install node@v6.9.4
</code>```

and the output is:

```<code>npm ERR! version not found: node@6.9.4-cls
</code>```

Is there a way to install certain node version with npm?

答:
I recommend you use nvm: Nodev Version Manager

It would be as easy as

```<code>nvm install 6.9.4
</code>```

It's a really good tool to manager all of your node versions.

Body:
I want to install node 6.9.4.

In windows console I try with this:

npm install node@v6.9.4

And it throws this error:

npm ERR! No compatible version found: node@v6.9.4
npm ERR! Valid install targets:
npm ERR! 0.0.0

In linux the result is similar. I try with

sudo npm install node@v6.9.4

and the output is:

npm ERR! version not found: node@6.9.4-cls

Is there a way to install certain node version with npm?

Body:
I recommend you use nvm: Nodev Version Manager

It would be as easy as

nvm install 6.9.4

It's a really good tool to manager all of your node versions.


问:
PostgreSQl pg_dump permission error?
Why a postgresql pg_dump not permitted with sudo which is producing permission denied error? Even root user is unable to pg_dump?</p>

答:
Use pg_dump -U postgres [other options] databasename to connect to the database as superuser while you perform the dump.

The database user is something different from the operating system user.

Title: PostgreSQl pg_dump permission error?


问:
Can i add an ActionListener() inside a main method or any method?
```<code>public void Message() {
@Override
public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

}
</code>```

<p>//Message() is a method inside a class.</p>

答:
No. We cannot create nested methods in java.
Try reading about actionlisteners . :)</p>

Body:
public void Message() {
@Override
public void actionPerformed(ActionEvent e) {
    JOptionPane.showMessageDialog(null, "Hello it is working");
}

}

//Message() is a method inside a class.


问:
Android layout collapse
I use a XWalkView to load webpage and a IjkVideoView to play live video in my app. I want the IjkVideoView playing the video in front the XwalkView, so I put these two view in a relativelayout and IijVideoView behind the XWalkView.

In the android studio's Component Tree of Design window the layout seems ok as below image,

While when I run the app in my device, the layout is in mess as below image. You can see the background of IjkVieoView is in front of XWalkView, but the video playing in the IjkVideoView is behind the XWalkView, as the upper part of the video has been covered by the XWalkView.

layout xml,

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="UselessParent">

        <!-- This could be your fragment container, or something -->

        <org.xwalk.core.XWalkView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/xWalkView"
            android:layout_width="fill_parent"
            android:layout_height="160dp"
            android:background="@color/blue"
            android:isScrollContainer="true">

        </org.xwalk.core.XWalkView>

        <com.xxxxxx.app.widget.media.IjkVideoView
            android:id="@+id/video_view"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="72dp"
            android:background="@color/colorAccent" />

        <com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            app:bb_tabXmlResource="@xml/web_tabs" />

    </RelativeLayout>
</LinearLayout>
</code>```

activity java code,

```<code>protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("INFO", "entered");
        setContentView(R.layout.activity_web);
        mXWalkView = (XWalkView) findViewById(R.id.xWalkView);
        XWalkSettings webSettings = mXWalkView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");

        videoView = (IjkVideoView) findViewById(R.id.video_view);
        videoView.setAspectRatio(IRenderView.AR_ASPECT_FILL_PARENT);
        videoView.setVideoURI(Uri.parse("http://live.xxxxxx.com/live/40xx27.flv"));
        videoView.start();

        final Bundle extras = getIntent().getExtras();
        mXWalkView.load("http://xxxxxxxxxxxxxx", null);
}
</code>```

答:
Your layout seems to be correct. It might be broken from the libs. It already has 1k+ issues.

Maybe you can use a custom dialog that has the video in it and show that dialog. This way the video will be in front of the images. Then you can try to remove the shadow or bgColor = transparent, so that the user might not realise that is a dialog. This hack may work.

Title: Android layout collapse

Body:
I use a XWalkView to load webpage and a IjkVideoView to play live video in my app. I want the IjkVideoView playing the video in front the XwalkView, so I put these two view in a relativelayout and IijVideoView behind the XWalkView.

In the android studio's Component Tree of Design window the layout seems ok as below image,

While when I run the app in my device, the layout is in mess as below image. You can see the background of IjkVieoView is in front of XWalkView, but the video playing in the IjkVideoView is behind the XWalkView, as the upper part of the video has been covered by the XWalkView.

layout xml,

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="UselessParent">

        <org.xwalk.core.XWalkView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/xWalkView"
            android:layout_width="fill_parent"
            android:layout_height="160dp"
            android:background="@color/blue"
            android:isScrollContainer="true">

        </org.xwalk.core.XWalkView>

        <com.xxxxxx.app.widget.media.IjkVideoView
            android:id="@+id/video_view"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="72dp"
            android:background="@color/colorAccent" />

        <com.roughike.bottombar.BottomBar
            android:id="@+id/bottomBar"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            app:bb_tabXmlResource="@xml/web_tabs" />

    </RelativeLayout>
</LinearLayout>

activity java code,

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("INFO", "entered");
        setContentView(R.layout.activity_web);
        mXWalkView = (XWalkView) findViewById(R.id.xWalkView);
        XWalkSettings webSettings = mXWalkView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mXWalkView.addJavascriptInterface(new JsInterface(), "NativeInterface");

        videoView = (IjkVideoView) findViewById(R.id.video_view);
        videoView.setAspectRatio(IRenderView.AR_ASPECT_FILL_PARENT);
        videoView.setVideoURI(Uri.parse("http://live.xxxxxx.com/live/40xx27.flv"));
        videoView.start();

        final Bundle extras = getIntent().getExtras();
        mXWalkView.load("http://xxxxxxxxxxxxxx", null);
}


问:
Grouping issue with addJSONData
I have some issue with jqGrid paging. I want create own group and add row data to it. While I add data to grid on the first page its Ok, but if add new group on the next page, I can see exception in Firebug and empty page. I use addJSONData method. The problem is that addJSONData iterate through all groups in Grid and look for their length:

```<code>str += "<tr id=\""+hid+"\" role=\"row\" class= \"ui-widget-content jqgroup ui-row-"+$t.p.direction+"\"><td colspan=\""+colspans+"\">"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"</td></tr>";
</code>```

But if I have one group on previous page and only sent data of second group with ajax and call addJSONData it throws exception: length of undefined. How can I solve it?

UPDATE: Here is my code:

```<code>function addToGrid(group, ids){
  var rowNum = jQuery(myGrid).jqGrid('getGridParam', 'rowNum');
  data = jQuery.ajax({
    url: myUrl,
    data: {'group': group, 'rowNum': rowNum, 'ids': ids},
    dataType: 'json',
    complete: function(jsondata,stat){
       if(stat=="success") {
          var targetGrid = jQuery(myGrid);
          var myjsongrid = eval('('+jsondata.responseText+')');
          var rows = myjsongrid.rows;
          if(rows.length != 0){
               targetGrid[0].addJSONData(myjsongrid);
          }
       }
    }
 });
</code>```

}

And table:

```<code>$(myGrid).jqGrid({
    url: myUrlTable,
    datatype: 'json',
    postData: {},
    mtype: 'GET',
    jsonReader: { repeatitems : false},
    colNames: ['Id', 'Group', 'Bytes'],
    colModel: [{name:'id', index: 'id', hidden: true},
               {name:'group', index: 'group', width: 100},
               {name:'bytes', index: 'bytes', width: 60, classes:'gc column-bytes', sortable: false, sorttype:'int', formatter:'integer'}
               ],
    grouping: true,
    groupingView: {
        groupField : ['group'],
        groupText : ['Group: ({1} items)'],
        groupOrder: 'asc',
        groupDataSorted : true
    },
    sortable: true,
    toppager: true,
    hoverrows: true,
    altrows: false,
});
</code>```

Test data from server:

```<code>{"total":1,"page":1,"records":1,"rows":[{"group":"abc", "bytes":229447,"id":"7124"}]}
</code>```

Another records are similar. I added 20 records and then I added next 5 on another page with group bbb.
Method addToGrid is called from another grid and with ids and entered group name to input dialog. Then I pass it to server and server returns valid data to fulefill grid. Server returns only data for the last page in my case 5 rows.

Server response:

```<code> {"total":2,"page":2,"records":5,"rows":[{"group":"bbb", "bytes":229447,"id":"7155"},
                                         {"group":"bbb", "bytes":229447,"id":"7156"},
                                         {"group":"bbb", "bytes":229447,"id":"7157"},
                                         {"group":"bbb", "bytes":229447,"id":"7158"},
                                         {"group":"bbb", "bytes":229447,"id":"7159"}
                                        ]
 }
</code>```

答:
i also got the same problem.following line would fix the code.

```<code>$("#jqGrid").jqGrid("groupingSetup");
</code>```

add this code before addJSONData function.

```<code>function addToGrid(group, ids){
  var rowNum = jQuery(myGrid).jqGrid('getGridParam', 'rowNum');
  data = jQuery.ajax({
    url: myUrl,
    data: {'group': group, 'rowNum': rowNum, 'ids': ids},
    dataType: 'json',
    complete: function(jsondata,stat){
       if(stat=="success") {
$("#myGrid").jqGrid("groupingSetup");
          var targetGrid = jQuery(myGrid);
          var myjsongrid = eval('('+jsondata.responseText+')');
          var rows = myjsongrid.rows;
          if(rows.length != 0){
               targetGrid[0].addJSONData(myjsongrid);
          }
       }
    }
 });
</code>```

Title: Grouping issue with addJSONData

Body:
I have some issue with jqGrid paging. I want create own group and add row data to it. While I add data to grid on the first page its Ok, but if add new group on the next page, I can see exception in Firebug and empty page. I use addJSONData method. The problem is that addJSONData iterate through all groups in Grid and look for their length:

str += "
"+icon+$.jgrid.format(grp.groupText[0], gv, grdata[n].length)+"
";

But if I have one group on previous page and only sent data of second group with ajax and call addJSONData it throws exception: length of undefined. How can I solve it?

UPDATE: Here is my code:

function addToGrid(group, ids){
  var rowNum = jQuery(myGrid).jqGrid('getGridParam', 'rowNum');
  data = jQuery.ajax({
    url: myUrl,
    data: {'group': group, 'rowNum': rowNum, 'ids': ids},
    dataType: 'json',
    complete: function(jsondata,stat){
       if(stat=="success") {
          var targetGrid = jQuery(myGrid);
          var myjsongrid = eval('('+jsondata.responseText+')');
          var rows = myjsongrid.rows;
          if(rows.length != 0){
               targetGrid[0].addJSONData(myjsongrid);
          }
       }
    }
 });

}

And table:

$(myGrid).jqGrid({
    url: myUrlTable,
    datatype: 'json',
    postData: {},
    mtype: 'GET',
    jsonReader: { repeatitems : false},
    colNames: ['Id', 'Group', 'Bytes'],
    colModel: [{name:'id', index: 'id', hidden: true},
               {name:'group', index: 'group', width: 100},
               {name:'bytes', index: 'bytes', width: 60, classes:'gc column-bytes', sortable: false, sorttype:'int', formatter:'integer'}
               ],
    grouping: true,
    groupingView: {
        groupField : ['group'],
        groupText : ['Group: ({1} items)'],
        groupOrder: 'asc',
        groupDataSorted : true
    },
    sortable: true,
    toppager: true,
    hoverrows: true,
    altrows: false,
});

Test data from server:

{"total":1,"page":1,"records":1,"rows":[{"group":"abc", "bytes":229447,"id":"7124"}]}

Another records are similar. I added 20 records and then I added next 5 on another page with group bbb.
Method addToGrid is called from another grid and with ids and entered group name to input dialog. Then I pass it to server and server returns valid data to fulefill grid. Server returns only data for the last page in my case 5 rows.

Server response:

 {"total":2,"page":2,"records":5,"rows":[{"group":"bbb", "bytes":229447,"id":"7155"},
                                         {"group":"bbb", "bytes":229447,"id":"7156"},
                                         {"group":"bbb", "bytes":229447,"id":"7157"},
                                         {"group":"bbb", "bytes":229447,"id":"7158"},
                                         {"group":"bbb", "bytes":229447,"id":"7159"}
                                        ]
 }

Body:
i also got the same problem.following line would fix the code.

$("#jqGrid").jqGrid("groupingSetup");

add this code before addJSONData function.

function addToGrid(group, ids){
  var rowNum = jQuery(myGrid).jqGrid('getGridParam', 'rowNum');
  data = jQuery.ajax({
    url: myUrl,
    data: {'group': group, 'rowNum': rowNum, 'ids': ids},
    dataType: 'json',
    complete: function(jsondata,stat){
       if(stat=="success") {
$("#myGrid").jqGrid("groupingSetup");
          var targetGrid = jQuery(myGrid);
          var myjsongrid = eval('('+jsondata.responseText+')');
          var rows = myjsongrid.rows;
          if(rows.length != 0){
               targetGrid[0].addJSONData(myjsongrid);
          }
       }
    }
 });


问:
Getting Error on PayPal PAYEE_ACCOUNT_LOCKED_OR_CLOSED
I have implemented Paypal API in my ASP.net MVC application and I have tested it using the live api key,
At the time of payment processing I am getting an error stated
reason=PAYEE_ACCOUNT_LOCKED_OR_CLOSED in the failure URL

This is the page which I am getting

答:
I got the resolution for the issue
It was the account was not completely created from paypal
Thats has been resolved and now the payment is working fine....

Thanks for your response micstr


问:
Java Signature.sign() with SHAwithECDSA produces different results on multiple runs
I am trying to sign a byte stream which does not change with a private key that does not change either, using the SHAwithECDSA. This should produce the same result, no matter how often you run the code.
However, I experience some randomness which I can't explain as the resulting output changes with every run.

Here is what I do (minimal example):

```<code>public byte[] sign() {
    Signature ecdsa = Signature.getInstance("SHA256withECDSA", "SunEC");

    // This is a hexadecimal byte sequence I need to sign
    String dataToBeSigned = "808112B43A3A381D1797BBBBBB973B99" +
                         "9737B93397AA2917B1B0B737B734B1B0" +
                         "B616B2BC3497A1AB43A3A381D1797BBB" +
                         "BBB973B999737B933979918181897981" +
                         "A17BC36B63239B4B396B6B7B93291B2B" +
                         "1B239B096B9B430991A9B22062349443" +
                         "1025687474703A2F2F7777772E77332E" +
                         "6F72672F54522F63616E6F6E6963616C" +
                         "2D6578692F4852D0E8E8E0745E5EEEEE" +
                         "EE5CEE665CDEE4CE5E646060625E6068" +
                         "5EF0DAD8CADCC646E6D0C2646A6C841A" +
                         "36BC07A00CB7DCAD662F3088A60A3D6A" +
                         "99431F81C122C2E9F1678EF531E95523" +
                         "70";

    String hexPrivKey = "B9134963F51C4414738435057F97BBF1" +
                        "010CABCB8DBDE9C5D48138396AA94B9D";
    byte[] privKey = DatatypeConverter.parseHexBinary(hexPrivKey);

    ecdsa.initSign(getPrivateKey(privKey));
    ecdsa.update(dataToBeSigned);
    byte[] signature = ecdsa.sign();

    System.out.println("Signature: " + DatatypeConverter.printHexBinary(signature));
}

public ECPrivateKey getPrivateKey(byte[] privateKeyBytes) {
    try {
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec("secp256r1"));

        ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
        ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKeyBytes), ecParameterSpec);

        ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);

        return privateKey;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException e) {
        System.out.println(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
        return null;
    }
}
</code>```

Do you have any hint why this would not result in the same signature output every time I run this code?
A similar question was raised here, but no real answer has been found yet.

Another question related to that:
I see that there is another initSign method provided by the Signature class:
initSign(PrivateKey privateKey, SecureRandom random)
Why would I wanna insert a random source/seed when creating a signature? How is the receiving side supposed to verify that signature then if the random seed is not known?

Thanks for any valuable input!
Marc

答:
The specification of the algorithm explains it:

One characteristic of DSA and ECDSA is that they need to produce, for
     each signature generation, a fresh random value (hereafter designated
     as k).  For effective security, k must be chosen randomly and
     uniformly from a set of modular integers, using a cryptographically
     secure process.  Even slight biases in that process may be turned
     into attacks on the signature schemes.

So what you're seeing is perfectly normal. Of course, the designers of the algorithms made it possible for the receiver to verify the signature, otherwise it would be pointless. That's what your test should verify.

Body:
I am trying to sign a byte stream which does not change with a private key that does not change either, using the SHAwithECDSA. This should produce the same result, no matter how often you run the code.
However, I experience some randomness which I can't explain as the resulting output changes with every run.

Here is what I do (minimal example):

public byte[] sign() {
    Signature ecdsa = Signature.getInstance("SHA256withECDSA", "SunEC");

    // This is a hexadecimal byte sequence I need to sign
    String dataToBeSigned = "808112B43A3A381D1797BBBBBB973B99" +
                         "9737B93397AA2917B1B0B737B734B1B0" +
                         "B616B2BC3497A1AB43A3A381D1797BBB" +
                         "BBB973B999737B933979918181897981" +
                         "A17BC36B63239B4B396B6B7B93291B2B" +
                         "1B239B096B9B430991A9B22062349443" +
                         "1025687474703A2F2F7777772E77332E" +
                         "6F72672F54522F63616E6F6E6963616C" +
                         "2D6578692F4852D0E8E8E0745E5EEEEE" +
                         "EE5CEE665CDEE4CE5E646060625E6068" +
                         "5EF0DAD8CADCC646E6D0C2646A6C841A" +
                         "36BC07A00CB7DCAD662F3088A60A3D6A" +
                         "99431F81C122C2E9F1678EF531E95523" +
                         "70";

    String hexPrivKey = "B9134963F51C4414738435057F97BBF1" +
                        "010CABCB8DBDE9C5D48138396AA94B9D";
    byte[] privKey = DatatypeConverter.parseHexBinary(hexPrivKey);

    ecdsa.initSign(getPrivateKey(privKey));
    ecdsa.update(dataToBeSigned);
    byte[] signature = ecdsa.sign();

    System.out.println("Signature: " + DatatypeConverter.printHexBinary(signature));
}

public ECPrivateKey getPrivateKey(byte[] privateKeyBytes) {
    try {
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC");
        parameters.init(new ECGenParameterSpec("secp256r1"));

        ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class);
        ECPrivateKeySpec ecPrivateKeySpec = new ECPrivateKeySpec(new BigInteger(privateKeyBytes), ecParameterSpec);

        ECPrivateKey privateKey = (ECPrivateKey) KeyFactory.getInstance("EC").generatePrivate(ecPrivateKeySpec);

        return privateKey;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidParameterSpecException e) {
        System.out.println(e.getClass().getSimpleName() + " occurred when trying to get private key from raw bytes", e);
        return null;
    }
}

Do you have any hint why this would not result in the same signature output every time I run this code?
A similar question was raised here, but no real answer has been found yet.

Another question related to that:
I see that there is another initSign method provided by the Signature class:
initSign(PrivateKey privateKey, SecureRandom random)
Why would I wanna insert a random source/seed when creating a signature? How is the receiving side supposed to verify that signature then if the random seed is not known?

Thanks for any valuable input!
Marc