问:
retrieve array from mongodb using java with mongodb api
I understand that there are many questions which as for the same and they are answered well. The problem is all those questions use MongoDBObject, MongoDBList to retrieve arrays. My problem is I am using http://api.mongodb.org/java/3.0/index.html?overview-summary.html api and I am having hard time retrieving array and adding elements to it. I have to use MongoCollection, MongoDatabase and MongoClient. I am trying to solve an assignment from mongodb course. The problem statement is to find an array and update it in mongod.

Here is what I have tried

```<code>      Document post = null; Bson filter = new Document("permalink",
      permalink); Bson projection = new Document("comments", true);
      List<Document> comments = postsCollection.find(filter)
      .projection(projection).into(new ArrayList<Document>());
      System.out.println(comments);

      post = postsCollection.find(Filters.eq("permalink",
      permalink)).first();

      Document newComment = new Document();

      newComment.append("author", name); newComment.append("body", body);
      if (email != null && (!email.equals(""))) {
      newComment.append("email", email); }

      comments.add(newComment);

      Bson filter2 = new Document("_id", post.get("_id"));
      System.out.println(comments); post =
      postsCollection.find(filter).first();

      postsCollection.updateOne(filter2, new Document("$unset",new
      Document("comments",true))); postsCollection.updateOne(filter2, new
      Document("$set", new Document( "comments", comments)));
</code>```

This does not create a new comment. Instead, it creates another comments array in comments array itself. THe array should be updated in student

Here is the json data

```<code>{
"_id" : ObjectId("55d965eee60dd20c14e8573e"),
"title" : "test title",
"author" : "prasad",
"body" : "test body",
"permalink" : "test_title",
"tags" : [
    "test",
    "teat"
],
"date" : ISODate("2015-08-23T06:19:26.826Z"),
"comments" : [
    {
        "_id" : ObjectId("55d965eee60dd20c14e8573e"),
        "comments" : [
            {
                "_id" : ObjectId("55d965eee60dd20c14e8573e"),
                "comments" : []
            },
            {
                "author" : "commented",
                "body" : "something in comment",
                "email" : "some@thing.com"
            }
        ]
    },
    {
        "author" : "commented",
        "body" : "something in comment",
        "email" : "some@thing.com"
    }
]
</code>```

}

答:
To avoid unchecked casts and linter warnings, along with writing your own loop, use the libary's get(final Object key, final Class<T> clazz) method:

```<code>List<Document> comments = posts.get("comments", docClazz)
</code>```

where docClazz is something that you create once:

```<code>final static Class<? extends List> docClazz = new ArrayList<Document>().getClass();
</code>```

Body:
I understand that there are many questions which as for the same and they are answered well. The problem is all those questions use MongoDBObject, MongoDBList to retrieve arrays. My problem is I am using http://api.mongodb.org/java/3.0/index.html?overview-summary.html api and I am having hard time retrieving array and adding elements to it. I have to use MongoCollection, MongoDatabase and MongoClient. I am trying to solve an assignment from mongodb course. The problem statement is to find an array and update it in mongod.

Here is what I have tried

      Document post = null; Bson filter = new Document("permalink",
      permalink); Bson projection = new Document("comments", true);
      List<Document> comments = postsCollection.find(filter)
      .projection(projection).into(new ArrayList<Document>());
      System.out.println(comments);

      post = postsCollection.find(Filters.eq("permalink",
      permalink)).first();

      Document newComment = new Document();

      newComment.append("author", name); newComment.append("body", body);
      if (email != null && (!email.equals(""))) {
      newComment.append("email", email); }

      comments.add(newComment);

      Bson filter2 = new Document("_id", post.get("_id"));
      System.out.println(comments); post =
      postsCollection.find(filter).first();

      postsCollection.updateOne(filter2, new Document("$unset",new
      Document("comments",true))); postsCollection.updateOne(filter2, new
      Document("$set", new Document( "comments", comments)));

This does not create a new comment. Instead, it creates another comments array in comments array itself. THe array should be updated in student

Here is the json data

{
"_id" : ObjectId("55d965eee60dd20c14e8573e"),
"title" : "test title",
"author" : "prasad",
"body" : "test body",
"permalink" : "test_title",
"tags" : [
    "test",
    "teat"
],
"date" : ISODate("2015-08-23T06:19:26.826Z"),
"comments" : [
    {
        "_id" : ObjectId("55d965eee60dd20c14e8573e"),
        "comments" : [
            {
                "_id" : ObjectId("55d965eee60dd20c14e8573e"),
                "comments" : []
            },
            {
                "author" : "commented",
                "body" : "something in comment",
                "email" : "some@thing.com"
            }
        ]
    },
    {
        "author" : "commented",
        "body" : "something in comment",
        "email" : "some@thing.com"
    }
]

}

Body:
To avoid unchecked casts and linter warnings, along with writing your own loop, use the libary's get(final Object key, final Class<T> clazz) method:

List<Document> comments = posts.get("comments", docClazz)

where docClazz is something that you create once:

final static Class<? extends List> docClazz = new ArrayList<Document>().getClass();


来源: stackexchange

问:
How can I change where lazy-loading Angular 2 looks for chunks?
I have set up lazy loading in my Angular 2 project using the loadChildren syntax. The problem I have is that after chunks are created, the browser doesn't seem to know where to look to find them. It always tries to load chunks from the root directory, e.g. http://localhost:55626/1.chunk.js. This is of course not where they're stored.

I've been able to work around this issue by bundling the chunks using the .NET bundler, but of course this means they're all loaded at start and defeats the purpose of using lazy loading. I'm guessing that this is an issue with webpack defaulting to look in the wrong place for chunks created during ng build but I'm not confident about that, and even if I'm right, I understand that projects built with angular-cli currently do not support a custom webpack.config.js.

Can anyone shed some insight on this problem? Thanks!

I am using Angular 2.4.6.

Edit: To clarify, I build this project using angular-cli, which doesn't support custom webpack.config files, per https://github.com/angular/angular-cli/issues/1656#issuecomment-240171375

答:
It turns out there is a setting in the angular-cli.json file that controls this:

```<code>{
  "apps": [
    {
      "deployUrl": "./path/to/files/"
    }
  ]
}
</code>```

I believe deployUrl should point to the sources output by ng build so they can be bundled up as needed by angular-cli. Note that the path must end in a slash ("/") for lazy-loading to work.

Adding this property fixed the problem for me and I am now loading as lazily as I do everything else.

See https://github.com/angular/angular-cli/issues/5652

ContentLicense: CC BY-SA 3.0

Body:
It turns out there is a setting in the angular-cli.json file that controls this:

{
  "apps": [
    {
      "deployUrl": "./path/to/files/"
    }
  ]
}

I believe deployUrl should point to the sources output by ng build so they can be bundled up as needed by angular-cli. Note that the path must end in a slash ("/") for lazy-loading to work.

Adding this property fixed the problem for me and I am now loading as lazily as I do everything else.

See https://github.com/angular/angular-cli/issues/5652

ContentLicense: CC BY-SA 4.0


问:
C# - Splitting the string when there are 3 chars and adding the values to the dictionary
I have a string like this:

```<code>var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";
</code>```

It's dynamically created, so this one is just for the sake of example. Numbers represent how many portions are ordered. I need to split it to dictionary by the name of food as a key and count how many portions are ordered which would be a value.

I've tried this for spliting the string, first by '\n' then by ' - ':

```<code>count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));
</code>```

but I get an error "cannot convert from string to char. I had to use double quotes, because " - " this has 3 chars (2 spaces and a dash) and it's not recognized as a char.

Also, I think the problem will be when I start adding food, because it will report that keys won't be unique, considering that food appears more than once. How to solve this?

EDIT:

When I try this:

```<code>string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);
</code>```

I get error at .Split

```<code>'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found
</code>```

and if I try this "string countOrders =" (so without []) I get

```<code>Cannot implicitly convert type 'string[]' to 'string'
</code>```

I don't understand how am I suppose to split the string by '\n' and then to split it by " - ", when it gives me errors in both cases?

答:
You need to split and get rid of empty entries.

You can split on '-', no need to split on " - "

Then, Group by and sum to get a total dictionary

```<code>Dictionary<string, int> count =
    totalOrders.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries)
        .Select(item => item.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries))
        .Select(arg=> new {Key = arg[0].Trim(), Val=  int.Parse(arg[1].Trim())})
        .GroupBy(arg=>arg.Key)
        .ToDictionary(g => g.Key, g => g.Sum(arg=>arg.Val));
</code>```

Body:
I have a string like this:

var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";

It's dynamically created, so this one is just for the sake of example. Numbers represent how many portions are ordered. I need to split it to dictionary by the name of food as a key and count how many portions are ordered which would be a value.

I've tried this for spliting the string, first by '\n' then by ' - ':

count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));

but I get an error "cannot convert from string to char. I had to use double quotes, because " - " this has 3 chars (2 spaces and a dash) and it's not recognized as a char.

Also, I think the problem will be when I start adding food, because it will report that keys won't be unique, considering that food appears more than once. How to solve this?

EDIT:

When I try this:

string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);

I get error at .Split

'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found

and if I try this "string countOrders =" (so without []) I get

Cannot implicitly convert type 'string[]' to 'string'

I don't understand how am I suppose to split the string by '\n' and then to split it by " - ", when it gives me errors in both cases?

Body:
You need to split and get rid of empty entries.

You can split on '-', no need to split on " - "

Then, Group by and sum to get a total dictionary

Dictionary<string, int> count =
    totalOrders.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries)
        .Select(item => item.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries))
        .Select(arg=> new {Key = arg[0].Trim(), Val=  int.Parse(arg[1].Trim())})
        .GroupBy(arg=>arg.Key)
        .ToDictionary(g => g.Key, g => g.Sum(arg=>arg.Val));


问:
Printing nested json data in Laravel view
below is the Json returned from controller to view

JSon Data

```<code>   [
       {
          "id":2,
          "firstname":"abc",
          "lastname":"def",
          "email":"abc@ab.ac.uk",
          "role":1,
          "university":1,
          "school_dept":5,
          "year":2,
          "photo":"URL",
          "bio":"ObxBJIDO6IfOU0DIw8a5",
          "search_status":"available",
          "created_at":null,
          "updated_at":null,
          "languages":[
             {
                "id":3,
                "language":"Spanish",
                "pivot":{
                   "user_id":2,
                   "language_id":3,
                   "type":"native"
                }
             },
             {
                "id":4,
                "language":"Greek",
                "pivot":{
                   "user_id":2,
                   "language_id":4,
                   "type":"learn"
                }
             }
          ],
          "hobbies":[
             {
                "id":2,
                "hobby":"Basketball",
                "pivot":{
                   "user_id":2,
                   "hobbie_id":2
                }
             },
             {
                "id":3,
                "hobby":"Skiing",
                "pivot":{
                   "user_id":2,
                   "hobbie_id":3
                }
             },
             {
                "id":4,
                "hobby":"Running",
                "pivot":{
                   "user_id":2,
                   "hobbie_id":4
                }
             }
          ],
          "universities":{
             "id":1,
             "university":"some Uni"
          },
          "years":{
             "id":2,
             "year":"2nd"
          },
          "departments":{
             "id":5,
             "department":"Languages and Intercultural Studies"
          }
       }
    ]
</code>```

I am able to pull id, firstname,lastname, email, ... first level data

```<code>@foreach($users as $user)
 <tr>
      <td>{{$user->firstname}} </td>
      <td>{{$user->lastname}} </td>
      <td>{{$user->email}} </td>
      <td>{{$user->photo}} </td>
      <td>{{$user->bio}} </td>
      <td></td>
    </tr>

@endforeach
</code>```

Also, departments, university and years              second level nested data

```<code><td>{{$user['universities']->university}} </td>
<td>{{$user['departments']->department}} </td>
<td>{{$user['languages']->language}} </td>
<td>{{$user['years']->year}} </td>
</code>```

But how to pull third level nested data plus its a type of array.

for example: Hobbies and Languages both.

I want to show languages like: learn : English and  teach: French  this has to be achieved by checking if type field is learn or teach in language array with a field called type. which tells if a user wants to learn a specific language or teach that language. All users have learn and teach both types.

Also, for list of hobbies like: hobby1, hobby2, hobby3,...

I want to show this most neatest and efficient way possible

Below is the technique I am trying to show level 3 data but if condition does not seem to work. I need to get the language as per the type.

```<code>@foreach($user->languages as $langs)
   @if($langs['pivot']->type =='native')
   <td>{{$langs['pivot']->language_id}}</td>
   @else
   <td>{{$langs['pivot']->language_id}}</td>
   @endif
@endforeach
</code>```

答:
I was having similar problem in Laravel to extract an image url. But I didn't need the for loop. So I thought I post the example.

Weather JSON.

```<code>{
  "coord": {
    "lon": -97.29,
    "lat": 32.63
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "02d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 297.61,
    "pressure": 1007,
    "humidity": 36,
    "temp_min": 296.15,
    "temp_max": 299.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 4.6,
    "deg": 200,
    "gust": 7.2
  },
  "clouds": {
    "all": 5
  },
  "dt": 1490813400,
  "sys": {
    "type": 1,
    "id": 2625,
    "message": 0.3809,
    "country": "US",
    "sunrise": 1490789980,
    "sunset": 1490834873
  },
  "id": 4689708,
  "name": "Everman",
  "cod": 200
}
</code>```

In the controller

```<code>    $restful_data=json_decode($res->getBody(), true);//to use in first and second level
    $restful_icon_array=$restful_data['weather']; //to use in third level
    $restful_icon = $restful_icon_array[0]; //second level is array

    return view('dashboard',['posts'=>$posts])
        ->with(['restful_data'=>$restful_data])//send array for second level
        ->with(['icon_weather'=>$restful_icon]);//send array for third level
</code>```

In the view

```<code> <p>{{$restful_data['coord']['lon']}}</p> //access to second level
 <img src="https://openweathermap.org/img/w/{{ $icon_weather['icon'] }}.png"> //access to third level
</code>```

Body:
below is the Json returned from controller to view

JSon Data

   [
       {
          "id":2,
          "firstname":"abc",
          "lastname":"def",
          "email":"abc@ab.ac.uk",
          "role":1,
          "university":1,
          "school_dept":5,
          "year":2,
          "photo":"URL",
          "bio":"ObxBJIDO6IfOU0DIw8a5",
          "search_status":"available",
          "created_at":null,
          "updated_at":null,
          "languages":[
             {
                "id":3,
                "language":"Spanish",
                "pivot":{
                   "user_id":2,
                   "language_id":3,
                   "type":"native"
                }
             },
             {
                "id":4,
                "language":"Greek",
                "pivot":{
                   "user_id":2,
                   "language_id":4,
                   "type":"learn"
                }
             }
          ],
          "hobbies":[
             {
                "id":2,
                "hobby":"Basketball",
                "pivot":{
                   "user_id":2,
                   "hobbie_id":2
                }
             },
             {
                "id":3,
                "hobby":"Skiing",
                "pivot":{
                   "user_id":2,
                   "hobbie_id":3
                }
             },
             {
                "id":4,
                "hobby":"Running",
                "pivot":{
                   "user_id":2,
                   "hobbie_id":4
                }
             }
          ],
          "universities":{
             "id":1,
             "university":"some Uni"
          },
          "years":{
             "id":2,
             "year":"2nd"
          },
          "departments":{
             "id":5,
             "department":"Languages and Intercultural Studies"
          }
       }
    ]

I am able to pull id, firstname,lastname, email, ... first level data

@foreach($users as $user)

      {{$user->firstname}}
      {{$user->lastname}}
      {{$user->email}}
      {{$user->photo}}
      {{$user->bio}}

@endforeach

Also, departments, university and years              second level nested data

{{$user['universities']->university}}
{{$user['departments']->department}}
{{$user['languages']->language}}
{{$user['years']->year}}

But how to pull third level nested data plus its a type of array.

for example: Hobbies and Languages both.

I want to show languages like: learn : English and  teach: French  this has to be achieved by checking if type field is learn or teach in language array with a field called type. which tells if a user wants to learn a specific language or teach that language. All users have learn and teach both types.

Also, for list of hobbies like: hobby1, hobby2, hobby3,...

I want to show this most neatest and efficient way possible

Below is the technique I am trying to show level 3 data but if condition does not seem to work. I need to get the language as per the type.

@foreach($user->languages as $langs)
   @if($langs['pivot']->type =='native')
   {{$langs['pivot']->language_id}}
   @else
   {{$langs['pivot']->language_id}}
   @endif
@endforeach

Body:
I was having similar problem in Laravel to extract an image url. But I didn't need the for loop. So I thought I post the example.

Weather JSON.

{
  "coord": {
    "lon": -97.29,
    "lat": 32.63
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "02d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 297.61,
    "pressure": 1007,
    "humidity": 36,
    "temp_min": 296.15,
    "temp_max": 299.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 4.6,
    "deg": 200,
    "gust": 7.2
  },
  "clouds": {
    "all": 5
  },
  "dt": 1490813400,
  "sys": {
    "type": 1,
    "id": 2625,
    "message": 0.3809,
    "country": "US",
    "sunrise": 1490789980,
    "sunset": 1490834873
  },
  "id": 4689708,
  "name": "Everman",
  "cod": 200
}

In the controller

    $restful_data=json_decode($res->getBody(), true);//to use in first and second level
    $restful_icon_array=$restful_data['weather']; //to use in third level
    $restful_icon = $restful_icon_array[0]; //second level is array

    return view('dashboard',['posts'=>$posts])
        ->with(['restful_data'=>$restful_data])//send array for second level
        ->with(['icon_weather'=>$restful_icon]);//send array for third level

In the view

 <p>{{$restful_data['coord']['lon']}}</p> //access to second level
 <img src="https://openweathermap.org/img/w/{{ $icon_weather['icon'] }}.png"> //access to third level


问:
Data transmission using RF with raspberryPi
I have a project that consisted of transmitting data wirelessly from 15 tractors to a station, the maximum distance between tractor and station is 13 miles. I used a raspberry pi 3 to collect data from tractors. with some research I found that there is no wifi or GSM coverage so the only solution is to use RF communication using VHF. so is that possible with raspberry pi or I must add a modem? if yes, what is the criterion for choosing a modem? and please if you have any other information tell me?
and thank you for your time.</p>

答:
Following on from the comments above, I'm not sure where you are located but spectrum around the 400mhz range is licensed in many countries so it would be worth checking exactly what you can use.

If this is your target then this is UHF rather than VHF so if you search for 'Raspberry PI UHF shield' or 'Raspberry PI UHF module' you will find some examples of cheap hardware you can add to your raspberry pi to support communication over these frequencies. Most of the results should include some software examples also.

There are also articles on using the pins on the PI to transmit directly by modulating the voltage them - this is almost certainly going to interfere with other communications so I doubt it would meet your needs.


问:
SQL Server - @@connections value increasing automatically?
I just started learning SQL Server v2014, about the global variables.

```<code>select @@CONNECTIONS conns, @@MAX_CONNECTIONS mx_conns;
</code>```

With every execution of this query, the value of @@CONNECTIONS is changing. As per the documentation, it says attempted successful/unsuccessful attempts. But, since it is a local installation, nobody else is trying to access it. How is the value changing?

Response much appreciated.

Regards,
Ranit

答: If you actually want to see what is triggering the increase here, set up a SQL Server Profiler trace on your local SQL instance to log everything. Let it run for a few minutes, then shut it off and look at the results.</p>

Body:
I just started learning SQL Server v2014, about the global variables.

select @@CONNECTIONS conns, @@MAX_CONNECTIONS mx_conns;

With every execution of this query, the value of @@CONNECTIONS is changing. As per the documentation, it says attempted successful/unsuccessful attempts. But, since it is a local installation, nobody else is trying to access it. How is the value changing?

Response much appreciated.

Regards,
Ranit


问:
how do you resolve JLabel?
When I tried to compile my code it said that JLabel can't be resolved and I'm not sure why since it works for me in the past.

here's my code so far:

```<code>import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.JLabel;

  public class build extends JFrame
  {
    private JLabel item1;
    public build(){
      super("coin flip");
      setLayout(new FlowLayout());

      item1 = new JLabel("This is coin flip game");
      item1.setToolTipText("Hover");
      add(item1);
    }
  }
</code>```

答:
```<code>import javax.JLabel;
</code>```

Should be:

```<code>import javax.swing.JLabel;
</code>```

Title: how do you resolve JLabel?

Body:
When I tried to compile my code it said that JLabel can't be resolved and I'm not sure why since it works for me in the past.

here's my code so far:

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.JLabel;

  public class build extends JFrame
  {
    private JLabel item1;
    public build(){
      super("coin flip");
      setLayout(new FlowLayout());

      item1 = new JLabel("This is coin flip game");
      item1.setToolTipText("Hover");
      add(item1);
    }
  }

Body:
import javax.JLabel;

Should be:

import javax.swing.JLabel;


问:
How to evaluate dimensionality reduction technique?
I have a dataset of NxM data in binary form. I apply a variety of dimensionality techniques on it and I plot the first two dimensions. This is how I get an intuition of whether the technique is suitable for my dataset or not. Is there a more appropriate/methodical/heuristic/formal way to test the suitability of the dimensionality reduction techniques I use? </p>

答:
The main purpose of applying dimensionality reduction on data is to capture the original data's distribution as much as possible even after the dimensionality reduction. Therefore, we want to make sure that we capture the variance of the data as much as we can.

Let's say you have a N*N matrix, and we perform SVD (Singular Value Decomposition) on X. Then, we'll observe the singular values, the diagonal entries in the resulting S matrix. (X = USV)

And you want to cut them off at some index K based on the desired percentage variance captured:

∑ i=1 K  sigma(i) / ∑ i=1 N  sigma(i)

If you select the first K columns of U, then you are reducing your original N-dimension to K-dimension.


问:
vba nested error handling
I am trying to understand how to set up error-handling for the situation cited below. Sub A has error handling for its own context. However it calls Sub B which creates database connection, resultsets etc which it cleans up in its error handler. The way it stands, it seems only ErrorHandler A is active throughout. How can I activate ErrorHandler B when B is called and revert back to error-handling after B returns.

Thanks

```<code>Sub A
' Preps for database access
On Error GoTo ErrorHandlerA

B
.
.

Exit Sub
ErrorHandlerA:
...
Resume
End Sub

Sub B
' Does database access stuff

On Error ErrorHandlerB

cleanUp:
con.close
rs.close

Exit Sub
ErrorHandlerB:
GoTo cleanup

End Sub
</code>```

答:
```<code>Exit Sub
ErrorHandlerA:
...
Resume
End Sub
</code>```

Resume here, resumes normal execution (clears "error handling mode") and jumps back to the instruction that caused the error. Presumably (hopefully?) the ... contains code that makes the previously-failing call, succeed.

```<code>cleanUp:
con.close
rs.close

Exit Sub
ErrorHandlerB:
GoTo cleanup

End Sub
</code>```

Here you're GoTo-jumping outside the error-handling subroutine, without resuming to normal execution, so the instructions under the cleanUp line label execute in an error-handling context. That should be Resume cleanUp, not GoTo.

The Exit Sub statement leaves the scope, which clears the error state and implicitly resumes to normal execution. Here's a little MCVE:

```<code>Public Sub Test()
On Error GoTo A
    DoSomething
    Debug.Print "After DoSomething: " & Err.Number
    Exit Sub
A:
    Debug.Print "Inside Test[A]: " & Err.Number
End Sub

Private Sub DoSomething()
On Error GoTo A

    Err.Raise 5

B:
    Debug.Print "Inside DoSomething[B]: " & Err.Number
    Exit Sub
A:
    Debug.Print "Inside DoSomething[A]: " & Err.Number
    Resume B
End Sub
</code>```

Running the Test procedure produces this output:

Inside DoSomething[A]: 5
Inside DoSomething[B]: 0
After DoSomething: 0
```

<p>Changing the <code>Resume B</code> instruction for a <code>GoTo B</code> produces this output:</p>

<pre class="lang-none prettyprint-override"><code>Inside DoSomething[A]: 5
Inside DoSomething[B]: 5
After DoSomething: 0
</code>```

As you can see, as the error was handled in DoSomething, error state is reset when execution returns to Test, and the handler in the Test procedure is never triggered.

If you want to propagate the error to the caller, you have a number of options:

Don't handle errors in the called procedure. In the above example this means DoSomething wouldn't have an On Error statement; any run-time errors would "bubble up" the call stack, and the output would look like this now:

```<code>Inside Test[A]: 5
</code>```

You would typically do this when it's the calling code that has the knowledge of what the best course of action would be (e.g. display a MsgBox to the user, or log the error, etc.).

Handle errors, and then re-raise them. In your example this means moving (or copying) the cleanup code into the ErrorHandlerB subroutine, and calling Err.Raise Err.Number instead of Resume. Or you keep the GoTo and then the cleanup subroutine can do If Err.Number <> 0 Then Err.Raise Err.Number to effectively re-throw the error for the caller to also handle. In other words:

```<code>Public Sub Test()
On Error GoTo A
    DoSomething
    Debug.Print "After DoSomething: " & Err.Number
    Exit Sub
A:
    Debug.Print "Inside Test[A]: " & Err.Number
End Sub

Private Sub DoSomething()
On Error GoTo A

    Err.Raise 5

B:
    Debug.Print "Inside DoSomething[B]: " & Err.Number
    If Err.Number <> 0 Then Err.Raise Err.Number
    Exit Sub
A:
    Debug.Print "Inside DoSomething[A]: " & Err.Number
    GoTo B 'resuming would clear the error and prevent rethrow
End Sub
</code>```

This outputs:

Inside DoSomething[A]: 5
Inside DoSomething[B]: 5
Inside Test[A]: 5
```</li>
</ul>

<p>Depending on the exact reason why you would want to handle the same error in two different places, you could also consider making <code>B</code> a <code>Function</code> that returns a <code>Boolean</code> indicating success or failure - in that case <code>A</code> no longer handles an <em>error</em> per se, but rather uses normal flow control to determine what to do:</p>

```Public Sub Test()
On Error GoTo A
    If Not DoSomething Then
        Debug.Print "After DoSomething failed: " & Err.Number
        Exit Sub
    End If
    Exit Sub
A:
    Debug.Print "Inside Test[A]: " & Err.Number
End Sub

Private Function DoSomething() As Boolean
'Dim success As Boolean
On Error GoTo A

    Err.Raise 5
    'success = True

B:
    Debug.Print "Inside DoSomething[B]: " & Err.Number
    DoSomething = (Err.Number = 0) 'DoSomething = success
    Exit Function
A:
    Debug.Print "Inside DoSomething[A]: " & Err.Number
    'success = False
    GoTo B 'Resume B
End Function
```

<p>Which produces this output:</p>

<pre class="lang-none prettyprint-override"><code>Inside DoSomething[A]: 5
Inside DoSomething[B]: 5
After DoSomething failed: 0
</code>```

Notice Test knows DoSomething failed, but Err.Number is 0. This is usually preferable to using runtime errors for flow control, again depending on your actual scenario. Also notice, the GoTo jump is avoidable in that situation, using a simple Boolean local variable to track your return value (the commented-out code).

Title: vba nested error handling

Body:
I am trying to understand how to set up error-handling for the situation cited below. Sub A has error handling for its own context. However it calls Sub B which creates database connection, resultsets etc which it cleans up in its error handler. The way it stands, it seems only ErrorHandler A is active throughout. How can I activate ErrorHandler B when B is called and revert back to error-handling after B returns.

Thanks

Sub A
' Preps for database access
On Error GoTo ErrorHandlerA

B
.
.

Exit Sub
ErrorHandlerA:
...
Resume
End Sub

Sub B
' Does database access stuff

On Error ErrorHandlerB

cleanUp:
con.close
rs.close

Exit Sub
ErrorHandlerB:
GoTo cleanup

End Sub

Body:
Exit Sub
ErrorHandlerA:
...
Resume
End Sub

Resume here, resumes normal execution (clears "error handling mode") and jumps back to the instruction that caused the error. Presumably (hopefully?) the ... contains code that makes the previously-failing call, succeed.

cleanUp:
con.close
rs.close

Exit Sub
ErrorHandlerB:
GoTo cleanup

End Sub

Here you're GoTo-jumping outside the error-handling subroutine, without resuming to normal execution, so the instructions under the cleanUp line label execute in an error-handling context. That should be Resume cleanUp, not GoTo.

The Exit Sub statement leaves the scope, which clears the error state and implicitly resumes to normal execution. Here's a little MCVE:

Public Sub Test()
On Error GoTo A
    DoSomething
    Debug.Print "After DoSomething: " & Err.Number
    Exit Sub
A:
    Debug.Print "Inside Test[A]: " & Err.Number
End Sub

Private Sub DoSomething()
On Error GoTo A

    Err.Raise 5

B:
    Debug.Print "Inside DoSomething[B]: " & Err.Number
    Exit Sub
A:
    Debug.Print "Inside DoSomething[A]: " & Err.Number
    Resume B
End Sub

Running the Test procedure produces this output:

Inside DoSomething[A]: 5
Inside DoSomething[B]: 0
After DoSomething: 0

Changing the Resume B instruction for a GoTo B produces this output:

Inside DoSomething[A]: 5
Inside DoSomething[B]: 5
After DoSomething: 0

As you can see, as the error was handled in DoSomething, error state is reset when execution returns to Test, and the handler in the Test procedure is never triggered.

If you want to propagate the error to the caller, you have a number of options:

Don't handle errors in the called procedure. In the above example this means DoSomething wouldn't have an On Error statement; any run-time errors would "bubble up" the call stack, and the output would look like this now:

Inside Test[A]: 5

You would typically do this when it's the calling code that has the knowledge of what the best course of action would be (e.g. display a MsgBox to the user, or log the error, etc.).

Handle errors, and then re-raise them. In your example this means moving (or copying) the cleanup code into the ErrorHandlerB subroutine, and calling Err.Raise Err.Number instead of Resume. Or you keep the GoTo and then the cleanup subroutine can do If Err.Number <> 0 Then Err.Raise Err.Number to effectively re-throw the error for the caller to also handle. In other words:

Public Sub Test()
On Error GoTo A
    DoSomething
    Debug.Print "After DoSomething: " & Err.Number
    Exit Sub
A:
    Debug.Print "Inside Test[A]: " & Err.Number
End Sub

Private Sub DoSomething()
On Error GoTo A

    Err.Raise 5

B:
    Debug.Print "Inside DoSomething[B]: " & Err.Number
    If Err.Number <> 0 Then Err.Raise Err.Number
    Exit Sub
A:
    Debug.Print "Inside DoSomething[A]: " & Err.Number
    GoTo B 'resuming would clear the error and prevent rethrow
End Sub

This outputs:

Inside DoSomething[A]: 5
Inside DoSomething[B]: 5
Inside Test[A]: 5

Depending on the exact reason why you would want to handle the same error in two different places, you could also consider making B a Function that returns a Boolean indicating success or failure - in that case A no longer handles an error per se, but rather uses normal flow control to determine what to do:

Public Sub Test()
On Error GoTo A
    If Not DoSomething Then
        Debug.Print "After DoSomething failed: " & Err.Number
        Exit Sub
    End If
    Exit Sub
A:
    Debug.Print "Inside Test[A]: " & Err.Number
End Sub

Private Function DoSomething() As Boolean
'Dim success As Boolean
On Error GoTo A

    Err.Raise 5
    'success = True

B:
    Debug.Print "Inside DoSomething[B]: " & Err.Number
    DoSomething = (Err.Number = 0) 'DoSomething = success
    Exit Function
A:
    Debug.Print "Inside DoSomething[A]: " & Err.Number
    'success = False
    GoTo B 'Resume B
End Function

Which produces this output:

Inside DoSomething[A]: 5
Inside DoSomething[B]: 5
After DoSomething failed: 0

Notice Test knows DoSomething failed, but Err.Number is 0. This is usually preferable to using runtime errors for flow control, again depending on your actual scenario. Also notice, the GoTo jump is avoidable in that situation, using a simple Boolean local variable to track your return value (the commented-out code).


问:
Tensor Flow: Ran out of memory trying to allocate
I am running Tensor Flow version 0.7.1, 64-bit GPU-enabled, installed with pip, and on a PC with Ubuntu 14.04. My issue is that Tensor Flow is running out of memory when building my network, even though based on my calculations, there should be sufficient room on my GPU.

Below is a minimal example of my code, which is based on the Tensor Flow MNIST tutorial. The network is a two-layer fully-connected network, and the number of nodes in the hidden layer is defined by the variable n. The size of the training minibatch is 1. Here is my code:

```<code>n = 23000

mnist = read_data_sets('MINST_Data', one_hot=True)
session = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])
W1 = tf.Variable(tf.truncated_normal([784, n], stddev=0.1))
b1 = tf.Variable(tf.constant(0.1, shape=[n]))
nn1 = tf.matmul(x, W1) + b1
W2 = tf.Variable(tf.truncated_normal([n, 10], stddev=0.1))
b2 = tf.Variable(tf.constant(0.1, shape=[10]))
nn2 = tf.matmul(nn1, W2) + b2
y = tf.nn.softmax(nn2)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(1)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
</code>```

Now, if n <= 22000, then the network runs fine. However, if n >= 23000, I get the following error:

```<code>W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:211] Ran out of memory trying to allocate 877.38MiB.  See logs for memory state
W tensorflow/core/kernels/cwise_ops_common.cc:56] Resource exhausted: OOM when allocating tensor with shape[10000,23000]
</code>```

However, according to my calculations, there should not be a problem with the memory. The number of parameters in the network is as follows:

```<code>First layer weights: 784 * n
First layer biases: n
Second layer weights: 10 * n
Second layer biases: 10
Total: 795n + 10
</code>```

So with n = 23000, and using float32 data, the total memory required for the network should therefore be 73.1 MB.

Now, my graphics card is the NVIDIA GeForce GTX 780 Ti, which has 3072 MB of memory. After finding my graphics card, Tensor Flow prints out the following:

```<code>Total memory: 3.00GiB
Free memory: 2.32GiB
</code>```

So, there should be around 2.32 GB memory available, which is far greater than the 73.1 MB calculated above. The minibatch size is 1, so this has minimal effect. Why am I getting this error?

I have also now tried this on my laptop, which has an NVida GeForce GTX 880M GPU. Here, Tensor Flow reads out Free memory: 7.60GiB. Running the same code as above, it gives me a memory error at around n = 700,000, which is equivalent to 2.2 GB. This makes a bit more sense, and is significantly higher than the point at which my PC code breaks. However, it is still puzzling to me why it does not break closer to the 7.6 GB mark.

The full output from Tensor Flow whilst running the above code on my PC, with n = 23000, is:

```<code>I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GeForce GTX 780 Ti
major: 3 minor: 5 memoryClockRate (GHz) 1.0455
pciBusID 0000:01:00.0
Total memory: 3.00GiB
Free memory: 2.32GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 780 Ti, pci bus id: 0000:01:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 2.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 4.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 8.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 16.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 32.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 64.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 128.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 256.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 512.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 2.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 4.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 8.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 16.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 32.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 64.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 128.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 256.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 512.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.00GiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 2.00GiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 4.00GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 780 Ti, pci bus id: 0000:01:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:73] Allocating 2.03GiB bytes.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:83] GPU 0 memory begins at 0xb04720000 extends to 0xb86295000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (256):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (1024):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (2048):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (4096):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (8192):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (16384):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (32768):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (65536):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (131072):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (262144):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (524288):    Total Chunks: 2, Chunks in use: 0 819.0KiB allocated for chunks. 390.6KiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (1048576):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (2097152):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (4194304):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (8388608):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (16777216):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (33554432):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (67108864):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (134217728):     Total Chunks: 1, Chunks in use: 0 68.79MiB allocated for chunks. 29.91MiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (268435456):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (536870912):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (1073741824):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (2147483648):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (4294967296):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:450] Bin for 877.38MiB was 1.00GiB, Chunk State:
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d239400 of size 80128
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7600 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d24cd00 of size 438528
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7500 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb1a3e3200 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb1a302800 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15d58800 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08cf7500 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736b00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b7f00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15e39200 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08c16b00 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c61500 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736d00 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b8100 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c4ad00 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736a00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b7e00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7900 of size 400128
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04720200 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736c00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08cf7600 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb1a3e3300 of size 1810570496
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1c0c00 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08c00300 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b8000 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7800 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04720100 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7700 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04720000 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7400 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb11781700 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c77d00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c77e00 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:468]      Summary of in-use Chunks by size:
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 16 Chunks of size 256 totalling 4.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 80128 totalling 78.2KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 5 Chunks of size 92160 totalling 450.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 400128 totalling 390.8KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 438528 totalling 428.2KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 4 Chunks of size 920064 totalling 3.51MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 5 Chunks of size 72128000 totalling 343.93MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 1810570496 totalling 1.69GiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:475] Sum Total of in-use chunks: 2.03GiB
W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:211] Ran out of memory trying to allocate 877.38MiB.  See logs for memory state
W tensorflow/core/kernels/cwise_ops_common.cc:56] Resource exhausted: OOM when allocating tensor with shape[10000,23000]
W tensorflow/core/common_runtime/executor.cc:1102] 0x50f40e0 Compute status: Resource exhausted: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
W tensorflow/core/common_runtime/executor.cc:1102] 0x3234d30 Compute status: Resource exhausted: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
     [[Node: range_1/_13 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_97_range_1", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
W tensorflow/core/common_runtime/executor.cc:1102] 0x3234d30 Compute status: Resource exhausted: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
     [[Node: Cast/_11 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_96_Cast", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Traceback (most recent call last):
  File "/home/jrowlay/Projects/Tensor_Flow_Tutorial/MNIST_CNN_Simple/memory_test.py", line 232, in <module>
    print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 315, in run
    return self._run(None, fetches, feed_dict)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 511, in _run
    feed_dict_string)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 564, in _do_run
    target_list)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 586, in _do_call
    e.code)
tensorflow.python.framework.errors.ResourceExhaustedError: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
     [[Node: range_1/_13 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_97_range_1", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'add', defined at:
  File "/home/jrowlay/Projects/Tensor_Flow_Tutorial/MNIST_CNN_Simple/memory_test.py", line 215, in <module>
    nn1 = tf.matmul(x, W1) + b1
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 468, in binary_op_wrapper
    return func(x, y, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 44, in add
    return _op_def_lib.apply_op("Add", x=x, y=y, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2040, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1087, in __init__
    self._traceback = _extract_stack()
</code>```

答:
Just for your information. I had same error on my Macbook pro.
After I closed few of other Applications, that issue is gone.
But I still got other errors like:

Blockquote
  W tensorflow/core/common_runtime/bfc_allocator.cc:217] Ran out of memory trying to allocate 214.51MiB. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory is available.

So, that's a real out of memory issue.

Body:
I am running Tensor Flow version 0.7.1, 64-bit GPU-enabled, installed with pip, and on a PC with Ubuntu 14.04. My issue is that Tensor Flow is running out of memory when building my network, even though based on my calculations, there should be sufficient room on my GPU.

Below is a minimal example of my code, which is based on the Tensor Flow MNIST tutorial. The network is a two-layer fully-connected network, and the number of nodes in the hidden layer is defined by the variable n. The size of the training minibatch is 1. Here is my code:

n = 23000

mnist = read_data_sets('MINST_Data', one_hot=True)
session = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784])
W1 = tf.Variable(tf.truncated_normal([784, n], stddev=0.1))
b1 = tf.Variable(tf.constant(0.1, shape=[n]))
nn1 = tf.matmul(x, W1) + b1
W2 = tf.Variable(tf.truncated_normal([n, 10], stddev=0.1))
b2 = tf.Variable(tf.constant(0.1, shape=[10]))
nn2 = tf.matmul(nn1, W2) + b2
y = tf.nn.softmax(nn2)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(1)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

Now, if n <= 22000, then the network runs fine. However, if n >= 23000, I get the following error:

W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:211] Ran out of memory trying to allocate 877.38MiB.  See logs for memory state
W tensorflow/core/kernels/cwise_ops_common.cc:56] Resource exhausted: OOM when allocating tensor with shape[10000,23000]

However, according to my calculations, there should not be a problem with the memory. The number of parameters in the network is as follows:

First layer weights: 784 * n
First layer biases: n
Second layer weights: 10 * n
Second layer biases: 10
Total: 795n + 10

So with n = 23000, and using float32 data, the total memory required for the network should therefore be 73.1 MB.

Now, my graphics card is the NVIDIA GeForce GTX 780 Ti, which has 3072 MB of memory. After finding my graphics card, Tensor Flow prints out the following:

Total memory: 3.00GiB
Free memory: 2.32GiB

So, there should be around 2.32 GB memory available, which is far greater than the 73.1 MB calculated above. The minibatch size is 1, so this has minimal effect. Why am I getting this error?

I have also now tried this on my laptop, which has an NVida GeForce GTX 880M GPU. Here, Tensor Flow reads out Free memory: 7.60GiB. Running the same code as above, it gives me a memory error at around n = 700,000, which is equivalent to 2.2 GB. This makes a bit more sense, and is significantly higher than the point at which my PC code breaks. However, it is still puzzling to me why it does not break closer to the 7.6 GB mark.

The full output from Tensor Flow whilst running the above code on my PC, with n = 23000, is:

I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:900] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
I tensorflow/core/common_runtime/gpu/gpu_init.cc:102] Found device 0 with properties:
name: GeForce GTX 780 Ti
major: 3 minor: 5 memoryClockRate (GHz) 1.0455
pciBusID 0000:01:00.0
Total memory: 3.00GiB
Free memory: 2.32GiB
I tensorflow/core/common_runtime/gpu/gpu_init.cc:126] DMA: 0
I tensorflow/core/common_runtime/gpu/gpu_init.cc:136] 0:   Y
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 780 Ti, pci bus id: 0000:01:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 2.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 4.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 8.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 16.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 32.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 64.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 128.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 256.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 512.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 2.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 4.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 8.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 16.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 32.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 64.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 128.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 256.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 512.00MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 1.00GiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 2.00GiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:51] Creating bin of max chunk size 4.00GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:717] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 780 Ti, pci bus id: 0000:01:00.0)
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:73] Allocating 2.03GiB bytes.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:83] GPU 0 memory begins at 0xb04720000 extends to 0xb86295000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (256):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (1024):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (2048):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (4096):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (8192):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (16384):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (32768):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (65536):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (131072):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (262144):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (524288):    Total Chunks: 2, Chunks in use: 0 819.0KiB allocated for chunks. 390.6KiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (1048576):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (2097152):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (4194304):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (8388608):   Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (16777216):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (33554432):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (67108864):  Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (134217728):     Total Chunks: 1, Chunks in use: 0 68.79MiB allocated for chunks. 29.91MiB client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (268435456):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (536870912):     Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (1073741824):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (2147483648):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:431] Bin (4294967296):    Total Chunks: 0, Chunks in use: 0 0B allocated for chunks. 0B client-requested for chunks. 0B in use in bin. 0B client-requested in use in bin.
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:450] Bin for 877.38MiB was 1.00GiB, Chunk State:
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d239400 of size 80128
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7600 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d24cd00 of size 438528
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7500 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb1a3e3200 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb1a302800 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15d58800 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08cf7500 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736b00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b7f00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15e39200 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08c16b00 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c61500 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736d00 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b8100 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c4ad00 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736a00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b7e00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7900 of size 400128
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04720200 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04736c00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08cf7600 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb1a3e3300 of size 1810570496
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1c0c00 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb08c00300 of size 92160
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d2b8000 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7800 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04720100 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7700 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb04720000 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb0d1d7400 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb11781700 of size 72128000
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c77d00 of size 256
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:465] Chunk at 0xb15c77e00 of size 920064
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:468]      Summary of in-use Chunks by size:
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 16 Chunks of size 256 totalling 4.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 80128 totalling 78.2KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 5 Chunks of size 92160 totalling 450.0KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 400128 totalling 390.8KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 438528 totalling 428.2KiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 4 Chunks of size 920064 totalling 3.51MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 5 Chunks of size 72128000 totalling 343.93MiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:471] 1 Chunks of size 1810570496 totalling 1.69GiB
I tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:475] Sum Total of in-use chunks: 2.03GiB
W tensorflow/core/common_runtime/gpu/gpu_bfc_allocator.cc:211] Ran out of memory trying to allocate 877.38MiB.  See logs for memory state
W tensorflow/core/kernels/cwise_ops_common.cc:56] Resource exhausted: OOM when allocating tensor with shape[10000,23000]
W tensorflow/core/common_runtime/executor.cc:1102] 0x50f40e0 Compute status: Resource exhausted: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
W tensorflow/core/common_runtime/executor.cc:1102] 0x3234d30 Compute status: Resource exhausted: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
     [[Node: range_1/_13 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_97_range_1", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
W tensorflow/core/common_runtime/executor.cc:1102] 0x3234d30 Compute status: Resource exhausted: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
     [[Node: Cast/_11 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_96_Cast", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Traceback (most recent call last):
  File "/home/jrowlay/Projects/Tensor_Flow_Tutorial/MNIST_CNN_Simple/memory_test.py", line 232, in <module>
    print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 315, in run
    return self._run(None, fetches, feed_dict)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 511, in _run
    feed_dict_string)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 564, in _do_run
    target_list)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 586, in _do_call
    e.code)
tensorflow.python.framework.errors.ResourceExhaustedError: OOM when allocating tensor with shape[10000,23000]
     [[Node: add = Add[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](MatMul, Variable_1/read)]]
     [[Node: range_1/_13 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_97_range_1", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'add', defined at:
  File "/home/jrowlay/Projects/Tensor_Flow_Tutorial/MNIST_CNN_Simple/memory_test.py", line 215, in <module>
    nn1 = tf.matmul(x, W1) + b1
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 468, in binary_op_wrapper
    return func(x, y, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 44, in add
    return _op_def_lib.apply_op("Add", x=x, y=y, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2040, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1087, in __init__
    self._traceback = _extract_stack()


问:
Asynchronous call inside a promise
First of all I know this question has been asked many times, but I can't figure how to do this.
I am new to Node.js and dealing with the asynchronous aspect of it.

Here is my code

```<code>passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, function (email, pass, done) {
    Users.query(email).exec(function (err, item) {
        const message = 'Login Invalid';
        if (err) return done(err);

        var promise = GetHash({ item, pass });
        promise.then((data) => {
            return done(null, data)
        }).catch((err) => {
            console.log(err);
            return done(null, false, { message });
        });
    });
}));

function GetHash(userPasswordRequest) {
    return new Promise(function (resolve, reject) {
        if (userPasswordRequest.item && userPasswordRequest.item.Items[0]) {
            var userRecord = userPasswordRequest.item.Items[0].attrs;
            if (userRecord.old) {
                if (crypto.createHash('sha256').update(userPasswordRequest.pass, 'ucs-2').digest('base64') === userRecord.password) {
                    var newHash = bcrypt.hashSync(userPasswordRequest.pass, 10);
                    Users.update({ email: userRecord.email, password: newHash, old: null }, function (err, newItem) {
                        if (err) { console.log(err); } else {
                            console.log('first call');
                            resolve(newItem.attrs);
                        }
                    });
                }
            }
            else {
                if (bcrypt.compareSync(userPasswordRequest.pass, userRecord.password)) {
                    console.log('first call');
                    resolve(userPasswordRequest.item.Items[0].attrs);
                }
            }
        }
        reject();
    })
}
</code>```

The issue  is situated here :

```<code> if (crypto.createHash('sha256').update(userPasswordRequest.pass, 'ucs-2').digest('base64') === userRecord.password) {
                    var newHash = bcrypt.hashSync(userPasswordRequest.pass, 10);
                    Users.update({ email: userRecord.email, password: newHash, old: null }, function (err, newItem) {
                        if (err) { console.log(err); } else {
                            console.log('first call');
                            resolve(newItem.attrs);
                        }
                    });
                }
</code>```

Because the Users.update is asynchronous, I'm rejecting the promise before resolving it.

I tried many things, a promise inside of a promise and many other stuff but I can't make this work properly.

Any help would be greatly appreciated

答:
You shouldn't use reject as a fall-through, but call is explicitly when an error condition occurs.

So like this:

```<code>if (userPasswordRequest.item && userPasswordRequest.item.Items[0]) {
  ...
} else {
  return reject(Error('invalid userPasswordRequest'));
}
</code>```

And also:

```<code>if (bcrypt.compareSync(userPasswordRequest.pass, userRecord.password)) {
  console.log('first call');
  return resolve(userPasswordRequest.item.Items[0].attrs);
} else {
  return reject(Error('invalid password'));
}
</code>```

This isn't right either:

```<code>if (err) { console.log(err); }
</code>```

Don't just log the error, reject the promise with it:

```<code>if (err) {
  console.log(err);
  return reject(err);
}
</code>```

As you can see, it's also good form to return after resolving or rejecting.

Title: Asynchronous call inside a promise

Body:
First of all I know this question has been asked many times, but I can't figure how to do this.
I am new to Node.js and dealing with the asynchronous aspect of it.

Here is my code

passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, function (email, pass, done) {
    Users.query(email).exec(function (err, item) {
        const message = 'Login Invalid';
        if (err) return done(err);

        var promise = GetHash({ item, pass });
        promise.then((data) => {
            return done(null, data)
        }).catch((err) => {
            console.log(err);
            return done(null, false, { message });
        });
    });
}));

function GetHash(userPasswordRequest) {
    return new Promise(function (resolve, reject) {
        if (userPasswordRequest.item && userPasswordRequest.item.Items[0]) {
            var userRecord = userPasswordRequest.item.Items[0].attrs;
            if (userRecord.old) {
                if (crypto.createHash('sha256').update(userPasswordRequest.pass, 'ucs-2').digest('base64') === userRecord.password) {
                    var newHash = bcrypt.hashSync(userPasswordRequest.pass, 10);
                    Users.update({ email: userRecord.email, password: newHash, old: null }, function (err, newItem) {
                        if (err) { console.log(err); } else {
                            console.log('first call');
                            resolve(newItem.attrs);
                        }
                    });
                }
            }
            else {
                if (bcrypt.compareSync(userPasswordRequest.pass, userRecord.password)) {
                    console.log('first call');
                    resolve(userPasswordRequest.item.Items[0].attrs);
                }
            }
        }
        reject();
    })
}

The issue  is situated here :

 if (crypto.createHash('sha256').update(userPasswordRequest.pass, 'ucs-2').digest('base64') === userRecord.password) {
                    var newHash = bcrypt.hashSync(userPasswordRequest.pass, 10);
                    Users.update({ email: userRecord.email, password: newHash, old: null }, function (err, newItem) {
                        if (err) { console.log(err); } else {
                            console.log('first call');
                            resolve(newItem.attrs);
                        }
                    });
                }

Because the Users.update is asynchronous, I'm rejecting the promise before resolving it.

I tried many things, a promise inside of a promise and many other stuff but I can't make this work properly.

Any help would be greatly appreciated

Body:
You shouldn't use reject as a fall-through, but call is explicitly when an error condition occurs.

So like this:

if (userPasswordRequest.item && userPasswordRequest.item.Items[0]) {
  ...
} else {
  return reject(Error('invalid userPasswordRequest'));
}

And also:

if (bcrypt.compareSync(userPasswordRequest.pass, userRecord.password)) {
  console.log('first call');
  return resolve(userPasswordRequest.item.Items[0].attrs);
} else {
  return reject(Error('invalid password'));
}

This isn't right either:

if (err) { console.log(err); }

Don't just log the error, reject the promise with it:

if (err) {
  console.log(err);
  return reject(err);
}

As you can see, it's also good form to return after resolving or rejecting.


问:
c# nesting classes and visibility?
I am trying to get the same functionality that a combobox has, like combobox1.Items.Add() // editor.Tags.Tags1()

Like this:

```<code>class Main()
{
    // The editor is passed into the editor class, that allows the editor class to update the editor.
    MyEditorClass editor = new MyEditorClass(editorBox);
    editor.Tags.InsertTag1();

    // Now i don't want people to do this
    // MyEditorClass.TagClass tags = new MyEditorClass.TagClass();
}
</code>```

The reason is that the tags class calls the editorBox passed into the MyEditorClass and if you create a tags class without that editor, it won't work.

My MyEditorClass looks like this:

```<code>public class MyEditorClass
{
    static RichTextBox editor;
    public TagClass Tags;

    public MyEditorClass(RichTextBox editorBox)
    {
        editor = editorBox;
        Tags = new TagClass();
    }

    public class TagClass
    {
        public void InsertTag1()
        {
            editor.Text += "Test tag 1";
        }
    }
}
</code>```

I was trying to make the TagClass static but that didn't work. How is the combobox structured? Since you cant use Combobox.Items but if you declare one you can use the Combobox.Items on the one that you declared.

答:
In the TagClass class add member of type MyEditorClass and assign it when creating new TagClass instance:</p>

```<code>public class TagClass
{
    private MyEditorClass editor = null;

    public TagClass(MyEditorClass parent)
    {
        this.editor = parent;
    }

    public void InsertTag1()
    {
        editor.Text += "Test tag 1";
    }
}

...

Tags = new TagClass(this);
</code>```

ContentLicense: CC BY-SA 2.5

Title: c# nesting classes and visibility?

Body:
I am trying to get the same functionality that a combobox has, like combobox1.Items.Add() // editor.Tags.Tags1()

Like this:

class Main()
{
    // The editor is passed into the editor class, that allows the editor class to update the editor.
    MyEditorClass editor = new MyEditorClass(editorBox);
    editor.Tags.InsertTag1();

    // Now i don't want people to do this
    // MyEditorClass.TagClass tags = new MyEditorClass.TagClass();
}

The reason is that the tags class calls the editorBox passed into the MyEditorClass and if you create a tags class without that editor, it won't work.

My MyEditorClass looks like this:

public class MyEditorClass
{
    static RichTextBox editor;
    public TagClass Tags;

    public MyEditorClass(RichTextBox editorBox)
    {
        editor = editorBox;
        Tags = new TagClass();
    }

    public class TagClass
    {
        public void InsertTag1()
        {
            editor.Text += "Test tag 1";
        }
    }
}

I was trying to make the TagClass static but that didn't work. How is the combobox structured? Since you cant use Combobox.Items but if you declare one you can use the Combobox.Items on the one that you declared.

Body:
In the TagClass class add member of type MyEditorClass and assign it when creating new TagClass instance:

public class TagClass
{
    private MyEditorClass editor = null;

    public TagClass(MyEditorClass parent)
    {
        this.editor = parent;
    }

    public void InsertTag1()
    {
        editor.Text += "Test tag 1";
    }
}

...

Tags = new TagClass(this);


问:
How do I create a pause and unpause button in Swift and Sprite Kit?
I have the following code. When the program runs, the game pauses when you click the pause button in the top left, but the unpause button in the middle does not show. It seems like the program is running the command to pause the game before it is running the command to create the unpause button but I don't know how to fix this.    </p>

```<code>import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var lanecounter:CGFloat = 0
var lastOpen:CGFloat = 0
var score:Int = 0
var BGspeed:CGFloat = -700
var player:SKSpriteNode?
let scoreLabel = SKLabelNode()
let highScoreLabel = SKLabelNode()
var direction:Int?
let noCategory:UInt32 = 0
let carCategory:UInt32 = 0b1
let playerCategory:UInt32 = 0b1 << 1
let pointCategory:UInt32 = 0b1 << 2
let bumperCategory:UInt32 = 0b1 << 3
var died:Bool?
var pause:Bool = false
var gameStarted:Bool?
var restartBTN = SKSpriteNode()
var pauseBTN = SKSpriteNode()
var unpauseBTN = SKSpriteNode()

func createPauseBTN()
{
    pauseBTN = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 100))
    pauseBTN.position = CGPoint(x: -self.frame.width/2 + 20, y: self.frame.height/2 - 20)
    pauseBTN.zPosition = 10
    self.addChild(pauseBTN)
}

func createunPauseBTN()
{
    unpauseBTN = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 100))
    unpauseBTN.position = CGPoint(x: 0, y: 0)
    unpauseBTN.zPosition = 1000
    self.addChild(unpauseBTN)
    //pauseGame()
    //scene?.view?.isPaused = true
}

func pauseGame() {
    scene?.view?.isPaused = true
    createunPauseBTN()
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches
    {
        let location = touch.location(in: self)

        if died == true
        {
            if restartBTN.contains(location) {
            restartScene()
            }
        }

        if pauseBTN.contains(location) {
            print(pause)
            createunPauseBTN()
            print("asd")
            pauseBTN.removeFromParent()
            pauseGame()
        }

        if unpauseBTN.contains(location) {
            scene?.view?.isPaused = false
            createPauseBTN()
        }
    }
}
</code>```

答:
Your problem is that you are pausing the SKView which will pause everything.

```<code> scene?.view?.isPaused = true
</code>```

That means everything in your SKScene such as SKActions, addingChildren etc will not work/stop working until you set it to false again.

It is usually a better idea to create a worldNode and add all nodes that you need paused to that node. Apple also does this in DemoBots.

So add another property in your class

```<code>let worldNode = SKNode()
</code>```

and add it to the scene in DidMoveToView

```<code>addChild(worldNode)
</code>```

Than add all your other nodes that you need paused such as your player, enemies etc to this worldNode

```<code> worldNode.addChild(someNode1)
 worldNode.addChild(someNode2)
</code>```

Than in your pause code you should say this

```<code> worldNode.isPaused = true
 physicsWorld.speed = 0
</code>```

and in the resume code this

```<code> worldNode.isPaused = false
 physicsWorld.speed = 1
</code>```

This should give you more flexibility because you can still do things such as letting certain SKActions run e.g for your background. It should also make your pause action smoother.

Hope this helps

Body:
I have the following code. When the program runs, the game pauses when you click the pause button in the top left, but the unpause button in the middle does not show. It seems like the program is running the command to pause the game before it is running the command to create the unpause button but I don't know how to fix this.

import SpriteKit
import GameplayKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var lanecounter:CGFloat = 0
var lastOpen:CGFloat = 0
var score:Int = 0
var BGspeed:CGFloat = -700
var player:SKSpriteNode?
let scoreLabel = SKLabelNode()
let highScoreLabel = SKLabelNode()
var direction:Int?
let noCategory:UInt32 = 0
let carCategory:UInt32 = 0b1
let playerCategory:UInt32 = 0b1 << 1
let pointCategory:UInt32 = 0b1 << 2
let bumperCategory:UInt32 = 0b1 << 3
var died:Bool?
var pause:Bool = false
var gameStarted:Bool?
var restartBTN = SKSpriteNode()
var pauseBTN = SKSpriteNode()
var unpauseBTN = SKSpriteNode()

func createPauseBTN()
{
    pauseBTN = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 100))
    pauseBTN.position = CGPoint(x: -self.frame.width/2 + 20, y: self.frame.height/2 - 20)
    pauseBTN.zPosition = 10
    self.addChild(pauseBTN)
}

func createunPauseBTN()
{
    unpauseBTN = SKSpriteNode(color: SKColor.purple, size: CGSize(width: 100, height: 100))
    unpauseBTN.position = CGPoint(x: 0, y: 0)
    unpauseBTN.zPosition = 1000
    self.addChild(unpauseBTN)
    //pauseGame()
    //scene?.view?.isPaused = true
}

func pauseGame() {
    scene?.view?.isPaused = true
    createunPauseBTN()
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    for touch in touches
    {
        let location = touch.location(in: self)

        if died == true
        {
            if restartBTN.contains(location) {
            restartScene()
            }
        }

        if pauseBTN.contains(location) {
            print(pause)
            createunPauseBTN()
            print("asd")
            pauseBTN.removeFromParent()
            pauseGame()
        }

        if unpauseBTN.contains(location) {
            scene?.view?.isPaused = false
            createPauseBTN()
        }
    }
}

Body:
Your problem is that you are pausing the SKView which will pause everything.

 scene?.view?.isPaused = true

That means everything in your SKScene such as SKActions, addingChildren etc will not work/stop working until you set it to false again.

It is usually a better idea to create a worldNode and add all nodes that you need paused to that node. Apple also does this in DemoBots.

So add another property in your class

let worldNode = SKNode()

and add it to the scene in DidMoveToView

addChild(worldNode)

Than add all your other nodes that you need paused such as your player, enemies etc to this worldNode

 worldNode.addChild(someNode1)
 worldNode.addChild(someNode2)

Than in your pause code you should say this

 worldNode.isPaused = true
 physicsWorld.speed = 0

and in the resume code this

 worldNode.isPaused = false
 physicsWorld.speed = 1

This should give you more flexibility because you can still do things such as letting certain SKActions run e.g for your background. It should also make your pause action smoother.

Hope this helps