问:
How can I collapse a fat toolbar into a one-liner?
I have a toolbar that I need to collapse, but all the examples I've seen of a CollapsingToolbarLayout just collapse an image into a minimal toolbar. Is it possible to collapse the following into a one-line toolbar that includes only a title?

Here is the XML for the above toolbar:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    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="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:title="@string/app_header"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextAppearance="@style/ToolbarTitle">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/login"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/login" />

                    <TextView
                        android:id="@+id/login_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/login"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/intro"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/account_switch" />

                    <TextView
                        android:id="@+id/intro_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/intro_page"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/video"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/video" />

                    <TextView
                        android:id="@+id/video_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/video_page"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/tutorial"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/book" />

                    <TextView
                        android:id="@+id/tutorial_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/tutorial_page"
                        />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/edit_profile"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/account_edit" />

                    <TextView
                        android:id="@+id/edit_profile_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorDisabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/create_profile2"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/in_common"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/account_search" />

                    <TextView
                        android:id="@+id/in_common_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorDisabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/what_in_common2"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/edit_colors"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/palette" />

                    <TextView
                        android:id="@+id/edit_colors_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorDisabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/settings_color"
                        />
                    </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/software_license"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/file_outline" />

                    <TextView
                        android:id="@+id/software_license_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/eula"
                        />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
</code>```

答: I finally got the toolbar to collapse, only to remove the code almost immediately. It turns out that the CollapsingToolbarLayout is incompatible with views that contain scrollable objects, like ListViews, as mine does.</p>

Body:
I have a toolbar that I need to collapse, but all the examples I've seen of a CollapsingToolbarLayout just collapse an image into a minimal toolbar. Is it possible to collapse the following into a one-line toolbar that includes only a title?

Here is the XML for the above toolbar:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    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="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:title="@string/app_header"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:titleTextAppearance="@style/ToolbarTitle">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/login"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/login" />

                    <TextView
                        android:id="@+id/login_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/login"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/intro"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/account_switch" />

                    <TextView
                        android:id="@+id/intro_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/intro_page"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/video"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/video" />

                    <TextView
                        android:id="@+id/video_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/video_page"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/tutorial"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/book" />

                    <TextView
                        android:id="@+id/tutorial_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/tutorial_page"
                        />
                </LinearLayout>
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/edit_profile"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/account_edit" />

                    <TextView
                        android:id="@+id/edit_profile_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorDisabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/create_profile2"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/in_common"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/account_search" />

                    <TextView
                        android:id="@+id/in_common_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorDisabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/what_in_common2"
                        />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/edit_colors"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/palette" />

                    <TextView
                        android:id="@+id/edit_colors_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorDisabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/settings_color"
                        />
                    </LinearLayout>

                <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:orientation="vertical">

                    <ImageButton
                        android:id="@+id/software_license"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        app:srcCompat="@drawable/file_outline" />

                    <TextView
                        android:id="@+id/software_license_text"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorEnabled"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/eula"
                        />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>


来源: stackexchange

问:
Structured Data Testing Tool showing JSON-LD syntax error: "value, object or array expected"
I have inputted my businesses name and it's still not excepting it and I have no idea why.

答:
You mix straight quotes (") and smart quotes (“, ”). Smart quotes look better in English writing and are used in professionally-printed books, but most programming languages don’t recognize them. By default, the quotation-mark key on your keyboard makes straight quotes, but a lot of word processors know that more people write prose than code and replace them with smart quotes; you always use a text editor or IDE which doesn’t do that when writing code.

In particular, the value of the name key is enclosed in smart quotes, and the value of the url key starts with a straight quote but ends with a smart quote.

ContentLicense: CC BY-SA 3.0


问:
How to create a new row with the total sum of a axis
I need create a new row with the total value of axis 0 sum.

I have the follow series values:

```<code>INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62
</code>```

How can i add a new row at the end of series with the total sum, like this:

```<code>INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62
TOTAL   0.26
</code>```

Body:
I need create a new row with the total value of axis 0 sum.

I have the follow series values:

INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62

How can i add a new row at the end of series with the total sum, like this:

INDEX
0      -1.09
1       1.15
2      -0.28
3      -0.14
4       0.62
TOTAL   0.26


问:
Error: The object cannot be deleted because it was not found in the ObjectStateManager
Trying to get a handle on Entity Framework here and I am hitting some speed bumps...
I have a Get() method that works fine and has been tested, but my Delete method is not working:

```<code>   public static void Delete(string name)
    {
        J1Entities db = new J1Entities();
        db.DeleteObject(Get(name));
        db.SaveChanges();
    }
</code>```

But I get the following error:
Error: The object cannot be deleted because it was not found in the ObjectStateManager.

I ran the debugger, and the object inside the DeleteObject is correct... what am I missing?  Thank you.

答:
Each EF object is tightly associated to the manager (for want of a better word) that created it. or to which it has been associated. Since you don't pass db to your Get method, I assume that Get has either used it's own J1Entities, or the object has been created standalone (perhaps deserialized).

In order to delete it, it must know about it first. That might mean by attaching an object to the manager - but in this case, it seems like an easier option is just to pass db into Get, so that the Get is done in the same context (since db will automatically attach objects that it creates itself).

Body:
Trying to get a handle on Entity Framework here and I am hitting some speed bumps...
I have a Get() method that works fine and has been tested, but my Delete method is not working:

   public static void Delete(string name)
    {
        J1Entities db = new J1Entities();
        db.DeleteObject(Get(name));
        db.SaveChanges();
    }

But I get the following error:
Error: The object cannot be deleted because it was not found in the ObjectStateManager.

I ran the debugger, and the object inside the DeleteObject is correct... what am I missing?  Thank you.

OwnerDisplayName: Marc Gravell

ContentLicense: CC BY-SA 2.5


问:
Ways to make it easier to work with shared pointers in C++
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

```<code>class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };
</code>```

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?

答:
Regarding the typedef, you should take a look on this question which addresses the exact same issue.

For the second part, I believe you are mistaken as std::shared_ptr can be used for incomplete types, as specified in 20.9.10.2/2 of N3225 :

The template parameter T of shared_ptr
  may be an incomplete type.

If your current implementation does not support that, I think it should be considered a bug.

Body:
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?


问:
How to compare button options against array then disable it using jquery
I want to disable a button or change its class if it is not a valid option.

I am using this for product options on an eCommerce site.

I have 3 arrays.  The first 2 i use to create the button combinations.  I am thinking I can use the last array to compare and decide if the option is valid.
 If it isn't valid I would like for the button to be disabled.

(ie: if medium or large option is selected then green is disabled or grayed out because it is not a valid option combination)

Sample Image of buttons

```<code>myArraySize = ['small', 'medium', 'large'];
myArrayColor = ["blue", "red", "green"];
myArrayValidOptions = ["small-blue", "medium-blue", "large-blue", "small-red", "medium-red", "large-red", "small-green"];
</code>```

Here is an example on codepen.  please somebody work their magic.  I really appreciate it.  I am really new to jquery/javascript and would like to get this working.

https://codepen.io/cliebich/pen/gRdKOq

答:
Does this do what you want?

myArraySize = ['small', 'medium', 'large'];
myArrayColor = ["blue", "red", "green"];
myArrayValidOptions = [
    "small-blue",
    "medium-blue",
    "large-blue",
    "small-red",
    "medium-red",
    "large-red",
    "small-green"
];

var result = $(".specOptions");
result.html("");

var result2 = $(".specOptions2");
result2.html("");

for (var i = 0; i < myArraySize.length; i++) {
    result.append(
        ' ' +
        myArraySize[i] +
        ""
    );
}
for (var i = 0; i < myArrayColor.length; i++) {
    result2.append(
        ' ' +
        myArrayColor[i] +
        ""
    );
}
$(document).ready(function() {
    $(".specOptions a, .specOptions2 a").click(function() {
        if ($(this).hasClass("disabled"))
            return;

        var theSelector = $(this).parent().attr("class");

        var value = $(this).data("value"); // value of checkbox
        $("." + theSelector + " a").removeClass("btn-primary"); // clear checkboxes in same group (mimic radio behavior)
        $("." + theSelector + ' a[data-value="' + value + '"]').addClass("btn-primary"); // check all checkboxes with same value

        if (this.name === "myArraySize") {
            $("a[name='myArrayColor']").each(function() {
                var color = $(this).data("value");
                if (myArrayValidOptions.indexOf(value + "-" + color) < 0)
                   $(this).addClass("disabled").removeClass("btn-primary");
                else
                   $(this).removeClass("disabled");
            });
        }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn{margin:3px;}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

```

Body:
I want to disable a button or change its class if it is not a valid option.

I am using this for product options on an eCommerce site.

I have 3 arrays.  The first 2 i use to create the button combinations.  I am thinking I can use the last array to compare and decide if the option is valid.
 If it isn't valid I would like for the button to be disabled.

(ie: if medium or large option is selected then green is disabled or grayed out because it is not a valid option combination)

Sample Image of buttons

myArraySize = ['small', 'medium', 'large'];
myArrayColor = ["blue", "red", "green"];
myArrayValidOptions = ["small-blue", "medium-blue", "large-blue", "small-red", "medium-red", "large-red", "small-green"];

Here is an example on codepen.  please somebody work their magic.  I really appreciate it.  I am really new to jquery/javascript and would like to get this working.

https://codepen.io/cliebich/pen/gRdKOq

Body:
Does this do what you want?

myArraySize = ['small', 'medium', 'large'];
myArrayColor = ["blue", "red", "green"];
myArrayValidOptions = [
    "small-blue",
    "medium-blue",
    "large-blue",
    "small-red",
    "medium-red",
    "large-red",
    "small-green"
];

var result = $(".specOptions");
result.html("");

var result2 = $(".specOptions2");
result2.html("");

for (var i = 0; i < myArraySize.length; i++) {
    result.append(
        '<a class="btn btn-default btn-variant" name="myArraySize" data-value="' +
        myArraySize[i] +
        '" > ' +
        myArraySize[i] +
        "</a>"
    );
}
for (var i = 0; i < myArrayColor.length; i++) {
    result2.append(
        '<a class="btn btn-default btn-variant" name="myArrayColor" data-value="' +
        myArrayColor[i] +
        '" > ' +
        myArrayColor[i] +
        "</a>"
    );
}
$(document).ready(function() {
    $(".specOptions a, .specOptions2 a").click(function() {
        if ($(this).hasClass("disabled"))
            return;

        var theSelector = $(this).parent().attr("class");

        var value = $(this).data("value"); // value of checkbox
        $("." + theSelector + " a").removeClass("btn-primary"); // clear checkboxes in same group (mimic radio behavior)
        $("." + theSelector + ' a[data-value="' + value + '"]').addClass("btn-primary"); // check all checkboxes with same value

        if (this.name === "myArraySize") {
            $("a[name='myArrayColor']").each(function() {
                var color = $(this).data("value");
                if (myArrayValidOptions.indexOf(value + "-" + color) < 0)
                   $(this).addClass("disabled").removeClass("btn-primary");
                else
                   $(this).removeClass("disabled");
            });
        }
    });
});

.btn{margin:3px;}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="row"></div>
  <div class="col-sm-6"></div>
  <div class="col-sm-6">
    <div class="prodOptions">
    <div class="specOptions">
    </div>
    <div class="specOptions2"></div>
      </div>
  </div>
</div>


问:
Max, Min, Avg function for an array in C++
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.</p>

```<code>#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}
</code>```

答:
Few problems:

deal with the empty data array case first.

set min and max to the first element of the array (not to zero). Think about what if the numbers are all negative. Will max contain the right answer?

You want to find the maximum and minimum elements so you have to use the data contained in data

```<code>if ( data[i] > max){
    max=data[i];
}
</code>```

Same goes for the min case.

normalizeMinMaxAvg does not return so you cannot use it in a cout expression. You can print the parameters directly.

Here is a working version of your code.

```<code>void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    if(size<=0)
        return;
    min= max = data[0];

    int count = 0;
    double sum = 0;
    int i;
    avg = 0;

    for (i=1; i < size; i++)
    {
        count++;
        sum += data[i];

        if ( data[i] > max)
        {
            max=data[i];
        }

        else if (data[i] < min)
        {
            min=data[i];
        }
    }
    avg = sum/(double)count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};
    double min,max,avg;
    normalizeMinMaxAvg (data, 4, min, max, avg);
    cout<<min<<"  "<<max<<" "<<avg<<endl;
    return 0;
}
</code>```

Body:
I am being tasked with writing a function that takes as parameters an array of doubles, the size of the array, and then 3 pass-by-reference parameters called min, max, and avg.  My function must:  process the array data to find the minimum value (min), maximum value (max), and calculate the average (avg), each of which gets assigned to the corresponding reference parameter so that the calling function will be able to see those values. I am fairly new to coding and am very confused in what my error is the main function included below, any help would be greatly appreciated.

#include <iostream>
using namespace std;

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    max = 0;
    min = 0;
    //int amount = size;
    int count = 0;
    int sum = 0;
    int i;
    avg = 0;

    for (i=0; i < size; i++)
    {
        count++;
        sum += i;

        if ( i > max)
        {
            i=max;
        }

        else if (i < min)
        {
            i=min;
        }
    }
    avg = sum/count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};

    cout << normalizeMinMaxAvg (data, 4, min, max, avg);
    return 0;
}

Body:
Few problems:

deal with the empty data array case first.

set min and max to the first element of the array (not to zero). Think about what if the numbers are all negative. Will max contain the right answer?

You want to find the maximum and minimum elements so you have to use the data contained in data

if ( data[i] > max){
    max=data[i];
}

Same goes for the min case.

normalizeMinMaxAvg does not return so you cannot use it in a cout expression. You can print the parameters directly.

Here is a working version of your code.

void normalizeMinMaxAvg(double data[], int size,double& min, double&
    max, double& avg)
{
    if(size<=0)
        return;
    min= max = data[0];

    int count = 0;
    double sum = 0;
    int i;
    avg = 0;

    for (i=1; i < size; i++)
    {
        count++;
        sum += data[i];

        if ( data[i] > max)
        {
            max=data[i];
        }

        else if (data[i] < min)
        {
            min=data[i];
        }
    }
    avg = sum/(double)count;
}

int main ()
{
    double data[]={10.0,0.0,20.0,30.0};
    double min,max,avg;
    normalizeMinMaxAvg (data, 4, min, max, avg);
    cout<<min<<"  "<<max<<" "<<avg<<endl;
    return 0;
}


问:
Log4j not writing logs to file on one Websphere server and writing to file on other
I have maven application with log4j.properties in it with setting to write the logs to a specified file instead of console. When I run the EAR on one of the websphere servers it is creating the file as expected and writing logs to it. But, when I am running the same EAR on other webspehere server it is writing to console instead of writing the logs to the specified file. I have checked the permissions and everything seems to be fine. Please help me in identifying what the issue is. Thanks in advance.  </p>

```<code> # CONSOLE APPENDER (stdout)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d] [%t] %-5p %20c - %m%n

# ROLLING FILE APPENDER (on the file system) for memberpolicyattributesservice code
log4j.appender.xxxxService=org.apache.log4j.RollingFileAppender
log4j.appender.xxxxService.Threshold=DEBUG
log4j.appender.xxxxService.File=/var/logs/xxxServer1/xxxServiceLog.log
log4j.appender.xxxxService.layout=org.apache.log4j.PatternLayout
log4j.appender.xxxxService.layout.ConversionPattern=%d{MM-dd@HH:mm:ss} %-5p (%13F:%L) %3x - %m%n
log4j.appender.xxxxService.MaxFileSize=10000KB
log4j.appender.xxxxService.MaxBackupIndex=30
log4j.appender.xxxxService.layout=org.apache.log4j.PatternLayout
log4j.appender.xxxxService.layout.ConversionPattern=[%d] [%t] %-5p %20c - %m%n

# ROLLING FILE APPENDER (on the file system) for hiberate, open source code log files
log4j.appender.open_source_code=org.apache.log4j.RollingFileAppender
log4j.appender.open_source_code.layout=org.apache.log4j.PatternLayout
log4j.appender.open_source_code.Threshold=DEBUG
#message format:YYYY-MM-DD HH:mm:ss,ms [ThreadId] <PRIORITY> classname.message
log4j.appender.open_source_code.layout.ConversionPattern=%d [%t]<%-5p> %c.%m \r\n
#file that will be logged to
log4j.appender.open_source_code.File=/var/logs/xxxServer1/open_source_code.log
log4j.appender.open_source_code.Append=true
log4j.appender.open_source_code.MaxFileSize=1024KB
log4j.appender.open_source_code.MaxBackupIndex=5

#turn on log4j verbose mode
log4j.debug = true

# Set root logger level to INFO and its  appender to DSInstrumentor,stdout.
log4j.rootLogger=DEBUG,stdout,xxxxService

# YOUR CATEGORIES (to customize logging per class/pkg/project/etc)
log4j.category.fatal=FATAL,xxxxService
log4j.category.error=ERROR,xxxxService

#This will also enable the logging for all the children (packages and classes) of this package

log4j.logger.com.xxxxx=ALL,xxxxService

# Print only messages of level INFO  in the open source code
log4j.logger.org=INFO,open_source_code
</code>```

答:
You have multiple loggers defined in your root logger (DEBUG, stdout, xxxxService) but the xxxxService loggers look like they're bound to the file system on one of the systems:

log4j.appender.open_source_code.File=/var/logs/xxxServer1/open_source_code.log

Make sure that path is valid for each server in your WAS cluster.

As a side note, you should probably avoid using debug and stdout on a remote server. This is fine for local development in your workstation, but not on a remote box. Instead, provide different log4j properties on your various deployment tiers. This lets you customize the log location or appender (say c:\temp or CONSOLE on your desktop, but /var/logs ... on all remote machines) as well as your log levels (DEBUG for desktop, maybe INFO for QA or Staging, and WARN or ERROR for Production).

Body:
I have maven application with log4j.properties in it with setting to write the logs to a specified file instead of console. When I run the EAR on one of the websphere servers it is creating the file as expected and writing logs to it. But, when I am running the same EAR on other webspehere server it is writing to console instead of writing the logs to the specified file. I have checked the permissions and everything seems to be fine. Please help me in identifying what the issue is. Thanks in advance.

 # CONSOLE APPENDER (stdout)
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d] [%t] %-5p %20c - %m%n

# ROLLING FILE APPENDER (on the file system) for memberpolicyattributesservice code
log4j.appender.xxxxService=org.apache.log4j.RollingFileAppender
log4j.appender.xxxxService.Threshold=DEBUG
log4j.appender.xxxxService.File=/var/logs/xxxServer1/xxxServiceLog.log
log4j.appender.xxxxService.layout=org.apache.log4j.PatternLayout
log4j.appender.xxxxService.layout.ConversionPattern=%d{MM-dd@HH:mm:ss} %-5p (%13F:%L) %3x - %m%n
log4j.appender.xxxxService.MaxFileSize=10000KB
log4j.appender.xxxxService.MaxBackupIndex=30
log4j.appender.xxxxService.layout=org.apache.log4j.PatternLayout
log4j.appender.xxxxService.layout.ConversionPattern=[%d] [%t] %-5p %20c - %m%n

# ROLLING FILE APPENDER (on the file system) for hiberate, open source code log files
log4j.appender.open_source_code=org.apache.log4j.RollingFileAppender
log4j.appender.open_source_code.layout=org.apache.log4j.PatternLayout
log4j.appender.open_source_code.Threshold=DEBUG
#message format:YYYY-MM-DD HH:mm:ss,ms [ThreadId] <PRIORITY> classname.message
log4j.appender.open_source_code.layout.ConversionPattern=%d [%t]<%-5p> %c.%m \r\n
#file that will be logged to
log4j.appender.open_source_code.File=/var/logs/xxxServer1/open_source_code.log
log4j.appender.open_source_code.Append=true
log4j.appender.open_source_code.MaxFileSize=1024KB
log4j.appender.open_source_code.MaxBackupIndex=5

#turn on log4j verbose mode
log4j.debug = true

# Set root logger level to INFO and its  appender to DSInstrumentor,stdout.
log4j.rootLogger=DEBUG,stdout,xxxxService

# YOUR CATEGORIES (to customize logging per class/pkg/project/etc)
log4j.category.fatal=FATAL,xxxxService
log4j.category.error=ERROR,xxxxService

#This will also enable the logging for all the children (packages and classes) of this package

log4j.logger.com.xxxxx=ALL,xxxxService

# Print only messages of level INFO  in the open source code
log4j.logger.org=INFO,open_source_code


问:
Ways to cast objects to a generic type
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

```<code>private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}
</code>```

and

```<code>private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}
</code>```

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?

答:
As far as operator as returns null in failure case, variable should be a class or nullable struct:

Meanwhile cast requires nothing like that and you can cast struct on struct.

Title: Ways to cast objects to a generic type

Body:
In relation to Casting generic type "as T" whilst enforcing the type of T

And with the following example

private static T deserialize<T>(string streng) where T : class
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return ser.Deserialize(reader) as T;
}

and

private static T deserialize<T>(string streng)
{
    XmlSerializer ser = new XmlSerializer(typeof(T));
    StringReader reader = new StringReader(streng);
    return (T)ser.Deserialize(reader);
}

I'm used to doing the object as Type casting, so I was a little confused when I found that I couldn't just do that with T. Then I found the question above and in that a solution to the as T compiler error.

But why is where T : class necessary when using object as T and not when using (T)object?
What is the actual difference between the two ways of casting the object?


问:
PHP, MySQL stored procedure not storing data as expected
There does not seem to be a repeat of this question and I feel this should be a simple fix.
I have tested the stored procedure and when adding the parameters it works fine,
I have also tested a simple SQL statement which also works as expected.
However, when I try to pass my variables into the statement, I get a "Zero results using SQL:" I have also tried to do this as just a prepared statement or as just pure SQL with my variables, but again it never stores anything in the database.
The debug output shows what I am trying to pass, but nothing goes into the database

Here is the full code

```<code>require_once (getcwd() . "/lib/dataLib.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    if (isset($_POST['btnSubmit']))
    {
        $projectName = $_POST['projectName'];
        $projectDescription = $_POST['projectDescription'];
        $projectLink = $_POST['projectLink'];
        addItemToDatabase($projectName, $projectDescription, $projectLink);
    }
}

/********************************
* addItemToDatabase
*******************************/
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";

databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn -> connect_error)
{
    die("Connection Failed!: " . $conn ->connect_error);
}
/*$sql = 'insert into projectList (
 *projectName,
 *projectDescription,
 *projectPage,
 *projectSource)
 *Values ("Stuff", "Things", "Yeah", "Yeah")'; */
$sql = "call insertItemIntoWork($name, $description, $projectLinkAsLink, $projectLinkAsLink)";
$result = $conn->query($sql);
displayResult($result, $sql);
}
</code>```

some notes on the code,
I am using a lib to call external functions which I did not copy/paste here, as I do not think they are relevant to the question. I also did not include the HTML bits which is just the form which should be fairly straight forward, and should work since the debug displayResults() shows values.

Bottom line question is, is there something procedural that I am screwing up here. I do not have to call a function I suppose but is this a situation where the variables are set after the query is ran?

UPDATE
I added an error handler per Jay below:

```<code>$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
    if ($echoSuccess)
    {
        echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
    }
} else
{
    echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "<br />" . $conn->error;
    //displayResult($result, $sql)
}
</code>```

Saying there are errors in my SQL.
I think I can work those out and on account of that I do not think this question needs further answering, but rather illustrates the need of error handlers

答:
So,
Thank you Jay Blanchard for pointing me in the right direction, turns out the spaces in my input were causing issues entering items into the database.
To fix this I had to add quotes around my parameters, though this seems like an odd requirement (perhaps I am missing something)
But it works now as expected.
Here are the alterations:

```<code>error_reporting(E_ALL); ini_set('display_errors', 1);
include "lib/style.php";
require_once (getcwd() . "/lib/coleSterlingLib.php");
//require_once (getcwd() . "/lib/jsFormInteraction.js");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    if (isset($_POST['btnSubmit']))
    {
        $projectName = $_POST['projectName'];
        $projectName = "'" . $projectName . "'";
        $projectDescription = $_POST['projectDescription'];
        $projectDescription = "'" . $projectDescription . "'";
        $projectLink = $_POST['projectLink'];
        $projectLink = "'" . $projectLink . "'";
        addItemToDatabase($projectName, $projectDescription, $projectLink);
    }
}
</code>```

Note the $projectName = "'" . $projectName . "'";

Everything else stayed roughly the same

```<code>function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";

databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn->connect_error)
{
    die("Connection Failed!: " . $conn->connect_error);
}
//$sql = 'insert into projectList (projectName, projectDescription, projectPage, projectSource) Values ("Stuff", "Things", "Yeah", "Yeah")';
$sql = "call insertItemIntoWork($name, $description, $link, $link)";
//$result = $conn->query($sql);
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
    if ($echoSuccess)
    {
        echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
    }
} else
{
    echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "
<br />" . $conn->error;
    //displayResult($result, $sql)
}
}
</code>```

Body:
There does not seem to be a repeat of this question and I feel this should be a simple fix.
I have tested the stored procedure and when adding the parameters it works fine,
I have also tested a simple SQL statement which also works as expected.
However, when I try to pass my variables into the statement, I get a "Zero results using SQL:" I have also tried to do this as just a prepared statement or as just pure SQL with my variables, but again it never stores anything in the database.
The debug output shows what I am trying to pass, but nothing goes into the database

Here is the full code

require_once (getcwd() . "/lib/dataLib.php");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    if (isset($_POST['btnSubmit']))
    {
        $projectName = $_POST['projectName'];
        $projectDescription = $_POST['projectDescription'];
        $projectLink = $_POST['projectLink'];
        addItemToDatabase($projectName, $projectDescription, $projectLink);
    }
}

/********************************
* addItemToDatabase
*******************************/
function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "" . $link . "";

databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn -> connect_error)
{
    die("Connection Failed!: " . $conn ->connect_error);
}
/*$sql = 'insert into projectList (
 *projectName,
 *projectDescription,
 *projectPage,
 *projectSource)
 *Values ("Stuff", "Things", "Yeah", "Yeah")'; */
$sql = "call insertItemIntoWork($name, $description, $projectLinkAsLink, $projectLinkAsLink)";
$result = $conn->query($sql);
displayResult($result, $sql);
}

some notes on the code,
I am using a lib to call external functions which I did not copy/paste here, as I do not think they are relevant to the question. I also did not include the HTML bits which is just the form which should be fairly straight forward, and should work since the debug displayResults() shows values.

Bottom line question is, is there something procedural that I am screwing up here. I do not have to call a function I suppose but is this a situation where the variables are set after the query is ran?

UPDATE
I added an error handler per Jay below:

$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
    if ($echoSuccess)
    {
        echo "" . $msg . " successful.
";
    }
} else
{
    echo "Error when: " . $msg . " using SQL: " . $sql . "
" . $conn->error;
    //displayResult($result, $sql)
}

Saying there are errors in my SQL.
I think I can work those out and on account of that I do not think this question needs further answering, but rather illustrates the need of error handlers

Body:
So,
Thank you Jay Blanchard for pointing me in the right direction, turns out the spaces in my input were causing issues entering items into the database.
To fix this I had to add quotes around my parameters, though this seems like an odd requirement (perhaps I am missing something)
But it works now as expected.
Here are the alterations:

error_reporting(E_ALL); ini_set('display_errors', 1);
include "lib/style.php";
require_once (getcwd() . "/lib/coleSterlingLib.php");
//require_once (getcwd() . "/lib/jsFormInteraction.js");
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    if (isset($_POST['btnSubmit']))
    {
        $projectName = $_POST['projectName'];
        $projectName = "'" . $projectName . "'";
        $projectDescription = $_POST['projectDescription'];
        $projectDescription = "'" . $projectDescription . "'";
        $projectLink = $_POST['projectLink'];
        $projectLink = "'" . $projectLink . "'";
        addItemToDatabase($projectName, $projectDescription, $projectLink);
    }
}

Note the $projectName = "'" . $projectName . "'";

Everything else stayed roughly the same

function addItemToDatabase($name, $description, $link)
{
$projectLinkSanSpace = str_replace(' ', '', $link);
$projectLinkAsLink = "<a href='project/" . $projectLinkSanSpace . "'>" . $link . "</a>";

databaseConnection('programWork');
$conn = new mysqli(DBF_SERVER, DBF_USER, DBF_PASSWORD, DBF_NAME);
if ($conn->connect_error)
{
    die("Connection Failed!: " . $conn->connect_error);
}
//$sql = 'insert into projectList (projectName, projectDescription, projectPage, projectSource) Values ("Stuff", "Things", "Yeah", "Yeah")';
$sql = "call insertItemIntoWork($name, $description, $link, $link)";
//$result = $conn->query($sql);
$echoSuccess = true;
$msg = "The query completed successfully";
if ($conn->query($sql) === TRUE)
{
    if ($echoSuccess)
    {
        echo "<span class='errMsg'>" . $msg . " successful.</span><br />";
    }
} else
{
    echo "<strong>Error when: " . $msg . "</strong> using SQL: " . $sql . "
<br />" . $conn->error;
    //displayResult($result, $sql)
}
}


问:
How to return a reference to a slice of an array in Chapel?
I'm trying to return a reference to a slice of an array , but am getting the following compile-time error (where the offending line is in slice

test.chpl:9: error: illegal expression to return by ref

Returning the full array works fine, as does taking a reference to a slice in the main program.

Is there a correct way to return a ref to a slice? Thanks in advance!

```<code>record R {
  var A : [0.. #10] int;

  proc full() ref {
    return A;
  }

  proc slice() ref {
    return A[0.. #5];
  }
}

var r : R;
ref x1 = r.full();
ref x2 = r.slice();
ref x3 = x1[0.. #5];
</code>```

Just for completeness :

chpl Version 1.16.0 pre-release (2659cc6)

答:
As of the current version of the compiler you're using, this is an open question which is being debated on GitHub issue #5341.  I agree with you that ref seems like an appropriate way to indicate the intent to return a slice of an array, but we haven't reached closure on the discussion yet.

In the meantime, you should be able to use the following pragma-based workaround (please note that Chapel pragmas are not generally intended for end-user use and that this pragma is unlikely to be supported in the long-term, though I wouldn't expect us to retire it without having come up with a replacement approach like the proposed ref):

```<code>record R {
  var A : [0.. #10] int;

  proc full() ref {
    return A;
  }

  pragma "no copy return"
  proc slice() {
    return A[0.. #5];
  }
}

var r : R;
ref x1 = r.full();
ref x2 = r.slice();
ref x3 = x1[0.. #5];
x1[0] = 1;
x2[1] = 2;
x3[2] = 3;
writeln(r);
</code>```

Body:
I'm trying to return a reference to a slice of an array , but am getting the following compile-time error (where the offending line is in slice

test.chpl:9: error: illegal expression to return by ref

Returning the full array works fine, as does taking a reference to a slice in the main program.

Is there a correct way to return a ref to a slice? Thanks in advance!

record R {
  var A : [0.. #10] int;

  proc full() ref {
    return A;
  }

  proc slice() ref {
    return A[0.. #5];
  }
}

var r : R;
ref x1 = r.full();
ref x2 = r.slice();
ref x3 = x1[0.. #5];

Just for completeness :

chpl Version 1.16.0 pre-release (2659cc6)

Body:
As of the current version of the compiler you're using, this is an open question which is being debated on GitHub issue #5341.  I agree with you that ref seems like an appropriate way to indicate the intent to return a slice of an array, but we haven't reached closure on the discussion yet.

In the meantime, you should be able to use the following pragma-based workaround (please note that Chapel pragmas are not generally intended for end-user use and that this pragma is unlikely to be supported in the long-term, though I wouldn't expect us to retire it without having come up with a replacement approach like the proposed ref):

record R {
  var A : [0.. #10] int;

  proc full() ref {
    return A;
  }

  pragma "no copy return"
  proc slice() {
    return A[0.. #5];
  }
}

var r : R;
ref x1 = r.full();
ref x2 = r.slice();
ref x3 = x1[0.. #5];
x1[0] = 1;
x2[1] = 2;
x3[2] = 3;
writeln(r);


问:
Java Regex capture nested matches
I am having trouble with regex here.

Say i have this input:

```<code>608094.21.1.2014.TELE.&BIG00Z.1.1.GBP
</code>```

My regex looks like this

```<code>(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)
</code>```

I want to extract the date 21.1.2014 out of the string, but all i get is

```<code>8094.21.1
</code>```

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

答:
You could use a regex like this:

```<code>\d{1,2}\.\d{1,2}\.\d{4}
</code>```

Working demo

Or shorten it and use:

```<code>(\d{1,2}\.){2}\d{4}
</code>```

Title: Java Regex capture nested matches

Body:
I am having trouble with regex here.

Say i have this input:

608094.21.1.2014.TELE.&BIG00Z.1.1.GBP

My regex looks like this

(\d\d\d\d\.\d?\d\.\d?\d)|(\d?\d\.\d?\d\.\d?\d?\d\d)

I want to extract the date 21.1.2014 out of the string, but all i get is

8094.21.1

I think my problem here is, that 21.1.2014 starts within the (wrong) match before. Is there a simple way to make the matcher look for the next match not after the end of the match before but one character after the beginning of the match before?

Body:
You could use a regex like this:

\d{1,2}\.\d{1,2}\.\d{4}

Working demo

Or shorten it and use:

(\d{1,2}\.){2}\d{4}


问:
MomentJS: how to parse dates in MM/DD/YYYY & DD/MM/YYYY
How can i use moment.js in both: Australia & USA time formats?

For example:

07/08/2017 - is good for both time formats, but!

30/08/2017 - is invalid for moment.js, but i can have such dateTime

You can check it here:

http://jsfiddle.net/rLjQx/2135/

答:
Specify the format via a second parameter to the moment call

```<code>var now2 = moment('30/08/2017', 'DD/MM/YYYY').format('MMM DD h:mm A');
</code>```

Otherwise there is no way for moment to know

Related docs here: https://momentjs.com/docs/#/parsing/string-format/

Corrected fiddle: http://jsfiddle.net/wu6wwsvp/

Body:
Specify the format via a second parameter to the moment call

var now2 = moment('30/08/2017', 'DD/MM/YYYY').format('MMM DD h:mm A');

Otherwise there is no way for moment to know

Related docs here: https://momentjs.com/docs/#/parsing/string-format/

Corrected fiddle: http://jsfiddle.net/wu6wwsvp/


问:
PHP question about global variables and form requests
This is probably a stupid question but will ask anyway sine I have no idea.

I have written basic php code which serve forms. Say I have a login page and I serve it using the login.php page and it will be called in the login.html page like this -

```<code><form action="login.php" method="post">
</code>```

By this it is also implied that every POST needs its own php file, doesn't it? This kind of feels weird. Is there a way to have a single file, say code.php, and just have each of the forms as functions instead?

EDIT: Specifically, say I have 5 forms that are used one after the other in my application. Say after login the user does A, B, C and D tasks each of which are sent to the server as a POST request. So instead of having A.php, B.php, C.php and D.php I would like to have a single code.php and have A(), B(), C() and D() as functions. Is there a way to do this?

Also on the same note, how do I deal with say a global array (e.g. an array of currently logged in users) across multiple forms? I want to do this without writing to a DB. I know its probably better to write to a DB and query but is it even possible to do it with a global array? The reason I was thinking about having all the form functions in one file is to use a global array.

Thanks,
- Pav

答:
Sure, no problem, just POST all forms to the same .php file and have it deal with all incoming POST data. There's nothing keeping you from doing it.

Usually your forms send different data though and each form needs a bit of custom handling. If you put all this logic into the same handler file, it'll become a reaaaally long, messy piece of code. It's better to separate code into different files if it does different things.

You can and should abstract the common parts like database connection handling into functions or objects and include them in each POST handler though.

Body:
This is probably a stupid question but will ask anyway sine I have no idea.

I have written basic php code which serve forms. Say I have a login page and I serve it using the login.php page and it will be called in the login.html page like this -

<form action="login.php" method="post">

By this it is also implied that every POST needs its own php file, doesn't it? This kind of feels weird. Is there a way to have a single file, say code.php, and just have each of the forms as functions instead?

EDIT: Specifically, say I have 5 forms that are used one after the other in my application. Say after login the user does A, B, C and D tasks each of which are sent to the server as a POST request. So instead of having A.php, B.php, C.php and D.php I would like to have a single code.php and have A(), B(), C() and D() as functions. Is there a way to do this?

Also on the same note, how do I deal with say a global array (e.g. an array of currently logged in users) across multiple forms? I want to do this without writing to a DB. I know its probably better to write to a DB and query but is it even possible to do it with a global array? The reason I was thinking about having all the form functions in one file is to use a global array.

Thanks,
- Pav


问:
How to create an instance of class and implement it in a subclass?
How would I create an instance of a class to use as an attribute in another class? I believe this is what I need to do:

```<code>ClassA a1 = new ClassA(); // ClassA is the super class
</code>```

This is where I get stuck, if my above code is even correct. How do I actually use this in a subclass of ClassA, say ClassB? So if ClassA has 'name' and 'age' and ClassB has 'tenant' what do I need to do in order to give tenant a name and age?

答:
You can use the idea of classes and subclasses, and the use of protected fields:</p>

```<code>public class ClassA {

    protected String name;
    protected int age;

    public ClassA(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class ClassB extends ClassA {

    private String tenant;

    public ClassB(String name, int age, String tenant) {
        super(name, age);
        this.tenant = tenant;
    }

    public static void main(String[] args) {
        ClassB b = new ClassB("Carol", 23, "some tenant");
        String tenant = b.tenant;
        int age = b.age;
        String name = b.name;

    }
}
</code>```

Body:
How would I create an instance of a class to use as an attribute in another class? I believe this is what I need to do:

ClassA a1 = new ClassA(); // ClassA is the super class

This is where I get stuck, if my above code is even correct. How do I actually use this in a subclass of ClassA, say ClassB? So if ClassA has 'name' and 'age' and ClassB has 'tenant' what do I need to do in order to give tenant a name and age?

Body:
You can use the idea of classes and subclasses, and the use of protected fields:

public class ClassA {

    protected String name;
    protected int age;

    public ClassA(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class ClassB extends ClassA {

    private String tenant;

    public ClassB(String name, int age, String tenant) {
        super(name, age);
        this.tenant = tenant;
    }

    public static void main(String[] args) {
        ClassB b = new ClassB("Carol", 23, "some tenant");
        String tenant = b.tenant;
        int age = b.age;
        String name = b.name;

    }
}


问:
how to convert certain columns as rows in r
I have a data frame like this

```<code>Htno         Subname             marks      credits
15mq1a0501     abc                43          3
15mq1a0501     xyz                55          6
15mq1a0502     abc                56          3
15mq1a0502     xyz                60          6
15mq1a0503     abc                10          0
15mq1a0503     xyz                56          6
</code>```

now i need a data frame to be converted like this

```<code>Htno               abc         xyz       Totalmarks        Totalcredits
15mq1a0501          43         55         98                  9
15mq1a0502          56         60        116                  9
15mq1a0503          10         56         66                  6
</code>```

I used dplyr package but I am not able to do so.

答:
Just an alternative that only uses dplyr functions. Note that the solution can be tedious when Subname has many factors. See if others can have a more general solution.

```<code>library(magrittr)
library(dplyr)

df %>% group_by(Htno) %>%
  summarize(abc = marks[Subname == "abc"],
            xyz = marks[Subname == "xyz"],
            Totalmarks = sum(marks),
            Totalcredits = sum(credits))
</code>```

Edit: The below generalisation works, but it is more complicated and needs tidyr::spread.

```<code>library(magrittr)
library(dplyr)

library(tidyr)
df_1 <- df %>% group_by(Htno) %>%
  summarize(Totalmarks = sum(marks),
            Totalcredits = sum(credits))

df_2 <- df %>% select(-credits) %>% spread(Subname, marks) %>%
  group_by(Htno) %>% summarize_each(funs(mean))

left_join(df_2, df_1, by = "Htno", all = TRUE)
</code>```

Body:
I have a data frame like this

Htno         Subname             marks      credits
15mq1a0501     abc                43          3
15mq1a0501     xyz                55          6
15mq1a0502     abc                56          3
15mq1a0502     xyz                60          6
15mq1a0503     abc                10          0
15mq1a0503     xyz                56          6

now i need a data frame to be converted like this

Htno               abc         xyz       Totalmarks        Totalcredits
15mq1a0501          43         55         98                  9
15mq1a0502          56         60        116                  9
15mq1a0503          10         56         66                  6

I used dplyr package but I am not able to do so.

Body:
Just an alternative that only uses dplyr functions. Note that the solution can be tedious when Subname has many factors. See if others can have a more general solution.

library(magrittr)
library(dplyr)

df %>% group_by(Htno) %>%
  summarize(abc = marks[Subname == "abc"],
            xyz = marks[Subname == "xyz"],
            Totalmarks = sum(marks),
            Totalcredits = sum(credits))

Edit: The below generalisation works, but it is more complicated and needs tidyr::spread.

library(magrittr)
library(dplyr)

library(tidyr)
df_1 <- df %>% group_by(Htno) %>%
  summarize(Totalmarks = sum(marks),
            Totalcredits = sum(credits))

df_2 <- df %>% select(-credits) %>% spread(Subname, marks) %>%
  group_by(Htno) %>% summarize_each(funs(mean))

left_join(df_2, df_1, by = "Htno", all = TRUE)


问:
MariaDB statement not compatible with MySQL
Backend is not my strongest background and I'm having troubles executing my php scripts while migrating from MySQL to MariaDB (a must for our server provider).
Here is the function I have in my php script that is working with MySQL 5.6 and it's not working with MariaDB (10.1.22-MariaDB-cll-lve - MariaDB Server):

```<code>public function getPostByName($postName) {
        $returnValue = array();
        $sql = "SELECT * FROM posts WHERE post_description LIKE ?";
        $statement = $this->conn->prepare($sql);
        if (!$statement)
            throw new Exception($statement->error);

        $postName = "%".$postName."%";
        $statement->bind_param("s", $postName);
        $statement->execute();

        $result = $statement->get_result();
        while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            array_push($returnValue, $row);
        }
        return $returnValue;
}
</code>```

I have already try most of the options out there but none of them worked (one example: php mysqli prepared statement LIKE). Any suggestion?

答:
Solved:</p>

```<code>public function getPostByName($postName){

    $returnValue = array();
    $sql = "SELECT * FROM posts WHERE post_description LIKE '%".$postName."%'";
    $result = $this->conn->query($sql);

    if($result != nill && (mysqli_num_rows($result) >= 1)){
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            array_push($returnValue, $row);
        }
    }
    return $returnValue;
}
</code>```

Body:
Backend is not my strongest background and I'm having troubles executing my php scripts while migrating from MySQL to MariaDB (a must for our server provider).
Here is the function I have in my php script that is working with MySQL 5.6 and it's not working with MariaDB (10.1.22-MariaDB-cll-lve - MariaDB Server):

public function getPostByName($postName) {
        $returnValue = array();
        $sql = "SELECT * FROM posts WHERE post_description LIKE ?";
        $statement = $this->conn->prepare($sql);
        if (!$statement)
            throw new Exception($statement->error);

        $postName = "%".$postName."%";
        $statement->bind_param("s", $postName);
        $statement->execute();

        $result = $statement->get_result();
        while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            array_push($returnValue, $row);
        }
        return $returnValue;
}

I have already try most of the options out there but none of them worked (one example: php mysqli prepared statement LIKE). Any suggestion?

Body:
Solved:

public function getPostByName($postName){

    $returnValue = array();
    $sql = "SELECT * FROM posts WHERE post_description LIKE '%".$postName."%'";
    $result = $this->conn->query($sql);

    if($result != nill && (mysqli_num_rows($result) >= 1)){
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            array_push($returnValue, $row);
        }
    }
    return $returnValue;
}


问:
Should I compress the data being exposed via wcf service?
I'm creating a WCF service which exposes an object graph which is expected to grow in size while the service is up and running.  In playing with some test data (85k), smaller that would be expected when live, I hit the default 65k message size limit.  A quick look on the net showed that it was simple enough to extend this in the config.

As I'm creating the service and the client which consumes it, I wondered if there was added value in compressing the data before I sent it.  Having run a brief test, the test data shrunk to around 7k, so this looks like it will aid in the time for the message to be sent over the wire and increase the amount of data I could send.

The service pre-prepares the data before the first call is made and so there is no initial overhead on every call due to the compression.

Is it a good idea to do this for the sake of scalability, and trying to optimise performance, or is this adding complexity where it is not needed?

答:
By reading your post, seems like you were able to implement this compression quite easily.

If you control both the sides, adding a layer of Compression/Decompression does not really increase complexity for general scenarios when you gain a lot of bandwidth benefit out of it.

What you could do to minimize the complexity by implementing some patterns like Interceptor or Decorator.


问:
Oracle SQL hierarchical query from bottom to top element
In my table I store the successor of each entry.

```
+----+-----------+--+
| ID | SUCCESSOR |  |
+----+-----------+--+
|  1 |         2 |  |
|  2 |         3 |  |
|  3 |           |  |
+----+-----------+--+
```

I need to get from ID 3 to ID 1.

I have tried to archieve this with the following query, but this does not work. :-(

```<code>SELECT NVL (id, 3)
FROM my_table
WHERE LEVEL = 1
CONNECT BY id = PRIOR successor
START WITH id = 3;
</code>```

Can somebody please give me some advice how to get this working?

答:
The following version should also provide the correct answer:</p>

```<code>with my_table as
(select 1 id, 2 successor from dual union
select 2 id, 3 successor from dual union
select 3 id, null successor from dual )
SELECT id FROM my_table
WHERE level = 3
CONNECT BY successor = PRIOR id
START WITH successor is null
;
</code>```

Body:
In my table I store the successor of each entry.

+----+-----------+--+
| ID | SUCCESSOR |  |
+----+-----------+--+
|  1 |         2 |  |
|  2 |         3 |  |
|  3 |           |  |
+----+-----------+--+

I need to get from ID 3 to ID 1.

I have tried to archieve this with the following query, but this does not work. :-(

SELECT NVL (id, 3)
FROM my_table
WHERE LEVEL = 1
CONNECT BY id = PRIOR successor
START WITH id = 3;

Can somebody please give me some advice how to get this working?

Body:
The following version should also provide the correct answer:

with my_table as
(select 1 id, 2 successor from dual union
select 2 id, 3 successor from dual union
select 3 id, null successor from dual )
SELECT id FROM my_table
WHERE level = 3
CONNECT BY successor = PRIOR id
START WITH successor is null
;


问:
Getting empty folder when using mongodump to back up my MongoDB
Basically, I have a problem with using mongodump to back up my MongoDB.

This is the general syntax I use in SSH:

```<code>mongodump -d myDatabaseName -o ~/backups/my_backup
</code>```

This is the resulting message:

```<code>Fri Apr 22 20:39:57.304 DATABASE: myDatabaseName   to     /root/backups/my_backup/myDatabaseName
</code>```

This simply generates a blank folder with no files in it whatsoever. The actual database is fairly large, so not sure what's going on.

I would also like to add that my mongodump client and my MongoDB version are both the same (version 2.4.9).

Not sure how to go about fixing this. Any help is appreciated.

答:
This is a similar question as Mongodump getting blank folders

There is no accepted answer as of writing my answer. Here is what I did to resolve my issue and I believe it will help you as well.

The default mongodb-client deb package with Ubuntu is the issue. I removed those and installed the mongodb-org-tools package from mongodb.com https://docs.mongodb.com/master/tutorial/install-mongodb-on-ubuntu/?_ga=2.36209632.1945690590.1499275806-1594815486.1499275806

They have other install instructions for your specific OS if you are not on Ubuntu https://www.mongodb.com/download-center?jmp=nav#community

Body:
Basically, I have a problem with using mongodump to back up my MongoDB.

This is the general syntax I use in SSH:

mongodump -d myDatabaseName -o ~/backups/my_backup

This is the resulting message:

Fri Apr 22 20:39:57.304 DATABASE: myDatabaseName   to     /root/backups/my_backup/myDatabaseName

This simply generates a blank folder with no files in it whatsoever. The actual database is fairly large, so not sure what's going on.

I would also like to add that my mongodump client and my MongoDB version are both the same (version 2.4.9).

Not sure how to go about fixing this. Any help is appreciated.


问:
How to treat a var as both int and string.
```<code>def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."
</code>```

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

答:
Keep your variables as numbers and let print do the formatting:

```<code>def die():
    first = randint(1, 6)
    second = randint(1, 6)
    total = first + second
    print "You have rolled a", first, "and a", second, ", for a total score of", total, "."
</code>```

Or you could do some formatting using str.format to have more control over the default inter-parameter spacing in the above:

```<code>print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)
</code>```

Body:
def die():
    first = str(randint(1, 6))
    second = str(randint(1, 6))
    total = first + second
    print "You have rolled a " + first + " and a " + second + ", for a total score of " + total + "."

Standard die throwing game, but I'm struggling to print the values for individual die as well as the total. Treating as a string for individual, but then sum leads to concatenation rather than actual sum.

Thanks

Body:
Keep your variables as numbers and let print do the formatting:

def die():
    first = randint(1, 6)
    second = randint(1, 6)
    total = first + second
    print "You have rolled a", first, "and a", second, ", for a total score of", total, "."

Or you could do some formatting using str.format to have more control over the default inter-parameter spacing in the above:

print "You have rolled a {} and a {}, for a \
total score of {}.".format(first, second, total)


问:
PHP: Turning multidimensional arrays to single dimension arrays
Basically my app is interacting with a web service that sends back a weird multidimensional array such as:

```<code>Array
(
    [0] => Array
        (
            [Price] => 1
        )
    [1] => Array
        (
            [Size] => 7
        )
    [2] => Array
        (
            [Type] => 2
        )
)
</code>```

That's not a problem, but the problem is that the service keeps changing the index of those items, so in the next array the Price could be at 1 instead of 0.

How do I effeciently transform arrays like this into a single dimension array so I can access the variables through $var['Size'] instead of $var[1]['Size']?

Appreciate your help

答:
If you use php >= 5.6, you may use array unpacking (it's much faster):

```<code>$result = array_merge(...$array);
</code>```

See wiki.php.net on unpacking

Body:
Basically my app is interacting with a web service that sends back a weird multidimensional array such as:

Array
(
    [0] => Array
        (
            [Price] => 1
        )
    [1] => Array
        (
            [Size] => 7
        )
    [2] => Array
        (
            [Type] => 2
        )
)

That's not a problem, but the problem is that the service keeps changing the index of those items, so in the next array the Price could be at 1 instead of 0.

How do I effeciently transform arrays like this into a single dimension array so I can access the variables through $var['Size'] instead of $var[1]['Size']?

Appreciate your help

Body:
If you use php >= 5.6, you may use array unpacking (it's much faster):

$result = array_merge(...$array);

See wiki.php.net on unpacking


问:
mysql select statement mc_decrypt
I need to decrypt value so mysql can match and show record</p>

```<code>$ck_data = ("SELECT user, alink AS url_name FROM my_link WHERE user = '$user_name' and '".mc_decrypt('"url_name"', ENCRYPTION_KEY)."' = '$url_name_check' ");
</code>```

答:
When you use AS in sql you need to check conndition using having try this:

SELECT user, alink AS url_name FROM my_link WHERE user = '$user_name' HAVING '".mc_decrypt('"url_name"', ENCRYPTION_KEY)."' = '$url_name_check'

Title: mysql select statement mc_decrypt

Body:
I need to decrypt value so mysql can match and show record

$ck_data = ("SELECT user, alink AS url_name FROM my_link WHERE user = '$user_name' and '".mc_decrypt('"url_name"', ENCRYPTION_KEY)."' = '$url_name_check' ");


问:
List<T> add method in C#
As I know. List Add method works as below.

```<code>List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
</code>```

If I designed the data structure as this

```<code>List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}
</code>```

Does the List Add method works or not if I add different types members in the same function.

答:
You should use the List.AddRange method for adding multiple items to a list.

```<code>cities.AddRange(AListObject);
</code>```

However, you'll have problems trying to add object to a list of string.

Title: List<T> add method in C#

Body:
As I know. List Add method works as below.

List<string> cities = new List<string>();
cities.Add("New York");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");

If I designed the data structure as this

List<object> lstObj = new List<object>();
if (true)  // string members
{
    cities.Add("New York");
    cities.Add("Istanbul");
}
else // List obj members here
{
    List<object> AListObject= new List<object>();
    cities.Add(AListObject);  // how to handle this?
}

Does the List Add method works or not if I add different types members in the same function.

Body:
You should use the List.AddRange method for adding multiple items to a list.

cities.AddRange(AListObject);

However, you'll have problems trying to add object to a list of string.


问:
Spring Batch MultiResourceItemReader Chunk Commit Per Resource
I currently have a Spring Batch job that does the following:

Reads a list of csv files using a MultiResourceItemReader which delegates to a FlatFileItemReader.

Splits each file into chunks and writes each chunk as a JMS message, with each message containing the list of lines in the chunk and the filename of the underlying resource in JSON format.

What I want is for each chunk to only contain lines from a single file resource so that the filename on the JMS message will link up to the corresponding file.

The problem is that when processing of one file resource is complete, the reader will just continue and process the next resource meaning that lines from multiple resource files are being inserted into the same chunk and the filename property will not necessarily match the underlying data in the chunk.

Is there any clean way to prevent the reader from including lines from separate file resources in the same chunk?

EDIT: I believe the solution will require using a custom chunk completion policy to somehow determine if the current item being read is from the same resource as the previous line, not sure how feasible this is though. Any thoughts?.

答: I changed my implementation to use MultiResourcePartitioner to create a partitioned step per file, everything working now.</p>


问:
What, exactly, is memcmp supposed to return?
I would like to know what the function memcmp must return.

I've been searching on the Internet, and usually, memcmp definitions state something like the following:

The memcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.

It is never explicitly said what, exactly, is returned: is it the difference between two byte values, or is it -1, 0 or 1? I am confused:

When testing the function memcmp in a little program, it returns -1, 0 or 1, even when the difference between the two bytes evaluated is higher than 1 or lower than -1.

When looking at functions named memcmp on the Internet, they almost all return the difference between 2 bytes, as an int, instead of returning either -1, 0 or 1.

Since I can't get a precise enough definition of the function memcmp, I ask this question here: what, exactly, is the function memcmp supposed to return? Is there an "official" source code somewhere? (I have seen a lot of source codes for memcmp but none gave me an answer: I then suppose that they are not the function that is written in the library string.h, at least not on my computer...)

答:
It does not specify what integer will return, it specifies that the result can be compared with 0.

Any values returned by an implementation is correct if it accomplish this test.


问:
Ways to make it easier to work with shared pointers in C++
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

```<code>class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };
</code>```

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?

答:
Don't just pick one smart pointer to use everywhere.  Not every screw is a Phillips head.

Also, you can use forward declarations for any smart pointer exactly the same as raw pointers:

```<code>struct X;

...
std::shared_ptr<X> ptr;  // legal

struct X {};
ptr = std::shared_ptr<X>(new X); // legal
</code>```

This is the second time I've heard this misconception on SO and it's simply 100% false.

Body:
I am busy designing a new C++ application.  In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers).

I worked out some tricks to make it easier to work with shared pointers, e.g.: using a typedef within the class, like this:

class X
   {
   public:
      ...
      typedef std::shared_ptr<X> Ptr;
   };

That way you can easily write X::Ptr, which is easier to write than "std::shared_ptr" everywhere.

I also noticed some disadvantages to shared pointers:

Everywhere I use a shared pointer I need to include <memory>

I can't use forward declaration anymore if I just want to use the pointer

Are there any other tricks to make shared pointers easier to work with?

Body:
Don't just pick one smart pointer to use everywhere.  Not every screw is a Phillips head.

Also, you can use forward declarations for any smart pointer exactly the same as raw pointers:

struct X;

...
std::shared_ptr<X> ptr;  // legal

struct X {};
ptr = std::shared_ptr<X>(new X); // legal

This is the second time I've heard this misconception on SO and it's simply 100% false.


问:
Cannot choose new data source from ReportViewer control
I'm following an ASP.NET tutorial about Reporting Services. I am at a point where I add a ReportViewer control to my aspx page. From there I have to select the report that I want to use and add a new Datasource. But adding the datasource is where I'm having trouble.

The tutorial says I have to choose: Choose Data Sources from the ReportViewer and then select: 'New data source`. But I don't seem to have that option.

This is from the tutorial:

And this is what I see:

So now I'm stuck with this. Anyone any idea how to solve this problem>

答:
Better late than never, I have had the same issue and managed to resolve by installing the reportviewer runtime: https://www.microsoft.com/en-gb/download/details.aspx?id=35747

Now I have the option to create a new datasource in Visual Studio, hope this helps someone


问:
Designing dialog box in R
How can we a design a dialog box in R?

In my mind I have something in which an alert message is displayed or where we can write a certain value and then clicking a button it performs some computation... is that possible within the R workspace?

答:
winDialog also works:

```<code>library(utils)
answer<-winDialog("yesno", "was the suggestion useful?")
if (answer=='YES') {print('good!')} else {print('sorry')}
</code>```

Just try to copy the full code and paste it into your R console: a dialog box will come out and a final output ('good!' or 'sorry') will appear depending on the answer you click.

Title: Designing dialog box in R

Body:
winDialog also works:

library(utils)
answer<-winDialog("yesno", "was the suggestion useful?")
if (answer=='YES') {print('good!')} else {print('sorry')}

Just try to copy the full code and paste it into your R console: a dialog box will come out and a final output ('good!' or 'sorry') will appear depending on the answer you click.


问:
How can we perform headless testing for Protractor Testing in Jenkins or other CI integration tool?
I found out that it is not good to use PhantomJS to perform Protractor Testing , instead use Karma Testing. However I want to do end-to-end testing not unit testing.

End to End meaning I want to set commands which will make the browser acts like human user. Therefore I cannot switch back to Karma . I tried to use PhantomJS with Protractor as browsername but it doesn't seem work. If anyone can share knowledge on how to use PhantomJS and Protractor for Jenkins (CI) integration environment will be great help or any other headless browser you know of.

答:
Starting Chrome version 59, there is a headless version of Chrome browser. You can use this as your headless browser, and integrate it in your CI .

You can use the headless mode of Chrome, by just specifying --headless option in chromeOptions in the test capabilities like

```<code> capabilities: {
browserName: 'chrome',
'chromeOptions': {
  args: ['--test-type','--headless']
}
</code>```

Please note that there are bugs in this headless mode, so you need to careful about them too.

Body:
Starting Chrome version 59, there is a headless version of Chrome browser. You can use this as your headless browser, and integrate it in your CI .

You can use the headless mode of Chrome, by just specifying --headless option in chromeOptions in the test capabilities like

 capabilities: {
browserName: 'chrome',
'chromeOptions': {
  args: ['--test-type','--headless']
}

Please note that there are bugs in this headless mode, so you need to careful about them too.


问:
group by users usage on a shared folder in Red hat FS
History: I have a shared folder which can be access by all the users of the system. every one claims that they are not using much. So, I decided to check how much each user uses the shared folder.

I am able to get the total usage by du -sh <path/to/folder>. but not at the individual users level.

I think, I am thinking too much to get this done. probably, there might be straight forward way to get this done.

If somebody asked similar kind of question please share the URL.

答:
Here's a couple of functions that may help

```<code>space() {
    local user=$1
    local space=0
    local tmp=`mktemp`
    find . -user $user -exec stat --printf="%s\n" {} \; 2>/dev/null >> $tmp
    for size in `cat $tmp`; do ((space=space + size)); done
    local humanized=`mb $space`
    echo "`pwd` $user $humanized"
    rm -f $tmp
}

mb() {
    local orig=$1
    if [[ $orig -gt $((2**20)) ]]; then
        echo -n $(($orig / 2**20))
        echo "mb"
    else
        echo -n $(($orig / 2**10))
        echo "kb"
    fi
}
</code>```

Paste these into your shell and then call it on the command line like

```<code>$space <user>
</code>```

it will print out all the file sizes to a temporary file and then add them all up. The mb function makes it human readable. When I run it I get

```<code>/home/me me 377mb
</code>```

Compared with

```<code>du -sh .
399M    .
</code>```

Pretty close ;)

Body:
Here's a couple of functions that may help

space() {
    local user=$1
    local space=0
    local tmp=`mktemp`
    find . -user $user -exec stat --printf="%s\n" {} \; 2>/dev/null >> $tmp
    for size in `cat $tmp`; do ((space=space + size)); done
    local humanized=`mb $space`
    echo "`pwd` $user $humanized"
    rm -f $tmp
}

mb() {
    local orig=$1
    if [[ $orig -gt $((2**20)) ]]; then
        echo -n $(($orig / 2**20))
        echo "mb"
    else
        echo -n $(($orig / 2**10))
        echo "kb"
    fi
}

Paste these into your shell and then call it on the command line like

$space <user>

it will print out all the file sizes to a temporary file and then add them all up. The mb function makes it human readable. When I run it I get

/home/me me 377mb

Compared with

du -sh .
399M    .

Pretty close ;)


问:
CurrentSourceFilename with wildcard Source
I'm using AfterInstall on a [Files] entry with a wildcard Source parameter. Calling CurrentSourceFilename simply gives me the source pattern -- not the actual file that is being processed. Is there any way to get the actual filename?

The following example would log {code:DirName}\*.ext once for each file, not {code:DirName}\file1.ext, {code:DirName}\file2.ext etc.

```<code>[Files]
Source: "{code:DirName}\*.ext"; Flags: external; AfterInstall: LogName
</code>```

[Code]
procedure LogName;
begin
  Log(CurrentSourceFilename);
end;

function DirName(Param: String): String;
begin
  Result := 'dir';
end;
```

答:
There's indeed no way to retrieve that information, when external flag is used - seems like a bug to me.

Without external flag, you can find out a file name using CurrentFilename.

Instead, you can code the file copy (including the logging) in Pascal script.

See Inno Setup: copy folder, subfolders and files recursively in Code section.

Body:
I'm using AfterInstall on a [Files] entry with a wildcard Source parameter. Calling CurrentSourceFilename simply gives me the source pattern -- not the actual file that is being processed. Is there any way to get the actual filename?

The following example would log {code:DirName}\*.ext once for each file, not {code:DirName}\file1.ext, {code:DirName}\file2.ext etc.

[Files]
Source: "{code:DirName}\*.ext"; Flags: external; AfterInstall: LogName

[Code]
procedure LogName;
begin
  Log(CurrentSourceFilename);
end;

function DirName(Param: String): String;
begin
  Result := 'dir';
end;

ContentLicense: CC BY-SA 4.0


问:
How do I scrape constantly updated JavaScript post-login using Python?
I know there are many similar questions, however, they are all piecemeal to the problem I have, and I haven't been successful in putting the information together.

I am using a FLIR ax8 thermal camera, and this camera has a web-interface that one can interact with via ethernet. Long story short, temperature values are constantly displayed and updated, and I would like to scrape those values. I would like to do this without opening a browser with a GUI, and just be able to call every so often to get them.

The first step is a simple login page, located at "cameraIP"/login. It's very basic, but I need a solution that gets me through this, and be able to maintain the login session. Then it's just the interface. Attached are two images, the first showing interface as seen in Chrome, and the second a terminal output of what I scraped using Python's Requests module.

As you can see, the numbers are clearly not there, as they are rendered by JavaScript. This is essentially all I have to work with. If someone could give advice on how this is possible to get those temperature values every so often, that would be great.

If there are ANY questions, just leave a comment down below and I can provide more information, such as the JS files listed under the web interface if they are needed.

答: I personally use scrapy splash to render the javascript when scraping using scrapy: http://splash.readthedocs.io/en/stable/</p>