问:
Angular App doesn't work when injecting a pagination dependency
I'm building a simple Sigle Page Application with AngularJs, which retrieves data stored on a server-based application. When I try to inject the pagination directive, the application doesn't work, where it shows only the navigation bar.
I've followed this tutorial.

Moreover, the console doesn't show any error.
Below are the files where I'm trying to implement the pagination:

main.html:

```<code><div class="page-header">
    <h2 id="tables">Pagination in Angular Js</h2>
</div>
<div ng-controller="UsersList">
    <table class="table striped">
        <thead>
            <tr>
                <th>Last Name</th>
                <th>First Name</th>
                <th>Created At</th>
                <!--<th>Status</th>-->
            </tr>
        </thead>
        <tbody>
            <tr dir-paginate="user in users | itemsPerPage: pageSize" current-page="currentPage">
                <td>{{user.last_name}}</td>
                <td>{{user.first_name}}</td>
                <td>{{user.created_at}}</td>
            </tr>
        </tbody>
    </table>
    <dir-pagination-controls boundary-links="true" max-size="10" template-url="app/main/dirPagination.tpl.html"></dir-pagination-controls>
</div>
</code>```

main.js:

```<code>angular.module('Js-Users-App', ['angularUtils.directives.dirPagination']).controller('UsersList', UsersList);

UsersList.$inject = ['$scope', 'userDataFactory', 'angularUtils.directives.dirPagination'];

function UsersList($scope, userDataFactory){
    $scope.users = [];
    $scope.currentPage = 1;
    $scope.pageSize = 10;

    // Get the list of users
    userDataFactory.userList().then(function(response) {
        $scope.users = response.data;
    });
}
</code>```

user-data-factory.js:

```<code>angular.module('Js-Users-App').factory('userDataFactory', userDataFactory);

function userDataFactory($http) {
    return {
        userList: userList
    };

    function userList() {
        return $http.get("users.json").then(complete).catch(failed);
    }

    function complete(response) {
        return response;
    }

    function failed(error) {
        console.log(error.statusText);
    }
}
</code>```

dir-paginate is declared in the file below:

```<code><html ng-app="Js-Users-App">

<head>
    <meta charset="utf-8">
    <title>Js Users</title>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="node_modules/materialize-css/dist/css/materialize.min.css">
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

</head>
<body>
    <nav class="white" role="navigation">
        <div class="nav-wrapper container">
            <a id="logo-container" href="#/" class="brand-logo">Js Users</a>
            <ul class="right hide-on-med-and-down">
                <li><a href="#/add">Add</a></li>
            </ul>

            <ul id="nav-mobile" class="side-nav">
                <li><a href="#/add">Add</a></li>
            </ul>
            <a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
        </div>
    </nav>

    <div class="container">
        <div ng-view></div>
    </div>

    <script src="node_modules/angular/angular.min.js"></script>
    <script src="node_modules/angular-route/angular-route.min.js"></script>
    <script src="node_modules/jquery/dist/jquery.min.js"></script>
    <script src="node_modules/materialize-css/dist/js/materialize.min.js"></script>
    <!--<script src="js/ui-bootstrap-2.5.0.min.js"></script>-->
    <script src="js/dirPagination.js"></script>

    <script type="text/javascript" src="app/app.js"></script>
    <script type="text/javascript" src="app/main/main.js"></script>
    <script type="text/javascript" src="app/user-data-factory/user-data-factory.js"></script>

</body>
</html>
</code>```

And the script is located inside the js folder.
The application is running on a simple web server, started with python -m SimpleHTTPServer.
I can't find the problem. Also because I still don't know how to debug very well. Is it because the application is not loading the new directive? Thanks.

UPDATE 1

I've made a plunk to show you the project structure and the entire code: http://plnkr.co/edit/LoICEnE5nkwLDvsu7URD

答:
ng-app shouldn't be defined on  element, unless proven otherwise. This can result in undesirable behaviour when jQuery is loaded.

jQuery should be loaded before Angular and other dependencies that may use of it (Materialize).

Js-Users-App module is being redefined:

```<code>angular.module('Js-Users-App', ['angularUtils.directives.dirPagination']).controller('UsersList', UsersList);
</code>```

This eliminates router configuration, so the application does nothing. The module should be defined once, with all module dependencies:

```<code>angular.module("Js-Users-App", ["ngRoute", 'angularUtils.directives.dirPagination'])
</code>```

After that angular.module("Js-Users-App") should be used only as a getter (no second argument).

UsersList controller injects angularUtils.directives.dirPagination for no good reason, this will result in error because there's no such service - it's a directive. It should be omitted.

Body:
I'm building a simple Sigle Page Application with AngularJs, which retrieves data stored on a server-based application. When I try to inject the pagination directive, the application doesn't work, where it shows only the navigation bar.
I've followed this tutorial.

Moreover, the console doesn't show any error.
Below are the files where I'm trying to implement the pagination:

main.html:

Pagination in Angular Js

                Last Name
                First Name
                Created At

                {{user.last_name}}
                {{user.first_name}}
                {{user.created_at}}

    <dir-pagination-controls boundary-links="true" max-size="10" template-url="app/main/dirPagination.tpl.html"></dir-pagination-controls>

main.js:

angular.module('Js-Users-App', ['angularUtils.directives.dirPagination']).controller('UsersList', UsersList);

UsersList.$inject = ['$scope', 'userDataFactory', 'angularUtils.directives.dirPagination'];

function UsersList($scope, userDataFactory){
    $scope.users = [];
    $scope.currentPage = 1;
    $scope.pageSize = 10;

    // Get the list of users
    userDataFactory.userList().then(function(response) {
        $scope.users = response.data;
    });
}

user-data-factory.js:

angular.module('Js-Users-App').factory('userDataFactory', userDataFactory);

function userDataFactory($http) {
    return {
        userList: userList
    };

    function userList() {
        return $http.get("users.json").then(complete).catch(failed);
    }

    function complete(response) {
        return response;
    }

    function failed(error) {
        console.log(error.statusText);
    }
}

dir-paginate is declared in the file below:

    <meta charset="utf-8">
    <title>Js Users</title>

    <link rel="stylesheet" href="node_modules/materialize-css/dist/css/materialize.min.css">

    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

    <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

            Js Users

Add

Add

            menu

And the script is located inside the js folder.
The application is running on a simple web server, started with python -m SimpleHTTPServer.
I can't find the problem. Also because I still don't know how to debug very well. Is it because the application is not loading the new directive? Thanks.

UPDATE 1

I've made a plunk to show you the project structure and the entire code: http://plnkr.co/edit/LoICEnE5nkwLDvsu7URD

Body:
ng-app shouldn't be defined on <html> element, unless proven otherwise. This can result in undesirable behaviour when jQuery is loaded.

jQuery should be loaded before Angular and other dependencies that may use of it (Materialize).

Js-Users-App module is being redefined:

angular.module('Js-Users-App', ['angularUtils.directives.dirPagination']).controller('UsersList', UsersList);

This eliminates router configuration, so the application does nothing. The module should be defined once, with all module dependencies:

angular.module("Js-Users-App", ["ngRoute", 'angularUtils.directives.dirPagination'])

After that angular.module("Js-Users-App") should be used only as a getter (no second argument).

UsersList controller injects angularUtils.directives.dirPagination for no good reason, this will result in error because there's no such service - it's a directive. It should be omitted.


来源: stackexchange

问:
Setting up JWT - Passing token from server to client in header, but cannot parse header in client
I am trying to use JWT for user authentication. The client is a React application with Relay. It is talking to a Rails backend through endpoints served by GraphQL.

From the Rails side, I've set up CORS to make sure that I've exposed my header in the response. I've also set my JWT under Authorization:

```<code>class Api::GraphsController < ActionController::Base

def create
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
  headers['Access-Control-Max-Age'] = "1728000"
  headers['Access-Control-Expose-Headers'] = 'content-length'

  #set a fresh token after every request
  headers['Authorization'] = "WOW.WoW.Wow"

  render json: Schema.execute()
end
</code>```

On the React side, I've set up the options in my Relay middleware layer (example from here - https://github.com/nodkz/react-relay-network-layer/blob/master/README.md#middlewares). However, this is where I cannot access my header. It just shows Header {} when I print res.headers.

```<code>const options = [
  urlMiddleware({
    url: (req) => getEndpoint()
  }),
  retryMiddleware({
    fetchTimeout: 60000,
    retryDelays: (attempt) => [7000],
    forceRetry: (cb, delay) => { window.forceRelayRetry = cb },
    statusCodes: [500, 503, 504]
  }),
  next => req => {
    req.credentials = 'same-origin'; // provide CORS policy to XHR request in fetch method
    const resPromise = next(req);
    resPromise.then(res => {
      let headers = res.headers //Headers is empty
      let user = res.json.data.user //Body is sent properly

      return res;
    })
    .catch((e) => {
      console.log('=============error===========', e);
    })

    return resPromise;
  }
]
</code>```

When I look in my Chrome's developer tool, I see the Authorization token being set correctly.

How do I expose and get the authorization token from my client application?

答:
What is resPromise?
If req is a promise, this should work</p>

```<code>next => req => {
        req.then(res => {
        console.log(res.headers);
    });
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to use JWT for user authentication. The client is a React application with Relay. It is talking to a Rails backend through endpoints served by GraphQL.

From the Rails side, I've set up CORS to make sure that I've exposed my header in the response. I've also set my JWT under Authorization:

class Api::GraphsController < ActionController::Base

def create
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
  headers['Access-Control-Max-Age'] = "1728000"
  headers['Access-Control-Expose-Headers'] = 'content-length'

  #set a fresh token after every request
  headers['Authorization'] = "WOW.WoW.Wow"

  render json: Schema.execute()
end

On the React side, I've set up the options in my Relay middleware layer (example from here - https://github.com/nodkz/react-relay-network-layer/blob/master/README.md#middlewares). However, this is where I cannot access my header. It just shows Header {} when I print res.headers.

const options = [
  urlMiddleware({
    url: (req) => getEndpoint()
  }),
  retryMiddleware({
    fetchTimeout: 60000,
    retryDelays: (attempt) => [7000],
    forceRetry: (cb, delay) => { window.forceRelayRetry = cb },
    statusCodes: [500, 503, 504]
  }),
  next => req => {
    req.credentials = 'same-origin'; // provide CORS policy to XHR request in fetch method
    const resPromise = next(req);
    resPromise.then(res => {
      let headers = res.headers //Headers is empty
      let user = res.json.data.user //Body is sent properly

      return res;
    })
    .catch((e) => {
      console.log('=============error===========', e);
    })

    return resPromise;
  }
]

When I look in my Chrome's developer tool, I see the Authorization token being set correctly.

How do I expose and get the authorization token from my client application?

Body:
What is resPromise?
If req is a promise, this should work

next => req => {
        req.then(res => {
        console.log(res.headers);
    });
}


问:
opencv Mat memory access error
I'm trying to write a function to compensate lens vignetting in an OpenCV project.  The problem is that when I attempt to access the first pixel in the Mat, I get a memory access error.  It's probably a silly error, but I'd appreciate it if you could point it out to me.  Here's the function:

```<code>void EckOpCam::FlatField(cv::Mat & parmI)
{
// workaround for access violation error
cv::Mat I = parmI;
const int channels = I.channels();
if (flatField.rows == 0)
    MakeFlatFieldMat(I.rows);
// accept only char type matrices
ASSERT(I.depth() == CV_8U);
// make sure the matrices are the same size
ASSERT(I.cols == flatField.cols);
ASSERT(channels == flatField.channels());

// Try the really slow way...
int nRows = I.rows;
int nCols = I.cols;
unsigned int ipix0, ipix1, ipix2;   // B,G,r values of pixel in I
float fpix0, fpix1,fpix2;           // B,G,r values of pixel in flatField
float pix0, pix1, pix2;
switch (channels)
{
case 1:
    for (int y = 0; y < nRows; ++y)
        for (int x = 0; x < nCols; ++x)
        {
            {
                ipix0 = I.at<cv::Vec3b>(x, y)[0];
                fpix0 = flatField.at<cv::Vec3f>(x, y)[0];
                pix0 = ipix0 * fpix0;
                I.at<cv::Vec3b>(x, y)[0] = (pix0 > 255) ? 255 : uchar(pix0);
            }
        }
    break;
case 3:
    for (int y = 0; y < nRows; ++y)
        for (int x = 0; x < nCols; ++x)
        {
            {
                ipix0 = static_cast<uchar>(I.at<cv::Vec3b>(x, y)[0]); //<<< memory access error!
                ipix1 = static_cast<uchar>(I.at<cv::Vec3b>(x, y)[1]);
                ipix2 = static_cast<uchar>(I.at<cv::Vec3b>(x, y)[2]);
                fpix0 = flatField.at<cv::Vec3f>(x, y)[0];
                fpix1 = flatField.at<cv::Vec3f>(x, y)[1];
                fpix2 = flatField.at<cv::Vec3f>(x, y)[2];
                pix0 = ipix0 * fpix0;
                pix1 = ipix1 * fpix1;
                pix2 = ipix2 * fpix2;
                I.at<cv::Vec3b>(x, y)[0] = (pix0 > 255) ? 255 : uchar(pix0);
                I.at<cv::Vec3b>(x, y)[1] = (pix1 > 255) ? 255 : uchar(pix1);
                I.at<cv::Vec3b>(x, y)[2] = (pix2 > 255) ? 255 : uchar(pix2);
            }
        }
}
</code>```

}

The error is: Exception thrown: read access violation.
cv::Vec::operator returned 0x240C37EC4A8.

The address given is exactly the address for I.data.  What's wrong?  Thanks for your help.

答: Um... Never mind.  It turned out that the exception was real and not a problem with this code.  I am using sample code from Point Grey.  It converts from a Point Grey ImagePtr to a Mat using a Mat constructor that just copies the pointer to the data.  The ImagePtr went out of scope, so the data was invalid when I attempted to use it.  Mat.CopyTo() solved the problem.  I highly recommend reading this if you need a fast way to solve a similar problem.</p>

Title: opencv Mat memory access error

Body:
I'm trying to write a function to compensate lens vignetting in an OpenCV project.  The problem is that when I attempt to access the first pixel in the Mat, I get a memory access error.  It's probably a silly error, but I'd appreciate it if you could point it out to me.  Here's the function:

void EckOpCam::FlatField(cv::Mat & parmI)
{
// workaround for access violation error
cv::Mat I = parmI;
const int channels = I.channels();
if (flatField.rows == 0)
    MakeFlatFieldMat(I.rows);
// accept only char type matrices
ASSERT(I.depth() == CV_8U);
// make sure the matrices are the same size
ASSERT(I.cols == flatField.cols);
ASSERT(channels == flatField.channels());

// Try the really slow way...
int nRows = I.rows;
int nCols = I.cols;
unsigned int ipix0, ipix1, ipix2;   // B,G,r values of pixel in I
float fpix0, fpix1,fpix2;           // B,G,r values of pixel in flatField
float pix0, pix1, pix2;
switch (channels)
{
case 1:
    for (int y = 0; y < nRows; ++y)
        for (int x = 0; x < nCols; ++x)
        {
            {
                ipix0 = I.at<cv::Vec3b>(x, y)[0];
                fpix0 = flatField.at<cv::Vec3f>(x, y)[0];
                pix0 = ipix0 * fpix0;
                I.at<cv::Vec3b>(x, y)[0] = (pix0 > 255) ? 255 : uchar(pix0);
            }
        }
    break;
case 3:
    for (int y = 0; y < nRows; ++y)
        for (int x = 0; x < nCols; ++x)
        {
            {
                ipix0 = static_cast<uchar>(I.at<cv::Vec3b>(x, y)[0]); //<<< memory access error!
                ipix1 = static_cast<uchar>(I.at<cv::Vec3b>(x, y)[1]);
                ipix2 = static_cast<uchar>(I.at<cv::Vec3b>(x, y)[2]);
                fpix0 = flatField.at<cv::Vec3f>(x, y)[0];
                fpix1 = flatField.at<cv::Vec3f>(x, y)[1];
                fpix2 = flatField.at<cv::Vec3f>(x, y)[2];
                pix0 = ipix0 * fpix0;
                pix1 = ipix1 * fpix1;
                pix2 = ipix2 * fpix2;
                I.at<cv::Vec3b>(x, y)[0] = (pix0 > 255) ? 255 : uchar(pix0);
                I.at<cv::Vec3b>(x, y)[1] = (pix1 > 255) ? 255 : uchar(pix1);
                I.at<cv::Vec3b>(x, y)[2] = (pix2 > 255) ? 255 : uchar(pix2);
            }
        }
}

}

The error is: Exception thrown: read access violation.
cv::Vec::operator returned 0x240C37EC4A8.

The address given is exactly the address for I.data.  What's wrong?  Thanks for your help.


问:
IPHONE - Use multiple views
I have to make an application with six views, which can be accessed to by bar button items on a toolbar.

I'm really new at this.
I have a view controller and a XIB file for each view, with six functions (goToView1, goToView2, ..., goToView6).

Here is an example :

```<code>SecondViewController *secondview;

-(IBAction)goToView2 {
    secondview = [[SecondViewController alloc]
                 initWithNibName:@"SecondViewController" bundle:nil];
    [self.view addSubview:secondview.view];
}
</code>```

But as you can see, if I want to go from view3 to view2, I'm not deleting the view3 from the stack : I'm just adding the view2 over it.
So here's my problem, how do I "delete" my view before using addSubView ?
I tried with removeFromSuperView, but I think I'm not using it right.

Thanks for helping, as I said I'm really new and I am aware it can be a stupid question :/

答:
to remove the fisrt view you should use something like this.

```<code>   [fisrtView removefromSuperview];
</code>```

put in where you want to remove view.

ContentLicense: CC BY-SA 2.5

Title: IPHONE - Use multiple views

Body:
I have to make an application with six views, which can be accessed to by bar button items on a toolbar.

I'm really new at this.
I have a view controller and a XIB file for each view, with six functions (goToView1, goToView2, ..., goToView6).

Here is an example :

SecondViewController *secondview;

-(IBAction)goToView2 {
    secondview = [[SecondViewController alloc]
                 initWithNibName:@"SecondViewController" bundle:nil];
    [self.view addSubview:secondview.view];
}

But as you can see, if I want to go from view3 to view2, I'm not deleting the view3 from the stack : I'm just adding the view2 over it.
So here's my problem, how do I "delete" my view before using addSubView ?
I tried with removeFromSuperView, but I think I'm not using it right.

Thanks for helping, as I said I'm really new and I am aware it can be a stupid question :/

Body:
to remove the fisrt view you should use something like this.

   [fisrtView removefromSuperview];

put in where you want to remove view.


问:
Socket closed error when trying to socket write (bytearray)
The code below triggers the following error:

Error: Exception when sending command: Socket closed

```<code>    public synchronized void sendCommand(final ServerCommand pServerCommand) {

    if (pServerCommand == null) {
        return;
    }

    try {
        //byte array to write server command
        ByteArrayOutputStream baosData = new ByteArrayOutputStream();
        DataOutputStream osData = new DataOutputStream(baosData);
        //byte array that will be used to write on socket
        //this will contain length of ByteArrayData and then ByteArrayData
        ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
        DataOutputStream osOut = new DataOutputStream(baosOut);

        //write command into osData byte array
        pServerCommand.write(osData);
        //write length of command into main byte array
        osOut.writeShort(baosData.size());
        //write command into main byte array
        baosData.writeTo(baosOut);

        OutputStream out = this.getSocket()
                               .getOutputStream();
        //write main byte array on socket
        byte[] data = baosOut.toByteArray();
        out.write(data, 0, data.length);
        out.flush();
    } catch (IOException e) {
        Log.pt("Exception when sending command", e.getMessage());
        // Socket is possibly closed
    }

}
</code>```

答:
For whatever reason, the socket to which you are writing is closed. Either it was not opened, it was closed already on your end, or it was closed on the other end, apparently a server.

A couple of suggestions. First, move all the data prep code to a method that returns a byte[]. Socket code is hard enough without mixing it with code that manipulates data.

Second, make sure the socket was actually opened. That's not a given.

Body:
The code below triggers the following error:

Error: Exception when sending command: Socket closed

    public synchronized void sendCommand(final ServerCommand pServerCommand) {

    if (pServerCommand == null) {
        return;
    }

    try {
        //byte array to write server command
        ByteArrayOutputStream baosData = new ByteArrayOutputStream();
        DataOutputStream osData = new DataOutputStream(baosData);
        //byte array that will be used to write on socket
        //this will contain length of ByteArrayData and then ByteArrayData
        ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
        DataOutputStream osOut = new DataOutputStream(baosOut);

        //write command into osData byte array
        pServerCommand.write(osData);
        //write length of command into main byte array
        osOut.writeShort(baosData.size());
        //write command into main byte array
        baosData.writeTo(baosOut);

        OutputStream out = this.getSocket()
                               .getOutputStream();
        //write main byte array on socket
        byte[] data = baosOut.toByteArray();
        out.write(data, 0, data.length);
        out.flush();
    } catch (IOException e) {
        Log.pt("Exception when sending command", e.getMessage());
        // Socket is possibly closed
    }

}


问:
Collection View terminates after cellForItemAtIndex
```<code>import UIKit
import Photos

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {
    var Receipts = [UIImage?]()

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        print("return1")
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("self.receipts.count")
        return self.Receipts.count
    }
</code>```

This code below is not working as it should and everytime I run the app it comes up with this error -

```
SmartReceipts[738:137366] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the collection view's data source did not return a valid cell from -collectionView:cellForItemAtIndexPath: for index path  {length = 2, path = 0 - 0}'
*** First throw call stack:
(0x186196364 0x1853dc528 0x186196238 0x186b317f4 0x1901010b0 0x18f6d7124 0x18f6d1de0 0x18f674f00 0x18a1d9998 0x18a1ddb20 0x18a14a36c 0x18a171b90 0x18f66a5c8 0x18613dedc 0x18613b894 0x18613be50 0x18605be58 0x187f08f84 0x18f6db67c 0x104484668 0x185b7856c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
```

Any help with this would be greatly appreciated.

And the code that needs fixing is the code below:

```<code>    func collectionView(_ collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        print("Assigned to cell and should come up")
        return cell!
    }
}
</code>```

It now errors as this error and i'm not sure how it's doing it? Because it is sending the image to an array but it's not showing up in the UICollectionViewCell?

答:
Please use Xcode's code completion to ensure you are providing the correct method signatures.

The method needs to be:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
</code>```

not:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell
</code>```

Note cellForItemAtindexPath should be cellForItemAt and NSIndexPath should be IndexPath.

With that, your whole becomes:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath) as! PhotoCell

    cell.imageView.image = self.Receipts[indexPath.row]
    print("Assigned to cell and should come up")
    return cell
}
</code>```

See how you should force-cast the cell type. You want this to crash early on in development if your have your cell setup incorrectly.

Body:
import UIKit
import Photos

class GalleryController: UICollectionViewController,
                         UIImagePickerControllerDelegate,
                         UINavigationControllerDelegate {
    var Receipts = [UIImage?]()

    //Number of Views
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        print("return1")
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("self.receipts.count")
        return self.Receipts.count
    }

This code below is not working as it should and everytime I run the app it comes up with this error -

SmartReceipts[738:137366] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'the collection view's data source did not return a valid cell from -collectionView:cellForItemAtIndexPath: for index path  {length = 2, path = 0 - 0}'
*** First throw call stack:
(0x186196364 0x1853dc528 0x186196238 0x186b317f4 0x1901010b0 0x18f6d7124 0x18f6d1de0 0x18f674f00 0x18a1d9998 0x18a1ddb20 0x18a14a36c 0x18a171b90 0x18f66a5c8 0x18613dedc 0x18613b894 0x18613be50 0x18605be58 0x187f08f84 0x18f6db67c 0x104484668 0x185b7856c)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Any help with this would be greatly appreciated.

And the code that needs fixing is the code below:

    func collectionView(_ collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath as IndexPath) as? PhotoCell

        cell?.imageView.image = self.Receipts[indexPath.row]
        print("Assigned to cell and should come up")
        return cell!
    }
}

It now errors as this error and i'm not sure how it's doing it? Because it is sending the image to an array but it's not showing up in the UICollectionViewCell?

Body:
Please use Xcode's code completion to ensure you are providing the correct method signatures.

The method needs to be:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

not:

func collectionView(_ collectionView: UICollectionView, cellForItemAtindexPath indexPath: NSIndexPath) -> UICollectionViewCell

Note cellForItemAtindexPath should be cellForItemAt and NSIndexPath should be IndexPath.

With that, your whole becomes:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "receipt", for: indexPath) as! PhotoCell

    cell.imageView.image = self.Receipts[indexPath.row]
    print("Assigned to cell and should come up")
    return cell
}

See how you should force-cast the cell type. You want this to crash early on in development if your have your cell setup incorrectly.


问:
what is [[prototype]] in Javascript
Referring to the following example (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain), why do I get error (using nodejs) when I write o.[[Prototype]] but not when I write o.__proto__

```<code>var o = {
    a: 1,
    b:2
}
o.[[Prototype]] = {b:1, c:3}; //doesn't work
o.__proto__= {b:1, c:3}; //works
console.log(o.a);
console.log(o.b);
console.log(o.c);
</code>```

答: [[Prototype]] is an internal property used by the Javascript Virtual Machine (the program that actually reads and executes the code you write). You can have read access to it in certain debuggers (like the one in Chrome) but it is not available to you in a code context. The property that is identical and is available is the __proto__ property which designates your object's parent with respect to the inheritance structure of your Javascript types.

Title: what is [[prototype]] in Javascript

Body:
Referring to the following example (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain), why do I get error (using nodejs) when I write o.[[Prototype]] but not when I write o.__proto__

var o = {
    a: 1,
    b:2
}
o.[[Prototype]] = {b:1, c:3}; //doesn't work
o.__proto__= {b:1, c:3}; //works
console.log(o.a);
console.log(o.b);
console.log(o.c);


问:
Does this C code leak memory?
So here is my code:

```<code>typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}
</code>```

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.

答:
Yes, you are leaking memory. w.t is never released.

Also pass the structures via pointers not by value. Returning vector is also expensive.

Your new program can look like this:

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

typedef struct {
    int x;
    int *t;
}vector;

void fct (vector *v, vector * w){

    int i;

    w->x = v->x;

    for (i=0; i<w->x; i++)
        w->t[i]=2*v->t[i];
}

int main (){
    int i;
    vector v;
    vector w;

    v.x=2;

    v.t = malloc(2*sizeof(int));
    w.t = malloc(2*sizeof(int));

    v.t[0]=1;
    v.t[1]=5;

    fct(&v,&w);

    for (i=0; i<2; i++)
        printf("%d \t",w.t[i]);

    puts("");

    free(v.t);
    free(w.t);

    return 0;
}
</code>```

OUTPUT:

```<code>2       10
</code>```

Title: Does this C code leak memory?

Body:
So here is my code:

typedef struct {
    int x;
    int *t;
}vector;

vector fct (vector v){
    vector w;
    int i;
    w.x=v.x;
    w.t=malloc(w.x *sizeof(int));
    for (i=0; i<w.x; i++)
        w.t[i]=2*v.t[i];
    return w;
}

int main (){
    int i;
    vector v;
    v.x=2;
    v.t=malloc(2*sizeof(int));
    v.t[0]=1; v.t[1]=5;
    v=fct(v);
    for (i=0; i<2; i++)
        printf("%d \t",v.t[i]);
    puts("");
    free(v.t);
    return 0;
}

I'm quite worried about whether or not it causes a memory leak, and how I can fix that in case it does.
Oh, and I know that if I define another vector let's say w, such that
w = fct(v)
it would clear the problem, but I need a different method, one that would work even if the function is returned to the original vector.

Body:
Yes, you are leaking memory. w.t is never released.

Also pass the structures via pointers not by value. Returning vector is also expensive.

Your new program can look like this:

#include <stdio.h>

typedef struct {
    int x;
    int *t;
}vector;

void fct (vector *v, vector * w){

    int i;

    w->x = v->x;

    for (i=0; i<w->x; i++)
        w->t[i]=2*v->t[i];
}

int main (){
    int i;
    vector v;
    vector w;

    v.x=2;

    v.t = malloc(2*sizeof(int));
    w.t = malloc(2*sizeof(int));

    v.t[0]=1;
    v.t[1]=5;

    fct(&v,&w);

    for (i=0; i<2; i++)
        printf("%d \t",w.t[i]);

    puts("");

    free(v.t);
    free(w.t);

    return 0;
}

OUTPUT:

2       10


问:
SQL - How to join two tables that are based on a bit condition and will always populate the field

I am trying to join two tables in MS SQL Server.

One table contains the persons Name and their ID.

```<code>+----+---------+--------------+---------+
| ID |  Name   |    phone     |  email  |
+----+---------+--------------+---------+
|  1 | John A. | 111-111-1111 | a@email |
|  2 | Sara B. | 111-111-1112 | b@email |
|  3 | Joe C.  | 111-111-1113 | c@email |
|  4 | Jane D. | 111-111-1114 | d@email |
+----+---------+--------------+---------+
</code>```

The other table contains the ID, the languages they know, and a bit that indicates if it is their native language.

```<code>+----+----------+---------+
| ID | Language | Native  |
+----+----------+---------+
|  1 | English  | True    |
|  1 | Spanish  | False   |
|  2 | Spanish  | True    |
|  2 | English  | False   |
|  2 | French   | False   |
|  3 | French   | False   |
|  3 | Spanish  | False   |
|  4 | English  | True    |
+----+----------+---------+
</code>```

The table I want should show the id, persons name, their native language or which ever language is returned first, if this is their native language, phone number, email.

```<code>+----+---------+----------+--------+--------------+---------+
| ID |  Name   | Language | Native |    phone     |  email  |
+----+---------+----------+--------+--------------+---------+
|  1 | John A. | English  | True   | 111-111-1111 | a@email |
|  2 | Sara B. | Spanish  | True   | 111-111-1112 | b@email |
|  3 | Joe C.  | French   | False  | 111-111-1113 | c@email |
|  4 | Jane D. | English  | True   | 111-111-1114 | d@email |
+----+---------+----------+--------+--------------+---------+
</code>```

I have tried joining the tables and providing a where condition but it either returns only the native languages or all of the languages that the person knows.  I have also tried grouping by the ID, which said that the columns are invalid in the selected list.  I put all the columns into the group by clause but that gave me operand data type bit is invalid for max operator.

```<code>SELECT p.ID
      ,p.Name
      ,l.Language
      ,coalesce(max(l.native),0) as native
      ,p.phone
      ,p.email
  FROM people as p
  JOIN Languages as l on p.ID = l.ID
  group by p.id
</code>```

答:
There are several ways to do this. You didn't say what DBMS you're using, so I'll assume MySQL as the most common open source product.

You can do it using a sub-query containing a LIMIT 1 clause (TOP 1 in SQL Server, but might not work in a subquery).

You should probably use an OUTER join in case some person has no language listed. The ORDER BY and LIMIT selects the native language or the first one alphabetically. Note there is no real "first" language, SQL has no record ordering, so you need to use ORDER BY to give a meaning to "first".

```<code>SELECT  p.ID,
        p.Name,
        p.phone,
        p.email,
        l.Language,
        l.Native
FROM    people as p,
LEFT OUTER JOIN
        (SELECT ID, Language, Native
         FROM Languages
         ORDER BY CASE WHEN Native THEN 0 ELSE 1 END, Language
        LIMIT 1) as l
ON      p.ID = l.ID
</code>```

I haven't tested this, but the approach is right. Let me know if it has a problem and I'll update the syntax.

Body:
I am trying to join two tables in MS SQL Server.

One table contains the persons Name and their ID.

+----+---------+--------------+---------+
| ID |  Name   |    phone     |  email  |
+----+---------+--------------+---------+
|  1 | John A. | 111-111-1111 | a@email |
|  2 | Sara B. | 111-111-1112 | b@email |
|  3 | Joe C.  | 111-111-1113 | c@email |
|  4 | Jane D. | 111-111-1114 | d@email |
+----+---------+--------------+---------+

The other table contains the ID, the languages they know, and a bit that indicates if it is their native language.

+----+----------+---------+
| ID | Language | Native  |
+----+----------+---------+
|  1 | English  | True    |
|  1 | Spanish  | False   |
|  2 | Spanish  | True    |
|  2 | English  | False   |
|  2 | French   | False   |
|  3 | French   | False   |
|  3 | Spanish  | False   |
|  4 | English  | True    |
+----+----------+---------+

The table I want should show the id, persons name, their native language or which ever language is returned first, if this is their native language, phone number, email.

+----+---------+----------+--------+--------------+---------+
| ID |  Name   | Language | Native |    phone     |  email  |
+----+---------+----------+--------+--------------+---------+
|  1 | John A. | English  | True   | 111-111-1111 | a@email |
|  2 | Sara B. | Spanish  | True   | 111-111-1112 | b@email |
|  3 | Joe C.  | French   | False  | 111-111-1113 | c@email |
|  4 | Jane D. | English  | True   | 111-111-1114 | d@email |
+----+---------+----------+--------+--------------+---------+

I have tried joining the tables and providing a where condition but it either returns only the native languages or all of the languages that the person knows.  I have also tried grouping by the ID, which said that the columns are invalid in the selected list.  I put all the columns into the group by clause but that gave me operand data type bit is invalid for max operator.

SELECT p.ID
      ,p.Name
      ,l.Language
      ,coalesce(max(l.native),0) as native
      ,p.phone
      ,p.email
  FROM people as p
  JOIN Languages as l on p.ID = l.ID
  group by p.id

Body:
There are several ways to do this. You didn't say what DBMS you're using, so I'll assume MySQL as the most common open source product.

You can do it using a sub-query containing a LIMIT 1 clause (TOP 1 in SQL Server, but might not work in a subquery).

You should probably use an OUTER join in case some person has no language listed. The ORDER BY and LIMIT selects the native language or the first one alphabetically. Note there is no real "first" language, SQL has no record ordering, so you need to use ORDER BY to give a meaning to "first".

SELECT  p.ID,
        p.Name,
        p.phone,
        p.email,
        l.Language,
        l.Native
FROM    people as p,
LEFT OUTER JOIN
        (SELECT ID, Language, Native
         FROM Languages
         ORDER BY CASE WHEN Native THEN 0 ELSE 1 END, Language
        LIMIT 1) as l
ON      p.ID = l.ID

I haven't tested this, but the approach is right. Let me know if it has a problem and I'll update the syntax.


问:
VS Setup installer doesn't include exe if app targets net461 and netcoreapp
I have a simple solution in VS that contains a Console app targeting netcoreapp2.0 and net461:

ConsoleTest.csproj

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.0;net461</TargetFrameworks>
  </PropertyGroup>
</Project>
</code>```

I also have a VS Setup installer project for this console app that is configured to include "Primary output from Control (Active)" of type "Output" in my Application Folder:

Whenever I build and run this installer (targeting net461), it only includes ConsoleTest.dll in the application folder output:

If I remove the target framework reference to netcoreapp2.0 in ConsoleTest.csproj and only target net461, I get the proper ConsoleTest.exe output from the installer that I need:

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net461</TargetFramework>
  </PropertyGroup>
</Project>
</code>```

It seems that when targeting both netcoreapp2.0 and net461 that the setup installer will always choose the output from netcoreapp2.0. Since this is a windows installer I need the net461 output with the exe.

How do I properly target net461 output for my windows setup installer while still being able to have both target frameworks present in the console project?

答:
If your app requires .NET 461 on the system then you specify that in the setup project. In View-Editor-Launch Conditions there's .NET FW dropdown choice where you specify the 461 version (I'm in VS 2017 Community Edition). </p>

<p>Using Primary Output often seems unpredictable. Just drag and drop the files from Explorer into the Application Folder, or right click in the Application Folder pane and add files. </p>

Body:
I have a simple solution in VS that contains a Console app targeting netcoreapp2.0 and net461:

ConsoleTest.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.0;net461</TargetFrameworks>
  </PropertyGroup>
</Project>

I also have a VS Setup installer project for this console app that is configured to include "Primary output from Control (Active)" of type "Output" in my Application Folder:

Whenever I build and run this installer (targeting net461), it only includes ConsoleTest.dll in the application folder output:

If I remove the target framework reference to netcoreapp2.0 in ConsoleTest.csproj and only target net461, I get the proper ConsoleTest.exe output from the installer that I need:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net461</TargetFramework>
  </PropertyGroup>
</Project>

It seems that when targeting both netcoreapp2.0 and net461 that the setup installer will always choose the output from netcoreapp2.0. Since this is a windows installer I need the net461 output with the exe.

How do I properly target net461 output for my windows setup installer while still being able to have both target frameworks present in the console project?

Body:
If your app requires .NET 461 on the system then you specify that in the setup project. In View-Editor-Launch Conditions there's .NET FW dropdown choice where you specify the 461 version (I'm in VS 2017 Community Edition).

Using Primary Output often seems unpredictable. Just drag and drop the files from Explorer into the Application Folder, or right click in the Application Folder pane and add files.


问:
Embedded C: How to apply the MAP macro to two arguments at a time instead of one?
I want to modify or use in a tricky way this https://github.com/swansontec/map-macro macro for using map in my C sources as follows:

```<code>MAP(f,1,2,3)
   f(1)
   f(2)
   f(3)
</code>```

into

```<code>MAP2(f,a,1,2,3)
   f(a,1)
   f(a,2)
   f(a,3)
</code>```

How should I?

答:
Just call MAP() with a macro for the function name, where the macro expansion inserts your argument:

```<code>#define F(x) f(a,x)
</code>```

Then in your function:

```<code>MAP(F, 1, 2, 3);
</code>```

Result is:

```<code>f(a, 1); f(a, 2); f(a, 3);
</code>```

(Not endorsing the approach, just providing an answer to the question.)

Body:
I want to modify or use in a tricky way this https://github.com/swansontec/map-macro macro for using map in my C sources as follows:

MAP(f,1,2,3)
   f(1)
   f(2)
   f(3)

into

MAP2(f,a,1,2,3)
   f(a,1)
   f(a,2)
   f(a,3)

How should I?

Body:
Just call MAP() with a macro for the function name, where the macro expansion inserts your argument:

#define F(x) f(a,x)

Then in your function:

MAP(F, 1, 2, 3);

Result is:

f(a, 1); f(a, 2); f(a, 3);

(Not endorsing the approach, just providing an answer to the question.)


问:
Convert an array of IDs to a map object
I'm looking for a concise way of creating an object whose property names match values from an array, where all properties have the same value (e.g. true). As an example:

My ID array looks like these arbitrary (in the actual software, not necessarily unique and not necessarily numeric, but primitive) values:

```<code>var ids = [4, 15, 8, 16, 42, 23];
</code>```

I am looking for some simple call to convert this into the following object:

```<code>{ 4: true, 15: true, 8: true, 16: true, 42: true, 23: true }
</code>```

With JavaScript objects internally being hashmaps, such an object should be much more convenient for quickly checking whether a given ID is contained in the array.

Now, of course I know how to generate this object. It's a four-liner:

```<code>var idMap = {};
ids.forEach(function (v) {
    idMap[v] = true;
});
</code>```

As this pattern occurs over and over in my code (lots of different item IDs being handled in this application), I feel the percentage of "boilerplate" in this is still too large. Furthermore, it appears to me that the four-liner occasionally distracts from the actually tricky algorithms for doing something with various of these ID lists. Therefore, I am looking for a shorter way to write this, hoping that there is something built-in either to standard JavaScript or to lodash, which is already in use in our application.

The most related question I could find appears to be lodash: mapping array to object. Yet, its proposed solutions are not really shorter and more legible than the above, basically replacing one sort of boilerplate code with another sort (as in my case, I'd usually throw away what the suggested solutions use as values for the object properties and always use true or some similarly small truthy value).

Is there something built-in that allows for a very simple command like

```<code>var idMap = arrayToMap(ids);
</code>```

or

```<code>var idMap = arrayToMap(ids, true);
</code>```

whose actual name I have not yet found?

(Obviously, the fallback solution is to simply write such a function in our application. I'd prefer to stick as closely as possible with the existing functions, though, hence this question.)

答:
You can create a simple function that generates maps for you:

var ids = [4, 15, 8, 16, 42, 23];

function hash(arr, prop) {
  return arr.reduce(function(r, n) {
    r[prop ? n[prop] : n] = true;

    return r;
  }, {});
}

console.log(hash(ids));

var objs = [{ a: 1 }, { a: 2 }, { a: 3}];

console.log(hash(objs, 'a'));```
</div>
</div>
</p>

<p>You can use an ES6 Set:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const ids = [4, 15, 8, 16, 42, 23];

const set = new Set(ids);

console.log(set.has(16));</code>```

Title: Convert an array of IDs to a map object

Body:
I'm looking for a concise way of creating an object whose property names match values from an array, where all properties have the same value (e.g. true). As an example:

My ID array looks like these arbitrary (in the actual software, not necessarily unique and not necessarily numeric, but primitive) values:

var ids = [4, 15, 8, 16, 42, 23];

I am looking for some simple call to convert this into the following object:

{ 4: true, 15: true, 8: true, 16: true, 42: true, 23: true }

With JavaScript objects internally being hashmaps, such an object should be much more convenient for quickly checking whether a given ID is contained in the array.

Now, of course I know how to generate this object. It's a four-liner:

var idMap = {};
ids.forEach(function (v) {
    idMap[v] = true;
});

As this pattern occurs over and over in my code (lots of different item IDs being handled in this application), I feel the percentage of "boilerplate" in this is still too large. Furthermore, it appears to me that the four-liner occasionally distracts from the actually tricky algorithms for doing something with various of these ID lists. Therefore, I am looking for a shorter way to write this, hoping that there is something built-in either to standard JavaScript or to lodash, which is already in use in our application.

The most related question I could find appears to be lodash: mapping array to object. Yet, its proposed solutions are not really shorter and more legible than the above, basically replacing one sort of boilerplate code with another sort (as in my case, I'd usually throw away what the suggested solutions use as values for the object properties and always use true or some similarly small truthy value).

Is there something built-in that allows for a very simple command like

var idMap = arrayToMap(ids);

or

var idMap = arrayToMap(ids, true);

whose actual name I have not yet found?

(Obviously, the fallback solution is to simply write such a function in our application. I'd prefer to stick as closely as possible with the existing functions, though, hence this question.)

Body:
You can create a simple function that generates maps for you:

var ids = [4, 15, 8, 16, 42, 23];

function hash(arr, prop) {
  return arr.reduce(function(r, n) {
    r[prop ? n[prop] : n] = true;

    return r;
  }, {});
}

console.log(hash(ids));

var objs = [{ a: 1 }, { a: 2 }, { a: 3}];

console.log(hash(objs, 'a'));

You can use an ES6 Set:

const ids = [4, 15, 8, 16, 42, 23];

const set = new Set(ids);

console.log(set.has(16));


问:
Java - Recursive Linked List implementation
I have fully implemented a singly Linked List (code below), however, the assignment specifically requests that it be implemented using recursion. I've been attempting to translate the while loops that I wrote into recursive calls, but Have gotten stuck and could use some help.  My most recent attempts at the recursion are included in the code, but have been commented out.Thanks in advance for your help.

```<code>public class AddressList
{
public Record firstLink ;
public String name, tel, email, addr, state, dob;
AddressList()
{
    firstLink = null;
}

public boolean isEmpty()
{
    return(firstLink == null);
}

public void addToFront(Record record)
{
    if(firstLink == null)
    {
        firstLink = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
            record.getState(), record.getDob());
    }
    else
    {
        Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
                record.getState(), record.getDob());
        newRecord.setNext(firstLink);
        firstLink = newRecord;
    }
}

public void addToBack(Record record)
{
    if(firstLink == null)
    {
        firstLink = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
            record.getState(), record.getDob());
    }
    else
    {
        Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
                record.getState(), record.getDob());
        Record currentRecord = firstLink;
        while(currentRecord.getNext() != null)
        {
            currentRecord = currentRecord.getNext();
        }
        currentRecord.setNext(newRecord);
    }
    /*
    if(firstLink == null)
    {
    firstLink = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob());
    }
    else if (firstLink.getNext() == null)
    {
    firstLink.setNext(new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob()));
    }
    else
    {
    Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob());
    newRecord.setNext(firstLink);
    firstLink = newRecord;
    addToBack(newRecord);
    }*/

    /*
    else
    {
    add
    }
    {
    Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob());
    Record current = firstLink;
    if(current.getNext() == null)
    current.setNext(newRecord);
    else
    addToBack(current.getNext());
    }
     */

}

public String toString()
{
    if(firstLink == null)
        return "Empty List\n\n";
    String result = "";
    Record current = firstLink;
    result += "\nName: "+current.getName()+"\nTelephone: "+current.getTel()+"\nEmail: "+current.getEmail()+
    "\nAddress: "+current.getAddr()+"\nState: "+current.getState()+"\nDOB: "+current.getDob()+"\n\n";
    while(current.getNext() != null)
    {
        current = current.getNext();
        result += "\nName: "+current.getName()+"\nTelephone: "+current.getTel()+"\nEmail: "+current.getEmail()+
        "\nAddress: "+current.getAddr()+"\nState: "+current.getState()+"\nDOB: "+current.getDob()+"\n\n";
    }
    return "List: \n\n"+result;
}

public void reverse()
{
    Record previousRecord = null;
    Record currentRecord = firstLink;
    while (currentRecord != null)
    {
        Record nextRecord = currentRecord.getNext();
        currentRecord.setNext(previousRecord);
        previousRecord = currentRecord;
        currentRecord = nextRecord;
    }
    firstLink = previousRecord;
}

public int sizeOf()
{
    Record currentRecord = firstLink;
    int size = 1;
    if (currentRecord == null)
    {
        return 0;
    }
    else
    {
        while (currentRecord.getNext() != null)
        {
            size++;
            currentRecord = currentRecord.getNext();
        }
    }
    return size;
}

public String phoneNumberByName(String name)
{
    Record currentRecord = firstLink;
    while(currentRecord.getName().equals(name) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getTel();
    /*
    Record currentRecord = firstLink;
    if (currentRecord.getName().equals(name))
    {
    return currentRecord.getTel();
    }
    else
    {
    firstLink = currentRecord.getNext();
    phoneNumberByName(name);

    }
    return "Unexpected behaviour. You should never see this message.";
     */

}

public String emailByName(String name)
{
    Record currentRecord = firstLink;
    while(currentRecord.getName().equals(name) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getEmail();
}

public String nameByPhoneNumber(String tel)
{
    Record currentRecord = firstLink;
    while(currentRecord.getTel().equals(tel) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getName();
}

public String dobByName(String name)
{
    Record currentRecord = firstLink;
    while (currentRecord.getName().equals(name) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getDob();
}
</code>```

}

The Record class, in case you need that too:

```<code>public class Record
{
private String name;
private String tel; // Telephone number
private String email;
private String addr; // Address
private String dob; // Date of birth
private String state;
private Record next = null;

public Record(String name, String tel, String email, String addr, String state, String dob)
{
    this.name = name;
    this.tel = tel;
    this.email = email;
    this.addr = addr;
    this.dob = dob;
    this.state = state;
    //this.next = null;
} // end of the constructor

public String getName()
{ return name; }

public String getTel()
{ return tel; }

public String getEmail()
{ return email; }

public String getAddr()
{ return addr; }

public String getState()
{ return state; }

public String getDob()
{return dob; }

public void setName(String name)
{ this.name = name; }

public void setTel(String tel)
{ this.tel = tel; }

public void setEmail(String email)
{ this.email = email; }

public void setAddr(String addr)
{ this.addr = addr; }

public void setState(String state)
{ this.state = state; }

public void setDob(String dob)
{ this.dob = dob; }

public Record getNext()
{ return next; }

public void setNext(Record record)
{ next = record; }
</code>```

}

答:
Recursive addToBack is fairly simple. In pseudo-code, your existing non-recursive is:

```<code>public void addToBack(rec) {
    if (first == null)
        first = new(rec)
    else {
        curr = first;
        while (curr.next != null)
           curr = curr.next
        curr.next = new(rec)
    }
}
</code>```

As recursive, it would have to be two methods:

```<code>public void addToBack(rec) {
    if (first == null)
        first = new(rec)
    else
        addToBackInternal(first, rec)
}

private void addToBackInternal(curr, rec) {
    if (curr.next == null)
        curr.next = new(rec)
    else
        addToBackInternal(curr.next, rec)
}
</code>```

A better implementation might be a more reusable findLast internal method:

```<code>public void addToBack(rec) {
    if (first == null)
        first = new(rec)
    else
        findLast(first).next = new(rec)
}

private Node findLast(curr) {
    if (curr.next == null)
        return curr
    return findLast(curr.next)
}
</code>```

Body:
I have fully implemented a singly Linked List (code below), however, the assignment specifically requests that it be implemented using recursion. I've been attempting to translate the while loops that I wrote into recursive calls, but Have gotten stuck and could use some help.  My most recent attempts at the recursion are included in the code, but have been commented out.Thanks in advance for your help.

public class AddressList
{
public Record firstLink ;
public String name, tel, email, addr, state, dob;
AddressList()
{
    firstLink = null;
}

public boolean isEmpty()
{
    return(firstLink == null);
}

public void addToFront(Record record)
{
    if(firstLink == null)
    {
        firstLink = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
            record.getState(), record.getDob());
    }
    else
    {
        Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
                record.getState(), record.getDob());
        newRecord.setNext(firstLink);
        firstLink = newRecord;
    }
}

public void addToBack(Record record)
{
    if(firstLink == null)
    {
        firstLink = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
            record.getState(), record.getDob());
    }
    else
    {
        Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
                record.getState(), record.getDob());
        Record currentRecord = firstLink;
        while(currentRecord.getNext() != null)
        {
            currentRecord = currentRecord.getNext();
        }
        currentRecord.setNext(newRecord);
    }
    /*
    if(firstLink == null)
    {
    firstLink = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob());
    }
    else if (firstLink.getNext() == null)
    {
    firstLink.setNext(new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob()));
    }
    else
    {
    Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob());
    newRecord.setNext(firstLink);
    firstLink = newRecord;
    addToBack(newRecord);
    }*/

    /*
    else
    {
    add
    }
    {
    Record newRecord = new Record(record.getName(), record.getTel(), record.getEmail(), record.getAddr(),
    record.getState(), record.getDob());
    Record current = firstLink;
    if(current.getNext() == null)
    current.setNext(newRecord);
    else
    addToBack(current.getNext());
    }
     */

}

public String toString()
{
    if(firstLink == null)
        return "Empty List\n\n";
    String result = "";
    Record current = firstLink;
    result += "\nName: "+current.getName()+"\nTelephone: "+current.getTel()+"\nEmail: "+current.getEmail()+
    "\nAddress: "+current.getAddr()+"\nState: "+current.getState()+"\nDOB: "+current.getDob()+"\n\n";
    while(current.getNext() != null)
    {
        current = current.getNext();
        result += "\nName: "+current.getName()+"\nTelephone: "+current.getTel()+"\nEmail: "+current.getEmail()+
        "\nAddress: "+current.getAddr()+"\nState: "+current.getState()+"\nDOB: "+current.getDob()+"\n\n";
    }
    return "List: \n\n"+result;
}

public void reverse()
{
    Record previousRecord = null;
    Record currentRecord = firstLink;
    while (currentRecord != null)
    {
        Record nextRecord = currentRecord.getNext();
        currentRecord.setNext(previousRecord);
        previousRecord = currentRecord;
        currentRecord = nextRecord;
    }
    firstLink = previousRecord;
}

public int sizeOf()
{
    Record currentRecord = firstLink;
    int size = 1;
    if (currentRecord == null)
    {
        return 0;
    }
    else
    {
        while (currentRecord.getNext() != null)
        {
            size++;
            currentRecord = currentRecord.getNext();
        }
    }
    return size;
}

public String phoneNumberByName(String name)
{
    Record currentRecord = firstLink;
    while(currentRecord.getName().equals(name) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getTel();
    /*
    Record currentRecord = firstLink;
    if (currentRecord.getName().equals(name))
    {
    return currentRecord.getTel();
    }
    else
    {
    firstLink = currentRecord.getNext();
    phoneNumberByName(name);

    }
    return "Unexpected behaviour. You should never see this message.";
     */

}

public String emailByName(String name)
{
    Record currentRecord = firstLink;
    while(currentRecord.getName().equals(name) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getEmail();
}

public String nameByPhoneNumber(String tel)
{
    Record currentRecord = firstLink;
    while(currentRecord.getTel().equals(tel) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getName();
}

public String dobByName(String name)
{
    Record currentRecord = firstLink;
    while (currentRecord.getName().equals(name) == false)
    {
        currentRecord = currentRecord.getNext();
    }
    return currentRecord.getDob();
}

}

The Record class, in case you need that too:

public class Record
{
private String name;
private String tel; // Telephone number
private String email;
private String addr; // Address
private String dob; // Date of birth
private String state;
private Record next = null;

public Record(String name, String tel, String email, String addr, String state, String dob)
{
    this.name = name;
    this.tel = tel;
    this.email = email;
    this.addr = addr;
    this.dob = dob;
    this.state = state;
    //this.next = null;
} // end of the constructor

public String getName()
{ return name; }

public String getTel()
{ return tel; }

public String getEmail()
{ return email; }

public String getAddr()
{ return addr; }

public String getState()
{ return state; }

public String getDob()
{return dob; }

public void setName(String name)
{ this.name = name; }

public void setTel(String tel)
{ this.tel = tel; }

public void setEmail(String email)
{ this.email = email; }

public void setAddr(String addr)
{ this.addr = addr; }

public void setState(String state)
{ this.state = state; }

public void setDob(String dob)
{ this.dob = dob; }

public Record getNext()
{ return next; }

public void setNext(Record record)
{ next = record; }

}

Body:
Recursive addToBack is fairly simple. In pseudo-code, your existing non-recursive is:

public void addToBack(rec) {
    if (first == null)
        first = new(rec)
    else {
        curr = first;
        while (curr.next != null)
           curr = curr.next
        curr.next = new(rec)
    }
}

As recursive, it would have to be two methods:

public void addToBack(rec) {
    if (first == null)
        first = new(rec)
    else
        addToBackInternal(first, rec)
}

private void addToBackInternal(curr, rec) {
    if (curr.next == null)
        curr.next = new(rec)
    else
        addToBackInternal(curr.next, rec)
}

A better implementation might be a more reusable findLast internal method:

public void addToBack(rec) {
    if (first == null)
        first = new(rec)
    else
        findLast(first).next = new(rec)
}

private Node findLast(curr) {
    if (curr.next == null)
        return curr
    return findLast(curr.next)
}


答:
It sounds very much like you want to use a UITabBarController, as this will provide the toolbar (with icons), etc. and will automatically handle displaying the appropriate view controller when a specific toolbar icon is selected.

However, I'd really recommend first reading the View Controller Programming Guide for iOS document, as it provides a good overview of the various UIKit controllers, etc. and how they should be used. If you take the time to read and understand this now, it'll serve you well in the future.

Title: IPHONE - Use multiple views

Body:
I have to make an application with six views, which can be accessed to by bar button items on a toolbar.

I'm really new at this.
I have a view controller and a XIB file for each view, with six functions (goToView1, goToView2, ..., goToView6).

Here is an example :

SecondViewController *secondview;

-(IBAction)goToView2 {
    secondview = [[SecondViewController alloc]
                 initWithNibName:@"SecondViewController" bundle:nil];
    [self.view addSubview:secondview.view];
}

But as you can see, if I want to go from view3 to view2, I'm not deleting the view3 from the stack : I'm just adding the view2 over it.
So here's my problem, how do I "delete" my view before using addSubView ?
I tried with removeFromSuperView, but I think I'm not using it right.

Thanks for helping, as I said I'm really new and I am aware it can be a stupid question :/


问:
Android background notifications with Firebase Cloud Messaging not received
I've searched a lot about notifications when the app is in the background or closed. I'm using Firebase Cloud Messaging by the way. It won't work for me. I've used the Android setup and when the app is in the foreground or the phone is not locked the notification is received.

When installed the token is printed correctly and subscribed to the topic.

When I send a notification when the app is active in the foreground (so screen is unlocked and app is shown) I receive the notification and title as stated in the onMessageReceived.

When I send a notification when the app is not shown but is still in recent apps and screen is unlocked I receive the notification with title and message as stated in notification payload.

When I send a notification when the app is not shown but is still in recent apps and screen is locked nothing is received.

When I send a notification when app is *closed and removed from recent apps nothing is received.

How can I change this so the app will always receive the notifications, even when closed or the phone is locked?

Ps. I read about the Doze modus with protected apps, even when I put my app with the protected ones I receive nothing. I'm testing on a Huawei P8 Lite.

AndroidManifest

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".activities.MainActivity"
        android:configChanges="orientation"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name=".services.MyAppFirebaseMessagingService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".services.FirebaseIDService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <receiver android:name=".services.NotificationReceiver" />
</application>
</code>```

Gradle

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
}

apply plugin: 'com.google.gms.google-services'
</code>```

FirebaseMessagingService

```<code>public class MyAppFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        showNotification(getApplicationContext());
    }

    public static void showNotification(Context context){
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("FCM Body")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}
</code>```

FirebaseInstanceIDService

```<code>public class FirebaseIDService extends FirebaseInstanceIdService {

    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        System.out.println("Devicetoken: " + refreshedToken);

        FirebaseMessaging.getInstance().subscribeToTopic("/topics/myapp");

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
     }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
         // Add custom implementation, as needed.
    }
}
</code>```

Notification payload

```<code>{
    "to": "/topics/mytopic",
    "priority": "high",
    "notification": {
        "sound": "default",
        "badge": "1",
        "body": "the body text",
        "title": "title text"
     },
     "data": {
         "id": "id",
         "channel": "channel"
     }
}
</code>```

EDIT - Add code for WakeFulBroadcastReceiver

```<code>public class NotificationReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // cancel any further alarms
        AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmMgr.cancel(alarmIntent);
        completeWakefulIntent(intent);

        // start the GcmTaskService
        MyAppFirebaseMessagingService.showNotification(context);
    }
}
</code>```

UPDATE PAYLOAD

If I change my payload to the suggested way in the comments like this it is still not working. Maybe it has something to do with the Huawei P8 Lite that I'm testing on with Android 6.0.1 installed.

```<code>{
    "to": "/topics/mytopic",
    "priority": "high",
    "data": {
        "sound": "default",
        "badge": "1",
        "body": "the body text",
        "title": "title text"
    }
}
</code>```

UPDATE 2.0

I've tested on multiple devices and versions. On devices with Android 5 it was working fine, also without app open and screen locked. Only device it wasn't working was my own Huawei P8 Lite. Still can't figure out why it's not working on that one.

答:
Firebase has different types of notifications, and each has special handling.

Assuming you're using a data push, you don't need special handling or a WakefulBroadcastReceiver.

If you're using a notification push, the notification will appear automatically in the system tray. You cannot do any special handling there.

Check the official documents here: https://firebase.google.com/docs/cloud-messaging/android/receive

Body:
I've searched a lot about notifications when the app is in the background or closed. I'm using Firebase Cloud Messaging by the way. It won't work for me. I've used the Android setup and when the app is in the foreground or the phone is not locked the notification is received.

When installed the token is printed correctly and subscribed to the topic.

When I send a notification when the app is active in the foreground (so screen is unlocked and app is shown) I receive the notification and title as stated in the onMessageReceived.

When I send a notification when the app is not shown but is still in recent apps and screen is unlocked I receive the notification with title and message as stated in notification payload.

When I send a notification when the app is not shown but is still in recent apps and screen is locked nothing is received.

When I send a notification when app is *closed and removed from recent apps nothing is received.

How can I change this so the app will always receive the notifications, even when closed or the phone is locked?

Ps. I read about the Doze modus with protected apps, even when I put my app with the protected ones I receive nothing. I'm testing on a Huawei P8 Lite.

AndroidManifest

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".activities.MainActivity"
        android:configChanges="orientation"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name=".services.MyAppFirebaseMessagingService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
    <service
        android:name=".services.FirebaseIDService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
    </service>
    <receiver android:name=".services.NotificationReceiver" />
</application>

Gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.google.firebase:firebase-core:9.2.0'
    compile 'com.google.firebase:firebase-messaging:9.2.0'
}

apply plugin: 'com.google.gms.google-services'

FirebaseMessagingService

public class MyAppFirebaseMessagingService extends FirebaseMessagingService {
    private static final String TAG = "FCM Service";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // TODO: Handle FCM messages here.
        // If the application is in the foreground handle both data and notification messages here.
        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated.
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());

        showNotification(getApplicationContext());
    }

    public static void showNotification(Context context){
        Intent intent = new Intent(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("FCM Body")
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setPriority(Notification.PRIORITY_MAX)
            .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

FirebaseInstanceIDService

public class FirebaseIDService extends FirebaseInstanceIdService {

    private static final String TAG = "FirebaseIDService";

    @Override
    public void onTokenRefresh() {
        // Get updated InstanceID token.
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);

        System.out.println("Devicetoken: " + refreshedToken);

        FirebaseMessaging.getInstance().subscribeToTopic("/topics/myapp");

        // TODO: Implement this method to send any registration to your app's servers.
        sendRegistrationToServer(refreshedToken);
     }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
         // Add custom implementation, as needed.
    }
}

Notification payload

{
    "to": "/topics/mytopic",
    "priority": "high",
    "notification": {
        "sound": "default",
        "badge": "1",
        "body": "the body text",
        "title": "title text"
     },
     "data": {
         "id": "id",
         "channel": "channel"
     }
}

EDIT - Add code for WakeFulBroadcastReceiver

public class NotificationReceiver extends WakefulBroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        // cancel any further alarms
        AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmMgr.cancel(alarmIntent);
        completeWakefulIntent(intent);

        // start the GcmTaskService
        MyAppFirebaseMessagingService.showNotification(context);
    }
}

UPDATE PAYLOAD

If I change my payload to the suggested way in the comments like this it is still not working. Maybe it has something to do with the Huawei P8 Lite that I'm testing on with Android 6.0.1 installed.

{
    "to": "/topics/mytopic",
    "priority": "high",
    "data": {
        "sound": "default",
        "badge": "1",
        "body": "the body text",
        "title": "title text"
    }
}

UPDATE 2.0

I've tested on multiple devices and versions. On devices with Android 5 it was working fine, also without app open and screen locked. Only device it wasn't working was my own Huawei P8 Lite. Still can't figure out why it's not working on that one.


问:
Print model summary in R markdown without running model
I have run a logistic mixed model that took about 3 hours to fit. I saved the model as an object in my global environment, and I want to include the model summary in my R markdown document. However, I don't want knitr to run the model when putting the html together (that would take 3 more hours to run). I just want to print the summary of the model I've already run.

Knitr throws an error saying that the model object isn't in its scope.

How do I get knitr to access the model object I've already created and not re-run the model when compiling the document?

答:
I would save the model as an RDS object, and then load it in the RMarkdown document. You can then load the RDS object, while hiding this fact if you want to simply present the code that you ran. For example, see the code below which would fit and save/reload a linear model:

```<code>fit <- lm(x ~ y)
saveRDS(fit, "fit.RDS")
</code>```

Then, in the RMarkdown document

```<code>## (if you do not wish to hide the fact that you are loading it, then omit `echo = FALSE`)
```{r, echo = FALSE}
fit <- readRDS("fit.RDS")
## To show the code that fit the model.
## `eval = FALSE` means the code is not run while knitting.
```{r, eval = FALSE}
fit <- lm(x ~ y)
```
```

Body:
I would save the model as an RDS object, and then load it in the RMarkdown document. You can then load the RDS object, while hiding this fact if you want to simply present the code that you ran. For example, see the code below which would fit and save/reload a linear model:

fit <- lm(x ~ y)
saveRDS(fit, "fit.RDS")

Then, in the RMarkdown document

## (if you do not wish to hide the fact that you are loading it, then omit `echo = FALSE`)
```{r, echo = FALSE}
fit <- readRDS("fit.RDS")
## To show the code that fit the model.
## `eval = FALSE` means the code is not run while knitting.
```{r, eval = FALSE}
fit <- lm(x ~ y)
```


问:
Find the line with all caps in Regex Python
I'm trying to find all lines that are all caps using regex, and so far I've tried this:

```<code>re.findall(r'\b\n|[A-Z]+\b', kaizoku)
</code>```

So far my database is as follows:

```<code>TRAFALGAR LAW
You shall not be the pirate king.
MONKEY D LUFFY
Now!
DOFLAMINGO'S UNDERLINGS:
Noooooo!
</code>```

I want it to return

```<code>TRAFALGAR LAW
MONKEY D LUFFY
DOFLAMINGO'S UNDERLINGS:
</code>```

But it's returning something else.
(Namely this:

```<code>TRAFALGAR
LAW
Y
MONKEY
D
LUFFY
N
DOFLAMINGO'
S
UNDERLINGS:
N
</code>```

EDIT
So far I really think the best fit for the answer is @Jan's answer

```<code>rx = re.compile(r"^([A-Z ':]+$)\b", re.M)
rx.findall(string)
</code>```

EDIT2 Found out what's wrong, thanks!

答:
Brief

No need for regex, python has the method isupper()

Return true if all cased characters[4] in the string are uppercase and there is at least one cased character, false otherwise.

[4] Cased characters are those with general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase).

Code

See code in use here

```<code>a = [
    "TRAFALGAR LAW",
    "You shall not be the pirate king.",
    "MONKEY D LUFFY",
    "Now!",
    "DOFLAMINGO'S UNDERLINGS:",
    "Noooooo!",
]

for s in a:
    print s.isupper()
</code>```

Result

```<code>True
False
True
False
True
False
</code>```

Body:
I'm trying to find all lines that are all caps using regex, and so far I've tried this:

re.findall(r'\b\n|[A-Z]+\b', kaizoku)

So far my database is as follows:

TRAFALGAR LAW
You shall not be the pirate king.
MONKEY D LUFFY
Now!
DOFLAMINGO'S UNDERLINGS:
Noooooo!

I want it to return

TRAFALGAR LAW
MONKEY D LUFFY
DOFLAMINGO'S UNDERLINGS:

But it's returning something else.
(Namely this:

TRAFALGAR
LAW
Y
MONKEY
D
LUFFY
N
DOFLAMINGO'
S
UNDERLINGS:
N

EDIT
So far I really think the best fit for the answer is @Jan's answer

rx = re.compile(r"^([A-Z ':]+$)\b", re.M)
rx.findall(string)

EDIT2 Found out what's wrong, thanks!

Body:
Brief

No need for regex, python has the method isupper()

Return true if all cased characters[4] in the string are uppercase and there is at least one cased character, false otherwise.

[4] Cased characters are those with general category property being one of “Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase).

Code

See code in use here

a = [
    "TRAFALGAR LAW",
    "You shall not be the pirate king.",
    "MONKEY D LUFFY",
    "Now!",
    "DOFLAMINGO'S UNDERLINGS:",
    "Noooooo!",
]

for s in a:
    print s.isupper()

Result

True
False
True
False
True
False


问:
Add column to SELECT IF Row Count > 1
Any suggestions or ideas are welcomed and maybe it can't be done... here is my main SELECT :

```<code>SELECT * From(
SELECT MODATA.CITEM, MODATA.QTREQ, MODATA.UNMSR, MODATA.CDESC, MODATA.USRSQ AS SQ, MODATA.OPRWU, SLQNTY.LLOCN, SLQNTY.LQNTY, ROW_NUMBER()     OVER (PARTITION BY CITEM ORDER By CITEM) as L, MODATA.FLSTK,
MODATA.ISQTY, (QTREQ - ISQTY) as finalQty, SLQNTY.HOUSE, MOMAST.FITWH
FROM MODATA
LEFT OUTER JOIN SLQNTY ON SLQNTY.ITNBR = MODATA.CITEM
LEFT OUTER JOIN MOMAST ON MOMAST.ORDNO = MODATA.ORDNO
WHERE MODATA.ORDNO = 'M889360'  AND FLSTK != 'U' AND FLSTK != 'C' AND (SLQNTY.HOUSE=MOMAST.FITWH OR HOUSE IS NULL)) AS X
</code>```

Which pulls up all items and if an item has more than 1 it does the row count which then I do this to only bring me the 1st item in the list

```<code>WHERE X.L = 1
ORDER BY X.SQ
</code>```

My data before I do  the WHERE X.L = 1 looks like this:

My issue is... i want to have another column on the right that shows an X or a 1 IF the item has more than one row... then I can do a sort by that to put the multiple location items at the top.  Any ideas I'm drawing blanks as to if it can be done.  Ideally want to sort by X then I'll do my X.L = 1 to only pull the item once but still have a trigger to show that there is more than one location on that item.

答:
Got it working!</p>

```<code>SELECT * From(
SELECT MODATA.CITEM, MODATA.QTREQ, MODATA.UNMSR, MODATA.CDESC, MODATA.USRSQ AS SQ, MODATA.OPRWU, SLQNTY.LLOCN, SLQNTY.LQNTY, ROW_NUMBER() OVER (PARTITION BY CITEM ORDER By CITEM) as L, MODATA.FLSTK,
MODATA.ISQTY, (QTREQ - ISQTY) as finalQty, SLQNTY.HOUSE, MOMAST.FITWH, (SELECT COUNT(*) FROM SLQNTY WHERE SLQNTY.ITNBR = MODATA.CITEM AND SLQNTY.LQNTY != 0  AND (SLQNTY.HOUSE=MOMAST.FITWH OR HOUSE IS NULL)) AS T
FROM MODATA
LEFT OUTER JOIN SLQNTY ON SLQNTY.ITNBR = MODATA.CITEM
LEFT OUTER JOIN MOMAST ON MOMAST.ORDNO = MODATA.ORDNO
WHERE MODATA.ORDNO = 'M838860'  AND FLSTK != 'U' AND FLSTK != 'C' AND (SLQNTY.HOUSE=MOMAST.FITWH OR HOUSE IS NULL)) AS X
WHERE X.L = 1
ORDER BY X.T DESC
</code>```

Title: Add column to SELECT IF Row Count > 1

Body:
Any suggestions or ideas are welcomed and maybe it can't be done... here is my main SELECT :

SELECT * From(
SELECT MODATA.CITEM, MODATA.QTREQ, MODATA.UNMSR, MODATA.CDESC, MODATA.USRSQ AS SQ, MODATA.OPRWU, SLQNTY.LLOCN, SLQNTY.LQNTY, ROW_NUMBER()     OVER (PARTITION BY CITEM ORDER By CITEM) as L, MODATA.FLSTK,
MODATA.ISQTY, (QTREQ - ISQTY) as finalQty, SLQNTY.HOUSE, MOMAST.FITWH
FROM MODATA
LEFT OUTER JOIN SLQNTY ON SLQNTY.ITNBR = MODATA.CITEM
LEFT OUTER JOIN MOMAST ON MOMAST.ORDNO = MODATA.ORDNO
WHERE MODATA.ORDNO = 'M889360'  AND FLSTK != 'U' AND FLSTK != 'C' AND (SLQNTY.HOUSE=MOMAST.FITWH OR HOUSE IS NULL)) AS X

Which pulls up all items and if an item has more than 1 it does the row count which then I do this to only bring me the 1st item in the list

WHERE X.L = 1
ORDER BY X.SQ

My data before I do  the WHERE X.L = 1 looks like this:

My issue is... i want to have another column on the right that shows an X or a 1 IF the item has more than one row... then I can do a sort by that to put the multiple location items at the top.  Any ideas I'm drawing blanks as to if it can be done.  Ideally want to sort by X then I'll do my X.L = 1 to only pull the item once but still have a trigger to show that there is more than one location on that item.

Body:
Got it working!

SELECT * From(
SELECT MODATA.CITEM, MODATA.QTREQ, MODATA.UNMSR, MODATA.CDESC, MODATA.USRSQ AS SQ, MODATA.OPRWU, SLQNTY.LLOCN, SLQNTY.LQNTY, ROW_NUMBER() OVER (PARTITION BY CITEM ORDER By CITEM) as L, MODATA.FLSTK,
MODATA.ISQTY, (QTREQ - ISQTY) as finalQty, SLQNTY.HOUSE, MOMAST.FITWH, (SELECT COUNT(*) FROM SLQNTY WHERE SLQNTY.ITNBR = MODATA.CITEM AND SLQNTY.LQNTY != 0  AND (SLQNTY.HOUSE=MOMAST.FITWH OR HOUSE IS NULL)) AS T
FROM MODATA
LEFT OUTER JOIN SLQNTY ON SLQNTY.ITNBR = MODATA.CITEM
LEFT OUTER JOIN MOMAST ON MOMAST.ORDNO = MODATA.ORDNO
WHERE MODATA.ORDNO = 'M838860'  AND FLSTK != 'U' AND FLSTK != 'C' AND (SLQNTY.HOUSE=MOMAST.FITWH OR HOUSE IS NULL)) AS X
WHERE X.L = 1
ORDER BY X.T DESC


问:
Locate a TempVar in a MS Access main form and write it to a table connected to the subform
I need to add some VBA code to a checkbox located on a subform of my front end Access 2016 database.

The goal is to insert to a table the value contained in a textbox located in the main form.

So far, the steps I took are:

Click on the checkbox located on the subform;

Create a temporary variable;

Insert the temporary variable into the related table;

Move on to the next item.

The code is the following:

```<code>    Option Compare Database

    Private Sub AssegnatoCampione_Click()

        'Create temporary variable and store the selected value
        TempVars("NumeroCampione").Value = Forms!FormCampioni2.SampleNo.Value

        'Write the value in the database
        CurrentDb.Execute " INSERT INTO DB_Offerte2017 " _
                        & "([NumeroCampione]) VALUES " _
                        & "(" & TempVars![NumeroCampione] & ")" ', dbFailOnError
    End Sub
</code>```

The error I get is: .

"Too few parameters. Expected 1."

Is there a way to know whether the variable is stored correctly or not?

Thank you so much for your help.

Edit 1:

Ok, so i guess that the error was due to DB_Offerte2017([NumeroCampione]) being a text field. I corrected the code in this way:

```<code>CurrentDb.Execute "INSERT INTO DB_Offerte2017 ( NumeroCampione ) VALUES ('" & Me.Parent.SampleNo & "')", dbFailOnError
</code>```

This way, every time I click on the check box, a new record is added in the table "DB_Offerte2017", under the field "NumeroCampione".

However, I need to add those records to the same row where the checkboxes is located (e.g. Click on checkbox where ID = 2438 -> Add "SampleNo" value on DB_Offerte2017.NumeroCampione where ID = 2438).

Is it possible to add a where statement in the code?

答:
Why not just a normal VBA variable or just reference the control? Code is behind subform and field/control on main form? Try:

CurrentDb.Execute "INSERT INTO DB_Offerte2017([NumeroCampione]) VALUES (" & Me.Parent.SampleNo & ")", dbFailOnError.

Body:
I need to add some VBA code to a checkbox located on a subform of my front end Access 2016 database.

The goal is to insert to a table the value contained in a textbox located in the main form.

So far, the steps I took are:

Click on the checkbox located on the subform;

Create a temporary variable;

Insert the temporary variable into the related table;

Move on to the next item.

The code is the following:

    Option Compare Database

    Private Sub AssegnatoCampione_Click()

        'Create temporary variable and store the selected value
        TempVars("NumeroCampione").Value = Forms!FormCampioni2.SampleNo.Value

        'Write the value in the database
        CurrentDb.Execute " INSERT INTO DB_Offerte2017 " _
                        & "([NumeroCampione]) VALUES " _
                        & "(" & TempVars![NumeroCampione] & ")" ', dbFailOnError
    End Sub

The error I get is: .

"Too few parameters. Expected 1."

Is there a way to know whether the variable is stored correctly or not?

Thank you so much for your help.

Edit 1:

Ok, so i guess that the error was due to DB_Offerte2017([NumeroCampione]) being a text field. I corrected the code in this way:

CurrentDb.Execute "INSERT INTO DB_Offerte2017 ( NumeroCampione ) VALUES ('" & Me.Parent.SampleNo & "')", dbFailOnError

This way, every time I click on the check box, a new record is added in the table "DB_Offerte2017", under the field "NumeroCampione".

However, I need to add those records to the same row where the checkboxes is located (e.g. Click on checkbox where ID = 2438 -> Add "SampleNo" value on DB_Offerte2017.NumeroCampione where ID = 2438).

Is it possible to add a where statement in the code?


问:
Automata Turing
Could someone explain the question below step by step?

Suppose that Σ is a finite set and that L1, L2 and L3 are Turing acceptable subsets of Σ^* that satisfy the following properties:
L1 ∪ L2 ∪ L3 = Σ^∗
; L1 ∩ L2 = L2 ∩ L3 = L3 ∩ L1 = ∅.
Show that L1, L2 and L3 must all be recursive.

答:
We are given that:

```<code>L1 union L2 union L3 = E*
L1 intersect L2 = {}
L1 intersect L3 = {}
L2 intersect L3 = {}
L1 is acceptable/semidecidable/recursively enumerable/recognizable
L2 is acceptable/semidecidable/recursively enumerable/recognizable
L3 is acceptable/semidecidable/recursively enumerable/recognizable
</code>```

We need to show that L1, L2 and L3 are rejectable/decidable/recursive/co-recognizable.

Can we show that a string is not in L1? Yes. Because the union of these three languages contains all strings, and because no two languages overlap, we know that any string not in L1 is in either L2 or L3. Because these languages are acceptable/semidecidable/recursively enumerable/recognizable, we have TMs TM2 and TM3 which will eventually accept/decide/enumerate/recognize strings in L2 and L3, respectively. In order to recognize a string is not in L1, we can set T2 and T3 running and see whether either one ever accepts/decides/enumerates/recognizes the string, in which case we know that L1 must not.

We now know that L1 is both acceptable/recursively enumerable/recognizable and, simultaneously, rejectable//co-recursively enumerable/co-recognizable. Languages such as this are decidable/recursive.

Because L1, L2 and L3 were numbered arbitrarily, any result that applies to L1 must apply to L2 and L3 as well, since we might as well have considered these other languages to be L1. In other words, the exact same argument given above applies if you swap L1 with either L2 or L3.

Therefore, each of the three languages is decidable/recursive.

Title: Automata Turing

Body:
We are given that:

L1 union L2 union L3 = E*
L1 intersect L2 = {}
L1 intersect L3 = {}
L2 intersect L3 = {}
L1 is acceptable/semidecidable/recursively enumerable/recognizable
L2 is acceptable/semidecidable/recursively enumerable/recognizable
L3 is acceptable/semidecidable/recursively enumerable/recognizable

We need to show that L1, L2 and L3 are rejectable/decidable/recursive/co-recognizable.

Can we show that a string is not in L1? Yes. Because the union of these three languages contains all strings, and because no two languages overlap, we know that any string not in L1 is in either L2 or L3. Because these languages are acceptable/semidecidable/recursively enumerable/recognizable, we have TMs TM2 and TM3 which will eventually accept/decide/enumerate/recognize strings in L2 and L3, respectively. In order to recognize a string is not in L1, we can set T2 and T3 running and see whether either one ever accepts/decides/enumerates/recognizes the string, in which case we know that L1 must not.

We now know that L1 is both acceptable/recursively enumerable/recognizable and, simultaneously, rejectable//co-recursively enumerable/co-recognizable. Languages such as this are decidable/recursive.

Because L1, L2 and L3 were numbered arbitrarily, any result that applies to L1 must apply to L2 and L3 as well, since we might as well have considered these other languages to be L1. In other words, the exact same argument given above applies if you swap L1 with either L2 or L3.

Therefore, each of the three languages is decidable/recursive.