### Install FALCONN Python Package Source: https://github.com/falconn-lib/falconn/wiki/Installation-and-Compiler-Setup Installs the FALCONN Python wrapper using pip. This is the recommended method for Python users. After installation, verify by importing the 'falconn' module in a Python interpreter. ```bash pip install FALCONN ``` -------------------------------- ### C++ Multithreaded Benchmark Setup and Teardown Source: https://github.com/falconn-lib/falconn/blob/master/src/include/falconn/ffht/external/benchmark/README.md Demonstrates how to manage setup and teardown logic in multithreaded benchmarks by checking the thread index. This ensures that global setup runs only once before all threads start and global teardown runs once after all threads have finished. It requires the 'benchmark' library. ```c++ static void BM_MultiThreaded(benchmark::State& state) { if (state.thread_index == 0) { // Setup code here. } while (state.KeepRunning()) { // Run the test as normal. } if (state.thread_index == 0) { // Teardown code here. } } BENCHMARK(BM_MultiThreaded)->Threads(2); ``` -------------------------------- ### Install FALCONN Python Package from Source Source: https://github.com/falconn-lib/falconn/wiki/Installation-and-Compiler-Setup Installs the FALCONN Python package from the cloned repository. This method requires NumPy and SWIG (version 3.0.8 or higher) and is an alternative if direct pip installation fails. ```bash make python_package_install ``` -------------------------------- ### C++ Include Path Setup for FALCONN Source: https://github.com/falconn-lib/falconn/wiki/Installation-and-Compiler-Setup Configures the compiler to find FALCONN header files. This involves adding the 'src/include' directory to the include path using a compiler flag like -I. ```bash gcc -I path/to/falconn/src/include main.cpp -o main ``` -------------------------------- ### C++ Include Path Setup for Eigen (Included) Source: https://github.com/falconn-lib/falconn/wiki/Installation-and-Compiler-Setup Configures the compiler to find FALCONN header files when using the Eigen library bundled within the FALCONN repository. This involves adding the 'external/eigen' directory to the include path. ```bash gcc -I path/to/falconn/external/eigen main.cpp -o main ``` -------------------------------- ### Bash: CMake Configuration Examples Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/compiling.rst Provides examples of setting CMake configuration variables from the command line to specify the Python version or a specific Python executable path when configuring a project that uses Pybind11. ```bash cmake -DPYBIND11_PYTHON_VERSION=3.6 .. # or cmake -DPYTHON_EXECUTABLE=path/to/python .. ``` -------------------------------- ### Clone FALCONN Source Code Source: https://github.com/falconn-lib/falconn/wiki/Installation-and-Compiler-Setup Clones the FALCONN C++ library source code from its GitHub repository. This method is used if the Python package installation fails or for direct C++ development. ```bash git clone https://github.com/FALCONN-LIB/falconn.git ``` -------------------------------- ### Include pybind11 headers and namespace Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/basics.rst Includes the necessary pybind11 header file and sets up a namespace alias for brevity. This is a prerequisite for most pybind11 code examples. ```cpp #include namespace py = pybind11; ``` -------------------------------- ### Install Google Mock Components Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/CMakeLists.txt Installs Google Mock targets, headers, and pkgconfig files. This section is conditional on the INSTALL_GMOCK flag and ensures that the necessary components for using Google Mock are placed in the correct installation directories. ```cmake if(INSTALL_GMOCK) install(TARGETS gmock gmock_main RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}") install(DIRECTORY "${gmock_SOURCE_DIR}/include/gmock" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") # configure and install pkgconfig files configure_file( cmake/gmock.pc.in "${CMAKE_BINARY_DIR}/gmock.pc" @ONLY) configure_file( cmake/gmock_main.pc.in "${CMAKE_BINARY_DIR}/gmock_main.pc" @ONLY) install(FILES "${CMAKE_BINARY_DIR}/gmock.pc" "${CMAKE_BINARY_DIR}/gmock_main.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif() ``` -------------------------------- ### CMake Install and Package Configuration Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/CMakeLists.txt This snippet includes CMake modules for defining installation directories and helper functions for creating package configuration files. These are essential for proper installation and packaging of the pybind11 library. ```cmake include(GNUInstallDirs) include(CMakePackageConfigHelpers) ``` -------------------------------- ### Compiler Flags for CPU Optimization (GCC/Clang) Source: https://github.com/falconn-lib/falconn/wiki/Installation-and-Compiler-Setup Enables CPU-specific instruction sets like AVX for performance optimization. Use '-march=native' for GCC or '-march=corei7-avx' for some Clang versions on OS X. ```bash g++ -march=native -O3 main.cpp -o main ``` ```bash clang++ -march=corei7-avx -O3 main.cpp -o main ``` -------------------------------- ### CMake: Configure C++ Interpreter Tests with Catch Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/tests/test_embed/CMakeLists.txt This snippet configures the CMake build system to find and utilize the Catch testing framework for C++ interpreter tests. It includes conditional logic for handling cases where Catch is not found, providing installation instructions or an option to download it automatically. This setup ensures that tests can be reliably executed. ```cmake if(${PYTHON_MODULE_EXTENSION} MATCHES "pypy") add_custom_target(cpptest) # Dummy target on PyPy. Embedding is not supported. set(_suppress_unused_variable_warning "${DOWNLOAD_CATCH}") return() endif() find_package(Catch 1.9.3) if(CATCH_FOUND) message(STATUS "Building interpreter tests using Catch v${CATCH_VERSION}") else() message(STATUS "Catch not detected. Interpreter tests will be skipped. Install Catch headers" " manually or use `cmake -DDOWNLOAD_CATCH=1` to fetch them automatically.") return() endif() add_executable(test_embed catch.cpp test_interpreter.cpp ) target_include_directories(test_embed PRIVATE ${CATCH_INCLUDE_DIR}) pybind11_enable_warnings(test_embed) if(NOT CMAKE_VERSION VERSION_LESS 3.0) target_link_libraries(test_embed PRIVATE pybind11::embed) else() target_include_directories(test_embed PRIVATE ${PYBIND11_INCLUDE_DIR} ${PYTHON_INCLUDE_DIRS}) target_compile_options(test_embed PRIVATE ${PYBIND11_CPP_STANDARD}) target_link_libraries(test_embed PRIVATE ${PYTHON_LIBRARIES}) endif() find_package(Threads REQUIRED) target_link_libraries(test_embed PUBLIC ${CMAKE_THREAD_LIBS_INIT}) add_custom_target(cpptest COMMAND $ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) pybind11_add_module(external_module THIN_LTO external_module.cpp) set_target_properties(external_module PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) add_dependencies(cpptest external_module) add_dependencies(check cpptest) ``` -------------------------------- ### Python Package Installation Source: https://github.com/falconn-lib/falconn/blob/master/src/include/falconn/ffht/README.md Instructions for installing the FFHT Python package. ```APIDOC ## Install FFHT Python Package ### Description Install the FFHT library using its Python setup script. ### Method Command Line ### Command ```bash python setup.py install ``` ### Usage Example After installation, you can import and use FFHT in your Python scripts. See `example.py` for usage details. ``` -------------------------------- ### Deprecated py::object APIs and Replacements Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/upgrade.rst Illustrates the deprecation of several py::object APIs in pybind11. The table provides old syntax examples and their corresponding new syntax for common operations like calling methods, string conversion, type checking, and attribute checking. ```cpp // Old syntax: obj.call(args...) // New syntax: obj(args...) ``` ```cpp // Old syntax: obj.str() // New syntax: py::str(obj) ``` ```cpp // Old syntax: auto l = py::list(obj); l.check() // New syntax: py::isinstance(obj) ``` ```cpp // Old syntax: py::object(ptr, true) // New syntax: py::reinterpret_borrow(ptr) ``` ```cpp // Old syntax: py::object(ptr, false) // New syntax: py::reinterpret_steal(ptr) ``` ```cpp // Old syntax: if (obj.attr("foo")) // New syntax: if (py::hasattr(obj, "foo")) ``` ```cpp // Old syntax: if (obj["bar"]) // New syntax: if (obj.contains("bar")) ``` -------------------------------- ### Install pybind11 Headers and Configuration Files - CMake Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/CMakeLists.txt This CMake script handles the installation of pybind11 headers, CMake configuration files (Config.cmake, ConfigVersion.cmake), and helper scripts. It carefully sets installation paths and configures package versioning. ```cmake install(DIRECTORY ${PYBIND11_INCLUDE_DIR}/pybind11 DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) # GNUInstallDirs "DATADIR" wrong here; CMake search path wants "share". set(PYBIND11_CMAKECONFIG_INSTALL_DIR "share/cmake/${PROJECT_NAME}" CACHE STRING "install path for pybind11Config.cmake") configure_package_config_file(tools/${PROJECT_NAME}Config.cmake.in "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" INSTALL_DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) # Remove CMAKE_SIZEOF_VOID_P from ConfigVersion.cmake since the library does # not depend on architecture specific settings or libraries. set(_PYBIND11_CMAKE_SIZEOF_VOID_P ${CMAKE_SIZEOF_VOID_P}) unset(CMAKE_SIZEOF_VOID_P) write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${${PROJECT_NAME}_VERSION} COMPATIBILITY AnyNewerVersion) set(CMAKE_SIZEOF_VOID_P ${_PYBIND11_CMAKE_SIZEOF_VOID_P}) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake tools/FindPythonLibsNew.cmake tools/pybind11Tools.cmake DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) ``` -------------------------------- ### CMake: Install Google Test Targets and Files Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/CMakeLists.txt This CMake code defines the installation rules for Google Test. It specifies where the executables, libraries, and header files should be installed on the system. It also configures and installs pkgconfig files for easier integration with other build systems. ```cmake if(INSTALL_GTEST) install(TARGETS gtest gtest_main RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") install(DIRECTORY "${gtest_SOURCE_DIR}/include/gtest" DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") # configure and install pkgconfig files configure_file( cmake/gtest.pc.in "${CMAKE_BINARY_DIR}/gtest.pc" @ONLY) configure_file( cmake/gtest_main.pc.in "${CMAKE_BINARY_DIR}/gtest_main.pc" @ONLY) install(FILES "${CMAKE_BINARY_DIR}/gtest.pc" "${CMAKE_BINARY_DIR}/gtest_main.pc" DESTINATION "${CMAKE_INSTALL_LIBDIR}/pkgconfig") endif() ``` -------------------------------- ### Pybind11 Module Initialization Warning Example Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/upgrade.rst Displays a sample warning message emitted by pybind11 during module initialization when using deprecated features like old-style placement-new constructors. This warning helps developers identify and migrate to newer, safer API patterns. The warning is typically visible only in debug builds. ```none pybind11-bound class 'mymodule.Foo' is using an old-style placement-new '__init__' which has been deprecated. See the upgrade guide in pybind11's docs. ``` -------------------------------- ### Compile and Test Google Test with CMake Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/CONTRIBUTING.md Compile and run Google Test's own tests using CMake. This process ensures that your changes do not break existing functionality. It requires Python to be installed. ```bash mkdir mybuild cd mybuild cmake -Dgtest_build_tests=ON ${GTEST_DIR} ``` ```bash cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR} ``` ```bash make test ``` -------------------------------- ### Compile C++ code to Python module on Linux Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/basics.rst Compiles the C++ example code into a Python extension module using g++. This command includes necessary flags for optimization, warnings, shared library creation, C++11 standard, position-independent code, and pybind11 include paths. ```bash c++ -O3 -Wall -shared -std=c++11 -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix` ``` -------------------------------- ### Using Split Binding Code in Python Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/faq.rst Demonstrates how to import and use a Python module that has its binding code split across multiple C++ files. The example shows calling functions (`add` and `sub`) exposed through the `example` module, illustrating the result of the C++ binding code. ```pycon >>> import example >>> example.add(1, 2) 3 >>> example.sub(1, 1) 0 ``` -------------------------------- ### Define Custom Build and Test Target (CMake) Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/tests/test_cmake_build/CMakeLists.txt This CMake function `pybind11_add_build_test` creates a custom target for building and testing a specified subdirectory. It accepts build options, can handle installation scenarios, and adds dependencies to ensure proper build order. It requires CMake version 3.1 or higher. ```cmake include(CMakeParseArguments) function(pybind11_add_build_test name) cmake_parse_arguments(ARG "INSTALL" "" "" ${ARGN}) set(build_options "-DCMAKE_PREFIX_PATH=${PROJECT_BINARY_DIR}/mock_install" "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}" "-DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE}" "-DPYBIND11_CPP_STANDARD=${PYBIND11_CPP_STANDARD}") if(NOT ARG_INSTALL) list(APPEND build_options "-DPYBIND11_PROJECT_DIR=${PROJECT_SOURCE_DIR}") endif() add_custom_target(test_${name} ${CMAKE_CTEST_COMMAND} --quiet --output-log ${name}.log --build-and-test "${CMAKE_CURRENT_SOURCE_DIR}/${name}" "${CMAKE_CURRENT_BINARY_DIR}/${name}" --build-config Release --build-noclean --build-generator ${CMAKE_GENERATOR} $<$:--build-generator-platform> ${CMAKE_GENERATOR_PLATFORM} --build-makeprogram ${CMAKE_MAKE_PROGRAM} --build-target check --build-options ${build_options} ) if(ARG_INSTALL) add_dependencies(test_${name} mock_install) endif() add_dependencies(test_cmake_build test_${name}) endfunction() ``` -------------------------------- ### Replace PYBIND11_PLUGIN with PYBIND11_MODULE in C++ Pybind11 Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/upgrade.rst Demonstrates the transition from the deprecated PYBIND11_PLUGIN macro to the preferred PYBIND11_MODULE for creating module entry points in C++ using Pybind11. The new macro simplifies module definition and improves code clarity. Warnings are emitted for the old macro. ```cpp // old PYBIND11_PLUGIN(example) { py::module m("example", "documentation string"); m.def("add", [](int a, int b) { return a + b; }); return m.ptr(); } // new PYBIND11_MODULE(example, m) { m.doc() = "documentation string"; // optional m.def("add", [](int a, int b) { return a + b; }); } ``` -------------------------------- ### CMake: Include Directories Setup Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/CMakeLists.txt This CMake snippet configures the include directories for Google Mock and Google Test. It adds both project-specific and Google Test source directories to the include path, ensuring headers are found during compilation. It also includes conditional setup for target header directories. ```cmake # Adds Google Mock's and Google Test's header directories to the search path. include_directories("${gmock_SOURCE_DIR}/include" "${gmock_SOURCE_DIR}" "${gtest_SOURCE_DIR}/include" # This directory is needed to build directly from Google # Test sources. "${gtest_SOURCE_DIR}") # If the CMake version supports it, attach header directory information # to the targets for when we are part of a parent build (ie being pulled # in via add_subdirectory() rather than being a standalone build). if (DEFINED CMAKE_VERSION AND NOT "${CMAKE_VERSION}" VERSION_LESS "2.8.11") target_include_directories(gmock SYSTEM INTERFACE "${gmock_SOURCE_DIR}/include") target_include_directories(gmock_main SYSTEM INTERFACE "${gmock_SOURCE_DIR}/include") endif() ``` -------------------------------- ### Example gUnit JSON Test Report Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/docs/AdvancedGuide.md An example of a generated JSON report from gUnit, illustrating the structure defined by the JSON schema and Proto3. This example includes details for multiple test suites and test cases, highlighting failures in one of the tests. ```json { "tests": 3, "failures": 1, "errors": 0, "time": "0.035s", "timestamp": "2011-10-31T18:52:42Z", "name": "AllTests", "testsuites": [ { "name": "MathTest", "tests": 2, "failures": 1, "errors": 0, "time": "0.015s", "testsuite": [ { "name": "Addition", "status": "RUN", "time": "0.007s", "classname": "", "failures": [ { "message": "Value of: add(1, 1)\n Actual: 3\nExpected: 2", "type": "" }, { "message": "Value of: add(1, -1)\n Actual: 1\nExpected: 0", "type": "" } ] }, { "name": "Subtraction", "status": "RUN", "time": "0.005s", "classname": "" } ] }, { "name": "LogicTest", "tests": 1, "failures": 0, "errors": 0, "time": "0.005s", "testsuite": [ { "name": "NonContradiction", "status": "RUN", "time": "0.005s", "classname": "" } ] } ] } ``` -------------------------------- ### CMake: Project Setup and Versioning Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/CMakeLists.txt This CMake code defines the project name, version, and required languages. It also sets the minimum CMake version and handles policy settings for newer CMake versions. The 'project()' command initializes the build environment for Google Test. ```cmake if (CMAKE_VERSION VERSION_LESS 3.0) project(gtest CXX C) else() cmake_policy(SET CMP0048 NEW) project(gtest VERSION 1.9.0 LANGUAGES CXX C) endif() cmake_minimum_required(VERSION 2.6.4) if (POLICY CMP0063) # Visibility cmake_policy(SET CMP0063 NEW) endif (POLICY CMP0063) ``` -------------------------------- ### Example Tests for Factorial Function (C++) Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/docs/Primer.md This example demonstrates how to use the TEST() macro and Google Test assertions to test a factorial function. It includes tests for handling zero input and positive inputs, grouping related tests under the same test case name 'FactorialTest'. ```cpp // Tests factorial of 0. TEST(FactorialTest, HandlesZeroInput) { EXPECT_EQ(1, Factorial(0)); } // Tests factorial of positive numbers. TEST(FactorialTest, HandlesPositiveInput) { EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(2, Factorial(2)); EXPECT_EQ(6, Factorial(3)); EXPECT_EQ(40320, Factorial(8)); } ``` -------------------------------- ### pybind11 Module Binding for Functional Examples Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/advanced/cast/functional.rst This C++ code snippet defines a pybind11 module named 'example' and binds three C++ functions (func_arg, func_ret, func_cpp) to be accessible from Python. It requires including the header. ```cpp #include PYBIND11_MODULE(example, m) { m.def("func_arg", &func_arg); m.def("func_ret", &func_ret); m.def("func_cpp", &func_cpp); } ``` -------------------------------- ### CMake: Pthreads dependency and directory setup Source: https://github.com/falconn-lib/falconn/blob/master/src/include/falconn/ffht/external/benchmark/CMakeLists.txt This CMake code ensures the pthreads library is available and required for the project. It also sets up the include directories for the project's header files and includes subdirectories for source and test code. ```cmake # Ensure we have pthreads find_package(Threads REQUIRED) # Set up directories include_directories(${PROJECT_SOURCE_DIR}/include) # Build the targets add_subdirectory(src) if (BENCHMARK_ENABLE_TESTING) enable_testing() add_subdirectory(test) endif() ``` -------------------------------- ### Example of EXPECT_CALL with Times and Actions (C++) Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/docs/ForDummies.md Provides a concrete example of using the EXPECT_CALL macro in Google Mock. This snippet shows how to specify that a method will be called a certain number of times and defines the return values for specific calls and subsequent repeated calls. ```cpp using ::testing::Return; ... EXPECT_CALL(turtle, GetX()) .Times(5) .WillOnce(Return(100)) .WillOnce(Return(150)) .WillRepeatedly(Return(200)); ``` -------------------------------- ### Autotools: Integrate GoogleTest with configure.ac and Makefile.am Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/docs/Pkgconfig.md This example shows how to configure Autotools (Autoconf and Automake) to use GoogleTest. It involves checking for the 'gtest_main' module in 'configure.ac' and then specifying the CFLAGS and LDADD for the test executable in 'Makefile.am'. ```autoconf AC_PREREQ([2.69]) AC_INIT([my_gtest_pkgconfig], [0.0.1]) AC_CONFIG_SRCDIR([samples/sample3_unittest.cc]) AC_PROG_CXX PKG_CHECK_MODULES([GTEST], [gtest_main]) AM_INIT_AUTOMAKE([foreign subdir-objects]) AC_CONFIG_FILES([Makefile]) AC_OUTPUT ``` ```makefile check_PROGRAMS = testapp TESTS = $(check_PROGRAMS) testapp_SOURCES = samples/sample3_unittest.cc testapp_CXXFLAGS = $(GTEST_CFLAGS) testapp_LDADD = $(GTEST_LIBS) ``` -------------------------------- ### CMake: Find Pybind11 Package Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/compiling.rst Demonstrates how to find an installed Pybind11 package using CMake's find_package command and then use the pybind11_add_module function to create a Python extension. This is suitable for projects that do not include the Pybind11 repository internally. ```cmake cmake_minimum_required(VERSION 2.8.12) project(example) find_package(pybind11 REQUIRED) pybind11_add_module(example example.cpp) ``` -------------------------------- ### Compile and Test Google Mock with Autotools Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/CONTRIBUTING.md Compile and run Google Mock's own tests using Autotools. This process involves configuring the mock library and then building and executing its tests. Note that building Google Mock also builds Google Test. ```bash ${GMOCK_DIR}/configure ``` ```bash make ``` ```bash make check ``` -------------------------------- ### Build Google Mock using GNU Make Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/README.md This command sequence shows how to build Google Mock using GNU Make, assuming the Makefile is configured correctly. It navigates to the make directory and executes the make command, followed by running the compiled test executable. ```bash cd ${GMOCK_DIR}/make make ./gmock_test ``` -------------------------------- ### Checkout Google Test Source Code (SVN) Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/docs/XcodeGuide.md This command downloads the latest source code for the Google Test framework from its SVN repository. It's a prerequisite for building the gtest.framework. Ensure you have Subversion (SVN) installed and configured. ```bash svn checkout http://googletest.googlecode.com/svn/trunk/ googletest-read-only ``` -------------------------------- ### pybind11 dict Keyword Constructor Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/changelog.rst Introduces a convenient keyword constructor for `py::dict` in pybind11, enabling the creation of dictionaries using named arguments. Example: `auto d = dict("number"_a=42, "name"_a="World");`. ```cpp auto d = dict("number"_a=42, "name"_a="World"); /* * Added `py::dict` keyword constructor. * Requires pybind11. */ ``` -------------------------------- ### Virtual Destructor Example for Mock Objects Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/docs/FrequentlyAskedQuestions.md Illustrates the importance of virtual destructors in base classes when using mock objects. Failing to make a destructor virtual can lead to memory leaks and heap check failures, as demonstrated with the `Base` and `Derived` class example. ```cpp class Base { public: // Not virtual, but should be. ~Base() { ... } ... }; class Derived : public Base { public: ... private: std::string value_; }; ... Base* p = new Derived; ... delete p; // Surprise! ~Base() will be called, but ~Derived() will not // - value_ is leaked. ``` -------------------------------- ### Configure Benchmark Library Build with CMake Source: https://github.com/falconn-lib/falconn/blob/master/src/include/falconn/ffht/external/benchmark/src/CMakeLists.txt This CMake script defines how to build the 'benchmark' library. It includes source files, sets target properties like version and output name, links necessary libraries (including threads and platform-specific ones), and defines installation directories for archives, libraries, runtime, and include files. ```cmake include_directories(${PROJECT_SOURCE_DIR}/src) if (DEFINED BENCHMARK_CXX_LINKER_FLAGS) list(APPEND CMAKE_SHARED_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) list(APPEND CMAKE_MODULE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS}) endif() file(GLOB SOURCE_FILES *.cc ${PROJECT_SOURCE_DIR}/include/benchmark/*.h ${CMAKE_CURRENT_SOURCE_DIR}/*.h) add_library(benchmark ${SOURCE_FILES}) set_target_properties(benchmark PROPERTIES OUTPUT_NAME "benchmark" VERSION ${GENERIC_LIB_VERSION} SOVERSION ${GENERIC_LIB_SOVERSION} ) target_include_directories(benchmark PUBLIC $ ) target_link_libraries(benchmark ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT}) find_library(LIBRT rt) if(LIBRT) target_link_libraries(benchmark ${LIBRT}) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Windows") target_link_libraries(benchmark Shlwapi) endif() set(include_install_dir "include") set(lib_install_dir "lib/") set(bin_install_dir "bin/") set(config_install_dir "lib/cmake/${PROJECT_NAME}") set(generated_dir "${CMAKE_CURRENT_BINARY_DIR}/generated") set(version_config "${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake") set(project_config "${generated_dir}/${PROJECT_NAME}Config.cmake") set(targets_export_name "${PROJECT_NAME}Targets") set(namespace "${PROJECT_NAME}::") include(CMakePackageConfigHelpers) write_basic_package_version_file( "${version_config}" VERSION ${GIT_VERSION} COMPATIBILITY SameMajorVersion ) configure_file("${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in" "${project_config}" @ONLY) install( TARGETS benchmark EXPORT ${targets_export_name} ARCHIVE DESTINATION ${lib_install_dir} LIBRARY DESTINATION ${lib_install_dir} RUNTIME DESTINATION ${bin_install_dir} INCLUDES DESTINATION ${include_install_dir}) install( DIRECTORY "${PROJECT_SOURCE_DIR}/include/benchmark" DESTINATION ${include_install_dir} FILES_MATCHING PATTERN "*.*h") install( FILES "${project_config}" "${version_config}" DESTINATION "${config_install_dir}") install( EXPORT "${targets_export_name}" NAMESPACE "${namespace}" DESTINATION "${config_install_dir}") ``` -------------------------------- ### Register pybind11 cleanup callback using atexit module Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/advanced/misc.rst This example demonstrates how to register a cleanup callback for pybind11 modules using Python's 'atexit' module. This approach works on both CPython and PyPy and ensures cleanup code runs when the interpreter exits. ```cpp auto atexit = py::module::import("atexit"); atexit.attr("register")(py::cpp_function([]() { // perform cleanup here -- this function is called with the GIL held })); ``` -------------------------------- ### Compile and run tests on Linux/MacOS Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/basics.rst Compiles and runs test cases for pybind11 on Linux and MacOS. Requires python-dev/python3-dev and cmake. The command builds and executes the tests in parallel. ```bash mkdir build cd build cmake .. make check -j 4 ``` -------------------------------- ### Compile and run tests on Windows Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/basics.rst Compiles and runs pybind11 test cases on Windows using Visual Studio 2015 or newer. This command creates a Visual Studio project and builds the test target from the command line. ```batch mkdir build cd build cmake .. cmake --build . --config Release --target check ``` -------------------------------- ### Using Google Mock Doctor for GCC Errors Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/docs/FrequentlyAskedQuestions.md This example shows how to use the gmock_doctor.py script to diagnose GCC compiler errors related to Google Mock. It involves aliasing the script and piping the build command's output to it for analysis. ```bash alias gmd='/scripts/gmock_doctor.py' 2>&1 | gmd # For example: make my_test 2>&1 | gmd ``` -------------------------------- ### Compile Google Mock and Google Test Source Files with g++ Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/README.md This example demonstrates how to compile the core Google Mock and Google Test source files using g++ on a Unix-like system. It specifies the necessary system and normal include paths, and the -pthread flag for thread support. The output is object files that are then archived into a static library. ```bash g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \ -pthread -c ${GTEST_DIR}/src/gtest-all.cc g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \ -isystem ${GMOCK_DIR}/include -I${GMOCK_DIR} \ -pthread -c ${GMOCK_DIR}/src/gmock-all.cc ar -rv libgmock.a gtest-all.o gmock-all.o ``` -------------------------------- ### Build Google Test with Make Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/README.md This sequence of commands utilizes a provided Makefile to build Google Test and a sample test. It assumes GNU make is available and that the user has navigated to the `make` directory within the Google Test installation. This is a convenient way to build on Linux, macOS, and Cygwin environments. ```bash cd ${GTEST_DIR}/make make ./sample1_unittest ``` -------------------------------- ### Global Test Environment Setup/Teardown in Google Test C++ Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/docs/AdvancedGuide.md Illustrates how to define and register a global test environment in Google Test for setup and teardown operations that apply to the entire test program. This is achieved by subclassing `::testing::Environment` and using `::testing::AddGlobalTestEnvironment()`. ```cpp class Environment { public: virtual ~Environment() {} // Override this to define how to set up the environment. virtual void SetUp() {} // Override this to define how to tear down the environment. virtual void TearDown() {} }; Environment* AddGlobalTestEnvironment(Environment* env); // Example of registering a global environment: ::testing::Environment* const foo_env = ::testing::AddGlobalTestEnvironment(new FooEnvironment); ``` -------------------------------- ### Add Dependencies for Testing (CMake) Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/tests/test_cmake_build/CMakeLists.txt This CMake code snippet defines dependencies for the main testing target `check`. It ensures that the `test_cmake_build` custom target is built before `check` is executed, which in turn aggregates all other `test_*` targets created by the `pybind11_add_build_test` function. ```cmake add_dependencies(check test_cmake_build) ``` -------------------------------- ### Check and configure pytest for CMake tests Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/tests/CMakeLists.txt This CMake code verifies the presence and version of the pytest Python package. If pytest is not found or is older than version 3.0, it throws a fatal error, guiding the user to install or update it. This ensures the testing environment is correctly set up. ```cmake if(NOT PYBIND11_PYTEST_FOUND) execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import pytest; print(pytest.__version__)" RESULT_VARIABLE pytest_not_found OUTPUT_VARIABLE pytest_version ERROR_QUIET) if(pytest_not_found) message(FATAL_ERROR "Running the tests requires pytest. Please install it manually" " (try: ${PYTHON_EXECUTABLE} -m pip install pytest)") elseif(pytest_version VERSION_LESS 3.0) message(FATAL_ERROR "Running the tests requires pytest >= 3.0. Found: ${pytest_version}" "Please update it (try: ${PYTHON_EXECUTABLE} -m pip install -U pytest)") endif() set(PYBIND11_PYTEST_FOUND TRUE CACHE INTERNAL "") endif() ``` -------------------------------- ### Basic Benchmark Definition and Registration in C++ Source: https://github.com/falconn-lib/falconn/blob/master/src/include/falconn/ffht/external/benchmark/README.md This C++ snippet demonstrates the basic structure for defining and registering benchmarks using the Google Benchmark library. It shows how to create benchmark functions that accept a `benchmark::State&` object and how to register these functions using `BENCHMARK` and `BENCHMARK_MAIN`. ```c++ static void BM_StringCreation(benchmark::State& state) { while (state.KeepRunning()) std::string empty_string; } // Register the function as a benchmark BENCHMARK(BM_StringCreation); // Define another benchmark static void BM_StringCopy(benchmark::State& state) { std::string x = "hello"; while (state.KeepRunning()) std::string copy(x); } BENCHMARK(BM_StringCopy); BENCHMARK_MAIN(); ``` -------------------------------- ### Executing Python Code with pybind11 API in Embedded Interpreter Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/advanced/embedding.rst Demonstrates executing Python code using pybind11's C++ API, offering a more integrated approach than `py::exec`. This example constructs Python dictionaries and formats strings using pybind11's literals and methods. ```cpp #include namespace py = pybind11; using namespace py::literals; int main() { py::scoped_interpreter guard{}; auto kwargs = py::dict("name"_a="World", "number"_a=42); auto message = "Hello, {name}! The answer is {number}"_s.format(**kwargs); py::print(message); } ``` -------------------------------- ### C++ Google Mock and Google Test Example Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/docs/ForDummies.md This C++ code snippet demonstrates the basic usage of Google Mock and Google Test for unit testing. It includes setting up expectations on a mock object, exercising code that uses the mock, and running the tests. It requires the Google Mock and Google Test libraries. The `main` function initializes the testing framework. ```cpp #include "path/to/mock-turtle.h" #include "gmock/gmock.h" #include "gtest/gtest.h" using ::testing::AtLeast; TEST(PainterTest, CanDrawSomething) { MockTurtle turtle; EXPECT_CALL(turtle, PenDown()) .Times(AtLeast(1)); Painter painter(&turtle); EXPECT_TRUE(painter.DrawCircle(0, 0, 10)); } int main(int argc, char** argv) { // The following line must be executed to initialize Google Mock // (and Google Test) before running the tests. ::testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } ``` -------------------------------- ### Install Source Directory Headers in CMake Source: https://github.com/falconn-lib/falconn/blob/master/external/eigen/Eigen/CMakeLists.txt This snippet installs all header files (*.h) from the 'src' directory to the specified installation destination. It ensures that only header files are installed from the source directory. ```cmake install(DIRECTORY src DESTINATION ${INCLUDE_INSTALL_DIR}/Eigen COMPONENT Devel FILES_MATCHING PATTERN "*.h") ``` -------------------------------- ### Build Google Mock with MSBuild on Windows Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/README.md This command demonstrates how to build Google Mock and its tests on Windows using MSBuild with the provided Visual Studio solution file. It assumes the user is in the correct msvc directory (e.g., msvc/2005 or msvc/2010). ```batch msbuild gmock.sln ``` -------------------------------- ### C++ pybind11: Example of strict constructor binding Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/upgrade.rst Demonstrates stricter compile-time error checking for py::init in pybind11. It shows how attempting to bind a constructor with an incompatible argument type (e.g., non-const lvalue reference to an rvalue) now results in a compile-time error, improving robustness by catching potential issues earlier. ```cpp struct Example { Example(int &); }; py::class_(m, "Example") .def(py::init()); // OK, exact match // .def(py::init()); // compile-time error, mismatch ``` -------------------------------- ### PYBIND11_MODULE vs PYBIND11_PLUGIN Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/changelog.rst Illustrates the modern approach to creating Python module entry points using PYBIND11_MODULE, contrasting it with the deprecated PYBIND11_PLUGIN macro. ```cpp // new PYBIND11_MODULE(example, m) { m.def("add", [](int a, int b) { return a + b; }); } // old PYBIND11_PLUGIN(example) { py::module m("example"); m.def("add", [](int a, int b) { return a + b; }); return m.ptr(); } ``` -------------------------------- ### Conditional Build and Test Target (CMake) Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/tests/test_cmake_build/CMakeLists.txt This CMake code snippet demonstrates how to conditionally add build and test targets based on certain conditions. It includes checks for the Python module extension not being 'pypy' and for the PYBIND11_INSTALL flag being set, to create specific testing scenarios for embedded Python and installed components. ```cmake if(NOT ${PYTHON_MODULE_EXTENSION} MATCHES "pypy") pybind11_add_build_test(subdirectory_embed) endif() if(PYBIND11_INSTALL) add_custom_target(mock_install ${CMAKE_COMMAND} "-DCMAKE_INSTALL_PREFIX=${PROJECT_BINARY_DIR}/mock_install" -P "${PROJECT_BINARY_DIR}/cmake_install.cmake" ) pybind11_add_build_test(installed_function INSTALL) pybind11_add_build_test(installed_target INSTALL) if(NOT ${PYTHON_MODULE_EXTENSION} MATCHES "pypy") pybind11_add_build_test(installed_embed INSTALL) endif() endif() ``` -------------------------------- ### Meson: Declarative Dependency Management for GoogleTest Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/docs/Pkgconfig.md This Meson build script demonstrates native support for pkgconfig to manage GoogleTest dependencies. It defines a project, finds the 'gtest_main' dependency, creates an executable, and sets up a test for it. ```meson project('my_gtest_pkgconfig', 'cpp', version : '0.0.1') gtest_dep = dependency('gtest_main') testapp = executable( 'testapp', files(['samples/sample3_unittest.cc']), dependencies : gtest_dep, install : false) test('first_and_only_test', testapp) ``` -------------------------------- ### Using NiceMock with EXPECT_CALL in Google Mock Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/docs/CookBook.md Demonstrates the basic usage of NiceMock in Google Mock with a specific EXPECT_CALL. This setup allows for flexibility by suppressing warnings for uninteresting calls, while unexpected calls (mismatched EXPECT_CALLs) still result in errors. The example shows setting an expectation for a specific argument and how it handles calls. ```cpp TEST(...) { NiceMock mock_registry; EXPECT_CALL(mock_registry, GetDomainOwner("google.com")) .WillRepeatedly(Return("Larry Page")); // Use mock_registry in code under test. ... &mock_registry ... } ``` -------------------------------- ### Compile and Link Test Application (g++) Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/README.md This command shows how to compile a user's test source file and link it against the previously built Google Test static library (`libgtest.a`). It requires setting the system include path for Google Test headers and links the necessary libraries to produce an executable named `your_test`. ```bash g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \ -o your_test ``` -------------------------------- ### Compile and Link Test Application with g++ Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googlemock/README.md This snippet shows how to compile a test source file and link it against the Google Mock library using g++. It includes the necessary header search paths for both Google Test and Google Mock, and links the previously created libgmock.a. ```bash g++ -isystem ${GTEST_DIR}/include -isystem ${GMOCK_DIR}/include \ -pthread path/to/your_test.cc libgmock.a -o your_test ``` -------------------------------- ### Install Embedded pybind11 Library with CMake Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/tests/test_cmake_build/subdirectory_embed/CMakeLists.txt This snippet shows how to build and install a C++ library that uses pybind11 for embedding, along with its CMake export configuration. It specifies installation destinations for the library files and the CMake export script. Dependencies include pybind11. ```cmake # Test custom export group -- PYBIND11_EXPORT_NAME add_library(test_embed_lib ../embed.cpp) target_link_libraries(test_embed_lib PRIVATE pybind11::embed) install(TARGETS test_embed_lib EXPORT test_export ARCHIVE DESTINATION bin LIBRARY DESTINATION lib RUNTIME DESTINATION lib) install(EXPORT test_export DESTINATION lib/cmake/test_export/test_export-Targets.cmake) ``` -------------------------------- ### Splitting Python Bindings Across Multiple C++ Files Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/faq.rst This example shows how to organize pybind11 binding code across multiple C++ files to improve build times. It uses separate initialization functions (`init_ex1`, `init_ex2`) which are then called within the main `PYBIND11_MODULE` macro. This allows for independent compilation and parallel builds. ```cpp // :file:`example.cpp`: void init_ex1(py::module &); void init_ex2(py::module &); /* ... */ PYBIND11_MODULE(example, m) { init_ex1(m); init_ex2(m); /* ... */ } // :file:`ex1.cpp`: void init_ex1(py::module &m) { m.def("add", [](int a, int b) { return a + b; }); } // :file:`ex2.cpp`: void init_ex1(py::module &m) { m.def("sub", [](int a, int b) { return a - b; }); } ``` -------------------------------- ### Install Interface Library Targets - CMake Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/CMakeLists.txt This CMake code block manages the installation of the 'pybind11', 'module', and 'embed' interface library targets. It exports these targets for use by other CMake projects, potentially with a custom namespace. ```cmake if(NOT (CMAKE_VERSION VERSION_LESS 3.0)) if(NOT PYBIND11_EXPORT_NAME) set(PYBIND11_EXPORT_NAME "${PROJECT_NAME}Targets") endif() install(TARGETS pybind11 module embed EXPORT "${PYBIND11_EXPORT_NAME}") if(PYBIND11_MASTER_PROJECT) install(EXPORT "${PYBIND11_EXPORT_NAME}" NAMESPACE "${PROJECT_NAME}::" DESTINATION ${PYBIND11_CMAKECONFIG_INSTALL_DIR}) endif() endif() ``` -------------------------------- ### Initialize CMake Build with Samples Enabled Source: https://github.com/falconn-lib/falconn/blob/master/external/googletest/googletest/README.md This CMake command initializes a build directory and specifically enables the building of Google Test's sample projects. This is done by passing the `-D` flag to `cmake` to set the `gtest_build_samples` option to `ON`. The `${GTEST_DIR}` variable should point to the root of the Google Test source code. ```bash cmake -Dgtest_build_samples=ON ${GTEST_DIR} ``` -------------------------------- ### Python Example of Overriding Animal::go Source: https://github.com/falconn-lib/falconn/blob/master/external/pybind11/docs/advanced/classes.rst Demonstrates how to define a Python class 'Cat' that inherits from the bound 'Animal' class and overrides the 'go' method. The example shows calling the overridden method through the 'call_go' function. ```python >>> from example import * >>> d = Dog() >>> call_go(d) u'woof! woof! woof! ' >>> class Cat(Animal): ... def go(self, n_times): ... return "meow! " * n_times ... >>> c = Cat() >>> call_go(c) u'meow! meow! meow! ' ```