问:
Why does changing an Array in JavaScript affect copies of the array?
I've written the following JavaScript:

```<code>var myArray = ['a', 'b', 'c'];
var copyOfMyArray = myArray;
copyOfMyArray.splice(0, 1);
alert(myArray); // alerts ['b','c']
alert(copyOfMyArray); // alerts ['b','c']

var myNumber = 5;
var copyOfMyNumber = myNumber;
copyOfMyNumber = copyOfMyNumber - 1;
alert(myNumber); // alerts 5
alert(copyOfMyNumber); // alerts 4
</code>```

This code declares a variable myArray and sets it to an array value.  It then declares a second variable copyOfMyArray and sets it to myArray.
It performs an operation on copyOfMyArray and then alerts both myArray and copyOfMyArray.  Somehow, when I perform an operation on copyOfMyArray, it appears that the same operation is performed on myArray.

The code then does the same thing with a number value:  It declares a variable myNumber and sets it to a number value.  It then declares a second variable copyOfMyNumber and sets it to myNumber.  It performs an operation on copyOfMyNumber and then alerts both myNumber and copyOfMyNumber.  Here, I get the expected behavior: different values for myNumber and copyOfMyNumber.

What is the difference between an array and a number in JavaScript that it seems changing an array changes the value of a copy of the array, where as changing a number does not change the value of a copy of the number?

I'm guessing that for some reason, the array is referred to by reference and the number by value, but why?  How can I know what behavior to expect with other objects?

答:
Create a filter of the original array in the arrayCopy. So that changes to the new array won't affect original array.

```<code>var myArray = ['a', 'b', 'c'];
var arrayCopy = myArray.filter(function(f){return f;})
arrayCopy.splice(0, 1);
alert(myArray); // alerts ['a','b','c']
alert(arrayCopy); // alerts ['b','c']
</code>```

Hope it helps.

Body:
I've written the following JavaScript:

var myArray = ['a', 'b', 'c'];
var copyOfMyArray = myArray;
copyOfMyArray.splice(0, 1);
alert(myArray); // alerts ['b','c']
alert(copyOfMyArray); // alerts ['b','c']

var myNumber = 5;
var copyOfMyNumber = myNumber;
copyOfMyNumber = copyOfMyNumber - 1;
alert(myNumber); // alerts 5
alert(copyOfMyNumber); // alerts 4

This code declares a variable myArray and sets it to an array value.  It then declares a second variable copyOfMyArray and sets it to myArray.
It performs an operation on copyOfMyArray and then alerts both myArray and copyOfMyArray.  Somehow, when I perform an operation on copyOfMyArray, it appears that the same operation is performed on myArray.

The code then does the same thing with a number value:  It declares a variable myNumber and sets it to a number value.  It then declares a second variable copyOfMyNumber and sets it to myNumber.  It performs an operation on copyOfMyNumber and then alerts both myNumber and copyOfMyNumber.  Here, I get the expected behavior: different values for myNumber and copyOfMyNumber.

What is the difference between an array and a number in JavaScript that it seems changing an array changes the value of a copy of the array, where as changing a number does not change the value of a copy of the number?

I'm guessing that for some reason, the array is referred to by reference and the number by value, but why?  How can I know what behavior to expect with other objects?

Body:
Create a filter of the original array in the arrayCopy. So that changes to the new array won't affect original array.

var myArray = ['a', 'b', 'c'];
var arrayCopy = myArray.filter(function(f){return f;})
arrayCopy.splice(0, 1);
alert(myArray); // alerts ['a','b','c']
alert(arrayCopy); // alerts ['b','c']

Hope it helps.


来源: stackexchange

问:
how to filter duplicate rows with different value
I hv a table like this

```<code>Model     Qty        Date
ABC        1         20110102
ABC       -1         20110105
QWE        1         20110103
ZXC        1         20110103
ABC        1         20110110
QWE       -1         20110110
</code>```

I wish to hv the final output like this:-

```<code>Model     Qty        Date
ZXC        1         20110103
ABC        1         20110110
</code>```

How can I do this via SQL ?

Thanks

答:
```<code>select t1.Model, t1.Qty, t1.Date from thetable t1 where t1.Date = (select max(t2.Date) from thetable t2 where t2.Model=t1.Model)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I hv a table like this

Model     Qty        Date
ABC        1         20110102
ABC       -1         20110105
QWE        1         20110103
ZXC        1         20110103
ABC        1         20110110
QWE       -1         20110110

I wish to hv the final output like this:-

Model     Qty        Date
ZXC        1         20110103
ABC        1         20110110

How can I do this via SQL ?

Thanks


问:
C++ conversion from unsigned char to std::string
Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks.
Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

```<code>std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....
</code>```

The result i want is to have the string value

```<code>some text @H...
</code>```

But what i get is an error while compiling

```<code>error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^
</code>```

Logic behind this thinking is that output of:

```<code>printf("%c%c",characters[0],characters[1]);
</code>```

and

```<code>std::cout << characters[0] << characters[0] << std::endl;
</code>```

results in

```<code>@H
</code>```

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question.
Thanks everyone - too bad I can't mark multiple answers!

答:
In C++98, the method std::string::append is overloaded with these arguments:

```<code>(1) string& append (const string& str);
(2) string& append (const string& str, size_t subpos, size_t sublen);
(3) string& append (const char* s);
(4) string& append (const char* s, size_t n);
(5) string& append (size_t n, char c);
(6) template <class InputIterator> string& append (InputIterator first, InputIterator last);
</code>```

And in C++11 and C++14, it is also overloaded with string& append (initializer_list<char> il);.

As you can see, there is no candidate for string& append(unsigned char).  The error might come from the compiler failing in overload resolution, trying to use the (3) which is for a null-terminated string argument, but fails to find a conversion defined for unsigned char -> const char *.

If you still want to use the method std::string::append, you can use (5): string& append (size_t n, char c) which will append your string with c n times. In your case, it would be:

```<code>stroutput.append(1, characters[0]);
stroutput.append(1, characters[1]);
</code>```

The unsgined char would be converted into char.

Another alternative is to use this constructor for std::string:

```<code>std::string(characters, characters + 12);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Intro: Consider that I have no experience with C++, but can find my way around any language to do basic tasks.
Most of my experience is with .net languages (vn.net and C#), php and js, so please explain as if you were teaching a complete noob.

Here is the problem: I receive data in an unsigned char characters[12]; and I have to then append that data to a std::string

data is always 12 characters long, and is not null terminated, because it is gathered by selecting specific bytes received from serial port.

Long story short:

std::string stroutput = "some text ";
unsigned char characters[12];
characters[0]=64; //demo data to shorten the code
characters[1]=72;
stroutput.append(characters[0]);
stroutput.append(characters[1]);
....

The result i want is to have the string value

some text @H...

But what i get is an error while compiling

error: invalid conversion from ‘unsigned char’ to ‘const char*’ [-fpermissive]
stroutput.append(characters[0]);
                 ~~~~~~~~~~~~^

Logic behind this thinking is that output of:

printf("%c%c",characters[0],characters[1]);

and

std::cout << characters[0] << characters[0] << std::endl;

results in

@H

So: How do I convert unsigned char something[12] to std::string?

Thanks

Edit: Sorry for the duplicate, search didn't return that question.
Thanks everyone - too bad I can't mark multiple answers!

Body:
In C++98, the method std::string::append is overloaded with these arguments:

(1) string& append (const string& str);
(2) string& append (const string& str, size_t subpos, size_t sublen);
(3) string& append (const char* s);
(4) string& append (const char* s, size_t n);
(5) string& append (size_t n, char c);
(6) template <class InputIterator> string& append (InputIterator first, InputIterator last);

And in C++11 and C++14, it is also overloaded with string& append (initializer_list<char> il);.

As you can see, there is no candidate for string& append(unsigned char).  The error might come from the compiler failing in overload resolution, trying to use the (3) which is for a null-terminated string argument, but fails to find a conversion defined for unsigned char -> const char *.

If you still want to use the method std::string::append, you can use (5): string& append (size_t n, char c) which will append your string with c n times. In your case, it would be:

stroutput.append(1, characters[0]);
stroutput.append(1, characters[1]);

The unsgined char would be converted into char.

Another alternative is to use this constructor for std::string:

std::string(characters, characters + 12);


问:
Bottom TabLayout leaving space at bottom
I am facing a problem. I have a custom layout for toolbar and in my activity xml, I am including this toolbar. The structure of my activity is:

Toolbar layout on top using include tag.

The ViewPager

TabLayout at bottom to get bottom tabs.

The problem I am facing is that on some devices, it is coming out perfect but in a few devices (tested on moto G series devices) the bottom tab is leaving space.

Please Refer the Images below:

In Normal Phones when it shows expected UI

In MOTO G series

The xml code is following

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

<include layout="@layout/custom_tool_bar" />

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="10" />

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/BottomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#fff"
    android:layout_weight="1"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    />

</LinearLayout>
</code>```

答:
remove android:weightSum=11 attribute in your parent LinearLayout;

change ViewPager's android:layout_weight=10 attribute to android:layout_weight=1;

remove TabLayout's android:layout_weight=1 attribute

and try again.

Body:
I am facing a problem. I have a custom layout for toolbar and in my activity xml, I am including this toolbar. The structure of my activity is:

Toolbar layout on top using include tag.

The ViewPager

TabLayout at bottom to get bottom tabs.

The problem I am facing is that on some devices, it is coming out perfect but in a few devices (tested on moto G series devices) the bottom tab is leaving space.

Please Refer the Images below:

In Normal Phones when it shows expected UI

In MOTO G series

The xml code is following

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

<include layout="@layout/custom_tool_bar" />

<android.support.v4.view.ViewPager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"

    android:layout_height="0dp"

    android:layout_weight="10" />

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    style="@style/BottomTabLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:background="#fff"
    android:layout_weight="1"
    app:tabIndicatorColor="@color/colorPrimaryDark"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    />

</LinearLayout>


问:
Msbuild ignores azure publish profile settings - Visual Studio 2015 - .Net 4.6.1
I have 2 web API Project in my solution. One project is 4.5.1 and another project is 4.6.1.

Project with .Net framework 4.5.1 builds p with the msbuild task with below parameters, and it properly publishes the code to azure. All Fine!!

Project with .Net framework 4.6.1 builds properly with the msbuild task with below parameters.

When build with above parameter the package is created not deployed to azure. See the log below.

Please help, it is really strange. Only difference i see between the two web api solution is there .Net framework version.

答:
First suggest you manually use the msbuild.exe command to do the publish. This will narrow down the issue related to TFS side or not.

Also update your Azure SDK on the build agent to latest version(Azure SDK for .NET 3.0).

Try to forcing the "PublishProfileRootFolder" parameter in your MSBuild argument. Details please refer this question: MsBuild not finding publish profile


问:
Xpath contain exact word
I have the following XML:

```<code><book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
<book>
    <title>Moby Dick</title>
    <category>foo bar</category>
    <author>Herman Melville</author>
</book>
<book>
    <title>Sayings of the Century</title>
    <category>bar foo</category>
    <author>Nigel Rees</author>
</book>
<book>
    <title>The Lord of the Rings</title>
    <category>bar</category>
    <author>J. R. R. Tolkien</author>
</book>
<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>
</code>```

I want to get data where category exactly contains "foo" which would be:

```<code><book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>
<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
</code>```

when I try :

```<code>//*[contains(category, "foo")]
</code>```

it returns the following elements :

```<code><book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
<book>
    <title>Moby Dick</title>
    <category>foo bar</category>
    <author>Herman Melville</author>
</book>
<book>
    <title>Sayings of the Century</title>
    <category>bar foo</category>
    <author>Nigel Rees</author>
</book>
<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>
</code>```

whereas when I try :

```<code>//*[category="foo"]
</code>```

it returns the following elements :

```<code><book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
</code>```

Is there a way that I could get my data. Any help would be appreciated. Thanks

答:
If category may contain list of item separated by comma:

```<code>//category[contains(concat(",", ., ","), ",foo,")]/ancestor::book[1]
</code>```

Adding comma before and after is needed to avoid selecting f.e.thefoos category while finding foo

Title: Xpath contain exact word

Body:
I have the following XML:

<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
<book>
    <title>Moby Dick</title>
    <category>foo bar</category>
    <author>Herman Melville</author>
</book>
<book>
    <title>Sayings of the Century</title>
    <category>bar foo</category>
    <author>Nigel Rees</author>
</book>
<book>
    <title>The Lord of the Rings</title>
    <category>bar</category>
    <author>J. R. R. Tolkien</author>
</book>
<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>

I want to get data where category exactly contains "foo" which would be:

<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>
<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>

when I try :

//*[contains(category, "foo")]

it returns the following elements :

<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>
<book>
    <title>Moby Dick</title>
    <category>foo bar</category>
    <author>Herman Melville</author>
</book>
<book>
    <title>Sayings of the Century</title>
    <category>bar foo</category>
    <author>Nigel Rees</author>
</book>
<book>
    <title>The Lord</title>
    <category>foo,bar</category>
    <author>J. Tolkien</author>
</book>

whereas when I try :

//*[category="foo"]

it returns the following elements :

<book>
    <title>Sword of Honour</title>
    <category>foo</category>
    <author>Evelyn Waugh</author>
</book>

Is there a way that I could get my data. Any help would be appreciated. Thanks

Body:
If category may contain list of item separated by comma:

//category[contains(concat(",", ., ","), ",foo,")]/ancestor::book[1]

Adding comma before and after is needed to avoid selecting f.e.thefoos category while finding foo


问:
Forge Color Display Error
I have set up the color scheme to identify the different system of the building services in Revit and Navisworks. When I uploaded to the forge viewer, the colors were shown correctly at the beginning. However, when I zoomed in, some of the colors were disappeared. Did anyone have this problem? How could the problem be solved?
Thank you.

Forge Display Error:

Zooming Lo01

答:
Apologizing for any inconvenience caused, this might be a known issue of our model extraction service for the Revit, it has been logged as REVIT-120524 in our case system to let our dev team to allocate time to investigate it. You can send this id to forge.help@autodesk.com to inquire updates in the future.

BTW, the reason caused this issue I discovered is there are many MEP system type, and they have owned different colored material, fittings will take materail color from the first system type from corrosponding MEP systems. Currently, there is not formal solution to avoid this. We apology for this again. Fortunately, there is a workaroud you could try:

Split your MEP models into servral RVT files that contain single pipe system, duct system and others.

Upload them to the Forge for translation seperately.

Load translated models via the Forge Viewer.

Hope it helps.

This workaround is working on my live projects now, but might not suite for you. And it's not the formal solution, you might have to use it at your own risk.

Title: Forge Color Display Error


问:
Trouble selecting item from dropdown options using IE
I'm trying to click on the dropdown option and select any item out of them but the clicking event is not being executed. As soon as the browser hits the line containing elem.click it throws an error object variable or with block variable not set. How can I mend my below effort to make it a go? Thanks in advance for any solution.

What I have tried so far is this:

```<code>Dim Hdoc as HTMLDocument, elem as object, s_item as object

Set Hdoc = IE.Document    ''here IE as New InternetExplorer
Set elem = Hdoc.getElementById("select")
elem.Click     ''error thrown here showing Object variable or with block ----

For Each s_item In Hdoc.getElementsByTagName("option")
    If InStr(1, s_item.innerText, "Asia Pacific Ex-Japan Fund", 1) > 0 Then s_item.Click: Exit For
Next s_item
</code>```

Elements within which select button and dropdown options are embedded:

```<code><html>
 <body>
  <select id="select" name="select" onchange="redirect(this.value);" style="width: 165px;">
   <option value="">
    Select a fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=480&shareId=33&viewMode=profile">
    <!-- Do Nothing -->
    Absolute Return Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=1466&shareId=33&viewMode=profile">
    <!-- Do Nothing -->
    Asia Pacific Ex-Japan Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=139597&shareId=33&viewMode=profile">
    <!-- Do Nothing -->
    Blended Research European Equity Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=3014&shareId=33&viewMode=profile">
    <!-- Do Nothing -->
    Continental European Equity Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=165855&shareId=33&viewMode=profile">
    <!-- Do Nothing -->
    Diversified Income Fund
   </option>
  </select>
 </body>
</html>
</code>```

答:
Can you please run this - i think it's because the Hdoc hasn't had time to set</p>

```<code>    Dim Hdoc As HTMLDocument, elem As Object, s_item As Object

    Set Hdoc = IE.Document    ''here IE as New InternetExplorer
    Set elem = Hdoc.getElementById("select")
    Application.Wait(Now + TimeValue("00:00:02"))
    elem.Click     ''error thrown here showing Object variable or with block ----

    For Each s_item In Hdoc.getElementsByTagName("option")
        If InStr(1, s_item.innerText, "Asia Pacific Ex-Japan Fund", 1) > 0 Then s_item.Click: Exit For
    Next s_item
</code>```

Body:
I'm trying to click on the dropdown option and select any item out of them but the clicking event is not being executed. As soon as the browser hits the line containing elem.click it throws an error object variable or with block variable not set. How can I mend my below effort to make it a go? Thanks in advance for any solution.

What I have tried so far is this:

Dim Hdoc as HTMLDocument, elem as object, s_item as object

Set Hdoc = IE.Document    ''here IE as New InternetExplorer
Set elem = Hdoc.getElementById("select")
elem.Click     ''error thrown here showing Object variable or with block ----

For Each s_item In Hdoc.getElementsByTagName("option")
    If InStr(1, s_item.innerText, "Asia Pacific Ex-Japan Fund", 1) > 0 Then s_item.Click: Exit For
Next s_item

Elements within which select button and dropdown options are embedded:

  <select id="select" name="select" onchange="redirect(this.value);" style="width: 165px;">
   <option value="">
    Select a fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=480&shareId=33&viewMode=profile">

    Absolute Return Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=1466&shareId=33&viewMode=profile">

    Asia Pacific Ex-Japan Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=139597&shareId=33&viewMode=profile">

    Blended Research European Equity Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=3014&shareId=33&viewMode=profile">

    Continental European Equity Fund
   </option>
   <option value="/wps/myportal/mfs/non-us-advisor/products/meridian-funds/!ut/p/a1/04_Sj9CPykssy0xPLMnMz0vMAfGjzOL9A40C_c09jAzcjYOdDYxcTPyNTUONDS1NjPW99KPSc_KTwEojHfOSjC3S9aOKUtNSi1KL9DLyi0v0I8rLy_Vy04r1kvNz9cOd9aMCEjMLMxz1C7KjkiodFRUBO3AG8w!!/dl5/d5/L2dJQSEvUUt3QS80SmlFL1o2X09RMlFPN0gyMEczU0MwMkQ0TzM1VTMxRk8y/?clearPortletSession=true&productId=165855&shareId=33&viewMode=profile">

    Diversified Income Fund
   </option>
  </select>

Body:
Can you please run this - i think it's because the Hdoc hasn't had time to set

    Dim Hdoc As HTMLDocument, elem As Object, s_item As Object

    Set Hdoc = IE.Document    ''here IE as New InternetExplorer
    Set elem = Hdoc.getElementById("select")
    Application.Wait(Now + TimeValue("00:00:02"))
    elem.Click     ''error thrown here showing Object variable or with block ----

    For Each s_item In Hdoc.getElementsByTagName("option")
        If InStr(1, s_item.innerText, "Asia Pacific Ex-Japan Fund", 1) > 0 Then s_item.Click: Exit For
    Next s_item


问:
JUnit spring boot application
I am writing JUnit test cases for my Spring Boot Application in which dynamically data is generated through various APIs. I wanted to truncate all the test data after test cases are passed. But is it advisable to write a test case which will truncate the data at the end of Unit testing. But provided that the developed application does not have a delete API and the API is solely developed only for JUnit.  </p>

答: A good practice is to create a database during your build process or within your test which will be automatically dropped afterwards. Some people use H2 database for testing.</p>

Title: JUnit spring boot application


问:
How to remove all duplicates from an array of objects?
I have an object that contains an array of objects.

```<code>obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});
</code>```

I'm wondering what is the best method to remove duplicate objects from an array.  So for example, obj.arr would become...

```<code>{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}
</code>```

答:
If you don't mind your unique array being sorted afterwards, this would be an efficient solution:

```<code>things.thing
  .sort(((a, b) => a.place < b.place)
  .filter((current, index, array) =>
    index === 0 || current.place !== array[index - 1].place)
</code>```

This way, you only have to compare the current element with the previous element in the array. Sorting once before filtering (O(n*log(n))) is cheaper than searching for a duplicate in the entire array for every array element (O(n²)).

ContentLicense: CC BY-SA 4.0

Body:
I have an object that contains an array of objects.

obj = {};

obj.arr = new Array();

obj.arr.push({place:"here",name:"stuff"});
obj.arr.push({place:"there",name:"morestuff"});
obj.arr.push({place:"there",name:"morestuff"});

I'm wondering what is the best method to remove duplicate objects from an array.  So for example, obj.arr would become...

{place:"here",name:"stuff"},
{place:"there",name:"morestuff"}

Body:
If you don't mind your unique array being sorted afterwards, this would be an efficient solution:

things.thing
  .sort(((a, b) => a.place < b.place)
  .filter((current, index, array) =>
    index === 0 || current.place !== array[index - 1].place)

This way, you only have to compare the current element with the previous element in the array. Sorting once before filtering (O(n*log(n))) is cheaper than searching for a duplicate in the entire array for every array element (O(n²)).


问:
Fb Ads api How to get Active only FB Campaigns?
I am trying to get the campaigns list from facebook ads api I am using below code

```<code>        $account = new AdAccount('act_' . $account_id);
        $campaignSets = $account->getCampaigns(array(
            CampaignFields::ID,
            CampaignFields::NAME,
            CampaignFields::START_TIME,
            CampaignFields::STOP_TIME,
            CampaignFields::SPEND_CAP,
            'effective_status'
                ));
</code>```

But I need only the active campaigns list so how can I filter the list by Camapign Status = Active only

Thanks,
Ronak Shah

答:
I can show you how to achieve this using the raw REST-API (I opted not to use FB's unnecessarily convoluted SDK (Python)).

https://graph.facebook.com/v2.11/act_99999999999999/campaigns?status=["ACTIVE","PAUSED","ARCHIVED","PENDING_REVIEW","DISAPPROVED","PREAPPROVED","PENDING_BILLING_INFO","CAMPAIGN_PAUSED","ARCHIVED","ADSET_PAUSED"]&format=json&method=get&pretty=1&limit=250&fields=field1,field2&time_range={"since": "2017-11-01", "until": "2017-12-05"}&access_token=XXX

The key here is the status=[] GET parameter.

Body:
I am trying to get the campaigns list from facebook ads api I am using below code

        $account = new AdAccount('act_' . $account_id);
        $campaignSets = $account->getCampaigns(array(
            CampaignFields::ID,
            CampaignFields::NAME,
            CampaignFields::START_TIME,
            CampaignFields::STOP_TIME,
            CampaignFields::SPEND_CAP,
            'effective_status'
                ));

But I need only the active campaigns list so how can I filter the list by Camapign Status = Active only

Thanks,
Ronak Shah


问:
Why the database didn't update anything although terminal shows "Completed 200" for Rails?
My controller code is like these:

```<code>def edit
  @user = User.find params[:id]
end

def update
  @user = User.find params[:id]
  if @user.update_attributes(params[:user])
    flash[:notice] = "success!"
  else
    flash[:notice] = "fail!"
  end
end

attr_accessor :username, :introduction, :first_name, :last_name

private

def user_params
  params.require(:user).permit(:username, :introduction, :first_name, :last_name)
end
</code>```

View:

```<code><%= form_for @user, :url =>edit_path(@user), :method => :PUT do |f| %>
<%= f.label :username %><br>
<%= f.text_field :username %>
<br>
<%= f.label :Introduction %><br>
<%= f.text_area :introduction %>
<br>
<%= f.label :FirstName %><br>
<%= f.text_field :first_name %>
<br>
<%= f.label :LastName %><br>
<%= f.text_field :last_name %>
<br>
<%= f.submit "Save changes"%><% end %>
</code>```

And the terminal is:

```

    Started PUT "/profile/1/edit" for 127.0.0.1 at 2017-12-06 04:30:05 -0500
    Processing by ProfileController#edit as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"eBvvAG892DTOFzYuFTKPCgbOuSQXB8BVOub7A8CgaPHLW2vaBFMpUGNHhgYZednfd5pqICCy1DykIarD7QYtIg==", "user"=>{"username"=>"aaa", "introduction"=>"aaaaa", "first_name"=>"a", "last_name"=>"a"}, "commit"=>"Save changes", "id"=>"1"}
      User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
      Notification Load (0.1ms)  SELECT "notifications".* FROM "notifications"
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."sender_id" = ? LIMIT 1  [["sender_id", 1]]
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."recip_id" = ? LIMIT 1  [["recip_id", 1]]
      User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
      CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
      Rendered profile/edit.html.erb within layouts/game (1.5ms)
      User Load (0.2ms)  SELECT "users".* FROM "users"
    Completed 200 OK in 32ms (Views: 28.5ms | ActiveRecord: 0.5ms)

```

But database is not updating:

1|du.1@osu.edu|$2a$11$2WHUjqQHU1gtlzw3ObXgVeE7dGG1qby2tLmATeoUyMnh1cg5wXv86||||3|2017-12-06 08:43:44.469588|2017-12-06 05:32:19.252680|127.0.0.1|127.0.0.1|2017-12-05 17:04:39.689636|2017-12-06 08:43:44.470487||1970-1-1|||This guy is lazy. Without an Introduction.|

答:
Try to use safe user_params instead of params[:user]:

```<code>if @user.update_attributes(user_params)
  # ...
</code>```

BTW you probably don't need attr_accessor :username, :introduction, :first_name, :last_name line in your controller.

Body:
My controller code is like these:

def edit
  @user = User.find params[:id]
end

def update
  @user = User.find params[:id]
  if @user.update_attributes(params[:user])
    flash[:notice] = "success!"
  else
    flash[:notice] = "fail!"
  end
end

attr_accessor :username, :introduction, :first_name, :last_name

private

def user_params
  params.require(:user).permit(:username, :introduction, :first_name, :last_name)
end

View:

<%= form_for @user, :url =>edit_path(@user), :method => :PUT do |f| %>
<%= f.label :username %>

<%= f.text_field :username %>

<%= f.label :Introduction %>

<%= f.text_area :introduction %>

<%= f.label :FirstName %>

<%= f.text_field :first_name %>

<%= f.label :LastName %>

<%= f.text_field :last_name %>

<%= f.submit "Save changes"%><% end %>

And the terminal is:

    Started PUT "/profile/1/edit" for 127.0.0.1 at 2017-12-06 04:30:05 -0500
    Processing by ProfileController#edit as HTML
      Parameters: {"utf8"=>"✓", "authenticity_token"=>"eBvvAG892DTOFzYuFTKPCgbOuSQXB8BVOub7A8CgaPHLW2vaBFMpUGNHhgYZednfd5pqICCy1DykIarD7QYtIg==", "user"=>{"username"=>"aaa", "introduction"=>"aaaaa", "first_name"=>"a", "last_name"=>"a"}, "commit"=>"Save changes", "id"=>"1"}
      User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
      Notification Load (0.1ms)  SELECT "notifications".* FROM "notifications"
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."sender_id" = ? LIMIT 1  [["sender_id", 1]]
      Chat Exists (0.0ms)  SELECT  1 AS one FROM "chats" WHERE "chats"."recip_id" = ? LIMIT 1  [["recip_id", 1]]
      User Load (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
      CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", "1"]]
      Rendered profile/edit.html.erb within layouts/game (1.5ms)
      User Load (0.2ms)  SELECT "users".* FROM "users"
    Completed 200 OK in 32ms (Views: 28.5ms | ActiveRecord: 0.5ms)

But database is not updating:

1|du.1@osu.edu|$2a$11$2WHUjqQHU1gtlzw3ObXgVeE7dGG1qby2tLmATeoUyMnh1cg5wXv86||||3|2017-12-06 08:43:44.469588|2017-12-06 05:32:19.252680|127.0.0.1|127.0.0.1|2017-12-05 17:04:39.689636|2017-12-06 08:43:44.470487||1970-1-1|||This guy is lazy. Without an Introduction.|

Body:
Try to use safe user_params instead of params[:user]:

if @user.update_attributes(user_params)
  # ...

BTW you probably don't need attr_accessor :username, :introduction, :first_name, :last_name line in your controller.


问:
Using mongodb-stitch library in Angular 4
Im been trying the MongoDB Stitch service in Angular, so far Im able to use the service. However, the only way I could connect to the service is by including the js library hosted in AWS on the html page.

There is a mongodb-stitch npm package available and there are sample pages on mongodb tutorial on how to use it. But this is a pure JS library (no TS support) and I have tried several ways (using require, installing typings of the lib (not available), using @types) to no avail.

Anyone tried this on Ng4? Would love to have the steps you did to use the 'mongodb-stitch' package the create a service.

答:
not sure whether the question is still relevant considering it was asked two months ago but anyway...

As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any

For example:

```<code>    declare var stitch: any;

    export class MyService implements OnInit {
    db;

    client;

    ngOnInit() {
        this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
        this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
        this.client.login();
    }

    save() {
        this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
    }

  }
</code>```

Body:
not sure whether the question is still relevant considering it was asked two months ago but anyway...

As you pointed out you can use
npm install --save mongodb-stitch
to install the package and since there is no TS binding you can declare the stitch library as any

For example:

    declare var stitch: any;

    export class MyService implements OnInit {
    db;

    client;

    ngOnInit() {
        this.client = new stitch.StitchClient('<check the stitch app page for proper value>');
        this.db = this.client.service('mongodb', 'mongodb-atlas').db('<the db name goes here>');
        this.client.login();
    }

    save() {
        this.db.collection('<collection name>').insertOne({key : 'value'}).then(() => console.log("All done"));
    }

  }


答:
Ensure your Excel data is formatted in Excel as a date, and then load from MATLAB using "basic" mode:

```<code>[data,header,raw]=xlsread('Mappe1.xlsx','','','basic');
</code>```

Firstly the data you show above gives your date format as 24.11.2017 09:41:25. The dot-separators don't look standard to me, which makes me wonder how they're stored in Excel. I would use a standard format like 2017-11-24 09:41:25 and ensure that Excel recognises them as dates/times. (See here for formats that MATLAB likes).

Doing the above I was able to read in numeric values in MATLAB that look the same as those you requested. Using basic mode will read in the dates as Excel serial numbers (not MATLAB datenums) as documented here.

If you don't use "basic" mode then the MATLAB behaviour depends on the the Excel version installed on your computer (which we don't know). I don't know how Octave works in this case.

Finally, writing code that works in both MATLAB and Octave may not be possible in the simple case (or even not at all). You will have to be prepared to jump through hoops to make this happen. Also I don't claim this will work the same in Octave as I don't have Octave to test!

Title: Why Xlsread reading (date time) as string

Body:
I am trying to read Excel sheet.
On the same computer, I have different results. What should I do to read Date-time as Date and not a string?

I know that I can change it later on, but I need to have the same code for Octave and Matlab.

Matlab:

[data,header, raw]=xlsread('Mappe1.xlsx');

data =

         0   -0.1843   -0.1445
         0   -0.1845   -0.1455
         0   -0.1833   -0.1461
         0   -0.1819   -0.1466

header =

    'Stamp'                  'R1.1'    'R2.1'    'R2.2'
    '24.11.2017 09:41:25'    ''        ''        ''
    '24.11.2017 05:41:23'    ''        ''        ''
    '24.11.2017 01:41:21'    ''        ''        ''
    '23.11.2017 21:41:19'    ''        ''        ''

Octave:
data =

  4.3063e+004  0.0000e+000  -1.8434e-001  -1.4451e-001
  4.3063e+004  0.0000e+000  -1.8445e-001  -1.4551e-001
  4.3063e+004  0.0000e+000  -1.8328e-001  -1.4611e-001
  4.3063e+004  0.0000e+000  -1.8186e-001  -1.4661e-001
  4.3063e+004  0.0000e+000  -1.8071e-001  -1.4493e-001
  4.3063e+004  0.0000e+000  -1.8192e-001  -1.4123e-001
  4.3062e+004  0.0000e+000  -1.8348e-001  -1.4165e-001
  4.3062e+004  0.0000e+000  -1.8358e-001  -1.4219e-001
  4.3062e+004  0.0000e+000  -1.8342e-001  -1.4284e-001

header =
{
  [1,1] = Stamp
  [1,2] = R1.1
  [1,3] = R2.1
  [1,4] = R2.2
}

Body:
Ensure your Excel data is formatted in Excel as a date, and then load from MATLAB using "basic" mode:

[data,header,raw]=xlsread('Mappe1.xlsx','','','basic');

Firstly the data you show above gives your date format as 24.11.2017 09:41:25. The dot-separators don't look standard to me, which makes me wonder how they're stored in Excel. I would use a standard format like 2017-11-24 09:41:25 and ensure that Excel recognises them as dates/times. (See here for formats that MATLAB likes).

Doing the above I was able to read in numeric values in MATLAB that look the same as those you requested. Using basic mode will read in the dates as Excel serial numbers (not MATLAB datenums) as documented here.

If you don't use "basic" mode then the MATLAB behaviour depends on the the Excel version installed on your computer (which we don't know). I don't know how Octave works in this case.

Finally, writing code that works in both MATLAB and Octave may not be possible in the simple case (or even not at all). You will have to be prepared to jump through hoops to make this happen. Also I don't claim this will work the same in Octave as I don't have Octave to test!


问:
How does PostgreSQL's CLUSTER differ from a clustered index in SQL Server?
Many posts like this stackoverflow link claim that there is no concept of a clustered index in PostgreSQL. However, the PostgreSQL documentation contains something similar. A few people claim it is similar to a clustered index in SQL Server.

Do you know what the exact difference between these two is, if there is any?

答:
A clustered index or index organized table is a data structure where all the table data are organized in index order, typically by organizing the table in a B-tree structure.

Once a table is organized like this, the order is automatically maintained by all future data modifications.

PostgreSQL does not have such clustering indexes. What the CLUSTER command does is rewrite the table in the order of the index, but the table remains a fundamentally unordered heap of data, so future data modifications will not maintain that index order.

You have to CLUSTER a PostgreSQL table regularly if you want to maintain an approximate index order in the face of data modifications to the table.

Clustering in PostgreSQL can improve performance, because tuples found during an index scan will be close together in the heap table, which can turn random access to the heap to faster sequential access.


问:
prevent redirects if not on same domain (javascript)
Is there a way to prevent redirects if they aren't on the same domain? There's this snippet that works well:

```<code>  window.onbeforeunload = function() {
    return true;
  }
</code>```

But the problem is that it prompts user on every redirect. I would like to truncate prompts only to different domain redirects. I've tried:

```<code>window.addEventListener('beforeunload', function(e) {
  if (!location.href.match('domain')) {
    window.onbeforeunload = function() {
    return true;
    }
  }
</code>```

and

```<code>    window.onhashchange = function() {
  if(!location.href.match('domain')) {
    window.onbeforeunload = function() {
        return true;
    };
  }
}
</code>```

and plenty of other variations but they don't seem to work. Did anyone have a similar problem?

答: Long story short: using JS it isn't possible to know what the next adress is so it can't be done due to privacy policy. </p>

Body:
Is there a way to prevent redirects if they aren't on the same domain? There's this snippet that works well:

  window.onbeforeunload = function() {
    return true;
  }

But the problem is that it prompts user on every redirect. I would like to truncate prompts only to different domain redirects. I've tried:

window.addEventListener('beforeunload', function(e) {
  if (!location.href.match('domain')) {
    window.onbeforeunload = function() {
    return true;
    }
  }

and

    window.onhashchange = function() {
  if(!location.href.match('domain')) {
    window.onbeforeunload = function() {
        return true;
    };
  }
}

and plenty of other variations but they don't seem to work. Did anyone have a similar problem?


问:
How to build an aggregate table based on the another shiny table?
I want to have a output table in the UI that has a conditional column sum based on the text of "Column 3".

Here is my example code:

```<code>library(shiny)
runApp(list(
ui=pageWithSidebar(headerPanel("Adding entries to table"),
                 sidebarPanel(textInput("text1", "Column 1", "66"),
                              textInput("text2", "Column 2", "100"),
                              textInput("text3", "Column 3", "Tony"),
                              actionButton("update", "Update Table")),
                 mainPanel(tableOutput("table1"))),
server=function(input, output, session) {
values <- reactiveValues()
values$df <- data.frame(Column3 = character(),
                        Column1 = numeric(0),
                        Column2 = numeric(0),
                        stringsAsFactors = FALSE)
newEntry <- observe({
  if(input$update > 0) {
    newLine <- isolate(c(input$text3, input$text1, input$text2))
    isolate(values$df[nrow(values$df) + 1,] <- c(input$text3,
input$text1, input$text2))
  }
})
output$table1 <- renderTable({values$df})
}))
</code>```

If you click on the "Update Table" button twice, the output table that I would like to see it is:

```<code>`1    Tony    132    200`
</code>```

The names in "Column 3" will be different depends on the input value from the sidebar. The output table should observe that, and then return all the names with sum of "Column 1" and sum of "Column 2" under that name.

I tried to create a new data frame using the aggregate function on the values$df, but it is not working.

答:
I guess this is what you are aiming for. I have added appropriate comments in the code for you to understand. Hope it helps!</p>

```<code>library(shiny)
    runApp(list(
      ui=pageWithSidebar(headerPanel("Adding entries to table"),
                         sidebarPanel(textInput("text1", "Column 1", "66"),
                                      textInput("text2", "Column 2", "100"),
                                      textInput("text3", "Column 3", "Tony"),
                                      actionButton("update", "Update Table")),
                         mainPanel(tableOutput("table1"))),
      server=function(input, output, session) {
        values <- reactiveValues()
        values$df <- data.frame(Column3 = character(),
                                Column1 = numeric(0),
                                Column2 = numeric(0),
                                stringsAsFactors = FALSE)
        observeEvent(input$update,{
          # if(input$update > 0) {#This is not required as this observeEvent will only be triggered when we click 'update' button
            newLine <- isolate(c(input$text3, input$text1, input$text2))
            #If any column 3 has already been updated, just add the other columns
            if(any(values$df$Column3 == input$text3))
            {
              #Get the row where there is match in the Column3
              matchRow = which(values$df$Column3 == input$text3)
              #Just add the values in column2 and column3 with input values
              values$df$Column1[matchRow] <- as.numeric(values$df$Column1[matchRow])+as.numeric(input$text1)
              values$df$Column2[matchRow] <- as.numeric(values$df$Column2[matchRow])+as.numeric(input$text2)

            }else{#Just add the new rows

              isolate(values$df[nrow(values$df) + 1,] <- c(input$text3,
                                                           input$text1, input$text2))
            }
          # }
        })
        output$table1 <- renderTable({values$df})
      }))
</code>```

Body:
I want to have a output table in the UI that has a conditional column sum based on the text of "Column 3".

Here is my example code:

library(shiny)
runApp(list(
ui=pageWithSidebar(headerPanel("Adding entries to table"),
                 sidebarPanel(textInput("text1", "Column 1", "66"),
                              textInput("text2", "Column 2", "100"),
                              textInput("text3", "Column 3", "Tony"),
                              actionButton("update", "Update Table")),
                 mainPanel(tableOutput("table1"))),
server=function(input, output, session) {
values <- reactiveValues()
values$df <- data.frame(Column3 = character(),
                        Column1 = numeric(0),
                        Column2 = numeric(0),
                        stringsAsFactors = FALSE)
newEntry <- observe({
  if(input$update > 0) {
    newLine <- isolate(c(input$text3, input$text1, input$text2))
    isolate(values$df[nrow(values$df) + 1,] <- c(input$text3,
input$text1, input$text2))
  }
})
output$table1 <- renderTable({values$df})
}))

If you click on the "Update Table" button twice, the output table that I would like to see it is:

`1    Tony    132    200`

The names in "Column 3" will be different depends on the input value from the sidebar. The output table should observe that, and then return all the names with sum of "Column 1" and sum of "Column 2" under that name.

I tried to create a new data frame using the aggregate function on the values$df, but it is not working.

Body:
I guess this is what you are aiming for. I have added appropriate comments in the code for you to understand. Hope it helps!

library(shiny)
    runApp(list(
      ui=pageWithSidebar(headerPanel("Adding entries to table"),
                         sidebarPanel(textInput("text1", "Column 1", "66"),
                                      textInput("text2", "Column 2", "100"),
                                      textInput("text3", "Column 3", "Tony"),
                                      actionButton("update", "Update Table")),
                         mainPanel(tableOutput("table1"))),
      server=function(input, output, session) {
        values <- reactiveValues()
        values$df <- data.frame(Column3 = character(),
                                Column1 = numeric(0),
                                Column2 = numeric(0),
                                stringsAsFactors = FALSE)
        observeEvent(input$update,{
          # if(input$update > 0) {#This is not required as this observeEvent will only be triggered when we click 'update' button
            newLine <- isolate(c(input$text3, input$text1, input$text2))
            #If any column 3 has already been updated, just add the other columns
            if(any(values$df$Column3 == input$text3))
            {
              #Get the row where there is match in the Column3
              matchRow = which(values$df$Column3 == input$text3)
              #Just add the values in column2 and column3 with input values
              values$df$Column1[matchRow] <- as.numeric(values$df$Column1[matchRow])+as.numeric(input$text1)
              values$df$Column2[matchRow] <- as.numeric(values$df$Column2[matchRow])+as.numeric(input$text2)

            }else{#Just add the new rows

              isolate(values$df[nrow(values$df) + 1,] <- c(input$text3,
                                                           input$text1, input$text2))
            }
          # }
        })
        output$table1 <- renderTable({values$df})
      }))


问:
Issues with Python while loop
I am currently having issues with a while loop in python

```<code>! curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open("mean_temp.txt", "a+")
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
headings = mean_temp.readline().split(",")

while mean_temp.readline():
    city_temp = mean_temp.readline().split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is",
    city_temp[2], "Celcius")
</code>```

This code currently skips the first and every other line when printing

Current output:

City of Cairo month ave: highest high is 34.7 Celcius

City of Nairobi month ave: highest high is 26.3 Celcius

City of Sydney month ave: highest high is 26.5 Celcius

City of Rio de Janeiro month ave: highest high is 30.0 Celcius

Required output:

City of Beijing month ave: highest high is 30.9 Celsius

City of Cairo month ave: highest high is 34.7 Celsius

City of London month ave: highest high is 23.5 Celsius

City of Nairobi month ave: highest high is 26.3 Celsius

City of New York City month ave: highest high is 28.9 Celsius

City of Sydney month ave: highest high is 26.5 Celsius

City of Tokyo month ave: highest high is 30.8 Celsius

City of Rio De Janeiro month ave: highest high is 30.0 Celsius

Thanks for your help

答:
You are reading 2 lines in one loop and printing it once. Instead use below code in place of while loop:</p>

```<code>for row in mean_temp:
    city_temp = row.split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is", city_temp[2], "Celcius")
</code>```

Title: Issues with Python while loop

Body:
I am currently having issues with a while loop in python

! curl https://raw.githubusercontent.com/MicrosoftLearning/intropython/master/world_temp_mean.csv -o mean_temp.txt

mean_temp = open("mean_temp.txt", "a+")
mean_temp.write("Rio de Janeiro,Brazil,30.0,18.0\n")
mean_temp.seek(0)
headings = mean_temp.readline().split(",")

while mean_temp.readline():
    city_temp = mean_temp.readline().split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is",
    city_temp[2], "Celcius")

This code currently skips the first and every other line when printing

Current output:

City of Cairo month ave: highest high is 34.7 Celcius

City of Nairobi month ave: highest high is 26.3 Celcius

City of Sydney month ave: highest high is 26.5 Celcius

City of Rio de Janeiro month ave: highest high is 30.0 Celcius

Required output:

City of Beijing month ave: highest high is 30.9 Celsius

City of Cairo month ave: highest high is 34.7 Celsius

City of London month ave: highest high is 23.5 Celsius

City of Nairobi month ave: highest high is 26.3 Celsius

City of New York City month ave: highest high is 28.9 Celsius

City of Sydney month ave: highest high is 26.5 Celsius

City of Tokyo month ave: highest high is 30.8 Celsius

City of Rio De Janeiro month ave: highest high is 30.0 Celsius

Thanks for your help

Body:
You are reading 2 lines in one loop and printing it once. Instead use below code in place of while loop:

for row in mean_temp:
    city_temp = row.split(",")
    print(headings[0].title(), "of",  city_temp[0], headings[2], "is", city_temp[2], "Celcius")


问:
OpenGL Error when using TAndroidHelper.Context in FMX Android APP
I am developing an APP with Rad Studio 10.2 and all hotfixes.

I now have a problem with icons that I added to the APP. Under Android 5 and some Android 7 devices (e. g. HTC One AICP) the ListView with the self-created icons works wonderfully. However, if I test this on a OnePlus One with Lineage OS (also Android 7) or some other Android 7 devices with manufacturer OS, the images are not shown on second app start (first works). I get the following error messages (on all! Devices) in the Android LogCat between the last "Application.CreateForm" or "Application.Run;"(in Project.dpr) and the first call of Form.Create:

12-05 11:40:28.395 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
  12-05 11:40:28.395 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/libEGL: call to OpenGL ES API with no current context (logged once per thread)
  12-05 11:40:28.395 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
  12-05 11:40:28.395 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/libEGL: call to OpenGL ES API with no current context (logged once per thread)

After that I get further error messages which look like this:

12-05 11:42:32.115 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:42:32.115 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:42:32.115 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:42:32.116 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Textur für 'TContextAndroid' kann nicht erstellt werden.
  12-05 11:42:32.118 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:42:32.119 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:42:32.119 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:42:32.119 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Textur für 'TContextAndroid' kann nicht erstellt werden.
  12-05 11:42:32.122 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:42:32.122 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:42:32.122 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:44:04.148 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Textur für 'TContextAndroid' kann nicht erstellt werden.
  12-05 11:44:04.178 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:44:04.178 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:44:04.178 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:44:04.179 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Schattiererprogramm für 'TContextAndroid' kann nicht aktiviert werden.
  12-05 11:44:04.179 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:44:04.179 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:44:04.179 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:44:04.186 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Fehler in der Kontextmethode "DoFinalizeTexture".
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Schattiererprogramm für 'TContextAndroid' kann nicht aktiviert werden.
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx E/BufferQueueProducer: [SurfaceTexture-0-20262-0] dequeueBuffer: BufferQueue has been abandoned
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-EGLSUB: : dequeue native buffer fail: No such device, buffer=0x0, handle=0x0
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx W/Adreno-ES20: : GL_OUT_OF_MEMORY
  12-05 11:44:04.218 20262-20262/com.xxxxxx.xxxxxx.Xxxxxx I/info: FMX: X_APP NAME_X: [Context Exception]: Fehler in der Kontextmethode "DoFinalizeTexture".

As far as i could inspect these errors appear after using TAndroidHelper.Context or changing the icons.

As far as i could inspect this errors appear after using TAndroidHelper.Context or changing the icons.

Does anyone know why this only appear on serveral devices and how to fix this?

I dont know if this errors are connected to the not showing images.

I dont get why the images are not displayed/disappearing.

答:
After I built a minimal build of the app, I found out that this bug is related to TPrototypeBindSource and the live binding. If you remove this component, the images will be displayed correctly under the affected Android 7 devices.
A bug report is available:
https://quality.embarcadero.com/browse/RSP-19484</p>


问:
multiple image upload to different column php mysql
good day , here i have a page that store data with some images in it , 3 images to be exact,

    <?php
    $brg            = $_POST['id'];
    $nama           = $_POST['nm'];
    $img            = $_FILES['img']['name'];
    $tmp            = $_FILES['img']['tmp_name'];
    $img1           = $_FILES['img1']['name'];
    $tmp1           = $_FILES['img1']['tmp_name'];
    $img2           = $_FILES['img2']['name'];
    $tmp2           = $_FILES['img2']['tmp_name'];

    $temp           = explode(".", $img);
    $temp1          = explode(".", $img1);
    $temp2          = explode(".", $img2);
    $new            = round(microtime(true)) . '.' . end($temp);
    $new1           = round(microtime(true)) . '.' . end($temp1);
    $new2           = round(microtime(true)) . '.' . end($temp2);
    $path           = "img/photo/".$new;
    $path1          = "img/photo/".$new1;
    $path2          = "img/photo/".$new2;
    move_uploaded_file($tmp, $path);
    move_uploaded_file($tmp1, $path1);
    move_uploaded_file($tmp2, $path2);

$c  = "insert into imgstuff values('$brg','$nama','$new','$new1','$new2');";

$ins=mysqli_query($con,$c);

if($ins){
header('location: test.php?success='.base64_encode('success'));
} else {
header('location: test.php?error='.base64_encode('failed'));
}
?>
```

code above works perfectly but as you can see it ends up horribly ugly and it produce same file name for three picture ,
 my question, is there any ways to made my code cleaner and easy to maintain and whats wrong with my naming files method ?

答:
I'd be tempted to use a loop so that you do not repeat code unnecessarily and definitely to use prepared statements to avoid nasty unpleasantness from sql injection attacks

As for the new image name - there are many ways in which you can achieve a new, unique name - the method here is not necessarily going to be unique but it does at least incorporate the original filename so of the three images they should be unique. None of the below is tested btw but it might give you some ideas.

```<code><?php
    if( isset( $_POST['id'], $_POST['nm'] ){

        $files=array();

        $sql='insert into `imgstuff` values (?,?,?,?,?)';
        $stmt=$con->prepare( $sql );

        if( $stmt ){

            for( $i=0; $i < 3; $i++ ){

                $obj = $i==0 ? (object)$_FILES[ 'img' ] : (object)$_FILES[ 'img' . $i ];
                $tmp=$obj->tmp_name;
                $name=$obj->name;

                $ext = pathinfo( $name,PATHINFO_EXTENSION );
                $new = round( microtime( true ) ) . '_' . $name . '.' . $ext;

                $path = "img/photo/$new";
                $status = is_uploaded_file( $tmp ) & move_uploaded_file( $tmp, $path );
                if( $status ) $files[] = $path;
            }

            if( count( $files )==count( $imgs ) ){

                $brg  = $_POST['id'];
                $nama = $_POST['nm'];

                $stmt->bind_param( 'issss', $brg, $nama, $files[0], $files[1], $files[2] );
                $stmt->execute();

                $rows=$stmt->affected_rows;
                $message=$rows!=0 ? 'success' : 'failed';

                header('location: test.php?success=' . base64_encode( $message ) );
            }
        }
    }
?>
</code>```

Body:
good day , here i have a page that store data with some images in it , 3 images to be exact,

    <?php
    $brg            = $_POST['id'];
    $nama           = $_POST['nm'];
    $img            = $_FILES['img']['name'];
    $tmp            = $_FILES['img']['tmp_name'];
    $img1           = $_FILES['img1']['name'];
    $tmp1           = $_FILES['img1']['tmp_name'];
    $img2           = $_FILES['img2']['name'];
    $tmp2           = $_FILES['img2']['tmp_name'];

    $temp           = explode(".", $img);
    $temp1          = explode(".", $img1);
    $temp2          = explode(".", $img2);
    $new            = round(microtime(true)) . '.' . end($temp);
    $new1           = round(microtime(true)) . '.' . end($temp1);
    $new2           = round(microtime(true)) . '.' . end($temp2);
    $path           = "img/photo/".$new;
    $path1          = "img/photo/".$new1;
    $path2          = "img/photo/".$new2;
    move_uploaded_file($tmp, $path);
    move_uploaded_file($tmp1, $path1);
    move_uploaded_file($tmp2, $path2);

$c  = "insert into imgstuff values('$brg','$nama','$new','$new1','$new2');";

$ins=mysqli_query($con,$c);

if($ins){
header('location: test.php?success='.base64_encode('success'));
} else {
header('location: test.php?error='.base64_encode('failed'));
}
?>

code above works perfectly but as you can see it ends up horribly ugly and it produce same file name for three picture ,
 my question, is there any ways to made my code cleaner and easy to maintain and whats wrong with my naming files method ?

Body:
I'd be tempted to use a loop so that you do not repeat code unnecessarily and definitely to use prepared statements to avoid nasty unpleasantness from sql injection attacks

As for the new image name - there are many ways in which you can achieve a new, unique name - the method here is not necessarily going to be unique but it does at least incorporate the original filename so of the three images they should be unique. None of the below is tested btw but it might give you some ideas.

<?php
    if( isset( $_POST['id'], $_POST['nm'] ){

        $files=array();

        $sql='insert into `imgstuff` values (?,?,?,?,?)';
        $stmt=$con->prepare( $sql );

        if( $stmt ){

            for( $i=0; $i < 3; $i++ ){

                $obj = $i==0 ? (object)$_FILES[ 'img' ] : (object)$_FILES[ 'img' . $i ];
                $tmp=$obj->tmp_name;
                $name=$obj->name;

                $ext = pathinfo( $name,PATHINFO_EXTENSION );
                $new = round( microtime( true ) ) . '_' . $name . '.' . $ext;

                $path = "img/photo/$new";
                $status = is_uploaded_file( $tmp ) & move_uploaded_file( $tmp, $path );
                if( $status ) $files[] = $path;
            }

            if( count( $files )==count( $imgs ) ){

                $brg  = $_POST['id'];
                $nama = $_POST['nm'];

                $stmt->bind_param( 'issss', $brg, $nama, $files[0], $files[1], $files[2] );
                $stmt->execute();

                $rows=$stmt->affected_rows;
                $message=$rows!=0 ? 'success' : 'failed';

                header('location: test.php?success=' . base64_encode( $message ) );
            }
        }
    }
?>


问:
MySql: Error #1242 updating a column with data taken from another table
I need to update a column of a table, currently empty, with the data taken from another table.

I have two tables. The "ar_geozone" table has the following structure

```<code>ID -> primary key;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city;
name_countries;
name_regions;
kind_regions.
</code>```

The "name_regions, kind_regions" columns are empty and I would like to update only the "name_regions" column

The second "regions" table has the following structure:

```<code>country;
code;
name;
kind.
</code>```

All the columns in the table "regions" have records. However, the number of records is lower than those in the table "ar_geozone".

Using the following query

```<code>UPDATE ar_geozone ct
    SET name_regions =
     (SELECT name FROM regions ag
      WHERE ag.country LIKE ct.code_countries)
</code>```

the system gives me the error:

"#1242 - Subquery returns more than 1 row".

How should I modify the query to update the column?

答:
SQL LIKE Operator fetches more than one row. Which means you are trying to update name_regions with more than one country names.

```<code>UPDATE ar_geozone ct
    SET name_regions =
     (SELECT GROUP_CONCAT(name SEPARATOR ', ') FROM regions ag
      WHERE ag.country LIKE ct.code_countries)
</code>```

It will combine more than one row into comma separated String.

Body:
I need to update a column of a table, currently empty, with the data taken from another table.

I have two tables. The "ar_geozone" table has the following structure

ID -> primary key;
code_countries;
code_city;
name_city;
longitude_city;
latitude_city;
name_countries;
name_regions;
kind_regions.

The "name_regions, kind_regions" columns are empty and I would like to update only the "name_regions" column

The second "regions" table has the following structure:

country;
code;
name;
kind.

All the columns in the table "regions" have records. However, the number of records is lower than those in the table "ar_geozone".

Using the following query

UPDATE ar_geozone ct
    SET name_regions =
     (SELECT name FROM regions ag
      WHERE ag.country LIKE ct.code_countries)

the system gives me the error:

"#1242 - Subquery returns more than 1 row".

How should I modify the query to update the column?

Body:
SQL LIKE Operator fetches more than one row. Which means you are trying to update name_regions with more than one country names.

UPDATE ar_geozone ct
    SET name_regions =
     (SELECT GROUP_CONCAT(name SEPARATOR ', ') FROM regions ag
      WHERE ag.country LIKE ct.code_countries)

It will combine more than one row into comma separated String.


问:
Await time is high but %util is less for SSD disk
For following SSD disk, await time is high but %util is less.

```<code>Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
dm-3              0.00     0.00  132.00 2272.00   892.00 100244.00    84.14  1111.70  658.36    5.00  696.32   0.20  49.20
</code>```

%util is ((r/s + w/s) * svctm/1000)*100 and util represents percentage of time device spent in servicing requests. So, ~50% util is not high.

On the other hand, await time is pretty high. Tasks actual await time in the queue is "await - svctm" i.e. (658.36 - 0.20)*100/658.36, which is close to 100%. That means that tasks are spending most of time waiting in the queue.

If util is low but await time is high, is disk being utilized properly? Which one of these two metrics is more reliable for SSDs?

答:
Screenshot shows your write wait time is high. SSD write generally tend to get slow after usage as they fill up and because of many other reasons like,

Compatibility issues - Check compatibility with your HW

If you clone the partition from HDD to SSD

If TRIM is not enabled

If its not initialized with zeros/ones

If its behind any IOcontroller then IOcontroller itself might be slow

Check what all scenarios fits you and perform cleanup/initialization once and see if it resolves the issue. For compatibility issues, you might need to contact support team.

Body:
For following SSD disk, await time is high but %util is less.

Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
dm-3              0.00     0.00  132.00 2272.00   892.00 100244.00    84.14  1111.70  658.36    5.00  696.32   0.20  49.20

%util is ((r/s + w/s) * svctm/1000)*100 and util represents percentage of time device spent in servicing requests. So, ~50% util is not high.

On the other hand, await time is pretty high. Tasks actual await time in the queue is "await - svctm" i.e. (658.36 - 0.20)*100/658.36, which is close to 100%. That means that tasks are spending most of time waiting in the queue.

If util is low but await time is high, is disk being utilized properly? Which one of these two metrics is more reliable for SSDs?


问:
Is it secure to run public ethereum node?
I'm creating my first Ethereum contract with truffle. I want the web application to be usable without MetaMask so I was wondering if it is a good idea to run my own private node and to
connect from the frontend like this:

```<code>this.web3 = new Web3(new Web3.providers.HttpProvider('http://my-public-ip:8545'));
</code>```

Are there any security risks with this approach?

答:
Here is how I did it, but it allows bots to steal the ether from these accounts:

I did setup publicly accessible node like this:

```<code>geth  --mine  --nodiscover  --maxpeers 0  --networkid 1  --rpc  --rpccorsdomain "*" --rpcaddr "my-public-ip" --rpcapi="db,eth,net,web3,personal,web3"
</code>```

I created a new Ethereum account that is going to be my "contract owner" account

I transferred a small amount of ether into the "contract owner" account so I would have enough gas to deploy my new contract

I did setup truffle to connect to my Ethereum node

I used truffle console to unlock my account

I got the error "Error: exceeds block gas limit"

At this point I was confused, because I saw that on etherscan I have about 10USD worth of ether in my account. That should be enough to deploy my contract.

I checked etherscan again, and I saw "outgoing" transactions draining all my money from the Ethereum address. This is how the money was stolen:

A bot found out about my public Ethereum node

It connected to it and requested the account list + account balances

It started sending sendTransaction requests non stop

When I unlocked my account on the public node to deploy my contract - the bot that was using the same node also got access to my account and it transferred the funds from my account

Body:
I'm creating my first Ethereum contract with truffle. I want the web application to be usable without MetaMask so I was wondering if it is a good idea to run my own private node and to
connect from the frontend like this:

this.web3 = new Web3(new Web3.providers.HttpProvider('http://my-public-ip:8545'));

Are there any security risks with this approach?

Body:
Here is how I did it, but it allows bots to steal the ether from these accounts:

I did setup publicly accessible node like this:

geth  --mine  --nodiscover  --maxpeers 0  --networkid 1  --rpc  --rpccorsdomain "*" --rpcaddr "my-public-ip" --rpcapi="db,eth,net,web3,personal,web3"

I created a new Ethereum account that is going to be my "contract owner" account

I transferred a small amount of ether into the "contract owner" account so I would have enough gas to deploy my new contract

I did setup truffle to connect to my Ethereum node

I used truffle console to unlock my account

I got the error "Error: exceeds block gas limit"

At this point I was confused, because I saw that on etherscan I have about 10USD worth of ether in my account. That should be enough to deploy my contract.

I checked etherscan again, and I saw "outgoing" transactions draining all my money from the Ethereum address. This is how the money was stolen:

A bot found out about my public Ethereum node

It connected to it and requested the account list + account balances

It started sending sendTransaction requests non stop

When I unlocked my account on the public node to deploy my contract - the bot that was using the same node also got access to my account and it transferred the funds from my account


问:
Docker-php-ext-install mcrypt missing folder
I try to install mcrypt in my docker image based on php:7.2-apache. Therefore I use the RUN-Command from the documentation and also answerd here but I receive this error:

```<code>error: /usr/src/php/ext/mcrypt does not exist

usage: /usr/local/bin/docker-php-ext-install [-jN] ext-name [ext-name ...]

   ie: /usr/local/bin/docker-php-ext-install gd mysqli
   /usr/local/bin/docker-php-ext-install pdo pdo_mysql
   /usr/local/bin/docker-php-ext-install -j5 gd mbstring mysqli pdo pdo_mysql shmop

if custom ./configure arguments are necessary, see docker-php-ext-configure

Possible values for ext-name:
bcmath bz2 calendar ctype curl dba dom enchant exif fileinfo filter ftp  gd gettext gmp hash iconv imap interbase intl json ldap mbstring mysqli oci8  odbc opcache pcntl pdo pdo_dblib pdo_firebird pdo_mysql pdo_oci pdo_odbc pdo_pgsql pdo_sqlite pgsql phar posix pspell readline recode reflection session shmop simplexml snmp soap sockets sodium spl standard sysvmsg sysvsem sysvshm tidy tokenizer wddx xml xmlreader xmlrpc xmlwriter xsl zend_test zip

Some of the above modules are already compiled into PHP; please check
the output of "php -i" to see which modules are already loaded.
ERROR: Service 'web' failed to build: The command '/bin/sh -c apt-get update && apt-get install -y          libfreetype6-dev          libjpeg62-turbo-dev          libmcrypt-dev          libpng-dev     && docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip' returned a non-zero code: 1
</code>```

My Dockerfile:

```<code>FROM php:7.2-apache

RUN apt-get update && apt-get install -y \
     libfreetype6-dev \
     libjpeg62-turbo-dev \
     libmcrypt-dev \
     libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip
#    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
#    && docker-php-ext-install -j$(nproc) gd

COPY ./etc/000-default.conf /etc/apache2/sites-available/

EXPOSE 80
</code>```

Has anybody an idea how to solve or how to get the needed files in the requested folder?

Thanks!

答:
To install mcrypt extension you have to make sure you did install libmcrypt-dev which is required.

Try to add:

```<code>RUN apt install libmcrypt-dev
</code>```

before you are trying to install extensions for php.

Update

Try to run first:

```<code>docker-php-ext-configure mcrypt
</code>```

and then

```<code>docker-php-ext-install mcrypt
</code>```

Body:
I try to install mcrypt in my docker image based on php:7.2-apache. Therefore I use the RUN-Command from the documentation and also answerd here but I receive this error:

error: /usr/src/php/ext/mcrypt does not exist

usage: /usr/local/bin/docker-php-ext-install [-jN] ext-name [ext-name ...]

   ie: /usr/local/bin/docker-php-ext-install gd mysqli
   /usr/local/bin/docker-php-ext-install pdo pdo_mysql
   /usr/local/bin/docker-php-ext-install -j5 gd mbstring mysqli pdo pdo_mysql shmop

if custom ./configure arguments are necessary, see docker-php-ext-configure

Possible values for ext-name:
bcmath bz2 calendar ctype curl dba dom enchant exif fileinfo filter ftp  gd gettext gmp hash iconv imap interbase intl json ldap mbstring mysqli oci8  odbc opcache pcntl pdo pdo_dblib pdo_firebird pdo_mysql pdo_oci pdo_odbc pdo_pgsql pdo_sqlite pgsql phar posix pspell readline recode reflection session shmop simplexml snmp soap sockets sodium spl standard sysvmsg sysvsem sysvshm tidy tokenizer wddx xml xmlreader xmlrpc xmlwriter xsl zend_test zip

Some of the above modules are already compiled into PHP; please check
the output of "php -i" to see which modules are already loaded.
ERROR: Service 'web' failed to build: The command '/bin/sh -c apt-get update && apt-get install -y          libfreetype6-dev          libjpeg62-turbo-dev          libmcrypt-dev          libpng-dev     && docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip' returned a non-zero code: 1

My Dockerfile:

FROM php:7.2-apache

RUN apt-get update && apt-get install -y \
     libfreetype6-dev \
     libjpeg62-turbo-dev \
     libmcrypt-dev \
     libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip
#    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
#    && docker-php-ext-install -j$(nproc) gd

COPY ./etc/000-default.conf /etc/apache2/sites-available/

EXPOSE 80

Has anybody an idea how to solve or how to get the needed files in the requested folder?

Thanks!

Body:
To install mcrypt extension you have to make sure you did install libmcrypt-dev which is required.

Try to add:

RUN apt install libmcrypt-dev

before you are trying to install extensions for php.

Update

Try to run first:

docker-php-ext-configure mcrypt

and then

docker-php-ext-install mcrypt


问:
Python 3 - Flask Restful API to restart another API
I created a python REST web-service, and it will execute a series of subprocess commands to restart another python REST webservice. But the problem is it doesn't really start my other REST service after I call it.

Here is my code for the REST API :

```<code>from flask import Flask, jsonify, request, make_response
from flask_restful import fields, reqparse, abort, Api, Resource
import sqlalchemy
from sqlalchemy.sql import table, column, select, update, insert, delete, func
from sqlalchemy.orm import sessionmaker
import requests
import time
import traceback
import subprocess
import os

app = Flask(__name__)
api = Api(app)

class RestartPython(Resource):
    def get(self):

        command1 = 'fuser -k 9876/tcp'
        proc1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        proc1.wait()

        print('kill python process done')

        command2 = 'source activate envpy3'
        proc2 = subprocess.Popen(command2, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        proc2.wait()

        print('switch python env done')

        command3 = 'python ReceiveCall.py'
        print(command3)
        proc3 = subprocess.Popen(command3, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        proc3.wait()

        print('ReceiveCall started')

        return make_response(jsonify({'message': 'Python webservice is restarted', 'status': 'Ok'}), 200)

    api.add_resource(RestartPython, '/restart')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8082, debug=True)
</code>```

This will works if I just run it without wrapping them in web-service

```<code>import subprocess

if __name__ == '__main__':
    command1 = 'fuser -k 9876/tcp'
    proc1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
    proc1.wait()

    print('kill python process done')

    command2 = 'source activate envpy3'
    proc2 = subprocess.Popen(command2, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
    proc2.wait()

    print('switch python env done')

    command3 = 'python ReceiveCall.py'
    print(command3)
    proc3 = subprocess.Popen(command3, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
    proc3.wait()

    print('ReceiveCall started')
</code>```

Any ideas?

答:
instead of wait() i would recommend to use communicate() . communicate is used to avoid deadlock wherever pipe is used . Let me know if below modification works for you</p>

```<code>from flask import Flask, jsonify, request, make_response
from flask_restful import fields, reqparse, abort, Api, Resource
import sqlalchemy
from sqlalchemy.sql import table, column, select, update, insert, delete, func
from sqlalchemy.orm import sessionmaker
import requests
import time
import traceback
import subprocess
from subprocess import PIPE,Popen
import os

app = Flask(__name__)
api = Api(app)

class RestartPython(Resource):
    def get(self):

        command1 = 'fuser -k 9876/tcp'
        proc1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        #proc1.wait()
        (stdout, stderr) = proc1.communicate()

        print '.'.join(stdout)
        print '.'.join(stderr)

        print('kill python process done')

        command2 = 'source activate envpy3'
        proc2 = subprocess.Popen(command2, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        #proc2.wait()
        proc2.communicate()

        print('switch python env done')

        command3 = 'python ReceiveCall.py'
        print(command3)
        proc3 = subprocess.Popen(command3, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        #proc3.wait()
         proc3.communicate()

        print('ReceiveCall started')

        return make_response(jsonify({'message': 'Python webservice is restarted', 'status': 'Ok'}), 200)

    api.add_resource(RestartPython, '/restart')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8082, debug=True)
</code>```

Body:
I created a python REST web-service, and it will execute a series of subprocess commands to restart another python REST webservice. But the problem is it doesn't really start my other REST service after I call it.

Here is my code for the REST API :

from flask import Flask, jsonify, request, make_response
from flask_restful import fields, reqparse, abort, Api, Resource
import sqlalchemy
from sqlalchemy.sql import table, column, select, update, insert, delete, func
from sqlalchemy.orm import sessionmaker
import requests
import time
import traceback
import subprocess
import os

app = Flask(__name__)
api = Api(app)

class RestartPython(Resource):
    def get(self):

        command1 = 'fuser -k 9876/tcp'
        proc1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        proc1.wait()

        print('kill python process done')

        command2 = 'source activate envpy3'
        proc2 = subprocess.Popen(command2, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        proc2.wait()

        print('switch python env done')

        command3 = 'python ReceiveCall.py'
        print(command3)
        proc3 = subprocess.Popen(command3, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        proc3.wait()

        print('ReceiveCall started')

        return make_response(jsonify({'message': 'Python webservice is restarted', 'status': 'Ok'}), 200)

    api.add_resource(RestartPython, '/restart')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8082, debug=True)

This will works if I just run it without wrapping them in web-service

import subprocess

if __name__ == '__main__':
    command1 = 'fuser -k 9876/tcp'
    proc1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
    proc1.wait()

    print('kill python process done')

    command2 = 'source activate envpy3'
    proc2 = subprocess.Popen(command2, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
    proc2.wait()

    print('switch python env done')

    command3 = 'python ReceiveCall.py'
    print(command3)
    proc3 = subprocess.Popen(command3, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
    proc3.wait()

    print('ReceiveCall started')

Any ideas?

Body:
instead of wait() i would recommend to use communicate() . communicate is used to avoid deadlock wherever pipe is used . Let me know if below modification works for you

from flask import Flask, jsonify, request, make_response
from flask_restful import fields, reqparse, abort, Api, Resource
import sqlalchemy
from sqlalchemy.sql import table, column, select, update, insert, delete, func
from sqlalchemy.orm import sessionmaker
import requests
import time
import traceback
import subprocess
from subprocess import PIPE,Popen
import os

app = Flask(__name__)
api = Api(app)

class RestartPython(Resource):
    def get(self):

        command1 = 'fuser -k 9876/tcp'
        proc1 = subprocess.Popen(command1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        #proc1.wait()
        (stdout, stderr) = proc1.communicate()

        print '.'.join(stdout)
        print '.'.join(stderr)

        print('kill python process done')

        command2 = 'source activate envpy3'
        proc2 = subprocess.Popen(command2, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        #proc2.wait()
        proc2.communicate()

        print('switch python env done')

        command3 = 'python ReceiveCall.py'
        print(command3)
        proc3 = subprocess.Popen(command3, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, shell=True)
        #proc3.wait()
         proc3.communicate()

        print('ReceiveCall started')

        return make_response(jsonify({'message': 'Python webservice is restarted', 'status': 'Ok'}), 200)

    api.add_resource(RestartPython, '/restart')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8082, debug=True)


问:
Can I detect at compile time "function arguments" that are compile-time constants
Can I detect at compile time whether "function arguments"1 are compile-time constants?

For example a function print(int i) that can print "constant 5" if called as print(5) but "non-constant 5" if called as print(i) where i is some non-constant variable. In particular, in the "is constant" branch I should be able to treat i as a constexpr, including using it for template arguments, etc.

Macro tricks, template meta-programming and SFINAE tricks are all OK. Ideally it is portable, but solutions that are compiler-specific are better than nothing.

It's OK if there are "false negatives" - i.e., if constant values are sometimes detected as non-constant (e.g., when certain optimizations are disabled).

Bonus points if the solution can detect when constant values are indirectly passed to the function (e.g., when a constant value is passed to an intermediate function that calls print and which is subsequently inlined exposing the constant to print). This last behavior is evidently optimization dependent.

Double bonus points if it naturally extends to multiple arguments.

If one could have overloaded versions of functions with and without constexpr arguments this would presumably be straightforward, but you can't.

1 I'm putting "function arguments" in quotes here because the solution doesn't strictly require detecting this state within a function (or at the caller/callee boundary with special arguments) - it just has to appear to the caller like a function but macros or other tricks like a static object with operator() etc could be used.

答:
For detecting the constexpr suitability one may consider this GCC-only suggestion from @JohannesSchaub-litb (see linked answer for limitations):

```<code>template<typename T>
constexpr typename remove_reference<T>::type makeprval(T && t) {
  return t;
}
</code>```

A working example with different cases reads

```<code>#include <iostream>

////////////////////////////////////////////////////////////////////////////////

// https://stackoverflow.com/a/13305072/2615118

template<class T>
constexpr std::remove_reference_t<T> makeprval(T&& t) {
  return t;
}

#define isprvalconstexpr(e) noexcept(makeprval(e))

////////////////////////////////////////////////////////////////////////////////

template<bool is_constexpr, class Lambda>
struct HybridArg {
  using T = std::invoke_result_t<Lambda>;

  Lambda lambda_;
  constexpr operator T() const { return lambda_(); }// implicit conversion
};

template<bool is_constexpr, class Lambda>
constexpr auto make_hybrid_arg(Lambda lambda) {
  return HybridArg<is_constexpr, Lambda>{lambda};
}

#define WRAP_ARG(arg)                     \
  make_hybrid_arg<isprvalconstexpr(arg)>( \
    [&] { return arg; }                   \
  )                                       \

////////////////////////////////////////////////////////////////////////////////

template<int i>
void print_impl_constexpr() {
  std::cout << i << ": ";
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

void print_impl_fallback(int i) {
  std::cout << i << ": ";
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

////////////////////////////////////////////////////////////////////////////////

// option 1 (for choosing implementation):
// compile-time introspection

template<class Arg>
struct is_constexpr_arg : std::false_type {};

template<class Lambda>
struct is_constexpr_arg<
  HybridArg<true, Lambda>
> : std::true_type {};

template<class Arg>
void print_by_introspection(Arg arg) {
  if constexpr(is_constexpr_arg<Arg>{}) {
    print_impl_constexpr<arg>();
  }
  else {
    print_impl_fallback(arg);
  }
}

////////////////////////////////////////////////////////////////////////////////

// option 2 (for choosing implementation):
// overload

void print_by_overload(int arg) {
  print_impl_fallback(arg);
}

template<class Lambda>
void print_by_overload(HybridArg<true, Lambda> arg) {
  print_impl_constexpr<arg>();
}

////////////////////////////////////////////////////////////////////////////////

template<class Arg>
void indirection(Arg arg) {
  print_by_introspection(arg);
  print_by_overload(arg);
}

void bad_indirection(int arg) {
  print_by_introspection(arg);
  print_by_overload(arg);
}

////////////////////////////////////////////////////////////////////////////////

int main() {
  {
    int i = 0;
    indirection(i);
  }
  {
    int i = 1;
    indirection(WRAP_ARG(i));
  }
  {
    constexpr int i = 2;
    indirection(WRAP_ARG(i));
  }
  {
    constexpr int i = 3;
    bad_indirection(WRAP_ARG(i));
  }
}
</code>```

Output after compilation with GCC:

```<code>0: void print_impl_fallback(int)
0: void print_impl_fallback(int)
1: void print_impl_fallback(int)
1: void print_impl_fallback(int)
2: void print_impl_constexpr() [with int i = 2]
2: void print_impl_constexpr() [with int i = 2]
3: void print_impl_fallback(int)
3: void print_impl_fallback(int)
</code>```

Body:
For detecting the constexpr suitability one may consider this GCC-only suggestion from @JohannesSchaub-litb (see linked answer for limitations):

template<typename T>
constexpr typename remove_reference<T>::type makeprval(T && t) {
  return t;
}

A working example with different cases reads

#include <iostream>

////////////////////////////////////////////////////////////////////////////////

// https://stackoverflow.com/a/13305072/2615118

template<class T>
constexpr std::remove_reference_t<T> makeprval(T&& t) {
  return t;
}

#define isprvalconstexpr(e) noexcept(makeprval(e))

////////////////////////////////////////////////////////////////////////////////

template<bool is_constexpr, class Lambda>
struct HybridArg {
  using T = std::invoke_result_t<Lambda>;

  Lambda lambda_;
  constexpr operator T() const { return lambda_(); }// implicit conversion
};

template<bool is_constexpr, class Lambda>
constexpr auto make_hybrid_arg(Lambda lambda) {
  return HybridArg<is_constexpr, Lambda>{lambda};
}

#define WRAP_ARG(arg)                     \
  make_hybrid_arg<isprvalconstexpr(arg)>( \
    [&] { return arg; }                   \
  )                                       \

////////////////////////////////////////////////////////////////////////////////

template<int i>
void print_impl_constexpr() {
  std::cout << i << ": ";
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

void print_impl_fallback(int i) {
  std::cout << i << ": ";
  std::cout << __PRETTY_FUNCTION__ << std::endl;
}

////////////////////////////////////////////////////////////////////////////////

// option 1 (for choosing implementation):
// compile-time introspection

template<class Arg>
struct is_constexpr_arg : std::false_type {};

template<class Lambda>
struct is_constexpr_arg<
  HybridArg<true, Lambda>
> : std::true_type {};

template<class Arg>
void print_by_introspection(Arg arg) {
  if constexpr(is_constexpr_arg<Arg>{}) {
    print_impl_constexpr<arg>();
  }
  else {
    print_impl_fallback(arg);
  }
}

////////////////////////////////////////////////////////////////////////////////

// option 2 (for choosing implementation):
// overload

void print_by_overload(int arg) {
  print_impl_fallback(arg);
}

template<class Lambda>
void print_by_overload(HybridArg<true, Lambda> arg) {
  print_impl_constexpr<arg>();
}

////////////////////////////////////////////////////////////////////////////////

template<class Arg>
void indirection(Arg arg) {
  print_by_introspection(arg);
  print_by_overload(arg);
}

void bad_indirection(int arg) {
  print_by_introspection(arg);
  print_by_overload(arg);
}

////////////////////////////////////////////////////////////////////////////////

int main() {
  {
    int i = 0;
    indirection(i);
  }
  {
    int i = 1;
    indirection(WRAP_ARG(i));
  }
  {
    constexpr int i = 2;
    indirection(WRAP_ARG(i));
  }
  {
    constexpr int i = 3;
    bad_indirection(WRAP_ARG(i));
  }
}

Output after compilation with GCC:

0: void print_impl_fallback(int)
0: void print_impl_fallback(int)
1: void print_impl_fallback(int)
1: void print_impl_fallback(int)
2: void print_impl_constexpr() [with int i = 2]
2: void print_impl_constexpr() [with int i = 2]
3: void print_impl_fallback(int)
3: void print_impl_fallback(int)