问:
User Defined Functions and Aggregate in Cassandra
I am testing the UDF / UDA feature in Cassandra, It seems good. But I have few questions in using it.

1) In the Cassandra.yaml, It is mentioned that sandboxing is enabled for avoiding the evil code, So are we violating the rule and what will be the consequences of enabling this support (flag)?

2) What are the advantages of using UDF / UDA in Cassandra compared to reading the data and writing the aggregation logic in client side?

3) Also, apart from JAVA, Is there a language support available for nodejs, python in writing UDF / UDA?

Thanks,
Harry

答:
Here are some comments:

Sandboxing prevents execution of "dangerous" code - working with files/sockets, starting threads, etc.   This blog post provides some additional details about it.

It could be several - you don't move data from coordinator node to your app, you offload calculations to cassandra cluster, etc.

Languages supporting JSR 223 "Scripting for Java" - JavaScript, Groovy, JRuby, Jython, ... (with enable_scripted_user_defined_functions set to true in Cassandra config).  But Java should be the fastest.

Also look to this presentation about UDF/UDA from author of this functionality (Robert Stupp) & this blog post with more details & examples.


来源: stackexchange

问:
Wirecloud geojson in a map
Hello i'm trylling to show an entity with geojson data in a map inside of Wirecloud. The data comes from my own instance of Orion. Here you have some screenshots where you can see the data from Orion and the configuration.

General configuration

Entity to POI configuration

Dashboard, Json editor is just to show the data

If i change the lat and long and i put it in a normal attribute with name, it works but in the geojson array it doesn't work.

Can someone tell me what i'm doing wrong.

Thanks

答:
After some days of working, I saw that the version in the repo of the component "NGSI Entity 2 PoI operator" is hightest than the one that it's in the Wirecloud's marketplace, in the last commits i saw that geojson support was added so i tried it but it didn't work so I forked the repo and i fixed it.

Here it is my fixed version.
https://github.com/xXcoronaXx/ngsi-entity2poi-operator

ContentLicense: CC BY-SA 3.0

Title: Wirecloud geojson in a map


问:
CascadeType.Merge in entity relations with Spring Data
I have two entities (Consultancy - the owner, and InterviewType) with @ManyToMany bidirectional relations. User can attach the interview type to the Consultancy. I know that in a case of we're using a Hibernate we can just invoke merge() method on EntityManager to persist a new transient entity or update a detach object, but what about save() method in Spring Data or Spring Data have another method? Does it make some effect on a depend entity of a @ManyToMany relations? In case of 'yes' in what way? Does it invoke a Hibernates merge() method under the hood?

答:
If you look at the implementation from the 2.0.2 version:

```<code>@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}
</code>```

The merge is invoked under the hood if the persistence provider decides that the passed entity new.. does not have an id / is not managed by the persistence provider.. So that 'new' depends a bit on the underlying implementation of the EntityInformation.

In general it should invoke the merge when there is a need though i had situations where I had to write my own custom merge logic as the implicit merge was not ivoked

Body:
If you look at the implementation from the 2.0.2 version:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

The merge is invoked under the hood if the persistence provider decides that the passed entity new.. does not have an id / is not managed by the persistence provider.. So that 'new' depends a bit on the underlying implementation of the EntityInformation.

In general it should invoke the merge when there is a need though i had situations where I had to write my own custom merge logic as the implicit merge was not ivoked


问:
Windows Console and Qt Unicode Text
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

```<code>#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}
</code>```

答:
I got a little farther today with the code bellow.  Now it displays unicode correctly to the console but still not working quite right because the console freezes/crashes after the first unicode text is put out to the console and nothing subsequent to that is show on the console.  It is as if unicode chars cause the console buffer to get confused after the first text output.</p>

```<code>#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    qin.setCodec("UTF-8");
    qin.autoDetectUnicode();

    QTextStream qout(stdout);
    qout.setCodec("UTF-8");
    qout.autoDetectUnicode();

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    qout << "Bellow are some unicode characters: " << endl;

    //Now this is displayed correctly on cosole but after displaying text
    //it no loger is capable of displaying anything subsequently.
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = qin.readLine();
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Windows Console and Qt Unicode Text

Body:
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}

Body:
I got a little farther today with the code bellow.  Now it displays unicode correctly to the console but still not working quite right because the console freezes/crashes after the first unicode text is put out to the console and nothing subsequent to that is show on the console.  It is as if unicode chars cause the console buffer to get confused after the first text output.

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    qin.setCodec("UTF-8");
    qin.autoDetectUnicode();

    QTextStream qout(stdout);
    qout.setCodec("UTF-8");
    qout.autoDetectUnicode();

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    qout << "Bellow are some unicode characters: " << endl;

    //Now this is displayed correctly on cosole but after displaying text
    //it no loger is capable of displaying anything subsequently.
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = qin.readLine();
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}


问:
How to increment Dates and use them with operators like '>' or '<' in SQL server?
How can I increment date in WHILE LOOP in a loop like this:

```<code>DECLARE @StartDate Datetime = some_date;
DECLARE @EndDate Datetime = other_date;
DECLARE @FinishDate Datetime = last_date;
    WHILE @EndDate < @FinishDate
      BEGIN
         [something happens]
        SET @StartDate = [ plus 1 day to @EndDate ]
        SET @EndDate = [ plus 8 days to itself]
      END
</code>```

And can I use an operator < in an expression lik this @EndDate < @FinishDate ?
By the way, I've tried to use DATEADD but it doesn't work. If i set data-type DATETIME2 it returns with ERROR 8117.

答:
Based on the comment the OP made above, they are looking for weeks up to the finish date. Rather than doing this with a loop, it can much more easily (and efficiently) be achieved with a rCTE:

```<code>DECLARE @FinishDate datetime = '20171231', @StartDate datetime = '20171204';
DECLARE @EndDate datetime = DATEADD(DAY, 6, @StartDate);

WITH Dates AS (
    SELECT @StartDate AS StartDate,
           @EndDate AS EndDate
    UNION ALL
    SELECT DATEADD(DAY, 7,StartDate),
           DATEADD(DAY, 7,EndDate)
    FROM Dates
    WHERE DATEADD(DAY, 7,EndDate) <= @FinishDate)
SELECT *
FROM Dates;
</code>```

This gives you all the weeks in December 2017.

Body:
How can I increment date in WHILE LOOP in a loop like this:

DECLARE @StartDate Datetime = some_date;
DECLARE @EndDate Datetime = other_date;
DECLARE @FinishDate Datetime = last_date;
    WHILE @EndDate < @FinishDate
      BEGIN
         [something happens]
        SET @StartDate = [ plus 1 day to @EndDate ]
        SET @EndDate = [ plus 8 days to itself]
      END

And can I use an operator < in an expression lik this @EndDate < @FinishDate ?
By the way, I've tried to use DATEADD but it doesn't work. If i set data-type DATETIME2 it returns with ERROR 8117.

Body:
Based on the comment the OP made above, they are looking for weeks up to the finish date. Rather than doing this with a loop, it can much more easily (and efficiently) be achieved with a rCTE:

DECLARE @FinishDate datetime = '20171231', @StartDate datetime = '20171204';
DECLARE @EndDate datetime = DATEADD(DAY, 6, @StartDate);

WITH Dates AS (
    SELECT @StartDate AS StartDate,
           @EndDate AS EndDate
    UNION ALL
    SELECT DATEADD(DAY, 7,StartDate),
           DATEADD(DAY, 7,EndDate)
    FROM Dates
    WHERE DATEADD(DAY, 7,EndDate) <= @FinishDate)
SELECT *
FROM Dates;

This gives you all the weeks in December 2017.


问:
slicing error in numpy array
I am trying to run the following code

```<code>fs = 1000
data = np.loadtxt("trainingdataset.txt", delimiter=",")
data1 = data[:,2]
data2 = data1.astype(int)
X,Y = data2['521']
</code>```

but it gets me the following error

```<code>Traceback (most recent call last):
  File "C:\Users\hadeer.elziaat\Desktop\testspec.py", line 58, in <module>
    X,Y = data2['521']
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
</code>```

my dataset

```<code>1,4,6,10
2,100,125,10
3,100,7216,254
4,100,527,263
5,100,954,13
6,100,954,23
</code>```

答:
You say you want all the data in the 3rd column.

I assume you also want some kind of x-axis, since you are attempting to do X, Y = .... How about using the first column for that? Then your code would be:

```<code>import numpy as np

data = np.loadtxt("trainingdataset.txt", delimiter=',', dtype='int')
x = data[:, 0]
y = data[:, 2]
</code>```

What remains unclear from your question is why you tried to index your data with 521 - which failed because you cannot use strings as indices on plain arrays.

Title: slicing error in numpy array

Body:
I am trying to run the following code

fs = 1000
data = np.loadtxt("trainingdataset.txt", delimiter=",")
data1 = data[:,2]
data2 = data1.astype(int)
X,Y = data2['521']

but it gets me the following error

Traceback (most recent call last):
  File "C:\Users\hadeer.elziaat\Desktop\testspec.py", line 58, in <module>
    X,Y = data2['521']
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

my dataset

1,4,6,10
2,100,125,10
3,100,7216,254
4,100,527,263
5,100,954,13
6,100,954,23

Body:
You say you want all the data in the 3rd column.

I assume you also want some kind of x-axis, since you are attempting to do X, Y = .... How about using the first column for that? Then your code would be:

import numpy as np

data = np.loadtxt("trainingdataset.txt", delimiter=',', dtype='int')
x = data[:, 0]
y = data[:, 2]

What remains unclear from your question is why you tried to index your data with 521 - which failed because you cannot use strings as indices on plain arrays.


问:
How reset ram by useing TI-Basic programming in TI-89 calculator
This is possible by manually pressing the F6 button and selecting Clear a-z...
How possible in the TI-Basic (TI-89) programming environment?

enter image description here

答:
The DelVar statement deletes a variable. Of course, deleting a-z manually would be a pain. Instead, you can do:

```<code>delaz()
Prgm
Local ch,ind,var
ord("a")→ch
For ind,0,25
 char(ch+ind)→var
 DelVar #var
EndFor
EndPrgm
</code>```

ord("a") gets the character code for "a", char(c) returns a string containing the the character with code c, and #var gives a refrence to the variable named by string var.

If you define this program, you can simply use delaz() to delete a-z programmatically. Be careful not to use one letter names for any of the local variables, because you will delete them before the program finishes.

Body:
The DelVar statement deletes a variable. Of course, deleting a-z manually would be a pain. Instead, you can do:

delaz()
Prgm
Local ch,ind,var
ord("a")→ch
For ind,0,25
 char(ch+ind)→var
 DelVar #var
EndFor
EndPrgm

ord("a") gets the character code for "a", char(c) returns a string containing the the character with code c, and #var gives a refrence to the variable named by string var.

If you define this program, you can simply use delaz() to delete a-z programmatically. Be careful not to use one letter names for any of the local variables, because you will delete them before the program finishes.


问:
Why am I unable to use app.Device.IsPhone in Xamarin UI Tests
I am running iOS tests which will be ran against iPhones and iPads. The app is slightly different on both devices so I need a way to differentiate which one the tests are being run against. I can see that there is an IDevice.IsPhone or IDevice.IsTablet properties but these are private and I can't access them.

Is there a simple way to find out what device you are using or a way to access the properties on the interface?

```<code>    [SetUp]
    public void BeforeEachTest()
    {
        app = AppInitializer.StartApp(platform);
    }

    public bool DeviceIsiPad()
    {
        var device = app.Device;
        if (device.IsTablet)
        {
            return true;
        }
        else {
            return false;
        }
    }
</code>```

答:
I ended up using the below. I get a warning telling me that its obsolete and to use Device but it still works:</p>

```<code>bool isPhone = ((Xamarin.UITest.iOS.iOSApp)app).Config.IsPhone;
</code>```

Body:
I am running iOS tests which will be ran against iPhones and iPads. The app is slightly different on both devices so I need a way to differentiate which one the tests are being run against. I can see that there is an IDevice.IsPhone or IDevice.IsTablet properties but these are private and I can't access them.

Is there a simple way to find out what device you are using or a way to access the properties on the interface?

    [SetUp]
    public void BeforeEachTest()
    {
        app = AppInitializer.StartApp(platform);
    }

    public bool DeviceIsiPad()
    {
        var device = app.Device;
        if (device.IsTablet)
        {
            return true;
        }
        else {
            return false;
        }
    }

Body:
I ended up using the below. I get a warning telling me that its obsolete and to use Device but it still works:

bool isPhone = ((Xamarin.UITest.iOS.iOSApp)app).Config.IsPhone;


问:
change of all immediate elements of the corrosponding class using jquery
my html content

```<code> <li class="info"> info<li>
 <li class="other"> info<li>
 <li class="other"> info<li>

 <li class="Error"> error<li>
 <li class="other"> error<li>
 <li class="warning"> warning<li>
 <li class="other"> warning<li>
 <li class="other"> warning<li>
 <li class="info"> info<li>
 <li class="other"> info<li>
 <li class="other"> info<li>
</code>```

based on the li element class, I want to filter only the immediate li.other class item css to be changed using jquery;

I followed the below approach: when I select info elements:

```<code>  $('.info').prevAll('li.other').css({});
</code>```

It worked but it will all the previous li.other elements changed. Instead I want only specific to that particular html(info) element li.other element. rest all to be ignored.
 Please any one provide the possible approach

答:
You can use next to solve this query</p>

```<code> $('.other').next().css({});
</code>```

Body:
my html content

 info

 info

 info

 error

 error

 warning

 warning

 warning

 info

 info

 info

based on the li element class, I want to filter only the immediate li.other class item css to be changed using jquery;

I followed the below approach: when I select info elements:

  $('.info').prevAll('li.other').css({});

It worked but it will all the previous li.other elements changed. Instead I want only specific to that particular html(info) element li.other element. rest all to be ignored.
 Please any one provide the possible approach

Body:
You can use next to solve this query

 $('.other').next().css({});


问:
Cloning a PHP PDO recordset object to count the rows returned by a select statement
I'm refactoring part of a PHP application which uses adodb as db library, in order to start using PDO.

I need something which provides me the number of rows included in a select recordset, something that can easily replace the old $rs->RecordCount() adodb method that I used before. It should work for sqlite3.

I can't simply re-execute the query (or re-execute the query using a select count(*) ) because I can't change so much the original application, the application calls in many parts a function get_num_rows($rs) (which contains just $rs->RecordCount() ) and I can just change the content of that function.

I tried cloning the recordset object and counting the records fetched:

```<code>function get_num_rows($rs)
{
    $rs_copy = clone $rs;
    return (count($rs_copy->fetchAll()));
}
</code>```

but it doesn't work, because $rs_copy->fetchAll() returns me false. I can't do it on the original recordset because later in the applicaiton I need to fetch it again and I think there is no way in PDO sqlite to reuse the recordset (correct me if I'm wrong).

Do you have any solutions?

答:
You can't properly clone and/or serialize/unserialize PDO objects, most probably because they are tightly tied to a connection resource.

The fact is, there is no point cloning it. If $rs is a PDOStatement object, you can just re-execute it, since you have access to it. This is one of the main advantage of prepared statements, prepare once, execute multiple times.

Like this:

```<code>function get_num_rows($rs)
{
 $rs->execute();
 return (count($rs->fetchAll()));
}
</code>```

You guessed it: calling execute() on the same PDOStatement instance the second time without specifying any parameters will reuse the last set of parameters and re-execute the statement as is.

Therefore, there is no need to clone PDOStatement objects.

Body:
I'm refactoring part of a PHP application which uses adodb as db library, in order to start using PDO.

I need something which provides me the number of rows included in a select recordset, something that can easily replace the old $rs->RecordCount() adodb method that I used before. It should work for sqlite3.

I can't simply re-execute the query (or re-execute the query using a select count(*) ) because I can't change so much the original application, the application calls in many parts a function get_num_rows($rs) (which contains just $rs->RecordCount() ) and I can just change the content of that function.

I tried cloning the recordset object and counting the records fetched:

function get_num_rows($rs)
{
    $rs_copy = clone $rs;
    return (count($rs_copy->fetchAll()));
}

but it doesn't work, because $rs_copy->fetchAll() returns me false. I can't do it on the original recordset because later in the applicaiton I need to fetch it again and I think there is no way in PDO sqlite to reuse the recordset (correct me if I'm wrong).

Do you have any solutions?

Body:
You can't properly clone and/or serialize/unserialize PDO objects, most probably because they are tightly tied to a connection resource.

The fact is, there is no point cloning it. If $rs is a PDOStatement object, you can just re-execute it, since you have access to it. This is one of the main advantage of prepared statements, prepare once, execute multiple times.

Like this:

function get_num_rows($rs)
{
 $rs->execute();
 return (count($rs->fetchAll()));
}

You guessed it: calling execute() on the same PDOStatement instance the second time without specifying any parameters will reuse the last set of parameters and re-execute the statement as is.

Therefore, there is no need to clone PDOStatement objects.


问:
Tests still failing on TeamCity even after full rollback
I use TeamCity 10.x (Enterprise), as well as TFS for source control.

I recently committed a changeset which did not break the build, but ended up causing hundreds of unit tests to fail across 10+ test projects. Those tests started failing immediately after my check-in, so naturally I assumed that I was at fault.

The changeset included these changes:

Changing the namespaces of various files (e.g., moving all test stubs to a "Stubs" folder and updating their namespace to end with the ".Stubs" suffix);

Updating the using statements in other files to reference these new namespaces where necessary;

Rewriting some unit tests using the Moq library, replacing TypeMock.

I rolled back the entire changeset, in the hopes that all the unit tests would pass again.

Unfortunately, most of the test projects continue to have a lot of failing tests. Additionally, these failing tests are causing all of the remaining tests to be skipped by the VS Test Engine. This is new behaviour that I hadn't seen before.

Questions:

Why are the tests still failing even though I have rolled back the offending changeset?

What can I do to fix this?

If I haven't provided enough information in this post, please let me know and I shall update.

答:
Please try below items to narrow down the issue:

Check that if you indeed rollback the changeset.

Check how TeamCity get the sources, get the latest changeset or
specific changeset?

Try to clean caches and pervious sources on agent machine（Clean all files before build）, then try it again.

Reference : Clean Checkout and
Clean Sources


问:
Fragment not showing previous data when coming from another fragment
In my android activity I am using multiple fragments, I am successfully switching these fragments according to my requirement but problem is that when I am switching Fragment 1 to Fragment 2 and back from Fragment 2 to Fragment 1, Fragment 1 not showing previous data Fragment 1 start from stretch, but I want to show previous data same as I was selected.

Here is my code for go Fragment 1 (fragment_search_customerProfile) to Fragment 2 (fragment_CustomerInfo):

```<code>FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, new fragment_Search());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();

transaction.remove(new fragment_search_customerProfile()).commit();
</code>```

Here is my code for back Fragment 1 (fragment_search_customerProfile) fromFragment 2 (fragment_CustomerInfo):

```<code>FragmentManager manager = getActivity().getSupportFragmentManager();

FragmentTransaction transaction = manager.beginTransaction();

Log.d("fragment_Search", fromSearch + "");
transaction.replace(R.id.custIndoFram, new fragment_search_customerProfile());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.custIndoFram);

layout.removeAllViewsInLayout();

transaction.remove(new fragment_CustomerInfo()).commit();
</code>```

Can anyone explain me how can I stay save my fragment data?

答:
Instead of transaction.replace(R.id.filterFram, new fragment_Search());
 you can use transaction.add to add fragment while having the data of first one
transaction.add(R.id.filterFram, new fragment_Search());
transaction.addToBackStack(null);

From fragment two you can use .show instead of replace to show the first fragment
and hide fragment two from the first one.           transaction.show(getSupportFragmentManager().findFragmentByTag("firstFragmentTag")).commit();

Body:
In my android activity I am using multiple fragments, I am successfully switching these fragments according to my requirement but problem is that when I am switching Fragment 1 to Fragment 2 and back from Fragment 2 to Fragment 1, Fragment 1 not showing previous data Fragment 1 start from stretch, but I want to show previous data same as I was selected.

Here is my code for go Fragment 1 (fragment_search_customerProfile) to Fragment 2 (fragment_CustomerInfo):

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.filterFram, new fragment_Search());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.cpFrame);
layout.removeAllViewsInLayout();

transaction.remove(new fragment_search_customerProfile()).commit();

Here is my code for back Fragment 1 (fragment_search_customerProfile) fromFragment 2 (fragment_CustomerInfo):

FragmentManager manager = getActivity().getSupportFragmentManager();

FragmentTransaction transaction = manager.beginTransaction();

Log.d("fragment_Search", fromSearch + "");
transaction.replace(R.id.custIndoFram, new fragment_search_customerProfile());

FrameLayout layout = (FrameLayout) rootView.findViewById(R.id.custIndoFram);

layout.removeAllViewsInLayout();

transaction.remove(new fragment_CustomerInfo()).commit();

Can anyone explain me how can I stay save my fragment data?


问:
SQL - Duplicate rows (changing one column)
I am having hard time trying to create an view that contains duplicated values from a table in SQL Server Management Studio 17.

My table look like this:

```<code>DATE = datetime
Product = varchar(10)
Price = decimal(18,2)

Date     | Product | Price

07-12-17 |    1    | 32

06-12-17 |    24   | 35
</code>```

There are 1-24 products for every day.

I want to create the following view-tabel:

```<code>Date     | Product | Price

07-12-17 |    1.1  | 32

07-12-17 |    1.2  | 32

07-12-17 |    1.3  | 32

07-12-17 |    1.4  | 32

06-12-17 |    24.1 | 35

06-12-17 |    24.2 | 35

06-12-17 |    24.3 | 35

06-12-17 |    24.4 | 35
</code>```

And so on for all 24 products for every day.

答:
Try to use CROSS JOIN with VALUES

```<code>SELECT
  t.[Date],
  CONCAT(t.Product,'.',l.num) ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN (VALUES(1),(2),(3),(4)) l(num)
ORDER BY t.[Date],t.Product,l.num
</code>```

Variant with UNION ALL

```<code>SELECT
  t.[Date],
  t.Product+'.'+l.Label ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN
  (
    SELECT '1' Label UNION ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4'
  ) l
ORDER BY t.[Date],t.Product,l.Label
</code>```

If you have another table which contains rows with numbers 1-4 then you can use CROS JOIN with that table

```<code>SELECT
  t.[Date],
  CONCAT(t.Product,'.',l.[ID from another table]) ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN [Your table with numbers] l
ORDER BY t.[Date],t.Product,l.[ID from another table]
</code>```

If you need only 4 duplicates then you also can use 4 queries with UNION ALL

```<code>SELECT [Date],Product+'.1' ProductLabel,Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.2',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.3',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.4',Price FROM [Your table]
ORDER BY [Date],ProductLabel
</code>```

Body:
I am having hard time trying to create an view that contains duplicated values from a table in SQL Server Management Studio 17.

My table look like this:

DATE = datetime
Product = varchar(10)
Price = decimal(18,2)

Date     | Product | Price

07-12-17 |    1    | 32

06-12-17 |    24   | 35

There are 1-24 products for every day.

I want to create the following view-tabel:

Date     | Product | Price

07-12-17 |    1.1  | 32

07-12-17 |    1.2  | 32

07-12-17 |    1.3  | 32

07-12-17 |    1.4  | 32

06-12-17 |    24.1 | 35

06-12-17 |    24.2 | 35

06-12-17 |    24.3 | 35

06-12-17 |    24.4 | 35

And so on for all 24 products for every day.

Body:
Try to use CROSS JOIN with VALUES

SELECT
  t.[Date],
  CONCAT(t.Product,'.',l.num) ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN (VALUES(1),(2),(3),(4)) l(num)
ORDER BY t.[Date],t.Product,l.num

Variant with UNION ALL

SELECT
  t.[Date],
  t.Product+'.'+l.Label ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN
  (
    SELECT '1' Label UNION ALL SELECT '2' UNION ALL SELECT '3' UNION ALL SELECT '4'
  ) l
ORDER BY t.[Date],t.Product,l.Label

If you have another table which contains rows with numbers 1-4 then you can use CROS JOIN with that table

SELECT
  t.[Date],
  CONCAT(t.Product,'.',l.[ID from another table]) ProductLabel,
  t.Price
FROM [Your table] t
CROSS JOIN [Your table with numbers] l
ORDER BY t.[Date],t.Product,l.[ID from another table]

If you need only 4 duplicates then you also can use 4 queries with UNION ALL

SELECT [Date],Product+'.1' ProductLabel,Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.2',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.3',Price FROM [Your table]
UNION ALL SELECT [Date],Product+'.4',Price FROM [Your table]
ORDER BY [Date],ProductLabel


问:
Yocto: Create a directory after mount
I have a Yocto bitbake recipe in my layer - base-files_%.bbappend. It creates mount points:

```<code>do_install_append() {
    mknod -m 622 ${D}/dev/console c 5 1
    install -m 0755 -d ${D}/boot/EFI
    install -m 0755 -d ${D}/data
}
</code>```

The /data/ directory is later mounted to the internal SD card.

I would like to create a directory ${D}/data/test. What is the best way to do it? I've added a line install -m 0755 -d ${D}/data/test to this function but it didn't do it.

Thanks so much.

答:
You have to ship those installed files by adding to your recipe:

FILES_${PN} += "/data/test"

Another solution is to add in your image recipe:

```<code>create_dirs() {
    mkdir -p ${IMAGE_ROOTFS}/data/test
}

ROOTFS_POSTPROCESS_COMMAND += "create_dirs ; "
</code>```

Title: Yocto: Create a directory after mount

Body:
I have a Yocto bitbake recipe in my layer - base-files_%.bbappend. It creates mount points:

do_install_append() {
    mknod -m 622 ${D}/dev/console c 5 1
    install -m 0755 -d ${D}/boot/EFI
    install -m 0755 -d ${D}/data
}

The /data/ directory is later mounted to the internal SD card.

I would like to create a directory ${D}/data/test. What is the best way to do it? I've added a line install -m 0755 -d ${D}/data/test to this function but it didn't do it.

Thanks so much.

Body:
You have to ship those installed files by adding to your recipe:

FILES_${PN} += "/data/test"

Another solution is to add in your image recipe:

create_dirs() {
    mkdir -p ${IMAGE_ROOTFS}/data/test
}

ROOTFS_POSTPROCESS_COMMAND += "create_dirs ; "


问:
How to preview PDF file in internet explorer in MVC Web Application
I require to preview PDF file stored in database. In Chrome its working fine but when i do it in IE it gets downloaded. Reason may be due to below code:

Javascript Method:

```<code>if (navigator.appVersion.toString().indexOf('.NET') > 0) {
    console.log(response._body);
    window.navigator.msSaveBlob(response._body, obj.documentName);
}
</code>```

Controller Method:

```<code>[HttpGet]
public FileResult DownLoadFile(int id)
{
    List<FileDetailsModel> ObjFiles = GetFileList();
    var FileById = (from FC in ObjFiles
                    where FC.Id.Equals(id)
                    select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();
     return File(FileById.FileContent, "application/pdf", FileById.FileName);
}
</code>```

So is there way by which we can preview PDF file as all files are in PDF format in database.

答:
I have this snippet for you where we check browsers. I think you can use parts of it to fix your problem. Cross-browser file serving through javascript is sometimes a PITA.

use GGO's iframe suggestion but to generate the url use this code:

```<code>var fileURL = URL.createObjectURL(file);
</code>```

Body:
I require to preview PDF file stored in database. In Chrome its working fine but when i do it in IE it gets downloaded. Reason may be due to below code:

Javascript Method:

if (navigator.appVersion.toString().indexOf('.NET') > 0) {
    console.log(response._body);
    window.navigator.msSaveBlob(response._body, obj.documentName);
}

Controller Method:

[HttpGet]
public FileResult DownLoadFile(int id)
{
    List<FileDetailsModel> ObjFiles = GetFileList();
    var FileById = (from FC in ObjFiles
                    where FC.Id.Equals(id)
                    select new { FC.FileName, FC.FileContent }).ToList().FirstOrDefault();
     return File(FileById.FileContent, "application/pdf", FileById.FileName);
}

So is there way by which we can preview PDF file as all files are in PDF format in database.

Body:
I have this snippet for you where we check browsers. I think you can use parts of it to fix your problem. Cross-browser file serving through javascript is sometimes a PITA.

use GGO's iframe suggestion but to generate the url use this code:

var fileURL = URL.createObjectURL(file);


问:
How to lookup the values of a column in a table, if one of its column matches with the other table
I'm using Power BI desktop. I have 2 tables named as Company details and Tax. These tables contains a common column Company ID. Actually these 2 tables contain different columns but I have only shown the columns needed for this question.

Company details:

```<code>+-------------+--------------+
| Company UID | Company name |
+-------------+--------------+
| C1000       | A            |
| C1400       | B            |
| C1200       | C            |
| C1100       | D            |
| C1300       | E            |
+-------------+--------------+
</code>```

Tax:

```<code>+-------------+-----+
| Company UID | FID |
+-------------+-----+
|       C1000 | F22 |
|       C1100 | F20 |
|       C1200 | F22 |
|       C1300 | F21 |
|       C1400 | F20 |
+-------------+-----+
</code>```

Now I need to create a calculated column Fcode  in Company details which has the values returned by the Existing column FID in TAX if the values of the column Company UID in both the table matches.

Expected result

Company details:

```<code>+-------------+--------------+-----+
| Company UID | Company name | FID |
+-------------+--------------+-----+
|       C1000 | A            | F22 |
|       C1400 | B            | F20 |
|       C1200 | C            | F22 |
|       C1100 | C            | F20 |
|       C1300 | D            | F21 |
+-------------+--------------+-----+
</code>```

My Dax:

```<code>    Fcode = IF(VALUES('Company details'[Company UID])=VALUES('Tax'[Company UID]),LOOKUPVALUE('Tax'[FID]), 0))
</code>```

I'm stuck up with what dax should I give in the place of TrueResult inside the If Loop. so I just tried on giving lookup function. Ofcourse it shows an error. Can anyone suggest what I should replace on behalf of lookup or any other way to get the expected result.

答:
First of all, why don't you add relationship between those columns and use RELATED function to get the related FID value from Tax. If you don't want to add relationship then you can still use CROSSJOIN.
Take a look at this article
https://www.sqlbi.com/articles/from-sql-to-dax-joining-tables/</p>

Body:
I'm using Power BI desktop. I have 2 tables named as Company details and Tax. These tables contains a common column Company ID. Actually these 2 tables contain different columns but I have only shown the columns needed for this question.

Company details:

+-------------+--------------+
| Company UID | Company name |
+-------------+--------------+
| C1000       | A            |
| C1400       | B            |
| C1200       | C            |
| C1100       | D            |
| C1300       | E            |
+-------------+--------------+

Tax:

+-------------+-----+
| Company UID | FID |
+-------------+-----+
|       C1000 | F22 |
|       C1100 | F20 |
|       C1200 | F22 |
|       C1300 | F21 |
|       C1400 | F20 |
+-------------+-----+

Now I need to create a calculated column Fcode  in Company details which has the values returned by the Existing column FID in TAX if the values of the column Company UID in both the table matches.

Expected result

Company details:

+-------------+--------------+-----+
| Company UID | Company name | FID |
+-------------+--------------+-----+
|       C1000 | A            | F22 |
|       C1400 | B            | F20 |
|       C1200 | C            | F22 |
|       C1100 | C            | F20 |
|       C1300 | D            | F21 |
+-------------+--------------+-----+

My Dax:

    Fcode = IF(VALUES('Company details'[Company UID])=VALUES('Tax'[Company UID]),LOOKUPVALUE('Tax'[FID]), 0))

I'm stuck up with what dax should I give in the place of TrueResult inside the If Loop. so I just tried on giving lookup function. Ofcourse it shows an error. Can anyone suggest what I should replace on behalf of lookup or any other way to get the expected result.


问:
Get Phone Number Label from String
How to get the phone number Label like Home, Work, Mobile, Fax, etc from string.
For example below is the string and one of the number i.e (91) 98203 88212 is mobile. So how to detect that.

```<code>Phone: (91-22) 6641 1234
Direct: (91-22) 6691 8972
Fax: (91-22) 6691 1455
Mobile: (91) 98203 88212
</code>```

Just like how business card OCR apps works. What logic is used behind to detect the phone number label?

答:
If you have CNContact object then you can get these easily.

```<code>for item in personContact.phoneNumbers {
        if let label = item.label{
            let localizedLabel = CNLabeledValue<NSString>.localizedString(forLabel: label)
//You will get your label here
            print(localizedLabel)
        }else{
            print(item.value.stringValue)
        }
    }
</code>```

Or if you have only String values then can use:

```<code> let contacts = ["Phone: (91-22) 6641 1234",
    "Direct: (91-22) 6691 8972",
    "Fax: (91-22) 6691 1455",
    "Mobile: (91) 98203 88212"]
    for contact in contacts{
        let contactParts = contact.components(separatedBy: ":")
        print(contactParts[0])
    }
</code>```

Title: Get Phone Number Label from String

Body:
How to get the phone number Label like Home, Work, Mobile, Fax, etc from string.
For example below is the string and one of the number i.e (91) 98203 88212 is mobile. So how to detect that.

Phone: (91-22) 6641 1234
Direct: (91-22) 6691 8972
Fax: (91-22) 6691 1455
Mobile: (91) 98203 88212

Just like how business card OCR apps works. What logic is used behind to detect the phone number label?

Body:
If you have CNContact object then you can get these easily.

for item in personContact.phoneNumbers {
        if let label = item.label{
            let localizedLabel = CNLabeledValue<NSString>.localizedString(forLabel: label)
//You will get your label here
            print(localizedLabel)
        }else{
            print(item.value.stringValue)
        }
    }

Or if you have only String values then can use:

 let contacts = ["Phone: (91-22) 6641 1234",
    "Direct: (91-22) 6691 8972",
    "Fax: (91-22) 6691 1455",
    "Mobile: (91) 98203 88212"]
    for contact in contacts{
        let contactParts = contact.components(separatedBy: ":")
        print(contactParts[0])
    }


问:
Keras crossentropy
I'm working with Keras and I'm trying to rewrite categorical_crossentropy by using the Keras abstract backend, but I'm stuck.

This is my custom function, I want just the weighted sum of crossentropy:

```<code>def custom_entropy( y_true, y_pred):
    y_pred /= K.sum(y_pred, axis=-1, keepdims=True)

    # clip to prevent NaN's and Inf's
    y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())

   loss = y_true * K.log(y_pred)
   loss = -K.sum(loss, -1)

   return loss
</code>```

In my program I generate a label_pred with to model.predict().

Finally I do:

```<code>    label_pred = model.predict(mfsc_train[:,:,5])
    cc = custom_entropy(label, label_pred)
    ce = K.categorical_crossentropy(label, label_pred)
</code>```

I get the following error:

```<code>Traceback (most recent call last):
  File "SAMME_train_all.py", line 47, in <module>
    ce = K.categorical_crossentropy(label, label_pred)
  File "C:\Users\gionata\AppData\Local\Programs\Python\Python36\lib
s\keras\backend\tensorflow_backend.py", line 2754, in categorical_c
    axis=len(output.get_shape()) - 1,
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'
</code>```

答:
Keras backend functions such K.categorical_crossentropy expect tensors.

It's not obvious from your question what type label is. However, we know that model.predict always returns NumPy ndarrays, so we know label_pred is not a tensor. It is easy to convert, e.g. (assuming label is already a tensor),

```<code>custom_entropy(label, K.constant(label_pred))
</code>```

Since the output of this function is a tensor, to actually evaluate it, you'd call

```<code>K.eval(custom_entropy(label, K.constant(label_pred)))
</code>```

Alternatively, you can just use model as an op, and calling it on a tensor results in another tensor, i.e.

```<code>label_pred = model(K.constant(mfsc_train[:,:,5]))
cc = custom_entropy(label, label_pred)
ce = K.categorical_crossentropy(label, label_pred)
</code>```

Now label_pred, cc and ce will all be tensors.

Title: Keras crossentropy

Body:
I'm working with Keras and I'm trying to rewrite categorical_crossentropy by using the Keras abstract backend, but I'm stuck.

This is my custom function, I want just the weighted sum of crossentropy:

def custom_entropy( y_true, y_pred):
    y_pred /= K.sum(y_pred, axis=-1, keepdims=True)

    # clip to prevent NaN's and Inf's
    y_pred = K.clip(y_pred, K.epsilon(), 1 - K.epsilon())

   loss = y_true * K.log(y_pred)
   loss = -K.sum(loss, -1)

   return loss

In my program I generate a label_pred with to model.predict().

Finally I do:

    label_pred = model.predict(mfsc_train[:,:,5])
    cc = custom_entropy(label, label_pred)
    ce = K.categorical_crossentropy(label, label_pred)

I get the following error:

Traceback (most recent call last):
  File "SAMME_train_all.py", line 47, in <module>
    ce = K.categorical_crossentropy(label, label_pred)
  File "C:\Users\gionata\AppData\Local\Programs\Python\Python36\lib
s\keras\backend\tensorflow_backend.py", line 2754, in categorical_c
    axis=len(output.get_shape()) - 1,
AttributeError: 'numpy.ndarray' object has no attribute 'get_shape'

Body:
Keras backend functions such K.categorical_crossentropy expect tensors.

It's not obvious from your question what type label is. However, we know that model.predict always returns NumPy ndarrays, so we know label_pred is not a tensor. It is easy to convert, e.g. (assuming label is already a tensor),

custom_entropy(label, K.constant(label_pred))

Since the output of this function is a tensor, to actually evaluate it, you'd call

K.eval(custom_entropy(label, K.constant(label_pred)))

Alternatively, you can just use model as an op, and calling it on a tensor results in another tensor, i.e.

label_pred = model(K.constant(mfsc_train[:,:,5]))
cc = custom_entropy(label, label_pred)
ce = K.categorical_crossentropy(label, label_pred)

Now label_pred, cc and ce will all be tensors.

ContentLicense: CC BY-SA 4.0


问:
Is there a jsonp interface on the web that will give me the destination of a redirect link?
See title for question.  Any help is appreciated.</p>

答:
i dont know of any because this is a rather trivial use case.
relying on something external and accepting the risk of your application to get disfunctional or compromised for this trivial feature is in my opinion rather stupid.

if you mean bei destination of a redirect link the value of the location header at a girven resource, you can just issue a head request and parse this header.

i don't see whats this got to do with jsonp. how you pass the results to your application is up to you. you can also do it client side.


问:
JMeter Results to Splunk
Is there any JMeter plugin available natively to send JMeter results to Splunk tcp forwarder? I looked up in jmeter-plugin's site but cannot find one. One other answer in SO suggested to use beanshell postprocessor to send the result. I am fairly new to Beanshell any help to get this done is much helpful.</p>

答:
Instead of sending data to Splunk from JMeter you could do the opposite thing - configure Splunk's input.conf to read JMeter's .jtl results file. See Monitor files and directories article for more details.

Second viable choice would be sticking to JMeter TCP Sampler, I believe it is easier than using any form of scripting

If you are looking for a ready solution you can consider SendToSplunk program which can be invoked via OS Process Sampler

Title: JMeter Results to Splunk


问:
PHP Sum array - only getting 1st result from DB
I'm fetching an array from my DB and I want to sum all the results, but I only seem to be getting the first result from the DB instead of all the results.

PHP CODE:

```<code>$jobID = $_GET['jobID'];

$sql_delivqty = "SELECT delQTY
                 FROM deliveries
                 WHERE jobID = '$jobID'
                 ";

$query_delivqty = mysqli_query($conn, $sql_delivqty) or die(mysqli_error($conn));

$row_delivqty = mysqli_fetch_array($query_delivqty);

if ($row_delivqty <= 0) {
    $delivqty = 0;
} else {
    $delivqty = array_sum($row_delivqty);
}
</code>```

VAR_DUMP:

```<code>var_dump($row_delivqty);

array (size=2)
0 => string '560' (length=3)
'delQTY' => string '560' (length=3)
</code>```

Expected Result:

560 + 85 + 25 = 670

This is not an exact duplicate of another question. The question suggested is trying to sum a column in a DB. I'm trying to sum specific rows in a DB.

答:
Do SUM in the query itself:-

```<code>$sql_delivqty = "SELECT SUM(delQTY) AS total
                 FROM deliveries
                 WHERE jobID = '$jobID'";

$query_delivqty = mysqli_query($conn, $sql_delivqty) or die(mysqli_error($conn));

$row_delivqty = mysqli_fetch_assoc($query_delivqty);

echo $row_delivqty['total'];
</code>```

Note:- This Query is vulnerable to SQL Injection. So use prepared statements of mysqli_* to prevent from it.

Reference:- mysqli::prepare Manual

For your help do like below (prepared statement way):-

```<code>$jobID = $_GET['jobID'];
if ($stmt = mysqli_prepare($conn, "SELECT SUM(delQTY) AS total FROM deliveries WHERE jobID = ?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "i", $jobID);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $row_delivqty);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    echo $row_delivqty['total'];

    /* close statement */
    mysqli_stmt_close($stmt);
}
</code>```

Body:
I'm fetching an array from my DB and I want to sum all the results, but I only seem to be getting the first result from the DB instead of all the results.

PHP CODE:

$jobID = $_GET['jobID'];

$sql_delivqty = "SELECT delQTY
                 FROM deliveries
                 WHERE jobID = '$jobID'
                 ";

$query_delivqty = mysqli_query($conn, $sql_delivqty) or die(mysqli_error($conn));

$row_delivqty = mysqli_fetch_array($query_delivqty);

if ($row_delivqty <= 0) {
    $delivqty = 0;
} else {
    $delivqty = array_sum($row_delivqty);
}

VAR_DUMP:

var_dump($row_delivqty);

array (size=2)
0 => string '560' (length=3)
'delQTY' => string '560' (length=3)

Expected Result:

560 + 85 + 25 = 670

This is not an exact duplicate of another question. The question suggested is trying to sum a column in a DB. I'm trying to sum specific rows in a DB.

Body:
Do SUM in the query itself:-

$sql_delivqty = "SELECT SUM(delQTY) AS total
                 FROM deliveries
                 WHERE jobID = '$jobID'";

$query_delivqty = mysqli_query($conn, $sql_delivqty) or die(mysqli_error($conn));

$row_delivqty = mysqli_fetch_assoc($query_delivqty);

echo $row_delivqty['total'];

Note:- This Query is vulnerable to SQL Injection. So use prepared statements of mysqli_* to prevent from it.

Reference:- mysqli::prepare Manual

For your help do like below (prepared statement way):-

$jobID = $_GET['jobID'];
if ($stmt = mysqli_prepare($conn, "SELECT SUM(delQTY) AS total FROM deliveries WHERE jobID = ?")) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "i", $jobID);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $row_delivqty);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    echo $row_delivqty['total'];

    /* close statement */
    mysqli_stmt_close($stmt);
}


问:
Getting ftp_put progress
I have a PHP script on a web server that uploads a file to another remote server via ftp_put.

How can I display the current upload progress to the user?

The only similar system I've seen is for file uploads from the user, with ajax requests to check the local size of the uploaded file on the server.

The equivalent system would be ajax requests to the web server, that then checked file sizes on the remote server and returned that data to the user's clientscript.

This seems horribly inefficient to me. Is there a better way?

答:
It can be implemented easily using FTP URL protocol wrappers:</p>

```<code>$url = "ftp://username:password@ftp.example.com/remote/dest/path/file.zip";
$local_path = "/local/source/path/file.zip";

$size = filesize($local_path) or die("Cannot retrieve size file");

$hout = fopen($url, "wb") or die("Cannot open destination file");
$hin = fopen($local_path, "rb") or die("Cannot open source file");

while (!feof($hin))
{
    $buf = fread($hin, 10240);
    fwrite($hout, $buf);
    echo "\r".intval(ftell($hin)/$size*100)."%";
}

echo "\n";

fclose($hin);
fclose($hout);
</code>```

Title: Getting ftp_put progress

Body:
It can be implemented easily using FTP URL protocol wrappers:

$url = "ftp://username:password@ftp.example.com/remote/dest/path/file.zip";
$local_path = "/local/source/path/file.zip";

$size = filesize($local_path) or die("Cannot retrieve size file");

$hout = fopen($url, "wb") or die("Cannot open destination file");
$hin = fopen($local_path, "rb") or die("Cannot open source file");

while (!feof($hin))
{
    $buf = fread($hin, 10240);
    fwrite($hout, $buf);
    echo "\r".intval(ftell($hin)/$size*100)."%";
}

echo "\n";

fclose($hin);
fclose($hout);


问:
Stripe Java integration payment process using Spring MVC
I am completely new to Stripe API. I want to embedded a payment gateway in my java J2EE application using Spring MVC. I am using stripe for it.

What I have done so far is I have included checkout.js in my checkout page and hit the pay with card button. It then successfully opens a popup which contains the necessary card details.

When clicking on pay button it should go to the stripe and generate a token for me, then redirect to the success page. But I am unable to hold that token in my back-end and do the necessary stuff.

Can you please provide me the sample codes in Spring MVC which meet my entire requirements?

Thanks in advance.

答:
actually i want to charge a credit card or debit card after check out through stripe .here is my controller to charge a card and so the result page after successful transaction.</p>

```<code>@RequestMapping(value="/charge", method = RequestMethod.POST)
  public String charge(ChargeRequest chargeRequest, Model model,HttpServletRequest request)
          throws StripeException {

        Stripe.apiKey = "sk_test_9kYpQEbABJQDw7PGSQ2Ji0m7";

        StripeApi stripeApi = new StripeApiImpl();

            chargeRequest.setDescription("Example charge");
            chargeRequest.setCurrency(Currency.EUR);

            chargeRequest.setAmount(5000);
            chargeRequest.setStripeEmail("lipsapatra23@gmail.com");
            Charge charge = stripeApi.charge(chargeRequest);
            model.addAttribute("id", charge.getId());
            model.addAttribute("status", charge.getStatus());
            model.addAttribute("chargeId", charge.getId());
            model.addAttribute("balance_transaction", charge.getBalanceTransaction());
            return "result";
        }
</code>```

Body:
actually i want to charge a credit card or debit card after check out through stripe .here is my controller to charge a card and so the result page after successful transaction.

@RequestMapping(value="/charge", method = RequestMethod.POST)
  public String charge(ChargeRequest chargeRequest, Model model,HttpServletRequest request)
          throws StripeException {

        Stripe.apiKey = "sk_test_9kYpQEbABJQDw7PGSQ2Ji0m7";

        StripeApi stripeApi = new StripeApiImpl();

            chargeRequest.setDescription("Example charge");
            chargeRequest.setCurrency(Currency.EUR);

            chargeRequest.setAmount(5000);
            chargeRequest.setStripeEmail("lipsapatra23@gmail.com");
            Charge charge = stripeApi.charge(chargeRequest);
            model.addAttribute("id", charge.getId());
            model.addAttribute("status", charge.getStatus());
            model.addAttribute("chargeId", charge.getId());
            model.addAttribute("balance_transaction", charge.getBalanceTransaction());
            return "result";
        }


问:
Python Web Scrape Unknown Number of Pages
I have working code that scrapes a single Craigslist page for specific information, but what would I need to add in order to grab the data from ALL of the pages (not knowing how many pages ahead of time)?</p>

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url="https://portland.craigslist.org/search/sss?query=electronics&sort=date"
uClient=uReq(my_url) #sends GET request to URL
page_html=uClient.read() #reads returned data and puts it in a variable
uClient.close() #close the connection

#create a file that we will want later to write parsed data to
filename="ScrapedData.csv"
f=open(filename, 'w')
headers="date, location, title, price\n"
f.write(headers)

#use BS to parse the webpage
page_soup=soup(page_html,'html.parser') #applying BS to the obtained html
containers=page_soup.findAll('p',{'class','result-info'})

for container in containers:
    container_date=container.findAll('time',{'class','result-date'})
    date=container_date[0].text
    try:
        container_location=container.findAll('span',{'class','result-hood'})
        location=container_location[0].text
    except:
        try:
            container_location=container.findAll('span',{'class','nearby'})
            location=container_location[0].text
        except:
            location='NULL'
    container_title=container.findAll('a',{'class','result-title'})
    title=container_title[0].text
    try:
        container_price=container.findAll('span',{'class','result-price'})
        price=container_price[0].text
    except:
        price='NULL'

    #to print to screen
    print('date:'+date)
    print('location:'+location)
    print('title:'+title)
    print('price:'+price)
    #to write to csv
    f.write(date+','+location.replace(",","-")+','+title.replace(","," ")+','+price+'\n')

f.close()
</code>```

答:
Apart from what sir Andersson has already shown, you can do that as well for this site:</p>

```<code>import requests
from bs4 import BeautifulSoup
import csv

page_link = "https://portland.craigslist.org/search/sss?s={}&query=electronics&sort=date"
for link in [page_link.format(page) for page in range(0,1147,120)]: #this is the fix
    res = requests.get(link)
    soup = BeautifulSoup(res.text,'lxml')
    for container in soup.select('.result-info'):
        try:
            date = container.select('.result-date')[0].text
        except IndexError:
            date = ""
        try:
            title = container.select('.result-title')[0].text
        except IndexError:
            title = ""
        try:
            price = container.select('.result-price')[0].text
        except IndexError:
            price = ""

        print(date,title,price)
        with open("craigs_item.csv","a",newline="",encoding="utf-8") as outfile:
            writer = csv.writer(outfile)
            writer.writerow([date,title,price])
</code>```

Body:
I have working code that scrapes a single Craigslist page for specific information, but what would I need to add in order to grab the data from ALL of the pages (not knowing how many pages ahead of time)?

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url="https://portland.craigslist.org/search/sss?query=electronics&sort=date"
uClient=uReq(my_url) #sends GET request to URL
page_html=uClient.read() #reads returned data and puts it in a variable
uClient.close() #close the connection

#create a file that we will want later to write parsed data to
filename="ScrapedData.csv"
f=open(filename, 'w')
headers="date, location, title, price\n"
f.write(headers)

#use BS to parse the webpage
page_soup=soup(page_html,'html.parser') #applying BS to the obtained html
containers=page_soup.findAll('p',{'class','result-info'})

for container in containers:
    container_date=container.findAll('time',{'class','result-date'})
    date=container_date[0].text
    try:
        container_location=container.findAll('span',{'class','result-hood'})
        location=container_location[0].text
    except:
        try:
            container_location=container.findAll('span',{'class','nearby'})
            location=container_location[0].text
        except:
            location='NULL'
    container_title=container.findAll('a',{'class','result-title'})
    title=container_title[0].text
    try:
        container_price=container.findAll('span',{'class','result-price'})
        price=container_price[0].text
    except:
        price='NULL'

    #to print to screen
    print('date:'+date)
    print('location:'+location)
    print('title:'+title)
    print('price:'+price)
    #to write to csv
    f.write(date+','+location.replace(",","-")+','+title.replace(","," ")+','+price+'\n')

f.close()

Body:
Apart from what sir Andersson has already shown, you can do that as well for this site:

import requests
from bs4 import BeautifulSoup
import csv

page_link = "https://portland.craigslist.org/search/sss?s={}&query=electronics&sort=date"
for link in [page_link.format(page) for page in range(0,1147,120)]: #this is the fix
    res = requests.get(link)
    soup = BeautifulSoup(res.text,'lxml')
    for container in soup.select('.result-info'):
        try:
            date = container.select('.result-date')[0].text
        except IndexError:
            date = ""
        try:
            title = container.select('.result-title')[0].text
        except IndexError:
            title = ""
        try:
            price = container.select('.result-price')[0].text
        except IndexError:
            price = ""

        print(date,title,price)
        with open("craigs_item.csv","a",newline="",encoding="utf-8") as outfile:
            writer = csv.writer(outfile)
            writer.writerow([date,title,price])


问:
Python 3.4 Find all file types and copy to directory
I am trying to create a backup program to find and copy all txt files from directory and subdirectories to another directory. I am new to python and have tried using glob and shutil modules. I added my paths to variables to make them easier to change.</p>

```<code>import os
import shutil

src= "C:/"
dest= "F:/newfolder"

src_files = os.listdir(src)
for file in src:
    filename = os.path.join(src, file)
    if file.endswith(".txt"):
        shutil.copy(file, dest)
</code>```

答:
Since Python 3.4 there is new module pathlib which can iterate over dirs and subdirs.
One possible way to do what you need is create generator which spit out all txt files. Iterate over the generator and use shutil to copy. </p>

```<code>from pathlib import Path
import shutil

src= "C:/"
dest= "F:/newfolder"

generator = (str(f) for f in Path(src).iterdir() if f.is_file() and f.suffix=='.txt')

for item in generator:
    shutil.copy2(item, dest)
</code>```

Body:
I am trying to create a backup program to find and copy all txt files from directory and subdirectories to another directory. I am new to python and have tried using glob and shutil modules. I added my paths to variables to make them easier to change.

import os
import shutil

src= "C:/"
dest= "F:/newfolder"

src_files = os.listdir(src)
for file in src:
    filename = os.path.join(src, file)
    if file.endswith(".txt"):
        shutil.copy(file, dest)

Body:
Since Python 3.4 there is new module pathlib which can iterate over dirs and subdirs.
One possible way to do what you need is create generator which spit out all txt files. Iterate over the generator and use shutil to copy.

from pathlib import Path
import shutil

src= "C:/"
dest= "F:/newfolder"

generator = (str(f) for f in Path(src).iterdir() if f.is_file() and f.suffix=='.txt')

for item in generator:
    shutil.copy2(item, dest)


问:
JSON structure PHP - strange
Im working with Google tag Manager API(v2), and trying to add some new lines to my existing JSON array. I first had some trouble adding data to my JSON object because the data was shown on the last row and not inside the object itself.

Now ive changed my code but the data does not look like its inside the object itself but im a little bit closer now. This is how my JSON object looks like now:

JSON:

```<code>{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
    }, 3, 3, 4, {
        "accountId": "17467*****",
        "containerId": "751****",
    }, 1, 1, 2],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
    }, 2, 1, 1],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
    }, 0, 0, 1],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
    }, 0, 0, 0]
}
</code>```

As you can see the object is structured like this:

1) Accountname

2) Inside Accountname we have accountId and containerId

3) at last of one Accountname object we have some numbers(count), the problem is that it looks like this:

What i would want the JSON-object to look like is like this:

```<code>{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"

    }, {
        "accountId": "17467*****",
        "containerId": "751****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"
    }],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
        "tags": "2",
        "triggers": "1",
        "variables": "1"
    }],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "1"
    }],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "0"
    }]
}
</code>```

You can see the numbers got a key and then value inside the object.

This is my PHP-code:

```<code>static public function listAllContainers() {

    try { //Because some containers might not have live-version
        $containers[] = array();
        foreach (self::listAccounts()->account as $accountKey => $account) {
            foreach (self::listAccountsContainers($account["path"]) as $account_container) {
                $containers[$account['name']][] = $account_container;

                $container_version = self::listAccountsContainersVersion($account_container['path']);
                $containers[$account['name']][] = count($container_version['tag']);
                $containers[$account['name']][] = count($container_version['trigger']);
                $containers[$account['name']][] = count($container_version['variable']);

            }
        }
        $filtered_array = (object)array_filter((array)$containers); // Removes empty object
        return $filtered_array;
    } catch (\Exception $e) {
        return $e->getCode();
    }
}
</code>```

Hope you understand my problem. Not so much experience with Arrays/JSON so maybe my explanation is not so good.
Thanks!

UPDATE:

Using $containers[$account['name']]['tag'] = count($container_version['tag']); gives me this JSON: (PS: ive removed some from the json so it wont be long, this makes the json invalid)

```<code>{
Account2: {
0: {
accountId: "174675****",
containerId: "745****",
},
1: {
accountId: "174675****59",
containerId: "751****83",
},
tag: 1,
trigger: 1,
variable: 2
},
Account 1: {
0: {
accountId: "1766***525",
containerId: "748***53",
},
tag: 2,
trigger: 1,
variable: 1
},
</code>```

Now each "Account" can have multiple "containers"(accountId,containerId), using this method does not store the data inside the object itself.

答:
If you have an array, you can add a key:value pair to it with the following syntax:

```<code>$array['key'] = 'value';
//array('key' : 'value')
</code>```

If you don't specify a key, it will just add the value:

```<code>$array[] = 'value';
//array('value')
</code>```

The last part is what you are doing now, but you add it to your $containers[...] array. What you want to do is add the values first to your $account_container array, and then add that array to your $containers[...] array. Put this in the inner foreach:

```<code>        $container_version = self::listAccountsContainersVersion($account_container['path']);

        //Add values to account_container
        $account_container['tag'] = count($container_version['tag']);
        $account_container['trigger'] = count($container_version['trigger']);
        $account_container['variable'] = count($container_version['variable']);

        // Add account_container to your $containers[..] array
        $containers[$account['name']][] = $account_container;
</code>```

Title: JSON structure PHP - strange

Body:
Im working with Google tag Manager API(v2), and trying to add some new lines to my existing JSON array. I first had some trouble adding data to my JSON object because the data was shown on the last row and not inside the object itself.

Now ive changed my code but the data does not look like its inside the object itself but im a little bit closer now. This is how my JSON object looks like now:

JSON:

{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
    }, 3, 3, 4, {
        "accountId": "17467*****",
        "containerId": "751****",
    }, 1, 1, 2],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
    }, 2, 1, 1],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
    }, 0, 0, 1],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
    }, 0, 0, 0]
}

As you can see the object is structured like this:

1) Accountname

2) Inside Accountname we have accountId and containerId

3) at last of one Accountname object we have some numbers(count), the problem is that it looks like this:

What i would want the JSON-object to look like is like this:

{
    "Account2": [{
        "accountId": "17467*****",
        "containerId": "745****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"

    }, {
        "accountId": "17467*****",
        "containerId": "751****",
        "tags": "3",
        "triggers": "3",
        "variables": "4"
    }],
    "Account 1": [{
        "accountId": "17661*****",
        "containerId": "748****",
        "tags": "2",
        "triggers": "1",
        "variables": "1"
    }],
    "GTMdocx": [{
        "accountId": "21200*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "1"
    }],
    "Account3": [{
        "accountId": "21281*****",
        "containerId": "803****",
        "tags": "0",
        "triggers": "0",
        "variables": "0"
    }]
}

You can see the numbers got a key and then value inside the object.

This is my PHP-code:

static public function listAllContainers() {

    try { //Because some containers might not have live-version
        $containers[] = array();
        foreach (self::listAccounts()->account as $accountKey => $account) {
            foreach (self::listAccountsContainers($account["path"]) as $account_container) {
                $containers[$account['name']][] = $account_container;

                $container_version = self::listAccountsContainersVersion($account_container['path']);
                $containers[$account['name']][] = count($container_version['tag']);
                $containers[$account['name']][] = count($container_version['trigger']);
                $containers[$account['name']][] = count($container_version['variable']);

            }
        }
        $filtered_array = (object)array_filter((array)$containers); // Removes empty object
        return $filtered_array;
    } catch (\Exception $e) {
        return $e->getCode();
    }
}

Hope you understand my problem. Not so much experience with Arrays/JSON so maybe my explanation is not so good.
Thanks!

UPDATE:

Using $containers[$account['name']]['tag'] = count($container_version['tag']); gives me this JSON: (PS: ive removed some from the json so it wont be long, this makes the json invalid)

{
Account2: {
0: {
accountId: "174675****",
containerId: "745****",
},
1: {
accountId: "174675****59",
containerId: "751****83",
},
tag: 1,
trigger: 1,
variable: 2
},
Account 1: {
0: {
accountId: "1766***525",
containerId: "748***53",
},
tag: 2,
trigger: 1,
variable: 1
},

Now each "Account" can have multiple "containers"(accountId,containerId), using this method does not store the data inside the object itself.

Body:
If you have an array, you can add a key:value pair to it with the following syntax:

$array['key'] = 'value';
//array('key' : 'value')

If you don't specify a key, it will just add the value:

$array[] = 'value';
//array('value')

The last part is what you are doing now, but you add it to your $containers[...] array. What you want to do is add the values first to your $account_container array, and then add that array to your $containers[...] array. Put this in the inner foreach:

        $container_version = self::listAccountsContainersVersion($account_container['path']);

        //Add values to account_container
        $account_container['tag'] = count($container_version['tag']);
        $account_container['trigger'] = count($container_version['trigger']);
        $account_container['variable'] = count($container_version['variable']);

        // Add account_container to your $containers[..] array
        $containers[$account['name']][] = $account_container;


问:
Can not create a content hierarchy inside a shared folder
I followed the steps in this post successfully, but I cannot make a new text document inside the shared folder.

I can create a top level folders inside the the shared folder, but I cannot also browse the folder to create second level folders and so on!

--

Update 1

Screenshot of Folder's Browse page

Update 2
Screenshot of Folder's Copy of Browse page

Update 3

If we browse a folder from mike's My page ,like the one in below, we got a result as in the second screenshot

答:
It is because the Folder content type has a separate custom Browse page and it is not the same as the one for the 'My page' which is a UserProfile. So if you want to make it work for folders:

Create a System Folder with the name (apps) into your 'shared folder' and a Folder in to the newly created (apps) folder with the name Folder

Copy the Browse page from the UserProfile folder (/Root/Profiles/(apps)/UserProfile) into the 'shared folder's (apps)/Folder folder

Change the list portlet on the Folder Browse page to display always the current folder (set CurrentContent as Bind Target and remove the path from the Custom Root Path input)

Check this article about sensenet smart application model which is strongly related to your question.


问:
How to get the response to post string for eg in sign up i m facing error
I m unable to signup the and i m no getting the response when i m trying to print it on on console so here is the code foe sign up form and i m unable to sign up now:</p>

```<code>    var request = URLRequest(url: URL(string: "http://fundedindia.org/funded/Doner_Registration.php")!)
    request.httpMethod = "POST"
    let postString = "Email=\(textfieldemail.text!)&Password=\(textfieldpassword.text!)&MobileNo=\(textfieldmobile.text!)&UserType=\(butname)&LoginType=Normal"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")

        }

        let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
        let msg = json.value(forKey: "message") as! NSString!

        self.activityIndi.stopAnimating()
        self.activityIndi.hidesWhenStopped = true
        let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }
    task.resume()
}
</code>```

答:
I tried to run your code with sample input

```<code>var request = URLRequest(url: URL(string: "http://fundedindia.org/funded/Doner_Registration.php")!)
    request.httpMethod = "POST"
    let email: String = "pardeep@yopmail.com"
    let password: String = "12345678"
    let mobileNo: String = "9599904029"
    let butname: String = "1"
    let postString = "Email=\(email)&Password=\(password)&MobileNo=\(mobileNo)&UserType=\(butname)&LoginType=Normal"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")

        }

        let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
        let msg = json.value(forKey: "message") as! NSString!

        let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }
    task.resume()
</code>```

Its responce status is not correct, please verify inputs and URl with your backend developer.

```<code>response = Optional(<NSHTTPURLResponse: 0x604000425fe0> { URL: http://fundedindia.org/funded/Doner_Registration.php } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 5759;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 07 Dec 2017 08:58:40 GMT";
Server = "Microsoft-IIS/8.0";
"X-Powered-By" = "ASP.NET";
"X-Powered-By-Plesk" = PleskWin;
</code>```

} })

"status code: 500" should be 200 for success.

Body:
I m unable to signup the and i m no getting the response when i m trying to print it on on console so here is the code foe sign up form and i m unable to sign up now:

    var request = URLRequest(url: URL(string: "http://fundedindia.org/funded/Doner_Registration.php")!)
    request.httpMethod = "POST"
    let postString = "Email=\(textfieldemail.text!)&Password=\(textfieldpassword.text!)&MobileNo=\(textfieldmobile.text!)&UserType=\(butname)&LoginType=Normal"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")

        }

        let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
        let msg = json.value(forKey: "message") as! NSString!

        self.activityIndi.stopAnimating()
        self.activityIndi.hidesWhenStopped = true
        let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }
    task.resume()
}

Body:
I tried to run your code with sample input

var request = URLRequest(url: URL(string: "http://fundedindia.org/funded/Doner_Registration.php")!)
    request.httpMethod = "POST"
    let email: String = "pardeep@yopmail.com"
    let password: String = "12345678"
    let mobileNo: String = "9599904029"
    let butname: String = "1"
    let postString = "Email=\(email)&Password=\(password)&MobileNo=\(mobileNo)&UserType=\(butname)&LoginType=Normal"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")

        }

        let json = try! JSONSerialization.jsonObject(with: data, options: []) as! NSDictionary
        let msg = json.value(forKey: "message") as! NSString!

        let alert : UIAlertView = UIAlertView(title: "Alert box!", message: "\(msg!).",delegate: nil, cancelButtonTitle: "OK")
        alert.show()
    }
    task.resume()

Its responce status is not correct, please verify inputs and URl with your backend developer.

response = Optional(<NSHTTPURLResponse: 0x604000425fe0> { URL: http://fundedindia.org/funded/Doner_Registration.php } { status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 5759;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 07 Dec 2017 08:58:40 GMT";
Server = "Microsoft-IIS/8.0";
"X-Powered-By" = "ASP.NET";
"X-Powered-By-Plesk" = PleskWin;

} })

"status code: 500" should be 200 for success.


问:
How to set client certificate chain in WinHttp
I am working on a client-server application where server is a web server which performs client validation based on SSL certificate. Server trust a Root CA certificate. Client is a windows application developed in C++ which has a certificate signed by intermediate CA which in turn signed by Root CA.
I am able to set client certificate during https connection by calling WinHttpSetOption api with WINHTTP_OPTION_CLIENT_CERT_CONTEXT as option. However this will set only client certificate but not the entire chain. Server does not have intermediate CA in its store hence it is not able to authenticate the client.

Is there a way to set the full client certificate chain in WinHttp, provided the full chain is already present in certificate store of client?

答: Only I could find was to Add Sub CA to system store. During service startup or installation, open the CA certificate store and Add certificate context to it.</p>


问:
How to get an integer value to a complex dictionary
Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,

```<code>    total[div]['total_transport_allowance'] = abc
</code>```

This error is shown : "KeyError: None"
Please Help

What I want from this statement is to get the abc's value to the key 'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....
```

答:
You are getting this error because div is None:

 if div:
    ....
    ....
 else:
    ...
    ...
    # div here is None or False ..
    # you cannot use it as key!!
    total[div]['total_transport_allowance'] = abc
```

<p>You need to define the key here first. so where
you want to put the abc when div is None.</p>

<p><strong>EDIT</strong></p>

<p>I don't know what the value of div should when it's not in <code>data.get('Division',False)</code>:</p>

<pre class="lang-py prettyprint-override"><code>    div = data.get('Division', False)
    ...
    ...
    if div:
       .....
    else:
        # assing a value to div
        div = 'NEW_VALUE'
        # add dictionary there
        total[div] = {}
        if 'Undefined' in total:
            ....
        ...
        ...
</code>```

Body:
Here the value of abc is an integer and total is a dictionary which contains another dictionaries.But when I run this line,

    total[div]['total_transport_allowance'] = abc

This error is shown : "KeyError: None"
Please Help

What I want from this statement is to get the abc's value to the key 'total_transport_allowance'

def print_excel_report(self,cr,uid,ids,data,context=None):
    result = self._get_lines(cr,uid,ids,data)
    filename= 'PayrollRegister.xls'
    workbook= xlwt.Workbook(encoding="UTF-8")
    sheet= workbook.add_sheet('Payroll Register',cell_overwrite_ok=True)
    style = xlwt.easyxf('font:height 400, bold True, name Arial; align: horiz center, vert center;borders: top medium,right medium,bottom medium,left medium')
    a = range(1,10)
    row = 1
    col =0
    header = ['Division','Basic','Transport Allowance']
    style2 = xlwt.easyxf('font: bold 1')
    total = {}

    for index,data in enumerate(result):
        div = data.get('Division',False)
        abc = data.get('transport_allowance',False) or 0

        if div:
            if div in total:
                total[div]['total_basic'] = total[div]['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] +  abc
            else:
                total[div] = {}
                total[div]['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc

        else:
            if 'Undefined' in total:
                total['Undefined']['total_basic'] = total['Undefined']['total_basic'] +  data.get('basic',0)
                total[div]['total_transport_allowance'] = total[div]['total_transport_allowance'] + abc

            else:
                total['Undefined'] = {}
                total['Undefined']['total_basic'] =  data.get('basic',0)
                total[div]['total_transport_allowance'] = abc
        .......
        .....

Body:
You are getting this error because div is None:

 if div:
    ....
    ....
 else:
    ...
    ...
    # div here is None or False ..
    # you cannot use it as key!!
    total[div]['total_transport_allowance'] = abc

You need to define the key here first. so where
you want to put the abc when div is None.

EDIT

I don't know what the value of div should when it's not in data.get('Division',False):

    div = data.get('Division', False)
    ...
    ...
    if div:
       .....
    else:
        # assing a value to div
        div = 'NEW_VALUE'
        # add dictionary there
        total[div] = {}
        if 'Undefined' in total:
            ....
        ...
        ...