问:
Cannot compile wxWidgets Hello World
So, I was trying to compile hello world example provided by wxWidgets but was unsuccessful in doing so. I will explain what I have done step by step to the current point where I am stuck.

Compiling wxWidgets

First of all, my compiler of choice is MinGw-w64, and since wxWidgets advise to build their library from source (downloaded from wxWidgets download),  I decided to do so using CMake.

I created a directory called cmake inside the root directory of wxWidgets (in my case: C:\C++\wxWidgets-3.1.3). Also I created bin directory for storing the compiled binaries.

I then navigated to the cmake directory and run the following CMake configuration command:```$ cmake -G "MinGW Makefiles" .. -D "wxBUILD_SHARED=OFF" -D "wxBUILD_MONOLITHIC=OFF" -D "CMAKE_BUILD_TYPE=debug" -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe"```then I started the build by using the following command:```$ cmake --build . --target all```The resulting .a files (static library files) were placed in the bin directory.

I repeated the step 3 with the -D "CMAKE_BUILD_TYPE=release" parameter.

The generated lib\gcc_x64_lib\mswu and lib\gcc_x64_lib\mswud directories into the include directory for the convenience (as they contain setup.h header file).

As the result my C:\C++\wxWidgets-3.1.3\bin directory contains following files: ```libwxexpat.a   libwxpngd.a        libwxtiff.a   wxbase31u_net.a   wxmsw31u_adv.a   wxmsw31u_media.a     wxmsw31u_stc.a      wxmsw31ud_core.a      wxmsw31ud_qa.a        wxmsw31ud_xrc.a
libwxexpatd.a  libwxregexu.a      libwxtiffd.a  wxbase31u_xml.a   wxmsw31u_aui.a   wxmsw31u_propgrid.a  wxmsw31u_webview.a  wxmsw31ud_gl.a        wxmsw31ud_ribbon.a    wxrc.exe*
libwxjpeg.a    libwxregexud.a     libwxzlib.a   wxbase31ud.a      wxmsw31u_core.a  wxmsw31u_qa.a        wxmsw31u_xrc.a      wxmsw31ud_html.a      wxmsw31ud_richtext.a
libwxjpegd.a   libwxscintilla.a   libwxzlibd.a  wxbase31ud_net.a  wxmsw31u_gl.a    wxmsw31u_ribbon.a    wxmsw31ud_adv.a     wxmsw31ud_media.a     wxmsw31ud_stc.a
libwxpng.a     libwxscintillad.a  wxbase31u.a   wxbase31ud_xml.a  wxmsw31u_html.a  wxmsw31u_richtext.a  wxmsw31ud_aui.a     wxmsw31ud_propgrid.a  wxmsw31ud_webview.a```

Creating Hello World project

I created simple wxWidgets hello world project with the following file structure: ```app
|   build
|   headers
|   sources
|   |    main.cpp
|   CMakeLists.txt```

The contents of main.cpp:

// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

class MyFrame : public wxFrame {
public:
    MyFrame();

private:
    void OnHello(wxCommandEvent& event);
    void OnExit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
};

enum {
    ID_Hello = 1
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(): wxFrame(NULL, wxID_ANY, "Hello World") {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);

    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    menuBar->Append(menuHelp, "&Help");

    SetMenuBar( menuBar );
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}

void MyFrame::OnExit(wxCommandEvent& event) {
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& event) {
    wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

void MyFrame::OnHello(wxCommandEvent& event) {
    wxLogMessage("Hello world from wxWidgets!");
}
```

<p>The contents of <strong><code>CMakeLists.txt</code></strong>:</p>

```cmake_minimum_required(VERSION 2.8)

project(hello_world)

if (MINGW)
    add_compile_options(--static)
endif()

set(wx_libraries_path "C:\\C++\\wxWidgets-3.1.3\\bin")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswud")
    find_library(libwxexpat       NAMES libwxexpatd        PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpegd         PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpngd          PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexud       PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintillad    PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiffd         PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlibd         PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31ud         PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31ud_net     PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31ud_xml     PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31ud_adv      PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31ud_aui      PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31ud_core     PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31ud_gl       PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31ud_html     PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31ud_media    PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31ud_propgrid PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31ud_qa       PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31ud_ribbon   PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31ud_richtext PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31ud_stc      PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31ud_webview  PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31ud_xrc      PATH ${wx_libraries_path})
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswu")
    find_library(libwxexpat       NAMES libwxexpat       PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpeg        PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpng         PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexu      PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintilla   PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiff        PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlib        PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31u        PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31u_xml    PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31u_net    PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31u_adv     PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31u_aui     PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31u_core    PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31u_gl      PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31u_html    PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31u_media   PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31u_propgri PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31u_qa      PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31u_ribbon  PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31u_richtex PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31u_stc     PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31u_webview PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31u_xrc     PATH ${wx_libraries_path})
endif()

include_directories("C:\\C++\\wxWidgets-3.1.3\\include")
link_directories("C:\\C++\\wxWidgets-3.1.3\\bin")

add_executable(app sources/main.cpp)

message(STATUS "${libwxexpat}")
target_link_libraries(app PRIVATE
    ${libwxexpat}
    ${libwxjpeg}
    ${libwxpng}
    ${libwxregexu}
    ${libwxscintilla}
    ${libwxtiff}
    ${libwxzlib}
    ${wxbase31u}
    ${wxbase31u_xml}
    ${wxbase31u_net}
    ${wxmsw31u_adv}
    ${wxmsw31u_aui}
    ${wxmsw31u_core}
    ${wxmsw31u_gl}
    ${wxmsw31u_html}
    ${wxmsw31u_media}
    ${wxmsw31u_propgrid}
    ${wxmsw31u_qa}
    ${wxmsw31u_ribbon}
    ${wxmsw31u_richtext}
    ${wxmsw31u_stc}
    ${wxmsw31u_webview}
    ${wxmsw31u_xrc}
)
```

<p>After I created project files I executed following CMake command to configure the project:```cmake -G "MinGW Makefiles" .. -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe" -D "CMAKE_BUILD_TYPE=Debug" -D "CMAKE_VERBOSE_MAKEFILE:BOOL=ON"```
Then I tried and failed to build the project with the following CMake command:```cmake --build .```</p>

<h3>Compilation errors</h3>

<p>Unfortunately, the program fails to compile with, here is the output:</p>

```"C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\progress.marks
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\Makefile2 all
mingw32-make.exe[1]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/depend
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake --color=
Dependee "C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Dependee "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Scanning dependencies of target app
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/build
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
[ 50%] Building CXX object CMakeFiles/app.dir/sources/main.cpp.obj
C:\C++\MingGW-w64\mingw64\bin\g++.exe   @CMakeFiles/app.dir/includes_CXX.rsp -g   --static -o CMakeFiles\app.dir\sources\main.cpp.obj -c C:\Users\Oiltanker\Git\Pepega-Inject\installer\sources\main.cpp
[100%] Linking CXX executable app.exe
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\app.dir\link.txt --verbose=1
"C:\Program Files\CMake\bin\cmake.exe" -E remove -f CMakeFiles\app.dir/objects.a
C:\C++\MingGW-w64\mingw64\bin\ar.exe cr CMakeFiles\app.dir/objects.a @CMakeFiles\app.dir\objects1.rsp
C:\C++\MingGW-w64\mingw64\bin\g++.exe -g   -Wl,--whole-archive CMakeFiles\app.dir/objects.a -Wl,--no-whole-archive  -o app.exe -Wl,--out-implib,libapp.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\app.dir\linklibs.rsp
C:/C++/wxWidgets-3.1.3/bin/wxbase31ud.a(dlmsw.cpp.obj): In function `GetFileVersion':
C:/C++/wxWidgets-3.1.3/src/msw/dlmsw.cpp:67: undefined reference to `GetFileVersionInfoSizeW'
      .......
C:/C++/wxWidgets-3.1.3/src/common/geometry.cpp:350: undefined reference to `wxDataInputStream::Read32()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\app.dir\build.make:110: app.exe] Error 1
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:78: CMakeFiles/app.dir/all] Error 2
mingw32-make.exe[1]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe: *** [Makefile:86: all] Error 2```
</code>```

答:
I managed to solve my problem. After I started searching on internet for answers and I found wxWidgets project CMakeLists.txt example that didn't work because it needed some variables set. After I set them correctly, I managed to compile hello world example.

Here is the contents of CMakeLists.txt file:

```<code>project(hello_world)
cmake_minimum_required(VERSION 2.8)

aux_source_directory(src SRC_LIST)

set(wxWidgets_ROOT_DIR "C:/C++/wxWidgets")
set(wxWidgets_LIB_DIR "C:/C++/wxWidgets/lib/gcc_x64_lib")
set(wxWidgets_LIBRARIES "C:/C++/wxWidgets/lib")
set(wxWidgets_INCLUDE_DIRS "C:/C++/wxWidgets/include/wx")

set(wxWidgets_CONFIGURATION mswud)
find_package(wxWidgets COMPONENTS core base REQUIRED)
include(${wxWidgets_USE_FILE})

add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${wxWidgets_LIBRARIES})
</code>```

Process in detail

I deleted wxWidgets and recompiled them.

This time the wxWidgets source code was located in C:\C++\wxWidgets-source directory

I built install target to the C:\C++\wxWidgets directory with the following command:```$ cmake --build . --target install```You can specify the destination where your installation will go to by altering wxINSTALL_PREFIX definition in setup.h file and alerting CMAKE_INSTALL_PREFIX definition in cmake_install.cmake file.

In case of debug configuration, the setup.h file will be located in <cmake_building_directory>\lib\gcc_x64_lib\mswud\wx

In case of release configuration, the setup.h file will be located in <cmake_building_directory>\lib\gcc_x64_lib\mswu\wx

I was also told that wxWidgets might have a specific linking order and that find_package function solves automatically, whether it is true or not I cannot tell.

Title: Cannot compile wxWidgets Hello World

Body:
So, I was trying to compile hello world example provided by wxWidgets but was unsuccessful in doing so. I will explain what I have done step by step to the current point where I am stuck.

Compiling wxWidgets

First of all, my compiler of choice is MinGw-w64, and since wxWidgets advise to build their library from source (downloaded from wxWidgets download),  I decided to do so using CMake.

I created a directory called cmake inside the root directory of wxWidgets (in my case: C:\C++\wxWidgets-3.1.3). Also I created bin directory for storing the compiled binaries.

I then navigated to the cmake directory and run the following CMake configuration command:
$ cmake -G "MinGW Makefiles" .. -D "wxBUILD_SHARED=OFF" -D "wxBUILD_MONOLITHIC=OFF" -D "CMAKE_BUILD_TYPE=debug" -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe"
then I started the build by using the following command:
$ cmake --build . --target all
The resulting .a files (static library files) were placed in the bin directory.

I repeated the step 3 with the -D "CMAKE_BUILD_TYPE=release" parameter.

The generated lib\gcc_x64_lib\mswu and lib\gcc_x64_lib\mswud directories into the include directory for the convenience (as they contain setup.h header file).

As the result my C:\C++\wxWidgets-3.1.3\bin directory contains following files:
libwxexpat.a   libwxpngd.a        libwxtiff.a   wxbase31u_net.a   wxmsw31u_adv.a   wxmsw31u_media.a     wxmsw31u_stc.a      wxmsw31ud_core.a      wxmsw31ud_qa.a        wxmsw31ud_xrc.a
libwxexpatd.a  libwxregexu.a      libwxtiffd.a  wxbase31u_xml.a   wxmsw31u_aui.a   wxmsw31u_propgrid.a  wxmsw31u_webview.a  wxmsw31ud_gl.a        wxmsw31ud_ribbon.a    wxrc.exe*
libwxjpeg.a    libwxregexud.a     libwxzlib.a   wxbase31ud.a      wxmsw31u_core.a  wxmsw31u_qa.a        wxmsw31u_xrc.a      wxmsw31ud_html.a      wxmsw31ud_richtext.a
libwxjpegd.a   libwxscintilla.a   libwxzlibd.a  wxbase31ud_net.a  wxmsw31u_gl.a    wxmsw31u_ribbon.a    wxmsw31ud_adv.a     wxmsw31ud_media.a     wxmsw31ud_stc.a
libwxpng.a     libwxscintillad.a  wxbase31u.a   wxbase31ud_xml.a  wxmsw31u_html.a  wxmsw31u_richtext.a  wxmsw31ud_aui.a     wxmsw31ud_propgrid.a  wxmsw31ud_webview.a

Creating Hello World project

I created simple wxWidgets hello world project with the following file structure:
app
|   build
|   headers
|   sources
|   |    main.cpp
|   CMakeLists.txt

The contents of main.cpp:

// wxWidgets "Hello World" Program
// For compilers that support precompilation, includes "wx/wx.h".
#include <wx/wxprec.h>

#ifndef WX_PRECOMP
    #include <wx/wx.h>
#endif

class MyApp : public wxApp {
public:
    virtual bool OnInit();
};

class MyFrame : public wxFrame {
public:
    MyFrame();

private:
    void OnHello(wxCommandEvent& event);
    void OnExit(wxCommandEvent& event);
    void OnAbout(wxCommandEvent& event);
};

enum {
    ID_Hello = 1
};

wxIMPLEMENT_APP(MyApp);

bool MyApp::OnInit() {
    MyFrame *frame = new MyFrame();
    frame->Show(true);
    return true;
}

MyFrame::MyFrame(): wxFrame(NULL, wxID_ANY, "Hello World") {
    wxMenu *menuFile = new wxMenu;
    menuFile->Append(ID_Hello, "&Hello...\tCtrl-H", "Help string shown in status bar for this menu item");
    menuFile->AppendSeparator();
    menuFile->Append(wxID_EXIT);

    wxMenu *menuHelp = new wxMenu;
    menuHelp->Append(wxID_ABOUT);

    wxMenuBar *menuBar = new wxMenuBar;
    menuBar->Append(menuFile, "&File");
    menuBar->Append(menuHelp, "&Help");

    SetMenuBar( menuBar );
    CreateStatusBar();
    SetStatusText("Welcome to wxWidgets!");

    Bind(wxEVT_MENU, &MyFrame::OnHello, this, ID_Hello);
    Bind(wxEVT_MENU, &MyFrame::OnAbout, this, wxID_ABOUT);
    Bind(wxEVT_MENU, &MyFrame::OnExit, this, wxID_EXIT);
}

void MyFrame::OnExit(wxCommandEvent& event) {
    Close(true);
}

void MyFrame::OnAbout(wxCommandEvent& event) {
    wxMessageBox("This is a wxWidgets Hello World example", "About Hello World", wxOK | wxICON_INFORMATION);
}

void MyFrame::OnHello(wxCommandEvent& event) {
    wxLogMessage("Hello world from wxWidgets!");
}

The contents of CMakeLists.txt:

cmake_minimum_required(VERSION 2.8)

project(hello_world)

if (MINGW)
    add_compile_options(--static)
endif()

set(wx_libraries_path "C:\\C++\\wxWidgets-3.1.3\\bin")

if(CMAKE_BUILD_TYPE STREQUAL "Debug")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswud")
    find_library(libwxexpat       NAMES libwxexpatd        PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpegd         PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpngd          PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexud       PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintillad    PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiffd         PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlibd         PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31ud         PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31ud_net     PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31ud_xml     PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31ud_adv      PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31ud_aui      PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31ud_core     PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31ud_gl       PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31ud_html     PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31ud_media    PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31ud_propgrid PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31ud_qa       PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31ud_ribbon   PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31ud_richtext PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31ud_stc      PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31ud_webview  PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31ud_xrc      PATH ${wx_libraries_path})
endif()

if(CMAKE_BUILD_TYPE STREQUAL "Release")
    include_directories("C:\\C++\\wxWidgets-3.1.3\\include\\mswu")
    find_library(libwxexpat       NAMES libwxexpat       PATH ${wx_libraries_path})
    find_library(libwxjpeg        NAMES libwxjpeg        PATH ${wx_libraries_path})
    find_library(libwxpng         NAMES libwxpng         PATH ${wx_libraries_path})
    find_library(libwxregexu      NAMES libwxregexu      PATH ${wx_libraries_path})
    find_library(libwxscintilla   NAMES libwxscintilla   PATH ${wx_libraries_path})
    find_library(libwxtiff        NAMES libwxtiff        PATH ${wx_libraries_path})
    find_library(libwxzlib        NAMES libwxzlib        PATH ${wx_libraries_path})
    find_library(wxbase31u        NAMES wxbase31u        PATH ${wx_libraries_path})
    find_library(wxbase31u_xml    NAMES wxbase31u_xml    PATH ${wx_libraries_path})
    find_library(wxbase31u_net    NAMES wxbase31u_net    PATH ${wx_libraries_path})
    find_library(wxmsw31u_adv     NAMES wxmsw31u_adv     PATH ${wx_libraries_path})
    find_library(wxmsw31u_aui     NAMES wxmsw31u_aui     PATH ${wx_libraries_path})
    find_library(wxmsw31u_core    NAMES wxmsw31u_core    PATH ${wx_libraries_path})
    find_library(wxmsw31u_gl      NAMES wxmsw31u_gl      PATH ${wx_libraries_path})
    find_library(wxmsw31u_html    NAMES wxmsw31u_html    PATH ${wx_libraries_path})
    find_library(wxmsw31u_media   NAMES wxmsw31u_media   PATH ${wx_libraries_path})
    find_library(wxmsw31u_propgri NAMES wxmsw31u_propgri PATH ${wx_libraries_path})
    find_library(wxmsw31u_qa      NAMES wxmsw31u_qa      PATH ${wx_libraries_path})
    find_library(wxmsw31u_ribbon  NAMES wxmsw31u_ribbon  PATH ${wx_libraries_path})
    find_library(wxmsw31u_richtex NAMES wxmsw31u_richtex PATH ${wx_libraries_path})
    find_library(wxmsw31u_stc     NAMES wxmsw31u_stc     PATH ${wx_libraries_path})
    find_library(wxmsw31u_webview NAMES wxmsw31u_webview PATH ${wx_libraries_path})
    find_library(wxmsw31u_xrc     NAMES wxmsw31u_xrc     PATH ${wx_libraries_path})
endif()

include_directories("C:\\C++\\wxWidgets-3.1.3\\include")
link_directories("C:\\C++\\wxWidgets-3.1.3\\bin")

add_executable(app sources/main.cpp)

message(STATUS "${libwxexpat}")
target_link_libraries(app PRIVATE
    ${libwxexpat}
    ${libwxjpeg}
    ${libwxpng}
    ${libwxregexu}
    ${libwxscintilla}
    ${libwxtiff}
    ${libwxzlib}
    ${wxbase31u}
    ${wxbase31u_xml}
    ${wxbase31u_net}
    ${wxmsw31u_adv}
    ${wxmsw31u_aui}
    ${wxmsw31u_core}
    ${wxmsw31u_gl}
    ${wxmsw31u_html}
    ${wxmsw31u_media}
    ${wxmsw31u_propgrid}
    ${wxmsw31u_qa}
    ${wxmsw31u_ribbon}
    ${wxmsw31u_richtext}
    ${wxmsw31u_stc}
    ${wxmsw31u_webview}
    ${wxmsw31u_xrc}
)

After I created project files I executed following CMake command to configure the project:
cmake -G "MinGW Makefiles" .. -D "CMAKE_C_COMPILER=gcc.exe" -D "CMAKE_CXX_COMPILER=g++.exe" -D "CMAKE_BUILD_TYPE=Debug" -D "CMAKE_VERBOSE_MAKEFILE:BOOL=ON"

Then I tried and failed to build the project with the following CMake command:
cmake --build .

Compilation errors

Unfortunately, the program fails to compile with, here is the output:

"C:\Program Files\CMake\bin\cmake.exe" -E cmake_progress_start C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\progress.marks
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\Makefile2 all
mingw32-make.exe[1]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/depend
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake --color=
Dependee "C:\Users\Oiltanker\Git\Pepega-Inject\installer\build\CMakeFiles\app.dir\DependInfo.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Dependee "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/CMakeDirectoryInformation.cmake" is newer than depender "C:/Users/Oiltanker/Git/Pepega-Inject/installer/build/CMakeFiles/app.dir/depend.internal".
Scanning dependencies of target app
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
C:/C++/MingGW-w64/mingw64/bin/mingw32-make.exe -f CMakeFiles\app.dir\build.make CMakeFiles/app.dir/build
mingw32-make.exe[2]: Entering directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
[ 50%] Building CXX object CMakeFiles/app.dir/sources/main.cpp.obj
C:\C++\MingGW-w64\mingw64\bin\g++.exe   @CMakeFiles/app.dir/includes_CXX.rsp -g   --static -o CMakeFiles\app.dir\sources\main.cpp.obj -c C:\Users\Oiltanker\Git\Pepega-Inject\installer\sources\main.cpp
[100%] Linking CXX executable app.exe
"C:\Program Files\CMake\bin\cmake.exe" -E cmake_link_script CMakeFiles\app.dir\link.txt --verbose=1
"C:\Program Files\CMake\bin\cmake.exe" -E remove -f CMakeFiles\app.dir/objects.a
C:\C++\MingGW-w64\mingw64\bin\ar.exe cr CMakeFiles\app.dir/objects.a @CMakeFiles\app.dir\objects1.rsp
C:\C++\MingGW-w64\mingw64\bin\g++.exe -g   -Wl,--whole-archive CMakeFiles\app.dir/objects.a -Wl,--no-whole-archive  -o app.exe -Wl,--out-implib,libapp.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\app.dir\linklibs.rsp
C:/C++/wxWidgets-3.1.3/bin/wxbase31ud.a(dlmsw.cpp.obj): In function `GetFileVersion':
C:/C++/wxWidgets-3.1.3/src/msw/dlmsw.cpp:67: undefined reference to `GetFileVersionInfoSizeW'
      .......
C:/C++/wxWidgets-3.1.3/src/common/geometry.cpp:350: undefined reference to `wxDataInputStream::Read32()'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[2]: *** [CMakeFiles\app.dir\build.make:110: app.exe] Error 1
mingw32-make.exe[2]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:78: CMakeFiles/app.dir/all] Error 2
mingw32-make.exe[1]: Leaving directory 'C:/Users/Oiltanker/Git/Pepega-Inject/installer/build'
mingw32-make.exe: *** [Makefile:86: all] Error 2```

Body:
I managed to solve my problem. After I started searching on internet for answers and I found wxWidgets project CMakeLists.txt example that didn't work because it needed some variables set. After I set them correctly, I managed to compile hello world example.

Here is the contents of CMakeLists.txt file:

project(hello_world)
cmake_minimum_required(VERSION 2.8)

aux_source_directory(src SRC_LIST)

set(wxWidgets_ROOT_DIR "C:/C++/wxWidgets")
set(wxWidgets_LIB_DIR "C:/C++/wxWidgets/lib/gcc_x64_lib")
set(wxWidgets_LIBRARIES "C:/C++/wxWidgets/lib")
set(wxWidgets_INCLUDE_DIRS "C:/C++/wxWidgets/include/wx")

set(wxWidgets_CONFIGURATION mswud)
find_package(wxWidgets COMPONENTS core base REQUIRED)
include(${wxWidgets_USE_FILE})

add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${wxWidgets_LIBRARIES})

Process in detail

I deleted wxWidgets and recompiled them.

This time the wxWidgets source code was located in C:\C++\wxWidgets-source directory

I built install target to the C:\C++\wxWidgets directory with the following command:
$ cmake --build . --target install
You can specify the destination where your installation will go to by altering wxINSTALL_PREFIX definition in setup.h file and alerting CMAKE_INSTALL_PREFIX definition in cmake_install.cmake file.

In case of debug configuration, the setup.h file will be located in <cmake_building_directory>\lib\gcc_x64_lib\mswud\wx

In case of release configuration, the setup.h file will be located in <cmake_building_directory>\lib\gcc_x64_lib\mswu\wx

I was also told that wxWidgets might have a specific linking order and that find_package function solves automatically, whether it is true or not I cannot tell.


来源: stackexchange

问:
Error "package android.support.v7.app does not exist"
I am new to android development, and I have been using the command line tools to create an android project.  I followed all the instructions given in the tutorial at android developers.  However, they are focused more on IDE users.

When I tried extending my MainActivity class from ActionBarActivity instead of just Activity, it threw the following error.

error: package android.support.v7.app does not exist

It was complaining about this import statement.

```<code>import android.support.v7.app.ActionBarActivity;
</code>```

I made sure to visit the SDK manager, and it says Android Support Library is installed.
I am truly stumped on this one, and I would really appreciate any help you guys could give me.

This might help:
http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html

答:
I just got this error today and this is how I fixed.

On my build output, I double click on the class with the error.

After the class opened, I expanded the imports section and deleted existing
imports with errors.

I then hovered my mouse near the errors which were:RecyclerView,LinearLayoutManager, and FragmentTransaction and chose Alt+Enter to import appropriate classes.

Note: in my case, the error occured after I migrated one of my old projects to androidx and so imports hard to be androidx related. I am using android studio.

Note: You may run into other issues, so everytime I run into an error, I check other called classes and makes sure their imports are correct. What I do mostly is press ctrl+shift+R, and put the old import in the first field and the correct import on the second field and then replace all. This way, I replace all imports that in the project at once.

You can use ctrl+shift+f to find where imports are used.

ContentLicense: CC BY-SA 3.0

Body:
I am new to android development, and I have been using the command line tools to create an android project.  I followed all the instructions given in the tutorial at android developers.  However, they are focused more on IDE users.

When I tried extending my MainActivity class from ActionBarActivity instead of just Activity, it threw the following error.

error: package android.support.v7.app does not exist

It was complaining about this import statement.

import android.support.v7.app.ActionBarActivity;

I made sure to visit the SDK manager, and it says Android Support Library is installed.
I am truly stumped on this one, and I would really appreciate any help you guys could give me.

This might help:
http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html

ContentLicense: CC BY-SA 4.0


问:
kubernetes liveliness is un-authorized
I am trying to define a livenessProbe by passing the value of httpheader as secret. but I am getting un-authorized 401.

```<code>  - name: mycontainer
    image: myimage
    env:
      - name: MY_SECRET
        valueFrom:
          secretKeyRef:
            name: actuatortoken
            key: token
    livenessProbe:
        httpGet:
          path: /test/actuator/health
          port: 9001
          httpHeaders:
          - name: Authorization
            value: $MY_SECRET

</code>```

My secret as follows:

```<code>apiVersion: v1
kind: Secret
metadata:
  name: actuatortoken
type: Opaque
stringData:
  token: Bearer <token>
</code>```

If I pass the same with actual value as below... it works as expected

```<code>  - name: mycontainer
    image: myimage
    livenessProbe:
        httpGet:
          path: /test/actuator/health
          port: 9001
          httpHeaders:
          - name: Authorization
            value: Bearer <token>

</code>```

Any help is highly appreciated.

答:
What you have will put the literal string $MY_SECRET as the Authorization header which won't work.

You don't want to put the actual value of the secret in your Pod/Deployment/whatever YAML since you don't want plaintext credentials in there.

3 options I can think of:

a) change your app to not require authentication for the /test/actuator/health endpoint;

b) change your app to not require authentication when the requested host is 127.0.0.1 and update the probe configuration to use that as the host;

c) switch from an HTTP probe to a command probe and write the curl/wget command yourself

Answer is being posted as Community wiki as it's from Amit Kumar Gupta comments.

Title: kubernetes liveliness is un-authorized

Body:
I am trying to define a livenessProbe by passing the value of httpheader as secret. but I am getting un-authorized 401.

  - name: mycontainer
    image: myimage
    env:
      - name: MY_SECRET
        valueFrom:
          secretKeyRef:
            name: actuatortoken
            key: token
    livenessProbe:
        httpGet:
          path: /test/actuator/health
          port: 9001
          httpHeaders:
          - name: Authorization
            value: $MY_SECRET

My secret as follows:

apiVersion: v1
kind: Secret
metadata:
  name: actuatortoken
type: Opaque
stringData:
  token: Bearer <token>

If I pass the same with actual value as below... it works as expected

  - name: mycontainer
    image: myimage
    livenessProbe:
        httpGet:
          path: /test/actuator/health
          port: 9001
          httpHeaders:
          - name: Authorization
            value: Bearer <token>

Any help is highly appreciated.


问:
How can I try catch a val in fetch data successfully?
I am trying to fetch a JSONObject "image" that is sometimes a null value, so I set a try {} catch {} for my val jsonMedia in order to make it nullable but Im not sure if I'm missing something because it doesnt seem to work.

Whenever I comment out the jsonMedia my fetch works fine so I'll focus on just sharing the fetch of the "image" so the data I share doesnt get confusing.

1st. Ill show how the "image" is in the database and what I mean by "sometimes" has a null value
- null:

```<code>{
    "listCar": [
   {
    //other data
    "image": null,
    //other data
   }
 ]
}
</code>```

when it contains an image:

```<code>{
    "listCar": [
   {
    //other data
     "image": {
                "path": "Upload/UploadCarMain/UploadCarMain-200-200/30032235992008220498istanbul_adalarCar195.jpg",
                "name": "30032235992008220498istanbul_adalarCar195.jpg"
            },
    //other data
   }
 ]
}
</code>```

Now my fetch data was followed by a course I'm watching the only difference is the values of "image" in the database Im using arent like the course which did not contain null values in their image path

Now here is my "Car" class that is supposed to get the image:

```<code>class Car(other data, val image: String?, other data) {
    override fun toString(): String {
        return "Car(//other data, image='$image', //other data')"
    }
}
</code>```

and here is my fetch code where I am trying to try {} catch(){} my "jsonMedia" image JSONOBject:

```<code>override fun doInBackground(vararg params: String?): ArrayList<Car> {
        Log.d(TAG, "doInBackground starts")

        val carList = ArrayList<Car>()
        try {
            val jsonData = JSONObject(params[0])
            val itemsArray = jsonData.getJSONArray("listCar")

            for (i in 0 until itemsArray.length()) {
                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: IllegalArgumentException) {null}
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)
                Log.d(TAG, ".doInBackground $carObject")
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            Log.e(TAG, "doInBackground: Error processing json data. ${e.message}")
            cancel(true)
            listener.onError(e)
        }

        Log.d(TAG, ".doInBackground ends")
        return carList
    }

    override fun onPostExecute(result: ArrayList<Car>) {
        Log.d(TAG, "onPostExecute starts")
        super.onPostExecute(result)
        listener.onDataAvailable(result)
        Log.d(TAG, ".onPostExecute ends")
    }
}
</code>```

and here is the error I get when i run the code:

```<code>2020-02-14 16:42:16.483 26642-26684/com.example.wasit E/GetFlickrJsonData: doInBackground: Error processing json data. Value null at image of type org.json.JSONObject$1 cannot be converted to JSONObject
</code>```

答:
I found a way.

I had to wrap my "jsonMedia" in the following try catch:

```<code>val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: JSONException) {
                    null
                }
</code>```

Now my images that are null contain placeholders and the others work fine!

Body:
I am trying to fetch a JSONObject "image" that is sometimes a null value, so I set a try {} catch {} for my val jsonMedia in order to make it nullable but Im not sure if I'm missing something because it doesnt seem to work.

Whenever I comment out the jsonMedia my fetch works fine so I'll focus on just sharing the fetch of the "image" so the data I share doesnt get confusing.

1st. Ill show how the "image" is in the database and what I mean by "sometimes" has a null value
- null:

{
    "listCar": [
   {
    //other data
    "image": null,
    //other data
   }
 ]
}

when it contains an image:

{
    "listCar": [
   {
    //other data
     "image": {
                "path": "Upload/UploadCarMain/UploadCarMain-200-200/30032235992008220498istanbul_adalarCar195.jpg",
                "name": "30032235992008220498istanbul_adalarCar195.jpg"
            },
    //other data
   }
 ]
}

Now my fetch data was followed by a course I'm watching the only difference is the values of "image" in the database Im using arent like the course which did not contain null values in their image path

Now here is my "Car" class that is supposed to get the image:

class Car(other data, val image: String?, other data) {
    override fun toString(): String {
        return "Car(//other data, image='$image', //other data')"
    }
}

and here is my fetch code where I am trying to try {} catch(){} my "jsonMedia" image JSONOBject:

override fun doInBackground(vararg params: String?): ArrayList<Car> {
        Log.d(TAG, "doInBackground starts")

        val carList = ArrayList<Car>()
        try {
            val jsonData = JSONObject(params[0])
            val itemsArray = jsonData.getJSONArray("listCar")

            for (i in 0 until itemsArray.length()) {
                val jsonCar = itemsArray.getJSONObject(i)
                //other fetch data

                val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: IllegalArgumentException) {null}
                val photoURL = jsonMedia?.getString("path")

                val carObject = Car(other data, photoURL)

                carList.add(carObject)
                Log.d(TAG, ".doInBackground $carObject")
            }
        } catch (e: JSONException) {
            e.printStackTrace()
            Log.e(TAG, "doInBackground: Error processing json data. ${e.message}")
            cancel(true)
            listener.onError(e)
        }

        Log.d(TAG, ".doInBackground ends")
        return carList
    }

    override fun onPostExecute(result: ArrayList<Car>) {
        Log.d(TAG, "onPostExecute starts")
        super.onPostExecute(result)
        listener.onDataAvailable(result)
        Log.d(TAG, ".onPostExecute ends")
    }
}

and here is the error I get when i run the code:

2020-02-14 16:42:16.483 26642-26684/com.example.wasit E/GetFlickrJsonData: doInBackground: Error processing json data. Value null at image of type org.json.JSONObject$1 cannot be converted to JSONObject

Body:
I found a way.

I had to wrap my "jsonMedia" in the following try catch:

val jsonMedia: JSONObject? = try {jsonCar.getJSONObject("image")} catch (e: JSONException) {
                    null
                }

Now my images that are null contain placeholders and the others work fine!


问:
Send e-mail code is sending a blank file, unless the template is saved first
The code below is used in other files to send in effect a form for review and approval, but within this workbook for some reason I am getting blank files sent and the content added by the users is lost.  I know this isn't a code checking service, but I was wondering have I missed something with this - so I need to have the file 'saved' before it is attached to the e-mail?

```<code>    'Open e-mail and create a new message
Set OutlookApp = CreateObject("Outlook.Application")
Set OlObjects = OutlookApp.GetNamespace("MAPI")
Set newmsg = OutlookApp.CreateItem(olMailItem)
Dim SubmitEMail As String: SubmitEMail = ws.Range("U1").Value

' set the requirements for the new message
With newmsg
    .Recipients.Add SubmitEMail
    .CC = ws.Range("U2").Value
    .Subject = "New Concession request form submitted"
'use string defined above as the main body of the message
    .Body = "Dear " & Location & "," & vbLf & vbLf & "Please find attached: a new Concession request.  Please review and indicate Concession number, or provide details of amendments needed." & vbLf & vbLf & "Regards," & vbLf & vbLf & SenderName
    .Attachments.Add wb.FullName
    .Display
End With
End If

MsgBox "Please review the E-Mail, Adding any additional recipients as required. add your signature and send to complete the submission"
</code>```

The e-mail sending bit works perfectly, but the attachment is always blank, the data the user has added is lost (if the user saves the workbook first on their local station) the process works perfectly, but I am wanting to avoid asking them to so this - potentially creates 2 versions of a document where I only want one)

答:
If you debug your sub and use Debug.Print wb.FullName without saving wb - you'll get only "Book(n)" name. For your case I may suggest following solution:

Dim fileName As String

' save to temp directory
wb.SaveAs Environ("TEMP") & wb.Name & ".xlsx"

' save the full name to string variable
fileName = wb.FullName

' close the file in order to be able to delete it
wb.Close

'[attach the file
'.Attachments.Add fileName
' and do other stuff you need]

' delete temporary file
Kill fileName
```

This will also allow you to avoid asking users to save file and they even won't know about this.

Body:
The code below is used in other files to send in effect a form for review and approval, but within this workbook for some reason I am getting blank files sent and the content added by the users is lost.  I know this isn't a code checking service, but I was wondering have I missed something with this - so I need to have the file 'saved' before it is attached to the e-mail?

    'Open e-mail and create a new message
Set OutlookApp = CreateObject("Outlook.Application")
Set OlObjects = OutlookApp.GetNamespace("MAPI")
Set newmsg = OutlookApp.CreateItem(olMailItem)
Dim SubmitEMail As String: SubmitEMail = ws.Range("U1").Value

' set the requirements for the new message
With newmsg
    .Recipients.Add SubmitEMail
    .CC = ws.Range("U2").Value
    .Subject = "New Concession request form submitted"
'use string defined above as the main body of the message
    .Body = "Dear " & Location & "," & vbLf & vbLf & "Please find attached: a new Concession request.  Please review and indicate Concession number, or provide details of amendments needed." & vbLf & vbLf & "Regards," & vbLf & vbLf & SenderName
    .Attachments.Add wb.FullName
    .Display
End With
End If

MsgBox "Please review the E-Mail, Adding any additional recipients as required. add your signature and send to complete the submission"

The e-mail sending bit works perfectly, but the attachment is always blank, the data the user has added is lost (if the user saves the workbook first on their local station) the process works perfectly, but I am wanting to avoid asking them to so this - potentially creates 2 versions of a document where I only want one)

Body:
If you debug your sub and use Debug.Print wb.FullName without saving wb - you'll get only "Book(n)" name. For your case I may suggest following solution:

Dim fileName As String

' save to temp directory
wb.SaveAs Environ("TEMP") & wb.Name & ".xlsx"

' save the full name to string variable
fileName = wb.FullName

' close the file in order to be able to delete it
wb.Close

'[attach the file
'.Attachments.Add fileName
' and do other stuff you need]

' delete temporary file
Kill fileName

This will also allow you to avoid asking users to save file and they even won't know about this.


问:
Angular 8: value used in comonent.html is not the value in the component.ts (azure app service)
I got a really strange behavior in one of my angular app.
In a component.html, I want to display "UAT" and color the angular mat markups with a bright orange when in UAT, otherwise it should be blue and no mention of of UAT anywhere (aka PROD).

In local, no problem. when I deploy to azure nothing makes sense. So here is a bit of my code.

In my angular solution I got this env.json file that looks like this

```<code>{
"production": false,
"isTestEnvironment": false,
}
</code>```

In VSTS, I build the app once, and use it for all deployements. So in the UAT deployement, I replace the iSTestingEnvironment with "true", and ship it to azure.
for production deployement, I replace production with "true", isTestingEnvironment by "false", and ship it.

This env.json is extracted using something like this in the app.module.ts

```<code>const appInitializer = {
 provide: APP_INITIALIZER,
 useFactory: configFactory,
 deps: [AppConfig],
 multi: true
};
</code>```

and appInitializer is registered in the providers section.
And the AppConfig injectable is:

```<code>import {Injectable} from '@angular/core';
</code>```

import {HttpClient} from '@angular/common/http';

```<code>@Injectable()
export class AppConfig {
 public config: any;

 constructor(private http: HttpClient) {}

 public load() {
  return new Promise((resolve, reject) => {
   this.http.get('env.json').subscribe((p: string) => {
    this.config = p;
    resolve(true);
   });
  });
 }
}
</code>```

In my component's contructor, I start by getting the isTestingEnvironment:

```<code>this.isTestEnvironment = appConfig.config.isTestEnvironment;
</code>```

At this very moment, when I console.log the values, it is always correct:
In UAT, it's true.
In PROD, it's false.
And in local, it's watchever i put in the env.json, even when I hot change the value while ng serve is running.

When I look at the env.json that is deployed (using kudu/powershell), the  file is well formed with the right values across all environments.

So far so good.
But this code then breaks everything in the component.html:

```<code>    <h5 style="margin: auto;" *ngIf="isTestEnvironment">UAT</h5>
</code>```

In UAT and PROD, it always show up. regardless of the isTestingEnvrionment being true or false just instants before in the console log.
However it works ust fine in local debug using VSC (1.42.1) and node (v10.18.1).

At this point, Angular is telling true == false, so I'm at a complete loss.

I triple checked, at no point in the angular solution is the variable isTestingEnvironment set to a value anywhere else than in the env.json. So yeah, I'm either completely missing something obvious or something is really wrong in my code.

Any help will be greatly appreciated.

Thanks.

答:
So, I figured it out.

TLDR : It was caused by VSTS release task called "Azure App Service Deploy" that change the variables to string in the "File Transform & Variable Substitution Option" section.

After looking again at the deployed file I finaly saw that the file that is :

```<code>{
"isTestEnvironment": true,
}
</code>```

in my sources had became :

```<code>{
"isTestEnvironment": "true",
}
</code>```

on the azure server.
This caused every check we made against this supposedly boolean variable bogus, since a non-empty string is equivalent to true in js.

So I'm now using JSON.parse(myVariable) when I extract it from the env.json file.
I could reproduce it in local and tested it. It works.

To anyone using the same releas etask as we do, be careful that boolean will be changed into string. I checked our release pipeline variable and they are NOT declared with quotes around them; plain simple true/false values.

In any case, thank you guys for giving potential workarounds.

Body:
I got a really strange behavior in one of my angular app.
In a component.html, I want to display "UAT" and color the angular mat markups with a bright orange when in UAT, otherwise it should be blue and no mention of of UAT anywhere (aka PROD).

In local, no problem. when I deploy to azure nothing makes sense. So here is a bit of my code.

In my angular solution I got this env.json file that looks like this

{
"production": false,
"isTestEnvironment": false,
}

In VSTS, I build the app once, and use it for all deployements. So in the UAT deployement, I replace the iSTestingEnvironment with "true", and ship it to azure.
for production deployement, I replace production with "true", isTestingEnvironment by "false", and ship it.

This env.json is extracted using something like this in the app.module.ts

const appInitializer = {
 provide: APP_INITIALIZER,
 useFactory: configFactory,
 deps: [AppConfig],
 multi: true
};

and appInitializer is registered in the providers section.
And the AppConfig injectable is:

import {Injectable} from '@angular/core';

import {HttpClient} from '@angular/common/http';

@Injectable()
export class AppConfig {
 public config: any;

 constructor(private http: HttpClient) {}

 public load() {
  return new Promise((resolve, reject) => {
   this.http.get('env.json').subscribe((p: string) => {
    this.config = p;
    resolve(true);
   });
  });
 }
}

In my component's contructor, I start by getting the isTestingEnvironment:

this.isTestEnvironment = appConfig.config.isTestEnvironment;

At this very moment, when I console.log the values, it is always correct:
In UAT, it's true.
In PROD, it's false.
And in local, it's watchever i put in the env.json, even when I hot change the value while ng serve is running.

When I look at the env.json that is deployed (using kudu/powershell), the  file is well formed with the right values across all environments.

So far so good.
But this code then breaks everything in the component.html:

UAT

In UAT and PROD, it always show up. regardless of the isTestingEnvrionment being true or false just instants before in the console log.
However it works ust fine in local debug using VSC (1.42.1) and node (v10.18.1).

At this point, Angular is telling true == false, so I'm at a complete loss.

I triple checked, at no point in the angular solution is the variable isTestingEnvironment set to a value anywhere else than in the env.json. So yeah, I'm either completely missing something obvious or something is really wrong in my code.

Any help will be greatly appreciated.

Thanks.

Body:
So, I figured it out.

TLDR : It was caused by VSTS release task called "Azure App Service Deploy" that change the variables to string in the "File Transform & Variable Substitution Option" section.

After looking again at the deployed file I finaly saw that the file that is :

{
"isTestEnvironment": true,
}

in my sources had became :

{
"isTestEnvironment": "true",
}

on the azure server.
This caused every check we made against this supposedly boolean variable bogus, since a non-empty string is equivalent to true in js.

So I'm now using JSON.parse(myVariable) when I extract it from the env.json file.
I could reproduce it in local and tested it. It works.

To anyone using the same releas etask as we do, be careful that boolean will be changed into string. I checked our release pipeline variable and they are NOT declared with quotes around them; plain simple true/false values.

In any case, thank you guys for giving potential workarounds.


问:
Create json file for many to many fields in django
I need to create json to insert data using inside both models, for tags I have created the json but I don't get how to create json for Question model to insert data directly from it.

model.py

```<code>class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

class Question(models.Model):
    name = models.CharField(max_length=255)
    Tag_name = models.ManyToManyField(Tag)
</code>```

Tag json look like:

```<code>[
  { "name": "a" },
  { "name": "b" }
]
</code>```

Since Tag_name is many to many field it create 2 tables in sqlite but I want to add data using one json only.How to make a json so that data in both table get inserted ?

答:
Let suppose you have read json file and now you want to store that data to db</p>

```<code>json_data = get_json_data() # write code to read json here

tag_list = []
for tag in json_data:
    tag_list.append(Tag(**tag))
added_tags = Tag.objects.bulk_create(tag_list)
added_tags = [t.id for t in added_tags]

question_object = # write code to get specific question object in which you want to add this
question_object.Tag_name.add(*added_tags)
</code>```

Body:
I need to create json to insert data using inside both models, for tags I have created the json but I don't get how to create json for Question model to insert data directly from it.

model.py

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

class Question(models.Model):
    name = models.CharField(max_length=255)
    Tag_name = models.ManyToManyField(Tag)

Tag json look like:

[
  { "name": "a" },
  { "name": "b" }
]

Since Tag_name is many to many field it create 2 tables in sqlite but I want to add data using one json only.How to make a json so that data in both table get inserted ?

Body:
Let suppose you have read json file and now you want to store that data to db

json_data = get_json_data() # write code to read json here

tag_list = []
for tag in json_data:
    tag_list.append(Tag(**tag))
added_tags = Tag.objects.bulk_create(tag_list)
added_tags = [t.id for t in added_tags]

question_object = # write code to get specific question object in which you want to add this
question_object.Tag_name.add(*added_tags)


问:
How do I generate array values in Vue.js and show them?
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template></code>```

答:
Change your code like this:</p>

```<code>export default {
    name:'FrontPage',
    data: function(){
        return {
            player: {
                'ap': this.ngen(),
                'df': this.ngen(),
                'iq': this.ngen(),
            }
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template>
</code>```

Body:
I only just started learning vue, trying to practice

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: [
                { 'ap': ngen() },
                { 'df': ngen() },
                { 'iq': ngen() },
            ]
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>

 {{ player.ap }}

 {{ player.df }}

 {{ player.iq }}

</template>

Body:
Change your code like this:

export default {
    name:'FrontPage',
    data: function(){
        return {
            player: {
                'ap': this.ngen(),
                'df': this.ngen(),
                'iq': this.ngen(),
            }
        }
    },
    methods: {
        ngen: function() {
            return Math.random()
        }
    }
}

<template>
    <div>
        <h2> {{ player.ap }} </h2>
        <h2> {{ player.df }} </h2>
        <h2> {{ player.iq }} </h2>
    </div>
</template>


问:
Could not fetch value from key inside list of dictionaries converted from BeautifulSoup ResultSet
I used BeautifulSoup to fetch a string representation of a list from https://api.huobi.pro/v1/common/symbols

Part of the string in the url looks like this:

```<code> {"status":"ok","data":[{"base-currency":"ont","quote-currency":"btc","price-precision":8,"amount-precision":4,"symbol-partition":"innovation","symbol":"ontbtc","state":"online","value-precision":8,"min-order-amt":0.01,"max-order-amt":100000,"min-order-value":0.0001,"leverage-ratio":2}, .. ]

</code>```

This is how I scraped it into a ResultSet:

```<code>import requests
from bs4 import BeautifulSoup
import re

url = 'https://api.huobi.pro/v1/common/symbols'
res = requests.get(url)
html_page = res.content

soup = BeautifulSoup(html_page, 'html.parser',from_encoding='utf-8')
text = soup.find_all(text=True)
</code>```

I then tried to convert the ResultSet into a list

```<code>huobiList = list(text)
</code>```

Afterwards, I tried to print values from the symbol key in the list:

```<code>print([d[`symbol`] for d in huobiList])
</code>```

but got this error:

```<code>print([d['symbol'] for d in huobiList])
TypeError: string indices must be integers
</code>```

When I tried printing the key using indices, it reads the key as letters instead of reading the entire key name:

```<code>>>>print([d[0] for d in huobiList])
[u'{']
</code>```

答:
Actually there are some multiple problems here

symbol keys are inside the object you are trying to print, but below data key

And before that you have to cast you string to dict, using json.loads()

Check this code:

```<code>import requests
from bs4 import BeautifulSoup
import re
import json

url = 'https://api.huobi.pro/v1/common/symbols'
res = requests.get(url)
html_page = res.content

soup = BeautifulSoup(html_page, 'html.parser',from_encoding='utf-8')
text = soup.find_all(text=True)
huobiList = list(text)
datas = [json.loads(d).get('data') for d in huobiList]
for data in datas:
    print([d.get('symbol') for d in data])
</code>```

RESULTS

```<code>['bfteth', 'kncbtc', 'nexoeth', 'mexbtc', 'bsvhusd', 'paybtc', 'icxeth', 'aebtc', 'bixeth', 'forusdt', 'itcusdt', 'abtbtc', 'btgbtc', 'eosht', 'hitbtc', 'dogeusdt', 'yeebtc', 'buteth', 'thetausdt', 'etneth', 'akrousdt', 'acteth', 'egtusdt', 'pcbtc', 'astbtc', 'oneht', 'renusdt', 'shebtc', 'naseth', 'aidoceth', 'bhdht', 'steemeth', 'sspeth', 'neobtc', 'ostbtc', 'qtumusdt', 'dgdbtc', 'idtbtc', 'btteth', 'venbtc', 'eoseth', 'dtausdt', 'ncashbtc', 'xtzbtc', 'ltcht', 'rteeth', 'utketh', 'iostusdt', 'zlabtc', 'nodeusdt', 'gtcbtc', 'bsvbtc', 'cnneth', 'scbtc', 'venusdt', 'edubtc', 'neousdt', 'ruffbtc', 'xmreth', 'crobtc', 'btseth', 'iostbtc', 'mcobtc', 'yccbtc', 'bchbtc', 'bsvusdt', 'itcbtc', 'cvcoinbtc', 'xmrusdt', 'xtzusdt', 'qtumbtc', 'cnnsbtc', 'thetabtc', 'dogebtc', 'gasbtc', 'bcveth', 'ruffusdt', 'skmbtc', 'topceth', 'reneth', 'uceth', 'bixusdt', 'gnxbtc', 'zjlteth', 'btchusd', 'gtusdt', 'wxtusdt', 'btcusdt', 'ctxceth', 'seelebtc', 'sceth', 'edueth', 'tnteth', 'hptbtc', 'ogobtc', 'rdnbtc', 'egccbtc', 'ontusdt', 'datbtc', 'daceth', 'nulseth', 'cvcoineth', 'dtaeth', 'lymbtc', 'grsbtc', 'idteth', 'xvgeth', 'dgdeth', 'atombtc', 'getbtc', 'propybtc', 'irisbtc', 'adaeth', 'btmeth', 'hitusdt', 'engeth', 'meeteth', 'wprbtc', 'ontbtc', 'cdcbtc', 'ogousdt', 'mdsusdt', 'wavesusdt', 'xrpbtc', 'mtbtc', 'bcdbtc', 'blzbtc', 'maneth', 'quneth', 'nexobtc', 'gtbtc', 'ftibtc', 'ektusdt', 'zrxbtc', 'bkbtbtc', 'ekobtc', 'wavesbtc', 'gxcbtc', 'covabtc', 'toseth', 'dbcbtc', 'elfeth', 'icxbtc', 'sspbtc', 'swftcbtc', 'bifibtc', 'ethbtc', 'storjbtc', 'bftbtc', 'oneusdt', 'aeeth', 'cvceth', 'wtceth', 'eoshusd', 'payeth', 'pvtht', 'eosusdt', 'lxtusdt', 'bt1btc', 'newbtc', 'creht', 'xmxbtc', 'ckbusdt', 'docketh', 'hptusdt', 'mtlbtc', 'iostht', 'mdsbtc', 'zileth', 'npxseth', 'wiccbtc', 'hiteth', 'btmusdt', 'akroht', 'iosteth', 'gveeth', 'onebtc', 'emht', 'cvntbtc', 'ckbbtc', 'newusdt', 'gntbtc', 'eosbtc', 'chatbtc', 'etcbtc', 'engbtc', 'stkbtc', 'lskbtc', 'rtebtc', 'loombtc', 'sbtcbtc', 'qtumeth', 'trioeth', 'bixbtc', 'mtneth', 'xvgbtc', 'storjusdt', 'vidyht', 'srnbtc', 'skmusdt', 'veneth', 'mexeth', 'gaseth', 'vsysht', 'xzceth', 'cnnbtc', 'rsrht', 'xtzeth', 'pnteth', 'crousdt', 'itceth', 'bateth', 'zenbtc', 'fsnbtc', 'etchusd', 'mtxbtc', 'ncceth', 'qashbtc', 'rbtcbtc', 'fttbtc', 'ctxcbtc', 'kanusdt', 'egtbtc', 'nulsbtc', 'elfusdt', 'topcbtc', 'ltcusdt', 'wiccusdt', 'covaeth', 'smtbtc', 'elaeth', 'gtht', 'thetaeth', 'btttrx', 'ltchusd', 'ekoeth', 'dtabtc', 'letbtc', 'wtcusdt', 'nodeht', 'forbtc', 'hceth', 'gnxeth', 'kcashbtc', 'wpreth', 'gsceth', 'uipbtc', 'atpusdt', '18cbtc', 'aacbtc', 'bkbteth', 'blzeth', 'nulsusdt', 'rcneth', 'gtceth', 'omgusdt', 'lxtbtc', 'paxhusd', 'wxtht', 'ugasbtc', 'bchht', 'polybtc', 'btmbtc', 'soceth', 'hoteth', 'bhdusdt', 'atometh', 'letusdt', 'egcceth', 'atpbtc', 'waxpeth', 'ctxcusdt', 'fttusdt', 'lambbtc', 'xembtc', 'bhdbtc', 'ltcbtc', 'bcvbtc', 'tntbtc', 'embtc', 'nknusdt', 'zilbtc', 'wicceth', 'vidyusdt', 'pvtusdt', 'ardrbtc', 'ttusdt', 'dgbbtc', 'xlmeth', 'dashbtc', 'vetusdt', 'boxeth', 'kmdbtc', 'htbtc', 'waxpbtc', 'wtcbtc', 'swftceth', 'batusdt', 'ckbht', 'lambusdt', 'uipusdt', 'elausdt', 'xzcbtc', 'xemusdt', 'npxsbtc', 'smtusdt', 'adxeth', 'rsrbtc', 'dcreth', 'vsysbtc', 'kanbtc', 'loometh', 'trxusdt', 'elfbtc', 'mtnbtc', 'dbceth', 'omgbtc', 'linkusdt', 'lsketh', 'mxcbtc', 'musketh', 'manausdt', 'lxteth', 'uuueth', 'mxbtc', 'rsrusdt', 'skmht', 'socbtc', 'qspeth', 'trxbtc', 'gnteth', 'paibtc', 'gvebtc', 'srneth', 'dockbtc', 'usdchusd', 'evxbtc', 'hptht', 'mxusdt', 'paiusdt', 'qasheth', 'fsnusdt', 'gntusdt', 'topht', 'cvnteth', 'mtxeth', 'emusdt', 'xrpht', 'salteth', 'vetbtc', 'newht', 'rcccbtc', 'etcusdt', 'stketh', 'xzcusdt', 'ocneth', 'arpaht', 'leteth', 'smteth', 'vsysusdt', 'dockusdt', 'nccbtc', 'triobtc', 'nanobtc', 'zeneth', 'tnbeth', 'gscbtc', 'reqbtc', 'manabtc', 'lbaeth', 'portalbtc', 'lambeth', 'faireth', 'ugaseth', 'dashhusd', 'ethusdt', 'socusdt', 'croht', 'lolht', 'appcbtc', 'aaceth', 'xlmusdt', 'dashusdt', 'ethhusd', 'topusdt', 'wanbtc', 'batbtc', 'hcusdt', 'elabtc', 'fttht', 'bhtht', 'evxeth', 'zilusdt', 'htusdt', 'powrbtc', 'cnnsht', 'datxeth', 'hthusd', 'sncbtc', 'tusdhusd', 'phxbtc', 'linkbtc', 'cmteth', 'topbtc', 'uipeth', 'iicbtc', 'ektbtc', 'nknbtc', 'ttht', 'pvtbtc', 'algoeth', 'pceth', 'omgeth', 'luneth', 'adxbtc', 'iotabtc', 'zrxusdt', 'iotausdt', 'ocnbtc', 'sheeth', 'lbausdt', 'dgbeth', 'mxht', 'kaneth', 'aidocbtc', 'sntbtc', 'atomusdt', 'etnbtc', 'forht', 'xlmbtc', 'muskbtc', 'mtht', 'saltbtc', 'cmtusdt', 'gxcusdt', 'irisusdt', 'atpht', 'xrphusd', 'btsbtc', 'nknht', 'nanousdt', 'uuubtc', 'arpabtc', 'knceth', 'wxtbtc', 'xrpusdt', 'hotbtc', 'ardreth', 'polyeth', 'snceth', 'lambht', 'abteth', 'yeeeth', 'butbtc', 'hteth', 'kmdeth', 'arpausdt', 'bchhusd', 'cmtbtc', 'rcnbtc', 'asteth', 'bchusdt', 'ncasheth', 'nasusdt', 'qspbtc', 'dcrbtc', 'zecusdt', 'btsusdt', 'zechusd', 'bcxbtc', 'fsnht', 'paieth', '18ceth', 'uuuusdt', 'adabtc', 'bttusdt', 'dogeeth', 'ycceth', 'kcasheth', 'rccceth', 'egtht', 'steembtc', 'zlaeth', 'bt2btc', 'sntusdt', 'zecbtc', 'hcbtc', 'usdthusd', 'seeleusdt', 'ruffeth', 'nasbtc', 'bttbtc', 'seeleeth', 'reqeth', 'ocnusdt', 'lunbtc', 'veteth', 'kcashht', 'dateth', 'nanoeth', 'appceth', 'nodebtc', 'geteth', 'hb10usdt', 'zjltbtc', 'ucbtc', 'iotaeth', 'zrxeth', 'dcrusdt', 'ftieth', 'etcht', 'lymeth', 'xmrbtc', 'cvcusdt', 'crebtc', 'gxceth', 'iriseth', 'chateth', 'cnnsusdt', 'aeusdt', 'mcoeth', 'linketh', 'portaleth', 'waveseth', 'pntbtc', 'ttbtc', 'utkbtc', 'meetbtc', 'adausdt', 'fairbtc', 'actusdt', 'osteth', 'vidybtc', 'manaeth', 'cdceth', 'steemusdt', 'rdneth', 'qunbtc', 'mdseth', 'mteth', 'actbtc', 'bhtbtc', 'onteth', 'datxbtc', 'powreth', 'manbtc', 'trxeth', 'lolusdt', 'algobtc', 'lbabtc', 'propyeth', 'xmxeth', 'ogoht', 'waneth', 'tnbbtc', 'renbtc', 'bhtusdt', 'lolbtc', 'tosbtc', 'ekteth', 'dacbtc', 'creusdt', 'dashht', 'grseth', 'algousdt', 'boxbtc', 'cvcbtc', 'akrobtc', 'iiceth']
</code>```

Body:
I used BeautifulSoup to fetch a string representation of a list from https://api.huobi.pro/v1/common/symbols

Part of the string in the url looks like this:

 {"status":"ok","data":[{"base-currency":"ont","quote-currency":"btc","price-precision":8,"amount-precision":4,"symbol-partition":"innovation","symbol":"ontbtc","state":"online","value-precision":8,"min-order-amt":0.01,"max-order-amt":100000,"min-order-value":0.0001,"leverage-ratio":2}, .. ]

This is how I scraped it into a ResultSet:

import requests
from bs4 import BeautifulSoup
import re

url = 'https://api.huobi.pro/v1/common/symbols'
res = requests.get(url)
html_page = res.content

soup = BeautifulSoup(html_page, 'html.parser',from_encoding='utf-8')
text = soup.find_all(text=True)

I then tried to convert the ResultSet into a list

huobiList = list(text)

Afterwards, I tried to print values from the symbol key in the list:

print([d[`symbol`] for d in huobiList])

but got this error:

print([d['symbol'] for d in huobiList])
TypeError: string indices must be integers

When I tried printing the key using indices, it reads the key as letters instead of reading the entire key name:

>>>print([d[0] for d in huobiList])
[u'{']

Body:
Actually there are some multiple problems here

symbol keys are inside the object you are trying to print, but below data key

And before that you have to cast you string to dict, using json.loads()

Check this code:

import requests
from bs4 import BeautifulSoup
import re
import json

url = 'https://api.huobi.pro/v1/common/symbols'
res = requests.get(url)
html_page = res.content

soup = BeautifulSoup(html_page, 'html.parser',from_encoding='utf-8')
text = soup.find_all(text=True)
huobiList = list(text)
datas = [json.loads(d).get('data') for d in huobiList]
for data in datas:
    print([d.get('symbol') for d in data])

RESULTS

['bfteth', 'kncbtc', 'nexoeth', 'mexbtc', 'bsvhusd', 'paybtc', 'icxeth', 'aebtc', 'bixeth', 'forusdt', 'itcusdt', 'abtbtc', 'btgbtc', 'eosht', 'hitbtc', 'dogeusdt', 'yeebtc', 'buteth', 'thetausdt', 'etneth', 'akrousdt', 'acteth', 'egtusdt', 'pcbtc', 'astbtc', 'oneht', 'renusdt', 'shebtc', 'naseth', 'aidoceth', 'bhdht', 'steemeth', 'sspeth', 'neobtc', 'ostbtc', 'qtumusdt', 'dgdbtc', 'idtbtc', 'btteth', 'venbtc', 'eoseth', 'dtausdt', 'ncashbtc', 'xtzbtc', 'ltcht', 'rteeth', 'utketh', 'iostusdt', 'zlabtc', 'nodeusdt', 'gtcbtc', 'bsvbtc', 'cnneth', 'scbtc', 'venusdt', 'edubtc', 'neousdt', 'ruffbtc', 'xmreth', 'crobtc', 'btseth', 'iostbtc', 'mcobtc', 'yccbtc', 'bchbtc', 'bsvusdt', 'itcbtc', 'cvcoinbtc', 'xmrusdt', 'xtzusdt', 'qtumbtc', 'cnnsbtc', 'thetabtc', 'dogebtc', 'gasbtc', 'bcveth', 'ruffusdt', 'skmbtc', 'topceth', 'reneth', 'uceth', 'bixusdt', 'gnxbtc', 'zjlteth', 'btchusd', 'gtusdt', 'wxtusdt', 'btcusdt', 'ctxceth', 'seelebtc', 'sceth', 'edueth', 'tnteth', 'hptbtc', 'ogobtc', 'rdnbtc', 'egccbtc', 'ontusdt', 'datbtc', 'daceth', 'nulseth', 'cvcoineth', 'dtaeth', 'lymbtc', 'grsbtc', 'idteth', 'xvgeth', 'dgdeth', 'atombtc', 'getbtc', 'propybtc', 'irisbtc', 'adaeth', 'btmeth', 'hitusdt', 'engeth', 'meeteth', 'wprbtc', 'ontbtc', 'cdcbtc', 'ogousdt', 'mdsusdt', 'wavesusdt', 'xrpbtc', 'mtbtc', 'bcdbtc', 'blzbtc', 'maneth', 'quneth', 'nexobtc', 'gtbtc', 'ftibtc', 'ektusdt', 'zrxbtc', 'bkbtbtc', 'ekobtc', 'wavesbtc', 'gxcbtc', 'covabtc', 'toseth', 'dbcbtc', 'elfeth', 'icxbtc', 'sspbtc', 'swftcbtc', 'bifibtc', 'ethbtc', 'storjbtc', 'bftbtc', 'oneusdt', 'aeeth', 'cvceth', 'wtceth', 'eoshusd', 'payeth', 'pvtht', 'eosusdt', 'lxtusdt', 'bt1btc', 'newbtc', 'creht', 'xmxbtc', 'ckbusdt', 'docketh', 'hptusdt', 'mtlbtc', 'iostht', 'mdsbtc', 'zileth', 'npxseth', 'wiccbtc', 'hiteth', 'btmusdt', 'akroht', 'iosteth', 'gveeth', 'onebtc', 'emht', 'cvntbtc', 'ckbbtc', 'newusdt', 'gntbtc', 'eosbtc', 'chatbtc', 'etcbtc', 'engbtc', 'stkbtc', 'lskbtc', 'rtebtc', 'loombtc', 'sbtcbtc', 'qtumeth', 'trioeth', 'bixbtc', 'mtneth', 'xvgbtc', 'storjusdt', 'vidyht', 'srnbtc', 'skmusdt', 'veneth', 'mexeth', 'gaseth', 'vsysht', 'xzceth', 'cnnbtc', 'rsrht', 'xtzeth', 'pnteth', 'crousdt', 'itceth', 'bateth', 'zenbtc', 'fsnbtc', 'etchusd', 'mtxbtc', 'ncceth', 'qashbtc', 'rbtcbtc', 'fttbtc', 'ctxcbtc', 'kanusdt', 'egtbtc', 'nulsbtc', 'elfusdt', 'topcbtc', 'ltcusdt', 'wiccusdt', 'covaeth', 'smtbtc', 'elaeth', 'gtht', 'thetaeth', 'btttrx', 'ltchusd', 'ekoeth', 'dtabtc', 'letbtc', 'wtcusdt', 'nodeht', 'forbtc', 'hceth', 'gnxeth', 'kcashbtc', 'wpreth', 'gsceth', 'uipbtc', 'atpusdt', '18cbtc', 'aacbtc', 'bkbteth', 'blzeth', 'nulsusdt', 'rcneth', 'gtceth', 'omgusdt', 'lxtbtc', 'paxhusd', 'wxtht', 'ugasbtc', 'bchht', 'polybtc', 'btmbtc', 'soceth', 'hoteth', 'bhdusdt', 'atometh', 'letusdt', 'egcceth', 'atpbtc', 'waxpeth', 'ctxcusdt', 'fttusdt', 'lambbtc', 'xembtc', 'bhdbtc', 'ltcbtc', 'bcvbtc', 'tntbtc', 'embtc', 'nknusdt', 'zilbtc', 'wicceth', 'vidyusdt', 'pvtusdt', 'ardrbtc', 'ttusdt', 'dgbbtc', 'xlmeth', 'dashbtc', 'vetusdt', 'boxeth', 'kmdbtc', 'htbtc', 'waxpbtc', 'wtcbtc', 'swftceth', 'batusdt', 'ckbht', 'lambusdt', 'uipusdt', 'elausdt', 'xzcbtc', 'xemusdt', 'npxsbtc', 'smtusdt', 'adxeth', 'rsrbtc', 'dcreth', 'vsysbtc', 'kanbtc', 'loometh', 'trxusdt', 'elfbtc', 'mtnbtc', 'dbceth', 'omgbtc', 'linkusdt', 'lsketh', 'mxcbtc', 'musketh', 'manausdt', 'lxteth', 'uuueth', 'mxbtc', 'rsrusdt', 'skmht', 'socbtc', 'qspeth', 'trxbtc', 'gnteth', 'paibtc', 'gvebtc', 'srneth', 'dockbtc', 'usdchusd', 'evxbtc', 'hptht', 'mxusdt', 'paiusdt', 'qasheth', 'fsnusdt', 'gntusdt', 'topht', 'cvnteth', 'mtxeth', 'emusdt', 'xrpht', 'salteth', 'vetbtc', 'newht', 'rcccbtc', 'etcusdt', 'stketh', 'xzcusdt', 'ocneth', 'arpaht', 'leteth', 'smteth', 'vsysusdt', 'dockusdt', 'nccbtc', 'triobtc', 'nanobtc', 'zeneth', 'tnbeth', 'gscbtc', 'reqbtc', 'manabtc', 'lbaeth', 'portalbtc', 'lambeth', 'faireth', 'ugaseth', 'dashhusd', 'ethusdt', 'socusdt', 'croht', 'lolht', 'appcbtc', 'aaceth', 'xlmusdt', 'dashusdt', 'ethhusd', 'topusdt', 'wanbtc', 'batbtc', 'hcusdt', 'elabtc', 'fttht', 'bhtht', 'evxeth', 'zilusdt', 'htusdt', 'powrbtc', 'cnnsht', 'datxeth', 'hthusd', 'sncbtc', 'tusdhusd', 'phxbtc', 'linkbtc', 'cmteth', 'topbtc', 'uipeth', 'iicbtc', 'ektbtc', 'nknbtc', 'ttht', 'pvtbtc', 'algoeth', 'pceth', 'omgeth', 'luneth', 'adxbtc', 'iotabtc', 'zrxusdt', 'iotausdt', 'ocnbtc', 'sheeth', 'lbausdt', 'dgbeth', 'mxht', 'kaneth', 'aidocbtc', 'sntbtc', 'atomusdt', 'etnbtc', 'forht', 'xlmbtc', 'muskbtc', 'mtht', 'saltbtc', 'cmtusdt', 'gxcusdt', 'irisusdt', 'atpht', 'xrphusd', 'btsbtc', 'nknht', 'nanousdt', 'uuubtc', 'arpabtc', 'knceth', 'wxtbtc', 'xrpusdt', 'hotbtc', 'ardreth', 'polyeth', 'snceth', 'lambht', 'abteth', 'yeeeth', 'butbtc', 'hteth', 'kmdeth', 'arpausdt', 'bchhusd', 'cmtbtc', 'rcnbtc', 'asteth', 'bchusdt', 'ncasheth', 'nasusdt', 'qspbtc', 'dcrbtc', 'zecusdt', 'btsusdt', 'zechusd', 'bcxbtc', 'fsnht', 'paieth', '18ceth', 'uuuusdt', 'adabtc', 'bttusdt', 'dogeeth', 'ycceth', 'kcasheth', 'rccceth', 'egtht', 'steembtc', 'zlaeth', 'bt2btc', 'sntusdt', 'zecbtc', 'hcbtc', 'usdthusd', 'seeleusdt', 'ruffeth', 'nasbtc', 'bttbtc', 'seeleeth', 'reqeth', 'ocnusdt', 'lunbtc', 'veteth', 'kcashht', 'dateth', 'nanoeth', 'appceth', 'nodebtc', 'geteth', 'hb10usdt', 'zjltbtc', 'ucbtc', 'iotaeth', 'zrxeth', 'dcrusdt', 'ftieth', 'etcht', 'lymeth', 'xmrbtc', 'cvcusdt', 'crebtc', 'gxceth', 'iriseth', 'chateth', 'cnnsusdt', 'aeusdt', 'mcoeth', 'linketh', 'portaleth', 'waveseth', 'pntbtc', 'ttbtc', 'utkbtc', 'meetbtc', 'adausdt', 'fairbtc', 'actusdt', 'osteth', 'vidybtc', 'manaeth', 'cdceth', 'steemusdt', 'rdneth', 'qunbtc', 'mdseth', 'mteth', 'actbtc', 'bhtbtc', 'onteth', 'datxbtc', 'powreth', 'manbtc', 'trxeth', 'lolusdt', 'algobtc', 'lbabtc', 'propyeth', 'xmxeth', 'ogoht', 'waneth', 'tnbbtc', 'renbtc', 'bhtusdt', 'lolbtc', 'tosbtc', 'ekteth', 'dacbtc', 'creusdt', 'dashht', 'grseth', 'algousdt', 'boxbtc', 'cvcbtc', 'akrobtc', 'iiceth']


问:
ValueError: "color kwarg must have one color per dataset"
I have a dataset regarding some used cars from eBay, which I tried to plot after I edited the dataset as follows:

```<code>import pandas as pd

df = pd.read_csv("./autos.csv.bz2", encoding = "iso8859-1")
df = df.drop(["dateCrawled", "abtest", "dateCreated", "nrOfPictures", "lastSeen", "postalCode", "seller", "offerType"], axis = 1)

import numpy as np

df["monthOfRegistration"] = np.where(df["monthOfRegistration"] == 0, 6, df["monthOfRegistration"])

df["registration"] = df["yearOfRegistration"] + (df["monthOfRegistration"] - 1) / 12

df = df.drop(["yearOfRegistration", "monthOfRegistration"], axis = 1)

df = df.drop(df[df["price"] == 0].index)
df = df.drop(df[df["powerPS"] == 0].index)

print(df["notRepairedDamage"].unique())
print(df["notRepairedDamage"])

df["notRepairedDamage"] = np.where(df["notRepairedDamage"] == "ja", 1, df["notRepairedDamage"])
df["notRepairedDamage"] = np.where(df["notRepairedDamage"] == "nein", 0, df["notRepairedDamage"])

df = df[df["notRepairedDamage"].notnull()]
</code>```

I tried to plot the data with matplotlib using seaborn.pairplot but got the following error:

ValueError: color kwarg must have one color per dataset

I do only get the plots with the relative frequencies of the first 3 lines, all the other graphs are empty, also relative frequencies in line 4 and 5.

Matplotlib seaborn, example image

```<code>df = df[(df["price"] < 100000) & (df["powerPS"] < 2000)

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

import seaborn as sns

g = sns.pairplot(df)
</code>```

I assume that something did go wrong when I edited my dataset.
Is there anyone who could help me? That would be great! Thank you very much!

答:
The problem comes from the fact that pairplot only accepts some pandas types in the PairGrid: float or int, but not Object or Int64 for exemple (at least for some versions of matplotlib and/or seaborn: 3.0.3 and 0.9.0 respectivly generates that error).

Using .astype('float') to modify the concerned series before plotting in the following exemple solves the problem as a.One is set to Int64 and a.Two is initially an Object type:

```<code>a = pd.DataFrame()
a['One'] = [1, 3, 3, 2, 1]
a['One']=a['One'].astype('Int64')
a['Two'] = ['yes', 'yes', 'no', 'yes', 'no']
a['Two'] = np.where(a['Two'] == 'yes', 1, a['Two'])
a['Two'] = np.where(a['Two'] == 'no', 0, a['Two'])
a['One']=a['One'].astype('int')
a['Two']=a['Two'].astype('int')
sns.pairplot(a)
plt.show()
</code>```

Remark that if you have some NaN in your dataframe, float is the only option as Int64 accepts missing values but not the Int type.

Body:
I have a dataset regarding some used cars from eBay, which I tried to plot after I edited the dataset as follows:

import pandas as pd

df = pd.read_csv("./autos.csv.bz2", encoding = "iso8859-1")
df = df.drop(["dateCrawled", "abtest", "dateCreated", "nrOfPictures", "lastSeen", "postalCode", "seller", "offerType"], axis = 1)

import numpy as np

df["monthOfRegistration"] = np.where(df["monthOfRegistration"] == 0, 6, df["monthOfRegistration"])

df["registration"] = df["yearOfRegistration"] + (df["monthOfRegistration"] - 1) / 12

df = df.drop(["yearOfRegistration", "monthOfRegistration"], axis = 1)

df = df.drop(df[df["price"] == 0].index)
df = df.drop(df[df["powerPS"] == 0].index)

print(df["notRepairedDamage"].unique())
print(df["notRepairedDamage"])

df["notRepairedDamage"] = np.where(df["notRepairedDamage"] == "ja", 1, df["notRepairedDamage"])
df["notRepairedDamage"] = np.where(df["notRepairedDamage"] == "nein", 0, df["notRepairedDamage"])

df = df[df["notRepairedDamage"].notnull()]

I tried to plot the data with matplotlib using seaborn.pairplot but got the following error:

ValueError: color kwarg must have one color per dataset

I do only get the plots with the relative frequencies of the first 3 lines, all the other graphs are empty, also relative frequencies in line 4 and 5.

Matplotlib seaborn, example image

df = df[(df["price"] < 100000) & (df["powerPS"] < 2000)

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

import seaborn as sns

g = sns.pairplot(df)

I assume that something did go wrong when I edited my dataset.
Is there anyone who could help me? That would be great! Thank you very much!

Body:
The problem comes from the fact that pairplot only accepts some pandas types in the PairGrid: float or int, but not Object or Int64 for exemple (at least for some versions of matplotlib and/or seaborn: 3.0.3 and 0.9.0 respectivly generates that error).

Using .astype('float') to modify the concerned series before plotting in the following exemple solves the problem as a.One is set to Int64 and a.Two is initially an Object type:

a = pd.DataFrame()
a['One'] = [1, 3, 3, 2, 1]
a['One']=a['One'].astype('Int64')
a['Two'] = ['yes', 'yes', 'no', 'yes', 'no']
a['Two'] = np.where(a['Two'] == 'yes', 1, a['Two'])
a['Two'] = np.where(a['Two'] == 'no', 0, a['Two'])
a['One']=a['One'].astype('int')
a['Two']=a['Two'].astype('int')
sns.pairplot(a)
plt.show()

Remark that if you have some NaN in your dataframe, float is the only option as Int64 accepts missing values but not the Int type.


问:
Is there anyway to catch javascript 'hover' event with chrome console?
So, I have many lines of Javascript codes which is quite unorganized right now.
One function among many function is doing some action on 'hover' event, however I cannot find it by just looking through the codes.

I am wondering if it is possible to catch which function cause on hover event with google chrome browser's 'Console.log'

答: If you are looking for a way to figure out which function is handling specific events using Chrome, you can look at the "event listeners" tab at the bottom right of the "Elements" tab when you do Wrench --> Tools --> Developer Tools in Chrome. That tab should list all the functions that are handling event on the selected node. </p>


问:
How to insert font awesome in a liferay's custom theme?
How can I insert and use font awesome 4 in a Liferay's 7.2 custom theme?

I saw in Liferay's portal dev that by selecting: Control Panel → Configuration → System Settings → Third Party, I could find a Font Awesome option, but that option is not in my panel.

Also in this tutorial it is explained how to use font awesome 3, but nothing about version 4.

答:
By default, Liferay use Font Awesome v3.2.1. I don't know if there is a way to change it.

If you want to use another version, then I suggest to add it in package.json file of your theme. It'll be the fastest and efficient way to add/customize the dependencies you want.

If you are okay with this solution, just don't forget to disable Font Awesome v3.2.1 to improve performance of your portal.


问:
Response Body Bad chunk header - I/O error on GET request
Setup - 2 Rest services, spring-boot 2.x, embedded tomcat 8.x

Service A calls Service B using restTemplate, in a test loop running for 300 times, on every 100th interval within the loop throws an exception "Bad chunk header exception".

Enabled debugging (<logger name="org.apache.http" level="DEBUG"/>), following is the analysis:

First 99 iterations - Request/Response headers have Connection: keep-alive and body/stream ends with carriage return \r\n

Request Headers

```<code>"GET /rest/customers/1000000030 HTTP/1.1[\r][\n]"
"Accept-Language: en-us[\r][\n]"
"Accept: application/json[\r][\n]"
"Content-Type: application/json[\r][\n]"
"Host: localhost:9192[\r][\n]"
"Connection: Keep-Alive[\r][\n]"
"User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_25)[\r][\n]"
"Accept-Encoding: gzip,deflate[\r][\n]"
"[\r][\n]"
</code>```

Response Headers

```<code>"HTTP/1.1 200 [\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-XSS-Protection: 1; mode=block[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"X-Frame-Options: DENY[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"Connection: close[\r][\n]"
"Transfer-Encoding: chunked[\r][\n]"
"Date: Wed, 03 Oct 2018 00:31:53 GMT[\r][\n]"
"Content-Type: application/json;charset=UTF-8[\r][\n]"
"[\r][\n]"
"{"customerNumber":"1000000030"}[\r][\n]"
</code>```

On 100th call - Request headers have Connection: keep-alive, but response haader has Connection: close and body/stream WITHOUT carriage return \r\n

http-outgoing-0 << "end of stream"

I/O error on GET request for "http://localhost:9192/rest/customers/1000000030": Bad chunk header

Request Headers

```<code>"GET /rest/customers/1000000030 HTTP/1.1[\r][\n]"
"Accept-Language: en-us[\r][\n]"
"Accept: application/json[\r][\n]"
"Content-Type: application/json[\r][\n]"
"Host: localhost:9192[\r][\n]"
"Connection: Keep-Alive[\r][\n]"
"User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_25)[\r][\n]"
"Accept-Encoding: gzip,deflate[\r][\n]"
"[\r][\n]"
</code>```

Response Headers

```<code>"HTTP/1.1 200 [\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-XSS-Protection: 1; mode=block[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"X-Frame-Options: DENY[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"Connection: close[\r][\n]"
"Transfer-Encoding: chunked[\r][\n]"
"Date: Wed, 03 Oct 2018 00:31:53 GMT[\r][\n]"
"Content-Type: application/json;charset=UTF-8[\r][\n]"
"[\r][\n]"
"{"customerNumber":"1000000030"}" <- MISSING \r\n
</code>```

a. Why is the server closing the connection after 100 calls?

Seems like this is the cause- Tomcat 8 with NIO connectors defaults:

Maximum connections that can be handled by each server are
maxConnections = 10000

Each connection timeout connectionTimeout
= 60 seconds

Maximum threads defines within each connection how many simultaneous requests can be handled  maxThreads = 200

Minimum spare threads that are always available (not connections)
= minSpareThreads = 10

Maximum number keep alive requests within a connection maxKeepAliveRequests = 100 (this seems to be closing the
connection, and does not send carriage return as part of response
body generating Buffer Read I/O exception)

b. When closing connection why server is not sending the termination or carriage return? Is this Spring or tomact issue?

c. How or what setting need to be changed to avoid this?
maxKeepAliveRequests is not exposed in Spring application properties, only way to override is to implement a customer container implementing WebServerFactoryCustomizer and then manually overriding.

Please advise if this a bug on connection close event on the server?

答: I met this issue when using RestTemplate exchange function, I just filter the Connection header, then the error disappears.</p>

Body:
Setup - 2 Rest services, spring-boot 2.x, embedded tomcat 8.x

Service A calls Service B using restTemplate, in a test loop running for 300 times, on every 100th interval within the loop throws an exception "Bad chunk header exception".

Enabled debugging (<logger name="org.apache.http" level="DEBUG"/>), following is the analysis:

First 99 iterations - Request/Response headers have Connection: keep-alive and body/stream ends with carriage return \r\n

Request Headers

"GET /rest/customers/1000000030 HTTP/1.1[\r][\n]"
"Accept-Language: en-us[\r][\n]"
"Accept: application/json[\r][\n]"
"Content-Type: application/json[\r][\n]"
"Host: localhost:9192[\r][\n]"
"Connection: Keep-Alive[\r][\n]"
"User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_25)[\r][\n]"
"Accept-Encoding: gzip,deflate[\r][\n]"
"[\r][\n]"

Response Headers

"HTTP/1.1 200 [\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-XSS-Protection: 1; mode=block[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"X-Frame-Options: DENY[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"Connection: close[\r][\n]"
"Transfer-Encoding: chunked[\r][\n]"
"Date: Wed, 03 Oct 2018 00:31:53 GMT[\r][\n]"
"Content-Type: application/json;charset=UTF-8[\r][\n]"
"[\r][\n]"
"{"customerNumber":"1000000030"}[\r][\n]"

On 100th call - Request headers have Connection: keep-alive, but response haader has Connection: close and body/stream WITHOUT carriage return \r\n

http-outgoing-0 << "end of stream"

I/O error on GET request for "http://localhost:9192/rest/customers/1000000030": Bad chunk header

Request Headers

"GET /rest/customers/1000000030 HTTP/1.1[\r][\n]"
"Accept-Language: en-us[\r][\n]"
"Accept: application/json[\r][\n]"
"Content-Type: application/json[\r][\n]"
"Host: localhost:9192[\r][\n]"
"Connection: Keep-Alive[\r][\n]"
"User-Agent: Apache-HttpClient/4.5.5 (Java/1.8.0_25)[\r][\n]"
"Accept-Encoding: gzip,deflate[\r][\n]"
"[\r][\n]"

Response Headers

"HTTP/1.1 200 [\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-XSS-Protection: 1; mode=block[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"X-Frame-Options: DENY[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"X-Content-Type-Options: nosniff[\r][\n]"
"Cache-Control: no-cache, no-store, max-age=0, must-revalidate[\r][\n]"
"Pragma: no-cache[\r][\n]"
"Expires: 0[\r][\n]"
"Connection: close[\r][\n]"
"Transfer-Encoding: chunked[\r][\n]"
"Date: Wed, 03 Oct 2018 00:31:53 GMT[\r][\n]"
"Content-Type: application/json;charset=UTF-8[\r][\n]"
"[\r][\n]"
"{"customerNumber":"1000000030"}" <- MISSING \r\n

a. Why is the server closing the connection after 100 calls?

Seems like this is the cause- Tomcat 8 with NIO connectors defaults:

Maximum connections that can be handled by each server are
maxConnections = 10000

Each connection timeout connectionTimeout
= 60 seconds

Maximum threads defines within each connection how many simultaneous requests can be handled  maxThreads = 200

Minimum spare threads that are always available (not connections)
= minSpareThreads = 10

Maximum number keep alive requests within a connection maxKeepAliveRequests = 100 (this seems to be closing the
connection, and does not send carriage return as part of response
body generating Buffer Read I/O exception)

b. When closing connection why server is not sending the termination or carriage return? Is this Spring or tomact issue?

c. How or what setting need to be changed to avoid this?
maxKeepAliveRequests is not exposed in Spring application properties, only way to override is to implement a customer container implementing WebServerFactoryCustomizer and then manually overriding.

Please advise if this a bug on connection close event on the server?


问:
socket hang up error with nodejs
I want to set up proxy for some XYZ server whose i am not the admin.
Then i want to do some analysis over the request and response headers then also over request and response bodies.
So i am using http-proxy https://github.com/nodejitsu/node-http-proxy

this is what i am doing :

```<code>  var proxy = httpProxy.createProxyServer();

  connect.createServer(
    connect.bodyParser(),
    require('connect-restreamer')(),
    function (req, res) {
      proxy.web(req, res, { target : 'XYZserver' });
    }
  ).listen(config.listenPort);
</code>```

Upto GET request everything is fine but whenever a request with some body like POST, PATCH, PUT etc request are made i get the error :

```<code>Error: socket hang up
    at createHangUpError (http.js:1472:15)
    at Socket.socketCloseListener (http.js:1522:23)
    at Socket.EventEmitter.emit (events.js:95:17)
    at TCP.close (net.js:466:12)
</code>```

I google a lot but found no clue whats wrong going on.
I enable socket proxy with 'ws:true' option of 'proxy.web' but still the same error.

答:
I had this problem with post, put and delete, but after read this issue from chimurai
/
http-proxy-middleware, I have done it.

1- Add onProxyReq: https://github.com/chimurai/http-proxy-middleware/issues/40#issuecomment-249430255

2- Notice that you have to add Content-Type: application/json to request's header

3- No change order of body-parser

Title: socket hang up error with nodejs

Body:
I want to set up proxy for some XYZ server whose i am not the admin.
Then i want to do some analysis over the request and response headers then also over request and response bodies.
So i am using http-proxy https://github.com/nodejitsu/node-http-proxy

this is what i am doing :

  var proxy = httpProxy.createProxyServer();

  connect.createServer(
    connect.bodyParser(),
    require('connect-restreamer')(),
    function (req, res) {
      proxy.web(req, res, { target : 'XYZserver' });
    }
  ).listen(config.listenPort);

Upto GET request everything is fine but whenever a request with some body like POST, PATCH, PUT etc request are made i get the error :

Error: socket hang up
    at createHangUpError (http.js:1472:15)
    at Socket.socketCloseListener (http.js:1522:23)
    at Socket.EventEmitter.emit (events.js:95:17)
    at TCP.close (net.js:466:12)

I google a lot but found no clue whats wrong going on.
I enable socket proxy with 'ws:true' option of 'proxy.web' but still the same error.


问:
using pandas to find number of duplicated sentences in a dataframe
I'm trying to find out how much duplicated sentences does my dataframe has which is any exact match sentences repeated more than one, I'm using Dataframe.Duplicated but it ignore the first oucurency of the sentences and I want it instead of printing the duplicated sentences just print the duplicated sentences one and the number of its occurrence

the code I'm trying is

```<code>wdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(wdata.count(' ') == 0)
wdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)
data=wdata[wdata.duplicated()]
print(data)

#dataframe example
#hi how are you
#hello sam how are you doing
#hello sam how are you doing
#helll Alex how are you doing
#hello sam how are you doing
#let us go eat
#where is the dog
#let us go eat

</code>```

I want my output to be something like

```<code>#hello sam how are you doing   3
#let us go eat                 2

</code>```

with duplicated function I get this output

```<code>#hello sam how are you doing
#hello sam how are you doing
#let us go eat

</code>```

this is the output I'm getting with second answer

```<code>wdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(wdata.count(' ') == 0)
wdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)

data=wdata.groupby(['sentences']).size().reset_index(name='counts')

#                      sentences  counts
#0  hello Alex how are you doing       1
#1   hello sam how are you doing       3
#2                hi how are you       1
#3                 let us go eat       1
#4                let us go eat        1
#5              where is the dog       1

</code>```

I want my output to be something like

```<code>#hello sam how are you doing   3
#let us go eat                 2

</code>```

答:
Because there are whitespaces, solution is remove them by Series.str.strip with GroupBy.size:

```<code>data=wdata.groupby(wdata['sentences'].str.strip()).size().reset_index(name='counts')
</code>```

And then filter by boolean indexing:

```<code>data = data[data['counts'].gt(1)]
</code>```

Another idea is use Series.value_counts for Series, filtering and last convert to 2 columns DataFrame:

```<code>s = wdata['sentences'].str.strip().value_counts()
data = s[s.gt(1)].rename_axis('sentences').reset_index(name='counts')
</code>```

Body:
I'm trying to find out how much duplicated sentences does my dataframe has which is any exact match sentences repeated more than one, I'm using Dataframe.Duplicated but it ignore the first oucurency of the sentences and I want it instead of printing the duplicated sentences just print the duplicated sentences one and the number of its occurrence

the code I'm trying is

wdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(wdata.count(' ') == 0)
wdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)
data=wdata[wdata.duplicated()]
print(data)

#dataframe example
#hi how are you
#hello sam how are you doing
#hello sam how are you doing
#helll Alex how are you doing
#hello sam how are you doing
#let us go eat
#where is the dog
#let us go eat

I want my output to be something like

#hello sam how are you doing   3
#let us go eat                 2

with duplicated function I get this output

#hello sam how are you doing
#hello sam how are you doing
#let us go eat

this is the output I'm getting with second answer

wdata = pd.read_csv(fileinput, nrows=0).columns[0]
skip = int(wdata.count(' ') == 0)
wdata = pd.read_csv(fileinput, names=['sentences'], skiprows=skip)

data=wdata.groupby(['sentences']).size().reset_index(name='counts')

#                      sentences  counts
#0  hello Alex how are you doing       1
#1   hello sam how are you doing       3
#2                hi how are you       1
#3                 let us go eat       1
#4                let us go eat        1
#5              where is the dog       1

I want my output to be something like

#hello sam how are you doing   3
#let us go eat                 2

Body:
Because there are whitespaces, solution is remove them by Series.str.strip with GroupBy.size:

data=wdata.groupby(wdata['sentences'].str.strip()).size().reset_index(name='counts')

And then filter by boolean indexing:

data = data[data['counts'].gt(1)]

Another idea is use Series.value_counts for Series, filtering and last convert to 2 columns DataFrame:

s = wdata['sentences'].str.strip().value_counts()
data = s[s.gt(1)].rename_axis('sentences').reset_index(name='counts')


问:
Errors while joining two tables using sqlalchemy
When I tried to join two tables I got the following error:

sqlalchemy.exc.ObjectNotExecutableError: Not an executable object:
 sqlalchemy.sql.selectable.Join at 0x7f31a35b02e8; Join object on

  chanel(139851192912136) and Device(139851192912864)

My code is:

```<code>import sqlalchemy as db
from sqlalchemy import and_,or_,not_,inspect,text,inspection
engine = db.create_engine("mssql+pymssql://sa:elnetsrv@192.108.55.95/ELNetDB")
Data1 = db.Table("chanel", metadata, autoload=True, autoload_with=engine)
Data2 = db.Table("Device",metadata,autoload = True,autoload_with = engine)
metadata = db.MetaData()
j = Data1.join(Data2,Data1.columns.No == Data2.columns.ID)
print(engine.execute(j))
</code>```

答:
Data1.join(Data2,Data1.columns.No == Data2.columns.ID) is not executable because it is not a query object.

You can try this instead (assuming you want to select every column from Data1):

```<code>print( engine.execute(select([Data1]).select_from(j) )
</code>```

see https://docs.sqlalchemy.org/en/13/core/metadata.html#sqlalchemy.schema.Table.join for reference.

Body:
When I tried to join two tables I got the following error:

sqlalchemy.exc.ObjectNotExecutableError: Not an executable object:
 sqlalchemy.sql.selectable.Join at 0x7f31a35b02e8; Join object on

  chanel(139851192912136) and Device(139851192912864)

My code is:

import sqlalchemy as db
from sqlalchemy import and_,or_,not_,inspect,text,inspection
engine = db.create_engine("mssql+pymssql://sa:elnetsrv@192.108.55.95/ELNetDB")
Data1 = db.Table("chanel", metadata, autoload=True, autoload_with=engine)
Data2 = db.Table("Device",metadata,autoload = True,autoload_with = engine)
metadata = db.MetaData()
j = Data1.join(Data2,Data1.columns.No == Data2.columns.ID)
print(engine.execute(j))

Body:
Data1.join(Data2,Data1.columns.No == Data2.columns.ID) is not executable because it is not a query object.

You can try this instead (assuming you want to select every column from Data1):

print( engine.execute(select([Data1]).select_from(j) )

see https://docs.sqlalchemy.org/en/13/core/metadata.html#sqlalchemy.schema.Table.join for reference.