问:
How to add an onclick method on dynamically created button using jquery
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

```<code>'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '
</code>```

but it leaves me an error saying the test function isn't defined.

here's my whole code:

```<code>$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('<tr><td>' + items[i].unitId + '</td><td>'+
             items[i].pcName +'</td><td>'+ items[i].user + '</td><td>'+
             items[i].department+'</td><td>'+items[i].location+ '</td><td>'+
             items[i].dateAssigned + '</td><td>' + items[i].status +'</td><td>' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '</td></tr>');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});
</code>```

答:
I have written jQuery to enable external function. and also you need to write call function in it, if the data is binding dynamically $(document).on("click", "#btnHistory", function(){ });

in your code you are looking for function and enabling click meted but data is blinded later and click method is not ready to trigger so if you use above  jQuery will solve issue.

$(document).ready(function(){
  $('.test').on('click',function(){
    alert('test');
    alert($(this).attr('id'));
  });
  for (var i = 0; i < 5; i++) {
    //test();
    $('#bindTable').append('

Id	Pic Name	' +
             '<button type="button"  id="btnHistory" class="btn btn-success">History</button> ' +
             ' <button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             ' <button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '

');
  }
});
function test(){
  alert ('test');
}
$(document).on("click", "#btnHistory", function(){
  test();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div id="bindTable"></div></code>```

Body:
I am fetching data from a php file using ajax. Looping through json object and creating buttons using ajax. I want to add an onclick event on that dynamically created button so that i can call a function, pass the current ID of the record to it, and then do some things to it like deleting or updating.

'<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> '

but it leaves me an error saying the test function isn't defined.

here's my whole code:

$.ajax({
    type: "POST",
    url: "../php_scripts/getUnits.php",
    success: function(data){
        var items = JSON.parse(data);

        /*var btnSomething = $("<button>")
        .attr('class', 'btn btn-danger')
        .attr('id', 'asdf')
        .html('Save');
*/

//$('#content').append(btnSomething);

        for (var i = 0; i < items.length; i++) {

            //test();
            $('#myTable').append('
' + items[i].unitId + '	'+
             items[i].pcName +'	'+ items[i].user + '	'+
             items[i].department+'	'+items[i].location+ '	'+
             items[i].dateAssigned + '	' + items[i].status +'	' +
             '<button type="button" onclick="test()" id="btnHistory" class="btn btn-success">History</button> ' +
             '<button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             '<button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '
');
        }

        function test(){
            alert('test');
        }

        /*$(document).on("click", "#btnHistory", function(){
          alert ('History clicked ');
        });*/

    }
});

Body:
I have written jQuery to enable external function. and also you need to write call function in it, if the data is binding dynamically $(document).on("click", "#btnHistory", function(){ });

in your code you are looking for function and enabling click meted but data is blinded later and click method is not ready to trigger so if you use above  jQuery will solve issue.

$(document).ready(function(){
  $('.test').on('click',function(){
    alert('test');
    alert($(this).attr('id'));
  });
  for (var i = 0; i < 5; i++) {
    //test();
    $('#bindTable').append('<table class="table table-striped"><tr><td>Id</td><td>Pic Name</td><td>' +
             '<button type="button"  id="btnHistory" class="btn btn-success">History</button> ' +
             ' <button id="btnUpdate" class="btn btn-primary">Update</button> ' +
             ' <button id="btnDelete" class="btn btn-danger">Delete</button> ' +
             '</td></tr></table>');
  }
});
function test(){
  alert ('test');
}
$(document).on("click", "#btnHistory", function(){
  test();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<div id="bindTable"></div>


来源: stackexchange

问:
Refreshing a Pivot table with VBA
I am trying to refresh automatically a pivot table with Powershell script that calls a vba code in an excel.
my powershell code is th following.

```<code>$excel = new-object -comobject excel.application
$workbook = $excel.workbooks.open("$para_temp\RapportPalettes.xlsm")
$worksheet = $workbook.worksheets.item("source")
$excel.Run('Import')
$worksheet = $workbook.worksheets.item("TCD")
$excel.Run('MAJ')
</code>```

the first macro "Import" works just fine. But the second "MAJ" that refreshes the Pivot table with the new data in source doesn't

I tried first this macro in maj :

```<code>Sub maj()

Dim pt As PivotTable

    Set pt = ActiveSheet.PivotTables("TCD")

    pt.RefreshTable

End Sub
</code>```

I don't get any error but my pivote table isn't refreshed and i have to do it manually.

Then I tried this one to change the pivot table's source of data :

```<code>Sub MAJ()

Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache

'Determine the data range you want to pivot
  Set sht = ThisWorkbook.Worksheets("Source")
  SrcData = sht.Name & "!" & Range("A1:Z10000").Address(ReferenceStyle:=xlR1C1)

'Create New Pivot Cache from Source Data
  Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Change which Pivot Cache the Pivot Table is referring to
  Worksheets("TCD").Activate
  ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)

End Sub
</code>```

but i have an 438 error in the VBA : object doesn't support this property or method for this line

```<code>ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)
</code>```

could you please Help ?

EDIT :

as you can see, I do have a worksheet and a pivot table named TCD.

EDIT :
In fact the macro is working, i tested it by creating a button that calls it.
It doesn't work when i call it with powershell

答:
I finally found the problem which was a bit stupid. In fact I was refreshing the Pivot Table but I wasn't saving the changes.

This is the macro I finally used and I used the same powershell script:

```<code>Sub Test()
Application.DisplayAlerts = False
Dim TCD As PivotTable
     For Each TCD In Worksheets("TCD").PivotTables
          TCD.RefreshTable
     Next
     ThisWorkbook.Save

     Application.DisplayAlerts = False
End Sub
</code>```

Thanks for all

ContentLicense: CC BY-SA 3.0

Title: Refreshing a Pivot table with VBA

Body:
I am trying to refresh automatically a pivot table with Powershell script that calls a vba code in an excel.
my powershell code is th following.

$excel = new-object -comobject excel.application
$workbook = $excel.workbooks.open("$para_temp\RapportPalettes.xlsm")
$worksheet = $workbook.worksheets.item("source")
$excel.Run('Import')
$worksheet = $workbook.worksheets.item("TCD")
$excel.Run('MAJ')

the first macro "Import" works just fine. But the second "MAJ" that refreshes the Pivot table with the new data in source doesn't

I tried first this macro in maj :

Sub maj()

Dim pt As PivotTable

    Set pt = ActiveSheet.PivotTables("TCD")

    pt.RefreshTable

End Sub

I don't get any error but my pivote table isn't refreshed and i have to do it manually.

Then I tried this one to change the pivot table's source of data :

Sub MAJ()

Dim sht As Worksheet
Dim SrcData As String
Dim pvtCache As PivotCache

'Determine the data range you want to pivot
  Set sht = ThisWorkbook.Worksheets("Source")
  SrcData = sht.Name & "!" & Range("A1:Z10000").Address(ReferenceStyle:=xlR1C1)

'Create New Pivot Cache from Source Data
  Set pvtCache = ActiveWorkbook.PivotCaches.Create( _
    SourceType:=xlDatabase, _
    SourceData:=SrcData)

'Change which Pivot Cache the Pivot Table is referring to
  Worksheets("TCD").Activate
  ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)

End Sub

but i have an 438 error in the VBA : object doesn't support this property or method for this line

ActiveSheet.PivotTables("TCD").ChangePivotCach (pvtCache)

could you please Help ?

EDIT :

as you can see, I do have a worksheet and a pivot table named TCD.

EDIT :
In fact the macro is working, i tested it by creating a button that calls it.
It doesn't work when i call it with powershell

Body:
I finally found the problem which was a bit stupid. In fact I was refreshing the Pivot Table but I wasn't saving the changes.

This is the macro I finally used and I used the same powershell script:

Sub Test()
Application.DisplayAlerts = False
Dim TCD As PivotTable
     For Each TCD In Worksheets("TCD").PivotTables
          TCD.RefreshTable
     Next
     ThisWorkbook.Save

     Application.DisplayAlerts = False
End Sub

Thanks for all

ContentLicense: CC BY-SA 4.0


问:
How to omit module prefix?
I am very new to python, I have a simple question.

For example

If I do

```<code>import A
</code>```

then I can use A.b().
I am wondering, how to omit A in A.b()?

答:
If you want to use b from module A:

```<code>from A import b
</code>```

If you want to rename it:

```<code>from A import b as my_b
</code>```

If you need several objects:

```<code>from A import b, c, d
</code>```

If you need everything:

```<code>from A import *
</code>```

About the import * option, please do read this post.
It's rather short, but tl;dr: do not import everything from a module by from A import *.
If you really need everything from the module, or a very big part of its content, prefer the normal import, possibly with renaming:

```<code>import numpy as np
import tkinter as tk
</code>```

Title: How to omit module prefix?

Body:
I am very new to python, I have a simple question.

For example

If I do

import A

then I can use A.b().
I am wondering, how to omit A in A.b()?

Body:
If you want to use b from module A:

from A import b

If you want to rename it:

from A import b as my_b

If you need several objects:

from A import b, c, d

If you need everything:

from A import *

About the import * option, please do read this post.
It's rather short, but tl;dr: do not import everything from a module by from A import *.
If you really need everything from the module, or a very big part of its content, prefer the normal import, possibly with renaming:

import numpy as np
import tkinter as tk


问:
How come my button appearance only changes when I hover over it after opening a new tab and coming back?
I press a button which generates a pdf for me through the jsPDF library. The problem is that the tab opens so fast I guess it messes with the visual effect of removeClass (when I come back to the page in Safari the button only visually lights up if I hover over it). The class I am removing is Bootstrap's disabled class. pdf.save is what is opening the new tab with my generated pdf file.</p>

```<code>pdf.save('test.pdf');
$('#validate-codes-button').removeClass('disabled');
</code>```

答:
You can try it like this.

If you click the generate button you can trigger the validate button to disabled.

```<code>$("#generateBtn").on("click", function(){
   $('#validate-codes-button').removeClass('disabled');
</code>```

});

Body:
I press a button which generates a pdf for me through the jsPDF library. The problem is that the tab opens so fast I guess it messes with the visual effect of removeClass (when I come back to the page in Safari the button only visually lights up if I hover over it). The class I am removing is Bootstrap's disabled class. pdf.save is what is opening the new tab with my generated pdf file.

pdf.save('test.pdf');
$('#validate-codes-button').removeClass('disabled');

Body:
You can try it like this.

If you click the generate button you can trigger the validate button to disabled.

$("#generateBtn").on("click", function(){
   $('#validate-codes-button').removeClass('disabled');

});


问:
Change ?selectableItemBackgroundBorderless ripple color
I'm trying to use ?selectableItemBackgroundBorderless to create borderless ripple for a LinearLayout, it works fine but is not clearly visible.

How can I change the default color for ?selectableItemBackgroundBorderless to make the ripple effect visible?

I've tried applying ThemeOverlay.AppCompat.Dark theme to the parent layout but it doesn't help.

答:
Using the attribute foreground instead of background works well for me:

```<code><Button
...
android:foreground="?android:attr/selectableItemBackground"
android:backgroundTint="@color/blue"
android:textColor="@color/white"
.../>
</code>```

Body:
Using the attribute foreground instead of background works well for me:

<Button
...
android:foreground="?android:attr/selectableItemBackground"
android:backgroundTint="@color/blue"
android:textColor="@color/white"
.../>


问:
Rename List item when there is the same string multiple time
I have List of names like:

```<code>var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};
</code>```

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

```<code>Allan
Michael
Jhon
Smith
George
Jhon2
</code>```

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

答:
Another possibility:</p>

```<code>var groups = list.Select((name, index) => new { name, index }).GroupBy(s => s.name).ToList();
foreach (var group in groups.Where(g => g.Count() > 1))
{
   foreach (var entry in group.Skip(1).Select((g, i) => new { g, i }))
   {
      list[entry.g.index] = list[entry.g.index] + entry.i;
   }
}
</code>```

Body:
I have List of names like:

var list = new List<string> {"Allan", "Michael", "Jhon", "Smith", "George", "Jhon"};

and a combobox which itemssource is my list. As you can see in the list there is Jhon 2 times, what I want is when I put those name into combobox add "2" to second Jhon. I mean when I open the combobox names in it shoud look like:

Allan
Michael
Jhon
Smith
George
Jhon2

I have tired linq to do that but I'm quite new to c#/linq. Could someone show me simple way to do that?

Body:
Another possibility:

var groups = list.Select((name, index) => new { name, index }).GroupBy(s => s.name).ToList();
foreach (var group in groups.Where(g => g.Count() > 1))
{
   foreach (var entry in group.Skip(1).Select((g, i) => new { g, i }))
   {
      list[entry.g.index] = list[entry.g.index] + entry.i;
   }
}


问:
Finding Class Elements in a List of Classes
I am trying to use the "List.Find" method to find a match with an element in my class.  Here is an example...

```<code>class MyClass
{
    String item1;
    String item2;
}

List<MyClass> myClassList = new List<MyClass>();

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????
</code>```

Anyway, I hope that explains a bit better.  I am confused about the last part, so my question is: How can I use List.Find to find matches of an element in a list of classes.

Thanks and please let me know if I'm not being clear.

答:
Your example is almost there. You should probably be using the FindAll method:

```<code>List<MyClass> results = myClassList.FindAll(x => x.item1 == "abc");
</code>```

Or, if you prefer your results to be typed as IEnumerable<T> rather than List<T>, you can use LINQ's Where method:

```<code>IEnumerable<MyClass> results = myClassList.Where(x => x.item1 == "abc");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use the "List.Find" method to find a match with an element in my class.  Here is an example...

class MyClass
{
    String item1;
    String item2;
}

List<MyClass> myClassList = new List<MyClass>();

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????

Anyway, I hope that explains a bit better.  I am confused about the last part, so my question is: How can I use List.Find to find matches of an element in a list of classes.

Thanks and please let me know if I'm not being clear.

Body:
Your example is almost there. You should probably be using the FindAll method:

List<MyClass> results = myClassList.FindAll(x => x.item1 == "abc");

Or, if you prefer your results to be typed as IEnumerable<T> rather than List<T>, you can use LINQ's Where method:

IEnumerable<MyClass> results = myClassList.Where(x => x.item1 == "abc");


问:
Uncaught PDOException: SQLSTATE[HY093] with UPDATE
I'm trying to create a function to change a users password:

```<code>    public function ChangePassword($password)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->execute();
        return true;
    }
</code>```

but it shows me the "Uncaught PDOException: SQLSTATE[HY093]". When I use

```<code>$query = $this->db->prepare("INSERT INTO users(password) VALUES (:password)");
</code>```

instead of

```<code>$query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
</code>```

it works, means I get an additional row with a password entry. I didn't find a documentation showing the proper use of UPDATE.

答:
I believe the current logged in user's ID is stored in a session when the user login.

Therefore this is all you need.

I believe the current logged in user's ID is stored in a session when the user login.

Therefore this is all you need.

```<code> <?php
function ChangePassword($password)
{

    $hash = password_hash($password, PASSWORD_BCRYPT,['cost' => 10]);

    $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id")->execute(array(
        ":password" => $hash,":user_id" => $_SESSION['userid']));
    return true;
}
?>
</code>```

Body:
I'm trying to create a function to change a users password:

    public function ChangePassword($password)
    {
        $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");
        $hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 10]);
        $query->bindParam("password", $hash, PDO::PARAM_STR);
        $query->execute();
        return true;
    }

but it shows me the "Uncaught PDOException: SQLSTATE[HY093]". When I use

$query = $this->db->prepare("INSERT INTO users(password) VALUES (:password)");

instead of

$query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id");

it works, means I get an additional row with a password entry. I didn't find a documentation showing the proper use of UPDATE.

Body:
I believe the current logged in user's ID is stored in a session when the user login.

Therefore this is all you need.

I believe the current logged in user's ID is stored in a session when the user login.

Therefore this is all you need.

 <?php
function ChangePassword($password)
{

    $hash = password_hash($password, PASSWORD_BCRYPT,['cost' => 10]);

    $query = $this->db->prepare("UPDATE users SET password = :password WHERE id=:user_id")->execute(array(
        ":password" => $hash,":user_id" => $_SESSION['userid']));
    return true;
}
?>


问:
How to count an hourly average number of persons using Hive?
I have this data in a table my_table:

```<code>person_id         datetime
1                 2017-03-02 18:06:20
1                 2017-03-02 18:05:10
1                 2017-04-01 18:04:09
1                 2017-03-02 19:06:50
1                 2017-04-01 19:07:22
2                 2017-03-03 18:09:15
2                 2017-05-03 19:07:05
2                 2017-05-03 20:19:08
</code>```

I need to count the number of persons (non-unique) per hour. The problem is that I should get averaged counts (averaged over days).

Imagine that today there are 10 visitors between 18:00 and 19:00, while yesterday there were 5 visitors in the same timeframe. So, what is the average number of visitors over these two days? (10 + 5)/2 = 15 / 2 = 7.5

I expect this result:

```<code>person_id   HOUR   HOURLY_AVG_COUNT
1           18     1.5
1           19     1
1           20     0
2           18     1
2           19     1
2           20     1
</code>```

I wrote the following query in Hive, but it calculates total number of persons per hour over all days:

```<code>SELECT person_id, HOUR(datetime), count(*)
FROM my_table
GROUP BY person_id, HOUR(datetime)
ORDER BY person_id
</code>```

答:
```<code>select      person_id
           ,hour
           ,avg (hourly_cnt)    as hourly_avg_count

from       (select      person_id
                       ,hour (datetime)     as hour
                       ,count(*)            as hourly_cnt

            from        my_table

            group by    person_id
                       ,hour (datetime)
                       ,date (datetime)
            ) t

group by    person_id
           ,hour

order by    person_id
           ,hour
;
</code>```

<hr>

```<code>+-----------+------+------------------+
| person_id | hour | hourly_avg_count |
+-----------+------+------------------+
|         1 |   18 | 1.5              |
|         1 |   19 | 1                |
|         2 |   18 | 1                |
|         2 |   19 | 1                |
|         2 |   20 | 1                |
+-----------+------+------------------+
</code>```

Body:
I have this data in a table my_table:

person_id         datetime
1                 2017-03-02 18:06:20
1                 2017-03-02 18:05:10
1                 2017-04-01 18:04:09
1                 2017-03-02 19:06:50
1                 2017-04-01 19:07:22
2                 2017-03-03 18:09:15
2                 2017-05-03 19:07:05
2                 2017-05-03 20:19:08

I need to count the number of persons (non-unique) per hour. The problem is that I should get averaged counts (averaged over days).

Imagine that today there are 10 visitors between 18:00 and 19:00, while yesterday there were 5 visitors in the same timeframe. So, what is the average number of visitors over these two days? (10 + 5)/2 = 15 / 2 = 7.5

I expect this result:

person_id   HOUR   HOURLY_AVG_COUNT
1           18     1.5
1           19     1
1           20     0
2           18     1
2           19     1
2           20     1

I wrote the following query in Hive, but it calculates total number of persons per hour over all days:

SELECT person_id, HOUR(datetime), count(*)
FROM my_table
GROUP BY person_id, HOUR(datetime)
ORDER BY person_id

Body:
select      person_id
           ,hour
           ,avg (hourly_cnt)    as hourly_avg_count

from       (select      person_id
                       ,hour (datetime)     as hour
                       ,count(*)            as hourly_cnt

            from        my_table

            group by    person_id
                       ,hour (datetime)
                       ,date (datetime)
            ) t

group by    person_id
           ,hour

order by    person_id
           ,hour
;

+-----------+------+------------------+
| person_id | hour | hourly_avg_count |
+-----------+------+------------------+
|         1 |   18 | 1.5              |
|         1 |   19 | 1                |
|         2 |   18 | 1                |
|         2 |   19 | 1                |
|         2 |   20 | 1                |
+-----------+------+------------------+


问:
how to install python package on azure hdinsight pyspark3 kernel?
I would like to install python 3.5 packages so they would be available in Jupyter notebook with pyspark3 kernel.

I've tried to run the following script action:

#!/bin/bash
source /usr/bin/anaconda/envs/py35/bin/activate py35
sudo /usr/bin/anaconda/envs/py35/bin/conda install -y keras tensorflow theano gensim

but the packages get installed on python 2.7 and not in 3.5

答:
According to the help information of the command conda help install, there is a parameter -n ENVIRONMENT to do the package installation on a specified environment like envs/py35, the explaination as below.

```<code>$ conda help install
.......
-n ENVIRONMENT, --name ENVIRONMENT
                    Name of environment (in
                    /home/sshuser/.conda/envs:/usr/bin/anaconda/envs).
</code>```

So you can install these packages you want via the command as below.

```<code>sudo /usr/bin/anaconda/bin/conda install -y keras tensorflow theano gensim -n py35
</code>```

Hope it helps.

Body:
According to the help information of the command conda help install, there is a parameter -n ENVIRONMENT to do the package installation on a specified environment like envs/py35, the explaination as below.

$ conda help install
.......
-n ENVIRONMENT, --name ENVIRONMENT
                    Name of environment (in
                    /home/sshuser/.conda/envs:/usr/bin/anaconda/envs).

So you can install these packages you want via the command as below.

sudo /usr/bin/anaconda/bin/conda install -y keras tensorflow theano gensim -n py35

Hope it helps.


问:
Can't send post request with cUrl when reading data from file
Hi I have a problem with sending using post command a jSon file.
I’m using curl in version 7.54.0 on windows.
I tried to execute command :

```<code>E:\Pobrane Na Big Data\cURL\curl-7.54.0-win64-mingw\bin>curl -v -X POST
http://my.host.ip: 8083/api/kpi -H "content-type: application/json" -d
@R.txt
</code>```

And I get response:

```<code>Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying my.host.ip...
* TCP_NODELAY set
* Connected to my.host.ip (my.host.ip: 8083) port 8083 (#0)
> POST /api/kpi HTTP/1.1
> Host: my.host.ip: 8083
> User-Agent: curl/7.54.0
> Accept: */*
> content-type: application/json
> Content-Length: 1398862
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: application/json; charset=utf-8
< Expires: -1
< Server: Microsoft-IIS/8.5
< X-AspNet-Version: 4.0.30319
< X-Powered-By: ASP.NET
< Date: Wed, 05 Jul 2017 09:26:11 GMT
< Content-Length: 193
<
{"StatusCode":400,"StatusDescription":"System.NullReferenceException: Object ref
erence not set to an instance of an object.\r\n   at KPI.WebApi.Controllers.KpiC
ontroller.<Post>d__2.MoveNext()"}* Connection #0 to host 10.23.2.124 left intact
</code>```

What I would like to add,  is that when I’m tried to send the same file via postman there is no problem. File is successfully loaded via rest to DB.
Also when I tried to put data directly into curl command, instead of using file, it successfully loaded data to DB.
Any suggestion how to send this json file to rest with curl?

答:
You need to set your content-type to "application/json". Have you tried...

```<code>curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' URL
</code>```

So something like:

```<code>curl -H "Content-Type: application/json" -X POST -d '{"username":"abc","password":"abc"}' http://my.host.ip: 8083/api/kpi
</code>```

UPDATE

I see your file is a txt file "@R.txt" you need to provide a json file. and then

can you try this..

```<code>$ curl -vX POST  http://my.host.ip:8083/api/kpi -d @R.json \
--header "Content-Type: application/json"
</code>```

If you want to still use the text file you can try this..

```<code> $ curl -F file=@R.txt http://my.host.ip:8083/api/kpi
</code>```

OR

```<code>$ curl -X POST -d @R.txt http://my.host.ip:8083/api/kpi
</code>```

and also make sure that you give absolute path to the file.

Update 2.0

```<code>curl http://my.host.ip:8083/api/kpi -H "Content-type:application/json" -X POST -d @R.txt
</code>```

Body:
Hi I have a problem with sending using post command a jSon file.
I’m using curl in version 7.54.0 on windows.
I tried to execute command :

E:\Pobrane Na Big Data\cURL\curl-7.54.0-win64-mingw\bin>curl -v -X POST
http://my.host.ip: 8083/api/kpi -H "content-type: application/json" -d
@R.txt

And I get response:

Note: Unnecessary use of -X or --request, POST is already inferred.
*   Trying my.host.ip...
* TCP_NODELAY set
* Connected to my.host.ip (my.host.ip: 8083) port 8083 (#0)
> POST /api/kpi HTTP/1.1
> Host: my.host.ip: 8083
> User-Agent: curl/7.54.0
> Accept: */*
> content-type: application/json
> Content-Length: 1398862
> Expect: 100-continue
>
< HTTP/1.1 100 Continue
* We are completely uploaded and fine
< HTTP/1.1 200 OK
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: application/json; charset=utf-8
< Expires: -1
< Server: Microsoft-IIS/8.5
< X-AspNet-Version: 4.0.30319
< X-Powered-By: ASP.NET
< Date: Wed, 05 Jul 2017 09:26:11 GMT
< Content-Length: 193
<
{"StatusCode":400,"StatusDescription":"System.NullReferenceException: Object ref
erence not set to an instance of an object.\r\n   at KPI.WebApi.Controllers.KpiC
ontroller.<Post>d__2.MoveNext()"}* Connection #0 to host 10.23.2.124 left intact

What I would like to add,  is that when I’m tried to send the same file via postman there is no problem. File is successfully loaded via rest to DB.
Also when I tried to put data directly into curl command, instead of using file, it successfully loaded data to DB.
Any suggestion how to send this json file to rest with curl?

Body:
You need to set your content-type to "application/json". Have you tried...

curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' URL

So something like:

curl -H "Content-Type: application/json" -X POST -d '{"username":"abc","password":"abc"}' http://my.host.ip: 8083/api/kpi

UPDATE

I see your file is a txt file "@R.txt" you need to provide a json file. and then

can you try this..

$ curl -vX POST  http://my.host.ip:8083/api/kpi -d @R.json \
--header "Content-Type: application/json"

If you want to still use the text file you can try this..

 $ curl -F file=@R.txt http://my.host.ip:8083/api/kpi

OR

$ curl -X POST -d @R.txt http://my.host.ip:8083/api/kpi

and also make sure that you give absolute path to the file.

Update 2.0

curl http://my.host.ip:8083/api/kpi -H "Content-type:application/json" -X POST -d @R.txt


问:
BeginReceive in a separate thread
For some reason, I need to do BeginReceive on a separate thread, much like this example :

```<code>    public void WaitForData()
    {
        Thread t = new Thread(WaitForDataThread);
        t.Start();
    }

    public void WaitForDataThread()
    {
        try
        {
            CSocketPacket theSocPkt = new CSocketPacket();
            theSocPkt.thisSocket = m_socClient;
            m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, OnDataReceived, theSocPkt);
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }
</code>```

But I've always received error right after the BeginReceive call, the OnDataReceived is instantly raised, in that event it will call the EndReceive method, and this error is always thrown : "The I/O operation has been aborted because of either a thread exit or an application request".

But if I remove the separate-thread part (like directly call the WaitForDataThread(), without going through the WaitForData() method), everything works fine.

If you are wondering why would I need to create a separate thread, it is because I need to call the BeginReceive during an event that will be generated from a different thread from a different class. This is pretty much the same like creating a new thread like the sample above, and I need to make it work.

Is there a way that I can do this??

答:
I assume your main thread doesn't wait till the data comes, and simply exits after spawning the other thread. Finishing the main thread kills the whole application, so your WaitForData-thread dies, too.

You have to do the following:

Start the WaitForData-thread

Do whatever you want in Main thread

Wait until the WaitForData-thread finishes in Main thread (Thread.Join?)

Then exit.

Title: BeginReceive in a separate thread

Body:
For some reason, I need to do BeginReceive on a separate thread, much like this example :

    public void WaitForData()
    {
        Thread t = new Thread(WaitForDataThread);
        t.Start();
    }

    public void WaitForDataThread()
    {
        try
        {
            CSocketPacket theSocPkt = new CSocketPacket();
            theSocPkt.thisSocket = m_socClient;
            m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, OnDataReceived, theSocPkt);
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }

But I've always received error right after the BeginReceive call, the OnDataReceived is instantly raised, in that event it will call the EndReceive method, and this error is always thrown : "The I/O operation has been aborted because of either a thread exit or an application request".

But if I remove the separate-thread part (like directly call the WaitForDataThread(), without going through the WaitForData() method), everything works fine.

If you are wondering why would I need to create a separate thread, it is because I need to call the BeginReceive during an event that will be generated from a different thread from a different class. This is pretty much the same like creating a new thread like the sample above, and I need to make it work.

Is there a way that I can do this??


问:
openwhisk cluster setup and load balancing
I am able to run openwhisk in my local dev machine. I like to extend this to production environment. Is there any concept of openwhisk cluster?. I am not able to find good documentation on this. How auto-load balancing is achieved, etcc..</p>

答:
Openwhisk will use ansible to deploy the openwhisk
I followed the follwoing way for my distributed setup

First ensure ssh passwrod less connectivity to all the servers

git clone https://github.com/apache/incubator-openwhisk.git

Add the remote_user and private_key_file values to the defaults section of

the ansible.cfg file. The remote_user value sets the default ssh user. The
private_key_file is required when using a private key that is not in the
default ~/.ssh folder
[defaults]
remote_user = ubuntu
private_key_file=/path/to/file.pem

Go to tools/ubuntu-setup run all.sh to install all the required softwares.

Now modify the inventory files(hosts) for your first node. this can become your bootstrapper VM

Check if you are able to ping the hosts : ansible all -i environments/distributed/hosts -m ping

if ping is fine run the next commad to generate the config files: ansible-playbook -i environments/distributed/hosts setup.yml

For installing the pre requisites: ansible-playbook -i environments/distributed prereq_build.yml

Deploy registry: ansible-playbook -i environments/distributed registry.yml

Go to openwhisk home run the following command to build the Openwhisk
./gradlew distDocker -PdockerHost=:4243 -PdockerRegistry=:5000

Once the build is successful run the following commands from the ansible folder

ansible-playbook -i environments/distributed/hosts couchdb.yml
ansible-playbook -i environments/distributed/hosts initdb.yml
ansible-playbook -i environments/distributed/hosts wipe.yml
ansible-playbook -i environments/distributed/hosts openwhisk.yml
ansible-playbook -i environments/distributed/hosts postdeploy.yml

Now edit the host file for other hosts and repeat the steps 7-8 and 12

this will create the setup in all the nodes. once done, you can use a node balancer to load balance on that. for sync between db instances i m using couchdb continuous replication


问:
How can I merge array's items?
I have an array like this:

```<code>$arr = array ( [0] => array("red","green"),
               [1] => array("blue","yellow")
             );
</code>```

And this is expected result:

```<code>Array ( [0] => red [1] => green [2] => blue [3] => yellow )
</code>```

See? I want to merge all items of $arr (which are also array themselves). How can I do that?

I can do a loop on it and then use array_merge() every time like this:

```<code>$res = [];
foreach ( $arr as $item ) {
    $res = array_merge($res, $item);
}
</code>```

It works as well. But I guess I can write it better. Any idea?

答:
You declare array in wrong way:

```<code>$arr = array ( 0 => array("red","green"),
               1 => array("blue","yellow")
             );
</code>```

The error reported by PHP says it clearly:

```<code>Fatal error: Illegal offset type in /in/Hhfqa on line 3
</code>```

Line 3 in your example is exactly line of first array element.

Please check http://php.net/manual/en/language.types.array.php

Title: How can I merge array's items?

Body:
I have an array like this:

$arr = array ( [0] => array("red","green"),
               [1] => array("blue","yellow")
             );

And this is expected result:

Array ( [0] => red [1] => green [2] => blue [3] => yellow )

See? I want to merge all items of $arr (which are also array themselves). How can I do that?

I can do a loop on it and then use array_merge() every time like this:

$res = [];
foreach ( $arr as $item ) {
    $res = array_merge($res, $item);
}

It works as well. But I guess I can write it better. Any idea?

Body:
You declare array in wrong way:

$arr = array ( 0 => array("red","green"),
               1 => array("blue","yellow")
             );

The error reported by PHP says it clearly:

Fatal error: Illegal offset type in /in/Hhfqa on line 3

Line 3 in your example is exactly line of first array element.

Please check http://php.net/manual/en/language.types.array.php


问:
node js event loop and polling
In the case where I have an http request handler in node js which performs some heavy synchronous code, the event loop isn't free to poll for incoming requests. But these requests are not lost anywhere and they are stored in some buffer internally, until node is free to poll. When it polls it executes them one at a time anyway. So I'm a little bit confused why it is bad to perform heavy synchronous code in request handlers. Thanks. </p>

答: As far as incoming TCP connections go, there is a backlog limit, which by default is usually 511, but could be further limited by your OS. Any connections that arrive after this limit is reached are rejected.</p>

Title: node js event loop and polling


问:
Dynemically timezone is not working in laravel
I have set dynamic time zone in my app but it's showing wrong result. Here is my code

```<code>    $timezone = [
        'asia_calcutta_time' => 'Asia/Calcutta',
        'europe_madrid_time' => 'Europe/Madrid',
        'us_eastern_time' => 'US/Eastern'
    ];
    foreach ($timezone as $timeKey => $timeValue) {
        \Config::set('app.timezone', $timeValue);
        echo $timeValue . "<br>Seted time zone => ";
        echo \Config::get('app.timezone') . "<br>";

        print_r(new \DateTime('now'));
        print_r("<br>");
    }
</code>```

My output

```<code>Asia/Calcutta
Seted time zone => Asia/Calcutta
DateTime Object ( [date] => 2017-07-05 14:51:41.000000 [timezone_type] => 3 [timezone] => Asia/Calcutta )
Europe/Madrid
Seted time zone => Europe/Madrid
DateTime Object ( [date] => 2017-07-05 14:51:41.000000 [timezone_type] => 3 [timezone] => Asia/Calcutta )
US/Eastern
Seted time zone => US/Eastern
DateTime Object ( [date] => 2017-07-05 14:51:41.000000 [timezone_type] => 3 [timezone] => Asia/Calcutta )
</code>```

Here i have set timezone using \Config::set('app.timezone', $timeValue); and after when i get timezone using \Config::get('app.timezone'); then it's show perfect but when i print datetime object then it's show different timezone so how can i solve this problem . i have also try after clear cache, clear compiled, clear config, clear route, clear view but it's not showing proper result

答:
I personally have encountered issues with using Config::set() sometimes ago. The first time the function is called is the last time it worked. You can see a ref here: Way to use Config::set() twice in a function

You can have it as this using new Instance of DateTimeZone in DateTime instead of using Config::set():

```<code>foreach ($timezone as $timeKey => $timeValue) {
    echo $timeValue . "<br>Seted time zone => ".$timeValue;
    print_r(new \DateTime('now', new \DateTimeZone($timeValue)));
    print_r("<br>");
}
</code>```

Body:
I have set dynamic time zone in my app but it's showing wrong result. Here is my code

    $timezone = [
        'asia_calcutta_time' => 'Asia/Calcutta',
        'europe_madrid_time' => 'Europe/Madrid',
        'us_eastern_time' => 'US/Eastern'
    ];
    foreach ($timezone as $timeKey => $timeValue) {
        \Config::set('app.timezone', $timeValue);
        echo $timeValue . "
Seted time zone => ";
        echo \Config::get('app.timezone') . "
";

        print_r(new \DateTime('now'));
        print_r("
");
    }

My output

Asia/Calcutta
Seted time zone => Asia/Calcutta
DateTime Object ( [date] => 2017-07-05 14:51:41.000000 [timezone_type] => 3 [timezone] => Asia/Calcutta )
Europe/Madrid
Seted time zone => Europe/Madrid
DateTime Object ( [date] => 2017-07-05 14:51:41.000000 [timezone_type] => 3 [timezone] => Asia/Calcutta )
US/Eastern
Seted time zone => US/Eastern
DateTime Object ( [date] => 2017-07-05 14:51:41.000000 [timezone_type] => 3 [timezone] => Asia/Calcutta )

Here i have set timezone using \Config::set('app.timezone', $timeValue); and after when i get timezone using \Config::get('app.timezone'); then it's show perfect but when i print datetime object then it's show different timezone so how can i solve this problem . i have also try after clear cache, clear compiled, clear config, clear route, clear view but it's not showing proper result

Body:
I personally have encountered issues with using Config::set() sometimes ago. The first time the function is called is the last time it worked. You can see a ref here: Way to use Config::set() twice in a function

You can have it as this using new Instance of DateTimeZone in DateTime instead of using Config::set():

foreach ($timezone as $timeKey => $timeValue) {
    echo $timeValue . "<br>Seted time zone => ".$timeValue;
    print_r(new \DateTime('now', new \DateTimeZone($timeValue)));
    print_r("<br>");
}


问:
Can I change my android application style at runtime?
I want to change the manifest style when the user chooses a setting in the preferences file or settings. I have a setting in my apk which includes a list of preferences with three entries {Style_1, Style_2, Style_3}. I want to change the style color, like primaryColor, when the user clicks a style. How can I do this?

答:
Create Two Style </p>

```<code> setTheme(darkTheme ? R.style.AppThemeDark : R.style.AppThemeLight);

<style name="AppThemeDark">
            <item name="main_background">@drawable/background_dark</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="button_light">@color/button_dark</item>
    </style>

<style name="AppThemeLight">
        <item name="main_background">@drawable/background_light</item>
        <item name="colorPrimaryDark">@color/colorPrimaryLight</item>
        <item name="button_light">@color/button_light</item>
</style>
</code>```

Body:
Create Two Style

 setTheme(darkTheme ? R.style.AppThemeDark : R.style.AppThemeLight);

<style name="AppThemeDark">
            <item name="main_background">@drawable/background_dark</item>
            <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
            <item name="button_light">@color/button_dark</item>
    </style>

<style name="AppThemeLight">
        <item name="main_background">@drawable/background_light</item>
        <item name="colorPrimaryDark">@color/colorPrimaryLight</item>
        <item name="button_light">@color/button_light</item>
</style>


问:
How to sum up a value without remove duplicated row in pandas?
I have one dataframe:

```<code>   a     b     c     d    f
0  ai    Y     5     3    w
1  ai    Y     5     3    r
2  ai    Y     5     2    t
3  ai    Y     5     3    o
</code>```

i wish my output is:

```<code>   a     b     c     d    f     e
0  ai    Y     5     3    w     5
1  ai    Y     5     3    r     5
2  ai    Y     5     2    t     5
3  ai    Y     5     3    o     5
</code>```

the column e is sum of the unique value in column d(mean the unique value is 2 and 3), anyone can share me the idea of the code?

this is my code:

```<code> df.groupby(['a','b','c'])['d'].transform('max')
</code>```

答:
Sum the unique values.</p>

```<code>In [280]: df['e'] = df.groupby(['a','b','c'])['d'].transform(lambda x: np.unique(x).sum())

In [281]: df
Out[281]:
    a  b  c  d  e
0  ai  Y  5  3  5
1  ai  Y  5  3  5
2  ai  Y  5  2  5
3  ai  Y  5  3  5
</code>```

Body:
I have one dataframe:

   a     b     c     d    f
0  ai    Y     5     3    w
1  ai    Y     5     3    r
2  ai    Y     5     2    t
3  ai    Y     5     3    o

i wish my output is:

   a     b     c     d    f     e
0  ai    Y     5     3    w     5
1  ai    Y     5     3    r     5
2  ai    Y     5     2    t     5
3  ai    Y     5     3    o     5

the column e is sum of the unique value in column d(mean the unique value is 2 and 3), anyone can share me the idea of the code?

this is my code:

 df.groupby(['a','b','c'])['d'].transform('max')

Body:
Sum the unique values.

In [280]: df['e'] = df.groupby(['a','b','c'])['d'].transform(lambda x: np.unique(x).sum())

In [281]: df
Out[281]:
    a  b  c  d  e
0  ai  Y  5  3  5
1  ai  Y  5  3  5
2  ai  Y  5  2  5
3  ai  Y  5  3  5


问:
REUSE_ALV_FIELDCATALOG_MERGE for generating ALV hierarchial list?
When I execute this code some error occurs. Can REUSE_ALV_FIELDCATALOG_MERGE function module be used to generate alv hierarchial reports in ABAP? And are there any tips for the simplest fieldcatalog merging?

```<code>REPORT ZSAMPLE_ALV_HIERACHIAL.

DATA : IT_VBAK LIKE TABLE OF VBAK,
       WA_VBAK LIKE VBAK,

       IT_VBAP LIKE TABLE OF VBAP,
       WA_VBAP LIKE VBAP,

       IT_MARA LIKE TABLE OF MARA,
       WA_MARA LIKE MARA,

       IT_FCAT TYPE SLIS_T_FIELDCAT_ALV,
       WA_FCAT TYPE SLIS_FIELDCAT_ALV,

       IT_FCAT1 TYPE SLIS_T_FIELDCAT_ALV,
       WA_FCAT1 TYPE SLIS_FIELDCAT_ALV,

       IT_EVENT TYPE SLIS_T_EVENT,
       WA_EVENT TYPE SLIS_ALV_EVENT,

       V_VBELN TYPE VBAK-VBELN,

       GS_KEYINFO TYPE SLIS_KEYINFO_ALV,

       WA_LAYOUT TYPE SLIS_LAYOUT_ALV,
       WA_LAYOUT1 TYPE SLIS_LAYOUT_ALV.

WA_LAYOUT-ZEBRA = 'X'.
WA_LAYOUT-COLWIDTH_OPTIMIZE = 'C510'.

WA_LAYOUT-ZEBRA = 'X'.
WA_LAYOUT-COLWIDTH_OPTIMIZE = 'C510'.

SELECT-OPTIONS S_VBELN FOR V_VBELN.

START-OF-SELECTION.
  PERFORM READ_DATA.
  PERFORM KEY_INFO.
  PERFORM FILL_FIELD_CATALOG USING 'IT_VBAK' 'VBAK'.
  PERFORM FILL_FIELD_CATALOG USING 'IT_VBAP' 'VBAP'.
  PERFORM DISPLAY_HIERACIAL_ALV.

*&---------------------------------------------------------------------*
*&      Form  READ_DATA
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM READ_DATA .

  SELECT * FROM VBAK INTO TABLE IT_VBAK WHERE VBELN IN S_VBELN.

  IF NOT IT_VBAK IS INITIAL .

    SELECT * FROM VBAP INTO TABLE IT_VBAP FOR ALL ENTRIES IN IT_VBAK WHERE VBELN = IT_VBAK-VBELN.

  ENDIF.

ENDFORM.                    "READ_DATA

*&---------------------------------------------------------------------*
*&      Form  KEY_INFO
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM KEY_INFO .

  CLEAR GS_KEYINFO.
  GS_KEYINFO-HEADER01 = 'VBELN'.
  GS_KEYINFO-ITEM01 = 'VBELN'.
  GS_KEYINFO-HEADER02 = SPACE.
  GS_KEYINFO-ITEM02 = 'VBELP'.

ENDFORM.                    "KEY_INFO

*&---------------------------------------------------------------------*
*&      Form  FILL_FIELD_CATALOG
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
*      -->TNAM       text
*      -->C          text
*----------------------------------------------------------------------*
FORM FILL_FIELD_CATALOG  USING    TNAM TYPE C STRUCTURE TYPE C.

  CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
      I_PROGRAM_NAME     = SY-REPID
      I_INTERNAL_TABNAME = TNAM
      I_STRUCTURE_NAME   = STRUCTURE
    CHANGING
      CT_FIELDCAT        = IT_FCAT.
ENDFORM.                    "FILL_FIELD_CATALOG

*&---------------------------------------------------------------------*
*&      Form  DISPLAY_HIERACIAL_ALV
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM DISPLAY_HIERACIAL_ALV .

  CALL FUNCTION 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
    EXPORTING
      I_CALLBACK_PROGRAM      = SY-CPROG
      IS_LAYOUT               = WA_LAYOUT
      IT_FIELDCAT             = IT_FCAT
      I_TABNAME_HEADER        = 'IT_VBAK'
      I_TABNAME_ITEM          = 'IT_VBAP'
*     I_STRUCTURE_NAME_HEADER = 'VBAK'
*     I_STRUCTURE_NAME_ITEM   = 'VBAP'
      IS_KEYINFO              = GS_KEYINFO
    TABLES
      T_OUTTAB_HEADER         = IT_VBAK
      T_OUTTAB_ITEM           = IT_VBAP.

ENDFORM.
</code>```

答:
You definitely can use it for hierarchical reports too! But you should declare your itabs another way to achieve this.

Couple of notes: with the below declaration you should check for it_vbak[], not it_vbak in read_data form, otherwise your it_vbap itab would be always empty. Also, you should pass itab to REUSE_ALV_FIELDCATALOG_MERGE only via i_internal_tabnam parameter, if it's internal table.

Finally, you code should look somewhat like this:

```<code>DATA: BEGIN OF it_vbak OCCURS 0,
        vbeln LIKE vbak-vbeln,
        expand,
      END OF it_vbak.
DATA: BEGIN OF it_vbap OCCURS 0,
        vbeln LIKE vbap-vbeln,
        posnr LIKE vbap-posnr,
        matnr LIKE vbap-matnr,
        netpr LIKE vbap-netpr,
      END OF it_vbap,

v_vbeln TYPE vbak-vbeln,
it_fcat TYPE slis_t_fieldcat_alv,
gs_keyinfo TYPE slis_keyinfo_alv,
wa_layout  TYPE slis_layout_alv.

SELECT-OPTIONS s_vbeln FOR v_vbeln.

START-OF-SELECTION.
  PERFORM read_data.
  PERFORM key_info.
  PERFORM fill_field_catalog USING 'IT_VBAK'.
  PERFORM fill_field_catalog USING 'IT_VBAP'.
  PERFORM display_hieracial_alv.
*&---------------------------------------------------------------------*
*&      Form  READ_DATA
*&---------------------------------------------------------------------*
FORM read_data .
  SELECT * FROM vbak INTO CORRESPONDING FIELDS OF TABLE it_vbak WHERE
  vbeln IN s_vbeln.
  IF NOT it_vbak[] IS INITIAL.
    SELECT * FROM vbap INTO CORRESPONDING FIELDS OF TABLE it_vbap FOR
ALL ENTRIES IN it_vbak
    WHERE vbeln = it_vbak-vbeln.
  ENDIF.
ENDFORM.                    "READ_DATA
*&---------------------------------------------------------------------*
*&      Form  KEY_INFO
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM key_info .
  CLEAR gs_keyinfo.
  gs_keyinfo-header01 = 'VBELN'.
  gs_keyinfo-item01 = 'VBELN'.
ENDFORM.                    "KEY_INFO
*&---------------------------------------------------------------------*
*&      Form  FILL_FIELD_CATALOG
*&---------------------------------------------------------------------*
FORM fill_field_catalog  USING tnam TYPE c.
  CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
      i_program_name     = sy-repid
      i_internal_tabname = tnam
      i_inclname         = sy-repid
    CHANGING
      ct_fieldcat        = it_fcat.
ENDFORM.                    "FILL_FIELD_CATALOG
*&---------------------------------------------------------------------*
*&      Form  DISPLAY_HIERACIAL_ALV
*&---------------------------------------------------------------------*
FORM display_hieracial_alv.
  wa_layout-zebra = 'X'.
  wa_layout-subtotals_text = 'SUBTOTAL TEXT'.
  wa_layout-key_hotspot = 'X'.
  wa_layout-expand_fieldname = 'EXPAND'.
  CALL FUNCTION 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
    EXPORTING
      i_callback_program      = sy-cprog
      is_layout               = wa_layout
      it_fieldcat             = it_fcat
      i_tabname_header        = 'IT_VBAK'
      i_tabname_item          = 'IT_VBAP'
      is_keyinfo              = gs_keyinfo
    TABLES
      t_outtab_header         = it_vbak
      t_outtab_item           = it_vbap.
ENDFORM.
</code>```

Body:
When I execute this code some error occurs. Can REUSE_ALV_FIELDCATALOG_MERGE function module be used to generate alv hierarchial reports in ABAP? And are there any tips for the simplest fieldcatalog merging?

REPORT ZSAMPLE_ALV_HIERACHIAL.

DATA : IT_VBAK LIKE TABLE OF VBAK,
       WA_VBAK LIKE VBAK,

       IT_VBAP LIKE TABLE OF VBAP,
       WA_VBAP LIKE VBAP,

       IT_MARA LIKE TABLE OF MARA,
       WA_MARA LIKE MARA,

       IT_FCAT TYPE SLIS_T_FIELDCAT_ALV,
       WA_FCAT TYPE SLIS_FIELDCAT_ALV,

       IT_FCAT1 TYPE SLIS_T_FIELDCAT_ALV,
       WA_FCAT1 TYPE SLIS_FIELDCAT_ALV,

       IT_EVENT TYPE SLIS_T_EVENT,
       WA_EVENT TYPE SLIS_ALV_EVENT,

       V_VBELN TYPE VBAK-VBELN,

       GS_KEYINFO TYPE SLIS_KEYINFO_ALV,

       WA_LAYOUT TYPE SLIS_LAYOUT_ALV,
       WA_LAYOUT1 TYPE SLIS_LAYOUT_ALV.

WA_LAYOUT-ZEBRA = 'X'.
WA_LAYOUT-COLWIDTH_OPTIMIZE = 'C510'.

WA_LAYOUT-ZEBRA = 'X'.
WA_LAYOUT-COLWIDTH_OPTIMIZE = 'C510'.

SELECT-OPTIONS S_VBELN FOR V_VBELN.

START-OF-SELECTION.
  PERFORM READ_DATA.
  PERFORM KEY_INFO.
  PERFORM FILL_FIELD_CATALOG USING 'IT_VBAK' 'VBAK'.
  PERFORM FILL_FIELD_CATALOG USING 'IT_VBAP' 'VBAP'.
  PERFORM DISPLAY_HIERACIAL_ALV.

*&---------------------------------------------------------------------*
*&      Form  READ_DATA
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM READ_DATA .

  SELECT * FROM VBAK INTO TABLE IT_VBAK WHERE VBELN IN S_VBELN.

  IF NOT IT_VBAK IS INITIAL .

    SELECT * FROM VBAP INTO TABLE IT_VBAP FOR ALL ENTRIES IN IT_VBAK WHERE VBELN = IT_VBAK-VBELN.

  ENDIF.

ENDFORM.                    "READ_DATA

*&---------------------------------------------------------------------*
*&      Form  KEY_INFO
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM KEY_INFO .

  CLEAR GS_KEYINFO.
  GS_KEYINFO-HEADER01 = 'VBELN'.
  GS_KEYINFO-ITEM01 = 'VBELN'.
  GS_KEYINFO-HEADER02 = SPACE.
  GS_KEYINFO-ITEM02 = 'VBELP'.

ENDFORM.                    "KEY_INFO

*&---------------------------------------------------------------------*
*&      Form  FILL_FIELD_CATALOG
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
*      -->TNAM       text
*      -->C          text
*----------------------------------------------------------------------*
FORM FILL_FIELD_CATALOG  USING    TNAM TYPE C STRUCTURE TYPE C.

  CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
      I_PROGRAM_NAME     = SY-REPID
      I_INTERNAL_TABNAME = TNAM
      I_STRUCTURE_NAME   = STRUCTURE
    CHANGING
      CT_FIELDCAT        = IT_FCAT.
ENDFORM.                    "FILL_FIELD_CATALOG

*&---------------------------------------------------------------------*
*&      Form  DISPLAY_HIERACIAL_ALV
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM DISPLAY_HIERACIAL_ALV .

  CALL FUNCTION 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
    EXPORTING
      I_CALLBACK_PROGRAM      = SY-CPROG
      IS_LAYOUT               = WA_LAYOUT
      IT_FIELDCAT             = IT_FCAT
      I_TABNAME_HEADER        = 'IT_VBAK'
      I_TABNAME_ITEM          = 'IT_VBAP'
*     I_STRUCTURE_NAME_HEADER = 'VBAK'
*     I_STRUCTURE_NAME_ITEM   = 'VBAP'
      IS_KEYINFO              = GS_KEYINFO
    TABLES
      T_OUTTAB_HEADER         = IT_VBAK
      T_OUTTAB_ITEM           = IT_VBAP.

ENDFORM.

Body:
You definitely can use it for hierarchical reports too! But you should declare your itabs another way to achieve this.

Couple of notes: with the below declaration you should check for it_vbak[], not it_vbak in read_data form, otherwise your it_vbap itab would be always empty. Also, you should pass itab to REUSE_ALV_FIELDCATALOG_MERGE only via i_internal_tabnam parameter, if it's internal table.

Finally, you code should look somewhat like this:

DATA: BEGIN OF it_vbak OCCURS 0,
        vbeln LIKE vbak-vbeln,
        expand,
      END OF it_vbak.
DATA: BEGIN OF it_vbap OCCURS 0,
        vbeln LIKE vbap-vbeln,
        posnr LIKE vbap-posnr,
        matnr LIKE vbap-matnr,
        netpr LIKE vbap-netpr,
      END OF it_vbap,

v_vbeln TYPE vbak-vbeln,
it_fcat TYPE slis_t_fieldcat_alv,
gs_keyinfo TYPE slis_keyinfo_alv,
wa_layout  TYPE slis_layout_alv.

SELECT-OPTIONS s_vbeln FOR v_vbeln.

START-OF-SELECTION.
  PERFORM read_data.
  PERFORM key_info.
  PERFORM fill_field_catalog USING 'IT_VBAK'.
  PERFORM fill_field_catalog USING 'IT_VBAP'.
  PERFORM display_hieracial_alv.
*&---------------------------------------------------------------------*
*&      Form  READ_DATA
*&---------------------------------------------------------------------*
FORM read_data .
  SELECT * FROM vbak INTO CORRESPONDING FIELDS OF TABLE it_vbak WHERE
  vbeln IN s_vbeln.
  IF NOT it_vbak[] IS INITIAL.
    SELECT * FROM vbap INTO CORRESPONDING FIELDS OF TABLE it_vbap FOR
ALL ENTRIES IN it_vbak
    WHERE vbeln = it_vbak-vbeln.
  ENDIF.
ENDFORM.                    "READ_DATA
*&---------------------------------------------------------------------*
*&      Form  KEY_INFO
*&---------------------------------------------------------------------*
*       text
*----------------------------------------------------------------------*
FORM key_info .
  CLEAR gs_keyinfo.
  gs_keyinfo-header01 = 'VBELN'.
  gs_keyinfo-item01 = 'VBELN'.
ENDFORM.                    "KEY_INFO
*&---------------------------------------------------------------------*
*&      Form  FILL_FIELD_CATALOG
*&---------------------------------------------------------------------*
FORM fill_field_catalog  USING tnam TYPE c.
  CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
      i_program_name     = sy-repid
      i_internal_tabname = tnam
      i_inclname         = sy-repid
    CHANGING
      ct_fieldcat        = it_fcat.
ENDFORM.                    "FILL_FIELD_CATALOG
*&---------------------------------------------------------------------*
*&      Form  DISPLAY_HIERACIAL_ALV
*&---------------------------------------------------------------------*
FORM display_hieracial_alv.
  wa_layout-zebra = 'X'.
  wa_layout-subtotals_text = 'SUBTOTAL TEXT'.
  wa_layout-key_hotspot = 'X'.
  wa_layout-expand_fieldname = 'EXPAND'.
  CALL FUNCTION 'REUSE_ALV_HIERSEQ_LIST_DISPLAY'
    EXPORTING
      i_callback_program      = sy-cprog
      is_layout               = wa_layout
      it_fieldcat             = it_fcat
      i_tabname_header        = 'IT_VBAK'
      i_tabname_item          = 'IT_VBAP'
      is_keyinfo              = gs_keyinfo
    TABLES
      t_outtab_header         = it_vbak
      t_outtab_item           = it_vbap.
ENDFORM.


问:
tkinter.TclError: couldn't connect to display "localhost:18.0"
I was trying to run a simulation (written in python) in the central server, and when simulation is finished, move saved figure file / saved data file to my local PC, by connecting to my local PC. Code is as following:

```<code>import matplotlib.pyplot as plt
import subprocess
import scipy.io
import os

#Save data file:
scipy.io.savemat(data_path + Filename_str, dict(A=board))

#Create / Save figure by using imshow (Heatmap)
p = plt.imshow(mean_map.T, cmap = plt.cm.gist_yarg_r, origin = 'lower',  extent = [0, phi, 0, Z], aspect='auto')
plt.savefig(figure_path + Filename_str + '-Homophily.pdf')

# Connect to my local host (arabian-knights) using ssh, and follow command.
ret = subprocess.call(['ssh', 'arabian-knights', 'mv Data/* /scratch/Data/'])
ret = subprocess.call(['ssh', 'arabian-knights', 'mv Figure/* /scratch/Figure/'])
</code>```

I run this simulation in background of server computer, after connecting to server computer from my local computer (arabian-knights). Even though I turn off connection to server computer, as simulation is running in background, it doesn't stop, and Data files are correctly moved to my local computer after simulation is done. However, Figure files (produced by matplotlib.pyplot.imshow) are not saved, showing following error messsage:

```<code>Traceback (most recent call last):
  File "./ThrHomoHeatmap-thrstep.py", line 179, in <module>
    p = plt.imshow(board.T, cmap = plt.cm.gist_yarg_r, vmin=0, vmax=n, origin = 'lower',  extent = [0, phi, 0, Z], aspect='auto')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2370, in imshow
    ax = gca()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 701, in gca
    ax =  gcf().gca(**kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 369, in gcf
    return figure()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display "localhost:18.0"
</code>```

Is there anyone who can solve this problem, to move matplotlib.pyplot figure files from server to local computer as well?

答:
Generate images without having a window appear (background)

use a non-interactive backend (see What is a backend?) such as Agg (for PNGs), PDF, SVG or PS. In your figure-generating script, just call the matplotlib.use() directive before importing pylab or pyplot:

```<code>import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('myfig')
</code>```

Note: This answer was in short mentioned in a comment. I put it here as an answer to increase visibility since it helped me and I was lucky enough that I decided to read the comments.

Body:
I was trying to run a simulation (written in python) in the central server, and when simulation is finished, move saved figure file / saved data file to my local PC, by connecting to my local PC. Code is as following:

import matplotlib.pyplot as plt
import subprocess
import scipy.io
import os

#Save data file:
scipy.io.savemat(data_path + Filename_str, dict(A=board))

#Create / Save figure by using imshow (Heatmap)
p = plt.imshow(mean_map.T, cmap = plt.cm.gist_yarg_r, origin = 'lower',  extent = [0, phi, 0, Z], aspect='auto')
plt.savefig(figure_path + Filename_str + '-Homophily.pdf')

# Connect to my local host (arabian-knights) using ssh, and follow command.
ret = subprocess.call(['ssh', 'arabian-knights', 'mv Data/* /scratch/Data/'])
ret = subprocess.call(['ssh', 'arabian-knights', 'mv Figure/* /scratch/Figure/'])

I run this simulation in background of server computer, after connecting to server computer from my local computer (arabian-knights). Even though I turn off connection to server computer, as simulation is running in background, it doesn't stop, and Data files are correctly moved to my local computer after simulation is done. However, Figure files (produced by matplotlib.pyplot.imshow) are not saved, showing following error messsage:

Traceback (most recent call last):
  File "./ThrHomoHeatmap-thrstep.py", line 179, in <module>
    p = plt.imshow(board.T, cmap = plt.cm.gist_yarg_r, vmin=0, vmax=n, origin = 'lower',  extent = [0, phi, 0, Z], aspect='auto')
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2370, in imshow
    ax = gca()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 701, in gca
    ax =  gcf().gca(**kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 369, in gcf
    return figure()
  File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 343, in figure
    **kwargs)
  File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 80, in new_figure_manager
    window = Tk.Tk()
  File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1688, in __init__
    self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display "localhost:18.0"

Is there anyone who can solve this problem, to move matplotlib.pyplot figure files from server to local computer as well?

Body:
Generate images without having a window appear (background)

use a non-interactive backend (see What is a backend?) such as Agg (for PNGs), PDF, SVG or PS. In your figure-generating script, just call the matplotlib.use() directive before importing pylab or pyplot:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('myfig')

Note: This answer was in short mentioned in a comment. I put it here as an answer to increase visibility since it helped me and I was lucky enough that I decided to read the comments.


问:
Sql Ansi to manage DateTime values
I'm developing a multi-database system.

I want the difference between two dates in seconds.

In SQL Server I got:

DATEDIFF(second,stardate,enddate)

In MySql:

TIME_TO_SEC(TIMEDIFF(stardate,enddate))

My question:

Does Sql Ansi have functions to manage DateTime values?
 i.e.: There are datetime functions generic for all databases?

答:
According to SQL:1999, date1-date0 should give you a value of type INTERVAL, a struct from which you should be able to extract YEAR, MONTH, DAY, etc.

I've never used it and I don't think it's widely supported (though I may not be up-to-date). If you're doing time arithmetic in the database layer and you want to be cross-DBMS compatible the usual solution is simply to use integer timestamps (of whatever resolution, but Unix time is common) and plain old integer arithmetic which is completely reliable cross-platform.

OwnerDisplayName: Click Ok

Title: Sql Ansi to manage DateTime values

OwnerDisplayName: bobince


问:
Async calls with new keyword 'await'
I've used async methods today, calling methods asynchronously and using the caller's callback methods.

Recently, I can across this post which talks about the new way to do this using the new await keyword. Other than saving few lines of code, what are the main advantages of this new model?

Does it offer a built in solution for when you make two different async calls but want the control to return to only one of the caller's callback, after both have completed?

What does CTP (Community Technical Preview) mean? Is this new keyword available in next version of C# and VB.NET?

答:
If you want to start a new task upon async operation completed you don't need the "await" keyword. All you need is Task.ContinueWhenAll method.

Regarding CTP - it means this is in "alpha" stage and may contain bugs and is not finalized (may change in the future. For example - "await" keyword will change to something else, or will have different syntax rules).

Title: Async calls with new keyword 'await'


问:
Elasticsearch Date Historam with first document
I am trying to write a query which will return first entry of every month but I am not able to find anything can any one please help me with it .

i tried the below query but it return number of documents in that month not the first document in that month

```<code>{
    "query" : {
        "term" : { "id" : "1" }
        },"size":0,
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "interval" : "month"
            }
        }
    }
}
</code>```

答: You should check out the top_hits aggregation.</p>

Body:
I am trying to write a query which will return first entry of every month but I am not able to find anything can any one please help me with it .

i tried the below query but it return number of documents in that month not the first document in that month

{
    "query" : {
        "term" : { "id" : "1" }
        },"size":0,
    "aggs" : {
        "sales_over_time" : {
            "date_histogram" : {
                "field" : "date",
                "interval" : "month"
            }
        }
    }
}


问:
Jmeter cookie manager does not seem to work with HTTPS login
I am trying to analyse a site using Jmeter. My plan includes a HTTPS login, for which I have included a HTTP Cookie manager in the ThreadGroup.
But still all subsequent requests are being forwarded to the login page. Seeing in the Tree View Listener, I can see that there is no cookie in any request or response.

Has anyone made Jmeter cookie manager work with HTTPS

答:
I've gotten it work on several different websites.  I assume you've verified via Tree View that the login was successful?

It could be that login is generating a unique key that was hardcoded during recording and should be removed.

Where do you have your cookie manager placed, and which option did you choose?  The manager should be at the highest level.


问:
How to set a value of a variable during a test?
Suppose I have a code in Java (or any other language) that I want to test. Let's say that I want to test how the code behaves when variable 'myVar' holds an integer value of 10 at a certain line.

One option will be to assign the value 10 to variable 'myVar' at this line. This will work fine, but it will make the code dirty. If I want to test another scenario, I'll have to fix this line. What will happen if I have a huge number of scenarios ?

I was wondering whether there is an option to hold an external file/configuration that will be loaded whenever I want to test this specific scenario without modifying the code?

答:
One of the ways is to use a Json File. Just put your value into the Json file "test.json" at location c:\testfolder with following content:

```<code>{
    "Scenario":"10"
}
</code>```

Now you can access the value using following code in C#:

```<code>StreamReader file = File.OpenText("c:\testfolder\test.json");
JsonTextReader reader = new JsonTextReader(file);
JObject jObject = (JObject)JToken.ReadFrom(reader);
int a = jObject ["Scenario"];
</code>```

You can use this variable a which contains value 10 from the Json file.

Body:
One of the ways is to use a Json File. Just put your value into the Json file "test.json" at location c:\testfolder with following content:

{
    "Scenario":"10"
}

Now you can access the value using following code in C#:

StreamReader file = File.OpenText("c:\testfolder\test.json");
JsonTextReader reader = new JsonTextReader(file);
JObject jObject = (JObject)JToken.ReadFrom(reader);
int a = jObject ["Scenario"];

You can use this variable a which contains value 10 from the Json file.


问:
gnu-make: Using individual files in a folder as dependencies and run rule on all filenames in folder
Suppose I have a file structure as follows:

```<code>code
├── configure
├── configure.in
├── Demo
│   ├── experiments
│   │   ├── 1.txt
│   │   ├── 2.txt
│   │   ├── 3.txt
│   │   ├── 4.txt
│   │   ├── 5.txt
│   │   └── 6.txt
|   |___test.cpp
</code>```

I am trying to create a rule that uses each one of the files in txt and creates the following files:

1.test
2.test
3.test
4.test
5.test

If I had the rule:

```<code>%.test: %.txt
        do something
</code>```

How do I run it on every file in experiments eg:

```<code>make *.test
</code>```

and then run them individually eg:

```<code>.\*.test?
</code>```

I really need help with this as I have thousands of files to process in this way.

答:
You can use $(wildcard):

```<code>TEST_SOURCES = $(wildcard *.txt)
TEST_OUTPUT = $(patsubst %.txt,%.test,${TEST_SOURCES})

all: ${TEST_OUTPUT}
</code>```

Body:
Suppose I have a file structure as follows:

code
├── configure
├── configure.in
├── Demo
│   ├── experiments
│   │   ├── 1.txt
│   │   ├── 2.txt
│   │   ├── 3.txt
│   │   ├── 4.txt
│   │   ├── 5.txt
│   │   └── 6.txt
|   |___test.cpp

I am trying to create a rule that uses each one of the files in txt and creates the following files:

1.test
2.test
3.test
4.test
5.test

If I had the rule:

%.test: %.txt
        do something

How do I run it on every file in experiments eg:

make *.test

and then run them individually eg:

.\*.test?

I really need help with this as I have thousands of files to process in this way.

Body:
You can use $(wildcard):

TEST_SOURCES = $(wildcard *.txt)
TEST_OUTPUT = $(patsubst %.txt,%.test,${TEST_SOURCES})

all: ${TEST_OUTPUT}


问:
Custom user data in access token with ASOS
I'm trying to impement the OpenID Connect server using AspNet.Security.OpenIdConnect.Server.

Is it possible to place some custom user data to the access token when issuing token at authorization Server and then retrieve it at Resource Server during token validation and request processing?

Example: I want to write to the access token an IP address that was used to get token by user. Then at the resource server I want to compare current user IP address and IP address from token during token validation.

Another example: I want to write user's roles to token and then retrieve them in WebApi action filter or action itself

答:
Consider simply storing the IP address as a claim:

```<code>identity.AddClaim("ip_addr", HttpContext.Connection.RemoteIpAddress.ToString(),
    OpenIdConnectConstants.Destinations.AccessToken);
</code>```

Then, in your API controller, retrieve it using:

```<code>var address = User.FindFirst("ip_addr").Value;
</code>```

Body:
Consider simply storing the IP address as a claim:

identity.AddClaim("ip_addr", HttpContext.Connection.RemoteIpAddress.ToString(),
    OpenIdConnectConstants.Destinations.AccessToken);

Then, in your API controller, retrieve it using:

var address = User.FindFirst("ip_addr").Value;


问:
Phalcon MongoDB
php7.0, Phalcon 3.2, MongoDB 3.2.14

I want to connect to MongoDB, but in Phalcon documentation only about connection via MongoClient() and working with it. I have php7.0 and MongoClient() is deprecated in it. How I can correctly use \MongoDB\Driver\Manager() with Phalcon?
In services.php I wrote this:

```<code>/**
* MongoDB connection
*/
$di->set( "mongo", function () {
       $config = $this->getConfig();

        $db_string = sprintf( 'mongodb://%s:%s/%s', $config->mongodb->host, $config->mongodb->port, $config->mongodb->database );

        if( isset( $config->mongodb->user ) AND isset( $config->mongodb->password ) ) {
            $db_string = sprintf( 'mongodb://%s:%s@%s:%s/%s',
                $config->mongodb->user,
                (string)$config->mongodb->password,
                $config->mongodb->host,
                (string)$config->mongodb->port,
                $config->mongodb->database );
       }

        try {
            return new \MongoDB\Driver\Manager( $db_string );
        } catch (MongoConnectionException $e) {
            die( 'Failed to connect to MongoDB '.$e->getMessage() );
        }
    },
    true
);
</code>```

It works. But in models there are errors. In app/models/User.php I wrote:

```<code>use Phalcon\Mvc\Collection;

class User extends Collection
{
    public function initialize()
    {
        $this->setSource('users');
    }
}
</code>```

And in controller:

```<code>class IndexController extends ControllerBase
{
    public function indexAction()
    {
        echo User::count();
    }
}
</code>```

In browser I have this:

```<code>Call to undefined method ::selectcollection()
#0 [internal function]: Phalcon\Mvc\Collection::_getGroupResultset(Array, Object(User), Object(MongoDB\Driver\Manager))
#1 /var/www/testing/app/controllers/IndexController.php(8): Phalcon\Mvc\Collection::count()
#2 [internal function]: IndexController->indexAction()
#3 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(IndexController), 'indexAction', Array)
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /var/www/testing/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}
</code>```

How I can do it correclty? :) sorry for my English, I from Russia :)

My original question is here.

答:
Use Incubator package: https://github.com/phalcon/incubator

See example of using here -
 https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Db/Adapter#mongodbclient

Title: Phalcon MongoDB

Body:
php7.0, Phalcon 3.2, MongoDB 3.2.14

I want to connect to MongoDB, but in Phalcon documentation only about connection via MongoClient() and working with it. I have php7.0 and MongoClient() is deprecated in it. How I can correctly use \MongoDB\Driver\Manager() with Phalcon?
In services.php I wrote this:

/**
* MongoDB connection
*/
$di->set( "mongo", function () {
       $config = $this->getConfig();

        $db_string = sprintf( 'mongodb://%s:%s/%s', $config->mongodb->host, $config->mongodb->port, $config->mongodb->database );

        if( isset( $config->mongodb->user ) AND isset( $config->mongodb->password ) ) {
            $db_string = sprintf( 'mongodb://%s:%s@%s:%s/%s',
                $config->mongodb->user,
                (string)$config->mongodb->password,
                $config->mongodb->host,
                (string)$config->mongodb->port,
                $config->mongodb->database );
       }

        try {
            return new \MongoDB\Driver\Manager( $db_string );
        } catch (MongoConnectionException $e) {
            die( 'Failed to connect to MongoDB '.$e->getMessage() );
        }
    },
    true
);

It works. But in models there are errors. In app/models/User.php I wrote:

use Phalcon\Mvc\Collection;

class User extends Collection
{
    public function initialize()
    {
        $this->setSource('users');
    }
}

And in controller:

class IndexController extends ControllerBase
{
    public function indexAction()
    {
        echo User::count();
    }
}

In browser I have this:

Call to undefined method ::selectcollection()
#0 [internal function]: Phalcon\Mvc\Collection::_getGroupResultset(Array, Object(User), Object(MongoDB\Driver\Manager))
#1 /var/www/testing/app/controllers/IndexController.php(8): Phalcon\Mvc\Collection::count()
#2 [internal function]: IndexController->indexAction()
#3 [internal function]: Phalcon\Dispatcher->callActionMethod(Object(IndexController), 'indexAction', Array)
#4 [internal function]: Phalcon\Dispatcher->_dispatch()
#5 [internal function]: Phalcon\Dispatcher->dispatch()
#6 /var/www/testing/public/index.php(42): Phalcon\Mvc\Application->handle()
#7 {main}

How I can do it correclty? :) sorry for my English, I from Russia :)

My original question is here.


问:
Tiles 3 List attributes not working properly
I'm facing several problems with my spring MVC project and tiles 3, and one of the main problems is with list attributes. What I'm trying to make is create a generic tiles definition using an OptionsRenderer, like in the ultimate view article (there is a mistake in the article, since the lit attribute is defined outside the definition, which is wrong). When I create some attributes with an ${options[myoptions]} expression, I always get an IllegalStateException in my template JSP because a list attribute with the name myoptions is missing, even though I defined this list attribute. My code is as follows:

tiles.xml

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">

<tiles-definitions>

    <definition name="WILDCARD:*/*" template="/WEB-INF/view/template.jsp">
        <put-attribute name="meta" value="/WEB-INF/view/${options[folder]}/meta.jsp" />
        <put-attribute name="header" value="/WEB-INF/view/${options[folder]}/header.jsp" />
        <put-attribute name="body" value="/WEB-INF/view/${options[folder]}/{2}.jsp" />
        <put-attribute name="footer" value="/WEB-INF/view/${options[folder]}/footer.jsp" />

        <put-list-attribute name="folder">
            <add-list-attribute>
                <add-attribute value="{1}" />
                <add-attribute value="common" />
            </add-list-attribute>
        </put-list-attribute>
    </definition>
</tiles-definitions>
</code>```

template.jsp

```<code><%@ page language="java" pageEncoding="UTF-8"
    contentType="text/html; charset=utf-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<html>
<head>
<title>${dynamicTitle} - <fmt:message key="common.siteName" /></title>
<tiles:insertAttribute name="meta" />
</head>
<body>
    <div id="header">
        <tiles:insertAttribute name="header" />
    </div>
    <div id="body">
        <tiles:insertAttribute name="body" />
    </div>
    <div id="footer">
        <tiles:insertAttribute name="footer" />
    </div>
</body>
</html>
</code>```

I tried several solutions with no result. My trials were as follows:
1. Use <tiles:importAttribute name="folder"/> in my JSP. Absolutely no difference
2. Use <tiles:insertAttribute name="folder"/> in my JSP. I got an exception since attribute was not a string.
3. Define attribute in JSP using <tiles:putListAttribute name="folder">FULL_DEFINITION_HERE</tiles:putListAttribute> no difference at all.

I've referred to the article mentioned above, and tiles documentation specifically the OptionsRenderer documentation with no use. Can anybody tell me what I'm doing wrong here? I believe that this is not related to spring MVC.

答: Please remove the $ from ${options.

Body:
I'm facing several problems with my spring MVC project and tiles 3, and one of the main problems is with list attributes. What I'm trying to make is create a generic tiles definition using an OptionsRenderer, like in the ultimate view article (there is a mistake in the article, since the lit attribute is defined outside the definition, which is wrong). When I create some attributes with an ${options[myoptions]} expression, I always get an IllegalStateException in my template JSP because a list attribute with the name myoptions is missing, even though I defined this list attribute. My code is as follows:

tiles.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">

<tiles-definitions>

    <definition name="WILDCARD:*/*" template="/WEB-INF/view/template.jsp">
        <put-attribute name="meta" value="/WEB-INF/view/${options[folder]}/meta.jsp" />
        <put-attribute name="header" value="/WEB-INF/view/${options[folder]}/header.jsp" />
        <put-attribute name="body" value="/WEB-INF/view/${options[folder]}/{2}.jsp" />
        <put-attribute name="footer" value="/WEB-INF/view/${options[folder]}/footer.jsp" />

        <put-list-attribute name="folder">
            <add-list-attribute>
                <add-attribute value="{1}" />
                <add-attribute value="common" />
            </add-list-attribute>
        </put-list-attribute>
    </definition>
</tiles-definitions>

template.jsp

<%@ page language="java" pageEncoding="UTF-8"
    contentType="text/html; charset=utf-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

<title>${dynamicTitle} - <fmt:message key="common.siteName" /></title>
<tiles:insertAttribute name="meta" />

        <tiles:insertAttribute name="header" />

        <tiles:insertAttribute name="body" />

        <tiles:insertAttribute name="footer" />

I tried several solutions with no result. My trials were as follows:
1. Use <tiles:importAttribute name="folder"/> in my JSP. Absolutely no difference
2. Use <tiles:insertAttribute name="folder"/> in my JSP. I got an exception since attribute was not a string.
3. Define attribute in JSP using <tiles:putListAttribute name="folder">FULL_DEFINITION_HERE</tiles:putListAttribute> no difference at all.

I've referred to the article mentioned above, and tiles documentation specifically the OptionsRenderer documentation with no use. Can anybody tell me what I'm doing wrong here? I believe that this is not related to spring MVC.

Body: Please remove the $ from ${options.