问:
Sending null parameters from Angular controller cause unreachable function
I have AngularCtrl where I receive a parameter, if it comes null, it just dont execute function:

HTML:

```<code><button type="submit" class="btn blue" ng-click="insertar();">Accept</button>
</code>```

Angular controller

```<code>    $scope.catalogoPadre = $stateParams.catalogopadre;

        if ($scope.catalogoPadre != null) {
            cargarCatalogo();
        }

        function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];
                   inicial
                   $scope.filtro($scope.selected);
               }, errorCatalogo);
</code>```

As you can see cargarCatalogo is a simple query that populates a select

Problem is when I try to execute insertar function (that is into ng-click of view), when I send all parameters, including $scope.selected.ID that I get into cargarCatalogo() function it runs correctly, but if I want to execute it without  $scope.selected.ID it don´t reach insertar function when I debbug chrome console.

Angular Controller second part

```<code>            $scope.filtro = function (selected) {

                $scope.selectedID = selected.ID;

                $scope.insertar = insertar;

                function insertar() {

                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url , null,
                            function (response) {
                                bootbox.alert("Operación Exitosa!");
                                $state.go("root.catalogosgenericos");
                            },
                            function (response) {

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

What can be wrong there? why  $scope.insertar = insertar; ´dont execute if I dont send all paramters if I have a validation

```<code> if ($scope.selected.ID != null) {
         url = url + "/" + $scope.selected.ID;
            }
</code>```

Regards

Update:

I change code as alphapilgrim comment but it still dont fire insertar action when $scope.selected.ID comes null

Code:

```<code> function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                 .
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];

                   $scope.filtro($scope.selected);
               }, errorCatalogo);

            $scope.filtro = function (selected) {
                $scope.selectedID = selected.ID;

                $scope.insertar = function() {
                    $scope.selectedID = selected.ID;
                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url, null,
                          function(response) {
                              bootbox.alert("Operación Exitosa!");
                              $state.go("root.catalogosgenericos");
                          },
                          function(response) {
                              if (response.status == "500") {
                                  window.location = "/";
                              } else {
                                  bootbox.alert(response.status + " " + response.statusText + "<br/>" + response.data.errores);
                              }
                          });
                      }
</code>```

Entire HTML

```<code><div class="page-head">
  <div class="page-title">
    <h1>
                Catálogos Genéricos
                <small>Nuevo Registro de: {{tipoCatalogo}}</small>
            </h1>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <!-- BEGIN Portlet PORTLET-->
    <div class="portlet box blue">
      <div class="portlet-title">
        <div class="caption">
          Catálogos
        </div>
        <div class="tools">
          <a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
          <!-- <a href="javascript:;" class="reload" data-original-title="" title=""> </a>-->
          <a href="javascript:;" class="fullscreen" data-original-title="" title=""> </a>
        </div>
      </div>
      <div class="portlet-body">
        <!-- PITE - INICIA TABS -->
        <div class="row">
          <div class="col-md-12">
            <!-- BEGIN Portlet PORTLET-->
            <div class="portlet box red">
              <div class="portlet-title">
                <div class="caption" id="tab_titulo">
                  Nuevo registro de: {{tipoCatalogo}}
                </div>
                <div class="tools">
                  <a href="javascript:;" class="collapse"> </a>
                  <a href="javascript:;" class="reload" ng-click="fill(conductor.ID); actualizardoctos();"> </a>
                  <a href="javascript:;" class="fullscreen"> </a>
                </div>
              </div>
              <div class="portlet-body">
                <div class="tab-content">
                  <div class="tab-pane fade active in" id="tab_2_1">

                    <div class="form-group">
                      <form id="detalle" name="detalle">
                        <div class="row">
                          <div class="col-xs-12 col-sm-6 col-md-4">
                            <div class="form-group">
                              <label> Código: </label>
                              <input type="text" class="form-control" id="Codigo" name="Codigo" ng-model="Codigo" maxlength="3" required/>
                              <span ng-show="detalle.Codigo.$error.maxlength || detalle.Codigo.length" class="required">El Código debe contener 3 caracteres</span>
                            </div>
                          </div>
                          <div class="col-xs-12 col-sm-6 col-md-4">
                            <div class="form-group">
                              <label> Nombre: </label>
                              <input type="text" class="form-control" id="Nombre" name="Nombre" ng-model="Nombre" maxlength="255" required />
                            </div>
                          </div>
                          <div class="col-xs-12 col-sm-4 col-md-4">
                            <div class="form-group" ng-init="cargarCatalogo()">
                              <label ng-hide="Catalogos.length==0">Catalogo Padre: </label>

                              <select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
                              <br />
                            </div>
                          </div>
                        </div>

                        <hr width="100%" style="color: #2F353B;">
                        <div class="form-actions">
                          <div class="row">
                            <div class="text-right col-md-12">
                              <button type="submit" class="btn blue" ng-click="insertar();">Aceptar</button>
                              <button type="button" class="btn default" ng-click="regresar();">Cancelar</button>
                            </div>
                          </div>
                        </div>
                      </form>
                    </div>

                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div ui-view> </div>
</code>```

答:
You can leave the button as is, and change insetar function to a scoped function. This should get you going. This should fire the function now, then you'll just need to tweak it to whatever is missing.

$scope.insertar = function() {
  $scope.selectedID = selected.ID;
  if ($scope.catalogoid != null) {
    var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
    if ($scope.selected.ID != null) {
      url = url + "/" + $scope.selected.ID;
    }
    apiService.post(url, null,
      function(response) {
        bootbox.alert("Operación Exitosa!");
        $state.go("root.catalogosgenericos");
      },
      function(response) {

      }
    });
};
```

Body:
I have AngularCtrl where I receive a parameter, if it comes null, it just dont execute function:

HTML:

<button type="submit" class="btn blue" ng-click="insertar();">Accept</button>

Angular controller

    $scope.catalogoPadre = $stateParams.catalogopadre;

        if ($scope.catalogoPadre != null) {
            cargarCatalogo();
        }

        function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];
                   inicial
                   $scope.filtro($scope.selected);
               }, errorCatalogo);

As you can see cargarCatalogo is a simple query that populates a select

Problem is when I try to execute insertar function (that is into ng-click of view), when I send all parameters, including $scope.selected.ID that I get into cargarCatalogo() function it runs correctly, but if I want to execute it without  $scope.selected.ID it don´t reach insertar function when I debbug chrome console.

Angular Controller second part

            $scope.filtro = function (selected) {

                $scope.selectedID = selected.ID;

                $scope.insertar = insertar;

                function insertar() {

                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url , null,
                            function (response) {
                                bootbox.alert("Operación Exitosa!");
                                $state.go("root.catalogosgenericos");
                            },
                            function (response) {

                                }
                            });
                    }

What can be wrong there? why  $scope.insertar = insertar; ´dont execute if I dont send all paramters if I have a validation

 if ($scope.selected.ID != null) {
         url = url + "/" + $scope.selected.ID;
            }

Regards

Update:

I change code as alphapilgrim comment but it still dont fire insertar action when $scope.selected.ID comes null

Code:

 function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                 .
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];

                   $scope.filtro($scope.selected);
               }, errorCatalogo);

            $scope.filtro = function (selected) {
                $scope.selectedID = selected.ID;

                $scope.insertar = function() {
                    $scope.selectedID = selected.ID;
                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url, null,
                          function(response) {
                              bootbox.alert("Operación Exitosa!");
                              $state.go("root.catalogosgenericos");
                          },
                          function(response) {
                              if (response.status == "500") {
                                  window.location = "/";
                              } else {
                                  bootbox.alert(response.status + " " + response.statusText + "
" + response.data.errores);
                              }
                          });
                      }

Entire HTML

                Catálogos Genéricos
                Nuevo Registro de: {{tipoCatalogo}}

          Catálogos

                  Nuevo registro de: {{tipoCatalogo}}

                      <form id="detalle" name="detalle">

                               Código:
                              <input type="text" class="form-control" id="Codigo" name="Codigo" ng-model="Codigo" maxlength="3" required/>
                              El Código debe contener 3 caracteres

                               Nombre:
                              <input type="text" class="form-control" id="Nombre" name="Nombre" ng-model="Nombre" maxlength="255" required />

                              Catalogo Padre:

                              <select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

                              <button type="submit" class="btn blue" ng-click="insertar();">Aceptar</button>
                              <button type="button" class="btn default" ng-click="regresar();">Cancelar</button>

                      </form>


来源: stackexchange

问:
SourceTree/Git Wants to Re-Add All Files
I apologize if this question has already been answered, but, I can't be sure any solutions line up exactly.

Anyway, I've been humming along for months now just fine using SourceTree with a Bitbucket account.  Now, all of a sudden, when I make a change and SourceTree picks it up, it actually wants to to "re-add" every single file in the project, from .gitignore to the .project file to all the source files and everything in between (I mean "re-add" as in "there's a green circle with a plus in it" in SourceTree).

Needless to say this has me a bit freaked out and while I'm relatively comfortable using Git, I don't want to chance anything here.

Anyone have any ideas?  I didn't do anything out of the ordinary (as far as I know) between the last change and this new change.

Thanks in advance.

答:
Based on my experience with the exact same issue, the solution is to back up your entire repo by copying it somewhere safe, cloning the last 'good' commit from the origin into your working project directory, then adding changed files in incrementally, and committing as-needed until you get back to where you need to be. Based on the solution here:
https://xkcd.com/1597/</p>

ContentLicense: CC BY-SA 3.0


问:
How to add new created page url to modified django-oscar
I'm a beginner in django-oscar and I try to manage a new view on the page.

I've already created two pages with django-oscar dashboard,

https://ibb.co/cM9r0v

and made new buttons in the templates:

Lib/site-packages/oscar/templates/oscar/partials/nav_primary.html

https://gist.github.com/Kalinar/076fc8144869c3b50fc0bc9e52f825e4

I have no idea how to make a good a href="???" to new pages in buttons ... can someone help?
Maybe there is better way to do it, can you explain it to me?

答:
Oscar uses Django's flatpages app, so you can use their template tags to dynamically add in navigation links to the pages you create.

```<code>{% load flatpages %}
{% get_flatpages as flatpages %}

{% for page in flatpages %}
<li class="dropdown active">
    <a href="{{ page.url }}" class="dropdown-toggle" {% if not expand_dropdown %} data-toggle="dropdown"{% endif %}>
        {% trans page.title %}
    </a>
</li>
{% endfor %}
</code>```

You can find more information on the flatpages app in the Django flatpage documentation.

Body:
Oscar uses Django's flatpages app, so you can use their template tags to dynamically add in navigation links to the pages you create.

{% load flatpages %}
{% get_flatpages as flatpages %}

{% for page in flatpages %}
<li class="dropdown active">
    <a href="{{ page.url }}" class="dropdown-toggle" {% if not expand_dropdown %} data-toggle="dropdown"{% endif %}>
        {% trans page.title %}
    </a>
</li>
{% endfor %}

You can find more information on the flatpages app in the Django flatpage documentation.


问:
Destroy action in RSpec test not returning success
I have a Rails 5 application that creates and destroys "csstests." I am attempting to write a test for the controllers destroy action. Here is the action:

```<code>def destroy
    @test = Csstest.find(params[:id])
    if @test.destroy
        flash.now[:success] = "Your test was removed"
        redirect_to csstests_path
    end
end
</code>```

Here is the RSpec test:

```<code>describe 'DELETE #destroy' do

    before do
        test1, test2 = Csstest.create, Csstest.create
        delete :destroy, params: { id: test1.id }
    end

    it 'returns HTTP success' do
        expect(response).to be_success
        expect(response).to return_http_status(200)
    end

end
</code>```

This is the message I get from the failure:

```<code>1) CsstestsController DELETE #destroy returns HTTP success
 Failure/Error: expect(response).to be_success
   expected `#<ActionDispatch::TestResponse:0x007fb1362beb68 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mu...spatch::Http::Headers:0x007fb1362de4b8 @req=#<ActionController::TestRequest:0x007fb1362becf8 ...>>>>.success?` to return true, got false
</code>```

答:
Read up on the basics of HTTP codes - in particular:

2xx responses are "success" status codes.

3xx responses are "redirection" status codes.

In your controller, you have chosen to perform a redirect if the Csstest record is deleted: redirect_to csstests_path.

If this is truly the desired behaviour, then you could update your rspec test to expect this:

```<code>expect(response).to redirect_to(csstests_path)
# This second assertion is probably not really necessary
# But I'll leave it here for completion...
expect(response).to return_http_status(302)
</code>```

It is also possible to explicitly return 301 or 303 status codes for the redirect (see the documentation). But again, these will not be considered "success" codes.

Body:
I have a Rails 5 application that creates and destroys "csstests." I am attempting to write a test for the controllers destroy action. Here is the action:

def destroy
    @test = Csstest.find(params[:id])
    if @test.destroy
        flash.now[:success] = "Your test was removed"
        redirect_to csstests_path
    end
end

Here is the RSpec test:

describe 'DELETE #destroy' do

    before do
        test1, test2 = Csstest.create, Csstest.create
        delete :destroy, params: { id: test1.id }
    end

    it 'returns HTTP success' do
        expect(response).to be_success
        expect(response).to return_http_status(200)
    end

end

This is the message I get from the failure:

1) CsstestsController DELETE #destroy returns HTTP success
 Failure/Error: expect(response).to be_success
   expected `#<ActionDispatch::TestResponse:0x007fb1362beb68 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mu...spatch::Http::Headers:0x007fb1362de4b8 @req=#<ActionController::TestRequest:0x007fb1362becf8 ...>>>>.success?` to return true, got false

Body:
Read up on the basics of HTTP codes - in particular:

2xx responses are "success" status codes.

3xx responses are "redirection" status codes.

In your controller, you have chosen to perform a redirect if the Csstest record is deleted: redirect_to csstests_path.

If this is truly the desired behaviour, then you could update your rspec test to expect this:

expect(response).to redirect_to(csstests_path)
# This second assertion is probably not really necessary
# But I'll leave it here for completion...
expect(response).to return_http_status(302)

It is also possible to explicitly return 301 or 303 status codes for the redirect (see the documentation). But again, these will not be considered "success" codes.


问:
pairwise distance fails on a sparse matrix with an uninformative error message
```<code>from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from scipy.spatial import distance

X = CountVectorizer().fit_transform(docs)
X = TfidfTransformer(use_idf=False).fit_transform(X)
print (X.shape) #prints (100, 1760)
</code>```

However when I try to calculate the pair-distance I get this error:

```<code>distance.pdist(X, metric='cosine')
</code>```

ValueError: A 2-dimensional array must be passed.

The shape indicates that X is a 2-dimensional array, what could be the issue ?

=====Update July 6th 2017======

This is a bug in scipy, sklearn has the correct implementation for sparse matrices.

I have proposed a code-change to the scipy repository here:

https://github.com/scipy/scipy/pull/7566

=====Update Feb 23rd 2018======

If you got here, you probably encountered that issue as well.

It's been more than 8 months since a one-line fix I proposed was pushed to the scipy repository.

Please comment here or here, to get some attention from the scipy maintainers.

答:
pdist starts with:

```<code>def pdist(X, metric='euclidean', p=2, w=None, V=None, VI=None):
    ....
    X = np.asarray(X, order='c')

    # The C code doesn't do striding.
    X = _copy_array_if_base_present(X)

    s = X.shape
    if len(s) != 2:
        raise ValueError('A 2-dimensional array must be passed.')
</code>```

But if I make a scipy.sparse matrix, and apply asarray I don't get a 2d array:

```<code>In [258]: from scipy import sparse
In [259]: M = sparse.random(100,100, format='csr')
In [260]: M
Out[260]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>
In [263]: np.asarray(M)
Out[263]:
array(<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>, dtype=object)
In [264]: _.shape
Out[264]: ()
</code>```

pdist is not designed to accept a sparse matrix.  A sparse matrix is not a subclass of ndarray.  You have to make it dense first.

```<code>In [266]: np.asarray(M.toarray()).shape
Out[266]: (100, 100)
</code>```

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html

Body:
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from scipy.spatial import distance

X = CountVectorizer().fit_transform(docs)
X = TfidfTransformer(use_idf=False).fit_transform(X)
print (X.shape) #prints (100, 1760)

However when I try to calculate the pair-distance I get this error:

distance.pdist(X, metric='cosine')

ValueError: A 2-dimensional array must be passed.

The shape indicates that X is a 2-dimensional array, what could be the issue ?

=====Update July 6th 2017======

This is a bug in scipy, sklearn has the correct implementation for sparse matrices.

I have proposed a code-change to the scipy repository here:

https://github.com/scipy/scipy/pull/7566

=====Update Feb 23rd 2018======

If you got here, you probably encountered that issue as well.

It's been more than 8 months since a one-line fix I proposed was pushed to the scipy repository.

Please comment here or here, to get some attention from the scipy maintainers.

Body:
pdist starts with:

def pdist(X, metric='euclidean', p=2, w=None, V=None, VI=None):
    ....
    X = np.asarray(X, order='c')

    # The C code doesn't do striding.
    X = _copy_array_if_base_present(X)

    s = X.shape
    if len(s) != 2:
        raise ValueError('A 2-dimensional array must be passed.')

But if I make a scipy.sparse matrix, and apply asarray I don't get a 2d array:

In [258]: from scipy import sparse
In [259]: M = sparse.random(100,100, format='csr')
In [260]: M
Out[260]:
<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>
In [263]: np.asarray(M)
Out[263]:
array(<100x100 sparse matrix of type '<class 'numpy.float64'>'
    with 100 stored elements in Compressed Sparse Row format>, dtype=object)
In [264]: _.shape
Out[264]: ()

pdist is not designed to accept a sparse matrix.  A sparse matrix is not a subclass of ndarray.  You have to make it dense first.

In [266]: np.asarray(M.toarray()).shape
Out[266]: (100, 100)

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html


问:
Session issue with unset() and the browser back button
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.

Pseudo code:

```<code>// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();

... more code here

// After insert
unset($_SESSION['next_id']);
</code>```

My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?

EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???

EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.

If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.

答:
Can't imagine a scenario where you would need to store nextId() in session to be used on a next page.

As webbiedave pointed out - $_SESSION is stored on a server, so no - hitting back button will not "reset" the session variable.

But, if user hits refresh on a second page (the one that cleared the _SESSION variable) your script will be launched again, with next_id set to null (because it is set to nextId() on a previous page)

The same will happen if a user hits the back button and the previous page will be loaded from browser cache - no request to a server, no next_id variable in a _SESSION.

But still, there is something really wrong if you store nextId() in a _SESSION.

ContentLicense: CC BY-SA 2.5

Body:
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.

Pseudo code:

// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();

... more code here

// After insert
unset($_SESSION['next_id']);

My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?

EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???

EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.

If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.


问:
List.JS - Cannot read property 'childNodes' of undefined
I cannot seem to figure this out. I've already tried $(document).ready and still doesn't work for me. I've also tried making a for loop specifically for these two value names to save the results to a var and pass it in that way. I've also tried putting the input with the class and id with search inside of the parent div and outside. Essentially like it in the nav bar. Using list.js & knockout.js btw. Im getting my venues using an ajax request using foursquares api.

JS:

```<code>        var options = {
        valueNames: ['name', 'category']
    };

    var userList = new List('search', options);
</code>```

HTML:

```<code><body>
<nav>
    <h1 class="formattedH1">Downtown SA,TX</h1>
    <span>
      <input type="search" placeholder="Search" class="search" id="search">
      <input type="button" class="sort searchButton" value="List"></input>
    </span>
</nav>
<div id="map" class="map"></div>
<div class="list">
    <input type="search" placeholder="Search" class="search" id="search">
    <h1>My Top 5</h1>
    <!-- Square card -->
    <div class="card" id="favViewModel" data-bind="foreach: favList">
        <div class="expand">
            <h2 class="venueName" data-bind="text:name"></h2>
        </div>
        <div class="cardSupport" data-bind="attr: {src: image()}">
        </div>
        <div class="cardSupport" data-bind="text:address">
        </div>
        <a data-bind="attr: {href: website()}">Website</a>
    </div>
    <h1>Foursquare Recommended</h1>
    <div class="card" id="recViewModel" data-bind="foreach: recommendedSpotList  ">
        <div class="expand">
            <h2 class="venueName" data-bind="text:name"></h2>
        </div>
        <div class="cardSupport" data-bind="text:location">
        </div>
        <div class="cardSupport" data-bind="text:category">
        </div>
        <div class="cardSupport" data-bind="text:rating">
        </div>
    </div>
    <script src="js/tester123.js"></script>
</code>```

答:
I fixed the same problem with some comments on the github page of the project, just make sure to have the same names as the examples and it will work, everything must be in a
 and the ul must have the class list

Like this

```<code><div id="hacker-list">
   <ul class="list"></ul>
</div>
</code>```

Link: https://github.com/javve/list.js/issues/9

Body:
I cannot seem to figure this out. I've already tried $(document).ready and still doesn't work for me. I've also tried making a for loop specifically for these two value names to save the results to a var and pass it in that way. I've also tried putting the input with the class and id with search inside of the parent div and outside. Essentially like it in the nav bar. Using list.js & knockout.js btw. Im getting my venues using an ajax request using foursquares api.

JS:

        var options = {
        valueNames: ['name', 'category']
    };

    var userList = new List('search', options);

HTML:

Downtown SA,TX

      <input type="search" placeholder="Search" class="search" id="search">
      <input type="button" class="sort searchButton" value="List"></input>

    <input type="search" placeholder="Search" class="search" id="search">

My Top 5

        Website

Foursquare Recommended

Body:
I fixed the same problem with some comments on the github page of the project, just make sure to have the same names as the examples and it will work, everything must be in a <div> and the ul must have the class list

Like this

<div id="hacker-list">
   <ul class="list"></ul>
</div>

Link: https://github.com/javve/list.js/issues/9


问:
U-SQL Job Failing in Data Factory
I keep getting following error from Data Factory whenever I run an U-SQL Job

```<code>Job submission failed, the user 'adla account name' does not have permissions to a subfolder in the /system/ path needed by Data Lake Analytics. Please run “Add User Wizard” from the Data Lake Analytics Azure Portal or use Azure PowerShell to grant access for the user to the /system/ and its children on the Data Lake Store.
</code>```

And I am not using any Firewall as suggested in this post:

Run U-SQL Script from C# code with Azure Data Factory

I am using the Azure Data Lake Store service principal authentication. When I start the Job from Visual Studio, it also works fine.

I would be grateful for any idea...

thanks

答:
It does sound like a permissions problem. You can run this powershell script to ensure you have applied the proper permissions to the security principal:

```<code>Login-AzureRmAccount
$appname = “adla”
$dataLakeStoreName = “yourdatalakename”

$app = Get-AzureRmADApplication -DisplayName $appname

$servicePrincipal = Get-AzureRmADServicePrincipal  -SearchString $appname

Set-AzureRmDataLakeStoreItemAclEntry -AccountName $dataLakeStoreName -Path / -AceType User -Id $servicePrincipal.Id -Permissions All

Set-AzureRmDataLakeStoreItemAclEntry -AccountName $dataLakeStoreName -Path /system -AceType User -Id $servicePrincipal.Id -Permissions All
</code>```

If you want to create everything from scratch using a powershell script, here is a blog that will help you:

http://dyor.com/setting-up-an-azure-data-lake-and-azure-data-factory-using-powershell/

Title: U-SQL Job Failing in Data Factory

Body:
I keep getting following error from Data Factory whenever I run an U-SQL Job

Job submission failed, the user 'adla account name' does not have permissions to a subfolder in the /system/ path needed by Data Lake Analytics. Please run “Add User Wizard” from the Data Lake Analytics Azure Portal or use Azure PowerShell to grant access for the user to the /system/ and its children on the Data Lake Store.

And I am not using any Firewall as suggested in this post:

Run U-SQL Script from C# code with Azure Data Factory

I am using the Azure Data Lake Store service principal authentication. When I start the Job from Visual Studio, it also works fine.

I would be grateful for any idea...

thanks

Body:
It does sound like a permissions problem. You can run this powershell script to ensure you have applied the proper permissions to the security principal:

Login-AzureRmAccount
$appname = “adla”
$dataLakeStoreName = “yourdatalakename”

$app = Get-AzureRmADApplication -DisplayName $appname

$servicePrincipal = Get-AzureRmADServicePrincipal  -SearchString $appname

Set-AzureRmDataLakeStoreItemAclEntry -AccountName $dataLakeStoreName -Path / -AceType User -Id $servicePrincipal.Id -Permissions All

Set-AzureRmDataLakeStoreItemAclEntry -AccountName $dataLakeStoreName -Path /system -AceType User -Id $servicePrincipal.Id -Permissions All

If you want to create everything from scratch using a powershell script, here is a blog that will help you:

http://dyor.com/setting-up-an-azure-data-lake-and-azure-data-factory-using-powershell/


问:
Prevent traceback in main
In my main.py module, I call a function myFunc() from util.py. In util.py, I handle the exception that myFunc() may throw, and call sys.exit(1). However, I still get a Traceback print in my main.py module. Is there a way to simply catch the exception in util and not have to deal with any output in main, or is it better for me to catch the exception in main rather than in util ?

```<code>def get_token(token_name):

    token_handler = Tokens(token_name)
    try:
        token = token_handler.get()
    except TokenException  as e:
        logging.error("{error}".format(error=e))
        sys.exit(1)

    return token
</code>```

答:
This is a matter of design principle, but the general idea is to catch exceptions only when you know what to do with it.

Swallowing exceptions is not a good idea, because it makes debugging that much harder. Especially when you have critical code written like this with multiple calling points. Exceptions as generated inside the function should be re-thrown/re-raised to be handled by the code that called that function.

For example, you could consider modifying utils.py like this:

```<code>def get_token(token_name):
    token_handler = Tokens(token_name)
    try:
        token = token_handler.get()
    except TokenException  as e:
        # write to some log file if needed
        raise e

    return token
</code>```

Similarly, your main.py would look something like this:

```<code>try:
    token = get_token(token_name)
except TokenException:
    ... # handle TokenException
except Exception:
    ... # handle any other Exception
</code>```

This certainly makes for more robust code since you as the caller have control over the function you call.

Title: Prevent traceback in main

Body:
In my main.py module, I call a function myFunc() from util.py. In util.py, I handle the exception that myFunc() may throw, and call sys.exit(1). However, I still get a Traceback print in my main.py module. Is there a way to simply catch the exception in util and not have to deal with any output in main, or is it better for me to catch the exception in main rather than in util ?

def get_token(token_name):

    token_handler = Tokens(token_name)
    try:
        token = token_handler.get()
    except TokenException  as e:
        logging.error("{error}".format(error=e))
        sys.exit(1)

    return token

Body:
This is a matter of design principle, but the general idea is to catch exceptions only when you know what to do with it.

Swallowing exceptions is not a good idea, because it makes debugging that much harder. Especially when you have critical code written like this with multiple calling points. Exceptions as generated inside the function should be re-thrown/re-raised to be handled by the code that called that function.

For example, you could consider modifying utils.py like this:

def get_token(token_name):
    token_handler = Tokens(token_name)
    try:
        token = token_handler.get()
    except TokenException  as e:
        # write to some log file if needed
        raise e

    return token

Similarly, your main.py would look something like this:

try:
    token = get_token(token_name)
except TokenException:
    ... # handle TokenException
except Exception:
    ... # handle any other Exception

This certainly makes for more robust code since you as the caller have control over the function you call.


问:
Travis-ci needs root privilege when using go test, how to set it?
I have Go test file and it needs root privilege to run it (go test). How to set it in Travis ci?

Here is yml:

```<code>language: go
sudo: required
go:
   - tip
notifications:
  email:
     on_success: change
     on_failure: always
</code>```

After git push, travis-ci build failing with default configure.

答:
script:
  - sudo env "PATH=$PATH" npm test

Body:
I have Go test file and it needs root privilege to run it (go test). How to set it in Travis ci?

Here is yml:

language: go
sudo: required
go:
   - tip
notifications:
  email:
     on_success: change
     on_failure: always

After git push, travis-ci build failing with default configure.


问:
How do I pull project properties in Google Scripts?
I'm currently working on a google script that emails designated users when a project is marked as complete in the associated spreadsheet. The first function triggers when the spreadsheet is edited, and checks column 5 and moves the row if it matches accordingly. The first If statement checks column 5 to see if it matches "Completed" and moves it to the "COMPLETED" sheet if it does. I'm able to have it email a desired user successfully, but I'm also trying to include the first column of the selected row in the email.

This lead me to trying to use project properties as global variables aren't possible in Google Scripts. However, when trying to pull a test property, it breaks the script.

Does anybody know how I might correct my code to be able to push column A to a project property in one function and pull it in a separate function?

The original idea for using project properties was taken from the following thread: How to define global variable in Google Apps Script

Thank you!

```<code>function onEditTrigger(event) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange()

  // Below sends a completed project from the IN PROGRESS sheet to the COMPLETED sheet
  if(s.getName() == "IN PROGRESS" && r.getColumn() == 5 && r.getValue() == "Completed") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("COMPLETED");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    // Send an email when a project is marked complete
    sendEmail();
  }
    // Below sends a completed project from the COMPLETED sheet to the IN PROGRESS sheet
   if(s.getName() == "COMPLETED" && r.getColumn() == 5 && (r.getValue() == "In Development" || r.getValue() == "On Hold" || r.getValue() == "Delayed")) {
    var row2 = r.getRow();
    var numColumns2 = s.getLastColumn();
    var targetSheet2 = ss.getSheetByName("IN PROGRESS");
    var target2 = targetSheet2.getRange(targetSheet2.getLastRow() + 1, 1);
    s.getRange(row2, 1, 1, numColumns2).moveTo(target2);
    s.deleteRow(row2);
  }
}
// Code that establishes desired emails, subject
function sendEmail() {
  var project = PropertiesService.getScriptProperties().getProperty('project');
  var subject = "Learning Solutions project has been completed: " + project;
  var emailAddress = "test@email.com";
  MailApp.sendEmail(emailAddress,subject,"This is a test"
    );
}
</code>```

Screenshot of the current setup for Project Properties

答:
I've attached the code after my adjustments that allows me to dynamically fill the subject of the email I'm sending out based on the first item of the row being moved to the COMPLETED sheet. </p>

```<code>            function onEditTrigger(event) {
              // assumes source data in sheet named Needed
              // target sheet of move to named Acquired
              // test column with yes/no is col 4 or D
              var ss = SpreadsheetApp.getActiveSpreadsheet();
              var s = event.source.getActiveSheet();
              var r = event.source.getActiveRange()

              // Below sends a completed project from the IN PROGRESS sheet to the COMPLETED sheet
              if(s.getName() == "IN PROGRESS" && r.getColumn() == 5 && r.getValue() == "Completed") {
                var row = r.getRow();
                var numColumns = s.getLastColumn();
                var targetSheet = ss.getSheetByName("COMPLETED");
                var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
                //Added below code to pull the first value of the current row and map it to an object in the project properties
                var project = s.getRange(row, 1,row,1).getDisplayValue();
                PropertiesService.getScriptProperties().setProperty('project', project);
                s.getRange(row, 1, 1, numColumns).moveTo(target);
                s.deleteRow(row);
                // Send an email when a project is marked complete
                sendEmail();
              }
                // Below sends a completed project from the COMPLETED sheet to the IN PROGRESS sheet
               if(s.getName() == "COMPLETED" && r.getColumn() == 5 && (r.getValue() == "In Development" || r.getValue() == "On Hold" || r.getValue() == "Delayed")) {
                var row2 = r.getRow();
                var numColumns2 = s.getLastColumn();
                var targetSheet2 = ss.getSheetByName("IN PROGRESS");
                var target2 = targetSheet2.getRange(targetSheet2.getLastRow() + 1, 1);
                s.getRange(row2, 1, 1, numColumns2).moveTo(target2);
                s.deleteRow(row2);
              }
            }
            // Code that establishes desired emails, subject
            function sendEmail() {
           //pulls down the 'project' property established earlier in the previous function and sets it as a variable in the new function
              var project = PropertiesService.getScriptProperties().getProperty('project');
              var subject = "Learning Solutions project has been completed: " + project;
              var emailAddress = "test@email.com";
              MailApp.sendEmail(emailAddress,subject,"This is a test"
                );
            }
</code>```

Body:
I'm currently working on a google script that emails designated users when a project is marked as complete in the associated spreadsheet. The first function triggers when the spreadsheet is edited, and checks column 5 and moves the row if it matches accordingly. The first If statement checks column 5 to see if it matches "Completed" and moves it to the "COMPLETED" sheet if it does. I'm able to have it email a desired user successfully, but I'm also trying to include the first column of the selected row in the email.

This lead me to trying to use project properties as global variables aren't possible in Google Scripts. However, when trying to pull a test property, it breaks the script.

Does anybody know how I might correct my code to be able to push column A to a project property in one function and pull it in a separate function?

The original idea for using project properties was taken from the following thread: How to define global variable in Google Apps Script

Thank you!

function onEditTrigger(event) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = event.source.getActiveSheet();
  var r = event.source.getActiveRange()

  // Below sends a completed project from the IN PROGRESS sheet to the COMPLETED sheet
  if(s.getName() == "IN PROGRESS" && r.getColumn() == 5 && r.getValue() == "Completed") {
    var row = r.getRow();
    var numColumns = s.getLastColumn();
    var targetSheet = ss.getSheetByName("COMPLETED");
    var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
    s.getRange(row, 1, 1, numColumns).moveTo(target);
    s.deleteRow(row);
    // Send an email when a project is marked complete
    sendEmail();
  }
    // Below sends a completed project from the COMPLETED sheet to the IN PROGRESS sheet
   if(s.getName() == "COMPLETED" && r.getColumn() == 5 && (r.getValue() == "In Development" || r.getValue() == "On Hold" || r.getValue() == "Delayed")) {
    var row2 = r.getRow();
    var numColumns2 = s.getLastColumn();
    var targetSheet2 = ss.getSheetByName("IN PROGRESS");
    var target2 = targetSheet2.getRange(targetSheet2.getLastRow() + 1, 1);
    s.getRange(row2, 1, 1, numColumns2).moveTo(target2);
    s.deleteRow(row2);
  }
}
// Code that establishes desired emails, subject
function sendEmail() {
  var project = PropertiesService.getScriptProperties().getProperty('project');
  var subject = "Learning Solutions project has been completed: " + project;
  var emailAddress = "test@email.com";
  MailApp.sendEmail(emailAddress,subject,"This is a test"
    );
}

Screenshot of the current setup for Project Properties

Body:
I've attached the code after my adjustments that allows me to dynamically fill the subject of the email I'm sending out based on the first item of the row being moved to the COMPLETED sheet.

            function onEditTrigger(event) {
              // assumes source data in sheet named Needed
              // target sheet of move to named Acquired
              // test column with yes/no is col 4 or D
              var ss = SpreadsheetApp.getActiveSpreadsheet();
              var s = event.source.getActiveSheet();
              var r = event.source.getActiveRange()

              // Below sends a completed project from the IN PROGRESS sheet to the COMPLETED sheet
              if(s.getName() == "IN PROGRESS" && r.getColumn() == 5 && r.getValue() == "Completed") {
                var row = r.getRow();
                var numColumns = s.getLastColumn();
                var targetSheet = ss.getSheetByName("COMPLETED");
                var target = targetSheet.getRange(targetSheet.getLastRow() + 1, 1);
                //Added below code to pull the first value of the current row and map it to an object in the project properties
                var project = s.getRange(row, 1,row,1).getDisplayValue();
                PropertiesService.getScriptProperties().setProperty('project', project);
                s.getRange(row, 1, 1, numColumns).moveTo(target);
                s.deleteRow(row);
                // Send an email when a project is marked complete
                sendEmail();
              }
                // Below sends a completed project from the COMPLETED sheet to the IN PROGRESS sheet
               if(s.getName() == "COMPLETED" && r.getColumn() == 5 && (r.getValue() == "In Development" || r.getValue() == "On Hold" || r.getValue() == "Delayed")) {
                var row2 = r.getRow();
                var numColumns2 = s.getLastColumn();
                var targetSheet2 = ss.getSheetByName("IN PROGRESS");
                var target2 = targetSheet2.getRange(targetSheet2.getLastRow() + 1, 1);
                s.getRange(row2, 1, 1, numColumns2).moveTo(target2);
                s.deleteRow(row2);
              }
            }
            // Code that establishes desired emails, subject
            function sendEmail() {
           //pulls down the 'project' property established earlier in the previous function and sets it as a variable in the new function
              var project = PropertiesService.getScriptProperties().getProperty('project');
              var subject = "Learning Solutions project has been completed: " + project;
              var emailAddress = "test@email.com";
              MailApp.sendEmail(emailAddress,subject,"This is a test"
                );
            }


问:
Querying with Multiple Listing Numbers in Evernet Soap service
I was trying to fetch data for NWMLS using evernet soap service. Here I have to extract data for Multiple listing Numbers / Listing Ids. But I am getting error response. Below is the  code snipper which I am trying to get specific data.

```<code><!-- language: php -->
$client=new SoapClient('http://evernet.nwmls.com/evernetqueryservice/evernetquery.asmx?WSDL');

$XMLQuery  = "<?xml version='1.0' encoding='utf-8' standalone='no' ?>";
$XMLQuery .="<EverNetQuerySpecification xmlns='urn:www.nwmls.com/Schemas/General/EverNetQueryXML.xsd'>";
    $XMLQuery .="<Message>";
    $XMLQuery .="<Head>";
    $XMLQuery .="<UserId>******</UserId>";
    $XMLQuery .="<Password>******</Password>";
    $XMLQuery .="<SchemaName>StandardXML1_1</SchemaName>";
    $XMLQuery .="</Head>";
    $XMLQuery .="<Body>";
    $XMLQuery .="<Query>";
    $XMLQuery .="<MLS>NWMLS</MLS>";
    $XMLQuery .="<ListingNumber>1045735555</ListingNumber>";
    $XMLQuery .="<ListingNumber>10641974354</ListingNumber>";
    $XMLQuery .="<PropertyType>RESI</PropertyType>";
    $XMLQuery .="</Query>";
    $XMLQuery .="<Filter></Filter>";
    $XMLQuery .="</Body>";
    $XMLQuery .="</Message>";
    $XMLQuery .="</EverNetQuerySpecification>";
    $params = array ('v_strXmlQuery' => $XMLQuery);
    $result = $client->RetrieveListingData($params);
    $access = $result->RetrieveListingDataResult; print_r($access);
   $xml[] = simplexml_load_string($access);
</code>```

The response I am getting from the Soap service is

"

    Element 'urn:www.nwmls.com/Schemas/General/EverNetQueryXML.xsd:ListingNumber' cannot appear more than once if content model type is "all".

"

How to form the query that needs to include multiple listing Numbers so that I will get the exact result ??

Thanks

答:
Per the XSD specification, the "ListingNumber" cannot appear more than once, in the query.
So that's why you're seeing that error.

But how to query for multiple ListingNumbers?
The way I know off the top of my head is to use the "BeginDate" and "EndDate", or "Status", "County", "Area".

Of course, this is not as exact as directly querying those two listing numbers, so you get a range of values in return.

Have you played around with http://evernet.nwmls.com/evernettest/RetrieveListingData.aspx?

Body:
I was trying to fetch data for NWMLS using evernet soap service. Here I have to extract data for Multiple listing Numbers / Listing Ids. But I am getting error response. Below is the  code snipper which I am trying to get specific data.

$client=new SoapClient('http://evernet.nwmls.com/evernetqueryservice/evernetquery.asmx?WSDL');

$XMLQuery  = "<?xml version='1.0' encoding='utf-8' standalone='no' ?>";
$XMLQuery .="<EverNetQuerySpecification xmlns='urn:www.nwmls.com/Schemas/General/EverNetQueryXML.xsd'>";
    $XMLQuery .="<Message>";
    $XMLQuery .="";
    $XMLQuery .="<UserId>******</UserId>";
    $XMLQuery .="<Password>******</Password>";
    $XMLQuery .="<SchemaName>StandardXML1_1</SchemaName>";
    $XMLQuery .="";
    $XMLQuery .="";
    $XMLQuery .="<Query>";
    $XMLQuery .="<MLS>NWMLS</MLS>";
    $XMLQuery .="<ListingNumber>1045735555</ListingNumber>";
    $XMLQuery .="<ListingNumber>10641974354</ListingNumber>";
    $XMLQuery .="<PropertyType>RESI</PropertyType>";
    $XMLQuery .="</Query>";
    $XMLQuery .="<Filter></Filter>";
    $XMLQuery .="";
    $XMLQuery .="</Message>";
    $XMLQuery .="</EverNetQuerySpecification>";
    $params = array ('v_strXmlQuery' => $XMLQuery);
    $result = $client->RetrieveListingData($params);
    $access = $result->RetrieveListingDataResult; print_r($access);
   $xml[] = simplexml_load_string($access);

The response I am getting from the Soap service is

"

    Element 'urn:www.nwmls.com/Schemas/General/EverNetQueryXML.xsd:ListingNumber' cannot appear more than once if content model type is "all".

"

How to form the query that needs to include multiple listing Numbers so that I will get the exact result ??

Thanks


问:
Email notification from R programming (R code runs successfully or fails)
I pulling data from JSON API, sometimes it fails and returns http code not equal to "200" [status_code="200" means connection was successful]

```<code>Get_data<- GET(URL,authentication("abs@def.com","password"))
Get_code<- status_code(Get_data)
</code>```

If Get_code=200; it means the Get_data worked well.
So here, I need help with:
If Get_code="200" then I need to send an email with message as "Connection is successful" else "Connection declined"

I tried using R packages like: mail, mailR, sendmailR but could not create the desired code. please direct us with your inputs.

Thanks!

答:
If you've tried mailR and that didn't work, I advise you take a look at an ifttt recipe : https://ifttt.com/

The maker channel from ifttt can take any input, including one from R. You can then set a recipe saying :

IF THIS : received an input from R in the maker channel

THEN THAT : send an email (or a push notification, or anything possible with ifttt).

You should check this blogpost to know how to connect ifttt & R : http://bconnelly.net/2015/06/connecting-r-to-everything-with-ifttt/

Best,

Colin

Body:
I pulling data from JSON API, sometimes it fails and returns http code not equal to "200" [status_code="200" means connection was successful]

Get_data<- GET(URL,authentication("abs@def.com","password"))
Get_code<- status_code(Get_data)

If Get_code=200; it means the Get_data worked well.
So here, I need help with:
If Get_code="200" then I need to send an email with message as "Connection is successful" else "Connection declined"

I tried using R packages like: mail, mailR, sendmailR but could not create the desired code. please direct us with your inputs.

Thanks!


问:
How to let people collaborate on my open source project?
A while ago I started an open-source project, which for me meant (until now) I simply pushed my source code to a public repository (Mercurial on Google Code). Recently though, I've received requests from other people to collaborate on my project. Having never collaborated on an open-source project before, I'm not sure how to proceed:

Do I just give them access to the repository so they can push changes? If they push something I don't like I can always roll back and if they get on my nerves I can always revoke their access to the repository.

Do I tell them to send in patches (via the issue tracker) and then apply the ones I like and revoke the ones I don't?

Now:

I don't want to lose ownership of my project. It's a pretty nice project and it's good resume material. I think this is what I am most afraid of. However, I want to give proper credit to my collaborators.

I know this is the whole point of open-source: collaboration, so I don't want to be an idiot and say no to these people who want to help.

Lately I haven't had much time to code on my project, so it could use some help.

Also, I'm a bit reluctant to let just anyone work on my project. What if they're, pardon the expression, noobs? I suppose I can just rollback they're changes and tell them to, pardon the expression, gtfo, but that wouldn't be particularly nice.

How is this usually done?

答:
Have different levels of contribution.

Start by taking patches from everyone. You don't have to accept them all - if rejecting a patch, explain why it was rejected and what can be done to improve it.

For accepted patches, clean them up (and document the cleanups in a coding style guide).

The people providing the most and best patches could then get access to the repository directly and start accepting patches themselves.

At this point, accept the fact that the project is no longer just yours, though you may want to continue and lead it.


问:
How to register and reference callback interface?
When I need a callback from Activity B back to Activity A I usually make the reference variable in Activity B 'static'.  I realize that if the user rotates the device the Life Cycle methods will remove my reference.

Is this the only drawback and is there a better way to register without a static reference. Is it better to simply put all data in the Application class  ? - Thank you.

```<code>    public class MainActivity extends Activity implements InterfaceMainActivityTwo {
    static Main2Activity main2Activity;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            main2Activity = new Main2Activity();
            main2Activity.setDataListener(this);
    }

        @Override
        public void getDataMainActivityTwo(String string) {
            tvTextData.setText(string);
        }

    }

    public class Main2Activity extends Activity {

        static InterfaceMainActivityTwo mGetDataInterface;

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
    }

        public void getDataSaveBtn(View v) {

            if (mGetDataInterface != null)
                mGetDataInterface.getDataMainActivityTwo(fullName);
            else
                Toast.makeText(this, "IS NULL.INTERFACE NOT INITIALIZED !!!!", Toast.LENGTH_SHORT).show();
    }

    /////////// interface setup
   interface InterfaceMainActivityTwo  {
        void getDataMainActivityTwo(String string);
    }

    public void setDataListener(InterfaceMainActivityTwo  listener) {
        this.mGetDataInterface = listener;
    }

    }
</code>```

答: You should never need a callback between two activities.  You're doing something wrong if you do.  If you need to pass data from A to B, pass it in the bundle.  If you need to pass it back from B to A, use startActivityForResult and pass it in the result.  If you need to share data between many activities, it should be held in some globally accessible data structure, either in memory or on disk.</p>

Body:
When I need a callback from Activity B back to Activity A I usually make the reference variable in Activity B 'static'.  I realize that if the user rotates the device the Life Cycle methods will remove my reference.

Is this the only drawback and is there a better way to register without a static reference. Is it better to simply put all data in the Application class  ? - Thank you.

    public class MainActivity extends Activity implements InterfaceMainActivityTwo {
    static Main2Activity main2Activity;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            main2Activity = new Main2Activity();
            main2Activity.setDataListener(this);
    }

        @Override
        public void getDataMainActivityTwo(String string) {
            tvTextData.setText(string);
        }

    }

    public class Main2Activity extends Activity {

        static InterfaceMainActivityTwo mGetDataInterface;

     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
    }

        public void getDataSaveBtn(View v) {

            if (mGetDataInterface != null)
                mGetDataInterface.getDataMainActivityTwo(fullName);
            else
                Toast.makeText(this, "IS NULL.INTERFACE NOT INITIALIZED !!!!", Toast.LENGTH_SHORT).show();
    }

    /////////// interface setup
   interface InterfaceMainActivityTwo  {
        void getDataMainActivityTwo(String string);
    }

    public void setDataListener(InterfaceMainActivityTwo  listener) {
        this.mGetDataInterface = listener;
    }

    }


问:
.NET Core MVC Controller Error
I recently reverse engineered a table to create a model and a context class. I then created a controller and a view from VS 2017 scaffolding. When I try to load my page I receive the following error:

InvalidOperationException: Unable to resolve service for type
  'TestSolutions.Models.TraderRoute.TraderContext' while attempting to
  activate 'TestSolutions.Controllers.RoutePartnersController'.

Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider
  sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Controller.

```<code>public class RoutePartnersController : Controller
{
    private readonly TraderContext _context;

    public RoutePartnersController(TraderContext context)
    {
        _context = context;
    }

    // GET: RoutePartners
    public async Task<IActionResult> Index()
    {
        return View(await _context.RoutePartner.ToListAsync());
    }

    // GET: RoutePartners/Details/5
    public async Task<IActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // GET: RoutePartners/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: RoutePartners/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (ModelState.IsValid)
        {
            routePartner.PartnerId = Guid.NewGuid();
            _context.Add(routePartner);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Edit/5
    public async Task<IActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }
        return View(routePartner);
    }

    // POST: RoutePartners/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(Guid id, [Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (id != routePartner.PartnerId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(routePartner);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoutePartnerExists(routePartner.PartnerId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Delete/5
    public async Task<IActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // POST: RoutePartners/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(Guid id)
    {
        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        _context.RoutePartner.Remove(routePartner);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    private bool RoutePartnerExists(Guid id)
    {
        return _context.RoutePartner.Any(e => e.PartnerId == id);
    }
}
</code>```

Here's my view:

```<code>@model TestSolutions.Models.TraderRoute.RoutePartner
@{ViewData["Title"] = "Details";}

<h2>Details</h2>

<div>
<h4>RoutePartner</h4>
<hr />

<dl class="dl-horizontal">
<dt>
        @Html.DisplayNameFor(model => model.Id)
</dt>
<dd>
        @Html.DisplayFor(model => model.Id)
</dd>
<dt>
        @Html.DisplayNameFor(model => model.Dark)
</dt>
<dd>
        @Html.DisplayFor(model => model.Dark)
</dd>
<dt>
        @Html.DisplayNameFor(model => model.Lit)
</dt>
<dd>
        @Html.DisplayFor(model => model.Lit)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Contra)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Contra)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.CreateDate)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.CreateDate)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.CreateBy)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.CreateBy)
    </dd>
</dl>
</div>
<div>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) | <a asp-action="Index">Back to List</a>
</div>
</code>```

答:
It seems that TraderContext is not registered in DI (IoC) container. Please make sure you register them.

```<code>public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddDbContext<TraderContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                // Remove this if you use SQL 2012 or higher.
                b => b.UseRowNumberForPaging()));
        ...
    }
}
</code>```

I normally use the following scaffold scripts to generate entities from existing tables -

```<code>Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Scaffold-DbContext "Server=SERVER;Database=DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
</code>```

Title: .NET Core MVC Controller Error

Body:
I recently reverse engineered a table to create a model and a context class. I then created a controller and a view from VS 2017 scaffolding. When I try to load my page I receive the following error:

InvalidOperationException: Unable to resolve service for type
  'TestSolutions.Models.TraderRoute.TraderContext' while attempting to
  activate 'TestSolutions.Controllers.RoutePartnersController'.

Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider
  sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

Controller.

public class RoutePartnersController : Controller
{
    private readonly TraderContext _context;

    public RoutePartnersController(TraderContext context)
    {
        _context = context;
    }

    // GET: RoutePartners
    public async Task<IActionResult> Index()
    {
        return View(await _context.RoutePartner.ToListAsync());
    }

    // GET: RoutePartners/Details/5
    public async Task<IActionResult> Details(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // GET: RoutePartners/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: RoutePartners/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (ModelState.IsValid)
        {
            routePartner.PartnerId = Guid.NewGuid();
            _context.Add(routePartner);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Edit/5
    public async Task<IActionResult> Edit(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }
        return View(routePartner);
    }

    // POST: RoutePartners/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(Guid id, [Bind("Id,PartnerId,RouteCompany,RouteCode,Dark,Lit,Contra,CreateDate,CreateBy")] RoutePartner routePartner)
    {
        if (id != routePartner.PartnerId)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(routePartner);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoutePartnerExists(routePartner.PartnerId))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }
        return View(routePartner);
    }

    // GET: RoutePartners/Delete/5
    public async Task<IActionResult> Delete(Guid? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var routePartner = await _context.RoutePartner
            .SingleOrDefaultAsync(m => m.PartnerId == id);
        if (routePartner == null)
        {
            return NotFound();
        }

        return View(routePartner);
    }

    // POST: RoutePartners/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(Guid id)
    {
        var routePartner = await _context.RoutePartner.SingleOrDefaultAsync(m => m.PartnerId == id);
        _context.RoutePartner.Remove(routePartner);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    private bool RoutePartnerExists(Guid id)
    {
        return _context.RoutePartner.Any(e => e.PartnerId == id);
    }
}

Here's my view:

@model TestSolutions.Models.TraderRoute.RoutePartner
@{ViewData["Title"] = "Details";}

Details

RoutePartner

        @Html.DisplayNameFor(model => model.Id)

        @Html.DisplayFor(model => model.Id)

        @Html.DisplayNameFor(model => model.Dark)

        @Html.DisplayFor(model => model.Dark)

        @Html.DisplayNameFor(model => model.Lit)

        @Html.DisplayFor(model => model.Lit)

        @Html.DisplayNameFor(model => model.Contra)

        @Html.DisplayFor(model => model.Contra)

        @Html.DisplayNameFor(model => model.CreateDate)

        @Html.DisplayFor(model => model.CreateDate)

        @Html.DisplayNameFor(model => model.CreateBy)

        @Html.DisplayFor(model => model.CreateBy)

    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) | Back to List

Body:
It seems that TraderContext is not registered in DI (IoC) container. Please make sure you register them.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        ...

        services.AddDbContext<TraderContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                // Remove this if you use SQL 2012 or higher.
                b => b.UseRowNumberForPaging()));
        ...
    }
}

I normally use the following scaffold scripts to generate entities from existing tables -

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

Scaffold-DbContext "Server=SERVER;Database=DATABASE;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models


问:
Trouble validating date entry
Needing to validate that user inputs date that is not before 2014 or after the current date. I tried splitting the date entry by "/" and then using parseInt to catch if the [2] spot was less than 2014 but it doesn't seem to work!

<!DOCTYPE HTML>

Internet Technologies Membership

<form name ="ratingForm">

    Full Name:
    <input type="text" id="FullName" name="FullName">
    Date:
    <input type="date" id="Date" name="Date">
    Opinion:

     <select name="opinion" id="opinion">
       <option value="★★★★★">Excellent</option>
       <option value="★★★★">Very Good</option>
       <option value="★★★">Good</option>
       <option value="★★">Fair</option>
       <option value="★">Poor</option>
       <option value="0">Very Bad</option>
     </select>

 <textarea name="list" id="list" rows="10" cols="100">
 </textarea>

 <input type="button" value="RATE" onClick="validateData();">
 <input type="button" value="DISPLAY" onClick="displayData();">
 <input type="reset" value="CLEAR" onClick="clearData();">

</form>
```

答:
The date will be retrieved in YYYY-MM-DD format irrespective of what is displayed in the input box.
Try to split it by hyphen (-).

Also while comparing use 2014 as a number instead of string

```<code>var dateParts = dateVal.split("-");
if (parseInt(dateParts[0]) < 2014)
</code>```

Title: Trouble validating date entry

Body:
The date will be retrieved in YYYY-MM-DD format irrespective of what is displayed in the input box.
Try to split it by hyphen (-).

Also while comparing use 2014 as a number instead of string

var dateParts = dateVal.split("-");
if (parseInt(dateParts[0]) < 2014)


问:
Abort trap 6 in array joining function
I'm trying to join the arrays together using a function. It works somehow but prompts an error abort trap 6. In addition, it also says that I cannot free the allocated memory.</p>

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *join_arrays(unsigned int arr1N, int arr1[], unsigned int arr2N, int arr2[], unsigned int arr3N, int arr3[]) {
  int tableLen = arr1N + arr2N + arr3N;
  printf("%d\n", tableLen);
  int *table = malloc(tableLen * sizeof(int));
  table = arr1;
  printf("%d\n", table[arr1N - 1]);
  for (int i = 0; i < arr2N; i++) {
   table[i + arr1N] = arr2[i];
  }
  printf("%d\n", table[arr1N + arr2N - 1]);
  for (int j = 0; j < arr3N; j++) {
   table[j + arr1N + arr2N] = arr3[j];
  }

  return table;
}

int main(void)
{
    int a1[] = { 89, 53, 98, 5, 5, 49, 95, 9, 54, 59, 59 };
    int a2[] = { 44, 25, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 144, 0, 0, 0, 0};
    int a3[] = { 20, 21, 22 };

    int *joined = join_arrays(11, a1, 17, a2, 3, a3);

    for (int i = 0; i < 11 + 17 + 3; i++) {
        printf("%d  ", joined[i]);
    }
    printf("\n");

    free(joined);

    return 0;
}
</code>```

答:
Note that you need to copy all 3 tables, not just the second and third.  The assignment of table is effectively throwing away your dynamic memory pointer:

```<code>int *join_arrays(unsigned int arr1N, int arr1[], unsigned int arr2N, int arr2[], unsigned int arr3N, int arr3[]) {
  int tableLen = arr1N + arr2N + arr3N;
  printf("%d\n", tableLen);
  int *table = malloc(tableLen * sizeof(int));
  int tableOffset = 0;

  for (int i = 0; i < arr1N; i++) {
   table[tableOffset++] = arr1[i];
  }

  for (int i = 0; i < arr2N; i++) {
   table[tableOffset++] = arr2[i];
  }

  for (int i = 0; i < arr3N; i++) {
   table[tableOffset++] = arr3[i];
  }

  return table;
}
</code>```

I'd also consider returning as a parameter so that the array length could be returned as well.  For higher performance, using memcpy() may also help on certain systems, though for such a simple example, the for loops are easier to understand.

Title: Abort trap 6 in array joining function

Body:
I'm trying to join the arrays together using a function. It works somehow but prompts an error abort trap 6. In addition, it also says that I cannot free the allocated memory.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int *join_arrays(unsigned int arr1N, int arr1[], unsigned int arr2N, int arr2[], unsigned int arr3N, int arr3[]) {
  int tableLen = arr1N + arr2N + arr3N;
  printf("%d\n", tableLen);
  int *table = malloc(tableLen * sizeof(int));
  table = arr1;
  printf("%d\n", table[arr1N - 1]);
  for (int i = 0; i < arr2N; i++) {
   table[i + arr1N] = arr2[i];
  }
  printf("%d\n", table[arr1N + arr2N - 1]);
  for (int j = 0; j < arr3N; j++) {
   table[j + arr1N + arr2N] = arr3[j];
  }

  return table;
}

int main(void)
{
    int a1[] = { 89, 53, 98, 5, 5, 49, 95, 9, 54, 59, 59 };
    int a2[] = { 44, 25, 0, 0, 0, 0, 0, 0, 0, 0, 80, 0, 144, 0, 0, 0, 0};
    int a3[] = { 20, 21, 22 };

    int *joined = join_arrays(11, a1, 17, a2, 3, a3);

    for (int i = 0; i < 11 + 17 + 3; i++) {
        printf("%d  ", joined[i]);
    }
    printf("\n");

    free(joined);

    return 0;
}

Body:
Note that you need to copy all 3 tables, not just the second and third.  The assignment of table is effectively throwing away your dynamic memory pointer:

int *join_arrays(unsigned int arr1N, int arr1[], unsigned int arr2N, int arr2[], unsigned int arr3N, int arr3[]) {
  int tableLen = arr1N + arr2N + arr3N;
  printf("%d\n", tableLen);
  int *table = malloc(tableLen * sizeof(int));
  int tableOffset = 0;

  for (int i = 0; i < arr1N; i++) {
   table[tableOffset++] = arr1[i];
  }

  for (int i = 0; i < arr2N; i++) {
   table[tableOffset++] = arr2[i];
  }

  for (int i = 0; i < arr3N; i++) {
   table[tableOffset++] = arr3[i];
  }

  return table;
}

I'd also consider returning as a parameter so that the array length could be returned as well.  For higher performance, using memcpy() may also help on certain systems, though for such a simple example, the for loops are easier to understand.


问:
Inherit from const class
I would like to inherit from a class with the const specifier like this:

```<code>class Property
{
    int get() const;
    void set(int a);
};

class ConstChild : public const Property
{
    // Can never call A::set() with this class, even if
    // the instantiation of this class is not const
};

class NonConstChild : public Property
{
    // Can call both A::set() and A::get() depending on
    // the constness of instantiation of this class
};
</code>```

My compiler obviously gives me an error for the const keyword in the second classes declaration. Ideally I'd like to avoid having to create a new class ReadOnlyProperty from which ConstChild would inherit.

Can I somehow use the const keyword for inheritance?

If not, do you have any other ideas on how to solve this problem?

答:
I have a trick, not a clean solution.

```<code>class ConstChild : private Property
{
    operator const Property () { return *this; }
};
</code>```

then

```<code>ConstChild cc;
cc.set(10); // ERROR
cc().get();
</code>```

Title: Inherit from const class

Body:
I would like to inherit from a class with the const specifier like this:

class Property
{
    int get() const;
    void set(int a);
};

class ConstChild : public const Property
{
    // Can never call A::set() with this class, even if
    // the instantiation of this class is not const
};

class NonConstChild : public Property
{
    // Can call both A::set() and A::get() depending on
    // the constness of instantiation of this class
};

My compiler obviously gives me an error for the const keyword in the second classes declaration. Ideally I'd like to avoid having to create a new class ReadOnlyProperty from which ConstChild would inherit.

Can I somehow use the const keyword for inheritance?

If not, do you have any other ideas on how to solve this problem?

Body:
I have a trick, not a clean solution.

class ConstChild : private Property
{
    operator const Property () { return *this; }
};

then

ConstChild cc;
cc.set(10); // ERROR
cc().get();