问:
Why destructors does not accept parameters in C++?
Recently, I came across an example that my destructor needs to take a parameter.

I am working on a C package that manages memory internally and keeps track of allocating and freeing with parameters of its own. I do not want to break that.

I wrote a C code, that initializes my own data structures and frees them at the end. When I decided to migrate to C++ I realized that allocating data structures and freeing them should be placed in constructor and destructors. So I changed those functions to constructor and destructor.
My problem now is that I need to use a parameter to pass to destructor to free allocated data; that parameter is not in my own code and is C and I do not want to mess with that.

My question is twofold:

Why C++ decided not to accept parameters in destructors in the first place?
and
What are my options?
(I can save a pointer to that parameter or somehow call that function in my destructor, but it seems not a good practice of C++ programming)

Update: adding some code
Here is my imaginary class:

```<code>class paru_symbolic/* paru_symbolic*/
{
    public:
        paru_symbolic ( cholmod_sparse *A, cholmod_common *cc ); // constructor
        ~paru_symbolic (cholmod_common *cc ); // destructor

        // -------------------------------------------------------------------------
        // row-form of the input matrix and its permutations
        // -----------------------------------------------------------------------
              //--- other stuff
                     ...
};
</code>```

Here is my current C constructor:

```<code>#include "Parallel_LU.hpp"
paru_symbolic *paru_sym_analyse
(
 // inputs, not modified
   cholmod_sparse *A,
 // workspace and parameters
   cholmod_common *cc ){

    DEBUGLEVEL(0);
...
   aParent = (Int*) paru_alloc (m+nf, sizeof(Int),cc);

...
}
</code>```

and destructor:

```<code>void paru_freesym (paru_symbolic **LUsym_handle,
            // workspace and parameters
    cholmod_common *cc
){
    DEBUGLEVEL (0);
    if (LUsym_handle == NULL || *LUsym_handle == NULL){
        // nothing to do; caller probably ran out of memory
        return;
    }

    paru_symbolic *LUsym;
    LUsym = *LUsym_handle;

    Int m, n, anz, nf, rjsize;
...
    cholmod_l_free (m+nf, sizeof (Int), LUsym->aParent, cc);

...
    cholmod_l_free (1, sizeof (paru_symbolic), LUsym, cc);

   *LUsym_handle = NULL;
}
</code>```

The parameter cc is used inside the SuiteSparse package for tracking allocations and freeing data. It has been used all over in SuiteSparse package and is a useful tool for tracking memory.
Some people mentioned that who wants to pass a parameter to the destructor.That is a fair point, but we could have the same parameters that we have in the constructor as a default.

答:
In C++, this sort of thing is done via an allocator, see also std::allocator. So, you could create your own allocator with a cholmod_common* data member.

Alternatively, you can use the deleter parameter for memory management via smart pointers. For example

```<code>class foo
{
  struct bar_deleter {
    cholmod_common *cc;
    bar_deleter(cholmod_common *c) : cc(c) {}
    void destroy(bar*) { cc->free(bar); }
  };
  std::unique_ptr<bar,bar_deleter> data;
public:
  foo(some_type const&input, cholmod_common *cc)
    : data(cc->create<bar>(input), bar_deleter(cc)) {}
};
</code>```

Which, of course, also keeps a cholmod_common* with the data.

The name "cholmod_common" suggests that this is a common resource, i.e. there is only one cholmod_common object at any given time. Iff this is so, then you could use a stateless allocator, which keeps the common resource as a static data member (or obtains it via a singleton).

Body:
Recently, I came across an example that my destructor needs to take a parameter.

I am working on a C package that manages memory internally and keeps track of allocating and freeing with parameters of its own. I do not want to break that.

I wrote a C code, that initializes my own data structures and frees them at the end. When I decided to migrate to C++ I realized that allocating data structures and freeing them should be placed in constructor and destructors. So I changed those functions to constructor and destructor.
My problem now is that I need to use a parameter to pass to destructor to free allocated data; that parameter is not in my own code and is C and I do not want to mess with that.

My question is twofold:

Why C++ decided not to accept parameters in destructors in the first place?
and
What are my options?
(I can save a pointer to that parameter or somehow call that function in my destructor, but it seems not a good practice of C++ programming)

Update: adding some code
Here is my imaginary class:

class paru_symbolic/* paru_symbolic*/
{
    public:
        paru_symbolic ( cholmod_sparse *A, cholmod_common *cc ); // constructor
        ~paru_symbolic (cholmod_common *cc ); // destructor

        // -------------------------------------------------------------------------
        // row-form of the input matrix and its permutations
        // -----------------------------------------------------------------------
              //--- other stuff
                     ...
};

Here is my current C constructor:

#include "Parallel_LU.hpp"
paru_symbolic *paru_sym_analyse
(
 // inputs, not modified
   cholmod_sparse *A,
 // workspace and parameters
   cholmod_common *cc ){

    DEBUGLEVEL(0);
...
   aParent = (Int*) paru_alloc (m+nf, sizeof(Int),cc);

...
}

and destructor:

void paru_freesym (paru_symbolic **LUsym_handle,
            // workspace and parameters
    cholmod_common *cc
){
    DEBUGLEVEL (0);
    if (LUsym_handle == NULL || *LUsym_handle == NULL){
        // nothing to do; caller probably ran out of memory
        return;
    }

    paru_symbolic *LUsym;
    LUsym = *LUsym_handle;

    Int m, n, anz, nf, rjsize;
...
    cholmod_l_free (m+nf, sizeof (Int), LUsym->aParent, cc);

...
    cholmod_l_free (1, sizeof (paru_symbolic), LUsym, cc);

   *LUsym_handle = NULL;
}

The parameter cc is used inside the SuiteSparse package for tracking allocations and freeing data. It has been used all over in SuiteSparse package and is a useful tool for tracking memory.
Some people mentioned that who wants to pass a parameter to the destructor.That is a fair point, but we could have the same parameters that we have in the constructor as a default.

Body:
In C++, this sort of thing is done via an allocator, see also std::allocator. So, you could create your own allocator with a cholmod_common* data member.

Alternatively, you can use the deleter parameter for memory management via smart pointers. For example

class foo
{
  struct bar_deleter {
    cholmod_common *cc;
    bar_deleter(cholmod_common *c) : cc(c) {}
    void destroy(bar*) { cc->free(bar); }
  };
  std::unique_ptr<bar,bar_deleter> data;
public:
  foo(some_type const&input, cholmod_common *cc)
    : data(cc->create<bar>(input), bar_deleter(cc)) {}
};

Which, of course, also keeps a cholmod_common* with the data.

The name "cholmod_common" suggests that this is a common resource, i.e. there is only one cholmod_common object at any given time. Iff this is so, then you could use a stateless allocator, which keeps the common resource as a static data member (or obtains it via a singleton).


来源: stackexchange

问:
Divide string before integer value using php
I have some random type string and I want them to separate from each other.
My string is like these:

```<code> 1.  GPF#: AUDITKT0059 800,126.00
 2.  GPF#: IV EMP KK 8 58,971.00
 3.  GPF#: GAKU 000006 317,253.00
</code>```

I want to get the GPF value but the issue is last values coming with string.I just want the value like AUDITKT0059,IV EMP KK 8 and GAKU 000006.I tried by exploding with GPF and then space but this not the way it works.So any suggestion? Thanks
I tried like this :

```<code>$gpf = explode("GPF#:", $data[$c]);

             $gpfs = explode(" ", $gpf[1]);
             print_r($gpfs);
            echo " GPF# ".$gpfs[0]."<br />\n";
</code>```

答:
You can use a simple regex like this:

```<code>_(.*)_
</code>```

Note that I used _ just to show a white space .

Working demo

Php code

```<code>$re = '/ (.*) /';
$str = 'GPF#: AUDITKT0059 800,126.00
GPF#: IV EMP KK 8 58,971.00
GPF#: GAKU 000006 317,253.00';

preg_match_all($re, $str, $matches);

// Print the entire match result
var_dump($matches);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some random type string and I want them to separate from each other.
My string is like these:

 1.  GPF#: AUDITKT0059 800,126.00
 2.  GPF#: IV EMP KK 8 58,971.00
 3.  GPF#: GAKU 000006 317,253.00

I want to get the GPF value but the issue is last values coming with string.I just want the value like AUDITKT0059,IV EMP KK 8 and GAKU 000006.I tried by exploding with GPF and then space but this not the way it works.So any suggestion? Thanks
I tried like this :

$gpf = explode("GPF#:", $data[$c]);

             $gpfs = explode(" ", $gpf[1]);
             print_r($gpfs);
            echo " GPF# ".$gpfs[0]."
\n";

Body:
You can use a simple regex like this:

_(.*)_

Note that I used _ just to show a white space .

Working demo

Php code

$re = '/ (.*) /';
$str = 'GPF#: AUDITKT0059 800,126.00
GPF#: IV EMP KK 8 58,971.00
GPF#: GAKU 000006 317,253.00';

preg_match_all($re, $str, $matches);

// Print the entire match result
var_dump($matches);


问:
Display textview below imageview and not bottom to the parent
I'm working on an Android application and I have an issue with how to display an image in a view. My issue is that I want to display an image and two textViews just below my imageView without aligning their bottom to the parent's. See the wireframe below.

My problem is that when the imageView is taking all the height of the relativeLayout, my textViews are hidden below the parents view.

I have tried a lot of things but nothing is satisfaying...
I have tried to put my imageview in a linearLayout and put a weight on it but if my imageView is smaller I have a blank between the imageView and the textView.

It's complicated because each image I load can have a different size and thus I can't fix a default size to it.
Also, my layout is in a viewPager and when I want to have the Height of the view when I instantiate it on my adapter it returns 0. So I can't compute the size of the elements in the view.

Have you any idea how can I make my layout ?

Maybe in a coordinatorLayout to have circular dependencies (but I don't know how to make it) ?

Here a wireframe of what I want to do with my view: image

And here the code of my layout :

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_photo_detail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/relative_photo_detail_bottom_infos">

        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/placeholder"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <TextView
            android:id="@+id/photo_detail_owner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/photo_detail_full_size"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:textColor="@color/grey"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_bottom_infos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/relative_photo_detail_image"
        android:padding="10dp">

        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>
</code>```

答: Try putting your code inside Scroll view</p>

Body:
I'm working on an Android application and I have an issue with how to display an image in a view. My issue is that I want to display an image and two textViews just below my imageView without aligning their bottom to the parent's. See the wireframe below.

My problem is that when the imageView is taking all the height of the relativeLayout, my textViews are hidden below the parents view.

I have tried a lot of things but nothing is satisfaying...
I have tried to put my imageview in a linearLayout and put a weight on it but if my imageView is smaller I have a blank between the imageView and the textView.

It's complicated because each image I load can have a different size and thus I can't fix a default size to it.
Also, my layout is in a viewPager and when I want to have the Height of the view when I instantiate it on my adapter it returns 0. So I can't compute the size of the elements in the view.

Have you any idea how can I make my layout ?

Maybe in a coordinatorLayout to have circular dependencies (but I don't know how to make it) ?

Here a wireframe of what I want to do with my view: image

And here the code of my layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_photo_detail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/relative_photo_detail_bottom_infos">

        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/placeholder"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <TextView
            android:id="@+id/photo_detail_owner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/photo_detail_full_size"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:textColor="@color/grey"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_bottom_infos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/relative_photo_detail_image"
        android:padding="10dp">

        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>


问:
Getting specific fields' values of a text using awk, sed, and grep
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

```<code>{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}
</code>```

答:
Another jq approach :

```<code>jq '.[]?|.[]?|.name' file
"Brian O'Halloran"
"Jason Mewes"
"Jeff Anderson"
"Kevin Smith"
"Richard J. Gasparian"
"Tristin Cole"
"Nadia Vurbenova"
"Simon Rodgers"
"Kevin Smith"
"Harvey Weinstein"
"Bob Weinstein"
</code>```

Note: The .foo? usage [ see manpage ] does not output even an error when . is not an array or an object.

Body:
I would like to get the values of the name fields of the following text, using sed, awk, grep or similar.

{
    "cast": [
        {
            "character": "",
            "credit_id": "52532e3119c29579400012b5",
            "gender": null,
            "id": 23629,
            "name": "Brian O'Halloran",
            "order": 0,
            "profile_path": "/eJsLxovTdcm6QK9PDB2pCe5FMqK.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c2957940001315",
            "gender": null,
            "id": 19302,
            "name": "Jason Mewes",
            "order": 1,
            "profile_path": "/so3nT2vgSCZMO2QXDVHF3ubxaFX.jpg"
        },
        {
            "character": "",
            "credit_id": "52532e3119c295794000133d",
            "gender": null,
            "id": 23630,
            "name": "Jeff Anderson",
            "order": 2,
            "profile_path": "/vjt5WhpJAx0jxvmiGc5PAOBzzb7.jpg"
        },
        {
            "character": "Silent Bob",
            "credit_id": "52532e3219c2957940001359",
            "gender": null,
            "id": 19303,
            "name": "Kevin Smith",
            "order": 4,
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        }
    ],
    "crew": [
        {
            "credit_id": "55425dbe9251410efa000094",
            "department": "Visual Effects",
            "gender": null,
            "id": 1419667,
            "job": "Animation Manager",
            "name": "Richard J. Gasparian",
            "profile_path": null
        },
        {
            "credit_id": "5544521dc3a3680ce60037e8",
            "department": "Art",
            "gender": null,
            "id": 1450356,
            "job": "Background Designer",
            "name": "Tristin Cole",
            "profile_path": null
        },
        {
            "credit_id": "554a142dc3a3683c84001851",
            "department": "Art",
            "gender": null,
            "id": 1447432,
            "job": "Background Designer",
            "name": "Nadia Vurbenova",
            "profile_path": null
        },
        {
            "credit_id": "554bcd2b9251414692002c9b",
            "department": "Production",
            "gender": null,
            "id": 1447493,
            "job": "Location Manager",
            "name": "Simon Rodgers",
            "profile_path": null
        },
        {
            "credit_id": "52532e3219c29579400013cd",
            "department": "Production",
            "gender": null,
            "id": 19303,
            "job": "Executive Producer",
            "name": "Kevin Smith",
            "profile_path": "/3XXThSMqHQgQFjM4bMJ25U1EJTj.jpg"
        },
        {
            "credit_id": "52532e3319c2957940001405",
            "department": "Production",
            "gender": null,
            "id": 59839,
            "job": "Producer",
            "name": "Harvey Weinstein",
            "profile_path": "/k4UCnh7n0r5CEjq30gAl6QCfF9g.jpg"
        },
        {
            "credit_id": "52532e3319c29579400014a7",
            "department": "Production",
            "gender": null,
            "id": 1307,
            "job": "Producer",
            "name": "Bob Weinstein",
            "profile_path": "/oe5Oxp034UOubnvZqqhurp6a1EP.jpg"
        }
    ],
    "id": 2
}

Body:
Another jq approach :

jq '.[]?|.[]?|.name' file
"Brian O'Halloran"
"Jason Mewes"
"Jeff Anderson"
"Kevin Smith"
"Richard J. Gasparian"
"Tristin Cole"
"Nadia Vurbenova"
"Simon Rodgers"
"Kevin Smith"
"Harvey Weinstein"
"Bob Weinstein"

Note: The .foo? usage [ see manpage ] does not output even an error when . is not an array or an object.


问:
checkboxes central vertical alignment using angular, bootstrap
I am trying to center align my checkboxes, when you add a new input this is how they are displayed now:
checkboxes not aligned well .
This is the code I am using (angular and bootstrap):

```<code><div  class="container text-center">
<form ng-submit="todoAdd()">
    <input type="text" ng-model="todoInput" size="50" placeholder="Add New">
    <input type="submit" class="btn btn-success" value="Add New">
</form>

<br>

<div ng-repeat="x in todoList">
    <input type="checkbox" ng-model="x.done"> <span ng-bind="x.todoText"></span>
</div>

<p><button ng-click="remove()">Remove marked</button></p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
    $scope.todoList = [{todoText:'Clean House', done:false}];

    $scope.todoAdd = function() {
        $scope.todoList.push({todoText:$scope.todoInput, done:false});
        $scope.todoInput = "";
    };

    $scope.remove = function() {
        var oldList = $scope.todoList;
        $scope.todoList = [];
        angular.forEach(oldList, function(x) {
            if (!x.done) $scope.todoList.push(x);
        });
    };
});
</script>
</code>```

I am wondering is there any way to align the boxes vertically (in the center of the page) maybe with bootstrap or any other suggestion would be helpful? This is my first question so I apologize in advance if it's not formulated right, and I thank you in advance for the answers!

答:
This is a pure css topic, you should use a flexbox:

```<code><div ng-repeat="x in todoList" style="display: flex; flex-direction: row; align-items: center">
<input type="checkbox" ng-model="x.done"> <span style="flex: 1" ng-bind="x.todoText"></span>
</div>
</code>```

or in classes:

```<code>.flex-container {
 display: flex;
 flex-direction: row;
 align-items: center;
}

.flex-fill {
 flex: 1;
}
</code>```

and set the container to the repeat div, and the fill class on the label.
fyi: flex: 1 means that the element should fill up the remaining width of the container.
(I hope the code above has a proper syntax)

In bootstrap it should be something like:

```<code><div ng-repeat="x in todoList" class="form-group">
  <label class="control-label" ng-bind="x.todoText">
      <input class="form-control" type="checkbox" ng-model="x.done">
  </label>
</div>
</code>```

but I'm not quite sure if this is a 100% correct

Body:
I am trying to center align my checkboxes, when you add a new input this is how they are displayed now:
checkboxes not aligned well .
This is the code I am using (angular and bootstrap):

<form ng-submit="todoAdd()">
    <input type="text" ng-model="todoInput" size="50" placeholder="Add New">
    <input type="submit" class="btn btn-success" value="Add New">
</form>

    <input type="checkbox" ng-model="x.done">

<button ng-click="remove()">Remove marked</button>

I am wondering is there any way to align the boxes vertically (in the center of the page) maybe with bootstrap or any other suggestion would be helpful? This is my first question so I apologize in advance if it's not formulated right, and I thank you in advance for the answers!

Body:
This is a pure css topic, you should use a flexbox:

<div ng-repeat="x in todoList" style="display: flex; flex-direction: row; align-items: center">
<input type="checkbox" ng-model="x.done"> <span style="flex: 1" ng-bind="x.todoText"></span>
</div>

or in classes:

.flex-container {
 display: flex;
 flex-direction: row;
 align-items: center;
}

.flex-fill {
 flex: 1;
}

and set the container to the repeat div, and the fill class on the label.
fyi: flex: 1 means that the element should fill up the remaining width of the container.
(I hope the code above has a proper syntax)

In bootstrap it should be something like:

<div ng-repeat="x in todoList" class="form-group">
  <label class="control-label" ng-bind="x.todoText">
      <input class="form-control" type="checkbox" ng-model="x.done">
  </label>
</div>

but I'm not quite sure if this is a 100% correct


问:
What is the fastest way to swap values in C?
I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:

```<code>void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
</code>```

Or the xor version that I'm sure most people have seen:

```<code>void swap(int* a, int* b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}
</code>```

It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each.  Can someone tell me which is faster and why?  The why being more important.

答:
I just placed both swaps (as macros) in hand written quicksort I've been playing with. The XOR version was much faster (0.1sec) then the one with the temporary variable (0.6sec). The XOR did however corrupt the data in the array (probably the same address thing Ant mentioned).

As it was a fat pivot quicksort, the XOR version's speed is probably from making large portions of the array the same. I tried a third version of swap which was the easiest to understand and it had the same time as the single temporary version.
```<code>
acopy=a;
bcopy=b;
a=bcopy;
b=acopy;
</code>```

[I just put an if statements around each swap, so it won't try to swap with itself, and the XOR now takes the same time as the others (0.6 sec)]

ContentLicense: CC BY-SA 2.5

Body:
I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:

void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

Or the xor version that I'm sure most people have seen:

void swap(int* a, int* b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each.  Can someone tell me which is faster and why?  The why being more important.

Body:
I just placed both swaps (as macros) in hand written quicksort I've been playing with. The XOR version was much faster (0.1sec) then the one with the temporary variable (0.6sec). The XOR did however corrupt the data in the array (probably the same address thing Ant mentioned).

As it was a fat pivot quicksort, the XOR version's speed is probably from making large portions of the array the same. I tried a third version of swap which was the easiest to understand and it had the same time as the single temporary version.

acopy=a;
bcopy=b;
a=bcopy;
b=acopy;

[I just put an if statements around each swap, so it won't try to swap with itself, and the XOR now takes the same time as the others (0.6 sec)]

OwnerDisplayName: paperhorse

LastEditorDisplayName: paperhorse


问:
Using javascript to alter span text dynamically and keeping the original text
I have a  html page, inside which i have following code snippet, depending on which case we're following:

```<code>CASE 1)    <p> <span id ="xyz">  some code here  </span> </p>
CASE 2)    <p> <span id ="xyz">   </span> some code here </p>
</code>```

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

答:
You can just store the current value in a String, and then modify this string:

```<code>var mySpan = document.getElementById('xyz').innerHTML;
mySpan += ' and this gets added after the some code here';
document.getElementById('xyz').innerHTML = mySpan;
</code>```

or faster and more shorthand,

```<code>document.getElementById('xyz').innerHTML = document.getElementById('xyz').innerHTML + ' new text after'; //to add text after the existing text
document.getElementById('xyz').innerHTML = 'your new text before ' + document.getElementById('xyz').innerHTML; //to add text before.
</code>```

Body:
I have a  html page, inside which i have following code snippet, depending on which case we're following:

CASE 1)
   some code here

CASE 2)
     some code here

Now in my javascript code I have to write values in span xyz dynamically. If I try to do get reference to span xyz by id and then try to alter its innerHTML, then the html already present in span xyz is lost.

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

Body:
You can just store the current value in a String, and then modify this string:

var mySpan = document.getElementById('xyz').innerHTML;
mySpan += ' and this gets added after the some code here';
document.getElementById('xyz').innerHTML = mySpan;

or faster and more shorthand,

document.getElementById('xyz').innerHTML = document.getElementById('xyz').innerHTML + ' new text after'; //to add text after the existing text
document.getElementById('xyz').innerHTML = 'your new text before ' + document.getElementById('xyz').innerHTML; //to add text before.


问:
Delete all rows from datagridview and database
Hi guys as the title says i want to delete all rows from a datagridview and in the process deleting them from the database. Heres my code but its only deleting one row and not all. Thank you</p>

```<code>     private void clear_Click(object sender, EventArgs e)
    {

        if (this.dgvProducts.SelectedRows.Count > 0)
        {
            foreach (DataGridViewRow row in dgvProducts.SelectedRows)
            {
                int selectedIndex = dgvProducts.SelectedRows[0].Index;
                int rowID = int.Parse(dgvProducts[0, selectedIndex].Value.ToString());
                 crud.AddRecord("Delete from Supplier_productlist where ProductID = '" + rowID + "' and SupplierID = '"+supplierid.Text+"' ");

            }
        }

        //dgvProducts.Refresh();

    }
</code>```

答:
It seems that in the foreach loop, only 0th item was processed.

If you want to specify index, I would suggest for loop instead of foreach.

If you want to use foreach, then you probably should work on "row" itself instead of keep working on 0th item:

```<code>dgvProducts.SelectedRows[0]
dgvProducts[0, selectedIndex]
</code>```

Body:
Hi guys as the title says i want to delete all rows from a datagridview and in the process deleting them from the database. Heres my code but its only deleting one row and not all. Thank you

     private void clear_Click(object sender, EventArgs e)
    {

        if (this.dgvProducts.SelectedRows.Count > 0)
        {
            foreach (DataGridViewRow row in dgvProducts.SelectedRows)
            {
                int selectedIndex = dgvProducts.SelectedRows[0].Index;
                int rowID = int.Parse(dgvProducts[0, selectedIndex].Value.ToString());
                 crud.AddRecord("Delete from Supplier_productlist where ProductID = '" + rowID + "' and SupplierID = '"+supplierid.Text+"' ");

            }
        }

        //dgvProducts.Refresh();

    }

Body:
It seems that in the foreach loop, only 0th item was processed.

If you want to specify index, I would suggest for loop instead of foreach.

If you want to use foreach, then you probably should work on "row" itself instead of keep working on 0th item:

dgvProducts.SelectedRows[0]
dgvProducts[0, selectedIndex]


问:
Rails 5, javascript is not loaded in production
In my app I use the bootstrap theme (gentelella), and in one of my pages I have a Moris graph which works perfect in Development evniroment but in production(heroku) doesn't work.

The error in the console is the following:
**Uncaught ReferenceError: Morris is not defined
**

It looks like the js for the Moris graph(the script is included in gentelella) is not loaded but everything else works fine.

Code for my graph:

```<code>   <div id="graph_line"></div>
   <script type="text/javascript">
   new Morris.Line({
      element: 'graph_line',
      data: [
      {Date: 'mydate1', y: myvalue1},
      {Date: 'mydate2', y: myvalue2},
      {Date: 'mydate3', y: myvalue3}
      ],
      xkey: 'Date',
      ykeys: ['y'],
      labels: ['Y'],
      hideHover: 'auto',
      lineColors: ['#26B99A', '#34495E', '#ACADAC', '#3498DB'],
      resize: true
    });
   </script>
</code>```

I don't include any Moris.js  because it is already included in my theme.

I don't understand why it works fine in local and not in production.

After some researching, I added this line in my production.rb:

```<code> config.assets.debug = true
</code>```

and in heroku logs I have the error:

The asset "application.css" is not present in the asset pipeline
and the app is not running but it runs without the above line.

Any idea why my graph is not working in production and why heroku does not see my application.css

P.S in my assets I have application.scss and not application.css could this cause the problem? But I need the file to be .scss

My application.js:

```<code>   //= require jquery
   //= require jquery.turbolinks
   //= require jquery_ujs
   //= require jquery.remotipart
   //= require pnotify
   //= require unobtrusive_flash
   //= require flashes
   //= require gentelella
   //= require gentelella-custom
   //= require_tree .
</code>```

The morris scripts are initialized in the gentellela-custom.js (init_morris_charts();)

And my application.html.erb

```<code>  <%= csrf_meta_tags %>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</code>```

答:
Update you code to have a debugger reference:
<%= debugger; %> before the line with: new Morris.Line({, and then open your favorite browser, switch to the debugger window and you will have a break point in there.
That will help you see if Morris is loaded at that point in time.

Body:
In my app I use the bootstrap theme (gentelella), and in one of my pages I have a Moris graph which works perfect in Development evniroment but in production(heroku) doesn't work.

The error in the console is the following:
**Uncaught ReferenceError: Morris is not defined
**

It looks like the js for the Moris graph(the script is included in gentelella) is not loaded but everything else works fine.

Code for my graph:

I don't include any Moris.js  because it is already included in my theme.

I don't understand why it works fine in local and not in production.

After some researching, I added this line in my production.rb:

 config.assets.debug = true

and in heroku logs I have the error:

The asset "application.css" is not present in the asset pipeline
and the app is not running but it runs without the above line.

Any idea why my graph is not working in production and why heroku does not see my application.css

P.S in my assets I have application.scss and not application.css could this cause the problem? But I need the file to be .scss

My application.js:

   //= require jquery
   //= require jquery.turbolinks
   //= require jquery_ujs
   //= require jquery.remotipart
   //= require pnotify
   //= require unobtrusive_flash
   //= require flashes
   //= require gentelella
   //= require gentelella-custom
   //= require_tree .

The morris scripts are initialized in the gentellela-custom.js (init_morris_charts();)

And my application.html.erb

  <%= csrf_meta_tags %>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>


问:
Error:(26, 13) Failed to resolve: com.android.support:appcompat-v7:25.+
I am facing gradle error when I build a project (simple helloworld app) in android studio 2.3.3. I have attached here screen shot that describes error messages I am facing. Please help me how to get rid of it?

NOTE -Please tell me which code files are to be added to get rid of this type of error.

My build.gradle:

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'

       }
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
</code>```

答:
Simply go to your project structure, then under Gradle Scripts>
build.gradle(Module:app)

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.0.1'
    //not like com.android.support:appcompat-v7:25.+
    testCompile 'junit:junit:4.12'
}
</code>```

Also newer version of appcompat hint appears under your status bar, use it.

Body:
I am facing gradle error when I build a project (simple helloworld app) in android studio 2.3.3. I have attached here screen shot that describes error messages I am facing. Please help me how to get rid of it?

NOTE -Please tell me which code files are to be added to get rid of this type of error.

My build.gradle:

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.1'

       }
}

allprojects {
repositories {
    jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

Body:
Simply go to your project structure, then under Gradle Scripts>
build.gradle(Module:app)

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.0.1'
    //not like com.android.support:appcompat-v7:25.+
    testCompile 'junit:junit:4.12'
}

Also newer version of appcompat hint appears under your status bar, use it.


问:
How do I merge consecutive elements in an array subject to a constraint?
I'm using Ruby 2.4.  I have an array of strings and I want to join consecutive elements if there is a "-" between them.  So, for example, if I have

```<code>["a", "-", "b", "c"]
</code>```

I want the result to be

```<code>["a - b", "c"]
</code>```

Similarly if the array is

```<code>["a-", "b", "c"]
</code>```

I want the result to be

```<code>["a- b", "c"]
</code>```

Or if the array is

```<code>["a", "-b", "c", "d"]
</code>```

I want the result to be

```<code>["a -b", "c", "d"]
</code>```

One exception is that if one of the adjacent tokens already contains a "-", I don't want to merge them together.  So for example, if I have

```<code>["a", "-", "b-c", "d"]
</code>```

I want the array to remain as

```<code>["a", "-", "b-c", "d"]
</code>```

Cary helped me come up with this function

```<code>  def join_some(arr, special_chars_arr)
    arr.drop(1).each_with_object([arr.first]).with_index(1) do |(s,a),i|
      puts "s: #{s} a: #{a.last}"
      if ((special_chars_arr.include?(s[0]) && (i < arr.size - 1 || s.size > 1)) ||
          (special_chars_arr.include?(a.last[-1]) && (i > 1 || a.last.size > 1))) &&
         a.last !~ Regexp.union(special_chars_arr)
        a.last << " #{s}"
      else
        a << s
      end
    end
  end
</code>```

but the problem is if my array is

```<code>["a", "-", "b-c"]
</code>```

calling join_some(arr, ["-"]) turns things into

```<code>["a - b-c"]
</code>```

and I don't want to merge adjacent tokens since one of them already contains a dash.  How can I modify my method to do what I want?

Body:
I'm using Ruby 2.4.  I have an array of strings and I want to join consecutive elements if there is a "-" between them.  So, for example, if I have

["a", "-", "b", "c"]

I want the result to be

["a - b", "c"]

Similarly if the array is

["a-", "b", "c"]

I want the result to be

["a- b", "c"]

Or if the array is

["a", "-b", "c", "d"]

I want the result to be

["a -b", "c", "d"]

One exception is that if one of the adjacent tokens already contains a "-", I don't want to merge them together.  So for example, if I have

["a", "-", "b-c", "d"]

I want the array to remain as

["a", "-", "b-c", "d"]

Cary helped me come up with this function

  def join_some(arr, special_chars_arr)
    arr.drop(1).each_with_object([arr.first]).with_index(1) do |(s,a),i|
      puts "s: #{s} a: #{a.last}"
      if ((special_chars_arr.include?(s[0]) && (i < arr.size - 1 || s.size > 1)) ||
          (special_chars_arr.include?(a.last[-1]) && (i > 1 || a.last.size > 1))) &&
         a.last !~ Regexp.union(special_chars_arr)
        a.last << " #{s}"
      else
        a << s
      end
    end
  end

but the problem is if my array is

["a", "-", "b-c"]

calling join_some(arr, ["-"]) turns things into

["a - b-c"]

and I don't want to merge adjacent tokens since one of them already contains a dash.  How can I modify my method to do what I want?

Body:
def massage(arr)
  arr.drop(1).each_with_object([arr.first]) do |s,a|
    a <<
    case
    when s == '-'
      s
    when a.last == '-'
      ((a.size > 1) && (a[-2] =~ / - [^ -]+\z|\A[^-]+\z/) && (s !~ /-/)) ?
        [*a.pop(2),s].join(' ') : s
    when a.last.end_with?('-') ^ s.start_with?('-')
      a.pop << ' ' << s
    else
      s
    end
  end
end

examples = [["a","-","b","c"], ["a-","b","c"], ["a","-b","c","d"],
            ["a","-","b-c","d"], ["-", "a", "b"], ["a", "b", "-"],
            ["a", "-", "b", "-", "c"], ["a", "-", "b", "-", "c", "-d"]]

examples.each { |a| puts "#{a.to_s.ljust(32)}  \#=> #{massage(a)}" }
["a", "-", "b", "c"]              #=> ["a - b", "c"]
["a-", "b", "c"]                  #=> ["a- b", "c"]
["a", "-b", "c", "d"]             #=> ["a -b", "c", "d"]
["a", "-", "b-c", "d"]            #=> ["a", "-", "b-c", "d"]
["-", "a", "b"]                   #=> ["-", "a", "b"]
["a", "b", "-"]                   #=> ["a", "b", "-"]
["a", "-", "b", "-", "c"]         #=> ["a - b - c"]
["a", "-", "b", "-", "c", "-d"]   #=> ["a - b - c -d"]

^ is both the logical and bit-wise XOR operator. Here the two operands are each true or false (logical), so it returns true if one operand is true and the other is false.


问:
pivot table sort datetime column
I have the following part of sql statement to  pivot dynamic columns. The number of columns (ClosingDate) is variable :

```<code>select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ClosingDate + '_'+ c.col)
                      from #TmpT
                      cross apply
                      (
                        select 'Cnt' col
                        union all
                        select 'TT'
                      ) c
            FOR XML PATH('') , TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')
</code>```

The problem is that ClosingDate columns get converted to varchar and they are ordered as varchar, not as date .

Is there a way to order by datetime ? Thanks!

答:
You could try converting them to dates yourself first:</p>

```<code>select @cols = STUFF((SELECT distinct ',' +
                             QUOTENAME(CONVERT(VARCHAR(8),ClosingDate,112) + '_'+ c.col)
                      from #TmpT
                      cross apply
                      (
                        select 'Cnt' col
                        union all
                        select 'TT'
                      ) c
            FOR XML PATH('') , TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')
</code>```

Title: pivot table sort datetime column

Body:
I have the following part of sql statement to  pivot dynamic columns. The number of columns (ClosingDate) is variable :

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(ClosingDate + '_'+ c.col)
                      from #TmpT
                      cross apply
                      (
                        select 'Cnt' col
                        union all
                        select 'TT'
                      ) c
            FOR XML PATH('') , TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

The problem is that ClosingDate columns get converted to varchar and they are ordered as varchar, not as date .

Is there a way to order by datetime ? Thanks!

Body:
You could try converting them to dates yourself first:

select @cols = STUFF((SELECT distinct ',' +
                             QUOTENAME(CONVERT(VARCHAR(8),ClosingDate,112) + '_'+ c.col)
                      from #TmpT
                      cross apply
                      (
                        select 'Cnt' col
                        union all
                        select 'TT'
                      ) c
            FOR XML PATH('') , TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')


问:
Preferably than 5 days when the user has set up
That's the way I'm doing so that those customers who have not bought membership should send out newsletters.

Right now it takes hold of everyone.

But I would only have had those who have been set up for the last 5 days.

```<code>var FiveDays = DateTime.Today.AddDays(-5);//There must have been 5 days

var userlist = db.Users.Where(i => i.CreateDateTime.Day <= FiveDays.Day &&
 i.CreateDateTime.Month <= FiveDays.Month &&
 i.CreateDateTime.Year <= FiveDays.Year &&
 i.CustomerID == null).ToList();
</code>```

So what it's supposed to do is take it all in the 5 days and the rest it's not allowed to be left alone.

As it seems, it should only take one from the database.

答: ...and the problem is? If comparison is the problem, then I would advise using CompareTo method. This kind of comparison you are using is wrong, because it wouldn't accept the date from previous year having greater value of Day</p>

Body:
That's the way I'm doing so that those customers who have not bought membership should send out newsletters.

Right now it takes hold of everyone.

But I would only have had those who have been set up for the last 5 days.

var FiveDays = DateTime.Today.AddDays(-5);//There must have been 5 days

var userlist = db.Users.Where(i => i.CreateDateTime.Day <= FiveDays.Day &&
 i.CreateDateTime.Month <= FiveDays.Month &&
 i.CreateDateTime.Year <= FiveDays.Year &&
 i.CustomerID == null).ToList();

So what it's supposed to do is take it all in the 5 days and the rest it's not allowed to be left alone.

As it seems, it should only take one from the database.


问:
highlighting html with prism.js
I cant seem to highlight html with prism.js because it removes the markup just printing the text. the following code inside the "pre" tag shows as just the text. I have the class for the "code" tag set to "language-markup".

```<code>    <table class="data-table">
        <tr>
            <td>Title</td>
            <td>Amount</td>
        </tr>
        <tr>
            <td>Shorts</td>
            <td>£1.00</td>
        </tr>
        <tr>
            <td>Shorts</td>
            <td>£1.00</td>
        </tr>
    </table>
</code>```

shows as

```<code>            Title
            Amount

            Shorts
            £1.00

            Shorts
            £1.00
</code>```

Title: highlighting html with prism.js

Body:
I cant seem to highlight html with prism.js because it removes the markup just printing the text. the following code inside the "pre" tag shows as just the text. I have the class for the "code" tag set to "language-markup".

            Title
            Amount

            Shorts
            £1.00

            Shorts
            £1.00

shows as

            Title
            Amount

            Shorts
            £1.00

            Shorts
            £1.00

Body: In alternative you can wrap your code with <script type="prism-html-markup"> your code </script>


问:
Display array in table with 2 columns
I have an array like this:

```<code>Array
(
    [0] => Array
        (
            [Title] => Title 1,
            [Value] => Value 1
        ),

    [1] => Array
        (
            [Title] => Title 2,
            [Value] => Value 2
        ),

    [2] => Array
        (
            [Title] => Title 3,
            [Value] => Value 3
        ),

    [3] => Array
        (
            [Title] => Title 4,
            [Value] => Value 4
        )

);
</code>```

And I would like to create a table like this:

```<code>|---------------------|------------------|
|      Title 1        |     Title 2      |
|---------------------|------------------|
|      Value 1        |     Value 2      |
|---------------------|------------------|
|      Title 3        |     Title 4      |
|---------------------|------------------|
|      Value 3        |     Value 4      |
|---------------------|------------------|
</code>```

I have found some foreach functions, but these all give me the title with the value next to it.. Any way to accomplish the above?

答:
If your array is $array, you can use foreach as such:

```<code>echo '<table>';
foreach ($array as $row)
{
    echo "<tr>";
    echo "<td>" . $row['Title'] . "</td>";
    echo "<td>" . $row['Value'] . "</td>";
    echo "</tr>";
}
echo '</table>';
</code>```

foreach basically loops through each element in $array and assigns it to $row. Since the elements of your array are other arrays, $row will be an array with the information you need for each row.

Title: Display array in table with 2 columns

Body:
I have an array like this:

Array
(
    [0] => Array
        (
            [Title] => Title 1,
            [Value] => Value 1
        ),

    [1] => Array
        (
            [Title] => Title 2,
            [Value] => Value 2
        ),

    [2] => Array
        (
            [Title] => Title 3,
            [Value] => Value 3
        ),

    [3] => Array
        (
            [Title] => Title 4,
            [Value] => Value 4
        )

);

And I would like to create a table like this:

|---------------------|------------------|
|      Title 1        |     Title 2      |
|---------------------|------------------|
|      Value 1        |     Value 2      |
|---------------------|------------------|
|      Title 3        |     Title 4      |
|---------------------|------------------|
|      Value 3        |     Value 4      |
|---------------------|------------------|

I have found some foreach functions, but these all give me the title with the value next to it.. Any way to accomplish the above?

Body:
If your array is $array, you can use foreach as such:

echo '<table>';
foreach ($array as $row)
{
    echo "<tr>";
    echo "<td>" . $row['Title'] . "</td>";
    echo "<td>" . $row['Value'] . "</td>";
    echo "</tr>";
}
echo '</table>';

foreach basically loops through each element in $array and assigns it to $row. Since the elements of your array are other arrays, $row will be an array with the information you need for each row.


问:
Getting error at Iterator while reading from excel sheet
Even though I have imported

```<code>import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
</code>```

I am getting error at part

Iterator<Cell> cellIterator=row.cellIterator();

Here is my full code

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
//import org.apache.poi.hssf.record.formula.functions.Cell;
//import org.apache.poi.hssf.record.formula.functions.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class UploadExcel {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();

                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator=row.cellIterator();

                while (cellIterator.hasNext())
                {
                     Cell cell = cellIterator.next();

                     //Check the cell type and format accordingly
                     switch (cell.getCellType())
                     {
                         case Cell.CELL_TYPE_NUMERIC:
                         System.out.print(cell.getNumericCellValue() + "\t");
                         break;
                         case Cell.CELL_TYPE_STRING:
                         System.out.print(cell.getStringCellValue() + "\t");
                         break;
                     }
                 }

                 System.out.println("");
             }

             file.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 }
</code>```

The error which i am getting is:

```<code>Type mismatch: cannot convert from java.util.Iterator<org.apache.poi.ss.usermodel.Cell> to java.util.Iterator<org.apache.poi.hssf.record.formula.functions.Cell>
</code>```

Could you please help me with this.

答:
You also need this dependency for xssf:

```<code><dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.16</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.16</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml-schemas</artifactId>
  <version>3.7</version>
</dependency>
</code>```

If you don't get compile errors now it means you have this dependency from somewhere else, likely your RiverBoat project exposes an older/incompatible version. So either you need both poi dependencies in this pom, or none (as both may be exposed by RiverBoat).

Body:
Even though I have imported

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

I am getting error at part

Iterator<Cell> cellIterator=row.cellIterator();

Here is my full code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
//import org.apache.poi.hssf.record.formula.functions.Cell;
//import org.apache.poi.hssf.record.formula.functions.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class UploadExcel {

    public static void main(String[] args) {
        try {
            FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));

            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);

            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();

            while (rowIterator.hasNext())
            {
                Row row = rowIterator.next();

                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator=row.cellIterator();

                while (cellIterator.hasNext())
                {
                     Cell cell = cellIterator.next();

                     //Check the cell type and format accordingly
                     switch (cell.getCellType())
                     {
                         case Cell.CELL_TYPE_NUMERIC:
                         System.out.print(cell.getNumericCellValue() + "\t");
                         break;
                         case Cell.CELL_TYPE_STRING:
                         System.out.print(cell.getStringCellValue() + "\t");
                         break;
                     }
                 }

                 System.out.println("");
             }

             file.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
 }

The error which i am getting is:

Type mismatch: cannot convert from java.util.Iterator<org.apache.poi.ss.usermodel.Cell> to java.util.Iterator<org.apache.poi.hssf.record.formula.functions.Cell>

Could you please help me with this.

Body:
You also need this dependency for xssf:

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.16</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.16</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml-schemas</artifactId>
  <version>3.7</version>
</dependency>

If you don't get compile errors now it means you have this dependency from somewhere else, likely your RiverBoat project exposes an older/incompatible version. So either you need both poi dependencies in this pom, or none (as both may be exposed by RiverBoat).


问:
Why does one method for allocating memory fail compared to another that works?
If my intention was to create a dynamically sized array of structs. Could someone explain to me how one method that allocates memory to resize the array works the way it should; compared to one that fails after x number of elements are added to the array?

The following method uses malloc() (incorrectly). Could someone explain how to properly allocate memory to the array?

```<code>struct some_struct{...data members...}*collection = NULL;
    int total_elements;
    int space_allocated; // the number of elements allocated to the array

    void resize_array(){
        if(total_elements == space_allocated) {
            if(space_allocated == 0)
                space_allocated =2;
            else
                space_allocated *= 2;
            //where collection is a pointer to a struct
            collection = malloc(space_allocated * sizeof(struct some_struct));

            if(collection == NULL){
                fprintf(stderr,"NO MEMORY ALLOCATED");
                exit(EXIT_FAILURE);
            }
        }
    }
</code>```

Compared to another method that uses realloc() correctly to dynamically allocate memory for the array. What is the significance of a void* type variable used to hold the memory?

```<code>    void resize_array(){

        if(total_elements == space_allocated){
            if(space_allocated == 0)
                space_allocated = 2;
            else
                space_allocated *= 2;
                //why is a variable of type void allowed? What does that mean?
                void* tmp = realloc(collection, ((num_allocated)*
                sizeof(struct some_struct)));
                if(!_tmp){
                    fprintf(stderr,"NO MEMORY ALLOCATED");
                    exit(EXIT_FAILURE);
                }
                //what is the significance of the pointer cast?
                collection = (some_struct*) _tmp;
        }
    }
</code>```

答:
You should allocate the first initialization with malloc, and resize it with realloc.

When you malloc again in the first way(completely nonsense), the system allocate a NEW memory space and return the address. Now you made one good memory leak.

The second way looks logical, and remember, beside in some compilers, realloc could be used instead of malloc(where reallocating memory is NULL), but you may do the first initialization with malloc and ignore their kindness.

both realloc and malloc return void*, but at the end they all are bytes(char). Since C is well weaked, you may or may not cast the return type to a type(pointer). But in c++, it's diff.

Body:
If my intention was to create a dynamically sized array of structs. Could someone explain to me how one method that allocates memory to resize the array works the way it should; compared to one that fails after x number of elements are added to the array?

The following method uses malloc() (incorrectly). Could someone explain how to properly allocate memory to the array?

struct some_struct{...data members...}*collection = NULL;
    int total_elements;
    int space_allocated; // the number of elements allocated to the array

    void resize_array(){
        if(total_elements == space_allocated) {
            if(space_allocated == 0)
                space_allocated =2;
            else
                space_allocated *= 2;
            //where collection is a pointer to a struct
            collection = malloc(space_allocated * sizeof(struct some_struct));

            if(collection == NULL){
                fprintf(stderr,"NO MEMORY ALLOCATED");
                exit(EXIT_FAILURE);
            }
        }
    }

Compared to another method that uses realloc() correctly to dynamically allocate memory for the array. What is the significance of a void* type variable used to hold the memory?

    void resize_array(){

        if(total_elements == space_allocated){
            if(space_allocated == 0)
                space_allocated = 2;
            else
                space_allocated *= 2;
                //why is a variable of type void allowed? What does that mean?
                void* tmp = realloc(collection, ((num_allocated)*
                sizeof(struct some_struct)));
                if(!_tmp){
                    fprintf(stderr,"NO MEMORY ALLOCATED");
                    exit(EXIT_FAILURE);
                }
                //what is the significance of the pointer cast?
                collection = (some_struct*) _tmp;
        }
    }


答:
Something like this </p>

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_gravity="center_horizontal" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:id="@+id/textView2"
    android:textAlignment="center" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:id="@+id/textView3"
    android:textAlignment="center" />

</LinearLayout>
</code>```

Title: Display textview below imageview and not bottom to the parent

Body:
I'm working on an Android application and I have an issue with how to display an image in a view. My issue is that I want to display an image and two textViews just below my imageView without aligning their bottom to the parent's. See the wireframe below.

My problem is that when the imageView is taking all the height of the relativeLayout, my textViews are hidden below the parents view.

I have tried a lot of things but nothing is satisfaying...
I have tried to put my imageview in a linearLayout and put a weight on it but if my imageView is smaller I have a blank between the imageView and the textView.

It's complicated because each image I load can have a different size and thus I can't fix a default size to it.
Also, my layout is in a viewPager and when I want to have the Height of the view when I instantiate it on my adapter it returns 0. So I can't compute the size of the elements in the view.

Have you any idea how can I make my layout ?

Maybe in a coordinatorLayout to have circular dependencies (but I don't know how to make it) ?

Here a wireframe of what I want to do with my view: image

And here the code of my layout :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_photo_detail"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

    <RelativeLayout
        android:id="@+id/relative_photo_detail_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/relative_photo_detail_bottom_infos">

        <ImageView
            android:id="@+id/photo_detail_full_size"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/placeholder"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"/>

        <TextView
            android:id="@+id/photo_detail_owner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/photo_detail_full_size"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="5dp"
            android:textColor="@color/grey"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relative_photo_detail_bottom_infos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/relative_photo_detail_image"
        android:padding="10dp">

        <ImageView
            android:id="@+id/photo_detail_delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:src="@drawable/delete"/>
    </RelativeLayout>
</RelativeLayout>

Body:
Something like this

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/imageView"
    android:layout_gravity="center_horizontal" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:id="@+id/textView2"
    android:textAlignment="center" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:id="@+id/textView3"
    android:textAlignment="center" />

</LinearLayout>


问:
Does spring-websocket STOMP support SUBSCRIBE id?
The STOMP spec says that SUBSCRIBE MUST have id header.

https://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_id_Header

SUBSCRIBE id Header

Since a single connection can have multiple open subscriptions with a
  server, an id header MUST be included in the frame to uniquely
  identify the subscription. The id header allows the client and server
  to relate subsequent MESSAGE or UNSUBSCRIBE frames to the original
  subscription. Within the same connection, different subscriptions MUST
  use different subscription identifiers.

However, in spring's example https://spring.io/guides/gs/messaging-stomp-websocket/, it doesn't specify an id when subscribing destination.

```<code>function connect() {
    var socket = new SockJS('/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}
</code>```

In spring's API, the SimpMessageSendingOperations.convertAndSendToUser doesn't support an id header explicitly.

My question is how to specify id header when sending a message to client?

答:
I don't think you can use a Subscription ID to send a message to a specific client. Stomp defines this ID and Spring's implementation uses it internally to create messages to every client subscribed to the destination address. Therefore, the Subscription ID is transparent in the Stomp communication... You can specify it in the client side or let Stomp JS (STOMP Over WebSocket) create a unique one.

If you subscribe to a destination prefixed with "/user/" and use org.springframework.messaging.simp.SimpMessagingTemplate#convertAndSendToUser or org.springframework.messaging.simp.annotation.SendToUser to send a message to a single client, what Spring does is register and create a subscription to a  custom session based destination based on the original destination. In another words, from Spring's Javadoc:

When a user attempts to subscribe, e.g. to
  "/user/queue/position-updates", the "/user" prefix is removed and a
  unique suffix added based on the session id, e.g.
  "/queue/position-updates-useri9oqdfzo" to ensure different users can
  subscribe to the same logical destination without colliding.

When sending to a user, e.g.
  "/user/{username}/queue/position-updates", the "/user/{username}"
  prefix is removed and a suffix based on active session id's is added,
  e.g. "/queue/position-updates-useri9oqdfzo".

See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/messaging/simp/user/DefaultUserDestinationResolver.html

See https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-user-destination

EDITED:

You can't use the subscription ID to send a message direct to it's subscribed client, but you can use the client's session ID. According to here, you could use the user's name to send him a message. But you would need authenticated sessions with a Principal on it. Or you can force the destination's session ID in the header of the message, avoiding the internal step to discover it, as shown here.

```<code>private void sendMessageToUser(String destinationSessionId, String message) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(destinationSessionId);
    headerAccessor.setLeaveMutable(true);
    messagingTemplate.convertAndSendToUser(destinationSessionId, "/subscribe/private", message, headerAccessor.getMessageHeaders());
}
</code>```

Doing like this, without a Principal in the session, I couldn't use @SendToUser annotation.

Body:
The STOMP spec says that SUBSCRIBE MUST have id header.

https://stomp.github.io/stomp-specification-1.2.html#SUBSCRIBE_id_Header

SUBSCRIBE id Header

Since a single connection can have multiple open subscriptions with a
  server, an id header MUST be included in the frame to uniquely
  identify the subscription. The id header allows the client and server
  to relate subsequent MESSAGE or UNSUBSCRIBE frames to the original
  subscription. Within the same connection, different subscriptions MUST
  use different subscription identifiers.

However, in spring's example https://spring.io/guides/gs/messaging-stomp-websocket/, it doesn't specify an id when subscribing destination.

function connect() {
    var socket = new SockJS('/gs-guide-websocket');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        setConnected(true);
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/greetings', function (greeting) {
            showGreeting(JSON.parse(greeting.body).content);
        });
    });
}

In spring's API, the SimpMessageSendingOperations.convertAndSendToUser doesn't support an id header explicitly.

My question is how to specify id header when sending a message to client?

Body:
I don't think you can use a Subscription ID to send a message to a specific client. Stomp defines this ID and Spring's implementation uses it internally to create messages to every client subscribed to the destination address. Therefore, the Subscription ID is transparent in the Stomp communication... You can specify it in the client side or let Stomp JS (STOMP Over WebSocket) create a unique one.

If you subscribe to a destination prefixed with "/user/" and use org.springframework.messaging.simp.SimpMessagingTemplate#convertAndSendToUser or org.springframework.messaging.simp.annotation.SendToUser to send a message to a single client, what Spring does is register and create a subscription to a  custom session based destination based on the original destination. In another words, from Spring's Javadoc:

When a user attempts to subscribe, e.g. to
  "/user/queue/position-updates", the "/user" prefix is removed and a
  unique suffix added based on the session id, e.g.
  "/queue/position-updates-useri9oqdfzo" to ensure different users can
  subscribe to the same logical destination without colliding.

When sending to a user, e.g.
  "/user/{username}/queue/position-updates", the "/user/{username}"
  prefix is removed and a suffix based on active session id's is added,
  e.g. "/queue/position-updates-useri9oqdfzo".

See http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/messaging/simp/user/DefaultUserDestinationResolver.html

See https://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-stomp-user-destination

EDITED:

You can't use the subscription ID to send a message direct to it's subscribed client, but you can use the client's session ID. According to here, you could use the user's name to send him a message. But you would need authenticated sessions with a Principal on it. Or you can force the destination's session ID in the header of the message, avoiding the internal step to discover it, as shown here.

private void sendMessageToUser(String destinationSessionId, String message) {
    SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
    headerAccessor.setSessionId(destinationSessionId);
    headerAccessor.setLeaveMutable(true);
    messagingTemplate.convertAndSendToUser(destinationSessionId, "/subscribe/private", message, headerAccessor.getMessageHeaders());
}

Doing like this, without a Principal in the session, I couldn't use @SendToUser annotation.


问:
ElasticSearch fetch child from parent
I want to get all child with value "sales" at some field from parent with some unique id.
this is my query: </p>

```<code>GET /_search
{
"query": {
    "bool": {
        "should": [{
            "query_string": {
                "query": "sales"
            }
        },
        {
            "has_parent": {
                "type": "role_permission_parent",
                "query": {
                    "match": {
                            "resourceURI": "urn:module:com.qad.collaboration"
                    }
                }
            }
        }]
    }
},
"size": 100
}
</code>```

<p>I get a childs from different parents but not from only what I type. Why? And how I fix it? </p>

答:
You must use must condition instead of should:

```<code>GET /_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "query_string": {
                        "query": "sales"
                    }
                },
                {
                    "has_parent": {
                        "type": "role_permission_parent",
                        "query": {
                            "match": {
                                "resourceURI": "urn:module:com.qad.collaboration"
                            }
                        }
                    }
                }
            ]
        }
    },
    "size": 100
}
</code>```

Otherwise it works like "parent match" or "query_string match" instead of "parent match" and "query_string match"

Title: ElasticSearch fetch child from parent

Body:
I want to get all child with value "sales" at some field from parent with some unique id.
this is my query:

GET /_search
{
"query": {
    "bool": {
        "should": [{
            "query_string": {
                "query": "sales"
            }
        },
        {
            "has_parent": {
                "type": "role_permission_parent",
                "query": {
                    "match": {
                            "resourceURI": "urn:module:com.qad.collaboration"
                    }
                }
            }
        }]
    }
},
"size": 100
}

I get a childs from different parents but not from only what I type. Why? And how I fix it?

Body:
You must use must condition instead of should:

GET /_search
{
    "query": {
        "bool": {
            "must": [
                {
                    "query_string": {
                        "query": "sales"
                    }
                },
                {
                    "has_parent": {
                        "type": "role_permission_parent",
                        "query": {
                            "match": {
                                "resourceURI": "urn:module:com.qad.collaboration"
                            }
                        }
                    }
                }
            ]
        }
    },
    "size": 100
}

Otherwise it works like "parent match" or "query_string match" instead of "parent match" and "query_string match"


问:
Issue with member function declaration in class
I have been battling with an issue on Qt for a while now and figured I'd come by here to see if anyone had any solutions.

I've created a GUI using the QT tools and have programmed all of the functions for each respective thing. However, I can't seem to successfully rectify the following issue:

C:\Python34\2SprayCoater\mainwindow.cpp:11: error: no 'int
  mainwindow::MainWindow(QWidget*)' member function declared in class
  'mainwindow'  mainwindow::MainWindow(QWidget
  *parent):QMainWindow(parent)

The part of code from the library in question is:

```<code>#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class mainwindow : public QMainWindow
{
    Q_OBJECT

    public:
    explicit mainwindow(QWidget *parent = 0);
    ~mainwindow();
</code>```

And the reference to this code in the cpp file is:

```<code>#include "mainwindow.h"
#include <QApplication>

#include "main.cpp"
#include <QtSerialPort/QSerialPort>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>

mainwindow::MainWindow(QWidget *parent):QMainWindow(parent)

{
    ui.setupUi(this);
}
</code>```

I tried to fix this by simply changing explicit

mainwindow(QWidget *parent = 0);

in the header file to

explicit mainwindow(QWidget *parent = 0):QMainWindow(parent);

Which just ends up creating a slough of different issues, but fixes the original. What am I missing? Thanks in advance.

答:
The problem is generated because you removed some necessary headers, for example:

```<code>#include "ui_mainwindow.h"
</code>```

This is generated by the .ui file, ie the design is converted to code before compiling it. The ui attribute needs that file, also ui is a pointer so to access its methods you must use ->. You must change:

```<code>ui.setupUi(this);
</code>```

to

```<code>ui->setupUi(this);
</code>```

Another serious problem is that you have renamed mainwindow to MainWindow in the constructor.

```<code>explicit mainwindow(QWidget *parent = 0);

mainwindow::MainWindow(QWidget *parent):QMainWindow(parent)
            [here]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been battling with an issue on Qt for a while now and figured I'd come by here to see if anyone had any solutions.

I've created a GUI using the QT tools and have programmed all of the functions for each respective thing. However, I can't seem to successfully rectify the following issue:

C:\Python34\2SprayCoater\mainwindow.cpp:11: error: no 'int
  mainwindow::MainWindow(QWidget*)' member function declared in class
  'mainwindow'  mainwindow::MainWindow(QWidget
  *parent):QMainWindow(parent)

The part of code from the library in question is:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class mainwindow : public QMainWindow
{
    Q_OBJECT

    public:
    explicit mainwindow(QWidget *parent = 0);
    ~mainwindow();

And the reference to this code in the cpp file is:

#include "mainwindow.h"
#include <QApplication>

#include "main.cpp"
#include <QtSerialPort/QSerialPort>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>

mainwindow::MainWindow(QWidget *parent):QMainWindow(parent)

{
    ui.setupUi(this);
}

I tried to fix this by simply changing explicit

mainwindow(QWidget *parent = 0);

in the header file to

explicit mainwindow(QWidget *parent = 0):QMainWindow(parent);

Which just ends up creating a slough of different issues, but fixes the original. What am I missing? Thanks in advance.

Body:
The problem is generated because you removed some necessary headers, for example:

#include "ui_mainwindow.h"

This is generated by the .ui file, ie the design is converted to code before compiling it. The ui attribute needs that file, also ui is a pointer so to access its methods you must use ->. You must change:

ui.setupUi(this);

to

ui->setupUi(this);

Another serious problem is that you have renamed mainwindow to MainWindow in the constructor.

explicit mainwindow(QWidget *parent = 0);

mainwindow::MainWindow(QWidget *parent):QMainWindow(parent)
            [here]


问:
Displaying errors for rails has_many through associations
I have the following class:

class Person < ApplicationRecord
  validates :name, presence: true

  has_many :parenthoods
  has_many :children, through: :parenthoods, index_errors: true

  has_many :childhoods, class_name: 'Parenthood', foreign_key: 'child_id'
  has_many :parents, through: :childhoods, source: :person
end
```

<p>With an explicit join-table model:</p>

<pre class="lang-rb prettyprint-override"><code>class Parenthood < ApplicationRecord
  belongs_to :person
  belongs_to :child, class_name: 'Person'
  validate :parent_can_not_be_child
  private
    def parent_can_not_be_child
      errors.add(:person, "child can not be parent") if person_id == child_id
    end
end
</code>```

I would prefer to keep working with a has_many :through as opposed to a habtm if possible. And it seemed to the most reasonable way to create the association. The update action in the controller is pretty straight forward:

def update
  @person = current_user.people.find(params[:id])
  if @person.update_attributes(person_params)
    redirect_to @person
  else
    render action: 'edit'
  end
end
```

<p>And in the view I have (HAML, but it seems pretty clear in its intent)</p>

```-if @person.errors.any?
  = @person.errors.full_messages.first
```

The update action has the following behaviours:

Input is all OK: Works as intended ✔

Name validation fails: Shows a validation error in the form template as you would expect ✔

Try to make somebody their own child: Instead of showing the validation error on the form it, I instead get the 500 error page with this error:

ActiveRecord::RecordInvalid in PeopleController#update

Validation failed: Person child can not be parent

I'm sure there is an easy way to handle this in rails but I just seem to be going around in circles at the moment, any help appreciated lots!

答:
Try to make somebody their own child: Instead of showing the
  validation error on the form it, I instead get the 500 error page with
  this error:

ActiveRecord::RecordInvalid in PeopleController#update Validation
  failed: Person child can not be parent

You have = @person.errors.full_messages.first which means it always shows only first error message. You should instead loop through it to show all error messages on the form

```<code>- @person.errors.full_messages.each do |msg|
  = msg
</code>```

Update:

add(attribute, message = :invalid, options = {}) public

As @gabrielhilal mentioned in the comments, the first parameter of the add should be an attribute. So change :person to :person_id

```<code>def parent_can_not_be_child
  errors.add(:person_id, "child can not be parent") if person_id == child_id
end
</code>```

And add validates_associated :parenthoods to Person model to show up that validation error in the list of @person.errors

Body:
I have the following class:

class Person < ApplicationRecord
  validates :name, presence: true

  has_many :parenthoods
  has_many :children, through: :parenthoods, index_errors: true

  has_many :childhoods, class_name: 'Parenthood', foreign_key: 'child_id'
  has_many :parents, through: :childhoods, source: :person
end

With an explicit join-table model:

class Parenthood < ApplicationRecord
  belongs_to :person
  belongs_to :child, class_name: 'Person'
  validate :parent_can_not_be_child
  private
    def parent_can_not_be_child
      errors.add(:person, "child can not be parent") if person_id == child_id
    end
end

I would prefer to keep working with a has_many :through as opposed to a habtm if possible. And it seemed to the most reasonable way to create the association. The update action in the controller is pretty straight forward:

def update
  @person = current_user.people.find(params[:id])
  if @person.update_attributes(person_params)
    redirect_to @person
  else
    render action: 'edit'
  end
end

And in the view I have (HAML, but it seems pretty clear in its intent)

-if @person.errors.any?
  = @person.errors.full_messages.first

The update action has the following behaviours:

Input is all OK: Works as intended ✔

Name validation fails: Shows a validation error in the form template as you would expect ✔

Try to make somebody their own child: Instead of showing the validation error on the form it, I instead get the 500 error page with this error:

ActiveRecord::RecordInvalid in PeopleController#update

Validation failed: Person child can not be parent

I'm sure there is an easy way to handle this in rails but I just seem to be going around in circles at the moment, any help appreciated lots!

Body:
Try to make somebody their own child: Instead of showing the
  validation error on the form it, I instead get the 500 error page with
  this error:

ActiveRecord::RecordInvalid in PeopleController#update Validation
  failed: Person child can not be parent

You have = @person.errors.full_messages.first which means it always shows only first error message. You should instead loop through it to show all error messages on the form

- @person.errors.full_messages.each do |msg|
  = msg

Update:

add(attribute, message = :invalid, options = {}) public

As @gabrielhilal mentioned in the comments, the first parameter of the add should be an attribute. So change :person to :person_id

def parent_can_not_be_child
  errors.add(:person_id, "child can not be parent") if person_id == child_id
end

And add validates_associated :parenthoods to Person model to show up that validation error in the list of @person.errors


问:
Why I can get subroutine address before it is declared without error?
I have next program:

```<code>use warnings;
use strict;

BEGIN {
    print \&mysub;
}

sub mysub {};

print \&mysub;
</code>```

Its output:

```<code>CODE(0x118e890)CODE(0x118e890)
</code>```

The BEGIN block is processed in compile time. At that point definition of sub mysub is not seen by compiler yet. But program still prints right subroutine address, which it will have when defined.

Why I do not get error here? Is this some sort of autovivification?

答:
Yes, this is a form of autovivification. A stub is created when a reference to the sub is required and the sub doesn't exist.

```<code>use strict;
use warnings qw( all );
use feature qw( say );

sub test {
   say  defined(&mysub) ? "defined (".\&mysub.")"
      : exists(&mysub)  ? "exists (".\&mysub.")"
      :                   "doesn't exist";
}

test();
my $ref = \&mysub;
test();
eval("sub mysub { }  1") or die($@);
test();
</code>```

Output:

```<code>doesn't exist
exists (CODE(0xab8cd8))
defined (CODE(0xab8cd8))
</code>```

Body:
I have next program:

use warnings;
use strict;

BEGIN {
    print \&mysub;
}

sub mysub {};

print \&mysub;

Its output:

CODE(0x118e890)CODE(0x118e890)

The BEGIN block is processed in compile time. At that point definition of sub mysub is not seen by compiler yet. But program still prints right subroutine address, which it will have when defined.

Why I do not get error here? Is this some sort of autovivification?

Body:
Yes, this is a form of autovivification. A stub is created when a reference to the sub is required and the sub doesn't exist.

use strict;
use warnings qw( all );
use feature qw( say );

sub test {
   say  defined(&mysub) ? "defined (".\&mysub.")"
      : exists(&mysub)  ? "exists (".\&mysub.")"
      :                   "doesn't exist";
}

test();
my $ref = \&mysub;
test();
eval("sub mysub { }  1") or die($@);
test();

Output:

doesn't exist
exists (CODE(0xab8cd8))
defined (CODE(0xab8cd8))


问:
Copying files to folder
I have this:

In addMusic.jsp:

```<code><form method="post" action="Handler" enctype="multipart/form-data">
    <div class="form-group">
        <label>Musica:</label>
        <input type="text" class="form-control" name="add_musica_nome" placeholder="Nome Musica">
    </div>
    <div class="form-group">
        <label>Localização:</label>
        <input type="file" class="form-control" name="add_musica_path" accept="audio/*">
    </div>
    <div class="form-group">
        <label>Ano:</label>
        <input type="text" class="form-control" name="add_musica_ano" pattern="[0-9]{4,4}">
    </div>
    <div class="form-group">
        <input type="hidden" name="logica" id="logica" value="SMusica"/>
        <input  type="hidden" name="acao" id="acao" value="addMusica"/>
        <input class="btn btn-success" type="submit" value="Inserir" name="inserir"/>
    </div>
</form>
</code>```

In Handler:

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String parametro = request.getParameter("logica"); // Recebe como parametro do jsp, qual a class do service que
                                                        // irá atuar
    String nomeDaClasse = "services." + parametro; // Nome da Classe

    try {
        Class<?> classe = Class.forName(nomeDaClasse);
        Logica logica = (Logica) classe.newInstance();

        String pagina = logica.executa(request, response);
        request.getRequestDispatcher(pagina).forward(request, response);

    } catch (Exception e) {
        throw new ServletException("A lógica causou uma exceção", e);
    }
}
</code>```

and in SMusica:

```<code>final String Dest = "/data/";

public void addMusica(String musica_nome, Part musica, String ano) throws IOException {

    String fileName = Paths.get(musica.getSubmittedFileName()).getFileName().toString(); // MSIE fix.

    try {

        File music = new File(fileName);

        System.out.println("Path: " + music.getAbsolutePath());

        if (music.renameTo(new File(Dest + music.getName()))) {
            System.out.println("File is moved successful!");
        } else {
            System.out.println("File is failed to move!");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {

    if (req.getParameter("acao").equals("addMusica")) {
        addMusica(req.getParameter("add_musica_nome"), req.getPart("add_musica_path"),
                req.getParameter("add_musica_ano"));
    }
    return "/index.jsp";
}
</code>```

And i made a print of absolutePath of music(File) and it returns C:\Users\Fabio\Desktop\eclipse\ProfJam_-_Mortalhas.mp3, not the real path.

My question is how can i get the real path of the file?

答:
There is a method in path called

```<code>  Path _rp = p.toRealPath();
</code>```

Maybe you Can search in this direction

Title: Copying files to folder

Body:
I have this:

In addMusic.jsp:

<form method="post" action="Handler" enctype="multipart/form-data">

        Musica:
        <input type="text" class="form-control" name="add_musica_nome" placeholder="Nome Musica">

        Localização:
        <input type="file" class="form-control" name="add_musica_path" accept="audio/*">

        Ano:
        <input type="text" class="form-control" name="add_musica_ano" pattern="[0-9]{4,4}">

        <input type="hidden" name="logica" id="logica" value="SMusica"/>
        <input  type="hidden" name="acao" id="acao" value="addMusica"/>
        <input class="btn btn-success" type="submit" value="Inserir" name="inserir"/>

</form>

In Handler:

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

    String parametro = request.getParameter("logica"); // Recebe como parametro do jsp, qual a class do service que
                                                        // irá atuar
    String nomeDaClasse = "services." + parametro; // Nome da Classe

    try {
        Class<?> classe = Class.forName(nomeDaClasse);
        Logica logica = (Logica) classe.newInstance();

        String pagina = logica.executa(request, response);
        request.getRequestDispatcher(pagina).forward(request, response);

    } catch (Exception e) {
        throw new ServletException("A lógica causou uma exceção", e);
    }
}

and in SMusica:

final String Dest = "/data/";

public void addMusica(String musica_nome, Part musica, String ano) throws IOException {

    String fileName = Paths.get(musica.getSubmittedFileName()).getFileName().toString(); // MSIE fix.

    try {

        File music = new File(fileName);

        System.out.println("Path: " + music.getAbsolutePath());

        if (music.renameTo(new File(Dest + music.getName()))) {
            System.out.println("File is moved successful!");
        } else {
            System.out.println("File is failed to move!");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
public String executa(HttpServletRequest req, HttpServletResponse res) throws Exception {

    if (req.getParameter("acao").equals("addMusica")) {
        addMusica(req.getParameter("add_musica_nome"), req.getPart("add_musica_path"),
                req.getParameter("add_musica_ano"));
    }
    return "/index.jsp";
}

And i made a print of absolutePath of music(File) and it returns C:\Users\Fabio\Desktop\eclipse\ProfJam_-_Mortalhas.mp3, not the real path.

My question is how can i get the real path of the file?

Body:
There is a method in path called

  Path _rp = p.toRealPath();

Maybe you Can search in this direction