问:
How to make electron work with sqlite3?
I have tried everything, can't get it to work. I get this error:

<img src="https://i.stack.imgur.com/D5Oyn.png" alt="here is my package.json">

```<code>{
  "name": "test",
  "version": "1.0.0",
  "description": "test",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "rebuild": "electron-rebuild -f -w sqlite3"
  },
  "repository": "https://github.com",
  "keywords": [
    "test"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "~1.6.2",
    "electron-rebuild": "^1.5.11"
  },
  "dependencies": {
    "bootstrap": "^4.0.0-alpha.6",
    "electron-fetch": "^1.0.0-aplha4",
    "electron-handlebars": "^1.0.0",
    "electron-prebuilt": "^1.4.13",
    "electron-rebuild": "^1.5.11",
    "electron-sqlite3": "^0.0.3",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.0",
    "sqlite3": "^3.1.8"
  }
}
</code>```

In the code I use:

```<code>const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database(':memory:');
</code>```

Any ideas how to make this work?

答:
Have you already run sqlite3 through electron-rebuild?

```<code>$ electron-rebuild -f -w sqlite3
</code>```

or

```<code>$ npm rebuild
</code>```

Title: How to make electron work with sqlite3?

Body:
I have tried everything, can't get it to work. I get this error:

<img src="https://i.stack.imgur.com/D5Oyn.png" alt="here is my package.json">

{
  "name": "test",
  "version": "1.0.0",
  "description": "test",
  "main": "main.js",
  "scripts": {
    "start": "electron .",
    "rebuild": "electron-rebuild -f -w sqlite3"
  },
  "repository": "https://github.com",
  "keywords": [
    "test"
  ],
  "author": "GitHub",
  "license": "CC0-1.0",
  "devDependencies": {
    "electron": "~1.6.2",
    "electron-rebuild": "^1.5.11"
  },
  "dependencies": {
    "bootstrap": "^4.0.0-alpha.6",
    "electron-fetch": "^1.0.0-aplha4",
    "electron-handlebars": "^1.0.0",
    "electron-prebuilt": "^1.4.13",
    "electron-rebuild": "^1.5.11",
    "electron-sqlite3": "^0.0.3",
    "font-awesome": "^4.7.0",
    "jquery": "^3.2.0",
    "sqlite3": "^3.1.8"
  }
}

In the code I use:

const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database(':memory:');

Any ideas how to make this work?

Body:
Have you already run sqlite3 through electron-rebuild?

$ electron-rebuild -f -w sqlite3

or

$ npm rebuild


来源: stackexchange

问:
How can I create iterators of a filtered vector?
Suppose I have a vector named spot_deals of SpotDeal that is a class:

```<code>class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}
</code>```

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

```<code>auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);
</code>```

答:
The answer is certainly "yes."  C++ iterators in the STL style can be made to do all sorts of tricks.  A common but basic one is making an iterator for std::map which when dereferenced gives only the key or the value.

In your particular case, a simple implementation might be like this:

```<code>template <typename BaseIterator>
struct filtered_iterator : BaseIterator
{
    typedef std::function<bool (const value_type&)> filter_type;

    filtered_iterator() = default;
    filtered_iterator(filter_type filter, BaseIterator base, BaseIterator end = {})
        : BaseIterator(base), _end(end), _filter(filter_type) {
        while (*this != _end && !_filter(**this)) {
            ++*this;
        }
    }

    filtered_iterator& operator++() {
        do {
            BaseIterator::operator++();
        } while (*this != _end && !_filter(**this));
    }

    filtered_iterator operator++(int) {
        filtered_iterator copy = *this;
        ++*this;
        return copy;
    }

private:
    BaseIterator _end;
    filter_type _filter;
};

template <typename BaseIterator>
filtered_iterator<BaseIterator> make_filtered_iterator(
        typename filtered_iterator<BaseIterator>::filter_type filter,
        BaseIterator base, BaseIterator end = {}) {
    return {filter, base, end};
}
</code>```

I set a default value for end because typically you can use a default-constructed iterator for that.  But in some cases you might want to filter only a subset of the container, in which case specifying the end makes it easy.

ContentLicense: CC BY-SA 4.0

Body:
Suppose I have a vector named spot_deals of SpotDeal that is a class:

class SpotDeal
{
public:
    int deal_id_; // primary key, and vector is sorted by id
    string ccy_pair_; // ccy pair, e.g. GBPUSD, AUDUSD
    double amount_;
}

Say I need to pass two subset of spot_deals to a function foo for some computation. I could make copies, however, that would cost memory and time. Actually foo only needs iterators of deals. So can I make 2 iterators of vector<SpotDeal>, namely it1 and it2 and pass them to foo?

The two subset of spot_deals could be filtered by ccy_pair_, e.g. deals of GBPUSD and AUDUSD, or by other conditions. So I'm looking for a way to define an iterator defined by a vector and a lambda function (could equivalently be a functor though).

Is there a way to write a helper function make_filtered_iterator so that I can have something like below?

auto it1 = make_filtered_iterator(spot_deals, filter_lambda1);
auto it2 = make_filtered_iterator(spot_deals, filter_lambda2);
foo(it1, it2);

Body:
The answer is certainly "yes."  C++ iterators in the STL style can be made to do all sorts of tricks.  A common but basic one is making an iterator for std::map which when dereferenced gives only the key or the value.

In your particular case, a simple implementation might be like this:

template <typename BaseIterator>
struct filtered_iterator : BaseIterator
{
    typedef std::function<bool (const value_type&)> filter_type;

    filtered_iterator() = default;
    filtered_iterator(filter_type filter, BaseIterator base, BaseIterator end = {})
        : BaseIterator(base), _end(end), _filter(filter_type) {
        while (*this != _end && !_filter(**this)) {
            ++*this;
        }
    }

    filtered_iterator& operator++() {
        do {
            BaseIterator::operator++();
        } while (*this != _end && !_filter(**this));
    }

    filtered_iterator operator++(int) {
        filtered_iterator copy = *this;
        ++*this;
        return copy;
    }

private:
    BaseIterator _end;
    filter_type _filter;
};

template <typename BaseIterator>
filtered_iterator<BaseIterator> make_filtered_iterator(
        typename filtered_iterator<BaseIterator>::filter_type filter,
        BaseIterator base, BaseIterator end = {}) {
    return {filter, base, end};
}

I set a default value for end because typically you can use a default-constructed iterator for that.  But in some cases you might want to filter only a subset of the container, in which case specifying the end makes it easy.

ContentLicense: CC BY-SA 3.0


问:
EXC_BAD_ACCESS on deep NSString stringWithFormat:
I'm writing a Mac OS (10.8.4) app using Xcode 5.1.1 just for my own use (to solve an Eight Off solitaire game when I get stuck), and I don't care about efficiency or memory usage.  It's a recursive program (it creates a tree of possible moves, recurses, creates the next move, etc.) so it needs a lot of memory (I've got 24 GB) and I've increased the stack (-Wl,-stack_size,0x4000000).  But, regardless of the stack size, I get EXC_BAD_ACCESS code=2, always at the same depth (about 170 levels), and it's always on a line that uses NSString stringWithFormat: such as:

```<code>   NSString *temp = [NSString stringWithFormat:@"%d",value]; // value is an integer
</code>```

The line has been executed just fine in all previous recursion levels.  If I remove that particular line, the exception happens at some other stringWithFormat line.  It's as if NSString has its own limit, regardless of my stack size setting.  It was working earlier, when using garbage collection instead of ARC.  (Xcode wanted me to convert to ARC.)

I've checked for Zombies, but there aren't any objects being referenced on the error lines anyway.

Why might I be getting the EXC_BAD_ACCESS regardless of the stack size, and always on stringWithFormat:?

Adding crash log:

```<code>Process:         EightOff Solver [11701]
Path:            /Users/USER/Library/Developer/Xcode/DerivedData/EightOff_Solver-dqppnsumvcsujjflailrgqxogyij/Build/Products/Debug/EightOff Solver.app/Contents/MacOS/EightOff Solver
Identifier:      com.yourcompany.EightOff_Solver
Version:         1.0
Code Type:       X86-64 (Native)
Parent Process:  launchd [179]
User ID:         501

Date/Time:       2014-06-25 01:38:46.581 -0500
OS Version:      Mac OS X 10.8.4 (12E55)
Report Version:  10
Sleep/Wake UUID: 561695D4-0498-43DC-9B0E-9417A5D5120D

Interval Since Last Report:          60266 sec
Crashes Since Last Report:           2
Per-App Crashes Since Last Report:   9
Anonymous UUID:                      96F16B3C-9A73-63C2-B5CD-11CC51CFE612

Crashed Thread:  1  Dispatch queue: com.apple.root.default-priority

Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000100400ec8

VM Regions Near 0x100400ec8:
    MALLOC_TINY            0000000100100000-0000000100400000 [ 3072K] rw-/rwx SM=PRV
--> STACK GUARD            0000000100400000-0000000100401000 [    4K] ---/rwx SM=NUL  stack guard for thread 1
    Stack                  0000000100401000-0000000100483000 [  520K] rw-/rwx SM=COW  thread 1

Thread 0:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff8eb18686 mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff8eb17c42 mach_msg + 70
2   com.apple.CoreFoundation        0x00007fff93d38233 __CFRunLoopServiceMachPort + 195
3   com.apple.CoreFoundation        0x00007fff93d3d916 __CFRunLoopRun + 1078
4   com.apple.CoreFoundation        0x00007fff93d3d0e2 CFRunLoopRunSpecific + 290
5   com.apple.HIToolbox             0x00007fff93a36eb4 RunCurrentEventLoopInMode + 209
6   com.apple.HIToolbox             0x00007fff93a36c52 ReceiveNextEventCommon + 356
7   com.apple.HIToolbox             0x00007fff93a36ae3 BlockUntilNextEventMatchingListInMode + 62
8   com.apple.AppKit                0x00007fff9a52a533 _DPSNextEvent + 685
9   com.apple.AppKit                0x00007fff9a529df2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
10  com.apple.AppKit                0x00007fff9a5211a3 -[NSApplication run] + 517
11  com.apple.AppKit                0x00007fff9a4c5bd6 NSApplicationMain + 869
12  com.yourcompany.EightOff_Solver 0x0000000100006ea2 main + 34 (main.m:13)
13  com.yourcompany.EightOff_Solver 0x0000000100001bc4 start + 52

Thread 1 Crashed:: Dispatch queue: com.apple.root.default-priority
0   libsystem_c.dylib               0x00007fff936c682d __vfprintf + 40
1   libsystem_c.dylib               0x00007fff936c4e16 vsnprintf_l + 254
2   libsystem_c.dylib               0x00007fff936bf462 snprintf_l + 127
3   com.apple.CoreFoundation        0x00007fff93d0ef3f __CFStringAppendFormatCore + 11199
4   com.apple.CoreFoundation        0x00007fff93d594fb _CFStringCreateWithFormatAndArgumentsAux + 107
5   com.apple.Foundation            0x00007fff9a03f13c +[NSString stringWithFormat:] + 170
6   com.yourcompany.EightOff_Solver 0x0000000100009b67 -[Card description] + 663 (Card.m:265)
7   com.yourcompany.EightOff_Solver 0x00000001000091f7 -[Card makeNewGameStates:] + 9031 (Card.m:211)
8   com.yourcompany.EightOff_Solver 0x0000000100005087 -[MyDocument recursiveOnGameState:depth:] + 6903 (MyDocument.m:1195)
9   com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
10  com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)

... [deleted identical lines numbered 11 through 170]

171 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
172 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
173 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
174 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
175 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
176 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
177 com.yourcompany.EightOff_Solver 0x00000001000029c2 -[MyDocument startBackgroundThread] + 2706 (MyDocument.m:882)
178 com.apple.CoreFoundation        0x00007fff93d8f09c __invoking___ + 140
179 com.apple.CoreFoundation        0x00007fff93d8ef37 -[NSInvocation invoke] + 263
180 com.apple.Foundation            0x00007fff9a07da30 -[NSInvocationOperation main] + 34
181 com.apple.Foundation            0x00007fff9a075926 -[__NSOperationInternal start] + 684
182 com.apple.Foundation            0x00007fff9a07d0f1 __block_global_6 + 129
183 libdispatch.dylib               0x00007fff96ec4f01 _dispatch_call_block_and_release + 15
184 libdispatch.dylib               0x00007fff96ec10b6 _dispatch_client_callout + 8
185 libdispatch.dylib               0x00007fff96ec21fa _dispatch_worker_thread2 + 304
186 libsystem_c.dylib               0x00007fff93654d0b _pthread_wqthread + 404
187 libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 2:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x00007fff8eb1ad16 kevent + 10
1   libdispatch.dylib               0x00007fff96ec3dea _dispatch_mgr_invoke + 883
2   libdispatch.dylib               0x00007fff96ec39ee _dispatch_mgr_thread + 54

Thread 3:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 4:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 5:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 6:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 1 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000208  rbx: 0x00007fff7ecb5a98  rcx: 0x00000001004014c0  rdx: 0x0000000100402d30
  rdi: 0x0000000100401338  rsi: 0x00007fff7ecb5a98  rbp: 0x0000000100401250  rsp: 0x0000000100400e20
   r8: 0x00000001004014c0   r9: 0x0000000000000003  r10: 0x0000000000000000  r11: 0x00000001004012b4
  r12: 0x00000000000001ff  r13: 0x0000000100401500  r14: 0x00000001004014c0  r15: 0x0000000100402d30
  rip: 0x00007fff936c682d  rfl: 0x0000000000010202  cr2: 0x0000000100400ec8
Logical CPU: 0
</code>```

6/30/14 Edited to add: this only started happening when I upgraded Xcode to 5.1.1 (from 5.0).  Could it be due to a changed build setting? (I don't know what they were before.)  I'm using an iMac (late 2012) Intel Core i5, OS 10.8.4.  Some of the settings are: Base SDK: Latest (I've tried restricting to 10.8); Valid Architectures i386, x86_64 (I've tried having just i386 or just x86_64).  Deployment Target: 10.8.

7/1/14 Edited to add: I was using NSOperationQueue (with dispatch_async on the main queue for the UI operations).  Removing the NSOperationQueue fixed the crash, but now I'm unable to get my UI to update (NSLog gives me some output).  Executing my loop in a dispatch_async() with a background queue also crashes, and again no UI updates.  Apparently, background tasks have a resource limit related to NSString that I'm unable to change.  It crashes (always on creating an NSString) even if I don't update my UI.

答: The fact that your problem is solved by removing dispatch_async() and just running it on the main thread leads me to believe you are indeed running out of stack memory in the thread. I just ran into a similar problem (EXC_BAD_ACCESS at the top of various functions in a deeply recursive set of functions), and was able to fix it by increasing the stack size. I didn't seem able to increase the size using those -Wl,-stack_size,... flags though, nor using NSThreads. (Perhaps that's why that didn't help you.) Instead I launched the thread using pthread_create(), first calling pthread_attr_setstacksize() on it. Code example here: https://developer.apple.com/library/content/qa/qa1419/_index.html</p>

Body:
I'm writing a Mac OS (10.8.4) app using Xcode 5.1.1 just for my own use (to solve an Eight Off solitaire game when I get stuck), and I don't care about efficiency or memory usage.  It's a recursive program (it creates a tree of possible moves, recurses, creates the next move, etc.) so it needs a lot of memory (I've got 24 GB) and I've increased the stack (-Wl,-stack_size,0x4000000).  But, regardless of the stack size, I get EXC_BAD_ACCESS code=2, always at the same depth (about 170 levels), and it's always on a line that uses NSString stringWithFormat: such as:

   NSString *temp = [NSString stringWithFormat:@"%d",value]; // value is an integer

The line has been executed just fine in all previous recursion levels.  If I remove that particular line, the exception happens at some other stringWithFormat line.  It's as if NSString has its own limit, regardless of my stack size setting.  It was working earlier, when using garbage collection instead of ARC.  (Xcode wanted me to convert to ARC.)

I've checked for Zombies, but there aren't any objects being referenced on the error lines anyway.

Why might I be getting the EXC_BAD_ACCESS regardless of the stack size, and always on stringWithFormat:?

Adding crash log:

Process:         EightOff Solver [11701]
Path:            /Users/USER/Library/Developer/Xcode/DerivedData/EightOff_Solver-dqppnsumvcsujjflailrgqxogyij/Build/Products/Debug/EightOff Solver.app/Contents/MacOS/EightOff Solver
Identifier:      com.yourcompany.EightOff_Solver
Version:         1.0
Code Type:       X86-64 (Native)
Parent Process:  launchd [179]
User ID:         501

Date/Time:       2014-06-25 01:38:46.581 -0500
OS Version:      Mac OS X 10.8.4 (12E55)
Report Version:  10
Sleep/Wake UUID: 561695D4-0498-43DC-9B0E-9417A5D5120D

Interval Since Last Report:          60266 sec
Crashes Since Last Report:           2
Per-App Crashes Since Last Report:   9
Anonymous UUID:                      96F16B3C-9A73-63C2-B5CD-11CC51CFE612

Crashed Thread:  1  Dispatch queue: com.apple.root.default-priority

Exception Type:  EXC_BAD_ACCESS (SIGBUS)
Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000100400ec8

VM Regions Near 0x100400ec8:
    MALLOC_TINY            0000000100100000-0000000100400000 [ 3072K] rw-/rwx SM=PRV
--> STACK GUARD            0000000100400000-0000000100401000 [    4K] ---/rwx SM=NUL  stack guard for thread 1
    Stack                  0000000100401000-0000000100483000 [  520K] rw-/rwx SM=COW  thread 1

Thread 0:: Dispatch queue: com.apple.main-thread
0   libsystem_kernel.dylib          0x00007fff8eb18686 mach_msg_trap + 10
1   libsystem_kernel.dylib          0x00007fff8eb17c42 mach_msg + 70
2   com.apple.CoreFoundation        0x00007fff93d38233 __CFRunLoopServiceMachPort + 195
3   com.apple.CoreFoundation        0x00007fff93d3d916 __CFRunLoopRun + 1078
4   com.apple.CoreFoundation        0x00007fff93d3d0e2 CFRunLoopRunSpecific + 290
5   com.apple.HIToolbox             0x00007fff93a36eb4 RunCurrentEventLoopInMode + 209
6   com.apple.HIToolbox             0x00007fff93a36c52 ReceiveNextEventCommon + 356
7   com.apple.HIToolbox             0x00007fff93a36ae3 BlockUntilNextEventMatchingListInMode + 62
8   com.apple.AppKit                0x00007fff9a52a533 _DPSNextEvent + 685
9   com.apple.AppKit                0x00007fff9a529df2 -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
10  com.apple.AppKit                0x00007fff9a5211a3 -[NSApplication run] + 517
11  com.apple.AppKit                0x00007fff9a4c5bd6 NSApplicationMain + 869
12  com.yourcompany.EightOff_Solver 0x0000000100006ea2 main + 34 (main.m:13)
13  com.yourcompany.EightOff_Solver 0x0000000100001bc4 start + 52

Thread 1 Crashed:: Dispatch queue: com.apple.root.default-priority
0   libsystem_c.dylib               0x00007fff936c682d __vfprintf + 40
1   libsystem_c.dylib               0x00007fff936c4e16 vsnprintf_l + 254
2   libsystem_c.dylib               0x00007fff936bf462 snprintf_l + 127
3   com.apple.CoreFoundation        0x00007fff93d0ef3f __CFStringAppendFormatCore + 11199
4   com.apple.CoreFoundation        0x00007fff93d594fb _CFStringCreateWithFormatAndArgumentsAux + 107
5   com.apple.Foundation            0x00007fff9a03f13c +[NSString stringWithFormat:] + 170
6   com.yourcompany.EightOff_Solver 0x0000000100009b67 -[Card description] + 663 (Card.m:265)
7   com.yourcompany.EightOff_Solver 0x00000001000091f7 -[Card makeNewGameStates:] + 9031 (Card.m:211)
8   com.yourcompany.EightOff_Solver 0x0000000100005087 -[MyDocument recursiveOnGameState:depth:] + 6903 (MyDocument.m:1195)
9   com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
10  com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)

... [deleted identical lines numbered 11 through 170]

171 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
172 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
173 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
174 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
175 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
176 com.yourcompany.EightOff_Solver 0x00000001000054b2 -[MyDocument recursiveOnGameState:depth:] + 7970 (MyDocument.m:1210)
177 com.yourcompany.EightOff_Solver 0x00000001000029c2 -[MyDocument startBackgroundThread] + 2706 (MyDocument.m:882)
178 com.apple.CoreFoundation        0x00007fff93d8f09c __invoking___ + 140
179 com.apple.CoreFoundation        0x00007fff93d8ef37 -[NSInvocation invoke] + 263
180 com.apple.Foundation            0x00007fff9a07da30 -[NSInvocationOperation main] + 34
181 com.apple.Foundation            0x00007fff9a075926 -[__NSOperationInternal start] + 684
182 com.apple.Foundation            0x00007fff9a07d0f1 __block_global_6 + 129
183 libdispatch.dylib               0x00007fff96ec4f01 _dispatch_call_block_and_release + 15
184 libdispatch.dylib               0x00007fff96ec10b6 _dispatch_client_callout + 8
185 libdispatch.dylib               0x00007fff96ec21fa _dispatch_worker_thread2 + 304
186 libsystem_c.dylib               0x00007fff93654d0b _pthread_wqthread + 404
187 libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 2:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x00007fff8eb1ad16 kevent + 10
1   libdispatch.dylib               0x00007fff96ec3dea _dispatch_mgr_invoke + 883
2   libdispatch.dylib               0x00007fff96ec39ee _dispatch_mgr_thread + 54

Thread 3:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 4:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 5:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 6:
0   libsystem_kernel.dylib          0x00007fff8eb1a6d6 __workq_kernreturn + 10
1   libsystem_c.dylib               0x00007fff93654f4c _pthread_workq_return + 25
2   libsystem_c.dylib               0x00007fff93654d13 _pthread_wqthread + 412
3   libsystem_c.dylib               0x00007fff9363f1d1 start_wqthread + 13

Thread 1 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000208  rbx: 0x00007fff7ecb5a98  rcx: 0x00000001004014c0  rdx: 0x0000000100402d30
  rdi: 0x0000000100401338  rsi: 0x00007fff7ecb5a98  rbp: 0x0000000100401250  rsp: 0x0000000100400e20
   r8: 0x00000001004014c0   r9: 0x0000000000000003  r10: 0x0000000000000000  r11: 0x00000001004012b4
  r12: 0x00000000000001ff  r13: 0x0000000100401500  r14: 0x00000001004014c0  r15: 0x0000000100402d30
  rip: 0x00007fff936c682d  rfl: 0x0000000000010202  cr2: 0x0000000100400ec8
Logical CPU: 0

6/30/14 Edited to add: this only started happening when I upgraded Xcode to 5.1.1 (from 5.0).  Could it be due to a changed build setting? (I don't know what they were before.)  I'm using an iMac (late 2012) Intel Core i5, OS 10.8.4.  Some of the settings are: Base SDK: Latest (I've tried restricting to 10.8); Valid Architectures i386, x86_64 (I've tried having just i386 or just x86_64).  Deployment Target: 10.8.

7/1/14 Edited to add: I was using NSOperationQueue (with dispatch_async on the main queue for the UI operations).  Removing the NSOperationQueue fixed the crash, but now I'm unable to get my UI to update (NSLog gives me some output).  Executing my loop in a dispatch_async() with a background queue also crashes, and again no UI updates.  Apparently, background tasks have a resource limit related to NSString that I'm unable to change.  It crashes (always on creating an NSString) even if I don't update my UI.


问:
OSX SSH keys seem unavailable to git
When I try and push commits up to GitHub, I get a

```<code>Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.
</code>```

Luckily, help.GitHub has a great article on solving SSH issues. I ran through this guide and found that ssh-add -l -E md5 returns The agent has no identities. The guide says to generate a new key, which I did. After that, ssh-add returns something like 2048 MD5:a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/you/.ssh/id_rsa (RSA) as expected.

Great, I think, the problem's solved. I try another push, and get the same public key issue. I've made sure that my key is correctly set in GitHub. When I start a new session, ssh-add again returns no identities. I've even started the process from scratch following the article above. I've checked my permissions, and now I'm out of troubleshooting leads.

答:
First, make sure your public key is correctly registered on your GitHub profile (as one continuous line, without any newline in it).

Second, make sure to generate (at least for testing) a private key not protected by a passphrase: you need ssh agent only to manage keys with passphrase. If your key has no passphrase, you don't need ssh agent at all.

```<code>  ssh-keygen -t rsa -C "key for GitHub access" -q -P ""
</code>```

That will replace your current key, so make sure you don't need your current key anymore.

Test your key with ssh -T git@github.com

Title: OSX SSH keys seem unavailable to git

Body:
When I try and push commits up to GitHub, I get a

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

Luckily, help.GitHub has a great article on solving SSH issues. I ran through this guide and found that ssh-add -l -E md5 returns The agent has no identities. The guide says to generate a new key, which I did. After that, ssh-add returns something like 2048 MD5:a0:dd:42:3c:5a:9d:e4:2a:21:52:4e:78:07:6e:c8:4d /Users/you/.ssh/id_rsa (RSA) as expected.

Great, I think, the problem's solved. I try another push, and get the same public key issue. I've made sure that my key is correctly set in GitHub. When I start a new session, ssh-add again returns no identities. I've even started the process from scratch following the article above. I've checked my permissions, and now I'm out of troubleshooting leads.

Body:
First, make sure your public key is correctly registered on your GitHub profile (as one continuous line, without any newline in it).

Second, make sure to generate (at least for testing) a private key not protected by a passphrase: you need ssh agent only to manage keys with passphrase. If your key has no passphrase, you don't need ssh agent at all.

  ssh-keygen -t rsa -C "key for GitHub access" -q -P ""

That will replace your current key, so make sure you don't need your current key anymore.

Test your key with ssh -T git@github.com


问:
How to Re-selecting row after store.load()
I have grid panel and a button.

when i click button it will transfer data via ajax and after finish grid will reload.

I try to re-selected row (in here i give u example is first row), but anyway it's not working

```<code>Ext.Ajax.request({
    url: ...,
    params: {
        v: ...
    },
    success: function(response){
        grid.store.load();
        grid.getSelectionModel().select(0, true); // example first row

    }
})
</code>```

答:
In case you want to select whatever was last selected (not just the first row as shown in the accepted answer) this is the simplest I think:

```<code>grid.store.load(function() {
    var view = grid.getView(),
        selModel = grid.getSelectionModel(),
        lastSelected = selModel.getLastSelected();

    view.select(lastSelected);
});
</code>```

or better, a listener for all loading done by the store in the future:

```<code>grid.store.on('load', function() {
    var view = grid.getView(),
        selModel = grid.getSelectionModel(),
        lastSelected = selModel.getLastSelected();

    view.select(lastSelected);
});

grid.store.load();
</code>```

Body:
I have grid panel and a button.

when i click button it will transfer data via ajax and after finish grid will reload.

I try to re-selected row (in here i give u example is first row), but anyway it's not working

Ext.Ajax.request({
    url: ...,
    params: {
        v: ...
    },
    success: function(response){
        grid.store.load();
        grid.getSelectionModel().select(0, true); // example first row

    }
})

Body:
In case you want to select whatever was last selected (not just the first row as shown in the accepted answer) this is the simplest I think:

grid.store.load(function() {
    var view = grid.getView(),
        selModel = grid.getSelectionModel(),
        lastSelected = selModel.getLastSelected();

    view.select(lastSelected);
});

or better, a listener for all loading done by the store in the future:

grid.store.on('load', function() {
    var view = grid.getView(),
        selModel = grid.getSelectionModel(),
        lastSelected = selModel.getLastSelected();

    view.select(lastSelected);
});

grid.store.load();


问:
mvc - Bind specific properties of ViewModel based on CheckBox
I have a model like this:

```<code> public class EmploymentVM
{
    public string EmploymentType { get; set; }
    public string Employer { get; set; }
    public string Position { get; set; }
    public double GrossMonthlyIncome { get; set; }
    public DateTime? StartDate { get; set; }
    public string AutonomousActivity { get; set; }
}
</code>```

In the view I have:

```<code>                <div class="form-group">
                    @Html.LabelFor(x => x.Employer)
                    @Html.TextBoxFor(x => x.Employer, new { @class = "form-control required" })
                </div>
                <div class="form-group">
                    @Html.LabelFor(x => x.Position)
                    @Html.TextBoxFor(x => x.Position, new { @class = "form-control required" })
                </div>
                <div class="form-group">
                    @Html.LabelFor(x => x.GrossMonthlyIncome)
                    @Html.TextBoxFor(x => x.GrossMonthlyIncome, new { @class = "form-control required digits" })
                </div>
</code>```

and so on for the different properties.

The controller is very basic:

```<code>[HttpPost]
    public ActionResult EmploymentInfo(EmploymentVM vm)
    {
        //the actual code to save employment
        return View();
    }
</code>```

I want to save the model with the property AutonomousActivity only if the user clicked the checkbox IsAutonomous, or save the properties Employer and Position if the checkbox is not checked.

How can I achieve that, does the model binder do that for me?

答:
```<code> public class EmploymentVM
 {
public string EmploymentType { get; set; }
public string Employer { get; set; }
public string Position { get; set; }
public double GrossMonthlyIncome { get; set; }
public DateTime? StartDate { get; set; }
public string AutonomousActivity { get; set; }
public bool IsAutonomous { get; set; } //add in viewmodel bind it with checkbox

}
</code>```

Controller:

```<code> public ActionResult EmploymentInfo(Employments vm)
{
   if(vm.IsAutonomous) {
    // you can set the value null/empty to any property
      vm.Employer =null;

    //save it
   }
   else {
        // if checkbox is not checked
       //save it
    }

    return View();
}
</code>```

Body:
I have a model like this:

 public class EmploymentVM
{
    public string EmploymentType { get; set; }
    public string Employer { get; set; }
    public string Position { get; set; }
    public double GrossMonthlyIncome { get; set; }
    public DateTime? StartDate { get; set; }
    public string AutonomousActivity { get; set; }
}

In the view I have:

                    @Html.LabelFor(x => x.Employer)
                    @Html.TextBoxFor(x => x.Employer, new { @class = "form-control required" })

                    @Html.LabelFor(x => x.Position)
                    @Html.TextBoxFor(x => x.Position, new { @class = "form-control required" })

                    @Html.LabelFor(x => x.GrossMonthlyIncome)
                    @Html.TextBoxFor(x => x.GrossMonthlyIncome, new { @class = "form-control required digits" })

and so on for the different properties.

The controller is very basic:

[HttpPost]
    public ActionResult EmploymentInfo(EmploymentVM vm)
    {
        //the actual code to save employment
        return View();
    }

I want to save the model with the property AutonomousActivity only if the user clicked the checkbox IsAutonomous, or save the properties Employer and Position if the checkbox is not checked.

How can I achieve that, does the model binder do that for me?

Body:
 public class EmploymentVM
 {
public string EmploymentType { get; set; }
public string Employer { get; set; }
public string Position { get; set; }
public double GrossMonthlyIncome { get; set; }
public DateTime? StartDate { get; set; }
public string AutonomousActivity { get; set; }
public bool IsAutonomous { get; set; } //add in viewmodel bind it with checkbox

}

Controller:

 public ActionResult EmploymentInfo(Employments vm)
{
   if(vm.IsAutonomous) {
    // you can set the value null/empty to any property
      vm.Employer =null;

    //save it
   }
   else {
        // if checkbox is not checked
       //save it
    }

    return View();
}


问:
What is the difference between tensorflow conv2d_transpose and conv2d_backprop_filter?
Can someone please explain in simple terms and examples on how these work after performing the conv2d forward pass.

Let me add to this question - What is the difference between conv2d_backprop_filter and tf.nn.conv2d_backprop_input?

答:
Plese see this answer for a detailed example of how tf.nn.conv2d_backprop_input and tf.nn.conv2d_backprop_filter in an example.

A short answer to your question:

In tf.nn, there are 4 closely related 2d conv functions:

tf.nn.conv2d

tf.nn.conv2d_backprop_filter

tf.nn.conv2d_backprop_input

tf.nn.conv2d_transpose

Given out = conv2d(x, w) and the output gradient d_out:

Use tf.nn.conv2d_backprop_filter to compute the filter gradient d_w

Use tf.nn.conv2d_backprop_input to compute the filter gradient d_x

tf.nn.conv2d_backprop_input can be implemented by tf.nn.conv2d_transpose

All 4 functions above can be implemented by tf.nn.conv2d

Actually, use TF's autodiff is the fastest way to compute gradients


问:
Javascript Use a returned value for a boolean comparison
If I have:

```<code>function Function1(){
    var Value = true;

    return Value;

};
</code>```

How can I use the returned value "Value" in another function for it to be used as true, if I use it as below, it doesn't returns nothing.

```<code>function Function2(){
    if(Function1 == true){
        console.log("Hello")
    }
}
</code>```

答:
```<code>function Function2(){
    if(Function1() == true){
        console.log("Hello")
    }
}
</code>```

only replace Function2 with Function2()

Body:
If I have:

function Function1(){
    var Value = true;

    return Value;

};

How can I use the returned value "Value" in another function for it to be used as true, if I use it as below, it doesn't returns nothing.

function Function2(){
    if(Function1 == true){
        console.log("Hello")
    }
}

Body:
function Function2(){
    if(Function1() == true){
        console.log("Hello")
    }
}

only replace Function2 with Function2()


问:
Binding to multiple button clicks
To bind to the 1 key I use:

```<code>hs.hotkey.bind(hyper, '1'
</code>```

How to bind to multiple presses of 1 key? Something like:

```<code>hs.hotkey.bind(hyper, '1+1'
</code>```

Reading the documentation, this functionality is not mentioned.

By multiple presses I mean press 1 twice to run some code and press 1 three times to run a separate piece of code.

答:
You're going to have to implement this yourself. Here's a basic summary of how to accomplish this:

Start a timer from zero, and set a flag for the first press initially to false, which indicates the first press has not happened yet

Observe and watch keypresses with hs.eventtap, specifically hs.eventtap.event.types.keyPress

When the event (keyPress) happens, check if the key pressed was the correct key

If it was the right key, check if it's the second press and if it was in time, if it wasn't in time or was not the second press then set the timer to the current time and first flag to true

If it was the second press and was in time, then execute our handler and reset timer and first flag

If it wasn't the right key then reset the timer and first flag

Translated into code, this is what is could look like (I'm not a Lua expert). Note that the flags could be implemented as booleans here, or as an internal table holding keypresses so far which you could check:

local timer = require("hs.timer")
local eventtap = require("hs.eventtap")
local keycodes = require("hs.keycodes")
local events = eventtap.event.types --all the event types

timeFrame = 1 --this is the timeframe in which the second press should occur, in seconds
key = 50 --the specific keycode we're detecting, in this case, 50

--print(keycodes.map["`"]) you can look up the certain keycode by accessing the map

function twoHandler()
    hs.alert("Pressed ` twice!") --the handler for the double press
end

function correctKeyChecker(event) --keypress validator, checks if the keycode matches the key we're trying to detect
    local keyCode = event:getKeyCode()
    return keyCode == key --return if keyCode is key
end

function inTime(time) --checks if the second press was in time
    return timer.secondsSinceEpoch() - time < timeFrame --if the time passed from the first press to the second was less than the timeframe, then it was in time
end

local pressTime, firstDown = 0, false --pressTime was the time the first press occurred which is set to 0, and firstDown indicates if the first press has occurred or not

eventtap.new({ events.keyDown }, function(event) --watch the keyDown event, trigger the function every time there is a keydown
    if correctKeyChecker(event) then --if correct key
        if firstDown and inTime(pressTime) then --if first press already happened and the second was in time
            twoHandler() --execute the handler
        elseif not firstDown or inTime(pressTime) then --if the first press has not happened or the second wasn't in time
            pressTime, firstDown = timer.secondsSinceEpoch(), true --set first press time to now and first press to true
            return false --stop prematurely
        end
    end
    pressTime, firstDown = 0, false --if it reaches here that means the double tap was successful or the key was incorrect, thus reset timer and flag
    return false --keeps the event propogating
end):start() --start our watcher
```

I've commented the code line-by-line for a better understanding. If you want to detect 3 or 4 or some other arbitrary N number of presses, just set flags for N - 1 presses and add a few checks, but it's unusual to have key combinations that take more than 2 successive presses. It does seem a little verbose, but AFAIK this is how you do it. To avoid duplicate code and boilerplate, try putting this in a class-like structure or a module so that you can reuse code.

As for executing a different handler for 2 successive presses, or 3 successive presses, that would be a little more hacky since you would have to wait the whole timeframe before knowing if the user will press again to know which handler to execute. That would cause a slight delay and a bad user experience, I would suggest against that, though you could probably implement that by refactoring the code and doing some more checks such as if it's the timeframe and the first flag was triggered, then execute the handler for one press.

Title: Binding to multiple button clicks

Body:
To bind to the 1 key I use:

hs.hotkey.bind(hyper, '1'

How to bind to multiple presses of 1 key? Something like:

hs.hotkey.bind(hyper, '1+1'

Reading the documentation, this functionality is not mentioned.

By multiple presses I mean press 1 twice to run some code and press 1 three times to run a separate piece of code.

Body:
You're going to have to implement this yourself. Here's a basic summary of how to accomplish this:

Start a timer from zero, and set a flag for the first press initially to false, which indicates the first press has not happened yet

Observe and watch keypresses with hs.eventtap, specifically hs.eventtap.event.types.keyPress

When the event (keyPress) happens, check if the key pressed was the correct key

If it was the right key, check if it's the second press and if it was in time, if it wasn't in time or was not the second press then set the timer to the current time and first flag to true

If it was the second press and was in time, then execute our handler and reset timer and first flag

If it wasn't the right key then reset the timer and first flag

Translated into code, this is what is could look like (I'm not a Lua expert). Note that the flags could be implemented as booleans here, or as an internal table holding keypresses so far which you could check:

local timer = require("hs.timer")
local eventtap = require("hs.eventtap")
local keycodes = require("hs.keycodes")
local events = eventtap.event.types --all the event types

timeFrame = 1 --this is the timeframe in which the second press should occur, in seconds
key = 50 --the specific keycode we're detecting, in this case, 50

--print(keycodes.map["`"]) you can look up the certain keycode by accessing the map

function twoHandler()
    hs.alert("Pressed ` twice!") --the handler for the double press
end

function correctKeyChecker(event) --keypress validator, checks if the keycode matches the key we're trying to detect
    local keyCode = event:getKeyCode()
    return keyCode == key --return if keyCode is key
end

function inTime(time) --checks if the second press was in time
    return timer.secondsSinceEpoch() - time < timeFrame --if the time passed from the first press to the second was less than the timeframe, then it was in time
end

local pressTime, firstDown = 0, false --pressTime was the time the first press occurred which is set to 0, and firstDown indicates if the first press has occurred or not

eventtap.new({ events.keyDown }, function(event) --watch the keyDown event, trigger the function every time there is a keydown
    if correctKeyChecker(event) then --if correct key
        if firstDown and inTime(pressTime) then --if first press already happened and the second was in time
            twoHandler() --execute the handler
        elseif not firstDown or inTime(pressTime) then --if the first press has not happened or the second wasn't in time
            pressTime, firstDown = timer.secondsSinceEpoch(), true --set first press time to now and first press to true
            return false --stop prematurely
        end
    end
    pressTime, firstDown = 0, false --if it reaches here that means the double tap was successful or the key was incorrect, thus reset timer and flag
    return false --keeps the event propogating
end):start() --start our watcher

I've commented the code line-by-line for a better understanding. If you want to detect 3 or 4 or some other arbitrary N number of presses, just set flags for N - 1 presses and add a few checks, but it's unusual to have key combinations that take more than 2 successive presses. It does seem a little verbose, but AFAIK this is how you do it. To avoid duplicate code and boilerplate, try putting this in a class-like structure or a module so that you can reuse code.

As for executing a different handler for 2 successive presses, or 3 successive presses, that would be a little more hacky since you would have to wait the whole timeframe before knowing if the user will press again to know which handler to execute. That would cause a slight delay and a bad user experience, I would suggest against that, though you could probably implement that by refactoring the code and doing some more checks such as if it's the timeframe and the first flag was triggered, then execute the handler for one press.


问:
Adding script tag before the end of body tag(Not Working)
In the below Code,I have added the script tag before the end of the body tag.So from my understanding,I should get html content first,in this case the header tag and three paragraph tags.After that,I should get the alert box.But I am getting the opposite.Alert box is being displayed first before the html content.I am not able to understand why.Please help me on this.Thanks in advance :)       </p>

```<code><html>

    <head>

        <title>Todo List</title>

    </head>

    <body>

    <h1>Todo List</h1>

    <p>new ---> Add A Todo</p>
    <p>list ---> List All Todos</p>
    <p>quit ----> Quit App</p>

    <script type="text/javascript">alert('h')</script>

    </body>

    </html>
</code>```

答: HTML page loads as it follows unless you use any define any importance. Here you are right but the situation is HTML shows for micro sec or even less which we can't see. Then the alert box shows up. For this reason, it seems different from the theory but you can call as an illusion. </p>

Body:
In the below Code,I have added the script tag before the end of the body tag.So from my understanding,I should get html content first,in this case the header tag and three paragraph tags.After that,I should get the alert box.But I am getting the opposite.Alert box is being displayed first before the html content.I am not able to understand why.Please help me on this.Thanks in advance :)

        <title>Todo List</title>

Todo List

new ---> Add A Todo

list ---> List All Todos

quit ----> Quit App


问:
How to create a GET request for checked checkboxes and then display it on the HTML page?
I'm creating an app for a project and I'm stuck with this feature. I've already created a POST method for the checked checkboxes but I don't know how to get that information and then display it on my HTML page. I'm not sure with my GET method.  It's basically an edit page feature. And we're only supposed to use AJAX and flask. Please help.</p>

```<code>function edit_food() {
    console.log($('input[name="food"]:checked').serialize());

    $.ajax({
        url: 'http://127.0.0.1:5000/edit_food.html/',
        data: JSON.stringify({}),
        type: "POST",
        dataType: "json",
        success: function (newSet) {
            $('input[name="food"]:checked');
            if (newSet.status == 'ok') {
                alert("SAVED!")
            }
        },
        error: function (e) {
            alert("Something went wrong!");
        }
    });

   var $set = $('#set');

    $.ajax({
        url: 'http://127.0.0.1:5000/food.html/',
        data: JSON.stringify({}),
        type: "GET",
        dataType: "json",
        success: function (set) {
            $('input[name="food"]:checked');
            if (set.status == 'ok') {
                alert("SAVED!")
            }
        },
        error: function(e) {
            alert("Something went wrong!");
        }
    });
}
</code>```

答:
When you use Ajax, you can return data type string, json, or html.
I often return json data or html data.
With html data you can using:</p>

```<code>.done(function(res){
    $('#id_reaload').html(res);
})
</code>```

Body:
I'm creating an app for a project and I'm stuck with this feature. I've already created a POST method for the checked checkboxes but I don't know how to get that information and then display it on my HTML page. I'm not sure with my GET method.  It's basically an edit page feature. And we're only supposed to use AJAX and flask. Please help.

function edit_food() {
    console.log($('input[name="food"]:checked').serialize());

    $.ajax({
        url: 'http://127.0.0.1:5000/edit_food.html/',
        data: JSON.stringify({}),
        type: "POST",
        dataType: "json",
        success: function (newSet) {
            $('input[name="food"]:checked');
            if (newSet.status == 'ok') {
                alert("SAVED!")
            }
        },
        error: function (e) {
            alert("Something went wrong!");
        }
    });

   var $set = $('#set');

    $.ajax({
        url: 'http://127.0.0.1:5000/food.html/',
        data: JSON.stringify({}),
        type: "GET",
        dataType: "json",
        success: function (set) {
            $('input[name="food"]:checked');
            if (set.status == 'ok') {
                alert("SAVED!")
            }
        },
        error: function(e) {
            alert("Something went wrong!");
        }
    });
}

Body:
When you use Ajax, you can return data type string, json, or html.
I often return json data or html data.
With html data you can using:

.done(function(res){
    $('#id_reaload').html(res);
})


问:
InsertionSort on Linked List , with Data from text file. Java
I'm doing insertion sort with my Linked List, and I have faced an issue.

My Data file:

```<code>Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44
</code>```

Here is my code for Insertion Sort

```<code>public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedNode;
          sortedNode = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }
</code>```

My currently output:

```<code>Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null
</code>```

they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help.  I'm very new in Java. Thank you so much.

My Data Class

```<code>public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

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

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}
</code>```

Here is my LinkedList Class:

```<code>public class LinkedList {
Node head;
Node prev;
Node cur;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head);
        l1.printLinkedList();
        System.out.println("************");
}
}
</code>```

Here is my Node Class:

```<code>public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}

public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator"));
    sb.append(next).append(System.getProperty("line.separator"));

    return sb.toString();

}
}
</code>```

The insertionSort method is inside the LinkedList Class.

答:
Ok So the code fragment below Here is my code for Insertion Sort is making some serious workarounds that I guess even you won't be able to properly imagine :).

Try breaking your problem into simpler steps, How would you have gone to implement a LinkedList where you could just add an Integer(Anything really, just the OOP complexity varies) in Ascending or Descending form. The following code that I just tested would help you atleast see how you should have implemented a LinkedList that grows via InsertionSort algo , note that this is dealing the ascending order case

```<code>public class LinkedList
{

    public Node first , last;

    public class Node
    {
        public int data;

        public Node next;

        public Node( int data )
        {
            this.data = data;
        }
    }

    public void addInsertSort( int num )
    {
        if( isEmpty() )
        {
            first = new Node( num );
            last = first;
        }
        else
        {
            Node newNode = new Node( num );
            Node curNode = first , preNode = null;
            while( curNode != null && newNode.data > curNode.data )
            {
                preNode = curNode;
                curNode = curNode.next;
            }
            if( curNode == first )
            {
                newNode.next = first;
                first = newNode;
            }
            else
            {
                if( curNode != null && preNode != null ) //middle of list
                {
                    newNode.next = curNode;
                    preNode.next = newNode;
                }
                else if( curNode == null ) // end of list
                {
                    preNode.next = newNode;
                    last = newNode;
                }
            }
        }
    }

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

    public String toString()
    {
        String str = "[";
        for( Node curNode = first; curNode != null; curNode = curNode.next )
        {
            str += curNode.data + " ";
        }
        return str + "]";
    }

    public static void main( String[] args )
    {
        LinkedList list = new LinkedList();

        list.addInsertSort( 4 );
        list.addInsertSort( 5 );
        list.addInsertSort( 1 );
        list.addInsertSort( 6 );
        list.addInsertSort( 10 );
        list.addInsertSort( 0 );

        System.out.println( list );
    }

}
</code>```

Im sorry, the code editor here is REALLY KILLING ME, please don't mind the frequent re-edits

Now going on with how you would integrate this idea in your methods, you can fix things like this, and make sure it looks exactly this way

```<code>// You really dont need more variables in your LinkedList class
// Both of these are enough, forget currentNode reference
public Node head , last;

public void initializeLL(){
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            addInsertSort( n );
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public Node addInsertSort( Node newNode )
{
    if( isEmpty() )
    {
        head = newNode;
        last = head;
    }
    else
    {
        Node curNode = head , preNode = null;
        // This is How InsertionSort would have gone to search the list
        while( curNode != null && newNode.getData().getNum() > curNode.getData().getNum() )
        {
            preNode = curNode;
            curNode = curNode.next;
        }
        //Thats the happy ending of the insertionSort algo
        //Now we need to link newNode with OUR DYNAMICALLY GROWING LIST
        //When the insertion Algo stopped, It told us where the newNode
        //shall be placed in comparison to the current state of list

        // Is this supposed to be the head node now??
        if( curNode == head )
        {
            newNode.next = head;
            head = newNode;
        }
        else // maybe we landed BETWEEN the list or at the END OF LIST??
        {
            if( curNode != null && preNode != null ) //BETWEEN THE list
            {
                newNode.next = curNode;
                preNode.next = newNode;
            }
            else if( curNode == null ) // end of list
            {
                preNode.next = newNode;
                last = newNode;
            }
        }
    }
    return newNode;
}

public boolean isEmpty()
{
    return head == null;
}
</code>```

Let me know if something still goes wrong, I will explain more deeply

Body:
I'm doing insertion sort with my Linked List, and I have faced an issue.

My Data file:

Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44

Here is my code for Insertion Sort

public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedNode;
          sortedNode = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }

My currently output:

Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null

they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help.  I'm very new in Java. Thank you so much.

My Data Class

public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

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

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}

Here is my LinkedList Class:

public class LinkedList {
Node head;
Node prev;
Node cur;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head);
        l1.printLinkedList();
        System.out.println("************");
}
}

Here is my Node Class:

public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}

public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator"));
    sb.append(next).append(System.getProperty("line.separator"));

    return sb.toString();

}
}

The insertionSort method is inside the LinkedList Class.

Body:
Ok So the code fragment below Here is my code for Insertion Sort is making some serious workarounds that I guess even you won't be able to properly imagine :).

Try breaking your problem into simpler steps, How would you have gone to implement a LinkedList where you could just add an Integer(Anything really, just the OOP complexity varies) in Ascending or Descending form. The following code that I just tested would help you atleast see how you should have implemented a LinkedList that grows via InsertionSort algo , note that this is dealing the ascending order case

public class LinkedList
{

    public Node first , last;

    public class Node
    {
        public int data;

        public Node next;

        public Node( int data )
        {
            this.data = data;
        }
    }

    public void addInsertSort( int num )
    {
        if( isEmpty() )
        {
            first = new Node( num );
            last = first;
        }
        else
        {
            Node newNode = new Node( num );
            Node curNode = first , preNode = null;
            while( curNode != null && newNode.data > curNode.data )
            {
                preNode = curNode;
                curNode = curNode.next;
            }
            if( curNode == first )
            {
                newNode.next = first;
                first = newNode;
            }
            else
            {
                if( curNode != null && preNode != null ) //middle of list
                {
                    newNode.next = curNode;
                    preNode.next = newNode;
                }
                else if( curNode == null ) // end of list
                {
                    preNode.next = newNode;
                    last = newNode;
                }
            }
        }
    }

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

    public String toString()
    {
        String str = "[";
        for( Node curNode = first; curNode != null; curNode = curNode.next )
        {
            str += curNode.data + " ";
        }
        return str + "]";
    }

    public static void main( String[] args )
    {
        LinkedList list = new LinkedList();

        list.addInsertSort( 4 );
        list.addInsertSort( 5 );
        list.addInsertSort( 1 );
        list.addInsertSort( 6 );
        list.addInsertSort( 10 );
        list.addInsertSort( 0 );

        System.out.println( list );
    }

}

Im sorry, the code editor here is REALLY KILLING ME, please don't mind the frequent re-edits

Now going on with how you would integrate this idea in your methods, you can fix things like this, and make sure it looks exactly this way

// You really dont need more variables in your LinkedList class
// Both of these are enough, forget currentNode reference
public Node head , last;

public void initializeLL(){
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            addInsertSort( n );
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public Node addInsertSort( Node newNode )
{
    if( isEmpty() )
    {
        head = newNode;
        last = head;
    }
    else
    {
        Node curNode = head , preNode = null;
        // This is How InsertionSort would have gone to search the list
        while( curNode != null && newNode.getData().getNum() > curNode.getData().getNum() )
        {
            preNode = curNode;
            curNode = curNode.next;
        }
        //Thats the happy ending of the insertionSort algo
        //Now we need to link newNode with OUR DYNAMICALLY GROWING LIST
        //When the insertion Algo stopped, It told us where the newNode
        //shall be placed in comparison to the current state of list

        // Is this supposed to be the head node now??
        if( curNode == head )
        {
            newNode.next = head;
            head = newNode;
        }
        else // maybe we landed BETWEEN the list or at the END OF LIST??
        {
            if( curNode != null && preNode != null ) //BETWEEN THE list
            {
                newNode.next = curNode;
                preNode.next = newNode;
            }
            else if( curNode == null ) // end of list
            {
                preNode.next = newNode;
                last = newNode;
            }
        }
    }
    return newNode;
}

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

Let me know if something still goes wrong, I will explain more deeply


答:
In order to get the returned value you need to call the function first. What you're doing is evaluating the function itself, not the returned value.

You also don't need the == true part because it will evaluate the returned value anyway.

Change your code to:

```<code>function Function2(){
    if(Function1()){
        console.log("Hello")
    }
}
</code>```

Title: Javascript Use a returned value for a boolean comparison

Body:
In order to get the returned value you need to call the function first. What you're doing is evaluating the function itself, not the returned value.

You also don't need the == true part because it will evaluate the returned value anyway.

Change your code to:

function Function2(){
    if(Function1()){
        console.log("Hello")
    }
}


答:
Function2 needs to be like this:

```<code>function Function2(){
    if(Function1()){
        console.log("Hello");
    }
}
</code>```

It is because you are calling a function and not a variable.
So since you are calling Function1 you need to make sure that you are calling it like this Function1().

If you are calling a variable you can just use the name.

And also since it is a variable of type boolean you can simply use if(Function1()) and omit the == true.

And you call it like this:

```<code>var k = Function1();
</code>```

Body:
Function2 needs to be like this:

function Function2(){
    if(Function1()){
        console.log("Hello");
    }
}

It is because you are calling a function and not a variable.
So since you are calling Function1 you need to make sure that you are calling it like this Function1().

If you are calling a variable you can just use the name.

And also since it is a variable of type boolean you can simply use if(Function1()) and omit the == true.

And you call it like this:

var k = Function1();


问:
Android studio 2.3.2 gradle issue
I am fairly new to Android. Installed Android studio 2.3.2. Now I have created a sample project.

But the popup of building gradle project info is shown forever.

答: Try deleting gradle folder within your Project Folder. Then close and reopen your project in Android studio.</p>

Title: Android studio 2.3.2 gradle issue


问:
select all data of date between the given date in ms access
i am trying to select all the data of month 5 from my table
using the query

```<code>SELECT cout.badgenumber,cout.Checktime FROM CHECKINOUT cout
inner join userinfo ui on(ui.userid=cout.userid)
WHERE cout.Checktime between #05/01/2017# and #05/31/2017#
and ui.badgenumber='1021'
</code>```

and

```<code>SELECT cout.badgenumber,cout.Checktime FROM CHECKINOUT cout
inner join userinfo ui on(ui.userid=cout.userid)
WHERE cout.Checktime>#05/01/2017# and cout.Checktime<=#05/31/2017#
and ui.badgenumber='1021'
</code>```

but both gives data excluding the data of 31

when i try to use 32 in between date as

```<code> SELECT cout.badgenumber,cout.Checktime FROM CHECKINOUT cout
    inner join userinfo ui on(ui.userid=cout.userid)
    WHERE cout.Checktime between #05/01/2017# and #05/32/2017#
    and ui.badgenumber='1021'
</code>```

syntax error in date query expression error comes

答:
Please try the following...

```<code>SELECT cout.badgenumber,
       cout.Checktime
FROM CHECKINOUT cout
INNER JOIN userinfo ui ON ( ui.userid = cout.userid )
WHERE MONTH( cout.Checktime ) = 5
  AND ui.badgenumber = '1021'
</code>```

This answer uses the MONTH() function to extract a numerical representation of the month from the date passed to it and compares it to 5 (the numerical representation of May).

Please read https://support.office.com/en-us/article/Month-Function-78182042-7bf0-46e9-829e-c7012f773fc5 for more information on the MONTH() function.

If you have any questuions or comments, then please feel free to post a comment accordingly.

Body:
i am trying to select all the data of month 5 from my table
using the query

SELECT cout.badgenumber,cout.Checktime FROM CHECKINOUT cout
inner join userinfo ui on(ui.userid=cout.userid)
WHERE cout.Checktime between #05/01/2017# and #05/31/2017#
and ui.badgenumber='1021'

and

SELECT cout.badgenumber,cout.Checktime FROM CHECKINOUT cout
inner join userinfo ui on(ui.userid=cout.userid)
WHERE cout.Checktime>#05/01/2017# and cout.Checktime<=#05/31/2017#
and ui.badgenumber='1021'

but both gives data excluding the data of 31

when i try to use 32 in between date as

 SELECT cout.badgenumber,cout.Checktime FROM CHECKINOUT cout
    inner join userinfo ui on(ui.userid=cout.userid)
    WHERE cout.Checktime between #05/01/2017# and #05/32/2017#
    and ui.badgenumber='1021'

syntax error in date query expression error comes

Body:
Please try the following...

SELECT cout.badgenumber,
       cout.Checktime
FROM CHECKINOUT cout
INNER JOIN userinfo ui ON ( ui.userid = cout.userid )
WHERE MONTH( cout.Checktime ) = 5
  AND ui.badgenumber = '1021'

This answer uses the MONTH() function to extract a numerical representation of the month from the date passed to it and compares it to 5 (the numerical representation of May).

Please read https://support.office.com/en-us/article/Month-Function-78182042-7bf0-46e9-829e-c7012f773fc5 for more information on the MONTH() function.

If you have any questuions or comments, then please feel free to post a comment accordingly.


答:
Maybe you have to type brackets '()' after the function:

```<code>function Function2(){
    if(Function1() == true){
        console.log("Hello")
    }
}
</code>```

Because now Syntax Parser thinks that Function1 is a variable.

Body:
Maybe you have to type brackets '()' after the function:

function Function2(){
    if(Function1() == true){
        console.log("Hello")
    }
}

Because now Syntax Parser thinks that Function1 is a variable.


问:
get this node value after added event listener by looping
Let's say I have several textareas, and I want to add event listener to each textarea. When I type inside a textarea, I need to console the value typed inside it. I just can't figure out how to refer "this" to each textarea called in looping when being added event listener. The code below results in "undefined" in the browser console. Maybe you can set it right. Appricated the help. Thank you very much.</p>

```<code>window.addEventListener("load", function(){
    var char_max_inputs = document.querySelectorAll('.char_max');
    for (var i = 0; i < char_max_inputs.length; i++){
        var max_char = char_max_inputs[i].getAttribute("max_char");
        var counter_id = char_max_inputs[i].getAttribute("counter_id");
        char_max_inputs[i].addEventListener("keyup", function(){count_char(counter_id, max_char);}, false);
    }
});

function count_char(counter_id, max_char) {
    console.log(this.value);
}
</code>```

答:
You can solve it like this by using Function.prototype.bind

window.addEventListener("load", function() {
  var char_max_inputs = document.querySelectorAll('.char_max');
  for (var i = 0; i < char_max_inputs.length; i++) {
    var max_char = char_max_inputs[i].getAttribute("max_char");
    var counter_id = char_max_inputs[i].getAttribute("counter_id");
    char_max_inputs[i].addEventListener("keyup", count_char.bind(char_max_inputs[i], counter_id, max_char), false);
  }
});

function count_char(counter_id, max_char) {
  console.log(this.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea></code>```

this can be very confusing in JavaScript, if not read about properly. An excellent resource to understand it is here

UPDATE

As pointed out in the comments, the example using call and bind together was incomplete. Removing it.

Body:
Let's say I have several textareas, and I want to add event listener to each textarea. When I type inside a textarea, I need to console the value typed inside it. I just can't figure out how to refer "this" to each textarea called in looping when being added event listener. The code below results in "undefined" in the browser console. Maybe you can set it right. Appricated the help. Thank you very much.

window.addEventListener("load", function(){
    var char_max_inputs = document.querySelectorAll('.char_max');
    for (var i = 0; i < char_max_inputs.length; i++){
        var max_char = char_max_inputs[i].getAttribute("max_char");
        var counter_id = char_max_inputs[i].getAttribute("counter_id");
        char_max_inputs[i].addEventListener("keyup", function(){count_char(counter_id, max_char);}, false);
    }
});

function count_char(counter_id, max_char) {
    console.log(this.value);
}

Body:
You can solve it like this by using Function.prototype.bind

window.addEventListener("load", function() {
  var char_max_inputs = document.querySelectorAll('.char_max');
  for (var i = 0; i < char_max_inputs.length; i++) {
    var max_char = char_max_inputs[i].getAttribute("max_char");
    var counter_id = char_max_inputs[i].getAttribute("counter_id");
    char_max_inputs[i].addEventListener("keyup", count_char.bind(char_max_inputs[i], counter_id, max_char), false);
  }
});

function count_char(counter_id, max_char) {
  console.log(this.value);
}

<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>
<textarea class="char_max"></textarea>

this can be very confusing in JavaScript, if not read about properly. An excellent resource to understand it is here

UPDATE

As pointed out in the comments, the example using call and bind together was incomplete. Removing it.


问:
Windows App Certification Kit stuck at language select. Should I proceed manually?
The main window asks me not to interact, but it's not progressing at all - I've left it for over half an hour. My setup is made using Inno Setup 5.5.9. From what I understand the whole process should be automatic, but as you can see it's not working, and I'm not sure what to do now.

答:
In case you want to do this in future (or for anyone else with the same issue who comes looking for this question) I did have a similar issue myself. I have no experience with Inno Setup but I used an MSI file created through a Visual Studio Installer project. It would get stuck on the first screen of the installer.

There should be a stage before the you start running the tests (the same stage when it asks for the file) when it asks for any parameters. I took this as an opportunity to include the same parameters I would use when running MSIExec.exe from the command line if I wanted an install to do a silent install (/qn). Presumably a passive install would have worked as well.

Looking at http://www.jrsoftware.org/ishelp/index.php?topic=setupcmdline, it appears Inno Setup should accept parameters such as /verysilent and /sp. I would expect these to have the same effect.


问:
Standard .NET side enum
I often use enums like

```<code>public enum Side { Left, Top, Right, Bottom };
</code>```

or

```<code>public enum Direction { Left, Up, Right, Down };
</code>```

Every time I describe the enum again. Is there a standard enum of this kind in .NET?

答: Old and answered, but there is a ArrowDirection enum. See https://msdn.microsoft.com/en-us/library/system.windows.forms.arrowdirection(v=vs.110).aspx.  Unfortunately, it is in System.Windows.Forms.

Title: Standard .NET side enum

Body:
I often use enums like

public enum Side { Left, Top, Right, Bottom };

or

public enum Direction { Left, Up, Right, Down };

Every time I describe the enum again. Is there a standard enum of this kind in .NET?


问:
Getting Module build failed: RangeError: Maximum call stack size exceeded after upgrade to Ionic 3
I have just gone upgraded my Ionic 2 app to Ionic 3, all of framework, Ionic native, and the CLI.

I now have the following setup..

```<code>    "dependencies": {
        "@angular/animations": "4.1.0",
        "@angular/common": "4.1.0",
        "@angular/compiler": "4.1.0",
        "@angular/compiler-cli": "4.1.0",
        "@angular/core": "^4.1.0",
        "@angular/forms": "4.1.0",
        "@angular/http": "^4.1.0",
        "@angular/platform-browser": "4.1.0",
        "@angular/platform-browser-dynamic": "4.1.0",
        "@ionic-native/app-version": "^3.8.0",
        "@ionic-native/core": "3.6.1",
        "@ionic-native/device": "^3.8.0",
        "@ionic-native/file": "^3.7.0",
        "@ionic-native/network": "^3.8.0",
        "@ionic-native/social-sharing": "^3.7.0",
        "@ionic-native/splash-screen": "3.6.1",
        "@ionic-native/status-bar": "3.6.1",
        "@ionic-native/toast": "^3.8.0",
        "@ionic/storage": "2.0.1",
        "c3": "^0.4.11",
        "ionic-angular": "3.2.1",
        "ionicons": "3.0.0",
        "js-logger": "^1.3.0",
        "jslogger": "^1.0.3",
        "jszip": "^3.1.3",
        "lodash": "^4.17.4",
        "moment": "^2.17.1",
        "moment-duration-format": "^1.3.0",
        "ng2-translate": "^5.0.0",
        "rxjs": "5.1.1",
        "semaphore-async-await": "^1.3.2",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.10"
      },
      "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "@ionic/cli-plugin-ionic-angular": "1.0.0",
        "@types/c3": "^0.4.38",
        "@types/jasmine": "^2.5.42",
        "@types/jszip": "0.0.32",
        "@types/lodash": "^4.14.51",
        "@types/moment-duration-format": "^1.3.1",
        "@types/node": "^7.0.5",
        "codecov": "^1.0.1",
        "install": "^0.8.7",
        "jasmine-core": "^2.5.2",
        "jasmine-spec-reporter": "^3.2.0",
        "karma": "^1.4.1",
        "karma-chrome-launcher": "^2.0.0",
        "karma-jasmine": "^1.1.0",
        "karma-mocha-reporter": "^2.2.2",
        "karma-remap-istanbul": "^0.6.0",
        "ts-node": "^2.1.0",
        "tslint": "^4.4.2",
        "tslint-eslint-rules": "^3.3.0",
        "typescript": "^2.2.1"
      },
</code>```

Now, if I build with the -prod flag (it id fine without this), I get the following error...

```<code>    [16:50:08]  webpack started ...
    Error: ./~/jszip/lib/index.js
    Module build failed: RangeError: Maximum call stack size exceeded
        at Object.forEachChild (D:\dev\myapp\node_modules\typescript\lib\typescript.js:14735:26)
        at traverse (D:\dev\myapp\node_modules\typescript\lib\typescript.js:7271:31)
        at Object.forEachReturnStatement (D:\dev\myapp\node_modules\typescript\lib\typescript.js:7251:16)
        at checkAndAggregateReturnExpressionTypes (D:\dev\myapp\node_modules\typescript\lib\typescript.js:40055:16)
        at getReturnTypeFromBody (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39965:29)
        at getReturnTypeOfSignature (D:\dev\myapp\node_modules\typescript\lib\typescript.js:31190:28)
        at resolveNewExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39483:21)
        at resolveSignature (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39639:28)
        at getResolvedSignature (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39669:26)
        at checkCallExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39696:29)
     @ ./src/providers/file-logger.ts 58:0-28
     @ ./src/app/app.module.ngfactory.ts
     @ ./src/app/main.ts,./~/d3/d3.js
    Module build failed: RangeError: Maximum call stack size exceeded
        at RegExp.[Symbol.replace] (native)
        at String.replace (native)
        at formatStringFromArgs (D:\dev\myapp\node_modules\typescript\lib\typescript.js:2365:21)
        at Object.chainDiagnosticMessages (D:\dev\myapp\node_modules\typescript\lib\typescript.js:2433:20)
        at reportNonexistentProperty (D:\dev\myapp\node_modules\typescript\lib\typescript.js:38290:28)
        at checkPropertyAccessExpressionOrQualifiedName (D:\dev\myapp\node_modules\typescript\lib\typescript.js:38332:
    21)
        at checkPropertyAccessExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:38274:20)
        at checkExpressionWorker (D:\dev\myapp\node_modules\typescript\lib\typescript.js:41158:28)
        at checkExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:41115:42)
        at checkExpressionWithContextualType (D:\dev\myapp\node_modules\typescript\lib\typescript.js:40983:26)
     @ ./src/pages/mypage/mypage.ts 61:0-25
     @ ./src/app/app.module.ts
     @ ./src/app/app.module.ngfactory.ts
     @ ./src/app/main.ts
</code>```

I have tracked this down to the 2 libs  C3/D3, and jszip. If I use either of these in a small newly created Ionic 3 app, then there is not a problem.

I have gone through many many other reports of webpack throwing this error, but just cannot see why this is now happening for me, in my existing project.

This occurs for either the new Ionic CLI version 3, or for an older version (2.2.3) when I downgraded to it.

[UPDATE1]

Running on a second machine (Windows 10) with node v6.9.4 (the above was node 7.something), and npm 4.2.0, I get similar but differently formatted error...

```<code>    [16:31:04]  webpack started ...
    [16:31:35]  webpack finished in 31.23 s
    [16:31:35]  sass started ...
    [16:31:36]  transpile bundle started ...
    [16:31:44]  build prod failed: Maximum call stack size exceeded
    [16:31:44]  ionic-app-script task: "build"
    [16:31:44]  RangeError: Maximum call stack size exceeded
    RangeError: Maximum call stack size exceeded
        at checkNonNullExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:38258:40)
        at resolveNewExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39433:34)
        at resolveSignature (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39639:28)
        at getResolvedSignature (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39669:26)
        at checkCallExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39696:29)
        at checkExpressionWorker (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:41163:28)
        at checkExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:41115:42)
        at checkExpressionCached (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:40996:38)
        at H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:40058:32
        at traverse (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:7255:28)
</code>```

[UPDATE2]

As another test, I added a new empty page, and added nothing but the C3 import, and then a call to a single function (generate) from the library.

This new page gets the same error.

Does anyone have any idea of how to track this down / fix this problem? I am out of ideas, and I just can't restart the project from blank again.

Thanks in advance for any help

[UPDATE3]

I thought I'd try to update TypeScript to the latest 2.3.2. When I rerun npm install, I do get some warnings..

```<code>    +-- UNMET PEER DEPENDENCY @angular/core@4.1.0
    +-- UNMET PEER DEPENDENCY @angular/http@4.1.0
    `-- typescript@2.3.2

    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (curre
    nt: {"os":"win32","arch":"x64"})
    npm WARN ng2-translate@5.0.0 requires a peer of @angular/core@^2.0.0 but none was installed.
    npm WARN ng2-translate@5.0.0 requires a peer of @angular/http@^2.0.0 but none was installed.
</code>```

I don't quite understand the two UNMET PEER DEPENDENCY as I do have exactly @angular/core@4.1.0 and @angular/http@4.1.0 installed.

At any rate, I still get the same overflow. Really not sure what to try next. Once again, these libraries both build fine in a newly created Ionic application, maybe because it is a lot smaller?

Also I did find this issue, but it looks a little different to mine here...

答: For me the solution has been to have the latest Ionic, including the latest CLI, except holding TypeScript at 2.3.0 as suggested by imgx64 here

Body:
I have just gone upgraded my Ionic 2 app to Ionic 3, all of framework, Ionic native, and the CLI.

I now have the following setup..

    "dependencies": {
        "@angular/animations": "4.1.0",
        "@angular/common": "4.1.0",
        "@angular/compiler": "4.1.0",
        "@angular/compiler-cli": "4.1.0",
        "@angular/core": "^4.1.0",
        "@angular/forms": "4.1.0",
        "@angular/http": "^4.1.0",
        "@angular/platform-browser": "4.1.0",
        "@angular/platform-browser-dynamic": "4.1.0",
        "@ionic-native/app-version": "^3.8.0",
        "@ionic-native/core": "3.6.1",
        "@ionic-native/device": "^3.8.0",
        "@ionic-native/file": "^3.7.0",
        "@ionic-native/network": "^3.8.0",
        "@ionic-native/social-sharing": "^3.7.0",
        "@ionic-native/splash-screen": "3.6.1",
        "@ionic-native/status-bar": "3.6.1",
        "@ionic-native/toast": "^3.8.0",
        "@ionic/storage": "2.0.1",
        "c3": "^0.4.11",
        "ionic-angular": "3.2.1",
        "ionicons": "3.0.0",
        "js-logger": "^1.3.0",
        "jslogger": "^1.0.3",
        "jszip": "^3.1.3",
        "lodash": "^4.17.4",
        "moment": "^2.17.1",
        "moment-duration-format": "^1.3.0",
        "ng2-translate": "^5.0.0",
        "rxjs": "5.1.1",
        "semaphore-async-await": "^1.3.2",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.10"
      },
      "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "@ionic/cli-plugin-ionic-angular": "1.0.0",
        "@types/c3": "^0.4.38",
        "@types/jasmine": "^2.5.42",
        "@types/jszip": "0.0.32",
        "@types/lodash": "^4.14.51",
        "@types/moment-duration-format": "^1.3.1",
        "@types/node": "^7.0.5",
        "codecov": "^1.0.1",
        "install": "^0.8.7",
        "jasmine-core": "^2.5.2",
        "jasmine-spec-reporter": "^3.2.0",
        "karma": "^1.4.1",
        "karma-chrome-launcher": "^2.0.0",
        "karma-jasmine": "^1.1.0",
        "karma-mocha-reporter": "^2.2.2",
        "karma-remap-istanbul": "^0.6.0",
        "ts-node": "^2.1.0",
        "tslint": "^4.4.2",
        "tslint-eslint-rules": "^3.3.0",
        "typescript": "^2.2.1"
      },

Now, if I build with the -prod flag (it id fine without this), I get the following error...

    [16:50:08]  webpack started ...
    Error: ./~/jszip/lib/index.js
    Module build failed: RangeError: Maximum call stack size exceeded
        at Object.forEachChild (D:\dev\myapp\node_modules\typescript\lib\typescript.js:14735:26)
        at traverse (D:\dev\myapp\node_modules\typescript\lib\typescript.js:7271:31)
        at Object.forEachReturnStatement (D:\dev\myapp\node_modules\typescript\lib\typescript.js:7251:16)
        at checkAndAggregateReturnExpressionTypes (D:\dev\myapp\node_modules\typescript\lib\typescript.js:40055:16)
        at getReturnTypeFromBody (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39965:29)
        at getReturnTypeOfSignature (D:\dev\myapp\node_modules\typescript\lib\typescript.js:31190:28)
        at resolveNewExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39483:21)
        at resolveSignature (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39639:28)
        at getResolvedSignature (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39669:26)
        at checkCallExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:39696:29)
     @ ./src/providers/file-logger.ts 58:0-28
     @ ./src/app/app.module.ngfactory.ts
     @ ./src/app/main.ts,./~/d3/d3.js
    Module build failed: RangeError: Maximum call stack size exceeded
        at RegExp.[Symbol.replace] (native)
        at String.replace (native)
        at formatStringFromArgs (D:\dev\myapp\node_modules\typescript\lib\typescript.js:2365:21)
        at Object.chainDiagnosticMessages (D:\dev\myapp\node_modules\typescript\lib\typescript.js:2433:20)
        at reportNonexistentProperty (D:\dev\myapp\node_modules\typescript\lib\typescript.js:38290:28)
        at checkPropertyAccessExpressionOrQualifiedName (D:\dev\myapp\node_modules\typescript\lib\typescript.js:38332:
    21)
        at checkPropertyAccessExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:38274:20)
        at checkExpressionWorker (D:\dev\myapp\node_modules\typescript\lib\typescript.js:41158:28)
        at checkExpression (D:\dev\myapp\node_modules\typescript\lib\typescript.js:41115:42)
        at checkExpressionWithContextualType (D:\dev\myapp\node_modules\typescript\lib\typescript.js:40983:26)
     @ ./src/pages/mypage/mypage.ts 61:0-25
     @ ./src/app/app.module.ts
     @ ./src/app/app.module.ngfactory.ts
     @ ./src/app/main.ts

I have tracked this down to the 2 libs  C3/D3, and jszip. If I use either of these in a small newly created Ionic 3 app, then there is not a problem.

I have gone through many many other reports of webpack throwing this error, but just cannot see why this is now happening for me, in my existing project.

This occurs for either the new Ionic CLI version 3, or for an older version (2.2.3) when I downgraded to it.

[UPDATE1]

Running on a second machine (Windows 10) with node v6.9.4 (the above was node 7.something), and npm 4.2.0, I get similar but differently formatted error...

    [16:31:04]  webpack started ...
    [16:31:35]  webpack finished in 31.23 s
    [16:31:35]  sass started ...
    [16:31:36]  transpile bundle started ...
    [16:31:44]  build prod failed: Maximum call stack size exceeded
    [16:31:44]  ionic-app-script task: "build"
    [16:31:44]  RangeError: Maximum call stack size exceeded
    RangeError: Maximum call stack size exceeded
        at checkNonNullExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:38258:40)
        at resolveNewExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39433:34)
        at resolveSignature (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39639:28)
        at getResolvedSignature (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39669:26)
        at checkCallExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:39696:29)
        at checkExpressionWorker (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:41163:28)
        at checkExpression (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:41115:42)
        at checkExpressionCached (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:40996:38)
        at H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:40058:32
        at traverse (H:\dev\myapp\upgradeto3\node_modules\typescript\lib\typescript.js:7255:28)

[UPDATE2]

As another test, I added a new empty page, and added nothing but the C3 import, and then a call to a single function (generate) from the library.

This new page gets the same error.

Does anyone have any idea of how to track this down / fix this problem? I am out of ideas, and I just can't restart the project from blank again.

Thanks in advance for any help

[UPDATE3]

I thought I'd try to update TypeScript to the latest 2.3.2. When I rerun npm install, I do get some warnings..

    +-- UNMET PEER DEPENDENCY @angular/core@4.1.0
    +-- UNMET PEER DEPENDENCY @angular/http@4.1.0
    `-- typescript@2.3.2

    npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\chokidar\node_modules\fsevents):
    npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (curre
    nt: {"os":"win32","arch":"x64"})
    npm WARN ng2-translate@5.0.0 requires a peer of @angular/core@^2.0.0 but none was installed.
    npm WARN ng2-translate@5.0.0 requires a peer of @angular/http@^2.0.0 but none was installed.

I don't quite understand the two UNMET PEER DEPENDENCY as I do have exactly @angular/core@4.1.0 and @angular/http@4.1.0 installed.

At any rate, I still get the same overflow. Really not sure what to try next. Once again, these libraries both build fine in a newly created Ionic application, maybe because it is a lot smaller?

Also I did find this issue, but it looks a little different to mine here...


问:
What is the point of encrypting web.config if user can just decrypt it?
Oi, some vendor is telling my bosses that not encrypting the web.config is big security hole. This sounds like bunk to me. I mean, if someone compromises the server aren't we screwed anyways?</p>

答:
Like @Joelt suggested, ASP.NET had a security issue semi recently that allowed people to access files in the root web etc. Now, this issue could have existed for a long time. Alternatively, there could be a secret flaw right now that no one knows about except some leet punks ... which means we're all vulnerable right now. I mean, until the ASP.NET team (and security people a week or two before them) announced that previous flaw ... how long was that out in the wild? How many people exploited that?

So - that's the general idea. If for some reason a flaw exists - where people can remotely gain access to files - including web.config - then your data could be known.

Now - the kicker is this. So .. someone might find out about my DB name, DB ip addy and DB password .. right? but they need to access my internal DB ... so good luck there. BUT, my web.config might have my twitter username password in there? (Ding! light just turned on). My 3rd party api username/passwords. etc.

THAT is where the real security issue lies, IMO.

I'd hate it if u learn my companies twitter username/password and then start defacing our twitter account.

ContentLicense: CC BY-SA 2.5