问:
Bizarre behavior in gdb
I'm experiencing a very strange bug in my code.

I use a variable m_requestedStructures in my program, and the debugger is accessing the wrong address when inspecting it. For example, I have in the code:

```<code>qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures
</code>```

and I set a breakpoint here. When the breakpoint is reached, I compare the printed value and address of m_requestedStructures with those that gdb is accessing:

```<code>requested:  0   0xfce640
Breakpoint 1
157         qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures;
(gdb) p m_requestedStructures
$5 = -1167616
(gdb) p &m_requestedStructures
$6 = (int *) 0xfce644
(gdb)
</code>```

As can be seen, both the value and the address differ.

Another symptom I'm seeing is that I had a function, QueueManager::checkPopulation_() which I removed quite a while ago, but gdb still tries to tab-complete it, and if I set a breakpoint on it, it will break at the point where the function used to be.

It appears to me that the symbols aren't read correctly. I've tried rebuilding from a clean directory, but the problem persists. Does anyone have any idea what might be causing this or how to fix it?

Thanks in advance!

Edit: I just tried setting a breakpoint on a new function I've added. The function QueueManager::run() appears in gdb's tab complete, but when I try to set the breakpoint, I get

```<code>the class GlobalSearch::QueueManager does not have any method named run
</code>```

Also, inspecting other variables, both locally scoped and members of QueueManager, seems to work fine.

Here is the compiler/linker output. The file containing the class is queuemanager.cpp, which is part of a static library libglobalsearch.a, which is used in a dynamic library xtalopt.so:

```<code>$ make VERBOSE=1 xtalopt
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
make -f CMakeFiles/Makefile2 xtalopt
make[1]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 63
make -f CMakeFiles/Makefile2 src/xtalopt/CMakeFiles/xtalopt.dir/all
make[2]: Entering directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/spglib /git/xtalopt-public/build /git/xtalopt-public/build/src/spglib /git/xtalopt-public/build/src/spglib/CMakeFiles/spglib.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/spglib/CMakeFiles/spglib.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  18 19 20 21 22 23
[  9%] Built target spglib
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/libssh /git/xtalopt-public/build /git/xtalopt-public/build/src/libssh /git/xtalopt-public/build/src/libssh/CMakeFiles/ssh_static.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/libssh/CMakeFiles/ssh_static.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
[ 33%] Built target ssh_static
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/globalsearch /git/xtalopt-public/build /git/xtalopt-public/build/src/globalsearch /git/xtalopt-public/build/src/globalsearch/CMakeFiles/globalsearch.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles
[ 33%] Building CXX object src/globalsearch/CMakeFiles/globalsearch.dir/queuemanager.cpp.o
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/c++   -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_PLUGIN -DQT_SHARED -D_HAVE_EXECINFO_H_ -DQT_DEBUG -fPIC -g -I/usr/include/QtOpenGL -I/usr/include/QtGui -I/usr/include/QtCore -I/usr/include/eigen2 -I/git/xtalopt-public/build -I/usr/include/openbabel-2.0 -I/git/xtalopt-public/src   -o CMakeFiles/globalsearch.dir/queuemanager.cpp.o -c /git/xtalopt-public/src/globalsearch/queuemanager.cpp
Linking CXX static library libglobalsearch.a
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -P CMakeFiles/globalsearch.dir/cmake_clean_target.cmake
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -E cmake_link_script CMakeFiles/globalsearch.dir/link.txt --verbose=1
/usr/bin/ar cr libglobalsearch.a  CMakeFiles/globalsearch.dir/optbase.cpp.o CMakeFiles/globalsearch.dir/queuemanager.cpp.o CMakeFiles/globalsearch.dir/structure.cpp.o CMakeFiles/globalsearch.dir/tracker.cpp.o CMakeFiles/globalsearch.dir/optimizer.cpp.o CMakeFiles/globalsearch.dir/bt.cpp.o CMakeFiles/globalsearch.dir/sshconnection.cpp.o CMakeFiles/globalsearch.dir/sshmanager.cpp.o CMakeFiles/globalsearch.dir/random.cpp.o CMakeFiles/globalsearch.dir/ui/abstractdialog.cpp.o CMakeFiles/globalsearch.dir/ui/abstracttab.cpp.o CMakeFiles/globalsearch.dir/moc_optbase.cxx.o CMakeFiles/globalsearch.dir/moc_queuemanager.cxx.o CMakeFiles/globalsearch.dir/moc_structure.cxx.o CMakeFiles/globalsearch.dir/moc_tracker.cxx.o CMakeFiles/globalsearch.dir/moc_optimizer.cxx.o CMakeFiles/globalsearch.dir/moc_bt.cxx.o CMakeFiles/globalsearch.dir/moc_sshconnection.cxx.o CMakeFiles/globalsearch.dir/moc_sshmanager.cxx.o CMakeFiles/globalsearch.dir/moc_random.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstractdialog.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstracttab.cxx.o
/usr/bin/ranlib libglobalsearch.a
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  1 2 3 4 5 6 7 8 9 10 11 12 13 14
[ 55%] Built target globalsearch
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/xtalopt /git/xtalopt-public/build /git/xtalopt-public/build/src/xtalopt /git/xtalopt-public/build/src/xtalopt/CMakeFiles/xtalopt.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
Linking CXX shared library xtalopt.so
cd /git/xtalopt-public/build/src/xtalopt && /usr/bin/cmake -E cmake_link_script CMakeFiles/xtalopt.dir/link.txt --verbose=1
/usr/bin/c++  -fPIC  -fPIC -g  -shared -Wl,-soname,xtalopt.so -o xtalopt.so CMakeFiles/xtalopt.dir/extension.cpp.o CMakeFiles/xtalopt.dir/xtalopt.cpp.o CMakeFiles/xtalopt.dir/genetic.cpp.o CMakeFiles/xtalopt.dir/structures/xtal.cpp.o CMakeFiles/xtalopt.dir/optimizers/xtaloptoptimizer.cpp.o CMakeFiles/xtalopt.dir/optimizers/vasp.cpp.o CMakeFiles/xtalopt.dir/optimizers/gulp.cpp.o CMakeFiles/xtalopt.dir/optimizers/pwscf.cpp.o CMakeFiles/xtalopt.dir/optimizers/castep.cpp.o CMakeFiles/xtalopt.dir/testing/xtalopttest.cpp.o CMakeFiles/xtalopt.dir/ui/dialog.cpp.o CMakeFiles/xtalopt.dir/ui/tab_init.cpp.o CMakeFiles/xtalopt.dir/ui/tab_edit.cpp.o CMakeFiles/xtalopt.dir/ui/tab_opt.cpp.o CMakeFiles/xtalopt.dir/ui/tab_sys.cpp.o CMakeFiles/xtalopt.dir/ui/tab_progress.cpp.o CMakeFiles/xtalopt.dir/ui/tab_plot.cpp.o CMakeFiles/xtalopt.dir/ui/tab_log.cpp.o CMakeFiles/xtalopt.dir/moc_extension.cxx.o CMakeFiles/xtalopt.dir/moc_xtalopt.cxx.o CMakeFiles/xtalopt.dir/moc_genetic.cxx.o CMakeFiles/xtalopt.dir/structures/moc_xtal.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_xtaloptoptimizer.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_vasp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_gulp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_pwscf.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_castep.cxx.o CMakeFiles/xtalopt.dir/testing/moc_xtalopttest.cxx.o CMakeFiles/xtalopt.dir/ui/moc_dialog.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_init.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_edit.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_opt.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_sys.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_progress.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_plot.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_log.cxx.o -lavogadro ../globalsearch/libglobalsearch.a ../spglib/libspglib.a -lQtOpenGL -lGLU -lGL -lSM -lICE -lX11 -lXext -lopenbabel -lQtGui -lQtCore ../libssh/libssh_static.a -lnsl -lresolv -lrt -lz -lssl -lcrypto
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[100%] Built target xtalopt
make[2]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 0
make[1]: Leaving directory `/git/xtalopt-public/build'
</code>```

答:
I finally managed to figure this out! Here's how:

In gdb, I printed all the shared libraries in memory with info shared. I copied this to a text file shared.txt and extracted the library names with:

```<code>cat shared.txt | grep -v \*|grep -v quit---|grep -v Syms\ Read|grep -v \(gdb\)|awk '{print $4}'>libs
</code>```

From there, I checked the symbols in each library with:

```<code>for i in `cat libs|xargs`;do nm --demangle $i|grep checkPopulation; if [ $? -eq 0 ]; then echo \($i\); fi;done
</code>```

Which prints all symbols containing "checkPopulation" followed by the name of the library that contains each. My output:

```<code>000adb18 T GlobalSearch::QueueManager::checkPopulation()
000adb8a T GlobalSearch::QueueManager::checkPopulation_()
(/usr/lib/avogadro/1_1/contrib/randomdock.so)
000db682 T GlobalSearch::QueueManager::checkPopulation()
(/usr/lib/avogadro/1_1/contrib/xtalopt.so)
</code>```

So this "phantom" checkPopulation_ symbol is coming from randomdock.so, which was built a long time ago against an older version of the static libglobalsearch.a, which contains the now removed GlobalSearch::QueueManager::checkPopulation_(). Removing randomdock.so causes everything to behave as it should.

Thanks for all the suggestions -- I certainly learned a few new gdb tricks while tracking this down. There's also a lesson here about breaking API, too ;-)

Title: Bizarre behavior in gdb

Body:
I'm experiencing a very strange bug in my code.

I use a variable m_requestedStructures in my program, and the debugger is accessing the wrong address when inspecting it. For example, I have in the code:

qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures

and I set a breakpoint here. When the breakpoint is reached, I compare the printed value and address of m_requestedStructures with those that gdb is accessing:

requested:  0   0xfce640
Breakpoint 1
157         qDebug() << "requested: " << m_requestedStructures << " " << &m_requestedStructures;
(gdb) p m_requestedStructures
$5 = -1167616
(gdb) p &m_requestedStructures
$6 = (int *) 0xfce644
(gdb)

As can be seen, both the value and the address differ.

Another symptom I'm seeing is that I had a function, QueueManager::checkPopulation_() which I removed quite a while ago, but gdb still tries to tab-complete it, and if I set a breakpoint on it, it will break at the point where the function used to be.

It appears to me that the symbols aren't read correctly. I've tried rebuilding from a clean directory, but the problem persists. Does anyone have any idea what might be causing this or how to fix it?

Thanks in advance!

Edit: I just tried setting a breakpoint on a new function I've added. The function QueueManager::run() appears in gdb's tab complete, but when I try to set the breakpoint, I get

the class GlobalSearch::QueueManager does not have any method named run

Also, inspecting other variables, both locally scoped and members of QueueManager, seems to work fine.

Here is the compiler/linker output. The file containing the class is queuemanager.cpp, which is part of a static library libglobalsearch.a, which is used in a dynamic library xtalopt.so:

$ make VERBOSE=1 xtalopt
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
make -f CMakeFiles/Makefile2 xtalopt
make[1]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -H/git/xtalopt-public -B/git/xtalopt-public/build --check-build-system CMakeFiles/Makefile.cmake 0
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 63
make -f CMakeFiles/Makefile2 src/xtalopt/CMakeFiles/xtalopt.dir/all
make[2]: Entering directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/spglib /git/xtalopt-public/build /git/xtalopt-public/build/src/spglib /git/xtalopt-public/build/src/spglib/CMakeFiles/spglib.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/spglib/CMakeFiles/spglib.dir/build.make src/spglib/CMakeFiles/spglib.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/spglib/CMakeFiles/spglib.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  18 19 20 21 22 23
[  9%] Built target spglib
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/libssh /git/xtalopt-public/build /git/xtalopt-public/build/src/libssh /git/xtalopt-public/build/src/libssh/CMakeFiles/ssh_static.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/libssh/CMakeFiles/ssh_static.dir/build.make src/libssh/CMakeFiles/ssh_static.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
make[3]: Nothing to be done for `src/libssh/CMakeFiles/ssh_static.dir/build'.
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
[ 33%] Built target ssh_static
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/globalsearch /git/xtalopt-public/build /git/xtalopt-public/build/src/globalsearch /git/xtalopt-public/build/src/globalsearch/CMakeFiles/globalsearch.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/globalsearch/CMakeFiles/globalsearch.dir/build.make src/globalsearch/CMakeFiles/globalsearch.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles
[ 33%] Building CXX object src/globalsearch/CMakeFiles/globalsearch.dir/queuemanager.cpp.o
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/c++   -DQT_OPENGL_LIB -DQT_GUI_LIB -DQT_CORE_LIB -DQT_PLUGIN -DQT_SHARED -D_HAVE_EXECINFO_H_ -DQT_DEBUG -fPIC -g -I/usr/include/QtOpenGL -I/usr/include/QtGui -I/usr/include/QtCore -I/usr/include/eigen2 -I/git/xtalopt-public/build -I/usr/include/openbabel-2.0 -I/git/xtalopt-public/src   -o CMakeFiles/globalsearch.dir/queuemanager.cpp.o -c /git/xtalopt-public/src/globalsearch/queuemanager.cpp
Linking CXX static library libglobalsearch.a
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -P CMakeFiles/globalsearch.dir/cmake_clean_target.cmake
cd /git/xtalopt-public/build/src/globalsearch && /usr/bin/cmake -E cmake_link_script CMakeFiles/globalsearch.dir/link.txt --verbose=1
/usr/bin/ar cr libglobalsearch.a  CMakeFiles/globalsearch.dir/optbase.cpp.o CMakeFiles/globalsearch.dir/queuemanager.cpp.o CMakeFiles/globalsearch.dir/structure.cpp.o CMakeFiles/globalsearch.dir/tracker.cpp.o CMakeFiles/globalsearch.dir/optimizer.cpp.o CMakeFiles/globalsearch.dir/bt.cpp.o CMakeFiles/globalsearch.dir/sshconnection.cpp.o CMakeFiles/globalsearch.dir/sshmanager.cpp.o CMakeFiles/globalsearch.dir/random.cpp.o CMakeFiles/globalsearch.dir/ui/abstractdialog.cpp.o CMakeFiles/globalsearch.dir/ui/abstracttab.cpp.o CMakeFiles/globalsearch.dir/moc_optbase.cxx.o CMakeFiles/globalsearch.dir/moc_queuemanager.cxx.o CMakeFiles/globalsearch.dir/moc_structure.cxx.o CMakeFiles/globalsearch.dir/moc_tracker.cxx.o CMakeFiles/globalsearch.dir/moc_optimizer.cxx.o CMakeFiles/globalsearch.dir/moc_bt.cxx.o CMakeFiles/globalsearch.dir/moc_sshconnection.cxx.o CMakeFiles/globalsearch.dir/moc_sshmanager.cxx.o CMakeFiles/globalsearch.dir/moc_random.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstractdialog.cxx.o CMakeFiles/globalsearch.dir/ui/moc_abstracttab.cxx.o
/usr/bin/ranlib libglobalsearch.a
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  1 2 3 4 5 6 7 8 9 10 11 12 13 14
[ 55%] Built target globalsearch
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/depend
make[3]: Entering directory `/git/xtalopt-public/build'
cd /git/xtalopt-public/build && /usr/bin/cmake -E cmake_depends "Unix Makefiles" /git/xtalopt-public /git/xtalopt-public/src/xtalopt /git/xtalopt-public/build /git/xtalopt-public/build/src/xtalopt /git/xtalopt-public/build/src/xtalopt/CMakeFiles/xtalopt.dir/DependInfo.cmake --color=
make[3]: Leaving directory `/git/xtalopt-public/build'
make -f src/xtalopt/CMakeFiles/xtalopt.dir/build.make src/xtalopt/CMakeFiles/xtalopt.dir/build
make[3]: Entering directory `/git/xtalopt-public/build'
Linking CXX shared library xtalopt.so
cd /git/xtalopt-public/build/src/xtalopt && /usr/bin/cmake -E cmake_link_script CMakeFiles/xtalopt.dir/link.txt --verbose=1
/usr/bin/c++  -fPIC  -fPIC -g  -shared -Wl,-soname,xtalopt.so -o xtalopt.so CMakeFiles/xtalopt.dir/extension.cpp.o CMakeFiles/xtalopt.dir/xtalopt.cpp.o CMakeFiles/xtalopt.dir/genetic.cpp.o CMakeFiles/xtalopt.dir/structures/xtal.cpp.o CMakeFiles/xtalopt.dir/optimizers/xtaloptoptimizer.cpp.o CMakeFiles/xtalopt.dir/optimizers/vasp.cpp.o CMakeFiles/xtalopt.dir/optimizers/gulp.cpp.o CMakeFiles/xtalopt.dir/optimizers/pwscf.cpp.o CMakeFiles/xtalopt.dir/optimizers/castep.cpp.o CMakeFiles/xtalopt.dir/testing/xtalopttest.cpp.o CMakeFiles/xtalopt.dir/ui/dialog.cpp.o CMakeFiles/xtalopt.dir/ui/tab_init.cpp.o CMakeFiles/xtalopt.dir/ui/tab_edit.cpp.o CMakeFiles/xtalopt.dir/ui/tab_opt.cpp.o CMakeFiles/xtalopt.dir/ui/tab_sys.cpp.o CMakeFiles/xtalopt.dir/ui/tab_progress.cpp.o CMakeFiles/xtalopt.dir/ui/tab_plot.cpp.o CMakeFiles/xtalopt.dir/ui/tab_log.cpp.o CMakeFiles/xtalopt.dir/moc_extension.cxx.o CMakeFiles/xtalopt.dir/moc_xtalopt.cxx.o CMakeFiles/xtalopt.dir/moc_genetic.cxx.o CMakeFiles/xtalopt.dir/structures/moc_xtal.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_xtaloptoptimizer.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_vasp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_gulp.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_pwscf.cxx.o CMakeFiles/xtalopt.dir/optimizers/moc_castep.cxx.o CMakeFiles/xtalopt.dir/testing/moc_xtalopttest.cxx.o CMakeFiles/xtalopt.dir/ui/moc_dialog.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_init.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_edit.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_opt.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_sys.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_progress.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_plot.cxx.o CMakeFiles/xtalopt.dir/ui/moc_tab_log.cxx.o -lavogadro ../globalsearch/libglobalsearch.a ../spglib/libspglib.a -lQtOpenGL -lGLU -lGL -lSM -lICE -lX11 -lXext -lopenbabel -lQtGui -lQtCore ../libssh/libssh_static.a -lnsl -lresolv -lrt -lz -lssl -lcrypto
make[3]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_report /git/xtalopt-public/build/CMakeFiles  45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
[100%] Built target xtalopt
make[2]: Leaving directory `/git/xtalopt-public/build'
/usr/bin/cmake -E cmake_progress_start /git/xtalopt-public/build/CMakeFiles 0
make[1]: Leaving directory `/git/xtalopt-public/build'

Body:
I finally managed to figure this out! Here's how:

In gdb, I printed all the shared libraries in memory with info shared. I copied this to a text file shared.txt and extracted the library names with:

cat shared.txt | grep -v \*|grep -v quit---|grep -v Syms\ Read|grep -v \(gdb\)|awk '{print $4}'>libs

From there, I checked the symbols in each library with:

for i in `cat libs|xargs`;do nm --demangle $i|grep checkPopulation; if [ $? -eq 0 ]; then echo \($i\); fi;done

Which prints all symbols containing "checkPopulation" followed by the name of the library that contains each. My output:

000adb18 T GlobalSearch::QueueManager::checkPopulation()
000adb8a T GlobalSearch::QueueManager::checkPopulation_()
(/usr/lib/avogadro/1_1/contrib/randomdock.so)
000db682 T GlobalSearch::QueueManager::checkPopulation()
(/usr/lib/avogadro/1_1/contrib/xtalopt.so)

So this "phantom" checkPopulation_ symbol is coming from randomdock.so, which was built a long time ago against an older version of the static libglobalsearch.a, which contains the now removed GlobalSearch::QueueManager::checkPopulation_(). Removing randomdock.so causes everything to behave as it should.

Thanks for all the suggestions -- I certainly learned a few new gdb tricks while tracking this down. There's also a lesson here about breaking API, too ;-)


来源: stackexchange

问:
Declare columns of a table with a varchar variable
```<code>DECLARE @newcolumns VARCHAR(2000);

WITH cte AS
(
    SELECT
        REPLACE(REPLACE(DateOut, ']', ''), '[', '') DateOut
    FROM
        #Columns
)
SELECT
    @newcolumns = COALESCE(@newcolumns + ',' + '[' + DateOut + '] REAL',
    '[' + DateOut + '] REAL')
FROM
    cte

CREATE TABLE #newtable
(
     Area NVARCHAR(50),
     EqpType NVARCHAR(50),
     @newcolumns
)
</code>```

I have this code the variable @newcolumns returns me something like

```<code>[dec-1] real, [dec-2] real, [dec-3] real
</code>```

I tried use another variable like this:

```<code>DECLARE @sql VARCHAR(4000)
SET @sql = '

CREATE TABLE #newtable
(
     Area NVARCHAR(50),
     EqpType NVARCHAR(50), ' + @newcolumns + ')
INSERT INTO #newtable
SELECT Area,EqpType,'+@listMAX+'
FROM #littletable
PIVOT (MAX(Metric) FOR DateOut IN ('+@list+')) Z
GROUP BY Area,EqpType
ORDER BY AREA' EXEC (@sql)
</code>```

And that works really good, but is there some way to do the same without using another variable? Like @sql?

答: No there is not.   To use variables for column names, you have to use dynamic sql, which is what you are doing with the @sql variable.

ContentLicense: CC BY-SA 3.0

Body:
DECLARE @newcolumns VARCHAR(2000);

WITH cte AS
(
    SELECT
        REPLACE(REPLACE(DateOut, ']', ''), '[', '') DateOut
    FROM
        #Columns
)
SELECT
    @newcolumns = COALESCE(@newcolumns + ',' + '[' + DateOut + '] REAL',
    '[' + DateOut + '] REAL')
FROM
    cte

CREATE TABLE #newtable
(
     Area NVARCHAR(50),
     EqpType NVARCHAR(50),
     @newcolumns
)

I have this code the variable @newcolumns returns me something like

[dec-1] real, [dec-2] real, [dec-3] real

I tried use another variable like this:

DECLARE @sql VARCHAR(4000)
SET @sql = '

CREATE TABLE #newtable
(
     Area NVARCHAR(50),
     EqpType NVARCHAR(50), ' + @newcolumns + ')
INSERT INTO #newtable
SELECT Area,EqpType,'+@listMAX+'
FROM #littletable
PIVOT (MAX(Metric) FOR DateOut IN ('+@list+')) Z
GROUP BY Area,EqpType
ORDER BY AREA' EXEC (@sql)

And that works really good, but is there some way to do the same without using another variable? Like @sql?


问:
moving to httpClient from http throwing error in angular 5
I am trying to create new wrapper for restservice, i am trying to move angular 4 to 5 and upgrading the same service. i get error like below. If i change Observable<Response> to Observable<HttpResponse> also i get error:

Argument of type 'HttpHeaders' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.

  Property 'headers' is private in type 'HttpHeaders' but not in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?:

below is code.

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpRequest, HttpHeaders, HttpResponse } from '@angular/common/http';

@Injectable()
export class httpService {
    private requestHeaders: HttpHeaders;

    constructor(private _http: HttpClient) {
        this.requestHeaders = new HttpHeaders();
        this.requestHeaders.append('Content-Type', 'application/json');
        this.requestHeaders.append('Accept', 'application/json');
    }

    post(url: string, requestData?: any): Observable<Response> {
        return this._http.post(url, requestData, this.requestHeaders);
    }
}
</code>```

Above is fixed by using {headers: this.requestHeaders}

but while line  return this._http.post(url, requestData, this.requestHeaders); throws error like

```<code>Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<Response>'.
Type 'ArrayBuffer' is not assignable to type 'Response'.
Property 'body' is missing in type 'ArrayBuffer'.
</code>```

答:
The implementation of append() is:

```<code>append(name: string, value: string|string[]): HttpHeaders {
   return this.clone({name, value, op: 'a'});
 }
</code>```

It returns a clone of hte headers object. You need to store/assign the returned result to your variable this.reqequestHeaders otherwise it would not be saved.

Alternatively, the constructor os HttpHeaders is:

```<code>constructor(headers?: string|{[name: string]: string | string[]})
</code>```

A cleaner way to do is:

```<code>const headerJson = {
  'Content-Type': 'application/json',
  'Accept' : 'application/json'
}

this.header = new HttpHeaders(headerJson);
</code>```

Body:
I am trying to create new wrapper for restservice, i am trying to move angular 4 to 5 and upgrading the same service. i get error like below. If i change Observable<Response> to Observable<HttpResponse> also i get error:

Argument of type 'HttpHeaders' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'.

  Property 'headers' is private in type 'HttpHeaders' but not in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?:

below is code.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpRequest, HttpHeaders, HttpResponse } from '@angular/common/http';

@Injectable()
export class httpService {
    private requestHeaders: HttpHeaders;

    constructor(private _http: HttpClient) {
        this.requestHeaders = new HttpHeaders();
        this.requestHeaders.append('Content-Type', 'application/json');
        this.requestHeaders.append('Accept', 'application/json');
    }

    post(url: string, requestData?: any): Observable<Response> {
        return this._http.post(url, requestData, this.requestHeaders);
    }
}

Above is fixed by using {headers: this.requestHeaders}

but while line  return this._http.post(url, requestData, this.requestHeaders); throws error like

Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<Response>'.
Type 'ArrayBuffer' is not assignable to type 'Response'.
Property 'body' is missing in type 'ArrayBuffer'.

Body:
The implementation of append() is:

append(name: string, value: string|string[]): HttpHeaders {
   return this.clone({name, value, op: 'a'});
 }

It returns a clone of hte headers object. You need to store/assign the returned result to your variable this.reqequestHeaders otherwise it would not be saved.

Alternatively, the constructor os HttpHeaders is:

constructor(headers?: string|{[name: string]: string | string[]})

A cleaner way to do is:

const headerJson = {
  'Content-Type': 'application/json',
  'Accept' : 'application/json'
}

this.header = new HttpHeaders(headerJson);


问:
How to run Celery Periodic task at every end of the month
Basically, I have a task to generate Invoice. So I have created a function generate_invoice() in my tasks.py file.

Now, I am using @periodic_task to call the function. But I need my task to run only on the last date of the month around 11:55 pm - 11:57 pm.

I am getting the last date of month using this function:

```<code>def get_last_date():
        today = timezone.now()
        year = today.year
        month = today.month
        last_date = calendar.monthrange(year, month)[1]
        return str(last_date)
</code>```

My code for task looks like this:

```<code>@periodic_task(run_every=(crontab(day_of_month=get_last_date())), name="invoice_simulation", ignore_result=True)
def invoice_simulation():
    generate_invoice()
</code>```

But this is not working!

Or is there any better way to implement this feature then please suggest.

答:
Update your get_last_date() function as follows.</p>

```<code>def get_last_date():
    today = datetime.date.today()
    year = today.year
    month = today.month
    last_date = calendar.monthrange(year, month)
    return str(last_date)
</code>```

Body:
Basically, I have a task to generate Invoice. So I have created a function generate_invoice() in my tasks.py file.

Now, I am using @periodic_task to call the function. But I need my task to run only on the last date of the month around 11:55 pm - 11:57 pm.

I am getting the last date of month using this function:

def get_last_date():
        today = timezone.now()
        year = today.year
        month = today.month
        last_date = calendar.monthrange(year, month)[1]
        return str(last_date)

My code for task looks like this:

@periodic_task(run_every=(crontab(day_of_month=get_last_date())), name="invoice_simulation", ignore_result=True)
def invoice_simulation():
    generate_invoice()

But this is not working!

Or is there any better way to implement this feature then please suggest.

Body:
Update your get_last_date() function as follows.

def get_last_date():
    today = datetime.date.today()
    year = today.year
    month = today.month
    last_date = calendar.monthrange(year, month)
    return str(last_date)


问:
Add a filter on a DbSet that is included on a related DbSet?
The following are some stuffs behind the scene.

```<code>public class User : BaseTransactionModel
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transaction
{

    public int TransactionId { get; set; }
    public string TransactionName { get; set; }
    public int TransactionHistoryId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
}

public class TransactionHistory
{
    public int TransactionHistoryId { get; set; }
    public DateTime CreatedDateTime { get; set; }
    public Guid UserId { get; set; }
    public int TransactionId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class BaseTransactionModel
{

    public int TransactionHistoryId { get; set; }
    public int TransactionId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
    public virtual Transaction Transaction { get; set; }
}
</code>```

With the above entities, I am trying to get all the Transactions from a User on a specified Date.

So I tried including both User and TransactionHistory on the Transaction DbSet:

```<code>Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    ...
</code>```

I wanted to add a where clause that filter the transaction from the date in transaction history entities:

```<code>Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)
</code>```

but could not able to do so. Since TransactionHistory is also a list of entity (or whatever it is called).

What could be the possible solution to get what I am trying to achieve ?

PS: I am new to EF and the title could be misleading. If so, feel free to update it.

答:
What you are looking is to be able to filter included entities.

There is two way to filter include Entity:

Using a projection (See @majita answer)

Using a third party library

Disclaimer: I'm the owner of the project Entity Framework Plus

The EF+ Query IncludeFilter allow easily filter included entities.

```<code>Context.Transaction
    .IncludeFilter(t => t.User)
    .IncludeFilter(t => t.TransactionHistory
        .Where(x => x.TransactionHistory.CreatedDateTime <= StartDateFilter && x.TransactionHistory.CreatedDateTime >= EndDateFilter))
</code>```

Under the hood, the library does exactly a projection.

One limitation is all Include but now be called with IncludeFilter even if no filter is specified such as the User.

Wiki: EF+ Query Include Filter

Body:
The following are some stuffs behind the scene.

public class User : BaseTransactionModel
{
    public Guid UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Transaction
{

    public int TransactionId { get; set; }
    public string TransactionName { get; set; }
    public int TransactionHistoryId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
}

public class TransactionHistory
{
    public int TransactionHistoryId { get; set; }
    public DateTime CreatedDateTime { get; set; }
    public Guid UserId { get; set; }
    public int TransactionId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
}

public class BaseTransactionModel
{

    public int TransactionHistoryId { get; set; }
    public int TransactionId { get; set; }

    public virtual TransactionHistory TransactionHistory { get; set; }
    public virtual Transaction Transaction { get; set; }
}

With the above entities, I am trying to get all the Transactions from a User on a specified Date.

So I tried including both User and TransactionHistory on the Transaction DbSet:

Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    ...

I wanted to add a where clause that filter the transaction from the date in transaction history entities:

Context.Transaction
    .Include(t => t.User)
    .Include(t => t.TransactionHistory)
    .Where(t => t.TransactionHistory.CreatedDateTime <= StartDateFilter && t.TransactionHistory.CreatedDateTime >= EndDateFilter)

but could not able to do so. Since TransactionHistory is also a list of entity (or whatever it is called).

What could be the possible solution to get what I am trying to achieve ?

PS: I am new to EF and the title could be misleading. If so, feel free to update it.

Body:
What you are looking is to be able to filter included entities.

There is two way to filter include Entity:

Using a projection (See @majita answer)

Using a third party library

Disclaimer: I'm the owner of the project Entity Framework Plus

The EF+ Query IncludeFilter allow easily filter included entities.

Context.Transaction
    .IncludeFilter(t => t.User)
    .IncludeFilter(t => t.TransactionHistory
        .Where(x => x.TransactionHistory.CreatedDateTime <= StartDateFilter && x.TransactionHistory.CreatedDateTime >= EndDateFilter))

Under the hood, the library does exactly a projection.

One limitation is all Include but now be called with IncludeFilter even if no filter is specified such as the User.

Wiki: EF+ Query Include Filter


问:
How to exclude auto-configuration from Spring Boot WebMvcTest
I am trying to implement a Spring Boot Mock MVC unit test and would like to exclude the spring-cloud-consul auto configuration to avoid requiring connectivity to a remote service.

It looks like I should be able to achieve this with the below:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class, excludeAutoConfiguration = ConsulAutoConfiguration.class)
@AutoConfigureMockMvc(addFilters = false, printOnlyOnFailure = false)
</code>```

However this still appears to be trying to connect to remote Consul as I am unable to run this unit test when offline.

```<code>Caused by: org.apache.http.conn.ConnectTimeoutException: Connect to consul.****:8500 [consul.****/**.**.**.**] failed: connect timed out
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:150)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
</code>```

If I add the -Ddebug to the unit test run configuration I am not seeing this listed in the exclusions:

```<code>Positive matches:
-----------------

ConsulAutoConfiguration matched:
      - AllNestedConditions 2 matched 0 did not; NestedCondition on ConditionalOnConsulEnabled.OnConsulEnabledCondition.FoundClass @ConditionalOnClass found required class 'com.ecwid.consul.v1.ConsulClient'; @ConditionalOnMissingClass did not find unwanted class; NestedCondition on ConditionalOnConsulEnabled.OnConsulEnabledCondition.FoundProperty @ConditionalOnProperty (spring.cloud.consul.enabled) matched (ConditionalOnConsulEnabled.OnConsulEnabledCondition)

Exclusions:
-----------

    None
</code>```

I am wondering if this is because this config is loaded at bootstrap time?

Any help would be greatly appreciated, thanks in advance.

答:
Managed to find a work around by adding the following annotation to the test. </p>

```<code>@TestPropertySource(properties="spring.cloud.consul.enabled=false")
</code>```

Body:
I am trying to implement a Spring Boot Mock MVC unit test and would like to exclude the spring-cloud-consul auto configuration to avoid requiring connectivity to a remote service.

It looks like I should be able to achieve this with the below:

@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class, excludeAutoConfiguration = ConsulAutoConfiguration.class)
@AutoConfigureMockMvc(addFilters = false, printOnlyOnFailure = false)

However this still appears to be trying to connect to remote Consul as I am unable to run this unit test when offline.

Caused by: org.apache.http.conn.ConnectTimeoutException: Connect to consul.****:8500 [consul.****/**.**.**.**] failed: connect timed out
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:150)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)

If I add the -Ddebug to the unit test run configuration I am not seeing this listed in the exclusions:

Positive matches:
-----------------

ConsulAutoConfiguration matched:
      - AllNestedConditions 2 matched 0 did not; NestedCondition on ConditionalOnConsulEnabled.OnConsulEnabledCondition.FoundClass @ConditionalOnClass found required class 'com.ecwid.consul.v1.ConsulClient'; @ConditionalOnMissingClass did not find unwanted class; NestedCondition on ConditionalOnConsulEnabled.OnConsulEnabledCondition.FoundProperty @ConditionalOnProperty (spring.cloud.consul.enabled) matched (ConditionalOnConsulEnabled.OnConsulEnabledCondition)

Exclusions:
-----------

    None

I am wondering if this is because this config is loaded at bootstrap time?

Any help would be greatly appreciated, thanks in advance.

Body:
Managed to find a work around by adding the following annotation to the test.

@TestPropertySource(properties="spring.cloud.consul.enabled=false")


问:
PRNG MTRand mt.seed() not working as intended (?)
In a simulation project where I need different PRNG with common random numbers (reproducability) I am using the Mersenne Twister implementation by Jasper Bedaux (http://www.bedaux.net/mtrand/). Now, the following loop should, in my understanding, produce a unique random number associated to the integer (i.e. the different instances should yield the same random numbers if initialised with the same seed):

```<code>#include <iostream>
#include "mtrand.cpp"

int main()
{
  MTRand tester_sh;
  MTRand tester_se;
  std::cout << std::fixed;
  std::cout << "This is a simple test program.\n";
  for (int sh = 1; sh < 3; sh++) {
    for (int se = 1; se < 3; se++) {
      tester_sh.seed( sh );
      tester_se.seed( se );
      std::cout << "\n" << sh << "\t" << tester_sh() << "\t" << se << "\t" << tester_se() ;
    }
  }
  return 0;
}
</code>```

The output I do get, however is:

Neither are the random numbers the same, nor does the "resetting" work for the individual generator. [edit: there is a pattern, of course, but I do not understand it / it is not as it should be]

As I am not a programmer, I am more than puzzled and do not know what I should do.

If important, I am compiling the model with cygwin64\bin\x86_64-w64-mingw32-g++.exe and the options -g  -Wall  -lm -std=gnu++14 -o %Name%.exe %Name%%Ext%, using a current version of cygwin on windows 7, 64bit.

Any help is welcome!

答:
It is because of some weird reason, MTRand's state is static, so the state is shared between MTRand instances. A really bad decision.

Perhaps you can fix this with making the state non-static. Or just use a better implementation of MT. (btw, C++11 has std::mersenne_twister_engine)

Body:
In a simulation project where I need different PRNG with common random numbers (reproducability) I am using the Mersenne Twister implementation by Jasper Bedaux (http://www.bedaux.net/mtrand/). Now, the following loop should, in my understanding, produce a unique random number associated to the integer (i.e. the different instances should yield the same random numbers if initialised with the same seed):

#include <iostream>
#include "mtrand.cpp"

int main()
{
  MTRand tester_sh;
  MTRand tester_se;
  std::cout << std::fixed;
  std::cout << "This is a simple test program.\n";
  for (int sh = 1; sh < 3; sh++) {
    for (int se = 1; se < 3; se++) {
      tester_sh.seed( sh );
      tester_se.seed( se );
      std::cout << "\n" << sh << "\t" << tester_sh() << "\t" << se << "\t" << tester_se() ;
    }
  }
  return 0;
}

The output I do get, however is:

Neither are the random numbers the same, nor does the "resetting" work for the individual generator. [edit: there is a pattern, of course, but I do not understand it / it is not as it should be]

As I am not a programmer, I am more than puzzled and do not know what I should do.

If important, I am compiling the model with cygwin64\bin\x86_64-w64-mingw32-g++.exe and the options -g  -Wall  -lm -std=gnu++14 -o %Name%.exe %Name%%Ext%, using a current version of cygwin on windows 7, 64bit.

Any help is welcome!


问:
How i can convert string to array in jquery
hi i have my data in a string
like this

```<code>Array
(
    [0] => Array
        (
            [pollId] => 2
            [poll] => new
            [cId] => 7
            [communityId] => 7
            [ansId] => Array
                (
                    [0] => 6
                    [1] => 7
                )

            [answer] => Array
                (
                    [0] => new1
                    [1] => new2
                )

            [vote] => Array
                (
                    [0] => 37
                    [1] => 36
                )

            [count] => 2
        )

)
</code>```

i want to convert it to array.

答:
<s>If you really have a string containing the text as quoted, you're going to have to either find or write a parser for it.

It's not a million miles off JSON, and so you might get a leg up on your implementation (if you have to write one) from the two non-eval implementations of JSON parsers found on Crockford's github page. There's json_parse.js, which is a recursive-descent parser; and json_parse_state.js which is a state machine. In both cases, they parse JSON, not your example format, but my point is that as your example format isn't a million miles away from JSON, you can probably use them as a starting point.</s>

Update: (I'd added a comment about this, but it's better as part of the answer.) I see from the comment stream on your question that you don't have to use this format, but instead can use JSON instead. In that case, you're in good shape — jQuery has JSON parsing built in, in its parseJSON function. That will accept a string containing JSON-encoded data and return a JavaScript object graph (which may or may not be an array, depending on what the JSON defines). If you retrieve the JSON via Ajax, jQuery will even parse it for you automatically and give you the resulting object graph as an argument to your success function, see $.ajax and $.getJSON. Here's a live example I did for another question just earlier today. That loads the JSON found at the URL you'll see in the code, has jQuery automatically parse it, and accesses one of the properties of the resulting JavaScript object graph.

ContentLicense: CC BY-SA 2.5

Body:
hi i have my data in a string
like this

Array
(
    [0] => Array
        (
            [pollId] => 2
            [poll] => new
            [cId] => 7
            [communityId] => 7
            [ansId] => Array
                (
                    [0] => 6
                    [1] => 7
                )

            [answer] => Array
                (
                    [0] => new1
                    [1] => new2
                )

            [vote] => Array
                (
                    [0] => 37
                    [1] => 36
                )

            [count] => 2
        )

)

i want to convert it to array.


问:
How to clear retrieve log in plugin registration tool
I'm using plugin registration tool.

In the section:  Debug -> setup tab -> Retrieve log -> 'select profile from CRM' popup, I need to clear all logs from 'select profile from CRM' popup.

How to do that?

答:
This will be stored in CRM entity - Plugin Profiles. Delete the unwanted old records.

You can do Advanced Find for that entity or navigate to Settings - Extensions.


问:
Trying to count words in different lists
I'm trying for sentiment analysis to score many comments in a data frame. I have a negative word corpora, and a positive one. I want to add 1 for every positive word, and remove 1 for every negative word in the comment. My code:

```<code>     text['counts'] = 0
     for i in text.Reviews:
         if i in p:
             text['counts'] += 1
         elif i in n:
             text['counts'] +=-1
</code>```

I want the new column, text.counts to give the comment's score for every comment, but so far I've only managed to get the total count appear on every row (as if my dataframe was one big comment.)

Thank you!

答:
Is this what you are looking for?</p>

```<code>In [28]: text  = pd.DataFrame( ['good and not bad', 'it is a terrible bad product', 'excellent product'], columns = ['reviews'])

In [29]: text
Out[29]:
                        reviews
0              good and not bad
1  it is a terrible bad product
2             excellent product

In [30]: n = set('bad worse terrible worse bad baddest'.split())
In [31]: p = set('good better excellent good best bestest good'.split())

In [32]: text['count'] = text['reviews'].apply(lambda review: sum(0 + ((word in p) and 1) + ((word in n) and -1) for word in review.split()))

In [33]: text
Out[33]:
                        reviews  count
0              good and not bad      0
1  it is a terrible bad product     -2
2             excellent product      1
</code>```

Body:
I'm trying for sentiment analysis to score many comments in a data frame. I have a negative word corpora, and a positive one. I want to add 1 for every positive word, and remove 1 for every negative word in the comment. My code:

     text['counts'] = 0
     for i in text.Reviews:
         if i in p:
             text['counts'] += 1
         elif i in n:
             text['counts'] +=-1

I want the new column, text.counts to give the comment's score for every comment, but so far I've only managed to get the total count appear on every row (as if my dataframe was one big comment.)

Thank you!

Body:
Is this what you are looking for?

In [28]: text  = pd.DataFrame( ['good and not bad', 'it is a terrible bad product', 'excellent product'], columns = ['reviews'])

In [29]: text
Out[29]:
                        reviews
0              good and not bad
1  it is a terrible bad product
2             excellent product

In [30]: n = set('bad worse terrible worse bad baddest'.split())
In [31]: p = set('good better excellent good best bestest good'.split())

In [32]: text['count'] = text['reviews'].apply(lambda review: sum(0 + ((word in p) and 1) + ((word in n) and -1) for word in review.split()))

In [33]: text
Out[33]:
                        reviews  count
0              good and not bad      0
1  it is a terrible bad product     -2
2             excellent product      1


问:
Binding a view to a changing controller property
I'm working in Kotlin with the TornadoFX library. Imagine you have a toolbar which shows the tool that are useful for the current view you have. So we have a MainController which has a subController property which is the controller of some view next to the tool bar. So if our subController changes, the view should update. Also, if any property (e.g. selectedTool, tools) of the subController changes, the toolbar should update accordingly. Momentarily, the toolbar is not updated.

```<code>class ToolBar : View("Tool bar") {
    private val controller: MainController by inject()
    override val root = vbox {
        tilepane {
            for (tool in controller.subController.tools) {
                button(tool.name, group).action {
                    controller.subController.changeTool(tool) // changes selected tool
                }
            }
        }
        this += controller.subController.selectedTool.options
    }
}
</code>```

Extra info: subController.tools is an ArrayList and subController.selectedTool is a Tool.

Now my question is, what's the recommended way to do this in TornadoFX?

答:
You have several options. A Parent supports a function called bindChildren which accepts an observable list of items and a function to turn each of these items into a Node. You can use this to create your buttons in the toolbar:

```<code>tilepane {
    bindChildren(controller.subController.tools) { tool ->
        Button(tool.name) ...
    }
}
</code>```

You can also do this manually if you need more control:

tilepane {
    controller.subController.tools.onChange {
        children.clear()
        // create new buttons here, like in your example
    }
}

However, instead of injecting controller to access subController to get to the tools, you should have a ToolsModel which is injected into the current scope. The tools model could have a list of tools and the selected tools and can be injected into all views and controllers which needs it. You say that selectedTool is a Tool, but you're not showing what a Tool is, but judging from your code it looks like Tool.options is a Node subclass (?).

You can add/remove the tool.options element using the same technique, or even wrap it in a stackpane or other layoutcontainer to be able to identify the tool to remove (or simply remove all children of the stackpane) on change using the same technique.

Body:
I'm working in Kotlin with the TornadoFX library. Imagine you have a toolbar which shows the tool that are useful for the current view you have. So we have a MainController which has a subController property which is the controller of some view next to the tool bar. So if our subController changes, the view should update. Also, if any property (e.g. selectedTool, tools) of the subController changes, the toolbar should update accordingly. Momentarily, the toolbar is not updated.

class ToolBar : View("Tool bar") {
    private val controller: MainController by inject()
    override val root = vbox {
        tilepane {
            for (tool in controller.subController.tools) {
                button(tool.name, group).action {
                    controller.subController.changeTool(tool) // changes selected tool
                }
            }
        }
        this += controller.subController.selectedTool.options
    }
}

Extra info: subController.tools is an ArrayList and subController.selectedTool is a Tool.

Now my question is, what's the recommended way to do this in TornadoFX?

Body:
You have several options. A Parent supports a function called bindChildren which accepts an observable list of items and a function to turn each of these items into a Node. You can use this to create your buttons in the toolbar:

tilepane {
    bindChildren(controller.subController.tools) { tool ->
        Button(tool.name) ...
    }
}

You can also do this manually if you need more control:

tilepane {
    controller.subController.tools.onChange {
        children.clear()
        // create new buttons here, like in your example
    }
}

However, instead of injecting controller to access subController to get to the tools, you should have a ToolsModel which is injected into the current scope. The tools model could have a list of tools and the selected tools and can be injected into all views and controllers which needs it. You say that selectedTool is a Tool, but you're not showing what a Tool is, but judging from your code it looks like Tool.options is a Node subclass (?).

You can add/remove the tool.options element using the same technique, or even wrap it in a stackpane or other layoutcontainer to be able to identify the tool to remove (or simply remove all children of the stackpane) on change using the same technique.


问:
Is it safe practice to dynamically render javascript using Twig?
I'm using Silex with Twig. My Twig template processes data passed in through the Silex side and renders Javascript based off of the data.

Is this good practice? I couldn't find anything about it online.

I thought about just passing the data from the Silex side straight to the front-end and processing it there, but I already started the implementation that renders Javascript through a Twig Template.

Thanks for the advice guys!

答: Twig is just a view layer. No matter if you render it directly from your programming language or through templating engine - it always gonna be available in the user interface (probably only for logged in users, depending on scenarios). I does not make much difference as long as you follow data hiding principle - expose only necessary data to the client.</p>


问:
Copy Cell's Formula result as Value into same Cell
I have this code I have written to find values over 0 in a particular column:

```<code>Private Sub CommandButton1_Click()

    a = Worksheets("Sheet1").Cells(Rows.Count, 3).End(xlUp).Row

    For i = 4 To a
        If Worksheets("sheet1").Cells(i, 3).Value > 0 Then
            Worksheets("sheet1").Cells(i, 3).Copy
            Worksheets("sheet1").Cells(1, 3).PasteSpecial xlPasteValues
        End If
    Next

    Application.CutCopyMode = False

End Sub
</code>```

My problem is in the copy and paste value.  I need to just copy the cell and paste value in that same cell.  for example, if the macro reads in cell c5 that the total is greater then 0, then it copies cell c5 and paste value in c5.

How do I fix the paste value line to paste the value in the same cell it copied?

答:
Use a with block to limit the amount of repetitive typing</p>

```<code>Private Sub CommandButton1_Click()
With Worksheets("Sheet1")
    a = .Cells(Rows.Count, 3).End(xlUp).Row
    For i = 4 To a
        With .Cells(i, 3)
            If .Value > 0 Then .Value = .Value
        End With
    Next
End With
End Sub
</code>```

Body:
I have this code I have written to find values over 0 in a particular column:

Private Sub CommandButton1_Click()

    a = Worksheets("Sheet1").Cells(Rows.Count, 3).End(xlUp).Row

    For i = 4 To a
        If Worksheets("sheet1").Cells(i, 3).Value > 0 Then
            Worksheets("sheet1").Cells(i, 3).Copy
            Worksheets("sheet1").Cells(1, 3).PasteSpecial xlPasteValues
        End If
    Next

    Application.CutCopyMode = False

End Sub

My problem is in the copy and paste value.  I need to just copy the cell and paste value in that same cell.  for example, if the macro reads in cell c5 that the total is greater then 0, then it copies cell c5 and paste value in c5.

How do I fix the paste value line to paste the value in the same cell it copied?

Body:
Use a with block to limit the amount of repetitive typing

Private Sub CommandButton1_Click()
With Worksheets("Sheet1")
    a = .Cells(Rows.Count, 3).End(xlUp).Row
    For i = 4 To a
        With .Cells(i, 3)
            If .Value > 0 Then .Value = .Value
        End With
    Next
End With
End Sub


问:
Converting a localized date of the form 12-okt-2007
I have imported a time series with dates of the following format:

```<code> test = c("11-Feb-01","12-Feb-01","01-Mai-08")
</code>```

This yields:

```<code>> as.Date(test, "%d-%b-%y")
[1] NA           NA           "2008-05-01"
</code>```

Since, May was translated it obviously takes locale into account.

According to the docs, the %b should be the abbreviated month name, but I guess there's might be some issue there.

How would I go about fixing this?

I'm running R under Linux t2.6.27-9-generic #1 SMP

Update: Digging a bit deeper i find that the issue is in the LC_TIME definition, where the appropriate abbrivations are of the form:

```<code>"jan.","feb.","mars", "apr", "mai", "juni", "juli", "aug.","sep.","okt.","nov.", "des."
</code>```

while my data contains:

```<code>"Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"
</code>```

I guess I could consider pre-processing the data, but a smooth way of doing this in R would be most welcome.

This works sort-of, but not so elegant:

```<code>> as.Date(gsub("Feb","feb.",test), "%d-%b-%y")
[1] "2001-02-11" "2008-02-12" "2008-05-01"
</code>```

Thanks!

答:
The closest thing I've found to a solution is to make multiple iterations over the data to replace the names of the months with something that can be parsed.

I'm not sure if this is the best solution.

```<code>setwd("/home/tovare/Data")

v <- read.csv2("valuta_dag.sdv",
  na.strings = c("NA","ND"),
  header = TRUE, sep=";", skip=2)

v$Dato <- gsub("Jan","01",v$Dato)
v$Dato <- gsub("Feb","02",v$Dato)
v$Dato <- gsub("Mar","03",v$Dato)
v$Dato <- gsub("Apr","04",v$Dato)
v$Dato <- gsub("Mai","05",v$Dato)
v$Dato <- gsub("Jun","06",v$Dato)
v$Dato <- gsub("Jul","07",v$Dato)
v$Dato <- gsub("Aug","08",v$Dato)
v$Dato <- gsub("Sep","09",v$Dato)
v$Dato <- gsub("Okt","10",v$Dato)
v$Dato <- gsub("Nov","11",v$Dato)
v$Dato <- gsub("Des","12",v$Dato)

v$Dato <- as.Date(v$Dato,"%d-%m-%y")
</code>```

OwnerDisplayName: tovare

Body:
I have imported a time series with dates of the following format:

 test = c("11-Feb-01","12-Feb-01","01-Mai-08")

This yields:

> as.Date(test, "%d-%b-%y")
[1] NA           NA           "2008-05-01"

Since, May was translated it obviously takes locale into account.

According to the docs, the %b should be the abbreviated month name, but I guess there's might be some issue there.

How would I go about fixing this?

I'm running R under Linux t2.6.27-9-generic #1 SMP

Update: Digging a bit deeper i find that the issue is in the LC_TIME definition, where the appropriate abbrivations are of the form:

"jan.","feb.","mars", "apr", "mai", "juni", "juli", "aug.","sep.","okt.","nov.", "des."

while my data contains:

"Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"

I guess I could consider pre-processing the data, but a smooth way of doing this in R would be most welcome.

This works sort-of, but not so elegant:

> as.Date(gsub("Feb","feb.",test), "%d-%b-%y")
[1] "2001-02-11" "2008-02-12" "2008-05-01"

Thanks!

LastEditorDisplayName: tovare

Body:
The closest thing I've found to a solution is to make multiple iterations over the data to replace the names of the months with something that can be parsed.

I'm not sure if this is the best solution.

setwd("/home/tovare/Data")

v <- read.csv2("valuta_dag.sdv",
  na.strings = c("NA","ND"),
  header = TRUE, sep=";", skip=2)

v$Dato <- gsub("Jan","01",v$Dato)
v$Dato <- gsub("Feb","02",v$Dato)
v$Dato <- gsub("Mar","03",v$Dato)
v$Dato <- gsub("Apr","04",v$Dato)
v$Dato <- gsub("Mai","05",v$Dato)
v$Dato <- gsub("Jun","06",v$Dato)
v$Dato <- gsub("Jul","07",v$Dato)
v$Dato <- gsub("Aug","08",v$Dato)
v$Dato <- gsub("Sep","09",v$Dato)
v$Dato <- gsub("Okt","10",v$Dato)
v$Dato <- gsub("Nov","11",v$Dato)
v$Dato <- gsub("Des","12",v$Dato)

v$Dato <- as.Date(v$Dato,"%d-%m-%y")


问:
Exporting JAR projects that use a common project
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

```<code>Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain
</code>```

答:
Copy into JAVA_HOME?  That's not the way to do anything.   You should never do that.

If it's a web project, you'll have to copy the JAR into the WEB-INF/lib for each project.

If it's not a web project, you'll have to package that JAR up with the main JAR and add it to the CLASSPATH.  I'll assume that the main is either an executable JAR with a manifest or that you've got a script to execute the main so you can encapsulate the CLASSPATH into it.

Body:
I have 4 different Java Projects created in Eclipse.

One of them contains all my Utilities and Helper methods, that the other 3 projects use.

I don't want to copy that same package 3 times into each project, since I want to be able to just edit it in one place if I should have to. So, I have referenced the myUtilities project from all other 3 projects.

I'll be exporting the 3 main projects and they will be going to different servers to run independently as  "java -jar myproject.jar"

Everytime I do an export, the myUtilities.jar is not getting compiled in the JAR. If I open the JAR, I can see it is not there.  And this is going to be a problem when I move them to the other servers.

Is there a way to add the package into the source for the JAR? Or am I going to have to copy the myUtilities.jar into the JAVA_HOME of each server?

This is my current Manifest file:

Manifest-Version: 1.0
Main-Class: com.elcool.process.alpha.RetrieverMain


问:
No handlers could be found for logger
I am newbie to python. I was trying logging in python and I came across No handlers could be found for logger error while trying to print some warning through logger instance. Below is the code I tried

```<code>import logging
logger=logging.getLogger('logger')
logger.warning('The system may break down')
</code>```

And I get this error No handlers could be found for logger "logger"

What's confusing me is when I first try to print warning using logging and then through logger , it works fine, like

```<code>>>> import logging
>>> logging.warning('This is a WARNING!!!!')
WARNING:root:This is a WARNING!!!!
>>>
>>> logger.warning('WARNING!!!!')
WARNING:logger:WARNING!!!!
</code>```

Can someone throw some light on what's happening in second scenario?

答:
Additional to phd's answer, calling logging.basicConfig() is a convenient function which will get you a default StreamHandler and a Formatter. That is enough if you want to quickly have a logging functionality. You can customize it's behaviour by passing basicConfig some arguments:

Add Useful parameters: output timestamp alongside the message

```<code>logger = logging.basicConfig(level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
</code>```

This should be fine for most of the one off needs. If you need more control about your config, you can add more sophisticated behaviours by defining the logger's attributes your self.

Sophisticated Example: without using the basicConfig function

```<code>import logging
logger = logging.getLogger("mylogger")
streamHandler = logging.StreamHandler()
streamHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)

logger.addHandler(streamHandler)

logger.info("Files copied")
logger.warning("disk quota exceeded")
>> 2017-12-06 11:11:12, 090 - mylogger - INFO Files copied
>> 2017-12-06 11:11:12, 091 - mylogger - WARNING disk quota exceeded
</code>```

The next step in a bigger environment, would be deriving a new logger from the previously created one, to first keep the formatting and as well to maintain a "log hierarchy"

```<code>logger2 = logging.getLogger("mylogger.new")
logger2.info("New Logger info")
>> 2017-12-06 11:11:12, 091 - mylogger.new - New logger info
</code>```

A good reference is the logging cookbook:
https://docs.python.org/2/howto/logging-cookbook.html

Title: No handlers could be found for logger

Body:
I am newbie to python. I was trying logging in python and I came across No handlers could be found for logger error while trying to print some warning through logger instance. Below is the code I tried

import logging
logger=logging.getLogger('logger')
logger.warning('The system may break down')

And I get this error No handlers could be found for logger "logger"

What's confusing me is when I first try to print warning using logging and then through logger , it works fine, like

>>> import logging
>>> logging.warning('This is a WARNING!!!!')
WARNING:root:This is a WARNING!!!!
>>>
>>> logger.warning('WARNING!!!!')
WARNING:logger:WARNING!!!!

Can someone throw some light on what's happening in second scenario?

Body:
Additional to phd's answer, calling logging.basicConfig() is a convenient function which will get you a default StreamHandler and a Formatter. That is enough if you want to quickly have a logging functionality. You can customize it's behaviour by passing basicConfig some arguments:

Add Useful parameters: output timestamp alongside the message

logger = logging.basicConfig(level=logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

This should be fine for most of the one off needs. If you need more control about your config, you can add more sophisticated behaviours by defining the logger's attributes your self.

Sophisticated Example: without using the basicConfig function

import logging
logger = logging.getLogger("mylogger")
streamHandler = logging.StreamHandler()
streamHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
streamHandler.setFormatter(formatter)

logger.addHandler(streamHandler)

logger.info("Files copied")
logger.warning("disk quota exceeded")
>> 2017-12-06 11:11:12, 090 - mylogger - INFO Files copied
>> 2017-12-06 11:11:12, 091 - mylogger - WARNING disk quota exceeded

The next step in a bigger environment, would be deriving a new logger from the previously created one, to first keep the formatting and as well to maintain a "log hierarchy"

logger2 = logging.getLogger("mylogger.new")
logger2.info("New Logger info")
>> 2017-12-06 11:11:12, 091 - mylogger.new - New logger info

A good reference is the logging cookbook:
https://docs.python.org/2/howto/logging-cookbook.html

ContentLicense: CC BY-SA 4.0


问:
Nodejs-mongoose-0.0.5 error when run app.js
```<code>/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40
          continue;
         ^^^^^^^^
node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
SyntaxError: Illegal continue statement
    at Module._compile (node.js:418:29)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)
    at require (node.js:367:23)
    at Object.<anonymous> (/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/model.js:2:13)
    at Module._compile (node.js:423:30)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)
</code>```

And the code is just:

```<code>var mongoose = require('mongoose').Mongoose;

mongoose.model('User', {
    properties: ['user', 'pass', 'widgets' ],
    indexes: [ { 'user' : 1 } , { unique : true }  ],
});
.......
</code>```

/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40

```<code> else {
       // Prevent never-ending loop
       if (target === d.value) {
             continue;
       }
</code>```

even if i comment the continue statement, causes another error log:

```<code>node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
Error: ECONNREFUSED, Connection refused
    at Socket._onConnect (net.js:548:18)
    at IOWatcher.onWritable [as callback] (net.js:165:12)
</code>```

Any idea?

答: ECONNREFUSED is because your mongod is not running - where's the connect string?</p>

Body:
/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40
          continue;
         ^^^^^^^^
node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
SyntaxError: Illegal continue statement
    at Module._compile (node.js:418:29)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)
    at require (node.js:367:23)
    at Object.<anonymous> (/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/model.js:2:13)
    at Module._compile (node.js:423:30)
    at Object..js (node.js:429:14)
    at Module.load (node.js:355:35)
    at Function._load (node.js:322:14)

And the code is just:

var mongoose = require('mongoose').Mongoose;

mongoose.model('User', {
    properties: ['user', 'pass', 'widgets' ],
    indexes: [ { 'user' : 1 } , { unique : true }  ],
});
.......

/usr/local/lib/node/.npm/mongoose/0.0.5/package/lib/util.js:40

 else {
       // Prevent never-ending loop
       if (target === d.value) {
             continue;
       }

even if i comment the continue statement, causes another error log:

node.js:68
      throw e; // process.nextTick error, or 'error' event on first tick
      ^
Error: ECONNREFUSED, Connection refused
    at Socket._onConnect (net.js:548:18)
    at IOWatcher.onWritable [as callback] (net.js:165:12)

Any idea?


问:
Plot CDF with GNUPLOT with data not being sorted

Hi I am trying to write a gnuplot script that produced CDF graph for the data produced from another program.

The data looks like this:

```<code>col1    col2    col3    col4    col5
ABCD11  19.8    1.13    129 2
AABC32  14.3    2.32    109 2
AACd12  19.1    0.21    103 2
</code>```

I want to plot CDF for the column 2. The point is that data in the col2 might not be sorted.

To compile the script I use online tool such as here

The script I tried is:

```<code>set output 'out.svg'
set terminal svg size 600,300 enhanced fname 'arial' fsize 10 mousing butt solid
set xlabel "X"
set ylabel "CDF"
set style line 2 lc rgb 'black' lt 1 lw 1
set xtics format "" nomirror rotate by -10 font ", 7"
set ytics nomirror

set grid ytics
set key box height .4 width -1 box right
set nokey
set title "CDF of X"

a=0
#gnuplot 4.4+ functions are now defined as:
#func(variable1,variable2...)=(statement1,statement2,...,return value)
cumulative_sum(x)=(a=a+x,a)
plot "data.txt" using 1:(cumulative_sum($2)) with linespoints lt -1
</code>```

答:
If you want to calculate the (running) cumulative sum of the values from second column using sorted values, then you could slightly extend your approach based on awk. To be more specific, the command would be

```<code>tail -n+2 'test.txt' | sort -k2,2n | awk '{s+=$2; print NR, s}'
</code>```

Here, tail strips off the header (skips the first line), sort sorts numerically according to the second column, and finally awk calculates the cumulative sum as a function of the number of records/items.

Body:
Hi I am trying to write a gnuplot script that produced CDF graph for the data produced from another program.

The data looks like this:

col1    col2    col3    col4    col5
ABCD11  19.8    1.13    129 2
AABC32  14.3    2.32    109 2
AACd12  19.1    0.21    103 2

I want to plot CDF for the column 2. The point is that data in the col2 might not be sorted.

To compile the script I use online tool such as here

The script I tried is:

set output 'out.svg'
set terminal svg size 600,300 enhanced fname 'arial' fsize 10 mousing butt solid
set xlabel "X"
set ylabel "CDF"
set style line 2 lc rgb 'black' lt 1 lw 1
set xtics format "" nomirror rotate by -10 font ", 7"
set ytics nomirror

set grid ytics
set key box height .4 width -1 box right
set nokey
set title "CDF of X"

a=0
#gnuplot 4.4+ functions are now defined as:
#func(variable1,variable2...)=(statement1,statement2,...,return value)
cumulative_sum(x)=(a=a+x,a)
plot "data.txt" using 1:(cumulative_sum($2)) with linespoints lt -1

Body:
If you want to calculate the (running) cumulative sum of the values from second column using sorted values, then you could slightly extend your approach based on awk. To be more specific, the command would be

tail -n+2 'test.txt' | sort -k2,2n | awk '{s+=$2; print NR, s}'

Here, tail strips off the header (skips the first line), sort sorts numerically according to the second column, and finally awk calculates the cumulative sum as a function of the number of records/items.


问:
End characters not being added to a string
I'm trying to load a string for a DirectorySearch filter.

```<code>strFilter = "((objectClass=container)(cn=" & strParameter & "))"
</code>```

It doesn't matter what the end characters are, they are not being added to the string. It always ends up as:

```<code>strFilter = "((objectClass=container)(cn=" & strParameter
</code>```

This is so frustrating. I can't even add the end brackets subsequently. What is going on? Strings should NOT behave like this!

答:
If strParameter contains a null-character (char 0) the rest of the string will usually not be rendered by most text editors/text viewers, even though it is actually there. This happens because the null-character is usually used to indicate the end of a string.

Try trimming any null-characters from your string and see if it fixes your problem:

```<code>strFilter = "((objectClass=container)(cn=" & strParameter.Trim(ChrW(0)) & "))"
</code>```

More information:

Null-terminated string - Wikipedia

If you in the future (for some reason) encounter a null-character in the middle of your string you can try removing all null-characters alltogether:

```<code>strFilter = "((objectClass=container)(cn=" & strParameter.Replace(ChrW(0), "") & "))"
</code>```

Body:
I'm trying to load a string for a DirectorySearch filter.

strFilter = "((objectClass=container)(cn=" & strParameter & "))"

It doesn't matter what the end characters are, they are not being added to the string. It always ends up as:

strFilter = "((objectClass=container)(cn=" & strParameter

This is so frustrating. I can't even add the end brackets subsequently. What is going on? Strings should NOT behave like this!

Body:
If strParameter contains a null-character (char 0) the rest of the string will usually not be rendered by most text editors/text viewers, even though it is actually there. This happens because the null-character is usually used to indicate the end of a string.

Try trimming any null-characters from your string and see if it fixes your problem:

strFilter = "((objectClass=container)(cn=" & strParameter.Trim(ChrW(0)) & "))"

More information:

Null-terminated string - Wikipedia

If you in the future (for some reason) encounter a null-character in the middle of your string you can try removing all null-characters alltogether:

strFilter = "((objectClass=container)(cn=" & strParameter.Replace(ChrW(0), "") & "))"


问:
Convert DISM output to PS objects
Can you point me in the right direction, on how do convert this DISM output to Powershell objects so i can use them in my script, to filter on the results ?
dism /Get-WimInfo /WimFile:"E:\_Source\OSD\x64\Windows 10 Enterprise\1607\Media\WIM\REFW10-X64-1607_04-12-2017.wim" /index:1

The out-put i get is :

```<code>Deployment Image Servicing and Management tool Version: 10.0.14393.0

Details for image : E:\_Source\OSD\x64\Windows 10 Enterprise\1607\Media\WIM\REFW10-X64-1607_04-12-2017.wim

Index : 1 Name : REFW10-X64EN-01EDrive
Description : Build Windows 10 Enterprise x64 en-US

Size : 18.500.052.305 bytes

WIM Bootable : No

Architecture : x64

Hal : acpiapic

Version : 10.0.16299

ServicePack Build : 15

ServicePack Level : 64

Edition : Enterprise

Installation : Client

ProductType : WinNT

ProductSuite : Terminal Server

System Root : WINDOWS

Directories : 24025

Files : 112737

Created : 24-11-2017 - 01:40:49

Modified : 24-11-2017 - 01:40:51

Languages :     en-US (Default)
</code>```

i tried with | Out-String -Stream | Select-String "Version "
But with no luck..

答:
Putting it together:</p>

```<code>$WimFile = "E:\_Source\OSD\x64\Windows 10 Enterprise\1607\Media\WIM\REFW10-X64-1607_04-12-2017.wim"
$Version = (dism /Get-WimInfo /WimFile:$WimFile /index:1 | Select-String "Version ").ToString().Split(":")[1].Trim()
$Language = ((dism /Get-WimInfo /WimFile:$WimFile /index:1 | Select-String "Languages " -Context 0,1).ToString() -Split "\s\(Default\)" -Split "\s")[-2]
</code>```

Title: Convert DISM output to PS objects

Body:
Can you point me in the right direction, on how do convert this DISM output to Powershell objects so i can use them in my script, to filter on the results ?
dism /Get-WimInfo /WimFile:"E:\_Source\OSD\x64\Windows 10 Enterprise\1607\Media\WIM\REFW10-X64-1607_04-12-2017.wim" /index:1

The out-put i get is :

Deployment Image Servicing and Management tool Version: 10.0.14393.0

Details for image : E:\_Source\OSD\x64\Windows 10 Enterprise\1607\Media\WIM\REFW10-X64-1607_04-12-2017.wim

Index : 1 Name : REFW10-X64EN-01EDrive
Description : Build Windows 10 Enterprise x64 en-US

Size : 18.500.052.305 bytes

WIM Bootable : No

Architecture : x64

Hal : acpiapic

Version : 10.0.16299

ServicePack Build : 15

ServicePack Level : 64

Edition : Enterprise

Installation : Client

ProductType : WinNT

ProductSuite : Terminal Server

System Root : WINDOWS

Directories : 24025

Files : 112737

Created : 24-11-2017 - 01:40:49

Modified : 24-11-2017 - 01:40:51

Languages :     en-US (Default)

i tried with | Out-String -Stream | Select-String "Version "
But with no luck..

Body:
Putting it together:

$WimFile = "E:\_Source\OSD\x64\Windows 10 Enterprise\1607\Media\WIM\REFW10-X64-1607_04-12-2017.wim"
$Version = (dism /Get-WimInfo /WimFile:$WimFile /index:1 | Select-String "Version ").ToString().Split(":")[1].Trim()
$Language = ((dism /Get-WimInfo /WimFile:$WimFile /index:1 | Select-String "Languages " -Context 0,1).ToString() -Split "\s\(Default\)" -Split "\s")[-2]


问:
Pandas difference in days between today's date and another date_time column?
I am running an analysis on transaction data, and want to calculate how long it has been in days since the most recent transaction for each unique customer.

My initial data frame (df1) looks like:

```<code>memberId     transactionDate
1111         2017-12-01
2222         2017-12-03
1111         2017-12-05
3333         2017-12-06
</code>```

TransactionDate is in datetime format.

This is my code trying to create a new dataframe with memberId and number of days since most recent transaction:

```<code>import datetime as dt
import pandas as pd

NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max())})
</code>```

This return as dataframe like:

```<code>memberId     transactionDate
1111         1 days
2222         3 days
3333         0 days
</code>```

But I want the days to be returns as an integer rather then with days.
My second try to fix this was:

```<code>NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max()).days})
</code>```

This returns something that looks like an epoch time for transactionDate, and output looks like:

```<code>memberId     transactionDate
1111         1970-01-01 00:00:00.000000001
2222         1970-01-01 00:00:00.000000003
3333         1970-01-01 00:00:00.000000000
</code>```

I think it is returning an epoch timestamp with number of days as microseconds.

How can I get an output like:

```<code>memberId     transactionDate
1111         1
2222         3
3333         0
</code>```

答:
Try using the following code</p>

```<code> df2.reset_index(inplace=True,drop=True)
 df2['Date2']=df2['Date'].apply(lambda x: x.days)
</code>```

Body:
I am running an analysis on transaction data, and want to calculate how long it has been in days since the most recent transaction for each unique customer.

My initial data frame (df1) looks like:

memberId     transactionDate
1111         2017-12-01
2222         2017-12-03
1111         2017-12-05
3333         2017-12-06

TransactionDate is in datetime format.

This is my code trying to create a new dataframe with memberId and number of days since most recent transaction:

import datetime as dt
import pandas as pd

NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max())})

This return as dataframe like:

memberId     transactionDate
1111         1 days
2222         3 days
3333         0 days

But I want the days to be returns as an integer rather then with days.
My second try to fix this was:

NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max()).days})

This returns something that looks like an epoch time for transactionDate, and output looks like:

memberId     transactionDate
1111         1970-01-01 00:00:00.000000001
2222         1970-01-01 00:00:00.000000003
3333         1970-01-01 00:00:00.000000000

I think it is returning an epoch timestamp with number of days as microseconds.

How can I get an output like:

memberId     transactionDate
1111         1
2222         3
3333         0

Body:
Try using the following code

 df2.reset_index(inplace=True,drop=True)
 df2['Date2']=df2['Date'].apply(lambda x: x.days)


问:
Mapping an array from props in a connected React component
I have a connected React component pulling into props from Redux state.

It is getting an array of objects called plots, like this:

```<code>function mapStateToProps(state) {
    return {
        plots: state.plots.plots
    };
}
</code>```

I want to map some properties of plots into arrays.

Making this call inside the render method works fine:

```<code>render() {
        if (this.props.plots) {
            console.log(this.props.plots.map(a => a.variety));
        }...
}
</code>```

Defining this method outside the class declaration and calling it inside the render method returns undefined:

```<code>const varieties = props => {
    if (props.plots) {
        props.plots.map(a => a.variety);
    }
};

render() {
        if (this.props.plots) {
            console.log(varieties(this.props);
        }
}
</code>```

Anyone know what I'm missing?

答:
Easy fix.

You are missing a return statement.

```<code>const varieties = props => {
    if (props.plots) {
        return props.plots.map(a => a.variety);
    }
};
</code>```

Body:
I have a connected React component pulling into props from Redux state.

It is getting an array of objects called plots, like this:

function mapStateToProps(state) {
    return {
        plots: state.plots.plots
    };
}

I want to map some properties of plots into arrays.

Making this call inside the render method works fine:

render() {
        if (this.props.plots) {
            console.log(this.props.plots.map(a => a.variety));
        }...
}

Defining this method outside the class declaration and calling it inside the render method returns undefined:

const varieties = props => {
    if (props.plots) {
        props.plots.map(a => a.variety);
    }
};

render() {
        if (this.props.plots) {
            console.log(varieties(this.props);
        }
}

Anyone know what I'm missing?

Body:
Easy fix.

You are missing a return statement.

const varieties = props => {
    if (props.plots) {
        return props.plots.map(a => a.variety);
    }
};


问:
DOM quotes by depth to Delta quotes - anyone an idea?
Ok, here we go. THis is a tricky one. FInancial market.

I have a trading application originally developped for the Rithmic API. FOr different reasons I am now moving real time data feed over to NxCore.

RIthmic has no concept of "DOM levels". I get moessages for every quote with volume, price. If a quote turns invalid, it gets 0 volume. WOrks nice....

NxCore does work with levels. I get a different message for every level (D1 - D10).

The problem is - I need to move from this to the RIthmic representation without sending too many errors / surplus messages.

Basically, the isue looks like this:

We establish a DOM - just ignore the items here. Interesting is D1 8 @ 11417

```<code>CBOT/YM.Z10 MM D2: 17 @ 11416 vs 10 @ 11421
CBOT/YM.Z10 MM D3: 10 @ 11415 vs 14 @ 11422
CBOT/YM.Z10 MM D5: 13 @ 11413 vs 13 @ 11424
CBOT/YM.Z10 MM D4: 17 @ 11414 vs 12 @ 11423
CBOT/YM.Z10 MM D9: 12 @ 11409 vs 12 @ 11428
CBOT/YM.Z10 MM D10: 14 @ 11408 vs 14 @ 11429
CBOT/YM.Z10 MM D5: 13 @ 11413 vs 16 @ 11424
CBOT/YM.Z10 MM D6: 20 @ 11412 vs 11 @ 11425
CBOT/YM.Z10 MM D1: 8 @ 11417 vs 3 @ 11420
CBOT/YM.Z10 2010-12-14 05:00:20.275000 BestBid 8 @ 11417

Something happens to he BestBid here..... so now it goes to 11418

CBOT/YM.Z10 MM D1: 3 @ 11418 vs 3 @ 11420
CBOT/YM.Z10 MM D2: 10 @ 11417 vs 10 @ 11421
CBOT/YM.Z10 MM D3: 17 @ 11416 vs 14 @ 11422
CBOT/YM.Z10 MM D4: 10 @ 11415 vs 12 @ 11423
CBOT/YM.Z10 MM D5: 16 @ 11414 vs 16 @ 11424
CBOT/YM.Z10 MM D6: 13 @ 11413 vs 11 @ 11425
CBOT/YM.Z10 MM D7: 17 @ 11412 vs 6 @ 11426
CBOT/YM.Z10 MM D8: 12 @ 11411 vs 5 @ 11427
CBOT/YM.Z10 MM D9: 18 @ 11410 vs 12 @ 11428
CBOT/YM.Z10 MM D10: 12 @ 11409 vs 14 @ 11429
CBOT/YM.Z10 2010-12-14 05:00:30.325000 BestBid 3 @ 11418

And that gives ups 10 updates just to move the DOM on the bid side. What I would need here is 2....
0 @ 11417
18 @ 11409
</code>```

Every line is a separate callback into my code (or event if you want to use that term). I already know I need to keep some sort o fbuffer (D1 - D10 on both sides, bid and ask, with price, level and volume). My main problem are all the edge cases. When a volume changes, same DOM level, same price - easy.

But when the DOM moves like above, I get 10 updates but most need to be thrown away for me.

Anyone an idea? Also note that D1 - D10 do not necessarily handle the next 10 prices - sometimes (off hours) there are gaps.... which makes things REALLY nasty. I sort of know that if I get a D1 or D10 I can throw out all reported items "further down" the line. But my problem is mostly around gaps...

Oh, and it needs to be fast. Like 200.000 messages per second sometimes.

Anyone a smart idea?

答:
If I compute this right:
2000 levels * 8000 symbols * 4 byte (size) * 2 (bid/ask) = 256 MB

No problem with todays computers.

Probably 2 bytes for size would also do the job which cuts it down to 128 MB.

(Btw if I get this right the job is to follow the complete US stocks universe via NxCore)

Body:
Ok, here we go. THis is a tricky one. FInancial market.

I have a trading application originally developped for the Rithmic API. FOr different reasons I am now moving real time data feed over to NxCore.

RIthmic has no concept of "DOM levels". I get moessages for every quote with volume, price. If a quote turns invalid, it gets 0 volume. WOrks nice....

NxCore does work with levels. I get a different message for every level (D1 - D10).

The problem is - I need to move from this to the RIthmic representation without sending too many errors / surplus messages.

Basically, the isue looks like this:

We establish a DOM - just ignore the items here. Interesting is D1 8 @ 11417

CBOT/YM.Z10 MM D2: 17 @ 11416 vs 10 @ 11421
CBOT/YM.Z10 MM D3: 10 @ 11415 vs 14 @ 11422
CBOT/YM.Z10 MM D5: 13 @ 11413 vs 13 @ 11424
CBOT/YM.Z10 MM D4: 17 @ 11414 vs 12 @ 11423
CBOT/YM.Z10 MM D9: 12 @ 11409 vs 12 @ 11428
CBOT/YM.Z10 MM D10: 14 @ 11408 vs 14 @ 11429
CBOT/YM.Z10 MM D5: 13 @ 11413 vs 16 @ 11424
CBOT/YM.Z10 MM D6: 20 @ 11412 vs 11 @ 11425
CBOT/YM.Z10 MM D1: 8 @ 11417 vs 3 @ 11420
CBOT/YM.Z10 2010-12-14 05:00:20.275000 BestBid 8 @ 11417

Something happens to he BestBid here..... so now it goes to 11418

CBOT/YM.Z10 MM D1: 3 @ 11418 vs 3 @ 11420
CBOT/YM.Z10 MM D2: 10 @ 11417 vs 10 @ 11421
CBOT/YM.Z10 MM D3: 17 @ 11416 vs 14 @ 11422
CBOT/YM.Z10 MM D4: 10 @ 11415 vs 12 @ 11423
CBOT/YM.Z10 MM D5: 16 @ 11414 vs 16 @ 11424
CBOT/YM.Z10 MM D6: 13 @ 11413 vs 11 @ 11425
CBOT/YM.Z10 MM D7: 17 @ 11412 vs 6 @ 11426
CBOT/YM.Z10 MM D8: 12 @ 11411 vs 5 @ 11427
CBOT/YM.Z10 MM D9: 18 @ 11410 vs 12 @ 11428
CBOT/YM.Z10 MM D10: 12 @ 11409 vs 14 @ 11429
CBOT/YM.Z10 2010-12-14 05:00:30.325000 BestBid 3 @ 11418

And that gives ups 10 updates just to move the DOM on the bid side. What I would need here is 2....
0 @ 11417
18 @ 11409

Every line is a separate callback into my code (or event if you want to use that term). I already know I need to keep some sort o fbuffer (D1 - D10 on both sides, bid and ask, with price, level and volume). My main problem are all the edge cases. When a volume changes, same DOM level, same price - easy.

But when the DOM moves like above, I get 10 updates but most need to be thrown away for me.

Anyone an idea? Also note that D1 - D10 do not necessarily handle the next 10 prices - sometimes (off hours) there are gaps.... which makes things REALLY nasty. I sort of know that if I get a D1 or D10 I can throw out all reported items "further down" the line. But my problem is mostly around gaps...

Oh, and it needs to be fast. Like 200.000 messages per second sometimes.

Anyone a smart idea?


问:
How to center everything inside navbar
I want to center everything in bootstrap navbar, it's my code:

```<code>    <nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
</code>```

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

```<code>.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }
</code>```

still doesn't work

答:
The problem is that both .navbar-header and .navbar-brand are float:left, so you need to explicitly override that. Then you can center them by changing them to display:inline-block and  adding the .text-center class to their container.

.navbar .text-center > * {
    float: none;
    display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<nav class="navbar navbar-default">
  <div class="container-fluid text-center"> <!-- added text-center class here -->
    <div class="navbar-header">
      WebSiteName
    </div>
    <ul class="nav navbar-nav">
      <li class="active">Home</li>
      <li>Page 1</li>
      <li>Page 2</li>
      <li>Page 3</li>
    </ul>
  </div>
</nav></code>```

Title: How to center everything inside navbar

Body:
I want to center everything in bootstrap navbar, it's my code:

      WebSiteName

Home

Page 1

Page 2

Page 3

I want to center div with class "container-fluid", I've tried adding "margin: 0 auto; float:none" to this div, but It doesn't work
I added this:

.container-fluid {
      margin: 0 auto !important;
      float: none !important;
    }

still doesn't work

Body:
The problem is that both .navbar-header and .navbar-brand are float:left, so you need to explicitly override that. Then you can center them by changing them to display:inline-block and  adding the .text-center class to their container.

.navbar .text-center > * {
    float: none;
    display: inline-block;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<nav class="navbar navbar-default">
  <div class="container-fluid text-center"> <!-- added text-center class here -->
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Home</a></li>
      <li><a href="#">Page 1</a></li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>


问:
UnderscoreJS - Retrieve specific keys from an object within a object
I have the follow object that I'm trying to retrieve the token and UserEmail from Details

```<code>var obj = {
  "id": null,
  "firstName": null,
  "lastName": null,
  "createdAt": "2016-10-05T18:16:07.000Z",
  "updatedAt": "2016-10-05T18:16:07.000Z",
  "Details":
    {
      "id": 1,
      "token": null,
      "deviceId": null,
      "code": 12345678,
      "verified": null,
      "createdAt": "2016-10-05T18:16:07.000Z",
      "updatedAt": "2016-10-05T18:16:07.000Z",
      "UserEmail": "joe@example.com"
    }
 }
</code>```

I tried this but I'm getting a blank?

```<code>_.pick(_.pick(obj, 'Details'), 'code', 'UserEmail');
</code>```

答:
Your inner pick will return you an object with a Details key, which you'll then have to access. Instead, do something like:

_.pick(obj['Details'], 'code', 'UserEmail')

Body:
I have the follow object that I'm trying to retrieve the token and UserEmail from Details

var obj = {
  "id": null,
  "firstName": null,
  "lastName": null,
  "createdAt": "2016-10-05T18:16:07.000Z",
  "updatedAt": "2016-10-05T18:16:07.000Z",
  "Details":
    {
      "id": 1,
      "token": null,
      "deviceId": null,
      "code": 12345678,
      "verified": null,
      "createdAt": "2016-10-05T18:16:07.000Z",
      "updatedAt": "2016-10-05T18:16:07.000Z",
      "UserEmail": "joe@example.com"
    }
 }

I tried this but I'm getting a blank?

_.pick(_.pick(obj, 'Details'), 'code', 'UserEmail');


问:
rewrite if/else for textbox into a single line of code
Is it possible to rewrite this into a single line of code?</p>

```<code>if (txtInvoiceDate.Text != "")
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DateTime.Parse(txtInvoiceDate.Text.ToString());
}
else
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DBNull.Value;
}
</code>```

答:
Yes

I have been reading about the ?: operator. I wasn't sure how this
  would work in this situation. I have never used it in this case

So, according to your code you can change it to

```<code>query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = txtInvoiceDate.Text != "" ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;
</code>```

but it will be better to use string.IsNullOrWhiteSpace()

```<code>query.Parameters.Add("@InvoiceDate", SqlDbType.SmallDateTime).Value = !string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;
</code>```

Read more about ?: Operator

Body:
Is it possible to rewrite this into a single line of code?

if (txtInvoiceDate.Text != "")
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DateTime.Parse(txtInvoiceDate.Text.ToString());
}
else
{
  query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = DBNull.Value;
}

Body:
Yes

I have been reading about the ?: operator. I wasn't sure how this
  would work in this situation. I have never used it in this case

So, according to your code you can change it to

query.Parameters.AddWithValue("@InvoiceDate", SqlDbType.SmallDateTime).Value = txtInvoiceDate.Text != "" ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;

but it will be better to use string.IsNullOrWhiteSpace()

query.Parameters.Add("@InvoiceDate", SqlDbType.SmallDateTime).Value = !string.IsNullOrWhiteSpace(txtInvoiceDate.Text) ? DateTime.Parse(txtInvoiceDate.Text.ToString()) : DBNull.Value;

Read more about ?: Operator