问:
How to write patterns for use with re.VERBOSE when they contain meaningful whitespace?
Regexes containing meaningful spaces break when re.VERBOSE is added, apparently because re.VERBOSE 'helpfully' magics away the (meaningful) whitespace inside 'Issue Summary', as well as all the crappy non-meaningful whitespace (e.g. padding and newlines inside a (multiline) pattern). (My use of re.VERBOSE with multiline is non-negotiable - this is actually a massive simplification of a huge multiline regex where re.VERBOSE is necessary just to stay sane.)

```<code>import re
re.match(r'''Issue Summary.*''', 'Issue Summary: fails''', re.U|re.VERBOSE)
# No match!
re.match(r'''Issue Summary.*''', 'Issue Summary: passes''', re.U)
<_sre.SRE_Match object at 0x10ba36030>
re.match(r'Issue Summary.*', 'Issue Summary: passes''', re.U)
<_sre.SRE_Match object at 0x10b98ff38>
</code>```

Is there a saner alternative to write re.VERBOSE-friendly patterns containing meaningful spaces, short of replacing each instance in my pattern with '\s' or '.', which is not just ugly but counter-intuitive and a pain to automate?

```<code>re.match(r'Issue\sSummary.*''', 'Issue Summary: fails', re.VERBOSE)
<_sre.SRE_Match object at 0x10ba36030>
re.match(r'Issue.Summary.*''', 'Issue Summary: fails', re.VERBOSE)
<_sre.SRE_Match object at 0x10b98ff38>
</code>```

(As an aside, this a useful docbug catch on Python 2 and 3. I'll file it once I get consensus here on what the right solution is)

答:
If re.VERBOSE is used, then I think there's no choice other than to change the regular expression string.  However, I would suggest one of the following:

```<code>r'abc\ def'
</code>```

or:

```<code>r'abc[ ]def'
</code>```

Both r'\ ' and '[ ]' match a single space character (not any whitespace, only an actual space).  Note that, without the r in front, the backslash character would need to be doubled, i.e. \\.

Body:
Regexes containing meaningful spaces break when re.VERBOSE is added, apparently because re.VERBOSE 'helpfully' magics away the (meaningful) whitespace inside 'Issue Summary', as well as all the crappy non-meaningful whitespace (e.g. padding and newlines inside a (multiline) pattern). (My use of re.VERBOSE with multiline is non-negotiable - this is actually a massive simplification of a huge multiline regex where re.VERBOSE is necessary just to stay sane.)

import re
re.match(r'''Issue Summary.*''', 'Issue Summary: fails''', re.U|re.VERBOSE)
# No match!
re.match(r'''Issue Summary.*''', 'Issue Summary: passes''', re.U)
<_sre.SRE_Match object at 0x10ba36030>
re.match(r'Issue Summary.*', 'Issue Summary: passes''', re.U)
<_sre.SRE_Match object at 0x10b98ff38>

Is there a saner alternative to write re.VERBOSE-friendly patterns containing meaningful spaces, short of replacing each instance in my pattern with '\s' or '.', which is not just ugly but counter-intuitive and a pain to automate?

re.match(r'Issue\sSummary.*''', 'Issue Summary: fails', re.VERBOSE)
<_sre.SRE_Match object at 0x10ba36030>
re.match(r'Issue.Summary.*''', 'Issue Summary: fails', re.VERBOSE)
<_sre.SRE_Match object at 0x10b98ff38>

(As an aside, this a useful docbug catch on Python 2 and 3. I'll file it once I get consensus here on what the right solution is)

Body:
If re.VERBOSE is used, then I think there's no choice other than to change the regular expression string.  However, I would suggest one of the following:

r'abc\ def'

or:

r'abc[ ]def'

Both r'\ ' and '[ ]' match a single space character (not any whitespace, only an actual space).  Note that, without the r in front, the backslash character would need to be doubled, i.e. \\.


来源: stackexchange

问:
Python IDLE crash only on second monitor. Tcl/Tk compatibility issue?
OS X 10.10.1
Python 3.4.2
ActiveTcl 8.5.17

Hi All,

Have a strange issue with IDLE crashing when using open parenthesis '(', specifically when using it after 'input'. It only seems to occur when the IDLE window is on my second monitor (LG IPS226). I can safely type the same characters if the IDLE window is on my laptop screen.

I have read around the Tcl/Tk compatibility on OSX with Python, and have manually installed the 8.5.17 version that Python suggests (with a fresh Python install afterwards). Is there anything I'm missing?

Thanks.

Here is the error report, I have removed the Binary Images section as it was huge. Let me know if you need any parts of it.:

```<code>Process:               Python [829]
Path:                  /Applications/Python 3.4/IDLE.app/Contents/MacOS/Python
Identifier:            org.python.IDLE
Version:               3.4.2 (3.4.2)
Code Type:             X86 (Native)
Parent Process:        ??? [1]
Responsible:           Python [829]
User ID:               501

Date/Time:             2015-01-27 18:23:25.347 +0000
OS Version:            Mac OS X 10.10.1 (14B25)
Report Version:        11
Anonymous UUID:        74C05961-5E20-89F0-8A61-57115D184D5B

Time Awake Since Boot: 880 seconds

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000002, 0x0000000000000000

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1000) creating window shape'

Application Specific Backtrace 1:
0   CoreFoundation                      0x985ba343 __raiseError + 195
1   libobjc.A.dylib                     0x9a69da2a objc_exception_throw + 276
2   CoreFoundation                      0x985ba25d +[NSException raise:format:] + 141
3   AppKit                              0x915af052 _NXCreateWindowWithStyleMask + 519
4   AppKit                              0x915aed92 _NSCreateWindow + 165
5   AppKit                              0x9147809f -[NSWindow _commonAwake] + 1447
6   AppKit                              0x91477930 -[NSWindow _makeKeyRegardlessOfVisibility] + 104
7   AppKit                              0x91477886 -[NSWindow makeKeyAndOrderFront:] + 35
8   Tk                                  0x02b0aeb4 XMapWindow + 149
9   Tk                                  0x02b108e3 TkWmMapWindow + 289
10  Tk                                  0x02a69c7d Tk_MapWindow + 89
11  Tk                                  0x02a73d2a MapFrame + 72
12  Tcl                                 0x029da0cb TclServiceIdle + 61
13  Tcl                                 0x029bc20f Tcl_DoOneEvent + 342
14  Tk                                  0x02ac49fa DisplayText + 511
15  Tcl                                 0x029da0cb TclServiceIdle + 61
16  Tcl                                 0x029bc20f Tcl_DoOneEvent + 342
17  Tk                                  0x02a45a86 Tk_UpdateObjCmd + 198
18  Tcl                                 0x0294c851 TclEvalObjvInternal + 770
19  Tcl                                 0x0294d83c Tcl_EvalObjv + 72
20  _tkinter.so                         0x006e7ae0 Tkapp_Call + 208
21  Python                              0x000e7865 PyEval_EvalFrameEx + 31653
22  Python                              0x000e7bc1 PyEval_EvalFrameEx + 32513
23  Python                              0x000e7bc1 PyEval_EvalFrameEx + 32513
24  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
25  Python                              0x00041bde function_call + 158
26  Python                              0x0000e0f9 PyObject_Call + 89
27  Python                              0x000e0cdc PyEval_EvalFrameEx + 4124
28  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
29  Python                              0x00041bde function_call + 158
30  Python                              0x0000e0f9 PyObject_Call + 89
31  Python                              0x000e0cdc PyEval_EvalFrameEx + 4124
32  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
33  Python                              0x00041bde function_call + 158
34  Python                              0x0000e0f9 PyObject_Call + 89
35  Python                              0x0002accc method_call + 140
36  Python                              0x0000e0f9 PyObject_Call + 89
37  Python                              0x000de00e PyEval_CallObjectWithKeywords + 78
38  _tkinter.so                         0x006e5c06 PythonCmd + 358
39  Tcl                                 0x0294919c TclInvokeStringCommand + 96
40  Tcl                                 0x0294c851 TclEvalObjvInternal + 770
41  Tcl                                 0x02989bcf TclExecuteByteCode + 4775
42  Tcl                                 0x02992ecd TclCompEvalObj + 439
43  Tcl                                 0x0294dc40 TclEvalObjEx + 871
44  Tcl                                 0x0294dd41 Tcl_EvalObjEx + 47
45  Tcl                                 0x029da395 AfterProc + 83
46  Tcl                                 0x029da26f TimerHandlerEventProc + 87
47  Tcl                                 0x029bbf0b Tcl_ServiceEvent + 160
48  Tcl                                 0x029bc150 Tcl_DoOneEvent + 151
49  _tkinter.so                         0x006e52c9 Tkapp_MainLoop + 201
50  Python                              0x000e7865 PyEval_EvalFrameEx + 31653
51  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
52  Python                              0x000e79c1 PyEval_EvalFrameEx + 32001
53  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
54  Python                              0x000e79c1 PyEval_EvalFrameEx + 32001
55  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
56  Python                              0x000e902f PyEval_EvalCode + 95
57  Python                              0x0011465e PyRun_FileExFlags + 206
58  Python                              0x00114ab7 PyRun_SimpleFileExFlags + 807
59  Python                              0x0012d021 Py_Main + 3425
60  Python                              0x00001e97 main + 471
61  Python                              0x00001cb5 start + 53

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.apple.CoreFoundation        0x985bacd7 ___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___ + 7
1   com.apple.CoreFoundation        0x985ba659 __raiseError + 985
2   libobjc.A.dylib                 0x9a69da2a objc_exception_throw + 276
3   com.apple.CoreFoundation        0x985ba25d +[NSException raise:format:] + 141
4   com.apple.AppKit                0x915af052 _NXCreateWindowWithStyleMask + 519
5   com.apple.AppKit                0x915aed92 _NSCreateWindow + 165
6   com.apple.AppKit                0x9147809f -[NSWindow _commonAwake] + 1447
7   com.apple.AppKit                0x91477930 -[NSWindow _makeKeyRegardlessOfVisibility] + 104
8   com.apple.AppKit                0x91477886 -[NSWindow makeKeyAndOrderFront:] + 35
9   Tk                              0x02b0aeb4 XMapWindow + 149
10  Tk                              0x02b108e3 TkWmMapWindow + 289
11  Tk                              0x02a69c7d Tk_MapWindow + 89
12  Tk                              0x02a73d2a MapFrame + 72
13  Tcl                             0x029da0cb TclServiceIdle + 61
14  Tcl                             0x029bc20f Tcl_DoOneEvent + 342
15  Tk                              0x02ac49fa DisplayText + 511
16  Tcl                             0x029da0cb TclServiceIdle + 61
17  Tcl                             0x029bc20f Tcl_DoOneEvent + 342
18  Tk                              0x02a45a86 Tk_UpdateObjCmd + 198
19  Tcl                             0x0294c851 TclEvalObjvInternal + 770
20  Tcl                             0x0294d83c Tcl_EvalObjv + 72
21  _tkinter.so                     0x006e7ae0 Tkapp_Call + 208
22  org.python.python               0x000e7865 PyEval_EvalFrameEx + 31653
23  org.python.python               0x000e7bc1 PyEval_EvalFrameEx + 32513
24  org.python.python               0x000e7bc1 PyEval_EvalFrameEx + 32513
25  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
26  org.python.python               0x00041bde function_call + 158
27  org.python.python               0x0000e0f9 PyObject_Call + 89
28  org.python.python               0x000e0cdc PyEval_EvalFrameEx + 4124
29  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
30  org.python.python               0x00041bde function_call + 158
31  org.python.python               0x0000e0f9 PyObject_Call + 89
32  org.python.python               0x000e0cdc PyEval_EvalFrameEx + 4124
33  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
34  org.python.python               0x00041bde function_call + 158
35  org.python.python               0x0000e0f9 PyObject_Call + 89
36  org.python.python               0x0002accc method_call + 140
37  org.python.python               0x0000e0f9 PyObject_Call + 89
38  org.python.python               0x000de00e PyEval_CallObjectWithKeywords + 78
39  _tkinter.so                     0x006e5c06 PythonCmd + 358
40  Tcl                             0x0294919c TclInvokeStringCommand + 96
41  Tcl                             0x0294c851 TclEvalObjvInternal + 770
42  Tcl                             0x02989bcf TclExecuteByteCode + 4775
43  Tcl                             0x02992ecd TclCompEvalObj + 439
44  Tcl                             0x0294dc40 TclEvalObjEx + 871
45  Tcl                             0x0294dd41 Tcl_EvalObjEx + 47
46  Tcl                             0x029da395 AfterProc + 83
47  Tcl                             0x029da26f TimerHandlerEventProc + 87
48  Tcl                             0x029bbf0b Tcl_ServiceEvent + 160
49  Tcl                             0x029bc150 Tcl_DoOneEvent + 151
50  _tkinter.so                     0x006e52c9 Tkapp_MainLoop + 201
51  org.python.python               0x000e7865 PyEval_EvalFrameEx + 31653
52  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
53  org.python.python               0x000e79c1 PyEval_EvalFrameEx + 32001
54  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
55  org.python.python               0x000e79c1 PyEval_EvalFrameEx + 32001
56  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
57  org.python.python               0x000e902f PyEval_EvalCode + 95
58  org.python.python               0x0011465e PyRun_FileExFlags + 206
59  org.python.python               0x00114ab7 PyRun_SimpleFileExFlags + 807
60  org.python.python               0x0012d021 Py_Main + 3425
61  Python                          0x00001e97 main + 471
62  Python                          0x00001cb5 start + 53

Thread 1:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x90f628d2 kevent64 + 10
1   libdispatch.dylib               0x9508473f _dispatch_mgr_invoke + 245
2   libdispatch.dylib               0x950843a2 _dispatch_mgr_thread + 52

Thread 2:
0   libsystem_kernel.dylib          0x90f61e6e __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x9284236d _pthread_wqthread + 939
2   libsystem_pthread.dylib         0x9283feea start_wqthread + 30

Thread 3:
0   libsystem_kernel.dylib          0x90f61e6e __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x9284236d _pthread_wqthread + 939
2   libsystem_pthread.dylib         0x9283feea start_wqthread + 30

Thread 4:
0   libsystem_kernel.dylib          0x90f61852 __select + 10
1   Tcl                             0x029f4a0b NotifierThreadProc + 628
2   libsystem_pthread.dylib         0x92841ecf _pthread_body + 138
3   libsystem_pthread.dylib         0x92841e45 _pthread_start + 162
4   libsystem_pthread.dylib         0x9283ff0e thread_start + 34

Thread 5:
0   libsystem_kernel.dylib          0x90f5ba2e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x90f5aad0 mach_msg + 68
2   com.apple.CoreFoundation        0x984b8ae6 __CFRunLoopServiceMachPort + 214
3   com.apple.CoreFoundation        0x984b7ef9 __CFRunLoopRun + 1529
4   com.apple.CoreFoundation        0x984b7696 CFRunLoopRunSpecific + 390
5   com.apple.CoreFoundation        0x984b74fb CFRunLoopRunInMode + 123
6   com.apple.AppKit                0x914ce6b4 _NSEventThread + 283
7   libsystem_pthread.dylib         0x92841ecf _pthread_body + 138
8   libsystem_pthread.dylib         0x92841e45 _pthread_start + 162
9   libsystem_pthread.dylib         0x9283ff0e thread_start + 34

Thread 0 crashed with X86 Thread State (32-bit):
  eax: 0x00000001  ebx: 0x004e0600  ecx: 0x00000000  edx: 0x00000000
  edi: 0x985ba28e  esi: 0x00c5a600  ebp: 0xbfffc158  esp: 0xbfffc150
   ss: 0x00000023  efl: 0x00000286  eip: 0x985bacd7   cs: 0x0000001b
   ds: 0x00000023   es: 0x00000023   fs: 0x00000000   gs: 0x0000000f
  cr2: 0x0bacc000

Logical CPU:     2
Error Code:      0x00000000
Trap Number:     3
</code>```

答:
I found a simple fix.

In IDLE:

Options Menu > Configure Extensions > CallTips > set to FALSE

Then restart IDLE.

Took much research to find that super simple solution... the problem is caused not by an error in IDLE but by an error in the mac's Tcl/Tk code specifically when calltips are called in external monitors above the default monitor.

ContentLicense: CC BY-SA 3.0

Body:
OS X 10.10.1
Python 3.4.2
ActiveTcl 8.5.17

Hi All,

Have a strange issue with IDLE crashing when using open parenthesis '(', specifically when using it after 'input'. It only seems to occur when the IDLE window is on my second monitor (LG IPS226). I can safely type the same characters if the IDLE window is on my laptop screen.

I have read around the Tcl/Tk compatibility on OSX with Python, and have manually installed the 8.5.17 version that Python suggests (with a fresh Python install afterwards). Is there anything I'm missing?

Thanks.

Here is the error report, I have removed the Binary Images section as it was huge. Let me know if you need any parts of it.:

Process:               Python [829]
Path:                  /Applications/Python 3.4/IDLE.app/Contents/MacOS/Python
Identifier:            org.python.IDLE
Version:               3.4.2 (3.4.2)
Code Type:             X86 (Native)
Parent Process:        ??? [1]
Responsible:           Python [829]
User ID:               501

Date/Time:             2015-01-27 18:23:25.347 +0000
OS Version:            Mac OS X 10.10.1 (14B25)
Report Version:        11
Anonymous UUID:        74C05961-5E20-89F0-8A61-57115D184D5B

Time Awake Since Boot: 880 seconds

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BREAKPOINT (SIGTRAP)
Exception Codes:       0x0000000000000002, 0x0000000000000000

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1000) creating window shape'

Application Specific Backtrace 1:
0   CoreFoundation                      0x985ba343 __raiseError + 195
1   libobjc.A.dylib                     0x9a69da2a objc_exception_throw + 276
2   CoreFoundation                      0x985ba25d +[NSException raise:format:] + 141
3   AppKit                              0x915af052 _NXCreateWindowWithStyleMask + 519
4   AppKit                              0x915aed92 _NSCreateWindow + 165
5   AppKit                              0x9147809f -[NSWindow _commonAwake] + 1447
6   AppKit                              0x91477930 -[NSWindow _makeKeyRegardlessOfVisibility] + 104
7   AppKit                              0x91477886 -[NSWindow makeKeyAndOrderFront:] + 35
8   Tk                                  0x02b0aeb4 XMapWindow + 149
9   Tk                                  0x02b108e3 TkWmMapWindow + 289
10  Tk                                  0x02a69c7d Tk_MapWindow + 89
11  Tk                                  0x02a73d2a MapFrame + 72
12  Tcl                                 0x029da0cb TclServiceIdle + 61
13  Tcl                                 0x029bc20f Tcl_DoOneEvent + 342
14  Tk                                  0x02ac49fa DisplayText + 511
15  Tcl                                 0x029da0cb TclServiceIdle + 61
16  Tcl                                 0x029bc20f Tcl_DoOneEvent + 342
17  Tk                                  0x02a45a86 Tk_UpdateObjCmd + 198
18  Tcl                                 0x0294c851 TclEvalObjvInternal + 770
19  Tcl                                 0x0294d83c Tcl_EvalObjv + 72
20  _tkinter.so                         0x006e7ae0 Tkapp_Call + 208
21  Python                              0x000e7865 PyEval_EvalFrameEx + 31653
22  Python                              0x000e7bc1 PyEval_EvalFrameEx + 32513
23  Python                              0x000e7bc1 PyEval_EvalFrameEx + 32513
24  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
25  Python                              0x00041bde function_call + 158
26  Python                              0x0000e0f9 PyObject_Call + 89
27  Python                              0x000e0cdc PyEval_EvalFrameEx + 4124
28  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
29  Python                              0x00041bde function_call + 158
30  Python                              0x0000e0f9 PyObject_Call + 89
31  Python                              0x000e0cdc PyEval_EvalFrameEx + 4124
32  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
33  Python                              0x00041bde function_call + 158
34  Python                              0x0000e0f9 PyObject_Call + 89
35  Python                              0x0002accc method_call + 140
36  Python                              0x0000e0f9 PyObject_Call + 89
37  Python                              0x000de00e PyEval_CallObjectWithKeywords + 78
38  _tkinter.so                         0x006e5c06 PythonCmd + 358
39  Tcl                                 0x0294919c TclInvokeStringCommand + 96
40  Tcl                                 0x0294c851 TclEvalObjvInternal + 770
41  Tcl                                 0x02989bcf TclExecuteByteCode + 4775
42  Tcl                                 0x02992ecd TclCompEvalObj + 439
43  Tcl                                 0x0294dc40 TclEvalObjEx + 871
44  Tcl                                 0x0294dd41 Tcl_EvalObjEx + 47
45  Tcl                                 0x029da395 AfterProc + 83
46  Tcl                                 0x029da26f TimerHandlerEventProc + 87
47  Tcl                                 0x029bbf0b Tcl_ServiceEvent + 160
48  Tcl                                 0x029bc150 Tcl_DoOneEvent + 151
49  _tkinter.so                         0x006e52c9 Tkapp_MainLoop + 201
50  Python                              0x000e7865 PyEval_EvalFrameEx + 31653
51  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
52  Python                              0x000e79c1 PyEval_EvalFrameEx + 32001
53  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
54  Python                              0x000e79c1 PyEval_EvalFrameEx + 32001
55  Python                              0x000e8f4a PyEval_EvalCodeEx + 2314
56  Python                              0x000e902f PyEval_EvalCode + 95
57  Python                              0x0011465e PyRun_FileExFlags + 206
58  Python                              0x00114ab7 PyRun_SimpleFileExFlags + 807
59  Python                              0x0012d021 Py_Main + 3425
60  Python                              0x00001e97 main + 471
61  Python                              0x00001cb5 start + 53

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.apple.CoreFoundation        0x985bacd7 ___TERMINATING_DUE_TO_UNCAUGHT_EXCEPTION___ + 7
1   com.apple.CoreFoundation        0x985ba659 __raiseError + 985
2   libobjc.A.dylib                 0x9a69da2a objc_exception_throw + 276
3   com.apple.CoreFoundation        0x985ba25d +[NSException raise:format:] + 141
4   com.apple.AppKit                0x915af052 _NXCreateWindowWithStyleMask + 519
5   com.apple.AppKit                0x915aed92 _NSCreateWindow + 165
6   com.apple.AppKit                0x9147809f -[NSWindow _commonAwake] + 1447
7   com.apple.AppKit                0x91477930 -[NSWindow _makeKeyRegardlessOfVisibility] + 104
8   com.apple.AppKit                0x91477886 -[NSWindow makeKeyAndOrderFront:] + 35
9   Tk                              0x02b0aeb4 XMapWindow + 149
10  Tk                              0x02b108e3 TkWmMapWindow + 289
11  Tk                              0x02a69c7d Tk_MapWindow + 89
12  Tk                              0x02a73d2a MapFrame + 72
13  Tcl                             0x029da0cb TclServiceIdle + 61
14  Tcl                             0x029bc20f Tcl_DoOneEvent + 342
15  Tk                              0x02ac49fa DisplayText + 511
16  Tcl                             0x029da0cb TclServiceIdle + 61
17  Tcl                             0x029bc20f Tcl_DoOneEvent + 342
18  Tk                              0x02a45a86 Tk_UpdateObjCmd + 198
19  Tcl                             0x0294c851 TclEvalObjvInternal + 770
20  Tcl                             0x0294d83c Tcl_EvalObjv + 72
21  _tkinter.so                     0x006e7ae0 Tkapp_Call + 208
22  org.python.python               0x000e7865 PyEval_EvalFrameEx + 31653
23  org.python.python               0x000e7bc1 PyEval_EvalFrameEx + 32513
24  org.python.python               0x000e7bc1 PyEval_EvalFrameEx + 32513
25  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
26  org.python.python               0x00041bde function_call + 158
27  org.python.python               0x0000e0f9 PyObject_Call + 89
28  org.python.python               0x000e0cdc PyEval_EvalFrameEx + 4124
29  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
30  org.python.python               0x00041bde function_call + 158
31  org.python.python               0x0000e0f9 PyObject_Call + 89
32  org.python.python               0x000e0cdc PyEval_EvalFrameEx + 4124
33  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
34  org.python.python               0x00041bde function_call + 158
35  org.python.python               0x0000e0f9 PyObject_Call + 89
36  org.python.python               0x0002accc method_call + 140
37  org.python.python               0x0000e0f9 PyObject_Call + 89
38  org.python.python               0x000de00e PyEval_CallObjectWithKeywords + 78
39  _tkinter.so                     0x006e5c06 PythonCmd + 358
40  Tcl                             0x0294919c TclInvokeStringCommand + 96
41  Tcl                             0x0294c851 TclEvalObjvInternal + 770
42  Tcl                             0x02989bcf TclExecuteByteCode + 4775
43  Tcl                             0x02992ecd TclCompEvalObj + 439
44  Tcl                             0x0294dc40 TclEvalObjEx + 871
45  Tcl                             0x0294dd41 Tcl_EvalObjEx + 47
46  Tcl                             0x029da395 AfterProc + 83
47  Tcl                             0x029da26f TimerHandlerEventProc + 87
48  Tcl                             0x029bbf0b Tcl_ServiceEvent + 160
49  Tcl                             0x029bc150 Tcl_DoOneEvent + 151
50  _tkinter.so                     0x006e52c9 Tkapp_MainLoop + 201
51  org.python.python               0x000e7865 PyEval_EvalFrameEx + 31653
52  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
53  org.python.python               0x000e79c1 PyEval_EvalFrameEx + 32001
54  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
55  org.python.python               0x000e79c1 PyEval_EvalFrameEx + 32001
56  org.python.python               0x000e8f4a PyEval_EvalCodeEx + 2314
57  org.python.python               0x000e902f PyEval_EvalCode + 95
58  org.python.python               0x0011465e PyRun_FileExFlags + 206
59  org.python.python               0x00114ab7 PyRun_SimpleFileExFlags + 807
60  org.python.python               0x0012d021 Py_Main + 3425
61  Python                          0x00001e97 main + 471
62  Python                          0x00001cb5 start + 53

Thread 1:: Dispatch queue: com.apple.libdispatch-manager
0   libsystem_kernel.dylib          0x90f628d2 kevent64 + 10
1   libdispatch.dylib               0x9508473f _dispatch_mgr_invoke + 245
2   libdispatch.dylib               0x950843a2 _dispatch_mgr_thread + 52

Thread 2:
0   libsystem_kernel.dylib          0x90f61e6e __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x9284236d _pthread_wqthread + 939
2   libsystem_pthread.dylib         0x9283feea start_wqthread + 30

Thread 3:
0   libsystem_kernel.dylib          0x90f61e6e __workq_kernreturn + 10
1   libsystem_pthread.dylib         0x9284236d _pthread_wqthread + 939
2   libsystem_pthread.dylib         0x9283feea start_wqthread + 30

Thread 4:
0   libsystem_kernel.dylib          0x90f61852 __select + 10
1   Tcl                             0x029f4a0b NotifierThreadProc + 628
2   libsystem_pthread.dylib         0x92841ecf _pthread_body + 138
3   libsystem_pthread.dylib         0x92841e45 _pthread_start + 162
4   libsystem_pthread.dylib         0x9283ff0e thread_start + 34

Thread 5:
0   libsystem_kernel.dylib          0x90f5ba2e mach_msg_trap + 10
1   libsystem_kernel.dylib          0x90f5aad0 mach_msg + 68
2   com.apple.CoreFoundation        0x984b8ae6 __CFRunLoopServiceMachPort + 214
3   com.apple.CoreFoundation        0x984b7ef9 __CFRunLoopRun + 1529
4   com.apple.CoreFoundation        0x984b7696 CFRunLoopRunSpecific + 390
5   com.apple.CoreFoundation        0x984b74fb CFRunLoopRunInMode + 123
6   com.apple.AppKit                0x914ce6b4 _NSEventThread + 283
7   libsystem_pthread.dylib         0x92841ecf _pthread_body + 138
8   libsystem_pthread.dylib         0x92841e45 _pthread_start + 162
9   libsystem_pthread.dylib         0x9283ff0e thread_start + 34

Thread 0 crashed with X86 Thread State (32-bit):
  eax: 0x00000001  ebx: 0x004e0600  ecx: 0x00000000  edx: 0x00000000
  edi: 0x985ba28e  esi: 0x00c5a600  ebp: 0xbfffc158  esp: 0xbfffc150
   ss: 0x00000023  efl: 0x00000286  eip: 0x985bacd7   cs: 0x0000001b
   ds: 0x00000023   es: 0x00000023   fs: 0x00000000   gs: 0x0000000f
  cr2: 0x0bacc000

Logical CPU:     2
Error Code:      0x00000000
Trap Number:     3


问:
Extracting JSON generic string from text file
I have a file the contents of which are formatted as follows:

```<code>{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}

This is a test }
</code>```

I'd like to extract just the JSON heading via regex (which I think is the most sensible approach here). However, in the future the JSON might change, (e.g. it might have extra fields added, or the current fields could change), so I'd like to keep the regex flexible. I have tried with the solution suggested here, however, that seems a bit too simplistic for my use case: in fact, the above "tricks" the regex, as shown in this regex101.com example.

Since my knowledge of regex is not that advanced, I'd like to know whether there's a regex approach that is able to cover my use case.

Thank you!

答:
You can check for the first index of \n} to get the sub-string:

s = `{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}
This is a test }
}`

i = s.indexOf('\n}')

if (i > 0) {
  o = JSON.parse(s = s.slice(0, i + 2))
  console.log(s); console.log(o)
}```
</div>
</div>
</p>

<p>or a bit shorter with RegEx:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>s = `{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}
This is a test }
}`

s.replace(/.*?\n}/s, function(m) {
  o = JSON.parse(m)
  console.log(m); console.log(o)
})</code>```

Body:
I have a file the contents of which are formatted as follows:

{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}

This is a test }

I'd like to extract just the JSON heading via regex (which I think is the most sensible approach here). However, in the future the JSON might change, (e.g. it might have extra fields added, or the current fields could change), so I'd like to keep the regex flexible. I have tried with the solution suggested here, however, that seems a bit too simplistic for my use case: in fact, the above "tricks" the regex, as shown in this regex101.com example.

Since my knowledge of regex is not that advanced, I'd like to know whether there's a regex approach that is able to cover my use case.

Thank you!

Body:
You can check for the first index of \n} to get the sub-string:

s = `{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}
This is a test }
}`

i = s.indexOf('\n}')

if (i > 0) {
  o = JSON.parse(s = s.slice(0, i + 2))
  console.log(s); console.log(o)
}

or a bit shorter with RegEx:

s = `{
  "title": "This is a test }",
  "date": "2017-11-16T20:47:16+00:00"
}
This is a test }
}`

s.replace(/.*?\n}/s, function(m) {
  o = JSON.parse(m)
  console.log(m); console.log(o)
})


问:
help for custom spinner?
i am getting error while using the custom class for spinner from below link.

How to make an Android Spinner with initial text "Select One"

can anyone suggest me how can i use it

thankx

答: If you are trying to have first item not being selected automatically, then I have answered that query in detail here with code snippets.</p>

ContentLicense: CC BY-SA 2.5

Title: help for custom spinner?


问:
Drive entity no longer returns a driveType attribute
I'm observing a change in functionality in Microsoft Graph. When requesting a list of drives from a SharePoint site, I used to see a driveItem attribute that no longer seems to be present as of Nov 14.

The site documentation mentions the relationship to the drives collection.

The drive documentation describes the driveType attribute as:

Describes the type of drive represented by this resource. OneDrive personal drives will return personal. OneDrive for Business will return business. SharePoint document libraries will return documentLibrary. Read-only.

Here is an example call:

```<code>https://graph.microsoft.com/v1.0/sites/{site-id}/drives
</code>```

Response:

client-request-id →d822c749-baf6-4857-abd9-6d80f70823d9
request-id →d822c749-baf6-4857-abd9-6d80f70823d9
x-ms-ags-diagnostic →{"ServerInfo":{"DataCenter":"EastUS","Slice":"SliceB","Ring":"NA","ScaleUnit":"003","Host":"AGSFE_IN_28","ADSiteName":"EST"}}

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#drives",
    "value": [
        {
            "createdBy": {
                "user": {
                    "displayName": "System Account"
                }
            },
            "createdDateTime": "2015-05-22T17:21:01Z",
            "description": "This system library was created by the PointPublishing feature to store application pages.",
            "id": "b!a4YqXM4QKkOPmOj73xfdss5bbYPr7MlFlXKVhtK0Dpjf4OJPyoBFQo2-YK5095t1",
            "lastModifiedDateTime": "2015-05-22T17:21:03Z",
            "name": "AppPages",
            "webUrl": "https://mysharepoint.sharepoint.com/portals/hub/AppPages",
            "quota": {
                "deleted": 0,
                "remaining": 0,
                "total": 0,
                "used": 0
            }
        }
      <snipped a few values>
    ]
}
```

<p>Is the change in functionality I am seeing here by design or non-intended?</p>

<p>Edit:   When attempting the call:</p>

```https://graph.microsoft.com/v1.0/sites/root/drives?$select=id,driveType,Name
```

<p>The <code>driveType</code> is returned</p>

<pre class="lang-json prettyprint-override"><code>{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#drives(id,driveType,name)",
    "value": [
        {
            "id": "fakeId",
            "name": "Documents",
            "driveType": "documentLibrary"
        }
    ]
}
</code>```

When requesting drives for a site based on the site-id (/sites/{site-id}/drives) we see different attributes returned.

答: Just closing the loop on this. As Brad mentioned, an issue has been identified. A fix is currently in the pipeline and should be rolling out soon.</p>

Body:
I'm observing a change in functionality in Microsoft Graph. When requesting a list of drives from a SharePoint site, I used to see a driveItem attribute that no longer seems to be present as of Nov 14.

The site documentation mentions the relationship to the drives collection.

The drive documentation describes the driveType attribute as:

Describes the type of drive represented by this resource. OneDrive personal drives will return personal. OneDrive for Business will return business. SharePoint document libraries will return documentLibrary. Read-only.

Here is an example call:

https://graph.microsoft.com/v1.0/sites/{site-id}/drives

Response:

client-request-id →d822c749-baf6-4857-abd9-6d80f70823d9
request-id →d822c749-baf6-4857-abd9-6d80f70823d9
x-ms-ags-diagnostic →{"ServerInfo":{"DataCenter":"EastUS","Slice":"SliceB","Ring":"NA","ScaleUnit":"003","Host":"AGSFE_IN_28","ADSiteName":"EST"}}

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#drives",
    "value": [
        {
            "createdBy": {
                "user": {
                    "displayName": "System Account"
                }
            },
            "createdDateTime": "2015-05-22T17:21:01Z",
            "description": "This system library was created by the PointPublishing feature to store application pages.",
            "id": "b!a4YqXM4QKkOPmOj73xfdss5bbYPr7MlFlXKVhtK0Dpjf4OJPyoBFQo2-YK5095t1",
            "lastModifiedDateTime": "2015-05-22T17:21:03Z",
            "name": "AppPages",
            "webUrl": "https://mysharepoint.sharepoint.com/portals/hub/AppPages",
            "quota": {
                "deleted": 0,
                "remaining": 0,
                "total": 0,
                "used": 0
            }
        }
      <snipped a few values>
    ]
}

Is the change in functionality I am seeing here by design or non-intended?

Edit:   When attempting the call:

https://graph.microsoft.com/v1.0/sites/root/drives?$select=id,driveType,Name

The driveType is returned

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#drives(id,driveType,name)",
    "value": [
        {
            "id": "fakeId",
            "name": "Documents",
            "driveType": "documentLibrary"
        }
    ]
}

When requesting drives for a site based on the site-id (/sites/{site-id}/drives) we see different attributes returned.


问:
How to Insert TIMESTAMP Column into Redshift
I created a table in Redshift:

```<code>create table myTable (
       dateTime TIMESTAMP NOT NULL,
       ...
);
</code>```

However, when I try to insert a record that contains a dateTime of, I get an error from stl_load_errors.

20080215 04:05:06.789

Since I took this timestamp from the docs, I would've expected it to have worked.

The error logs from Redshift show:

Invalid timestamp format or value [YYYY-MM-DD HH24:MI:SS]

However, I'd like to include 3 extra seconds, example: 2015-02-01 15:49:35.123.

How do I need to modify my timestamp field to insert it with the extra precision on seconds?

答: timeformat 'auto' and dateformat 'auto' worked well on my format, 2017-11-02T21:04:03.108Z. Documentation at http://docs.aws.amazon.com/redshift/latest/dg/automatic-recognition.html

Body:
I created a table in Redshift:

create table myTable (
       dateTime TIMESTAMP NOT NULL,
       ...
);

However, when I try to insert a record that contains a dateTime of, I get an error from stl_load_errors.

20080215 04:05:06.789

Since I took this timestamp from the docs, I would've expected it to have worked.

The error logs from Redshift show:

Invalid timestamp format or value [YYYY-MM-DD HH24:MI:SS]

However, I'd like to include 3 extra seconds, example: 2015-02-01 15:49:35.123.

How do I need to modify my timestamp field to insert it with the extra precision on seconds?

ContentLicense: CC BY-SA 4.0


问:
How to check if data in linked list exists C++
I'm working on creating a function that will remove an item from a linked list, however, I'm unsure how to check if the item passed to the function exists in the linked list. Because of this, my program crashes in the event that it gets an input it doesn't recognize.

Here is my function:

```<code>bool StringList::remove(string rmData){
    StringNode *current = new StringNode;
    StringNode *previous = new StringNode;
    current = head;
    while(current->data != rmData){
        previous = current;
        current = current->next;
    }

    previous->next = current->next;
}
</code>```

How can I check if the data exists in the list?

答: You always need to check if current->next points to a null, if so break;

Body:
I'm working on creating a function that will remove an item from a linked list, however, I'm unsure how to check if the item passed to the function exists in the linked list. Because of this, my program crashes in the event that it gets an input it doesn't recognize.

Here is my function:

bool StringList::remove(string rmData){
    StringNode *current = new StringNode;
    StringNode *previous = new StringNode;
    current = head;
    while(current->data != rmData){
        previous = current;
        current = current->next;
    }

    previous->next = current->next;
}

How can I check if the data exists in the list?


问:
WooCommerce Checkout Template without table breaks JS functionality
I changed the frontend templates (override by copying the file(s) into my custom theme folder) of the cart and checkout page by replacing some table-row-columns-constructs with div containers in order to create a (in my opinion) clearer layout, also for handling responsive layout changes.

It seems, the Wordpress hook/action woocommerce_checkout_order_review triggered from the template checkout/form-checkout.php template uses the code from cart/cart-shipping.php which is fine, because ist keeps the list containing the choosable shipping methods consistant on both pages.

A 'critical' change was: removing the td and th tags, and replacing
 with
 in cart/cart-shipping.php.

This leads to the problem:

Clicking a list item of the shipping_methods ul triggers the events update_checkout and updated_checkout, which (i think) are responsible for updating the cart/chekout page.
With my changed HTML templates things are not working as they should; with every click the whole ul gets replicated.
I could not find any occurences of tr.shipping or .shipping in the woocommerce js code.

Why is changing the template structure breaking the jQuery code? And how can I achieve that change without breaking?

答:
without more code it's very hard to say. Perhaps if you could provide a link I can assist more?

Going blind, it sounds like this is an issue tied to clicking...

I can confirm that in assets/js/admin/meta-boxes-order.js there are several references to tr.shipping from line 250-251 and lines 541, 786 and 874. It will likely be these lines that are causing the issue.

It's kind of hackish what you are trying to do...and without being able to test it's hard to say or confirm, but try duplicating those concerned functions but only call it on your div.shipping

See where that nets you out.


问:
How to return the first exception that occurred?
There's a method called validate which as input accepts an instance of Option and a Predicate - two arguments (yeah, I know Option should be passed as an argument but this is simplified real-world scenario here. Now, if Option is empty I need to throw NotFoundException. When it has a value that doesn't match the Predicate passed it should fail with ForbiddenException. If it has value and it matches the predicate nothing happens.

So this will be:

```<code>                Option, Predicate
                     /\
          isEmpty() /  \ isDefined()
                   /    \
            throw NFE    matches(Predicate)
                        / \
                    no /   \ yes
                      /     \
                throw FE     end
</code>```

I have some solutions but would like potential answerers to come to this question with clear mind ;) My problem is getting the first exception if both tests fail. I expect an elegant solution if I may expect anything ;) All vavr beings allowed (Either, Validation, Try..)

One of the ideas is to use double Option:

```<code>Option
  .of(o.getOrElseThrow(NotFoundException::new))
  .filter(p)
  .getOrElseThrow(ForbiddenException::new);
</code>```

But this seems a bit awkward.

Here sample project may be found.

答:
As I see it, the best option would be to create readable code, which in this case means using two if statements:

```<code>if (!o.isPresent()) throw new NotFoundException();
if (!p.test(o.get())) throw new ForbiddenException();
</code>```

Simple, readable and straightforward for whoever will need to maintain this code in the future.

If nonetheless you want to do it in some functionalish style:

```<code>o.orElseThrow(NotFoundException::new);
o.filter(p).orElseThrow(ForbiddenException::new);
</code>```

With Java 9:

```<code>o.ifPresentOrElse(
    t -> if (!p.test(t)) throw new ForbiddenException(),
    () -> throw new NotFoundException());
</code>```

Body:
There's a method called validate which as input accepts an instance of Option and a Predicate - two arguments (yeah, I know Option should be passed as an argument but this is simplified real-world scenario here. Now, if Option is empty I need to throw NotFoundException. When it has a value that doesn't match the Predicate passed it should fail with ForbiddenException. If it has value and it matches the predicate nothing happens.

So this will be:

                Option, Predicate
                     /\
          isEmpty() /  \ isDefined()
                   /    \
            throw NFE    matches(Predicate)
                        / \
                    no /   \ yes
                      /     \
                throw FE     end

I have some solutions but would like potential answerers to come to this question with clear mind ;) My problem is getting the first exception if both tests fail. I expect an elegant solution if I may expect anything ;) All vavr beings allowed (Either, Validation, Try..)

One of the ideas is to use double Option:

Option
  .of(o.getOrElseThrow(NotFoundException::new))
  .filter(p)
  .getOrElseThrow(ForbiddenException::new);

But this seems a bit awkward.

Here sample project may be found.

Body:
As I see it, the best option would be to create readable code, which in this case means using two if statements:

if (!o.isPresent()) throw new NotFoundException();
if (!p.test(o.get())) throw new ForbiddenException();

Simple, readable and straightforward for whoever will need to maintain this code in the future.

If nonetheless you want to do it in some functionalish style:

o.orElseThrow(NotFoundException::new);
o.filter(p).orElseThrow(ForbiddenException::new);

With Java 9:

o.ifPresentOrElse(
    t -> if (!p.test(t)) throw new ForbiddenException(),
    () -> throw new NotFoundException());


问:
How to validate number is greater than 0 in python?
I tried to validate the returned number from input form in python. The input value must be a number and greater than 0.

My script is like this:

hello.py

```<code># -*- coding: utf-8 -*-
from flask import *

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def checNumber():
    if request.method=='POST':

        number = request.form['Number']

        try:
            if int(number) < 0:
                raise 'Number should be greater than 0'
        except:
                raise 'Please enter number only'

    return render_template('hello.html')

if __name__ == '__main__':

    app.run(debug=True)
</code>```

hello.html

```<code><form class="form-horizontal" action='' method='POST'>
      <div class="form-group">
        <label for="KhmerName" class="col-sm-2 control-label">Number:</label>
        <div class="col-sm-10">
          <input type="text" class="form-control" id="Number" name="Number" placeholder="Please enter number only">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default">Submit</button>
        </div>
      </div>
    </form>
</code>```

After I click on submit form, if the inputted value is not a number (alphabet or something else) it will raise 'Please enter number only'. However, if number is negative, it never raise 'Number should be greater than 0', yet the python regards it as not a number and raise 'Please enter number only'.

I think a negative value is also a number.

How can I fix this? Thanks.

答:
```<code>raise 'Number should be greater than 0'
</code>```

You expect this line will raise an exception and the checNumber function dump, but the exception caught by the try ... except ... block.

Try this:

```<code>@app.route('/', methods=['GET', 'POST'])
def checNumber():
    if request.method == 'POST':

        number_str = request.form['Number']
        try:
            number = float(number_str)
        except ValueError:
            number = None

        if number is None:
            raise ValueError('Please enter number only')
        elif number <= 0:
            raise ValueError('Number should be greater than 0')
        else:
            pass

    return render_template('hello.html')
</code>```

Body:
I tried to validate the returned number from input form in python. The input value must be a number and greater than 0.

My script is like this:

hello.py

# -*- coding: utf-8 -*-
from flask import *

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def checNumber():
    if request.method=='POST':

        number = request.form['Number']

        try:
            if int(number) < 0:
                raise 'Number should be greater than 0'
        except:
                raise 'Please enter number only'

    return render_template('hello.html')

if __name__ == '__main__':

    app.run(debug=True)

hello.html

<form class="form-horizontal" action='' method='POST'>

        Number:

          <input type="text" class="form-control" id="Number" name="Number" placeholder="Please enter number only">

          <button type="submit" class="btn btn-default">Submit</button>

    </form>

After I click on submit form, if the inputted value is not a number (alphabet or something else) it will raise 'Please enter number only'. However, if number is negative, it never raise 'Number should be greater than 0', yet the python regards it as not a number and raise 'Please enter number only'.

I think a negative value is also a number.

How can I fix this? Thanks.

Body:
raise 'Number should be greater than 0'

You expect this line will raise an exception and the checNumber function dump, but the exception caught by the try ... except ... block.

Try this:

@app.route('/', methods=['GET', 'POST'])
def checNumber():
    if request.method == 'POST':

        number_str = request.form['Number']
        try:
            number = float(number_str)
        except ValueError:
            number = None

        if number is None:
            raise ValueError('Please enter number only')
        elif number <= 0:
            raise ValueError('Number should be greater than 0')
        else:
            pass

    return render_template('hello.html')


问:
Find and extract a number from a string
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

```<code>string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"
</code>```

How can I do this?

答:
You will have to use Regex as \d+

\d matches digits in the given string.

Title: Find and extract a number from a string

Body:
I have a requirement to find and extract a number contained within a string.

For example, from these strings:

string test = "1 test"
string test1 = " 1 test"
string test2 = "test 99"

How can I do this?


问:
Get 'ref' of a Child of Route React Element
I try to access to a ref of a child of a Route element of react router but it doesn't work.

```<code><Route path={path} render={ () => (
            <Child ref={ (el => this.$child = el)} />
          )} />
</code>```

Console log: "Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail."

答:
You should be able to get the ref of Child component even though it's inside Route element. The problem here is your Child element is probably a stateless function component which doesn't support ref. Because functional components don't have instances.

Define your Child component as an ES6 class instead of a function.

You can read about this more here:https://reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components

Body:
I try to access to a ref of a child of a Route element of react router but it doesn't work.

<Route path={path} render={ () => (
            <Child ref={ (el => this.$child = el)} />
          )} />

Console log: "Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail."


问:
Are two classes in same namespace & project also in the same executing assembly?
I am asking the question in the title because this works:

```<code>FooBar fooBar = new FooBar();
</code>```

It hits the constructor in FooBar, etc.  But this returns null:

```<code>Type type = Type.GetType("FooBar");
</code>```

Both FooBar and the class from which I am trying to do this are in the same namespace, the same project, etc.

I've looked over this thread:

Type.GetType("namespace.a.b.ClassName") returns null

According to that accepted answer (and some others), this "only works when the type is found in either mscorlib.dll or the currently executing assembly."

If the two classes are in the same namespace and the same project (ie: same .dll) would that not make the same executing assembly?

What am I doing wrong?

答:
From the documentation:

typeName.  The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

So you still need to provide the namespace, e.g.

```<code>var type = Type.GetType("MyNamespace.FooBar");
</code>```

If you really don't want to provide the namespace for some reason, as an alternative, you could just as easily do something like this:

```<code>var type = System.Reflection.Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(a => a.Name == "FooBar");
</code>```

Body:
I am asking the question in the title because this works:

FooBar fooBar = new FooBar();

It hits the constructor in FooBar, etc.  But this returns null:

Type type = Type.GetType("FooBar");

Both FooBar and the class from which I am trying to do this are in the same namespace, the same project, etc.

I've looked over this thread:

Type.GetType("namespace.a.b.ClassName") returns null

According to that accepted answer (and some others), this "only works when the type is found in either mscorlib.dll or the currently executing assembly."

If the two classes are in the same namespace and the same project (ie: same .dll) would that not make the same executing assembly?

What am I doing wrong?

Body:
From the documentation:

typeName.  The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

So you still need to provide the namespace, e.g.

var type = Type.GetType("MyNamespace.FooBar");

If you really don't want to provide the namespace for some reason, as an alternative, you could just as easily do something like this:

var type = System.Reflection.Assembly.GetExecutingAssembly()
    .GetTypes()
    .Where(a => a.Name == "FooBar");


问:
installing python 2.7 package with anaconda
I am trying to figure out how to install packages for the first time. I have downloaded Python 2.7 with the Anaconda distribution. When I go to terminal and I type:

```<code>pip install pandas-datareader
</code>```

I see a message that the package was installed successfully. However, when I enter:

```<code>import pandas-datareader as pdr
</code>```

into Spyder, I get the error:

```<code>No module named pandas-datareader
</code>```

I think this might be because I am not installing the package in the right directory. I also tried:

```<code> conda install -c anaconda pandas-datareader
</code>```

and got the same result. I know there are many posts about installing packages, but I am looking for a super basic beginner explanation for how to troubleshoot this. What directory should I save packages in? How do I navigate to that directory? How do I use terminal to download the package into that directory, etc.

答:
After following your link, I got it to work by entering

```<code>!pip install pandas-datareader
</code>```

in the Spyder Ipython console!

Body:
I am trying to figure out how to install packages for the first time. I have downloaded Python 2.7 with the Anaconda distribution. When I go to terminal and I type:

pip install pandas-datareader

I see a message that the package was installed successfully. However, when I enter:

import pandas-datareader as pdr

into Spyder, I get the error:

No module named pandas-datareader

I think this might be because I am not installing the package in the right directory. I also tried:

 conda install -c anaconda pandas-datareader

and got the same result. I know there are many posts about installing packages, but I am looking for a super basic beginner explanation for how to troubleshoot this. What directory should I save packages in? How do I navigate to that directory? How do I use terminal to download the package into that directory, etc.

Body:
After following your link, I got it to work by entering

!pip install pandas-datareader

in the Spyder Ipython console!


问:
How can I dynamically create class methods for a class in python
If I define a little python program as

```<code>class a():
    def _func(self):
        return "asdf"

    # Not sure what to resplace __init__ with so that a.func will return asdf
    def __init__(self, *args, **kwargs):
         setattr(self, 'func', classmethod(self._func))

if __name__ == "__main__":
    a.func
</code>```

I receive the traceback error

```<code>Traceback (most recent call last):
  File "setattr_static.py", line 9, in <module>
    a.func
AttributeError: class a has no attribute 'func'
</code>```

What I am trying to figure out is, how can I dynamically set a class method to a class without instantiating an object?

Edit:

The answer for this problem is

```<code>class a():
    pass

def func(cls, some_other_argument):
    return some_other_argument

setattr(a, 'func', classmethod(func))

if __name__ == "__main__":
    print(a.func)
    print(a.func("asdf"))
</code>```

returns the following output

```<code><bound method type.func of <class '__main__.a'>>
asdf
</code>```

答:
I'm using Python 2.7.5, and I wasn't able to get the above solutions working for me. This is what I ended up with:</p>

```<code># define a class object (your class may be more complicated than this...)
class A(object):
    pass

def func(self):
    print 'I am class {}'.format(self.name)

A.func = func

# using classmethod() here failed with:
#       AttributeError: type object '...' has no attribute 'name'
</code>```

Body:
If I define a little python program as

class a():
    def _func(self):
        return "asdf"

    # Not sure what to resplace __init__ with so that a.func will return asdf
    def __init__(self, *args, **kwargs):
         setattr(self, 'func', classmethod(self._func))

if __name__ == "__main__":
    a.func

I receive the traceback error

Traceback (most recent call last):
  File "setattr_static.py", line 9, in <module>
    a.func
AttributeError: class a has no attribute 'func'

What I am trying to figure out is, how can I dynamically set a class method to a class without instantiating an object?

Edit:

The answer for this problem is

class a():
    pass

def func(cls, some_other_argument):
    return some_other_argument

setattr(a, 'func', classmethod(func))

if __name__ == "__main__":
    print(a.func)
    print(a.func("asdf"))

returns the following output

<bound method type.func of <class '__main__.a'>>
asdf

Body:
I'm using Python 2.7.5, and I wasn't able to get the above solutions working for me. This is what I ended up with:

# define a class object (your class may be more complicated than this...)
class A(object):
    pass

def func(self):
    print 'I am class {}'.format(self.name)

A.func = func

# using classmethod() here failed with:
#       AttributeError: type object '...' has no attribute 'name'


问:
React component initialize state from props
In React, are there any real differences between these two implementations?
Some friends tell me that the FirstComponent is the pattern, but I don't see why. The SecondComponent seems simpler because the render is called only once.

First:

```<code>import React, { PropTypes } from 'react'

class FirstComponent extends React.Component {

  state = {
    description: ''
  }

  componentDidMount() {
    const { description} = this.props;
    this.setState({ description });
  }

  render () {
    const {state: { description }} = this;
    return (
      <input type="text" value={description} />
    );
  }
}

export default FirstComponent;
</code>```

Second:

```<code>import React, { PropTypes } from 'react'

class SecondComponent extends React.Component {

  state = {
    description: ''
  }

  constructor (props) => {
    const { description } = props;
    this.state = {description};
  }

  render () {
    const {state: { description }} = this;
    return (
      <input type="text" value={description} />
    );
  }
}

export default SecondComponent;
</code>```

Update:
I changed setState() to this.state = {} (thanks joews), However, I still don't see the difference. Is one better than other?

答:
It should be noted that it is an anti-pattern to copy properties that never change to the state (just access .props directly in that case). If you have a state variable that will change eventually but starts with a value from .props, you don't even need a constructor call - these local variables are initialized after a call to the parent's constructor:

```<code>class FirstComponent extends React.Component {
  state = {
    x: this.props.initialX,
    // You can even call functions and class methods:
    y: this.someMethod(this.props.initialY),
  };
}
</code>```

This is a shorthand equivalent to the answer from @joews below. It seems to only work on more recent versions of es6 transpilers, I have had issues with it on some webpack setups. If this doesn't work for you, you can try adding the babel plugin babel-plugin-transform-class-properties, or you can use the non-shorthand version by @joews below.

Body:
In React, are there any real differences between these two implementations?
Some friends tell me that the FirstComponent is the pattern, but I don't see why. The SecondComponent seems simpler because the render is called only once.

First:

import React, { PropTypes } from 'react'

class FirstComponent extends React.Component {

  state = {
    description: ''
  }

  componentDidMount() {
    const { description} = this.props;
    this.setState({ description });
  }

  render () {
    const {state: { description }} = this;
    return (
      <input type="text" value={description} />
    );
  }
}

export default FirstComponent;

Second:

import React, { PropTypes } from 'react'

class SecondComponent extends React.Component {

  state = {
    description: ''
  }

  constructor (props) => {
    const { description } = props;
    this.state = {description};
  }

  render () {
    const {state: { description }} = this;
    return (
      <input type="text" value={description} />
    );
  }
}

export default SecondComponent;

Update:
I changed setState() to this.state = {} (thanks joews), However, I still don't see the difference. Is one better than other?

Body:
It should be noted that it is an anti-pattern to copy properties that never change to the state (just access .props directly in that case). If you have a state variable that will change eventually but starts with a value from .props, you don't even need a constructor call - these local variables are initialized after a call to the parent's constructor:

class FirstComponent extends React.Component {
  state = {
    x: this.props.initialX,
    // You can even call functions and class methods:
    y: this.someMethod(this.props.initialY),
  };
}

This is a shorthand equivalent to the answer from @joews below. It seems to only work on more recent versions of es6 transpilers, I have had issues with it on some webpack setups. If this doesn't work for you, you can try adding the babel plugin babel-plugin-transform-class-properties, or you can use the non-shorthand version by @joews below.


问:
How do I make a real-time updating grid in c++
So I'm making a sudoku solver to kind of test myself, and I have seem to hit a wall.

I'm trying to get the user to input values into a grid, and it'll automatically update every couple of seconds to see the next value they put in the grid.

I don't know how to get the user input into the grid itself.

Here is my code for the grid itself.

```<code>void draw()
{
int given;
cout << endl;
for (int i = 0; i < 13; i++)
{
    for (int j = 0; j <= 9; j++)
    {
        if (j == 0)
        {
            cout << "|";
        }
        if (j == 3 || j == 6 || j == 9 )
        {
            cout << "|";
        }
        if (i == 0 || i == 4 || i == 8 || i == 12)
        {
            cout << "#";
        }
        else
        {
            cout << " ";
        }
    }

    cout << endl;

}
</code>```

}

To get this to refresh, I have this loop.

```<code>while (gameOver != TRUE)
{
    system("cls");
    draw();
    cout << "\nEnter the next given number, or 0 for a blank space: ";
    Sleep(600);
}
</code>```

So I need help getting the user input value to both

Display on the grid

Save in any way (I think an array might work best?)

Thanks.

答:
I personally think that the easiest way to visualize (and store) the values would be in a two-dimensional array.

You can declare and n * m array like this :

```<code>int x[n][m];
</code>```

Then access elements (i,j) like this in your for loop to display it :

```<code>x[i][j]
</code>```

Body:
So I'm making a sudoku solver to kind of test myself, and I have seem to hit a wall.

I'm trying to get the user to input values into a grid, and it'll automatically update every couple of seconds to see the next value they put in the grid.

I don't know how to get the user input into the grid itself.

Here is my code for the grid itself.

void draw()
{
int given;
cout << endl;
for (int i = 0; i < 13; i++)
{
    for (int j = 0; j <= 9; j++)
    {
        if (j == 0)
        {
            cout << "|";
        }
        if (j == 3 || j == 6 || j == 9 )
        {
            cout << "|";
        }
        if (i == 0 || i == 4 || i == 8 || i == 12)
        {
            cout << "#";
        }
        else
        {
            cout << " ";
        }
    }

    cout << endl;

}

}

To get this to refresh, I have this loop.

while (gameOver != TRUE)
{
    system("cls");
    draw();
    cout << "\nEnter the next given number, or 0 for a blank space: ";
    Sleep(600);
}

So I need help getting the user input value to both

Display on the grid

Save in any way (I think an array might work best?)

Thanks.

Body:
I personally think that the easiest way to visualize (and store) the values would be in a two-dimensional array.

You can declare and n * m array like this :

int x[n][m];

Then access elements (i,j) like this in your for loop to display it :

x[i][j]


问:
stop javascript loop, setTimeout
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

```<code>setTimeout(function() {
createSnow(20);
loop();
}, 10000)
</code>```

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

答:
the only thing that you have to change is a little change of your code plz see this code below : </p>

```<code>var timeOut = setTimeout(function() {
createSnow(20);
loop();
}, 10000);

clearTimeout(timeOut);
</code>```

Title: stop javascript loop, setTimeout

Body:
This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

setTimeout(function() {
createSnow(20);
loop();
}, 10000)

here is a codePen to see what I mean:
https://codepen.io/celli/pen/XzzjRW

Body:
the only thing that you have to change is a little change of your code plz see this code below :

var timeOut = setTimeout(function() {
createSnow(20);
loop();
}, 10000);

clearTimeout(timeOut);


问:
How to make a characteristic both read and write?
I understand that a characteristic can have only one property and one permission, and that the property must have the same value as the permission e.g. a characteristic must have the property of being writable if it has permission to be written to... so how can I make a characteristic readable AND writable?

e.g.

How to turn this

```<code>int permission = BluetoothGattCharacteristic.PERMISSION_WRITE;
int property = BluetoothGattCharacteristic.PROPERTY_WRITE;
</code>```

Into read and write

答:
Use a mask    </p>

```<code>int permission = BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ;
int property = BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_READ;
</code>```

Body:
I understand that a characteristic can have only one property and one permission, and that the property must have the same value as the permission e.g. a characteristic must have the property of being writable if it has permission to be written to... so how can I make a characteristic readable AND writable?

e.g.

How to turn this

int permission = BluetoothGattCharacteristic.PERMISSION_WRITE;
int property = BluetoothGattCharacteristic.PROPERTY_WRITE;

Into read and write

Body:
Use a mask

int permission = BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ;
int property = BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_READ;


问:
Installshield Include redistributable with program setup exe
Just got InstallShield Pro and I've created my setup singleimage executable.

I need to include the Visual C++ 2005 SP1 redistributable within the setup.

I've ticked the redistributable I want in the menu under 'Application Data'.
I've right clicked it and changed the 'Build Location' to 'extract from setup.exe'.

However, when I build my setup, it has a folder called 'ISSetupPrerequisites' which has the VC++ redistributable in it.

Is there anyway I can incorporate this in to a single exe with my installer?

If I remove that folder it downloads the redistributable from the internet.

Thanks

答:
I added a post build custom action aver the setup dialog success.  Added vcredist_x86.exe to the install. And put /install as the command line - which is the only command line option that worked for me.

If I did it any other way the redist error-ed  because two installs were going on.


问:
@Cacheble annotation on no parameter method
I want to have @Cacheable annotation on method with no parameter. In that case, I use @Cacheable as follows

```<code>@Cacheable(value="usercache", key = "mykey")
public string sayHello(){
    return "test"
}
</code>```

However, when I call this method, it doesn't get executed and it get exception as below

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'mykey' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public?

Please suggest.

答:
Try adding single quotes around mykey.  It's a SPEL expression, and the singles quotes make it a String again.

```<code>@Cacheable(value="usercache", key = "'mykey'")
</code>```

Body:
I want to have @Cacheable annotation on method with no parameter. In that case, I use @Cacheable as follows

@Cacheable(value="usercache", key = "mykey")
public string sayHello(){
    return "test"
}

However, when I call this method, it doesn't get executed and it get exception as below

org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Property or field 'mykey' cannot be found on object of type 'org.springframework.cache.interceptor.CacheExpressionRootObject' - maybe not public?

Please suggest.

Body:
Try adding single quotes around mykey.  It's a SPEL expression, and the singles quotes make it a String again.

@Cacheable(value="usercache", key = "'mykey'")


问:
How to create Loopback model with random string as primary key?

TL; DR

How to make Accounts.create({ provider: "facebook" }) create the id primary key automatically?

Description

Given a persistent Loopback model definition

```<code>{
  "name": "Account",
  "plural": "accounts",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "id": true,
      "type": "string",
      "required": true
    },
    "provider": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "acls": [],
  "methods": {}
}
</code>```

how it would be possible add a remote method at Account.js to automatically create a random string as primary key?

答:
try adding this as a property within the json file of the model:

```<code>"id": {
  "type": "string",
  "id": true,
  "defaultFn": "uuid"
},
</code>```

This should auto-generate random Primary key as uuid.

Body:
TL; DR

How to make Accounts.create({ provider: "facebook" }) create the id primary key automatically?

Description

Given a persistent Loopback model definition

{
  "name": "Account",
  "plural": "accounts",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "id": true,
      "type": "string",
      "required": true
    },
    "provider": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "acls": [],
  "methods": {}
}

how it would be possible add a remote method at Account.js to automatically create a random string as primary key?

Body:
try adding this as a property within the json file of the model:

"id": {
  "type": "string",
  "id": true,
  "defaultFn": "uuid"
},

This should auto-generate random Primary key as uuid.


问:
Convert attribute value into element
I'm trying to transform this xml:

```<code><tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>
</code>```

into this xml:

```<code><tokens>
 <a>
  <b>nomX</b>
  <c>prenomX</c>
  <d>villeX</d>
 </a>
 <a>
  <b>nomY</b>
  <c>prenomY</c>
  <d>villeY</d>
 </a>
 <e>nomZ</e>
</tokens>
</code>```

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet.
If anyone has an idea, it would be  greatly appreciated.

Thx.

答:
I used your answer to find the right xsl:

here is what i use:

```<code><xsl:template match="token">
        <xsl:element name="{@cle}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>
</code>```

Thank a lot !

Title: Convert attribute value into element

Body:
I'm trying to transform this xml:

<tokens>
 <token cle="a">
  <token cle="b">nomX</token>
  <token cle="c">prenomX</token>
  <token cle="d">villeX</token>
 </token>
 <token cle="a">
  <token cle="b">nomY</token>
  <token cle="c">prenomY</token>
  <token cle="d">villeY</token>
 </token>
 <token cle="e">nomZ</token>
</tokens>

into this xml:

<tokens>

  nomX
  <c>prenomX</c>
  <d>villeX</d>

  nomY
  <c>prenomY</c>
  <d>villeY</d>

 <e>nomZ</e>
</tokens>

so convert the attribute value into an element , but i need to keep the whole structure and deph.

I've tried using XSL, but i didn't succeed yet.
If anyone has an idea, it would be  greatly appreciated.

Thx.

Body:
I used your answer to find the right xsl:

here is what i use:

<xsl:template match="token">
        <xsl:element name="{@cle}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

Thank a lot !


问:
How can I use the name of a string in the form of a string variable to retrieve that string from the XML files?
I want to use the string's name or label in the form of a string variable to retrieve that string from R.string.nameOfString but can't figure out how. In the method getText() which is used to get the string, it takes "resource id for the string as a parameter," and the resource id is an int. I'm not sure how the path in a string variable can be converted to this resource id so I can retrieve that string from the XML file.

答:
1.Add it to res/values/strings.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="nameOfString">helloworld</string>
</resources>
</code>```

2.Use in your code

```<code>String value = context.getResources().getString(R.string.nameOfString);
</code>```

Note

You just change context to your current context(Activity or fragment)

Body:
1.Add it to res/values/strings.xml file

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="nameOfString">helloworld</string>
</resources>

2.Use in your code

String value = context.getResources().getString(R.string.nameOfString);

Note

You just change context to your current context(Activity or fragment)


问:
Outlook: How to access other contact folders?
Some people have a number of lists/folders in Outlook, under Contacts (e.g. besides Contacts and Suggested Contacts, people can add new "folders" of contacts).

Now, my questions:

How can I get a list of all these lists/folders?

How can I access all the contacts in any of these folders?

I know that if I want to access the contacts from the main "Contacts" list, then the code looks like this:

```<code>   MAPIFolder oMAPIFolder =
              oNmSpc.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
   oItemsTemp = oMAPIFolder.Items;
</code>```

How would it look like when accessing other contact lists/folders?

Thanks!

答:
To access the "Suggested Contacts" Folder proceed exactly as you do for contact but

Instead of

```<code>outlook := CreateOLEObject('Outlook.Application');
  NameSpace := outlook.GetNameSpace('MAPI');
  ContactsRoot := NameSpace.GetDefaultFolder(olFolderContacts) ;
</code>```

Use

```<code>outlook := CreateOLEObject('Outlook.Application');
  NameSpace := outlook.GetNameSpace('MAPI');
  SuggestedContactsRoot := NameSpace.GetDefaultFolder(olFolderSuggestedContacts);
</code>```

Where olFolderSuggestedContacts has a value of 30 (decimal) or $0000001E in Hexadecimal

I know this is Delphi language, but adapatation to C# should be straightforward.

Body:
Some people have a number of lists/folders in Outlook, under Contacts (e.g. besides Contacts and Suggested Contacts, people can add new "folders" of contacts).

Now, my questions:

How can I get a list of all these lists/folders?

How can I access all the contacts in any of these folders?

I know that if I want to access the contacts from the main "Contacts" list, then the code looks like this:

   MAPIFolder oMAPIFolder =
              oNmSpc.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
   oItemsTemp = oMAPIFolder.Items;

How would it look like when accessing other contact lists/folders?

Thanks!

Body:
To access the "Suggested Contacts" Folder proceed exactly as you do for contact but

Instead of

outlook := CreateOLEObject('Outlook.Application');
  NameSpace := outlook.GetNameSpace('MAPI');
  ContactsRoot := NameSpace.GetDefaultFolder(olFolderContacts) ;

Use

outlook := CreateOLEObject('Outlook.Application');
  NameSpace := outlook.GetNameSpace('MAPI');
  SuggestedContactsRoot := NameSpace.GetDefaultFolder(olFolderSuggestedContacts);

Where olFolderSuggestedContacts has a value of 30 (decimal) or $0000001E in Hexadecimal

I know this is Delphi language, but adapatation to C# should be straightforward.


问:
Why does IDLE continue to crash?
Idle keeps crashing and I can't figure it out. After restarting the computer and reinstalling Python, none of which seemed to work, I looked to my peers and was told to "install one of the Tcl/Tk". After getting another opinion I was also told that I already had this and found it to be true but decided to try it anyway since it continued to crash. Nothing has improved and I have an assignment due.

Any ideas on why this continues to happen and what I can do to fix the crash?

Problem details:

```<code>Process:         Python [1183]
Path:            /Applications/Python 3.3/IDLE.app/Contents/MacOS/Python
Identifier:      org.python.IDLE
Version:         3.3.0 (3.3.0)
Code Type:       X86-64 (Native)
Parent Process:  launchd [793]

Date/Time:       2012-11-05 14:10:54.124 -0500
OS Version:      Mac OS X 10.7.5 (11G63)
Report Version:  9

Interval Since Last Report:          181805 sec
Crashes Since Last Report:           4
Per-App Interval Since Last Report:  20 sec
Per-App Crashes Since Last Report:   4
Anonymous UUID:                      68994A08-7FFB-4074-A553-CB60A60BB412

Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1007) creating CGSWindow on line 263'
</code>```

答:
For me, 90% of crashes were caused when I typed a left-parenthesis. That was fixed by:

In IDLE:

Options Menu > Configure Extensions > CallTips > set to FALSE

Then restart.

Took much research to find that super simple solution... the problem is caused not by an error in IDLE but by an error in the mac's Tcl/Tk code when calltips are called in external monitors above the default monitor.

OwnerDisplayName: Dyana

Title: Why does IDLE continue to crash?

Body:
Idle keeps crashing and I can't figure it out. After restarting the computer and reinstalling Python, none of which seemed to work, I looked to my peers and was told to "install one of the Tcl/Tk". After getting another opinion I was also told that I already had this and found it to be true but decided to try it anyway since it continued to crash. Nothing has improved and I have an assignment due.

Any ideas on why this continues to happen and what I can do to fix the crash?

Problem details:

Process:         Python [1183]
Path:            /Applications/Python 3.3/IDLE.app/Contents/MacOS/Python
Identifier:      org.python.IDLE
Version:         3.3.0 (3.3.0)
Code Type:       X86-64 (Native)
Parent Process:  launchd [793]

Date/Time:       2012-11-05 14:10:54.124 -0500
OS Version:      Mac OS X 10.7.5 (11G63)
Report Version:  9

Interval Since Last Report:          181805 sec
Crashes Since Last Report:           4
Per-App Interval Since Last Report:  20 sec
Per-App Crashes Since Last Report:   4
Anonymous UUID:                      68994A08-7FFB-4074-A553-CB60A60BB412

Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000

Application Specific Information:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Error (1007) creating CGSWindow on line 263'


问:
Sorting through array c++
So I am attempting to do a bubble-like sort. Not a bubble sort because I don't want to exchange every single value that i run into. I simply want to find the smallest value of each index and place it in order. Such as in the arrayVal[3, 5, 2].

Instead of replacing the value 3 with 2 and then replacing 5 with 3. I want to find the smallest number of the entire array and place it at arrayVal[0] and then move to arrayVal[1].

I can't quite figure out how to do this and am kind of stuck.(I took out the <> on the libraries so you could see which libraries I am using)

```<code>#include iostream
#include cmath
#include ctime
using namespace std;

int main()
{
    const int STARTLOOP = 0;
    const int MAXLOOP = 5;
    const int MINRANGE = 1;
    const int MAXRANGE = 10;

    //int temp = 0;
    int smallestVal = 0;
    int arrayVal[MAXLOOP];

    srand(time(0));

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        arrayVal[i] = (rand() % MAXRANGE) + MINRANGE;
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "Before the sort" << endl;

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        for (int j = i; j < MAXLOOP; j++)
        {
            if (arrayVal[j] < arrayVal[i])
            {
                arrayVal[i] = smallestVal;
            }

        }
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "After the sort" << endl;

    return 0;
</code>```

I also recognize I'm not using functions, i just wrote up the code because I was trying to figure this out. Thank you in advance.

答:
You're never setting smallestVal to anything from the array. You don't need nested loops. Just go through the array once, comparing each value to smallestVal. If it's smaller, you set smallestVal to that value. You should also have a variable that holds the index of the smallest value, which you update at the same time.

At the end, you swap the first element with the smallest one.

```<code>int smallestVal = arrayVal[STARTLOOP];
int smallestIndex = STARTLOOP;
for (int i = STARTLOOP + 1; i < MAXLOOP; i++) {
    if (arrayVal[i] < smallestVal) {
        smallestVal = arrayVal[i];
        smallestIndex = i;
    }
}
if (smallestIndex != STARTLOOP) {
    // swap it with the first element
    int temp = arrayVal[STARTLOOP];
    arrayVal[STARTLOOP] = smallestVal;
    arrayVal[smallestIndex] = temp;
}
</code>```

You can then increment STARTLOOP and repeat this.

Title: Sorting through array c++

Body:
So I am attempting to do a bubble-like sort. Not a bubble sort because I don't want to exchange every single value that i run into. I simply want to find the smallest value of each index and place it in order. Such as in the arrayVal[3, 5, 2].

Instead of replacing the value 3 with 2 and then replacing 5 with 3. I want to find the smallest number of the entire array and place it at arrayVal[0] and then move to arrayVal[1].

I can't quite figure out how to do this and am kind of stuck.(I took out the <> on the libraries so you could see which libraries I am using)

#include iostream
#include cmath
#include ctime
using namespace std;

int main()
{
    const int STARTLOOP = 0;
    const int MAXLOOP = 5;
    const int MINRANGE = 1;
    const int MAXRANGE = 10;

    //int temp = 0;
    int smallestVal = 0;
    int arrayVal[MAXLOOP];

    srand(time(0));

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        arrayVal[i] = (rand() % MAXRANGE) + MINRANGE;
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "Before the sort" << endl;

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        for (int j = i; j < MAXLOOP; j++)
        {
            if (arrayVal[j] < arrayVal[i])
            {
                arrayVal[i] = smallestVal;
            }

        }
    }

    for (int i = STARTLOOP; i < MAXLOOP; i++)
    {
        cout << arrayVal[i] << endl;
    }

    cout << "After the sort" << endl;

    return 0;

I also recognize I'm not using functions, i just wrote up the code because I was trying to figure this out. Thank you in advance.

Body:
You're never setting smallestVal to anything from the array. You don't need nested loops. Just go through the array once, comparing each value to smallestVal. If it's smaller, you set smallestVal to that value. You should also have a variable that holds the index of the smallest value, which you update at the same time.

At the end, you swap the first element with the smallest one.

int smallestVal = arrayVal[STARTLOOP];
int smallestIndex = STARTLOOP;
for (int i = STARTLOOP + 1; i < MAXLOOP; i++) {
    if (arrayVal[i] < smallestVal) {
        smallestVal = arrayVal[i];
        smallestIndex = i;
    }
}
if (smallestIndex != STARTLOOP) {
    // swap it with the first element
    int temp = arrayVal[STARTLOOP];
    arrayVal[STARTLOOP] = smallestVal;
    arrayVal[smallestIndex] = temp;
}

You can then increment STARTLOOP and repeat this.


问:
ControlsFX PopOver - adding style classes cuts off the borders
I've been using The PopOver node of controlsFX so i wanted to change the background color of the control so i've changed the background color of my content node but that left the arrow and the header uncolored here (The white boxes are just cards and are meant to be white) so i tried this approach that i've found here

```<code>globalScopingPopOver.show(owner);

((Parent) globalScopingPopOver.getSkin().getNode()).getStylesheets()
        .remove(getClass().getResource("/css/myCustomPopOver.css").toExternalForm());

((Parent) globalScopingPopOver.getSkin().getNode()).getStylesheets()
        .add(getClass().getResource("/css/myCustomPopOver.css").toExternalForm());
</code>```

where myCustomPopOver.css contains:

```<code>.popover > .border {
    -fx-fill: rgb(0,0,0);
}

.popover > .header {
    -fx-fill: rgb(0,0,0);
}
</code>```

which left me with this which has two obvious problems, the first is that the right border is trimmed and the second is that the arrow is hidden under the footer bar.

Detaching the popover by dragging fixes the right border problem, yet detaching and reattaching it by code sends us back to where we started removing the effects of the CSS stylesheet:

```<code>globalScopingPopOver.detach();
globalScopingPopOver.setDetached(false);
</code>```

So any help why this's happening and how to fix it?

Thank you!

答: Calling show(owner) a second time after adding the stylesheet did the trick for me.

Body:
I've been using The PopOver node of controlsFX so i wanted to change the background color of the control so i've changed the background color of my content node but that left the arrow and the header uncolored here (The white boxes are just cards and are meant to be white) so i tried this approach that i've found here

globalScopingPopOver.show(owner);

((Parent) globalScopingPopOver.getSkin().getNode()).getStylesheets()
        .remove(getClass().getResource("/css/myCustomPopOver.css").toExternalForm());

((Parent) globalScopingPopOver.getSkin().getNode()).getStylesheets()
        .add(getClass().getResource("/css/myCustomPopOver.css").toExternalForm());

where myCustomPopOver.css contains:

.popover > .border {
    -fx-fill: rgb(0,0,0);
}

.popover > .header {
    -fx-fill: rgb(0,0,0);
}

which left me with this which has two obvious problems, the first is that the right border is trimmed and the second is that the arrow is hidden under the footer bar.

Detaching the popover by dragging fixes the right border problem, yet detaching and reattaching it by code sends us back to where we started removing the effects of the CSS stylesheet:

globalScopingPopOver.detach();
globalScopingPopOver.setDetached(false);

So any help why this's happening and how to fix it?

Thank you!


问:
Fastest Multithreading Sorting Method
Currently, I am creating a multi-threaded sorter that reads in a bunch of CSV files and outputs a single large sorted CSV file consisting of all the data in the CSV files. Right now, I am planning on sorting each of the CSV's in their individual thread using mergesort and then sorting it one last time when all the data from the threads are concatenated together. I am just curious whether only using mergesort would be considered "fast". After the threads concatenate the sorted data together, the data is sorted in their individual sections but overall, it is still unsorted. </p>

答:
How large is your data? Sorting is O(n log n), and the final merge step which is inherently not parallelizable is of course O(n), so unless log n is utterly gigantic or the cost of comparisons is disproportionately large compared to the cost of moving data around, there's very little to be gained by multithreaded sorting.

If you still do want to try it, what's wrong with your approach is doing a final merge sort of the concatenated list. That's essentially going to be the same speed as doing the whole sort all over again. Instead, you want to merge the output from each pair of threads using a single merge operation rather than a whole merge-sort. Repeat this, halving the number of sorted lists you have each time, until the last step just merges 2 lists. You can break this work up into threads by setting up a hierarchical relationship between threads where, when two "sibling" threads in the hierarchy finish their jobs, one exits and the other "moves up" in the hierarchy and picks up merging its sibling's output.

Title: Fastest Multithreading Sorting Method