问:
While passing id from a json to an URL, undefined value is getting passed
I've a sample JSON as given below:

```<code>[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]
</code>```

And I prepared a HTML content based on that data. Code is given below:

```<code>function prepareTopComponentList(data) {

    var preparedHtml = "";

    for (var count = 0; count < data.length; count++) {
        preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
            "                <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
            "                    <img class=\"img-fluid\" src=\"";
        preparedHtml += data[0].displayImageUrl;
        preparedHtml += "\" alt=\"N/A\">\n" +
            "                    <div class=\"card-body\">\n" +
            "                        <h4 class=\"card-title\">";
        preparedHtml += data[0].title;
        preparedHtml += "</h4>\n" +
            "                        <p class=\"card-text\">";
        preparedHtml += data[0].shortdesc;
        preparedHtml += "</p>\n" +
            "                        <a onclick = \"redirect(this, this);\" href='#' class=\"btn btn-info\" id=\"";
        preparedHtml += "component_desc_" + data[count].componentid;

        /*I replaced 0 with count so that we can get proper ids*/
        //console.log(data[0].componentid);

        preparedHtml += "\">Learn more</a>\n" +
            "                    </div>\n" +
            "\n" +
            "                </div>\n" +
            "            </div>";
    }

    $("#div_top_component").append(preparedHtml);

}
</code>```

Now, I'm redirecting to a page based on value of componentid. Redirection function code is given below:

```<code>function redirect(element, data) {
    // data = prepareTopComponentList(data);
    for (var count = 0; count < data.length; count++) {
        var url = "inside.dell.com";
        var query = data[count].componentid;
        var finalUrl = "inside.dell.com/componentid=" + query;
        console.log(finalUrl);
    }
    window.location = "inside.dell.com/componentid=" + query;
}
</code>```

When I run this code, I get this error:

```<code>The requested URL /Reusable Components/pages/inside.dell.com/componentid=undefined was not found on this server.
</code>```

That error is fine, I don't have any problem with that. However in redirection URL, component id is undefined. How do I make sure that value of component ID gets passed to URL?

答: The variable query used for windows.location is defined in the for loop block and therefore is undefined outside of it.

Body:
I've a sample JSON as given below:

[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]

And I prepared a HTML content based on that data. Code is given below:

function prepareTopComponentList(data) {

    var preparedHtml = "";

    for (var count = 0; count < data.length; count++) {
        preparedHtml += "
\n" +
            "
\n" +
            "                    \n" +
            "
\n" +
            "
";
        preparedHtml += data[0].title;
        preparedHtml += "
\n" +
            "
";
        preparedHtml += data[0].shortdesc;
        preparedHtml += "
\n" +
            "                        Learn more\n" +
            "
\n" +
            "\n" +
            "
\n" +
            "
";
    }

    $("#div_top_component").append(preparedHtml);

}

Now, I'm redirecting to a page based on value of componentid. Redirection function code is given below:

function redirect(element, data) {
    // data = prepareTopComponentList(data);
    for (var count = 0; count < data.length; count++) {
        var url = "inside.dell.com";
        var query = data[count].componentid;
        var finalUrl = "inside.dell.com/componentid=" + query;
        console.log(finalUrl);
    }
    window.location = "inside.dell.com/componentid=" + query;
}

When I run this code, I get this error:

The requested URL /Reusable Components/pages/inside.dell.com/componentid=undefined was not found on this server.

That error is fine, I don't have any problem with that. However in redirection URL, component id is undefined. How do I make sure that value of component ID gets passed to URL?


来源: stackexchange

问:
Specific regular expression not valid in C#
I am trying to Replace with C# the content inside id in this html:

```<code>    <tr class=\"ListRow EvenListRow\" id=\"e2505_735.8429.2125\">
</code>```

so I use this regular expression that works in php.

```<code>id=\\"(.*?)\\"
</code>```

Then I try to use this regular expression to do a Replace in C# in this way:

```<code>//htmlSourceReportInfo contains html information with the previous said html code.
htmlSourceReportInfo = htmlSourceReportInfo.Replace(@"(id=\\""(.*?)\\"")", "");
</code>```

It does not do anything.

答:
You can use the following:

```<code>var text = "<tr class=\"ListRow EvenListRow\" id=\"e2505_735.8429.2125\">";
string result = Regex.Replace(text, "id=\"[^\"]*\"", "id=\"\"");
</code>```

Please note that the Regex.Replace does not change the string itself, it rather returns the changed string.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to Replace with C# the content inside id in this html:

so I use this regular expression that works in php.

id=\\"(.*?)\\"

Then I try to use this regular expression to do a Replace in C# in this way:

//htmlSourceReportInfo contains html information with the previous said html code.
htmlSourceReportInfo = htmlSourceReportInfo.Replace(@"(id=\\""(.*?)\\"")", "");

It does not do anything.

Body:
You can use the following:

var text = "<tr class=\"ListRow EvenListRow\" id=\"e2505_735.8429.2125\">";
string result = Regex.Replace(text, "id=\"[^\"]*\"", "id=\"\"");

Please note that the Regex.Replace does not change the string itself, it rather returns the changed string.


问:
Difference in value
I have a simple audit table:

```<code>PersonID   Date    Value

01        1/1/17   Faulkner
01        1/2/17   Hemingway
</code>```

Which shows me where a person's surname has changed and the date this happened.

Please can someone advise if there is a report I can run / which T-SQL I should use that will just bring up when a person's surname has changed, e.g. just display row 2 above?

Suggestions /ideas very welcome.

答:
Try this:

```<code>DECLARE @DataSource TABLE
(
    [PersonId] INT
   ,[Date] DATE
   ,[value] VARCHAR(12)
);

INSERT INTO @DataSource ([PersonId], [Date], [value])
VALUES (1, '1/1/17', 'Faulkner')
      ,(1, '1/2/17', 'Hemingway')
      ,(2, '1/1/17', 'Faulkner')
      ,(3, '1/2/17', 'Faulkner 1')
      ,(3, '1/3/17', 'Faulkner 2')
      ,(3, '1/3/17', 'Faulkner 3');

;WITH CTE AS
(
    SELECT  PersonId
           ,Date
           ,Value
           ,COUNT(*) OVER (PARTITION BY PersonId) as cnt
           ,ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY [Date] DESC) as [rowID]
    FROM @DataSource
)

SELECT PersonId, Date, Value
FROM CTE
WHERE cnt > 1
    AND [rowID] = 1
ORDER BY Date;
</code>```

It will give you only records which have been updated but returning the lats value only.

Title: Difference in value

Body:
I have a simple audit table:

PersonID   Date    Value

01        1/1/17   Faulkner
01        1/2/17   Hemingway

Which shows me where a person's surname has changed and the date this happened.

Please can someone advise if there is a report I can run / which T-SQL I should use that will just bring up when a person's surname has changed, e.g. just display row 2 above?

Suggestions /ideas very welcome.

Body:
Try this:

DECLARE @DataSource TABLE
(
    [PersonId] INT
   ,[Date] DATE
   ,[value] VARCHAR(12)
);

INSERT INTO @DataSource ([PersonId], [Date], [value])
VALUES (1, '1/1/17', 'Faulkner')
      ,(1, '1/2/17', 'Hemingway')
      ,(2, '1/1/17', 'Faulkner')
      ,(3, '1/2/17', 'Faulkner 1')
      ,(3, '1/3/17', 'Faulkner 2')
      ,(3, '1/3/17', 'Faulkner 3');

;WITH CTE AS
(
    SELECT  PersonId
           ,Date
           ,Value
           ,COUNT(*) OVER (PARTITION BY PersonId) as cnt
           ,ROW_NUMBER() OVER (PARTITION BY PersonId ORDER BY [Date] DESC) as [rowID]
    FROM @DataSource
)

SELECT PersonId, Date, Value
FROM CTE
WHERE cnt > 1
    AND [rowID] = 1
ORDER BY Date;

It will give you only records which have been updated but returning the lats value only.


问:
Need of declaration of a variable in a for loop
I am newbie but cannot find the answer to this question after looking thoroughly in other questions.

Why is there a need sometimes to declare a variable and sometimes not? I give you two examples:

Example 1: here, we don't have to declare i before the for loop.

```<code>class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
</code>```

Example 2: Here we need to declare i before the loop.

```<code>class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = {
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
</code>```

I will appreciate if you could also tell me why do I have also to initialize the variable j = 0 if within the for loop I am already assigning the value 0.

答:
If you declare the loop variable within the loop, it is only accessible inside the loop.

Since, in your last snippet, you are accessing both i and j after the loop ends (in System.out.println("Found " + searchfor + " at " + i + ", " + j);), you must declare them before the loop.

That's also the reason why you have to initialize j prior to the loop. The loop may never be executed (if arrayOfInts.length is 0), but you would still access j in the mentioned println statement, so it must be initialized at this point.

Body:
I am newbie but cannot find the answer to this question after looking thoroughly in other questions.

Why is there a need sometimes to declare a variable and sometimes not? I give you two examples:

Example 1: here, we don't have to declare i before the for loop.

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }

Example 2: Here we need to declare i before the loop.

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = {
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }

I will appreciate if you could also tell me why do I have also to initialize the variable j = 0 if within the for loop I am already assigning the value 0.


答: In Example 1, i is only used within the for-loop. That's why you do not need to declare it beforehand. In Example 2, i is used in the loop, but also afterwards in the "if (foundIt)"-Block. Therefore, it must be declared outside the loop. </p>

Title: Need of declaration of a variable in a for loop


问:
UWP, how to handle images and scaling?
We have a Xamarin Forms project which shall run on Android, iOS and UWP. On Android you have a number of different images in different folder to support a vast number of different screens (and PPIs) on iOS you have a similar system (@2x, @3x etc.). I can't for the life of me find how to achive something similar for UWP. When I run the project on a Windows tablet with a recommended scaling of 150 % or 200 % all the images are also scaled up, which results in a blurry image. I can't find any thing on how to handle images in an UWP app, even for a "native" (not using Xamarin) UWP app.</p>

答:
Scaling images in UWP native is done by supplying different scaled versions in the Assets folder.

The file naming pattern is like so : ****.scale-100.png or ****.scale-200.png
The actual file name to use in your app is still ****.png but the system will auto detect the needed scaled version and use that.

For reference the doc on this is here https://learn.microsoft.com/en-us/windows/uwp/app-resources/images-tailored-for-scale-theme-contrast and here https://learn.microsoft.com/en-us/windows/uwp/app-resources/tailor-resources-lang-scale-contrast

Recommended scale factors are 100, 200 and 400.

Title: UWP, how to handle images and scaling?


问:
How to overlap two Barcharts over each other?
I am creating a Bar Chart in android. I am trying to overlap two Bar Charts on each other. I am using CombinedChart provided in the MPAndroidChart. But problem is both the Bar Charts are coming one beside another.

Here is the screenshot of the chart:

Blue bars should overlap the Green bars.

Here is my code:

```<code>public class MainActivity extends AppCompatActivity {

    private CombinedChart combinedChart;
    protected String[] mMonths = new String[] {
            "Jan", "Feb", "Mar", "Apr", "May", "June"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        combinedChart = (CombinedChart) findViewById(R.id.combinedChart);
        combinedChart.getDescription().setEnabled(false);
        combinedChart.setBackgroundColor(Color.WHITE);
        combinedChart.setDrawGridBackground(false);
        combinedChart.setDrawBarShadow(false);
        combinedChart.setHighlightFullBarEnabled(false);
        Legend l = combinedChart.getLegend();
        l.setWordWrapEnabled(true);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        YAxis rightAxis = combinedChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        YAxis leftAxis = combinedChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        XAxis xAxis = combinedChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mMonths[(int) value % mMonths.length];
            }
        });
        CombinedData data = new CombinedData();
        data.setData(generateBarData());
        combinedChart.setData(data);
        combinedChart.invalidate();
    }

    private ArrayList<BarEntry> getBar1Enteries(ArrayList<BarEntry> entries){
        entries.add(new BarEntry(1, 25));
        entries.add(new BarEntry(2, 30));
        entries.add(new BarEntry(3, 38));
        entries.add(new BarEntry(4, 10));
        entries.add(new BarEntry(5, 15));
        return  entries;
    }

    private ArrayList<BarEntry> getBar2Enteries(ArrayList<BarEntry> entries){
        entries.add(new BarEntry(1, 20));
        entries.add(new BarEntry(2, 25));
        entries.add(new BarEntry(3, 33));
        entries.add(new BarEntry(4, 5));
        entries.add(new BarEntry(5, 10));
        return  entries;
    }

    private BarData generateBarData() {

        ArrayList<BarEntry> entries1 = new ArrayList<BarEntry>();
        ArrayList<BarEntry> entries2 = new ArrayList<BarEntry>();

//        for (int index = 0; index < 12; index++) {
//            entries1.add(new BarEntry(0, getRandom(25, 25)));
//
//            // stacked
//            entries2.add(new BarEntry(0, new float[]{getRandom(13, 12), getRandom(13, 12)}));
//        }

        BarDataSet set1 = new BarDataSet(getBar1Enteries(entries1), "Bar 1");
        set1.setColor(Color.rgb(60, 220, 78));
        set1.setValueTextColor(Color.rgb(60, 220, 78));
        set1.setValueTextSize(10f);
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);

        BarDataSet set2 = new BarDataSet(getBar2Enteries(entries2), "");
        set2.setStackLabels(new String[]{"Stack 1", "Stack 2"});
        set2.setColors(new int[]{Color.rgb(61, 165, 255), Color.rgb(23, 197, 255)});
        set2.setValueTextColor(Color.rgb(61, 165, 255));
        set2.setValueTextSize(10f);
        set2.setAxisDependency(YAxis.AxisDependency.LEFT);

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
        // (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"

        BarData d = new BarData(set1, set2);
        d.setBarWidth(barWidth);

        // make this BarData object grouped
        d.groupBars(0, groupSpace, barSpace); // start at x = 0

        return d;
    }
}
</code>```

答:
You need to use Stacked BarChart

```<code>BarEntry stackedEntry = new BarEntry(0f, new float[] { 10, 20, 30 });
</code>```

You can also look into the example activity, which also contains a stacked barchart.

Body:
I am creating a Bar Chart in android. I am trying to overlap two Bar Charts on each other. I am using CombinedChart provided in the MPAndroidChart. But problem is both the Bar Charts are coming one beside another.

Here is the screenshot of the chart:

Blue bars should overlap the Green bars.

Here is my code:

public class MainActivity extends AppCompatActivity {

    private CombinedChart combinedChart;
    protected String[] mMonths = new String[] {
            "Jan", "Feb", "Mar", "Apr", "May", "June"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        combinedChart = (CombinedChart) findViewById(R.id.combinedChart);
        combinedChart.getDescription().setEnabled(false);
        combinedChart.setBackgroundColor(Color.WHITE);
        combinedChart.setDrawGridBackground(false);
        combinedChart.setDrawBarShadow(false);
        combinedChart.setHighlightFullBarEnabled(false);
        Legend l = combinedChart.getLegend();
        l.setWordWrapEnabled(true);
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);

        YAxis rightAxis = combinedChart.getAxisRight();
        rightAxis.setDrawGridLines(false);
        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        YAxis leftAxis = combinedChart.getAxisLeft();
        leftAxis.setDrawGridLines(false);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

        XAxis xAxis = combinedChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mMonths[(int) value % mMonths.length];
            }
        });
        CombinedData data = new CombinedData();
        data.setData(generateBarData());
        combinedChart.setData(data);
        combinedChart.invalidate();
    }

    private ArrayList<BarEntry> getBar1Enteries(ArrayList<BarEntry> entries){
        entries.add(new BarEntry(1, 25));
        entries.add(new BarEntry(2, 30));
        entries.add(new BarEntry(3, 38));
        entries.add(new BarEntry(4, 10));
        entries.add(new BarEntry(5, 15));
        return  entries;
    }

    private ArrayList<BarEntry> getBar2Enteries(ArrayList<BarEntry> entries){
        entries.add(new BarEntry(1, 20));
        entries.add(new BarEntry(2, 25));
        entries.add(new BarEntry(3, 33));
        entries.add(new BarEntry(4, 5));
        entries.add(new BarEntry(5, 10));
        return  entries;
    }

    private BarData generateBarData() {

        ArrayList<BarEntry> entries1 = new ArrayList<BarEntry>();
        ArrayList<BarEntry> entries2 = new ArrayList<BarEntry>();

//        for (int index = 0; index < 12; index++) {
//            entries1.add(new BarEntry(0, getRandom(25, 25)));
//
//            // stacked
//            entries2.add(new BarEntry(0, new float[]{getRandom(13, 12), getRandom(13, 12)}));
//        }

        BarDataSet set1 = new BarDataSet(getBar1Enteries(entries1), "Bar 1");
        set1.setColor(Color.rgb(60, 220, 78));
        set1.setValueTextColor(Color.rgb(60, 220, 78));
        set1.setValueTextSize(10f);
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);

        BarDataSet set2 = new BarDataSet(getBar2Enteries(entries2), "");
        set2.setStackLabels(new String[]{"Stack 1", "Stack 2"});
        set2.setColors(new int[]{Color.rgb(61, 165, 255), Color.rgb(23, 197, 255)});
        set2.setValueTextColor(Color.rgb(61, 165, 255));
        set2.setValueTextSize(10f);
        set2.setAxisDependency(YAxis.AxisDependency.LEFT);

        float groupSpace = 0.06f;
        float barSpace = 0.02f; // x2 dataset
        float barWidth = 0.45f; // x2 dataset
        // (0.45 + 0.02) * 2 + 0.06 = 1.00 -> interval per "group"

        BarData d = new BarData(set1, set2);
        d.setBarWidth(barWidth);

        // make this BarData object grouped
        d.groupBars(0, groupSpace, barSpace); // start at x = 0

        return d;
    }
}

Body:
You need to use Stacked BarChart

BarEntry stackedEntry = new BarEntry(0f, new float[] { 10, 20, 30 });

You can also look into the example activity, which also contains a stacked barchart.


问:
Error with for_each, map and lambda when passing by non-auto non-const lvalue reference
In the following code, the first for_each statement gives me errors with GCC 7.2, some of which says:

cannot bind non-const lvalue reference of type 'std::pair&' to an rvalue of type 'std::pair'

```<code>#include <algorithm>
#include <iostream>
#include <map>

int main() {
  std::map<int, double> m = { {1, 1.0}, {2, 2.0}, {3, 3.0} };

  std::for_each(std::begin(m), std::end(m),
                [](std::pair<int, double>& e){ e.second += 1.0; }); // ERROR

  std::for_each(std::begin(m), std::end(m),
                [](auto& e){ e.second += 1.0; }); // OK

  for (auto iter = std::begin(m); iter != std::end(m); ++iter)
    iter->second += 1.0;

  for (auto & e : m)
    e.second += 1.0;

  for (auto & [ key, value ] : m)
    value += 1.0;

  std::cout << m[1] << ", " << m[2] << ", " << m[3] << std::endl;
}
</code>```

What causes this error? How's that it works with auto, i.e., in the second for_each statement?

According to this answers: https://stackoverflow.com/a/14037863/580083 the first for_each should work (and I've also found another answer that said the very same).

Online code: https://wandbox.org/permlink/mOUS1NMjKooetnN1

答:
Try this:

```<code>  std::for_each(std::begin(m), std::end(m),
            [](std::pair<const int, double>& e){ e.second += 1.0; });
</code>```

It is crucial to declare Key element of pair as const. See the value_type member type in std::map documentation.

In your next line auto works, because it automatically declares Key as const.

Body:
In the following code, the first for_each statement gives me errors with GCC 7.2, some of which says:

cannot bind non-const lvalue reference of type 'std::pair&' to an rvalue of type 'std::pair'

#include <algorithm>
#include <iostream>
#include <map>

int main() {
  std::map<int, double> m = { {1, 1.0}, {2, 2.0}, {3, 3.0} };

  std::for_each(std::begin(m), std::end(m),
                [](std::pair<int, double>& e){ e.second += 1.0; }); // ERROR

  std::for_each(std::begin(m), std::end(m),
                [](auto& e){ e.second += 1.0; }); // OK

  for (auto iter = std::begin(m); iter != std::end(m); ++iter)
    iter->second += 1.0;

  for (auto & e : m)
    e.second += 1.0;

  for (auto & [ key, value ] : m)
    value += 1.0;

  std::cout << m[1] << ", " << m[2] << ", " << m[3] << std::endl;
}

What causes this error? How's that it works with auto, i.e., in the second for_each statement?

According to this answers: https://stackoverflow.com/a/14037863/580083 the first for_each should work (and I've also found another answer that said the very same).

Online code: https://wandbox.org/permlink/mOUS1NMjKooetnN1

Body:
Try this:

  std::for_each(std::begin(m), std::end(m),
            [](std::pair<const int, double>& e){ e.second += 1.0; });

It is crucial to declare Key element of pair as const. See the value_type member type in std::map documentation.

In your next line auto works, because it automatically declares Key as const.


问:
URLconf not matching URL patterns for loading a template
Python/Django beginner here. I'm running into this error:

Using the URLconf defined in learning_log.urls, Django tried these URL
  patterns, in this order:

^admin/

^$ [name='index']

^topics/$ [name='topics']

^topics/(?P\d+)/$ [name='topic']

The current URL, topics/% url 'learning_logs:topic' topic.id %}, didn't match any of these.

When I am trying to load my topic template. Here is my template:

```<code>{% extends 'learning_logs/base.html' %}

{% block content %}

<p>Topic: {{ topic }}</p>

<p>Entries:</p>
<ul>
{% for entry in entries %}
    <li>
        <p>{{ entry.date_added|date:'M d, Y H:i' }} </p>
        <p>{{ entry.text|linebreaks }}</p>
    </li>
{% empty %}
    <li>
        There are no entries for this topic yet.
    </li>
{% endfor %}
</ul>

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

This is my views.py:

```<code>from django.shortcuts import render
from .models import Topic

def index(request):
    '''The home page for Learning Log'''
    return render(request, 'learning_logs/index.html')

def topics(request):
    '''Show all topics.'''
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    '''Show a single topic and all its entries.'''
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)
</code>```

And this is my urls.py code:

```<code>'''Defines URL patterns for learning_logs.'''

from django.conf.urls import url

from . import views

urlpatterns = [
    # Home page
    url(r'^$', views.index, name='index'),

    # Show all topics.
    url(r'^topics/$', views.topics, name='topics'),

    # Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')
]
</code>```

I am using Python Crash Course: A Hands-On, Project-Based Introduction to Programming for my tutorials.

Any help would be much appreciated.

答:
it will be like this

```<code>url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')
</code>```

There are error with this expression: unbalanced parenthesis.

Body:
Python/Django beginner here. I'm running into this error:

Using the URLconf defined in learning_log.urls, Django tried these URL
  patterns, in this order:

^admin/

^$ [name='index']

^topics/$ [name='topics']

^topics/(?P\d+)/$ [name='topic']

The current URL, topics/% url 'learning_logs:topic' topic.id %}, didn't match any of these.

When I am trying to load my topic template. Here is my template:

{% extends 'learning_logs/base.html' %}

{% block content %}

Topic: {{ topic }}

Entries:

{% for entry in entries %}

{{ entry.date_added|date:'M d, Y H:i' }}

{{ entry.text|linebreaks }}

{% empty %}

        There are no entries for this topic yet.

{% endfor %}

{% endblock content %}

This is my views.py:

from django.shortcuts import render
from .models import Topic

def index(request):
    '''The home page for Learning Log'''
    return render(request, 'learning_logs/index.html')

def topics(request):
    '''Show all topics.'''
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    '''Show a single topic and all its entries.'''
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

And this is my urls.py code:

'''Defines URL patterns for learning_logs.'''

from django.conf.urls import url

from . import views

urlpatterns = [
    # Home page
    url(r'^$', views.index, name='index'),

    # Show all topics.
    url(r'^topics/$', views.topics, name='topics'),

    # Detail page for a single topic
    url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')
]

I am using Python Crash Course: A Hands-On, Project-Based Introduction to Programming for my tutorials.

Any help would be much appreciated.

Body:
it will be like this

url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic')

There are error with this expression: unbalanced parenthesis.


问:
React-Native Error - "[TypeError: undefined is not an object (evaluating '_this2._OnAlert(count)')]"
I am trying to build a sample app which pops up an alert displaying the number of objects in the response of an API. The alert pops up once but afterwards, I am getting this error

```<code>[TypeError: undefined is not an object (evaluating '_this2._OnAlert(count)')]
</code>```

This is my code

```<code>import React from 'react';
import { View, Button, Alert } from 'react-native';
import ProductListingItem from './ProductListingItem';

export default class ProductDetailedListingPage extends React.Component {
  constructor() {
    super();

 }

 _OnAlert(count){
    console.log('_onAlert');
    console.log('count = '+ count);
    Alert.alert(
      'API call success',
      count+' objects',
      [
        {text:'done',onPress: () => { }}
      ]
    );
  }

 _getResponseFromApi(){
    console.log('_getREsponseFromApi called');
    var myRequest = new Request('http://mysampleapi.com:8082/listProducts',);
    myRequest.method = 'GET';
    return fetch(myRequest)
      .then((response)=> response.json())
      .then((responseJson) => {
        var data = responseJson.error;
        console.log('data = '+data);
        /*console.log(responseJson);*/
        var count = Object.keys(responseJson).length;
         count = '2';
         console.log('count in _getResponseFromApi = '+count);
        this._OnAlert(count);
        return responseJson;
      })
      .catch((error) => {
        console.log(error);
      });
  }

 componentDidMount () {
    console.log('componentDidMount');
    this._getResponseFromApi();
  }
  componentWillMount () {
    console.log('componentWillMount');
  }

 render(){
    console.log('render');
    return(
      <View style = {{
        flex:1,
        flexDirection:'column',
      }}>
      <Button style ={{flex:1}}
        onPress ={this._getResponseFromApi}
        title ="Call"
        />

     </View>
    );
  }
}
</code>```

The problem is with _OnAlert() , it runs for the first time at componentDidMount() without issues and displays the alert dialog, but at the instance of onPress() it gives me the above mentioned error. I am a noob when it comes to React and Javascript, especially JSX. How can I fix this issue?

答:
You should change your constructor and bind the method '_getResponseFromApi' to the scope here,</p>

```<code>constructor() {
super();
  this._getResponseFromApi = this._getResponseFromApi.bind(this);
}
</code>```

Body:
I am trying to build a sample app which pops up an alert displaying the number of objects in the response of an API. The alert pops up once but afterwards, I am getting this error

[TypeError: undefined is not an object (evaluating '_this2._OnAlert(count)')]

This is my code

import React from 'react';
import { View, Button, Alert } from 'react-native';
import ProductListingItem from './ProductListingItem';

export default class ProductDetailedListingPage extends React.Component {
  constructor() {
    super();

 }

 _OnAlert(count){
    console.log('_onAlert');
    console.log('count = '+ count);
    Alert.alert(
      'API call success',
      count+' objects',
      [
        {text:'done',onPress: () => { }}
      ]
    );
  }

 _getResponseFromApi(){
    console.log('_getREsponseFromApi called');
    var myRequest = new Request('http://mysampleapi.com:8082/listProducts',);
    myRequest.method = 'GET';
    return fetch(myRequest)
      .then((response)=> response.json())
      .then((responseJson) => {
        var data = responseJson.error;
        console.log('data = '+data);
        /*console.log(responseJson);*/
        var count = Object.keys(responseJson).length;
         count = '2';
         console.log('count in _getResponseFromApi = '+count);
        this._OnAlert(count);
        return responseJson;
      })
      .catch((error) => {
        console.log(error);
      });
  }

 componentDidMount () {
    console.log('componentDidMount');
    this._getResponseFromApi();
  }
  componentWillMount () {
    console.log('componentWillMount');
  }

 render(){
    console.log('render');
    return(
      <View style = {{
        flex:1,
        flexDirection:'column',
      }}>
      <Button style ={{flex:1}}
        onPress ={this._getResponseFromApi}
        title ="Call"
        />

     </View>
    );
  }
}

The problem is with _OnAlert() , it runs for the first time at componentDidMount() without issues and displays the alert dialog, but at the instance of onPress() it gives me the above mentioned error. I am a noob when it comes to React and Javascript, especially JSX. How can I fix this issue?

Body:
You should change your constructor and bind the method '_getResponseFromApi' to the scope here,

constructor() {
super();
  this._getResponseFromApi = this._getResponseFromApi.bind(this);
}


问:
How to create a custom form using CRUD controller in sonata admin bundle?
I'm a beginner in sonata admin, I need to know how to create custom form using route and controller and index.html.twig.</p>

```<code>   app.admin.category:
        class: AppBundle\Admin\CategoryAdmin
        arguments: [~, AppBundle\Entity\Category, SonataAdminBundle:CRUD]
        tags:
            - { name: sonata.admin, manager_type: orm, group: adminn, label: Category }
        public: true
</code>```

答:
You need to create CRUD controller. For each admin service you have default one and you can overwrite it.
In your case, service is app.admin.category

How to create CRUD controller? I am going to explain the most simple way.

Create class in your AppBundle/Controller/Admin/folder and call it CategoryAdminController.
Here is code of your class:

```<code><?php

namespace AppBundle\Controller\Admin;

use Sonata\AdminBundle\Controller\CRUDController;

/**
 * Class CategoryAdminController
 * @package AppBundle\Controller\Admin\
 */
class CategoryAdminController extends CRUDController
{
}
</code>```

As you can see this class extends default SonataAdminCRUDController.

Then point to your sonata service that it has to use this class as it's CRUDContoller.
In your service.yml change the stndard CRUD controller:

app.admin.category:
    class: AppBundle\Admin\CategoryAdmin
    arguments: [~, AppBundle\Entity\Category, AppBundle:Admin\CategoryAdmin]
    tags:
        - { name: sonata.admin, manager_type: orm, group: adminn, label: Category }
    public: true

Now you are ready to make your new action in your new Controller. Let's call it changeAction.

```<code> /**
  * @param int $id
  *
  * @return Response
  */
 public function changeAction($id = null)
 {
     try {
        if ($id !== null) {
            $category = $this->admin->getObject($id);
        }
    } catch (NotFoundHttpException $e) {
        error_log($e->getMessage());
    }

    // .. Here is a code of creating your custom form with variable $form

    return $this->render('@App/Admin/CRUD/index.html.twig', [
        'custom_form' => $form->createView(),
    ]);
 }
</code>```

Make the route to your new action! In your CategoryAdmin service overwrite configureRoutes() method

```<code>/**
 * @param RouteCollection $collection
 */
protected function configureRoutes(RouteCollection $collection)
{
    $collection->add('change', $this->getRouterIdParameter().'/change');
}
</code>```

Finally - we can make the button to our route:

```<code>/**
 * @param ListMapper $listMapper
 */
protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        //.. Your fields...
        ->add('_action', 'actions', [
            'label' => ' ',
            'actions' => [
                //'show' => array(),    // I removed show action button, but you can uncomment
                //'edit' => array(),    // I removed edit action button, but you can uncomment
                //'delete' => array(),  // I removed delete action button, but you can uncomment
            'change' => [
                    'template' => 'AppBundle::Admin\CRUD\Buttons\change_category_button.html.twig',
                ]
            ]
        ])
    ;
}
</code>```

And of course don't forget to create a twig template for your new button and place it in right place AppBundle/Resources/views/Admin/CRUD/Buttons/:

```<code>//'AppBundle::Admin\CRUD\Buttons\change_category_button.html.twig':

{% if admin.isGranted('EDIT', object) and admin.hasRoute('change') %}
    <a href="{{ admin.generateObjectUrl('change', object) }}" class="btn btn-sm btn-primary edit_link" title="Your title here"  style="display: inline-block">
        <i class="fa fa-toggle-on"> </i>
        Change Button
    </a>
{% endif %}
</code>```

Body:
I'm a beginner in sonata admin, I need to know how to create custom form using route and controller and index.html.twig.

   app.admin.category:
        class: AppBundle\Admin\CategoryAdmin
        arguments: [~, AppBundle\Entity\Category, SonataAdminBundle:CRUD]
        tags:
            - { name: sonata.admin, manager_type: orm, group: adminn, label: Category }
        public: true

Body:
You need to create CRUD controller. For each admin service you have default one and you can overwrite it.
In your case, service is app.admin.category

How to create CRUD controller? I am going to explain the most simple way.

Create class in your AppBundle/Controller/Admin/folder and call it CategoryAdminController.
Here is code of your class:

<?php

namespace AppBundle\Controller\Admin;

use Sonata\AdminBundle\Controller\CRUDController;

/**
 * Class CategoryAdminController
 * @package AppBundle\Controller\Admin\
 */
class CategoryAdminController extends CRUDController
{
}

As you can see this class extends default SonataAdminCRUDController.

Then point to your sonata service that it has to use this class as it's CRUDContoller.
In your service.yml change the stndard CRUD controller:

app.admin.category:
    class: AppBundle\Admin\CategoryAdmin
    arguments: [~, AppBundle\Entity\Category, AppBundle:Admin\CategoryAdmin]
    tags:
        - { name: sonata.admin, manager_type: orm, group: adminn, label: Category }
    public: true

Now you are ready to make your new action in your new Controller. Let's call it changeAction.

 /**
  * @param int $id
  *
  * @return Response
  */
 public function changeAction($id = null)
 {
     try {
        if ($id !== null) {
            $category = $this->admin->getObject($id);
        }
    } catch (NotFoundHttpException $e) {
        error_log($e->getMessage());
    }

    // .. Here is a code of creating your custom form with variable $form

    return $this->render('@App/Admin/CRUD/index.html.twig', [
        'custom_form' => $form->createView(),
    ]);
 }

Make the route to your new action! In your CategoryAdmin service overwrite configureRoutes() method

/**
 * @param RouteCollection $collection
 */
protected function configureRoutes(RouteCollection $collection)
{
    $collection->add('change', $this->getRouterIdParameter().'/change');
}

Finally - we can make the button to our route:

/**
 * @param ListMapper $listMapper
 */
protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        //.. Your fields...
        ->add('_action', 'actions', [
            'label' => ' ',
            'actions' => [
                //'show' => array(),    // I removed show action button, but you can uncomment
                //'edit' => array(),    // I removed edit action button, but you can uncomment
                //'delete' => array(),  // I removed delete action button, but you can uncomment
            'change' => [
                    'template' => 'AppBundle::Admin\CRUD\Buttons\change_category_button.html.twig',
                ]
            ]
        ])
    ;
}

And of course don't forget to create a twig template for your new button and place it in right place AppBundle/Resources/views/Admin/CRUD/Buttons/:

//'AppBundle::Admin\CRUD\Buttons\change_category_button.html.twig':

{% if admin.isGranted('EDIT', object) and admin.hasRoute('change') %}
    <a href="{{ admin.generateObjectUrl('change', object) }}" class="btn btn-sm btn-primary edit_link" title="Your title here"  style="display: inline-block">
        <i class="fa fa-toggle-on"> </i>
        Change Button
    </a>
{% endif %}


问:
r - Collapse multiple rows in one following multiple conditions with tidyr
i have a database structure like this

```<code> A   B   C
 n   1   M
 n   2   U
 n   1   U
 f   3   M
 f   4   M
 f   1   U
</code>```

using the package tidyr, I want to obtain this result:

```<code> A   B   C
 n   1   M
 n   3   U
 f   7   M
 f   1   U
</code>```

So I want to make a sum of the b value characterized by the same A value and, obtained this sub set, collapsing B value in relation to the same C value.

How could I do?

答:
```<code>library(dplyr)
df %>%
  group_by(A,C) %>%
  summarize(B=sum(B)) %>%
  data.frame()
</code>```

Body:
i have a database structure like this

 A   B   C
 n   1   M
 n   2   U
 n   1   U
 f   3   M
 f   4   M
 f   1   U

using the package tidyr, I want to obtain this result:

 A   B   C
 n   1   M
 n   3   U
 f   7   M
 f   1   U

So I want to make a sum of the b value characterized by the same A value and, obtained this sub set, collapsing B value in relation to the same C value.

How could I do?

ContentLicense: CC BY-SA 4.0


问:
Using Parameters httpClient and generated Url in request in Angular 4
Iam using httpGet to access Lumen web api server with 4 parameters in angular 4, this is my web api url : http://sismonev.api/member/2017/8, they have 2 parameter year and month and member key. in my angular4 component bellow my code :

```<code> let params = new HttpParams();
    params = params.append('tahun', '2017');
    params = params.append('bulan', '5');

   this.http.get<JuResponse>(environment.url + '/member', {params: params})
              .subscribe(data => {
                        for (var i = 0; i < data.length; i++) {
                        let pd=+data[i].jumlah; // comvert to number
                          this.pieD.push(pd);
                          this.pieChartLabels.push(data[i].jenis_bu);
                      }
                      this.pieChartData=this.pieD;
                      console.log(this.pieChartData);
                  },
                  err => {
                      console.log("Error occured.")
                  });
</code>```

this not working, because angular generated like this :

```<code>http://sismonev.api/member?year=2017&month=8
</code>```

Lumen web api give the error like this :

```<code>NotFoundHttpException in RoutesRequests.php line 596:
</code>```

Could anyone give me explanation? how to generate url to access web api with this http://sismonev.api/member/2017/8 format.

thank you

答:
Try this, year and month are variables.

```<code>let year = '2017';
let month = '8';
this.http.get<JuResponse>(`&{environment.url}/member/${year}/${month}`)
</code>```

function could be something like:

```<code>getPieChartDateFor(month:string, year:string){...}
</code>```

Body:
Iam using httpGet to access Lumen web api server with 4 parameters in angular 4, this is my web api url : http://sismonev.api/member/2017/8, they have 2 parameter year and month and member key. in my angular4 component bellow my code :

 let params = new HttpParams();
    params = params.append('tahun', '2017');
    params = params.append('bulan', '5');

   this.http.get<JuResponse>(environment.url + '/member', {params: params})
              .subscribe(data => {
                        for (var i = 0; i < data.length; i++) {
                        let pd=+data[i].jumlah; // comvert to number
                          this.pieD.push(pd);
                          this.pieChartLabels.push(data[i].jenis_bu);
                      }
                      this.pieChartData=this.pieD;
                      console.log(this.pieChartData);
                  },
                  err => {
                      console.log("Error occured.")
                  });

this not working, because angular generated like this :

http://sismonev.api/member?year=2017&month=8

Lumen web api give the error like this :

NotFoundHttpException in RoutesRequests.php line 596:

Could anyone give me explanation? how to generate url to access web api with this http://sismonev.api/member/2017/8 format.

thank you

Body:
Try this, year and month are variables.

let year = '2017';
let month = '8';
this.http.get<JuResponse>(`&{environment.url}/member/${year}/${month}`)

function could be something like:

getPieChartDateFor(month:string, year:string){...}


问:
Liferay Delegate Servlet cannot access liferay utility beans
I am trying to build a delegate servlet in Liferay that needs to know the list of connected users in Liferay (using com.liferay.portal.service.UserLocalServiceUtil)

I had no problem getting a simple delegated servlet to work and say Hello when deployed in Liferay, but when I try to use UserLocalServiceUtil I get this exception

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'com.liferay.portal.service.UserLocalService' is defined
</code>```

Reading docs it seems that a delegate server could access core portal utilities, but could I be wrong. Any help or advice will be appreciated.

This is the servlet

```<code>package mycompany.liferay;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.service.UserServiceUtil;
import com.liferay.portal.model.User;
import java.util.List;

public class myDelegateServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

       try {

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>My delegate Servlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>My delegate Servlet at " + request.getContextPath() + "</h1>");

            int userCount = UserLocalServiceUtil.getUsersCount();
            List<User> users = UserLocalServiceUtil.getUsers(0, userCount);

            out.print("<br>Connected Users:<br>");
            for (User user : users)
              {
               out.print("<li>User: "+user.getUserId()+"</li>" );
              }

            out.println("</body>");
            out.println("</html>");

        }
        catch (Exception e)
            {
             out.print("Exception! "+e.getMessage() );
             }
        finally {
            out.close();
        }
    }
...
</code>```

and this its definition at web.xml

```<code><servlet>
    <servlet-name>myDelegateServlet</servlet-name>
    <servlet-class>com.liferay.portal.kernel.servlet.PortalDelegateServlet</servlet-class>
    <init-param>
        <param-name>servlet-class</param-name>
        <param-value>mycompany.liferay.myDelegateServlet</param-value>
    </init-param>
    <init-param>
        <param-name>sub-context</param-name>
        <param-value>myDelegateServlet</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
</code>```

答:
Have a look at this sample servlet. https://github.com/liferay/liferay-blade-samples/tree/master/gradle/extensions/servlet. The approach that you mentioned is more for the 6.2 version.

Then when you have the OSGi component you can easily inject services.

```<code>@Reference
private UserLocalService servcie;
</code>```

You need to have the dependency org.osgi:org.osgi.service.component.annotations:1.3.0

Alternatively have a look at the JAX-RS interface

Body:
I am trying to build a delegate servlet in Liferay that needs to know the list of connected users in Liferay (using com.liferay.portal.service.UserLocalServiceUtil)

I had no problem getting a simple delegated servlet to work and say Hello when deployed in Liferay, but when I try to use UserLocalServiceUtil I get this exception

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'com.liferay.portal.service.UserLocalService' is defined

Reading docs it seems that a delegate server could access core portal utilities, but could I be wrong. Any help or advice will be appreciated.

This is the servlet

package mycompany.liferay;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liferay.portal.service.UserLocalServiceUtil;
import com.liferay.portal.service.UserServiceUtil;
import com.liferay.portal.model.User;
import java.util.List;

public class myDelegateServlet extends HttpServlet {

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

       try {

            out.println("<!DOCTYPE html>");
            out.println("");
            out.println("");
            out.println("<title>My delegate Servlet</title>");
            out.println("");
            out.println("");
            out.println("
My delegate Servlet at " + request.getContextPath() + "
");

            int userCount = UserLocalServiceUtil.getUsersCount();
            List<User> users = UserLocalServiceUtil.getUsers(0, userCount);

            out.print("
Connected Users:
");
            for (User user : users)
              {
               out.print("
User: "+user.getUserId()+"
" );
              }

            out.println("");
            out.println("");

        }
        catch (Exception e)
            {
             out.print("Exception! "+e.getMessage() );
             }
        finally {
            out.close();
        }
    }
...

and this its definition at web.xml

<servlet>
    <servlet-name>myDelegateServlet</servlet-name>
    <servlet-class>com.liferay.portal.kernel.servlet.PortalDelegateServlet</servlet-class>
    <init-param>
        <param-name>servlet-class</param-name>
        <param-value>mycompany.liferay.myDelegateServlet</param-value>
    </init-param>
    <init-param>
        <param-name>sub-context</param-name>
        <param-value>myDelegateServlet</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Body:
Have a look at this sample servlet. https://github.com/liferay/liferay-blade-samples/tree/master/gradle/extensions/servlet. The approach that you mentioned is more for the 6.2 version.

Then when you have the OSGi component you can easily inject services.

@Reference
private UserLocalService servcie;

You need to have the dependency org.osgi:org.osgi.service.component.annotations:1.3.0

Alternatively have a look at the JAX-RS interface


问:
JSON Array request cannot be applied error listener
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

```<code>private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }
</code>```

答:
You have passed wrong parameter in your JSONArryRequest, You need to pass URL (String) and your response listeners.</p>

```<code>   JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,"http://example.com/feed.json",
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                             //Your code
                       }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(MainActivity.this, "Unable to fetch data: " + volleyError.getMessage(), Toast.LENGTH_SHORT).show();
                    }
    });
</code>```

Body:
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }

Body:
You have passed wrong parameter in your JSONArryRequest, You need to pass URL (String) and your response listeners.

   JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,"http://example.com/feed.json",
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray jsonArray) {
                             //Your code
                       }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(MainActivity.this, "Unable to fetch data: " + volleyError.getMessage(), Toast.LENGTH_SHORT).show();
                    }
    });


答:
So in my comment above I said easily. The problem, however, is the fact that the data is very flat at the end. Cubic and higher order interpolation do not like flat data. They tend to oscillate. The trick would be, as mentioned by @f5r5e5d, to rescale the data in such a way that the flat part becomes very short. In this case a double-log-scale seems OK. Unfortunately, this does not work with y = 0 values. Hence, either one has to remove this value or choose a reasonable small value for it (but not too small as on a double-log-scale that point would drift off).

```<code>import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

xList = [0.078130000000000005, 0.15626000000000001, 0.31252000000000002, 0.62504000000000004, 1.2500800000000001, 2.5001600000000002, 5.0003200000000003, 10.000640000000001, 20.001280000000001]

yList = [ 1.0512499897262986, 0.8764973224043381, 0.6221799472771921, 0.3760124741123981, 0.19346808043817057, 0.08474951460350254, 0.0316071940839253, 0.010035880788326037, 0.0]

yList[-1] = 1.e-5 ###manually put a value for the zero

xLogList = [ np.log( x ) for x in xList ]
yLogList = [ np.log( y ) for y in yList ]
f = interp1d(xLogList, yLogList, kind='cubic')
xInterLogList = np.linspace( np.log( xList[0] ), np.log( xList[-1] ), 100 )
yInterLogList = [ f( x ) for x in xInterLogList ]

fig1=plt.figure()
ax=fig1.add_subplot( 1, 1, 1 )

ax.plot(xList, yList)
ax.plot( [ np.exp( x ) for x in xInterLogList  ], [ np.exp( y ) for y in yInterLogList ] )

plt.show()
</code>```

In blue the original data, in orange the smooth interpolation.

Title: How to interpolate a curve with irregular scale?

Body:
I have the following granulometric data that I want to show on a graph, where x is the grain size and y, the probability density function. x follows a geometric sequence (each value multiplied by 2)

x: [0.0, 0.078130000000000005, 0.15626000000000001, 0.31252000000000002, 0.62504000000000004, 1.2500800000000001, 2.5001600000000002, 5.0003200000000003, 10.000640000000001, 20.001280000000001]

y:  [0.0, 1.0512499897262986, 0.8764973224043381, 0.6221799472771921, 0.3760124741123981, 0.19346808043817057, 0.08474951460350254, 0.0316071940839253, 0.010035880788326037, 0.0]

Here is the graph:

I've been trying to smooth the curve like Excel does. I've tried using interp1d (all methods), spline, Akima1DInterpolator.

Body:
So in my comment above I said easily. The problem, however, is the fact that the data is very flat at the end. Cubic and higher order interpolation do not like flat data. They tend to oscillate. The trick would be, as mentioned by @f5r5e5d, to rescale the data in such a way that the flat part becomes very short. In this case a double-log-scale seems OK. Unfortunately, this does not work with y = 0 values. Hence, either one has to remove this value or choose a reasonable small value for it (but not too small as on a double-log-scale that point would drift off).

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

xList = [0.078130000000000005, 0.15626000000000001, 0.31252000000000002, 0.62504000000000004, 1.2500800000000001, 2.5001600000000002, 5.0003200000000003, 10.000640000000001, 20.001280000000001]

yList = [ 1.0512499897262986, 0.8764973224043381, 0.6221799472771921, 0.3760124741123981, 0.19346808043817057, 0.08474951460350254, 0.0316071940839253, 0.010035880788326037, 0.0]

yList[-1] = 1.e-5 ###manually put a value for the zero

xLogList = [ np.log( x ) for x in xList ]
yLogList = [ np.log( y ) for y in yList ]
f = interp1d(xLogList, yLogList, kind='cubic')
xInterLogList = np.linspace( np.log( xList[0] ), np.log( xList[-1] ), 100 )
yInterLogList = [ f( x ) for x in xInterLogList ]

fig1=plt.figure()
ax=fig1.add_subplot( 1, 1, 1 )

ax.plot(xList, yList)
ax.plot( [ np.exp( x ) for x in xInterLogList  ], [ np.exp( y ) for y in yInterLogList ] )

plt.show()

In blue the original data, in orange the smooth interpolation.


问:
fast/right way to create Domain-Objects out of database
i have in the database typical tables like user, usergroup, and they have relations.

in my domain-model i want that if you request users, you will get the users and each user has the property belongsto, which means these are the groups he belongs to. in the property i want to have the list of groups (typesafe as groups)

the same should be done on the other hand, that means each group should know which users belong to the group.

i have this classes (example):

```<code>public class User
{
    int Id { get; set; }
    string Name { get; set; }
    List<Usergroup> BelongsTo { get; set; }

    User()
    {
        BelongsTo = new List<Usergroup>();
    }
}

public class Usergroup
{
    int Id { get; set; }
    string Name { get; set; }
    List<User> Users { get; set; }

    Usergroup()
    {
        Users = new List<User>();
    }
}

internal class Relation
{
    int userId;
    int groupId;
}
</code>```

now, whats the best way to implement it, and whats the fastest way to get all objects filled.

btw: i'm using subsonic to get all the database-records (for each table one select). and there are at least 1500 user and 30 groups.

my current code is based on foreach over the groups, relations.where for the groups, and then users.singleordefault to find the user and then add the user to the group and the group to the user. but it takes appx 30secs to do this.

my client-app is a webapp, so i store the results after all in a cached repository, thats why i'm doing it in this way!!

答:
The best thing is to only retrieve the entity that was requested by the client but allow that entity to expose a method for retrieving all its related entities from the database.  You shouldn't attempt to pull everything back at once from the database as you are not certain if the client even needs this data.

Do something like this:

```<code>public class User
{
    int Id { get; set; }
    string Name { get; set; }

    public List<Usergroup> GetUserGroups()
    {
        // go and get the user groups
    }
}
</code>```

If you wanted to you could create a property that would hold this value as a member of the User class and use the GetUserGroups method to lazy-load the value for you.

ContentLicense: CC BY-SA 2.5

Body:
i have in the database typical tables like user, usergroup, and they have relations.

in my domain-model i want that if you request users, you will get the users and each user has the property belongsto, which means these are the groups he belongs to. in the property i want to have the list of groups (typesafe as groups)

the same should be done on the other hand, that means each group should know which users belong to the group.

i have this classes (example):

public class User
{
    int Id { get; set; }
    string Name { get; set; }
    List<Usergroup> BelongsTo { get; set; }

    User()
    {
        BelongsTo = new List<Usergroup>();
    }
}

public class Usergroup
{
    int Id { get; set; }
    string Name { get; set; }
    List<User> Users { get; set; }

    Usergroup()
    {
        Users = new List<User>();
    }
}

internal class Relation
{
    int userId;
    int groupId;
}

now, whats the best way to implement it, and whats the fastest way to get all objects filled.

btw: i'm using subsonic to get all the database-records (for each table one select). and there are at least 1500 user and 30 groups.

my current code is based on foreach over the groups, relations.where for the groups, and then users.singleordefault to find the user and then add the user to the group and the group to the user. but it takes appx 30secs to do this.

my client-app is a webapp, so i store the results after all in a cached repository, thats why i'm doing it in this way!!

Body:
The best thing is to only retrieve the entity that was requested by the client but allow that entity to expose a method for retrieving all its related entities from the database.  You shouldn't attempt to pull everything back at once from the database as you are not certain if the client even needs this data.

Do something like this:

public class User
{
    int Id { get; set; }
    string Name { get; set; }

    public List<Usergroup> GetUserGroups()
    {
        // go and get the user groups
    }
}

If you wanted to you could create a property that would hold this value as a member of the User class and use the GetUserGroups method to lazy-load the value for you.

OwnerDisplayName: Andrew Hare


问:
copy_if in C++...having troubles
I'm trying to use the copy_if in my program. I would like to copy every 3 elements the values of one array into another one.

basically, I wrote a program like this:

```<code>#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
    int16_t *array;
    int16_t *new_array;

    array = new int16_t[10]();
    new_array = new int16_t[4]();

    array[0] = 9;
    array[1] = 1;
    array[2] = 50;
    array[3] = 30;
    array[4] = 3;
    array[5] = 24;
    array[6] = 66;
    array[7] = 73;
    array[8] = 108;
    array[9] = 10;

    copy_if(array, array+9, new_array, [&] (const int& i) -> bool
    { size_t index = i -array[0]; return index % 3 == 0; });

    for (int jj = 0; jj < 4; jj++) {
        cout << "new_array[" << jj << "] = " << new_array[jj] << endl;
    }
}
</code>```

The final result SHOULD be like

```<code>new_array[0] = 9
new_array[1] = 30
new_array[2] = 66
new_array[3] = 10
</code>```

but I obtain:

```<code>new_array[0] = 9
new_array[1] = 30
new_array[2] = 24
new_array[3] = 66
</code>```

I saw many times the copy_if used with vector but problay i'm missing something since i'm using pointers.

答:
i is the element, not a pointer to it. Your predicate is wrong, since it relies on the values of the array elements, not their position. It should be:

```<code>size_t index = &i - &array[0]; return index % 3 == 0;
</code>```

Now it calculates the position with pointer arithmetic. Bear in mind that such a predicate can only work for contiguous storage: A c-array, a std::array or a std::vector.

Title: copy_if in C++...having troubles

Body:
I'm trying to use the copy_if in my program. I would like to copy every 3 elements the values of one array into another one.

basically, I wrote a program like this:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int argc, char *argv[])
{
    int16_t *array;
    int16_t *new_array;

    array = new int16_t[10]();
    new_array = new int16_t[4]();

    array[0] = 9;
    array[1] = 1;
    array[2] = 50;
    array[3] = 30;
    array[4] = 3;
    array[5] = 24;
    array[6] = 66;
    array[7] = 73;
    array[8] = 108;
    array[9] = 10;

    copy_if(array, array+9, new_array, [&] (const int& i) -> bool
    { size_t index = i -array[0]; return index % 3 == 0; });

    for (int jj = 0; jj < 4; jj++) {
        cout << "new_array[" << jj << "] = " << new_array[jj] << endl;
    }
}

The final result SHOULD be like

new_array[0] = 9
new_array[1] = 30
new_array[2] = 66
new_array[3] = 10

but I obtain:

new_array[0] = 9
new_array[1] = 30
new_array[2] = 24
new_array[3] = 66

I saw many times the copy_if used with vector but problay i'm missing something since i'm using pointers.

Body:
i is the element, not a pointer to it. Your predicate is wrong, since it relies on the values of the array elements, not their position. It should be:

size_t index = &i - &array[0]; return index % 3 == 0;

Now it calculates the position with pointer arithmetic. Bear in mind that such a predicate can only work for contiguous storage: A c-array, a std::array or a std::vector.


问:
Return a authentication token
I am using devise_auth_token gem in my rails-api app. I used omniauth_google_oauth2 gem with my app for auth but it was very buggy so I decided to follow a different approach.

I have a route in my api app that will response

```<code>{ "url": google-oauth-login-url }
</code>```

The frontend app use that route to put it in the login with google btn.

After a user click in the btn they will be redirected to google oauth page and after filling in the details they will be then redirected to the frontend home page with the google code in the url.

The frontend app will send a req to the api server with the code and the server will req to the google server again to exchange that google code for access-token, refresh token and all that.

After the server receives those token, the server again makes another req to the google server to fetch user profile.

I dont know how to register the user after I get the user profile info.

How do i register it ? After registering it, how do I sign it in or send a  authentication token to the frontend app? The authentication token will be used in every headers while making the api call.

Any idea?

答:
I had to dive into the gem code to get this right

```<code>def log_in_or_create_employee(user_info)
    @resource = Employee.find_by email: user_info["emails"][0]["value"]
    if @resource.nil?
        password = Devise.friendly_token[0,10]
        @resource = Employee.new({
            name: user_info["displayName"],
            admin: true,
            first_name: CustomRegex.japanese?(user_info["name"]["givenName"]) ? '' : user_info["name"]["givenName"],
            last_name: CustomRegex.japanese?(user_info["name"]["familyName"]) ? '' : user_info["name"]["familyName"],
            email: user_info["emails"][0]["value"],
            password: password,
            password_confirmation: password
            })
    end
        @client_id = SecureRandom.urlsafe_base64(nil, false)
  @token     = SecureRandom.urlsafe_base64(nil, false)
  @resource.tokens[@client_id] = {
          token: BCrypt::Password.create(@token),
          expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
  }
  @resource.skip_confirmation!
        @resource.save!

        return render json: {client_id: @client_id, expiry: @resource.tokens[@client_id][:"expiry"],
                                                 token: @token, uid: @resource.uid
                                                }
end
</code>```

I save the user with token and return the access tokens.

Title: Return a authentication token

Body:
I am using devise_auth_token gem in my rails-api app. I used omniauth_google_oauth2 gem with my app for auth but it was very buggy so I decided to follow a different approach.

I have a route in my api app that will response

{ "url": google-oauth-login-url }

The frontend app use that route to put it in the login with google btn.

After a user click in the btn they will be redirected to google oauth page and after filling in the details they will be then redirected to the frontend home page with the google code in the url.

The frontend app will send a req to the api server with the code and the server will req to the google server again to exchange that google code for access-token, refresh token and all that.

After the server receives those token, the server again makes another req to the google server to fetch user profile.

I dont know how to register the user after I get the user profile info.

How do i register it ? After registering it, how do I sign it in or send a  authentication token to the frontend app? The authentication token will be used in every headers while making the api call.

Any idea?

Body:
I had to dive into the gem code to get this right

def log_in_or_create_employee(user_info)
    @resource = Employee.find_by email: user_info["emails"][0]["value"]
    if @resource.nil?
        password = Devise.friendly_token[0,10]
        @resource = Employee.new({
            name: user_info["displayName"],
            admin: true,
            first_name: CustomRegex.japanese?(user_info["name"]["givenName"]) ? '' : user_info["name"]["givenName"],
            last_name: CustomRegex.japanese?(user_info["name"]["familyName"]) ? '' : user_info["name"]["familyName"],
            email: user_info["emails"][0]["value"],
            password: password,
            password_confirmation: password
            })
    end
        @client_id = SecureRandom.urlsafe_base64(nil, false)
  @token     = SecureRandom.urlsafe_base64(nil, false)
  @resource.tokens[@client_id] = {
          token: BCrypt::Password.create(@token),
          expiry: (Time.now + DeviseTokenAuth.token_lifespan).to_i
  }
  @resource.skip_confirmation!
        @resource.save!

        return render json: {client_id: @client_id, expiry: @resource.tokens[@client_id][:"expiry"],
                                                 token: @token, uid: @resource.uid
                                                }
end

I save the user with token and return the access tokens.


问:
While passing id from a json to an URL, undefined value is getting passed
I've a sample JSON as given below:

```<code>[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]
</code>```

And I prepared a HTML content based on that data. Code is given below:

```<code>function prepareTopComponentList(data) {

    var preparedHtml = "";

    for (var count = 0; count < data.length; count++) {
        preparedHtml += "<div class=\"col-lg-4\" style=\"margin-top: 20px\">\n" +
            "                <div class=\"card wow fadeIn\" data-wow-delay=\"0.2s\">\n" +
            "                    <img class=\"img-fluid\" src=\"";
        preparedHtml += data[0].displayImageUrl;
        preparedHtml += "\" alt=\"N/A\">\n" +
            "                    <div class=\"card-body\">\n" +
            "                        <h4 class=\"card-title\">";
        preparedHtml += data[0].title;
        preparedHtml += "</h4>\n" +
            "                        <p class=\"card-text\">";
        preparedHtml += data[0].shortdesc;
        preparedHtml += "</p>\n" +
            "                        <a onclick = \"redirect(this, this);\" href='#' class=\"btn btn-info\" id=\"";
        preparedHtml += "component_desc_" + data[count].componentid;

        /*I replaced 0 with count so that we can get proper ids*/
        //console.log(data[0].componentid);

        preparedHtml += "\">Learn more</a>\n" +
            "                    </div>\n" +
            "\n" +
            "                </div>\n" +
            "            </div>";
    }

    $("#div_top_component").append(preparedHtml);

}
</code>```

Now, I'm redirecting to a page based on value of componentid. Redirection function code is given below:

```<code>function redirect(element, data) {
    // data = prepareTopComponentList(data);
    for (var count = 0; count < data.length; count++) {
        var url = "inside.dell.com";
        var query = data[count].componentid;
        var finalUrl = "inside.dell.com/componentid=" + query;
        console.log(finalUrl);
    }
    window.location = "inside.dell.com/componentid=" + query;
}
</code>```

When I run this code, I get this error:

```<code>The requested URL /Reusable Components/pages/inside.dell.com/componentid=undefined was not found on this server.
</code>```

That error is fine, I don't have any problem with that. However in redirection URL, component id is undefined. How do I make sure that value of component ID gets passed to URL?

答:
In your HTML

```<code>"<a onclick = \"redirect(" + data[count].componentid + ");\" href='#' class=\"btn btn-info\" id=\"";
</code>```

And then your function

```<code>function redirect(id) {
    window.location = "inside.dell.com/componentid=" + id;
}
</code>```

Body:
I've a sample JSON as given below:

[
    {
        "componentid": 4,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "theme",
        "shortdesc": "to set theme for different applications"
    },
    {
        "componentid": 7,
        "displayImageUrl": "https://via.placeholder.com/350x200",
        "title": "preferences",
        "shortdesc": "preferences screen for apps"
    }
]

And I prepared a HTML content based on that data. Code is given below:

function prepareTopComponentList(data) {

    var preparedHtml = "";

    for (var count = 0; count < data.length; count++) {
        preparedHtml += "
\n" +
            "
\n" +
            "                    \n" +
            "
\n" +
            "
";
        preparedHtml += data[0].title;
        preparedHtml += "
\n" +
            "
";
        preparedHtml += data[0].shortdesc;
        preparedHtml += "
\n" +
            "                        Learn more\n" +
            "
\n" +
            "\n" +
            "
\n" +
            "
";
    }

    $("#div_top_component").append(preparedHtml);

}

Now, I'm redirecting to a page based on value of componentid. Redirection function code is given below:

function redirect(element, data) {
    // data = prepareTopComponentList(data);
    for (var count = 0; count < data.length; count++) {
        var url = "inside.dell.com";
        var query = data[count].componentid;
        var finalUrl = "inside.dell.com/componentid=" + query;
        console.log(finalUrl);
    }
    window.location = "inside.dell.com/componentid=" + query;
}

When I run this code, I get this error:

The requested URL /Reusable Components/pages/inside.dell.com/componentid=undefined was not found on this server.

That error is fine, I don't have any problem with that. However in redirection URL, component id is undefined. How do I make sure that value of component ID gets passed to URL?

Body:
In your HTML

"<a onclick = \"redirect(" + data[count].componentid + ");\" href='#' class=\"btn btn-info\" id=\"";

And then your function

function redirect(id) {
    window.location = "inside.dell.com/componentid=" + id;
}


问:
download wso2 identity server by using wget in unix
I am setting up WSO2 Identity server in my AWS EC2 instance.
What is the URL to WGET so that i can download the installation.I cant find the URL in the website anywhere
The version of identity server is 5.3.0 and I am using the prepackaged version so that i can use it as the key manager. I tried some urls from the download links.But whats the official page which tells which urls to use?Is there a product page which tells how to download in Unix box
How can i download in Unix box?which URL to use ?</p>

答:
Use below for downloading latest Identity Server release.

```<code>wget --user-agent="testuser" --referer="http://connect.wso2.com/wso2/getform/reg/new_product_download"  http://product-dist.wso2.com/products/identity-server/5.3.0/wso2is-5.3.0.zip
</code>```

For latest API Manager, use below

```<code>wget --user-agent="testuser" --referer="http://connect.wso2.com/wso2/getform/reg/new_product_download"  http://product-dist.wso2.com/products/api-manager/2.1.0/wso2am-2.1.0.zip
</code>```

Body:
Use below for downloading latest Identity Server release.

wget --user-agent="testuser" --referer="http://connect.wso2.com/wso2/getform/reg/new_product_download"  http://product-dist.wso2.com/products/identity-server/5.3.0/wso2is-5.3.0.zip

For latest API Manager, use below

wget --user-agent="testuser" --referer="http://connect.wso2.com/wso2/getform/reg/new_product_download"  http://product-dist.wso2.com/products/api-manager/2.1.0/wso2am-2.1.0.zip


问:
INSTALL_FAILED_INVALID_APK error with debug version code 1 inconsistent with 0
I have built an Android app on Android Studio version 2.3.3. As I try to deploy the app to a phone (lennovo) or an emulator (GenyMotion) I get an error, which says:

```<code>INSTALL_FAILED_INVALID_APK: /data/app/vmdl235652946.tmp/4_yCommerceApp-b_c-dev-debug version code 1 inconsistent with 0.
</code>```

I have looked at various posts here and tried the approaches below, none of which seems to help

Did a clean build followed by a rebuild after a restart of the Android Studio

Disconnected and reconnected devices

I deleted the .idea, .gradle and build directories and built again

Any suggestions to solve this pls? What is the version code being referred to here? I see one version code in the AndroidManifest.xml like below:

```<code><manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">
</code>```

I don't see any other version code anywhere else. BTW, I did not use an Android emulator as they seem to take hours to start. My processor is AMD and not Intel. I have the ARM images downloaded for the emulators.

答:
The trouble maybe caused by Instant Run feature of new Gradle.

Try disable Instant Run by going into File > Settings > Build, Execution, Deployment > Instant Run

Body:
I have built an Android app on Android Studio version 2.3.3. As I try to deploy the app to a phone (lennovo) or an emulator (GenyMotion) I get an error, which says:

INSTALL_FAILED_INVALID_APK: /data/app/vmdl235652946.tmp/4_yCommerceApp-b_c-dev-debug version code 1 inconsistent with 0.

I have looked at various posts here and tried the approaches below, none of which seems to help

Did a clean build followed by a rebuild after a restart of the Android Studio

Disconnected and reconnected devices

I deleted the .idea, .gradle and build directories and built again

Any suggestions to solve this pls? What is the version code being referred to here? I see one version code in the AndroidManifest.xml like below:

<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">

I don't see any other version code anywhere else. BTW, I did not use an Android emulator as they seem to take hours to start. My processor is AMD and not Intel. I have the ARM images downloaded for the emulators.


问:
SQL Server stored procedure does not return any values
I have this stored procedure which doesn't return any values I run EXEC command

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GClient]
    @CLIENT_CODE INT = NULL output,
    @CLIENT_NAME VARCHAR = 50 output,
    @CATEGORY VARCHAR = 50 output,
    @ATC VARCHAR = 50 output
AS
BEGIN
    SELECT
        *
    FROM
        dbo.CLIENT
    WHERE
        CLIENT_CODE = @CLIENT_CODE OR
        CLIENT_NAME = @CLIENT_NAME OR
        CATEGORY = @CATEGORY OR
        ATC = @ATC;
END
</code>```

I execute it like this:

```<code> DECLARE @client_name varchar(50)
 EXEC GCLIENT @client_name='rillera general merchandise'
</code>```

There is a record on the table with that value, I don't why it doesn't return any records at all.

答:
Modify your procedure with input parameter and assign columns to the output parameters.

```<code>ALTER PROCEDURE [dbo].[GClient]
@client_name varchar(50)
@CLIENT_CODE INT output,
@CLIENT_NAME VARCHAR(50) output,
@CATEGORY VARCHAR(50) output,
@ATC VARCHAR(50) output

AS
BEGIN
SELECT
@CLIENT_CODE = CLIENT_CODE,
@CLIENT_NAME=CLIENT_NAME,
@CATEGORY = CATEGORY,
@ATC = ATC
FROM
 dbo.CLIENT
WHERE
client_name =@client_name
END
</code>```

Also your execution step is wrong, you need to declare the output parameters and call them with exec. For eg.

```<code>DECLARE @CLIENT_CODE varchar(50)
DECLARE @CLIENT_NAME varchar(50)
DECLARE @CATEGORY varchar(50)
DECLARE @ATC varchar(50)

EXEC GCLIENT 'rillera general merchandise', @CLIENT_CODE OUTPUT,
@CLIENT_NAME OUTPUT, @CATEGORY OUTPUT, @ATC OUTPUT
</code>```

Body:
I have this stored procedure which doesn't return any values I run EXEC command

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GClient]
    @CLIENT_CODE INT = NULL output,
    @CLIENT_NAME VARCHAR = 50 output,
    @CATEGORY VARCHAR = 50 output,
    @ATC VARCHAR = 50 output
AS
BEGIN
    SELECT
        *
    FROM
        dbo.CLIENT
    WHERE
        CLIENT_CODE = @CLIENT_CODE OR
        CLIENT_NAME = @CLIENT_NAME OR
        CATEGORY = @CATEGORY OR
        ATC = @ATC;
END

I execute it like this:

 DECLARE @client_name varchar(50)
 EXEC GCLIENT @client_name='rillera general merchandise'

There is a record on the table with that value, I don't why it doesn't return any records at all.

Body:
Modify your procedure with input parameter and assign columns to the output parameters.

ALTER PROCEDURE [dbo].[GClient]
@client_name varchar(50)
@CLIENT_CODE INT output,
@CLIENT_NAME VARCHAR(50) output,
@CATEGORY VARCHAR(50) output,
@ATC VARCHAR(50) output

AS
BEGIN
SELECT
@CLIENT_CODE = CLIENT_CODE,
@CLIENT_NAME=CLIENT_NAME,
@CATEGORY = CATEGORY,
@ATC = ATC
FROM
 dbo.CLIENT
WHERE
client_name =@client_name
END

Also your execution step is wrong, you need to declare the output parameters and call them with exec. For eg.

DECLARE @CLIENT_CODE varchar(50)
DECLARE @CLIENT_NAME varchar(50)
DECLARE @CATEGORY varchar(50)
DECLARE @ATC varchar(50)

EXEC GCLIENT 'rillera general merchandise', @CLIENT_CODE OUTPUT,
@CLIENT_NAME OUTPUT, @CATEGORY OUTPUT, @ATC OUTPUT


问:
MySQL latitude and Longitude table setup
I want to store latitude and longitude values of places in a mysql database table. With the future in mind I will want to be able to find these places within a certain radius of a specific location. Having said that, what datatypes should I store the latitude and longitude values in? Please could you provide me with a create table script for columns like so:

```<code>place_id  |  lat  |  long
</code>```

Is there perhaps a column I am missing in the above table that will provide me with additional information that I may not see I need at the current time?

Thanks for any help.

答:
You should store the points in a singe column of datatype Point which you can index with a SPATIAL index (if your table type is MyISAM):

```<code>CREATE SPATIAL INDEX sx_place_location ON place (location)

SELECT  *
FROM    mytable
WHERE   MBRContains
               (
               LineString
                       (
                       Point($x - $radius, $y - $radius),
                       Point($x + $radius, $y + $radius)
                       )
               location
               )
        AND Distance(Point($x, $y), location) <= $radius
</code>```

This will drastically improve the speed of queries like "find all within a given radius".

Note that it is better to use plain TM metrical coordinates (easting and northing) instead of polar (latitude and longitude). For small radii, they are accurate enough, and the calculations are simplified greatly. If all your points are in one hemishpere and are far from the poles, you can use a single central meridian.

You still can use polar coordinates of course, but the formulae for calculating the MBR and the distance will be more complex.

Body:
I want to store latitude and longitude values of places in a mysql database table. With the future in mind I will want to be able to find these places within a certain radius of a specific location. Having said that, what datatypes should I store the latitude and longitude values in? Please could you provide me with a create table script for columns like so:

place_id  |  lat  |  long

Is there perhaps a column I am missing in the above table that will provide me with additional information that I may not see I need at the current time?

Thanks for any help.

Body:
You should store the points in a singe column of datatype Point which you can index with a SPATIAL index (if your table type is MyISAM):

CREATE SPATIAL INDEX sx_place_location ON place (location)

SELECT  *
FROM    mytable
WHERE   MBRContains
               (
               LineString
                       (
                       Point($x - $radius, $y - $radius),
                       Point($x + $radius, $y + $radius)
                       )
               location
               )
        AND Distance(Point($x, $y), location) <= $radius

This will drastically improve the speed of queries like "find all within a given radius".

Note that it is better to use plain TM metrical coordinates (easting and northing) instead of polar (latitude and longitude). For small radii, they are accurate enough, and the calculations are simplified greatly. If all your points are in one hemishpere and are far from the poles, you can use a single central meridian.

You still can use polar coordinates of course, but the formulae for calculating the MBR and the distance will be more complex.


问:
How can I increase the scrollspeed of the div?
I am trying to make a sort of parallax webdesign. My question is, if someone knows how I can make the red div move faster. I think its in the formule but dont know sure. Maybe someone knows?

Here is my code: http://jsfiddle.net/PvVdq/

```<code>$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * ($(document).width() - $horizontal.width()));

    $horizontal.css({
        'left': position
    });
});
</code>```

});

答:
I'm not so sure about this. When I tried this one, it speeds up the movement of the red div</p>

```<code>$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * 10 * ($(document).width() - $horizontal.width()));

    $horizontal.css({
        'left': position
    });
});
});
</code>```

Body:
I am trying to make a sort of parallax webdesign. My question is, if someone knows how I can make the red div move faster. I think its in the formule but dont know sure. Maybe someone knows?

Here is my code: http://jsfiddle.net/PvVdq/

$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * ($(document).width() - $horizontal.width()));

    $horizontal.css({
        'left': position
    });
});

});

Body:
I'm not so sure about this. When I tried this one, it speeds up the movement of the red div

$(document).ready(function () {
var $horizontal = $('#horizontal');

$(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * 10 * ($(document).width() - $horizontal.width()));

    $horizontal.css({
        'left': position
    });
});
});


问:
Kotlin android studio I try to change the button text but get an "exepected a value of type boolean" message
Kotlin in Android Studio. I'm trying to change the button text but I'm getting an "exepected a value of type boolean" message. How can I fix this?

```<code>    button11.setOnLongClickListener{
        button11.text = ""
    }
</code>```

答:
Try using not null or safe :</p>

```<code>button11?.setOnLongClickListener{
    button?.text=""
}
</code>```

Body:
Kotlin in Android Studio. I'm trying to change the button text but I'm getting an "exepected a value of type boolean" message. How can I fix this?

    button11.setOnLongClickListener{
        button11.text = ""
    }

Body:
Try using not null or safe :

button11?.setOnLongClickListener{
    button?.text=""
}


问:
Setting a parameter using dynamic SQL
I have been attempting to set a parameter using dynamic SQL however everytime i do it it is always returning a NULL. Below i have copied a basic version of my code, can anyone advise how i would do what i am looking to do.

```<code>DECLARE
@SQL_Prev_Values nvarchar(max),
@Value nchar(100),
@Prev_Values varchar(150) =' '

SET @Value = 'dave'

SET @SQL_Prev_Values = 'SET @Prev_Values = @Prev_Values + ''' + REPLACE(@Value,' ' ,'')+''''
SELECT @SQL_Prev_Values
EXEC sp_executesql @SQL_Prev_values,N'@Prev_Values nchar out',@Prev_Values out
SELECT @Prev_Values
SET @Prev_Values = @Prev_Values + 'dave'
SELECT @Prev_Values
</code>```

I have seen things online however they just do not appear to be making sense to me.
Any help would be appreciated.
Thanks in advance.

答:
As you can see from the screen shot below, the template is working perfectly:

```<code>DECLARE @Prev_Values nchar;
DECLARE @SQL_Prev_Values NVARCHAR(MAX);

SET @SQL_Prev_Values = N'SET @Prev_Values = 1;'

EXEC sp_executesql @SQL_Prev_values,N'@Prev_Values nchar out',@Prev_Values out

SELECT @Prev_Values;
</code>```

Try this:

```<code>DECLARE
@SQL_Prev_Values nvarchar(max),
@Value nchar(100),
@Prev_Values varchar(150) =' '

SET @Value = 'dave'

SET @SQL_Prev_Values = 'SET @Prev_Values =  @Prev_Values + ''' + REPLACE(@Value,' ' ,'')+''''
SELECT @SQL_Prev_Values

EXEC sp_executesql @SQL_Prev_values,N'@Prev_Values varchar(150) out',@Prev_Values out
SELECT @Prev_Values
</code>```

The value of the output parameter was different then the one set in the sp_executesql.

Title: Setting a parameter using dynamic SQL

Body:
I have been attempting to set a parameter using dynamic SQL however everytime i do it it is always returning a NULL. Below i have copied a basic version of my code, can anyone advise how i would do what i am looking to do.

DECLARE
@SQL_Prev_Values nvarchar(max),
@Value nchar(100),
@Prev_Values varchar(150) =' '

SET @Value = 'dave'

SET @SQL_Prev_Values = 'SET @Prev_Values = @Prev_Values + ''' + REPLACE(@Value,' ' ,'')+''''
SELECT @SQL_Prev_Values
EXEC sp_executesql @SQL_Prev_values,N'@Prev_Values nchar out',@Prev_Values out
SELECT @Prev_Values
SET @Prev_Values = @Prev_Values + 'dave'
SELECT @Prev_Values

I have seen things online however they just do not appear to be making sense to me.
Any help would be appreciated.
Thanks in advance.

Body:
As you can see from the screen shot below, the template is working perfectly:

DECLARE @Prev_Values nchar;
DECLARE @SQL_Prev_Values NVARCHAR(MAX);

SET @SQL_Prev_Values = N'SET @Prev_Values = 1;'

EXEC sp_executesql @SQL_Prev_values,N'@Prev_Values nchar out',@Prev_Values out

SELECT @Prev_Values;

Try this:

DECLARE
@SQL_Prev_Values nvarchar(max),
@Value nchar(100),
@Prev_Values varchar(150) =' '

SET @Value = 'dave'

SET @SQL_Prev_Values = 'SET @Prev_Values =  @Prev_Values + ''' + REPLACE(@Value,' ' ,'')+''''
SELECT @SQL_Prev_Values

EXEC sp_executesql @SQL_Prev_values,N'@Prev_Values varchar(150) out',@Prev_Values out
SELECT @Prev_Values

The value of the output parameter was different then the one set in the sp_executesql.